Delete api
Browse files- api/__pycache__/dependencies.cpython-311.pyc +0 -0
- api/__pycache__/dependencies.cpython-313.pyc +0 -0
- api/__pycache__/routes.cpython-311.pyc +0 -0
- api/__pycache__/routes.cpython-313.pyc +0 -0
- api/dependencies.py +0 -191
- api/routers/__pycache__/auth.cpython-311.pyc +0 -0
- api/routers/auth.py +0 -111
- api/routes.py +0 -240
api/__pycache__/dependencies.cpython-311.pyc
DELETED
|
Binary file (8.68 kB)
|
|
|
api/__pycache__/dependencies.cpython-313.pyc
DELETED
|
Binary file (5.18 kB)
|
|
|
api/__pycache__/routes.cpython-311.pyc
DELETED
|
Binary file (12.5 kB)
|
|
|
api/__pycache__/routes.cpython-313.pyc
DELETED
|
Binary file (9.12 kB)
|
|
|
api/dependencies.py
DELETED
|
@@ -1,191 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Dependency injection module for FastAPI.
|
| 3 |
-
Instantiates all infrastructure components (LLMs, Databases, STT) as singletons
|
| 4 |
-
and wires them into the core domain services (Orchestrator, PatientService).
|
| 5 |
-
Provides getter functions to inject these into FastAPI route handlers.
|
| 6 |
-
"""
|
| 7 |
-
import os
|
| 8 |
-
from dotenv import load_dotenv
|
| 9 |
-
|
| 10 |
-
from providers.llms.groq_llm_provider import GroqLLMProvider
|
| 11 |
-
from providers.llms.ollama_llm_provider import OllamaLLMProvider
|
| 12 |
-
from providers.llms.huggingface_llm_provider import HuggingFaceLLMProvider
|
| 13 |
-
from providers.llms.fallback_llm_provider import FallbackLLMProvider
|
| 14 |
-
from providers.speech_to_text_provider import SenseVoiceSTTProvider
|
| 15 |
-
from providers.chroma_provider import ChromaVectorStore
|
| 16 |
-
from providers.pinecone_provider import PineconeVectorStore
|
| 17 |
-
from persistence.sqlite_memory_store import SQLiteProfileStore, SQLiteSessionStore
|
| 18 |
-
from persistence.user_store import SQLiteUserStore
|
| 19 |
-
|
| 20 |
-
# Safety/Risk Signals
|
| 21 |
-
from providers.safety.llm import LLMRiskSignal
|
| 22 |
-
from providers.safety.clinical import ClinicalRiskSignal
|
| 23 |
-
|
| 24 |
-
# Uncomment if using Cascade
|
| 25 |
-
# from core.ports import SafetySignal
|
| 26 |
-
from providers.safety.bert import BertRiskSignal
|
| 27 |
-
from providers.safety.keyword import KeywordRiskSignal
|
| 28 |
-
from providers.safety.cascade import CascadeRiskSignal
|
| 29 |
-
from fastapi.security import OAuth2PasswordBearer
|
| 30 |
-
from fastapi import Depends, HTTPException, status
|
| 31 |
-
from services.auth_service import decode_access_token
|
| 32 |
-
from services.risk_assessment_service import RiskAssessmentService
|
| 33 |
-
from services.conversation_orchestrator import ConversationOrchestrator
|
| 34 |
-
from services.patient_service import PatientService
|
| 35 |
-
from core.ports import ProfileStore, SessionStore, STTProvider, LLMProvider, VectorStore
|
| 36 |
-
|
| 37 |
-
load_dotenv()
|
| 38 |
-
|
| 39 |
-
OLLAMA_HOST = os.getenv("OLLAMA_HOST", "http://localhost:11434")
|
| 40 |
-
OLLAMA_LLM1_MODEL = os.getenv("OLLAMA_LLM1_MODEL", "phi4-mini")
|
| 41 |
-
OLLAMA_LLM2_MODEL = os.getenv("OLLAMA_LLM2_MODEL", "qwen2.5:7b-instruct")
|
| 42 |
-
GROQ_LLM1_MODEL = os.getenv("GROQ_LLM1_MODEL", "llama-3.1-8b-instant")
|
| 43 |
-
GROQ_LLM2_MODEL = os.getenv("GROQ_LLM2_MODEL", "llama-3.3-70b-versatile")
|
| 44 |
-
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "nomic-embed-text")
|
| 45 |
-
CHROMA_PERSIST_DIR = os.getenv("CHROMA_PERSIST_DIR", "./chroma_db")
|
| 46 |
-
CHROMA_COLLECTION = os.getenv("CHROMA_COLLECTION_NAME", "mhcva-knowledge")
|
| 47 |
-
VECTOR_STORE_TYPE = os.getenv("VECTOR_STORE_TYPE", "chroma").lower()
|
| 48 |
-
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
|
| 49 |
-
PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME", "serinity-knowledge")
|
| 50 |
-
MEMORY_DB_PATH = os.getenv("MEMORY_DB_PATH", "./data/serinity.db")
|
| 51 |
-
WORKING_MEMORY_TURNS = int(os.getenv("WORKING_MEMORY_TURNS", "20"))
|
| 52 |
-
CLOUD_MODE = os.getenv("CLOUD_MODE", "false").lower() == "true"
|
| 53 |
-
# LLM_PROVIDER selects the cloud backend when CLOUD_MODE=true.
|
| 54 |
-
# Options: "groq" (default) | "hf" (HuggingFace Serverless Inference API)
|
| 55 |
-
LLM_PROVIDER = os.getenv("LLM_PROVIDER", "groq").lower()
|
| 56 |
-
HF_LLM1_MODEL = os.getenv("HF_LLM1_MODEL", "meta-llama/Llama-3.1-8B-Instruct")
|
| 57 |
-
HF_LLM2_MODEL = os.getenv("HF_LLM2_MODEL", "meta-llama/Llama-3.3-70B-Instruct")
|
| 58 |
-
|
| 59 |
-
_hf_home_raw = os.getenv("HF_HOME", "./models")
|
| 60 |
-
if not os.path.isabs(_hf_home_raw):
|
| 61 |
-
_hf_home_raw = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), _hf_home_raw)
|
| 62 |
-
os.environ["HF_HOME"] = _hf_home_raw
|
| 63 |
-
os.makedirs(_hf_home_raw, exist_ok=True)
|
| 64 |
-
|
| 65 |
-
# Instantiate singleton infrastructure
|
| 66 |
-
ollama_provider = OllamaLLMProvider(host=OLLAMA_HOST, model1=OLLAMA_LLM1_MODEL, model2=OLLAMA_LLM2_MODEL)
|
| 67 |
-
|
| 68 |
-
if CLOUD_MODE:
|
| 69 |
-
if LLM_PROVIDER == "hf":
|
| 70 |
-
_cloud_provider = HuggingFaceLLMProvider(model1=HF_LLM1_MODEL, model2=HF_LLM2_MODEL)
|
| 71 |
-
print(f"[STARTUP] LLM backend: HuggingFace ({HF_LLM1_MODEL} / {HF_LLM2_MODEL})")
|
| 72 |
-
else:
|
| 73 |
-
_cloud_provider = GroqLLMProvider(model1=GROQ_LLM1_MODEL, model2=GROQ_LLM2_MODEL)
|
| 74 |
-
print(f"[STARTUP] LLM backend: Groq ({GROQ_LLM1_MODEL} / {GROQ_LLM2_MODEL})")
|
| 75 |
-
llm_provider = FallbackLLMProvider(providers=[_cloud_provider])
|
| 76 |
-
vector_store = PineconeVectorStore(
|
| 77 |
-
host=OLLAMA_HOST,
|
| 78 |
-
embedding_model=EMBEDDING_MODEL,
|
| 79 |
-
index_name=PINECONE_INDEX_NAME,
|
| 80 |
-
api_key=PINECONE_API_KEY
|
| 81 |
-
)
|
| 82 |
-
else:
|
| 83 |
-
llm_provider = FallbackLLMProvider(providers=[ollama_provider])
|
| 84 |
-
vector_store = ChromaVectorStore(
|
| 85 |
-
host=OLLAMA_HOST,
|
| 86 |
-
embedding_model=EMBEDDING_MODEL,
|
| 87 |
-
persist_dir=CHROMA_PERSIST_DIR,
|
| 88 |
-
collection_name=CHROMA_COLLECTION
|
| 89 |
-
)
|
| 90 |
-
profile_store = SQLiteProfileStore(db_path=MEMORY_DB_PATH)
|
| 91 |
-
session_store = SQLiteSessionStore(db_path=MEMORY_DB_PATH, working_memory_turns=WORKING_MEMORY_TURNS)
|
| 92 |
-
user_store = SQLiteUserStore(db_path=MEMORY_DB_PATH)
|
| 93 |
-
|
| 94 |
-
stt_provider = SenseVoiceSTTProvider()
|
| 95 |
-
|
| 96 |
-
# Setup DI dependencies for FastAPI routes
|
| 97 |
-
def get_llm_provider() -> FallbackLLMProvider:
|
| 98 |
-
return llm_provider
|
| 99 |
-
|
| 100 |
-
def get_vector_store():
|
| 101 |
-
return vector_store
|
| 102 |
-
|
| 103 |
-
def get_profile_store() -> SQLiteProfileStore:
|
| 104 |
-
return profile_store
|
| 105 |
-
|
| 106 |
-
def get_session_store() -> SQLiteSessionStore:
|
| 107 |
-
return session_store
|
| 108 |
-
|
| 109 |
-
def get_user_store() -> SQLiteUserStore:
|
| 110 |
-
return user_store
|
| 111 |
-
|
| 112 |
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
|
| 113 |
-
|
| 114 |
-
def get_current_user(token: str = Depends(oauth2_scheme), store: SQLiteUserStore = Depends(get_user_store)):
|
| 115 |
-
credentials_exception = HTTPException(
|
| 116 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 117 |
-
detail="Could not validate credentials",
|
| 118 |
-
headers={"WWW-Authenticate": "Bearer"},
|
| 119 |
-
)
|
| 120 |
-
payload = decode_access_token(token)
|
| 121 |
-
if payload is None:
|
| 122 |
-
raise credentials_exception
|
| 123 |
-
|
| 124 |
-
user_id: str = payload.get("sub")
|
| 125 |
-
if user_id is None:
|
| 126 |
-
raise credentials_exception
|
| 127 |
-
|
| 128 |
-
user = store.get_user_by_id(user_id)
|
| 129 |
-
if user is None:
|
| 130 |
-
raise credentials_exception
|
| 131 |
-
return user
|
| 132 |
-
|
| 133 |
-
# Instantiate Risk Service
|
| 134 |
-
risk_service = RiskAssessmentService([
|
| 135 |
-
CascadeRiskSignal(
|
| 136 |
-
filter_signal=KeywordRiskSignal(),
|
| 137 |
-
verify_signal=BertRiskSignal()
|
| 138 |
-
),
|
| 139 |
-
LLMRiskSignal(),
|
| 140 |
-
ClinicalRiskSignal()
|
| 141 |
-
])
|
| 142 |
-
|
| 143 |
-
# Instantiate Domain Services
|
| 144 |
-
conversation_orchestrator = ConversationOrchestrator(
|
| 145 |
-
llm_provider=llm_provider,
|
| 146 |
-
vector_store=vector_store,
|
| 147 |
-
session_store=session_store,
|
| 148 |
-
profile_store=profile_store,
|
| 149 |
-
risk_service=risk_service
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
patient_service = PatientService(
|
| 153 |
-
profile_store=profile_store,
|
| 154 |
-
session_store=session_store,
|
| 155 |
-
llm_provider=llm_provider
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
# FastAPI dependency injection functions
|
| 159 |
-
def get_orchestrator(
|
| 160 |
-
llm_provider: LLMProvider = Depends(get_llm_provider),
|
| 161 |
-
vector_store: VectorStore = Depends(get_vector_store),
|
| 162 |
-
session_store: SessionStore = Depends(get_session_store),
|
| 163 |
-
profile_store: ProfileStore = Depends(get_profile_store)
|
| 164 |
-
) -> ConversationOrchestrator:
|
| 165 |
-
return ConversationOrchestrator(
|
| 166 |
-
llm_provider=llm_provider,
|
| 167 |
-
vector_store=vector_store,
|
| 168 |
-
session_store=session_store,
|
| 169 |
-
profile_store=profile_store,
|
| 170 |
-
risk_service=risk_service
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
def get_patient_service(
|
| 174 |
-
profile_store: ProfileStore = Depends(get_profile_store),
|
| 175 |
-
session_store: SessionStore = Depends(get_session_store),
|
| 176 |
-
llm_provider: LLMProvider = Depends(get_llm_provider)
|
| 177 |
-
) -> PatientService:
|
| 178 |
-
return PatientService(
|
| 179 |
-
profile_store=profile_store,
|
| 180 |
-
session_store=session_store,
|
| 181 |
-
llm_provider=llm_provider
|
| 182 |
-
)
|
| 183 |
-
|
| 184 |
-
def get_stt_provider() -> STTProvider:
|
| 185 |
-
return stt_provider
|
| 186 |
-
|
| 187 |
-
def get_profile_store() -> ProfileStore:
|
| 188 |
-
return profile_store
|
| 189 |
-
|
| 190 |
-
def get_session_store() -> SessionStore:
|
| 191 |
-
return session_store
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/routers/__pycache__/auth.cpython-311.pyc
DELETED
|
Binary file (5.7 kB)
|
|
|
api/routers/auth.py
DELETED
|
@@ -1,111 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Authentication Router
|
| 3 |
-
Handles JWT-based authentication, user registration, and OTP flows (signup, password reset, account deletion).
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from fastapi import APIRouter, HTTPException, status, Depends
|
| 7 |
-
from schemas.auth_schemas import SignupRequest, LoginRequest, TokenResponse, ResetPasswordRequest
|
| 8 |
-
from services.auth_service import get_password_hash, verify_password, create_access_token
|
| 9 |
-
from datetime import datetime, timedelta, timezone
|
| 10 |
-
from api.dependencies import profile_store, get_user_store, get_current_user
|
| 11 |
-
from persistence.user_store import SQLiteUserStore
|
| 12 |
-
|
| 13 |
-
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
| 14 |
-
|
| 15 |
-
@router.post("/signup", response_model=TokenResponse)
|
| 16 |
-
def signup(request: SignupRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
|
| 17 |
-
"""
|
| 18 |
-
Register a new user and create an initial patient profile.
|
| 19 |
-
Returns a JWT access token upon successful registration.
|
| 20 |
-
"""
|
| 21 |
-
# Check if user exists
|
| 22 |
-
if user_store.get_user_by_email(request.email):
|
| 23 |
-
raise HTTPException(status_code=400, detail="Email already registered")
|
| 24 |
-
if user_store.get_user_by_username(request.username):
|
| 25 |
-
raise HTTPException(status_code=400, detail="Username already taken")
|
| 26 |
-
|
| 27 |
-
# Hash password
|
| 28 |
-
hashed_password = get_password_hash(request.password)
|
| 29 |
-
|
| 30 |
-
# Create user
|
| 31 |
-
user_id = user_store.create_user(
|
| 32 |
-
username=request.username,
|
| 33 |
-
email=request.email,
|
| 34 |
-
password_hash=hashed_password,
|
| 35 |
-
nationality=request.nationality,
|
| 36 |
-
emergency_contact_name=request.emergency_contact_name,
|
| 37 |
-
emergency_contact_phone=request.emergency_contact_phone
|
| 38 |
-
)
|
| 39 |
-
|
| 40 |
-
# Create patient profile linked to user_id
|
| 41 |
-
patient_id = profile_store.create_patient(
|
| 42 |
-
name=request.name,
|
| 43 |
-
age=request.age,
|
| 44 |
-
gender=request.gender,
|
| 45 |
-
primary_concern=request.primary_concern,
|
| 46 |
-
user_id=user_id
|
| 47 |
-
)
|
| 48 |
-
|
| 49 |
-
# Generate token
|
| 50 |
-
access_token = create_access_token(data={"sub": user_id, "username": request.username})
|
| 51 |
-
|
| 52 |
-
return TokenResponse(access_token=access_token, user_id=user_id)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
@router.post("/login", response_model=TokenResponse)
|
| 56 |
-
def login(request: LoginRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
|
| 57 |
-
"""
|
| 58 |
-
Authenticate a user using username or email and password.
|
| 59 |
-
Returns a JWT access token.
|
| 60 |
-
"""
|
| 61 |
-
if "@" in request.username:
|
| 62 |
-
user = user_store.get_user_by_email(request.username)
|
| 63 |
-
else:
|
| 64 |
-
user = user_store.get_user_by_username(request.username)
|
| 65 |
-
|
| 66 |
-
if not user:
|
| 67 |
-
raise HTTPException(
|
| 68 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 69 |
-
detail="Incorrect username or password",
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
if not verify_password(request.password, user["password_hash"]):
|
| 73 |
-
raise HTTPException(
|
| 74 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 75 |
-
detail="Incorrect username or password",
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
-
access_token = create_access_token(data={"sub": user["id"], "username": user["username"]})
|
| 79 |
-
return TokenResponse(access_token=access_token, user_id=user["id"])
|
| 80 |
-
|
| 81 |
-
@router.post("/reset-password")
|
| 82 |
-
def reset_password(request: ResetPasswordRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
|
| 83 |
-
user = user_store.get_user_by_email(request.email)
|
| 84 |
-
if not user:
|
| 85 |
-
raise HTTPException(status_code=404, detail="No account found with that email address.")
|
| 86 |
-
|
| 87 |
-
# Hash new password
|
| 88 |
-
hashed_password = get_password_hash(request.new_password)
|
| 89 |
-
user_store.update_password(request.email, hashed_password)
|
| 90 |
-
|
| 91 |
-
return {"message": "Password successfully updated."}
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
@router.post("/delete-account")
|
| 95 |
-
def delete_account(
|
| 96 |
-
user_store: SQLiteUserStore = Depends(get_user_store),
|
| 97 |
-
current_user: dict = Depends(get_current_user)
|
| 98 |
-
):
|
| 99 |
-
user = user_store.get_user_by_id(current_user["id"])
|
| 100 |
-
if not user:
|
| 101 |
-
raise HTTPException(status_code=404, detail="User not found")
|
| 102 |
-
|
| 103 |
-
# Delete patient associated with user first
|
| 104 |
-
patients = profile_store.list_patients_for_user(user["id"])
|
| 105 |
-
for p in patients:
|
| 106 |
-
profile_store.delete_patient(p["patient_id"])
|
| 107 |
-
|
| 108 |
-
# Delete user
|
| 109 |
-
user_store.delete_user(user["id"])
|
| 110 |
-
|
| 111 |
-
return {"message": "Account has been successfully deleted."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/routes.py
DELETED
|
@@ -1,240 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Main API Routes
|
| 3 |
-
Handles patient management, dashboard, and conversation endpoints.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from fastapi import APIRouter, Depends, UploadFile, File, Request, Response, BackgroundTasks, HTTPException
|
| 7 |
-
from fastapi.concurrency import run_in_threadpool
|
| 8 |
-
from fastapi.responses import HTMLResponse
|
| 9 |
-
from fastapi.templating import Jinja2Templates
|
| 10 |
-
from pydantic import BaseModel
|
| 11 |
-
|
| 12 |
-
from core.schemas import (
|
| 13 |
-
ResetRequest, ChatRequest, StartRequest,
|
| 14 |
-
PatientCreateRequest, EndSessionRequest
|
| 15 |
-
)
|
| 16 |
-
from api.dependencies import (
|
| 17 |
-
get_orchestrator, get_patient_service,
|
| 18 |
-
get_stt_provider, get_profile_store, get_session_store,
|
| 19 |
-
get_current_user,
|
| 20 |
-
ConversationOrchestrator, PatientService
|
| 21 |
-
)
|
| 22 |
-
from core.ports import ProfileStore, SessionStore, STTProvider
|
| 23 |
-
|
| 24 |
-
router = APIRouter()
|
| 25 |
-
templates = Jinja2Templates(directory="templates")
|
| 26 |
-
|
| 27 |
-
@router.get("/health")
|
| 28 |
-
def health():
|
| 29 |
-
"""Simple health check endpoint to verify API is running."""
|
| 30 |
-
return {"status": "ok"}
|
| 31 |
-
|
| 32 |
-
@router.get("/", response_class=HTMLResponse)
|
| 33 |
-
def home(request: Request):
|
| 34 |
-
"""Serves the main frontend Single Page Application (SPA)."""
|
| 35 |
-
return templates.TemplateResponse(request, "index.html")
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
@router.get("/patients")
|
| 40 |
-
def get_patients(profile_store: ProfileStore = Depends(get_profile_store), user: dict = Depends(get_current_user)):
|
| 41 |
-
"""Retrieve a list of all registered patients for the logged-in user."""
|
| 42 |
-
patients = profile_store.list_patients_for_user(user["id"])
|
| 43 |
-
if not patients:
|
| 44 |
-
# Auto-create a default profile for older accounts that lack one
|
| 45 |
-
patient_id = profile_store.create_patient(
|
| 46 |
-
name=user.get("username", "User"),
|
| 47 |
-
age=None,
|
| 48 |
-
gender=None,
|
| 49 |
-
primary_concern=None,
|
| 50 |
-
user_id=user["id"]
|
| 51 |
-
)
|
| 52 |
-
return [{"patient_id": patient_id, "name": user.get("username", "User")}]
|
| 53 |
-
return patients
|
| 54 |
-
|
| 55 |
-
@router.post("/patients/create")
|
| 56 |
-
def create_new_patient(
|
| 57 |
-
request: PatientCreateRequest,
|
| 58 |
-
profile_store: ProfileStore = Depends(get_profile_store),
|
| 59 |
-
user: dict = Depends(get_current_user)
|
| 60 |
-
):
|
| 61 |
-
"""Create a new patient record in the database."""
|
| 62 |
-
p_id = profile_store.create_patient(
|
| 63 |
-
name=request.name,
|
| 64 |
-
age=request.age,
|
| 65 |
-
gender=request.gender,
|
| 66 |
-
occupation=request.occupation,
|
| 67 |
-
primary_concern=request.primary_concern,
|
| 68 |
-
user_id=user["id"]
|
| 69 |
-
)
|
| 70 |
-
return {"patient_id": p_id, "name": request.name}
|
| 71 |
-
|
| 72 |
-
@router.get("/patients/{patient_id}/dashboard")
|
| 73 |
-
def patient_dashboard(
|
| 74 |
-
patient_id: str,
|
| 75 |
-
profile_store: ProfileStore = Depends(get_profile_store),
|
| 76 |
-
user: dict = Depends(get_current_user)
|
| 77 |
-
):
|
| 78 |
-
"""Retrieve full dashboard data for a patient (info, profile, past sessions)."""
|
| 79 |
-
patient_info = profile_store.get_patient(patient_id)
|
| 80 |
-
if not patient_info:
|
| 81 |
-
return Response(status_code=404)
|
| 82 |
-
|
| 83 |
-
profile = profile_store.get_patient_profile(patient_id)
|
| 84 |
-
sessions = profile_store.get_patient_sessions(patient_id)
|
| 85 |
-
|
| 86 |
-
return {
|
| 87 |
-
"patient": patient_info,
|
| 88 |
-
"profile": profile,
|
| 89 |
-
"sessions": sessions
|
| 90 |
-
}
|
| 91 |
-
|
| 92 |
-
@router.post("/patients/{patient_id}/reset")
|
| 93 |
-
def reset_patient(
|
| 94 |
-
patient_id: str,
|
| 95 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 96 |
-
user: dict = Depends(get_current_user)
|
| 97 |
-
):
|
| 98 |
-
"""Reset the patient's data, including sessions, messages, and profile."""
|
| 99 |
-
patient_service.reset_patient_data(patient_id)
|
| 100 |
-
return {"status": "success", "message": "Patient data reset successfully."}
|
| 101 |
-
|
| 102 |
-
@router.delete("/patients/{patient_id}")
|
| 103 |
-
def delete_patient(
|
| 104 |
-
patient_id: str,
|
| 105 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 106 |
-
user: dict = Depends(get_current_user)
|
| 107 |
-
):
|
| 108 |
-
"""Delete a patient and all their associated data completely."""
|
| 109 |
-
patient_service.delete_patient(patient_id)
|
| 110 |
-
return {"status": "success", "message": "Patient deleted successfully."}
|
| 111 |
-
|
| 112 |
-
@router.post("/end_session")
|
| 113 |
-
def end_session_endpoint(
|
| 114 |
-
request: EndSessionRequest,
|
| 115 |
-
background_tasks: BackgroundTasks,
|
| 116 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 117 |
-
user: dict = Depends(get_current_user)
|
| 118 |
-
):
|
| 119 |
-
"""Gracefully terminate an active session and generate a clinical summary in the background."""
|
| 120 |
-
patient_service.end_session(request.session_id, request.patient_id)
|
| 121 |
-
background_tasks.add_task(patient_service.generate_session_summary, request.session_id, request.patient_id)
|
| 122 |
-
return {"status": "ended"}
|
| 123 |
-
|
| 124 |
-
@router.post("/start")
|
| 125 |
-
def start_session(
|
| 126 |
-
request: StartRequest = StartRequest(),
|
| 127 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 128 |
-
user: dict = Depends(get_current_user)
|
| 129 |
-
):
|
| 130 |
-
"""Initialize a new conversation session and generate the psychiatrist's opening remark."""
|
| 131 |
-
try:
|
| 132 |
-
session_id, opening_message, patient_id = patient_service.create_new_session(request.patient_id)
|
| 133 |
-
return {
|
| 134 |
-
"assistant_message": opening_message,
|
| 135 |
-
"session_id": session_id,
|
| 136 |
-
"patient_id": patient_id,
|
| 137 |
-
}
|
| 138 |
-
except Exception as e:
|
| 139 |
-
error_str = str(e).lower()
|
| 140 |
-
if "connection error" in error_str or "all providers failed" in error_str or "unavailable" in error_str:
|
| 141 |
-
raise HTTPException(status_code=503, detail="LLMs are currently unavailable. Cannot start session.")
|
| 142 |
-
raise e
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
@router.post("/chat_text")
|
| 146 |
-
def chat_text(
|
| 147 |
-
request: ChatRequest,
|
| 148 |
-
orchestrator: ConversationOrchestrator = Depends(get_orchestrator),
|
| 149 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 150 |
-
session_store: SessionStore = Depends(get_session_store),
|
| 151 |
-
profile_store: ProfileStore = Depends(get_profile_store),
|
| 152 |
-
user: dict = Depends(get_current_user)
|
| 153 |
-
):
|
| 154 |
-
"""
|
| 155 |
-
Process a user's chat message through the core orchestrator.
|
| 156 |
-
LLM2 analysis is run synchronously within the orchestrator if triggered.
|
| 157 |
-
"""
|
| 158 |
-
if not session_store.session_exists(request.session_id):
|
| 159 |
-
# Session expired, create a new one
|
| 160 |
-
session_id, opening_message, patient_id = patient_service.create_new_session(request.patient_id)
|
| 161 |
-
# Instead of dropping the user's message and returning the greeting, pipe the user's message into the new session
|
| 162 |
-
request.session_id = session_id
|
| 163 |
-
request.patient_id = patient_id
|
| 164 |
-
|
| 165 |
-
try:
|
| 166 |
-
chat_result = orchestrator.handle_message(
|
| 167 |
-
session_id=request.session_id,
|
| 168 |
-
message=request.message,
|
| 169 |
-
emotion=request.emotion,
|
| 170 |
-
default_patient_id=request.patient_id
|
| 171 |
-
)
|
| 172 |
-
except Exception as e:
|
| 173 |
-
error_str = str(e).lower()
|
| 174 |
-
error_type = type(e).__name__.lower()
|
| 175 |
-
if any(k in error_str for k in ("rate limit", "ratelimit", "429", "402", "tokens exhausted", "quota")) or "ratelimit" in error_type:
|
| 176 |
-
raise HTTPException(status_code=429, detail="Tokens Exhausted")
|
| 177 |
-
if "connection error" in error_str or "all providers failed" in error_str or "unavailable" in error_str:
|
| 178 |
-
raise HTTPException(status_code=503, detail="LLMs are currently unavailable. Please try again later.")
|
| 179 |
-
raise e
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
return {
|
| 183 |
-
"assistant_message": chat_result.assistant_message,
|
| 184 |
-
"intent": chat_result.intent,
|
| 185 |
-
"risk_flagged": chat_result.risk_flagged,
|
| 186 |
-
"session_id": request.session_id,
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
@router.post("/transcribe")
|
| 190 |
-
async def transcribe(
|
| 191 |
-
audio: UploadFile = File(...),
|
| 192 |
-
stt_provider: STTProvider = Depends(get_stt_provider)
|
| 193 |
-
):
|
| 194 |
-
"""
|
| 195 |
-
Accepts raw audio bytes from the frontend and passes them to the STTProvider
|
| 196 |
-
for speech-to-text and emotional tone extraction.
|
| 197 |
-
"""
|
| 198 |
-
audio_bytes = await audio.read()
|
| 199 |
-
# Run the CPU-bound transcription in a threadpool to prevent blocking the async event loop
|
| 200 |
-
result = await run_in_threadpool(stt_provider.transcribe, audio_bytes)
|
| 201 |
-
return {
|
| 202 |
-
"text": result.get("text", ""),
|
| 203 |
-
"emotion": result.get("emotion", "unknown"),
|
| 204 |
-
"event": result.get("event", None),
|
| 205 |
-
}
|
| 206 |
-
|
| 207 |
-
@router.get("/patients/{patient_id}/active_session")
|
| 208 |
-
def get_active_session(
|
| 209 |
-
patient_id: str,
|
| 210 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 211 |
-
user: dict = Depends(get_current_user)
|
| 212 |
-
):
|
| 213 |
-
"""Check if the patient currently has an active session."""
|
| 214 |
-
session_id = patient_service.get_active_session(patient_id)
|
| 215 |
-
return {"session_id": session_id}
|
| 216 |
-
|
| 217 |
-
@router.get("/sessions/{session_id}/messages")
|
| 218 |
-
def get_session_messages(
|
| 219 |
-
session_id: str,
|
| 220 |
-
patient_service: PatientService = Depends(get_patient_service),
|
| 221 |
-
user: dict = Depends(get_current_user)
|
| 222 |
-
):
|
| 223 |
-
"""Retrieve all raw messages for a given session to continue a chat."""
|
| 224 |
-
messages = patient_service.get_session_messages(session_id)
|
| 225 |
-
return {"messages": messages}
|
| 226 |
-
|
| 227 |
-
_BLOCKED_PATH_FRAGMENTS = {
|
| 228 |
-
".streamlit", ".env", "secrets.toml", "config.toml", ".git", "wp-admin", ".well-known"
|
| 229 |
-
}
|
| 230 |
-
|
| 231 |
-
@router.get("/{full_path:path}", response_class=HTMLResponse)
|
| 232 |
-
def catch_all(request: Request, full_path: str):
|
| 233 |
-
"""
|
| 234 |
-
Catch-all route to support History API (clean URLs) in the frontend SPA.
|
| 235 |
-
Returns 404 for known config/secret paths probed by bots (e.g. .streamlit/secrets.toml).
|
| 236 |
-
Otherwise serves index.html so the frontend JS handles SPA routing.
|
| 237 |
-
"""
|
| 238 |
-
if any(fragment in full_path for fragment in _BLOCKED_PATH_FRAGMENTS):
|
| 239 |
-
return Response(status_code=404)
|
| 240 |
-
return templates.TemplateResponse(request, "index.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|