Spaces:
Sleeping
Sleeping
Commit
Β·
4339866
1
Parent(s):
a867323
Add authorization to the project
Browse files- .env +3 -0
- auth/__pycache__/auth_bearer.cpython-312.pyc +0 -0
- auth/__pycache__/auth_handler.cpython-312.pyc +0 -0
- auth/auth_bearer.py +30 -0
- auth/auth_handler.py +26 -0
- config.py +11 -0
- main.py +27 -12
- schemas/__pycache__/auth.cpython-312.pyc +0 -0
- schemas/__pycache__/user.cpython-312.pyc +0 -0
- schemas/auth.py +9 -0
.env
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
SECRET_KEY=your-secret-key-here
|
2 |
+
ALGORITHM=HS256
|
3 |
+
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
auth/__pycache__/auth_bearer.cpython-312.pyc
ADDED
Binary file (1.9 kB). View file
|
|
auth/__pycache__/auth_handler.cpython-312.pyc
ADDED
Binary file (2.32 kB). View file
|
|
auth/auth_bearer.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import Request, HTTPException
|
2 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
3 |
+
|
4 |
+
from auth.auth_handler import decode_token
|
5 |
+
|
6 |
+
class JWTBearer(HTTPBearer):
|
7 |
+
def __init__(self, auto_error: bool = True):
|
8 |
+
super(JWTBearer, self).__init__(auto_error=auto_error)
|
9 |
+
|
10 |
+
async def __call__(self, request: Request):
|
11 |
+
credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
|
12 |
+
if credentials:
|
13 |
+
if not credentials.scheme == "Bearer":
|
14 |
+
raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
|
15 |
+
if not self.verify_jwt(credentials.credentials):
|
16 |
+
raise HTTPException(status_code=403, detail="Invalid token or expired token.")
|
17 |
+
return credentials.credentials
|
18 |
+
else:
|
19 |
+
raise HTTPException(status_code=403, detail="Invalid authorization code.")
|
20 |
+
|
21 |
+
def verify_jwt(self, jwtoken: str) -> bool:
|
22 |
+
isTokenValid: bool = False
|
23 |
+
|
24 |
+
try:
|
25 |
+
payload = decode_token(jwtoken)
|
26 |
+
except:
|
27 |
+
payload = None
|
28 |
+
if payload:
|
29 |
+
isTokenValid = True
|
30 |
+
return isTokenValid
|
auth/auth_handler.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime, timedelta
|
2 |
+
from typing import Optional
|
3 |
+
|
4 |
+
from jose import JWTError, jwt
|
5 |
+
from passlib.context import CryptContext
|
6 |
+
|
7 |
+
from schemas.auth import TokenData
|
8 |
+
from config import settings
|
9 |
+
|
10 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
11 |
+
|
12 |
+
SECRET_KEY = settings.SECRET_KEY
|
13 |
+
ALGORITHM = settings.ALGORITHM
|
14 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
15 |
+
|
16 |
+
def decode_token(token: str):
|
17 |
+
try:
|
18 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
19 |
+
username: str = payload.get("sub")
|
20 |
+
user_id: str = payload.get("user_id")
|
21 |
+
if username is None and user_id is None:
|
22 |
+
return None
|
23 |
+
token_data = TokenData(username=username, user_id=user_id)
|
24 |
+
except JWTError:
|
25 |
+
return None
|
26 |
+
return token_data
|
config.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pydantic_settings import BaseSettings
|
2 |
+
|
3 |
+
class Settings(BaseSettings):
|
4 |
+
SECRET_KEY: str
|
5 |
+
ALGORITHM: str
|
6 |
+
ACCESS_TOKEN_EXPIRE_MINUTES: int
|
7 |
+
|
8 |
+
class Config:
|
9 |
+
env_file = ".env"
|
10 |
+
|
11 |
+
settings = Settings()
|
main.py
CHANGED
@@ -717,8 +717,8 @@ class HealthcareChatbot:
|
|
717 |
print(f"π Making API call to {endpoint_method} {self.BASE_URL + endpoint_url} with params: {endpoint_params}")
|
718 |
|
719 |
# Inject patient_id if needed
|
720 |
-
if 'patient_id' in endpoint_params:
|
721 |
-
|
722 |
|
723 |
retries = 0
|
724 |
response = None
|
@@ -810,10 +810,10 @@ class HealthcareChatbot:
|
|
810 |
# router_data['params'][param] = parsed_date
|
811 |
|
812 |
# Inject patient_id if needed
|
813 |
-
if 'patient_id' in router_data['params']:
|
814 |
-
|
815 |
-
else:
|
816 |
-
|
817 |
|
818 |
|
819 |
print(f"π Final API call data: {router_data}")
|
@@ -1073,11 +1073,12 @@ class HealthcareChatbot:
|
|
1073 |
# if __name__ == "__main__":
|
1074 |
# main()
|
1075 |
|
1076 |
-
from fastapi import FastAPI, HTTPException, UploadFile, File
|
1077 |
from pydantic import BaseModel
|
1078 |
from typing import Dict, Any, Optional
|
1079 |
from fastapi.middleware.cors import CORSMiddleware
|
1080 |
-
|
|
|
1081 |
|
1082 |
|
1083 |
app = FastAPI(
|
@@ -1099,23 +1100,37 @@ class QueryRequest(BaseModel):
|
|
1099 |
query: str
|
1100 |
|
1101 |
|
1102 |
-
@app.post("/query")
|
1103 |
-
async def process_query(request: QueryRequest):
|
1104 |
"""
|
1105 |
Process a user query and return a response
|
1106 |
"""
|
1107 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1108 |
response = agent.chat(request.query).message
|
1109 |
return response
|
1110 |
except Exception as e:
|
1111 |
raise HTTPException(status_code=500, detail=str(e))
|
1112 |
|
1113 |
-
@app.post("/voice-text")
|
1114 |
-
async def process_voice(file: UploadFile = File(...)):
|
1115 |
"""
|
1116 |
Process a user voice and return a response
|
1117 |
"""
|
1118 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1119 |
audio_bytes = await file.read()
|
1120 |
audio_numpy = load_audio(audio_bytes)
|
1121 |
text_response = voice_to_text_model.transcribe(audio_numpy, fp16=False)
|
|
|
717 |
print(f"π Making API call to {endpoint_method} {self.BASE_URL + endpoint_url} with params: {endpoint_params}")
|
718 |
|
719 |
# Inject patient_id if needed
|
720 |
+
# if 'patient_id' in endpoint_params:
|
721 |
+
# endpoint_params['patient_id'] = self.user_id
|
722 |
|
723 |
retries = 0
|
724 |
response = None
|
|
|
810 |
# router_data['params'][param] = parsed_date
|
811 |
|
812 |
# Inject patient_id if needed
|
813 |
+
# if 'patient_id' in router_data['params']:
|
814 |
+
# router_data['params']['patient_id'] = self.user_id
|
815 |
+
# else:
|
816 |
+
# router_data['params']['patient_id'] = self.user_id
|
817 |
|
818 |
|
819 |
print(f"π Final API call data: {router_data}")
|
|
|
1073 |
# if __name__ == "__main__":
|
1074 |
# main()
|
1075 |
|
1076 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File, Depends
|
1077 |
from pydantic import BaseModel
|
1078 |
from typing import Dict, Any, Optional
|
1079 |
from fastapi.middleware.cors import CORSMiddleware
|
1080 |
+
from auth.auth_handler import decode_token
|
1081 |
+
from auth.auth_bearer import JWTBearer
|
1082 |
|
1083 |
|
1084 |
app = FastAPI(
|
|
|
1100 |
query: str
|
1101 |
|
1102 |
|
1103 |
+
@app.post("/query", dependencies=[Depends(JWTBearer())])
|
1104 |
+
async def process_query(request: QueryRequest, token: str = Depends(JWTBearer())):
|
1105 |
"""
|
1106 |
Process a user query and return a response
|
1107 |
"""
|
1108 |
try:
|
1109 |
+
token_data = decode_token(token)
|
1110 |
+
print(f"π Token data: {token_data}")
|
1111 |
+
agent.user_id = token_data.user_id
|
1112 |
+
agent.headers = {
|
1113 |
+
"Authorization": f"Bearer {token}",
|
1114 |
+
"Content-Type": "application/json",
|
1115 |
+
}
|
1116 |
response = agent.chat(request.query).message
|
1117 |
return response
|
1118 |
except Exception as e:
|
1119 |
raise HTTPException(status_code=500, detail=str(e))
|
1120 |
|
1121 |
+
@app.post("/voice-text", dependencies=[Depends(JWTBearer())])
|
1122 |
+
async def process_voice(file: UploadFile = File(...), token: str = Depends(JWTBearer())):
|
1123 |
"""
|
1124 |
Process a user voice and return a response
|
1125 |
"""
|
1126 |
try:
|
1127 |
+
token_data = decode_token(token)
|
1128 |
+
print(f"π Token data: {token_data}")
|
1129 |
+
agent.user_id = token_data.user_id
|
1130 |
+
agent.headers = {
|
1131 |
+
"Authorization": f"Bearer {token}",
|
1132 |
+
"Content-Type": "application/json",
|
1133 |
+
}
|
1134 |
audio_bytes = await file.read()
|
1135 |
audio_numpy = load_audio(audio_bytes)
|
1136 |
text_response = voice_to_text_model.transcribe(audio_numpy, fp16=False)
|
schemas/__pycache__/auth.cpython-312.pyc
ADDED
Binary file (690 Bytes). View file
|
|
schemas/__pycache__/user.cpython-312.pyc
ADDED
Binary file (1.1 kB). View file
|
|
schemas/auth.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pydantic import BaseModel
|
2 |
+
|
3 |
+
class Token(BaseModel):
|
4 |
+
access_token: str
|
5 |
+
token_type: str
|
6 |
+
|
7 |
+
class TokenData(BaseModel):
|
8 |
+
username: str | None = None
|
9 |
+
user_id: str | None = None
|