Skip to content

Solutions #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 73 additions & 36 deletions melli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from fastapi import FastAPI
import spacy

app = FastAPI(
title="Melli Hiring Challenge 👩‍💻",
Expand All @@ -12,11 +13,17 @@


@app.get("/task1/greet/{name}", tags=["Task 1"], summary="👋🇩🇪🇬🇧🇪🇸")
async def task1_greet(name: str) -> str:
async def task1_greet(name: str, lang: str = "en") -> str:
"""Greet somebody in German, English or Spanish!"""
# Write your code below
...
return f"Hello {name}, I am Melli."
if lang == "en":
return f"Hello {name}, I am Melli."
elif lang == "de":
return f"Hallo {name}, Ich bin Melli"
elif lang == "es":
return f"Hola {name}, Yo soy Melli"
else:
return f"Sorry we don't speak {lang}!"


"""
Expand All @@ -29,8 +36,9 @@ async def task1_greet(name: str) -> str:
def camelize(key: str):
"""Takes string in snake_case format returns camelCase formatted version."""
# Write your code below
...
return key
vec_of_words = key.split('_')
camel_cases = "".join(list(map(lambda x: x.capitalize() if vec_of_words.index(x) > 0 else x, vec_of_words)))
return camel_cases


@app.post("/task2/camelize", tags=["Task 2"], summary="🐍➡️🐪")
Expand Down Expand Up @@ -60,49 +68,60 @@ class ActionResponse(BaseModel):
message: str


def handle_call_action(action: str):
def handle_call_action(name: str|None, username: str):
# Write your code below
...
return "🤙 Why don't you call them yourself!"
if not name in friends[username]:
return f"{username}, I can't find this person in your contacts."

return f"🤙 Calling {name} ..."

def handle_reminder_action(action: str):

def handle_reminder_action():
# Write your code below
...
return "🔔 I can't even remember my own stuff!"
return "🔔 Alright, I will remind you!"


def handle_timer_action(action: str):
def handle_timer_action():
# Write your code below
...
return "⏰ I don't know how to read the clock!"
return "⏰ Alright, the timer is set!"


def handle_unknown_action(action: str):
def handle_unknown_action():
# Write your code below
...
return "🤬 #$!@"
return "👀 Sorry , but I can't help with that!"

def handle_unknown_user(username: str|None):
return f"Hi {username}, I don't know you yet. But I would love to meet you!"

@app.post("/task3/action", tags=["Task 3"], summary="🤌")
def task3_action(request: ActionRequest):
"""Accepts an action request, recognizes its intent and forwards it to the corresponding action handler."""
# tip: you have to use the response model above and also might change the signature
# of the action handlers
# Write your code below
...
from random import choice

# There must be a better way!
handler = choice(
[
handle_call_action,
handle_reminder_action,
handle_timer_action,
handle_unknown_action,
]
)
return handler(request.action)
nlp = spacy.load("en_core_web_sm")
doc = nlp(request.action)
name = None
action = None
for ent in doc.ents:
if ent.label == "PERSON":
name = ent.text
elif ent.label == "ACTION":
action = ent.text

if not action:
return ActionResponse(message=f"Sorry couldn't understand your request.")

if not name in friends.keys():
return ActionResponse(message=handle_unknown_user(name))
if action.startswith("call"):
return ActionResponse(message=handle_call_action(name, request.username))

if "remind" in action:
return ActionResponse(message=handle_reminder_action())
if "timer" in action:
return ActionResponse(message=handle_timer_action())



"""
Expand Down Expand Up @@ -166,9 +185,16 @@ async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# this is probably not very secure 🛡️ ...
# tip: check the verify_password above
# Write your code below
...
user = get_user(form_data.username)
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)

payload = {
"sub": form_data.username,
"sub": user.username,
"exp": datetime.utcnow() + timedelta(minutes=30),
}
return {
Expand All @@ -189,10 +215,18 @@ async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = decode_jwt(token)
username = payload.get("sub")

except JWTError:
raise credentials_exception
if username is None:
raise credentials_exception
return get_user(username)
# check if the token 🪙 is valid and return a user as specified by the tokens payload
# otherwise raise the credentials_exception above
# Write your code below
...


@app.get("/task4/users/{username}/secret", summary="🤫", tags=["Task 4"])
Expand All @@ -202,9 +236,12 @@ async def read_user_secret(
"""Read a user's secret."""
# uppps 🤭 maybe we should check if the requested secret actually belongs to the user
# Write your code below
...
if user := get_user(username):
return user.secret
if username != current_user.username:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Don't spy on other user!"
)
return current_user.secret


"""
Expand Down
Loading