Amogh1221 commited on
Commit
b4bfeb7
·
verified ·
1 Parent(s): 598dc16

Delete api

Browse files
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 (11.8 kB)
 
api/__pycache__/routes.cpython-313.pyc DELETED
Binary file (9.12 kB)
 
api/dependencies.py DELETED
@@ -1,180 +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.fallback_llm_provider import FallbackLLMProvider
13
- from providers.speech_to_text_provider import SenseVoiceSTTProvider
14
- from providers.chroma_provider import ChromaVectorStore
15
- from providers.pinecone_provider import PineconeVectorStore
16
- from persistence.sqlite_memory_store import SQLiteProfileStore, SQLiteSessionStore
17
- from persistence.user_store import SQLiteUserStore
18
-
19
- # Safety/Risk Signals
20
- from providers.safety.llm import LLMRiskSignal
21
- from providers.safety.clinical import ClinicalRiskSignal
22
-
23
- # Uncomment if using Cascade
24
- # from core.ports import SafetySignal
25
- from providers.safety.bert import BertRiskSignal
26
- from providers.safety.keyword import KeywordRiskSignal
27
- from providers.safety.cascade import CascadeRiskSignal
28
- from fastapi.security import OAuth2PasswordBearer
29
- from fastapi import Depends, HTTPException, status
30
- from services.auth_service import decode_access_token
31
- from services.risk_assessment_service import RiskAssessmentService
32
- from services.conversation_orchestrator import ConversationOrchestrator
33
- from services.patient_service import PatientService
34
- from core.ports import ProfileStore, SessionStore, STTProvider, LLMProvider, VectorStore
35
-
36
- load_dotenv()
37
-
38
- OLLAMA_HOST = os.getenv("OLLAMA_HOST", "http://localhost:11434")
39
- OLLAMA_LLM1_MODEL = os.getenv("OLLAMA_LLM1_MODEL", "phi4-mini")
40
- OLLAMA_LLM2_MODEL = os.getenv("OLLAMA_LLM2_MODEL", "qwen2.5:7b-instruct")
41
- GROQ_LLM1_MODEL = os.getenv("GROQ_LLM1_MODEL", "llama-3.1-8b-instant")
42
- GROQ_LLM2_MODEL = os.getenv("GROQ_LLM2_MODEL", "llama-3.3-70b-versatile")
43
- EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "nomic-embed-text")
44
- CHROMA_PERSIST_DIR = os.getenv("CHROMA_PERSIST_DIR", "./chroma_db")
45
- CHROMA_COLLECTION = os.getenv("CHROMA_COLLECTION_NAME", "mhcva-knowledge")
46
- VECTOR_STORE_TYPE = os.getenv("VECTOR_STORE_TYPE", "chroma").lower()
47
- PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
48
- PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME", "serinity-knowledge")
49
- MEMORY_DB_PATH = os.getenv("MEMORY_DB_PATH", "./data/serinity.db")
50
- WORKING_MEMORY_TURNS = int(os.getenv("WORKING_MEMORY_TURNS", "20"))
51
- CLOUD_MODE = os.getenv("CLOUD_MODE", "false").lower() == "true"
52
-
53
- _hf_home_raw = os.getenv("HF_HOME", "./models")
54
- if not os.path.isabs(_hf_home_raw):
55
- _hf_home_raw = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), _hf_home_raw)
56
- os.environ["HF_HOME"] = _hf_home_raw
57
- os.makedirs(_hf_home_raw, exist_ok=True)
58
-
59
- # Instantiate singleton infrastructure
60
- groq_provider = GroqLLMProvider(model1=GROQ_LLM1_MODEL, model2=GROQ_LLM2_MODEL)
61
- ollama_provider = OllamaLLMProvider(host=OLLAMA_HOST, model1=OLLAMA_LLM1_MODEL, model2=OLLAMA_LLM2_MODEL)
62
-
63
- if CLOUD_MODE:
64
- llm_provider = FallbackLLMProvider(providers=[groq_provider])
65
- vector_store = PineconeVectorStore(
66
- host=OLLAMA_HOST,
67
- embedding_model=EMBEDDING_MODEL,
68
- index_name=PINECONE_INDEX_NAME,
69
- api_key=PINECONE_API_KEY
70
- )
71
- else:
72
- llm_provider = FallbackLLMProvider(providers=[ollama_provider])
73
- vector_store = ChromaVectorStore(
74
- host=OLLAMA_HOST,
75
- embedding_model=EMBEDDING_MODEL,
76
- persist_dir=CHROMA_PERSIST_DIR,
77
- collection_name=CHROMA_COLLECTION
78
- )
79
- profile_store = SQLiteProfileStore(db_path=MEMORY_DB_PATH)
80
- session_store = SQLiteSessionStore(db_path=MEMORY_DB_PATH, working_memory_turns=WORKING_MEMORY_TURNS)
81
- user_store = SQLiteUserStore(db_path=MEMORY_DB_PATH)
82
-
83
- stt_provider = SenseVoiceSTTProvider()
84
-
85
- # Setup DI dependencies for FastAPI routes
86
- def get_llm_provider() -> FallbackLLMProvider:
87
- return llm_provider
88
-
89
- def get_vector_store():
90
- return vector_store
91
-
92
- def get_profile_store() -> SQLiteProfileStore:
93
- return profile_store
94
-
95
- def get_session_store() -> SQLiteSessionStore:
96
- return session_store
97
-
98
- def get_user_store() -> SQLiteUserStore:
99
- return user_store
100
-
101
- oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
102
-
103
- def get_current_user(token: str = Depends(oauth2_scheme), store: SQLiteUserStore = Depends(get_user_store)):
104
- credentials_exception = HTTPException(
105
- status_code=status.HTTP_401_UNAUTHORIZED,
106
- detail="Could not validate credentials",
107
- headers={"WWW-Authenticate": "Bearer"},
108
- )
109
- payload = decode_access_token(token)
110
- if payload is None:
111
- raise credentials_exception
112
-
113
- user_id: str = payload.get("sub")
114
- if user_id is None:
115
- raise credentials_exception
116
-
117
- user = store.get_user_by_id(user_id)
118
- if user is None:
119
- raise credentials_exception
120
- return user
121
-
122
- # Instantiate Risk Service
123
- risk_service = RiskAssessmentService([
124
- CascadeRiskSignal(
125
- filter_signal=KeywordRiskSignal(),
126
- verify_signal=BertRiskSignal()
127
- ),
128
- LLMRiskSignal(),
129
- ClinicalRiskSignal()
130
- ])
131
-
132
- # Instantiate Domain Services
133
- conversation_orchestrator = ConversationOrchestrator(
134
- llm_provider=llm_provider,
135
- vector_store=vector_store,
136
- session_store=session_store,
137
- profile_store=profile_store,
138
- risk_service=risk_service
139
- )
140
-
141
- patient_service = PatientService(
142
- profile_store=profile_store,
143
- session_store=session_store,
144
- llm_provider=llm_provider
145
- )
146
-
147
- # FastAPI dependency injection functions
148
- def get_orchestrator(
149
- llm_provider: LLMProvider = Depends(get_llm_provider),
150
- vector_store: VectorStore = Depends(get_vector_store),
151
- session_store: SessionStore = Depends(get_session_store),
152
- profile_store: ProfileStore = Depends(get_profile_store)
153
- ) -> ConversationOrchestrator:
154
- return ConversationOrchestrator(
155
- llm_provider=llm_provider,
156
- vector_store=vector_store,
157
- session_store=session_store,
158
- profile_store=profile_store,
159
- risk_service=risk_service
160
- )
161
-
162
- def get_patient_service(
163
- profile_store: ProfileStore = Depends(get_profile_store),
164
- session_store: SessionStore = Depends(get_session_store),
165
- llm_provider: LLMProvider = Depends(get_llm_provider)
166
- ) -> PatientService:
167
- return PatientService(
168
- profile_store=profile_store,
169
- session_store=session_store,
170
- llm_provider=llm_provider
171
- )
172
-
173
- def get_stt_provider() -> STTProvider:
174
- return stt_provider
175
-
176
- def get_profile_store() -> ProfileStore:
177
- return profile_store
178
-
179
- def get_session_store() -> SessionStore:
180
- return session_store
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routers/__pycache__/auth.cpython-311.pyc DELETED
Binary file (12.9 kB)
 
api/routers/auth.py DELETED
@@ -1,230 +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, SignupOtpRequest, LoginRequest, TokenResponse, ForgotPasswordRequest, ResetPasswordRequest, DeleteAccountVerifyRequest, VerifyOtpRequest
8
- from services.auth_service import get_password_hash, verify_password, create_access_token
9
- from services.email_service import send_otp_email
10
- import secrets
11
- from datetime import datetime, timedelta, timezone
12
- from api.dependencies import profile_store, get_user_store, get_current_user
13
- from persistence.user_store import SQLiteUserStore
14
-
15
- router = APIRouter(prefix="/api/auth", tags=["auth"])
16
-
17
- @router.post("/signup/request-otp")
18
- def request_signup_otp(request: SignupOtpRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
19
- """
20
- Check if email and username are available, then generate and send an OTP for signup verification.
21
- """
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
- # Generate 6 digit secure OTP
28
- otp_code = str(secrets.randbelow(1000000)).zfill(6)
29
- expires_at = datetime.now(timezone.utc) + timedelta(minutes=10)
30
-
31
- user_store.store_otp(request.email, otp_code, expires_at)
32
-
33
- send_otp_email(
34
- to_email=request.email,
35
- subject="Your Signup Verification Code",
36
- otp_code=otp_code,
37
- body_text=f"Your Serinity signup verification code is: {otp_code}\nThis code will expire in 10 minutes."
38
- )
39
-
40
- return {"message": "OTP has been sent to your email."}
41
-
42
- @router.post("/signup", response_model=TokenResponse)
43
- def signup(request: SignupRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
44
- """
45
- Register a new user and create an initial patient profile.
46
- Returns a JWT access token upon successful registration.
47
- """
48
- # Verify OTP first
49
- otp_record = user_store.get_otp(request.email)
50
- if not otp_record or otp_record["otp_code"] != request.otp_code:
51
- raise HTTPException(status_code=400, detail="Invalid or expired OTP")
52
-
53
- expires_at = datetime.fromisoformat(otp_record["expires_at"])
54
- if datetime.now(timezone.utc) > expires_at:
55
- user_store.delete_otp(request.email)
56
- raise HTTPException(status_code=400, detail="OTP has expired")
57
-
58
- # Check if user exists (double check just in case)
59
- if user_store.get_user_by_email(request.email):
60
- raise HTTPException(status_code=400, detail="Email already registered")
61
- if user_store.get_user_by_username(request.username):
62
- raise HTTPException(status_code=400, detail="Username already taken")
63
-
64
- # Hash password
65
- hashed_password = get_password_hash(request.password)
66
-
67
- # Create user
68
- user_id = user_store.create_user(
69
- username=request.username,
70
- email=request.email,
71
- password_hash=hashed_password,
72
- nationality=request.nationality,
73
- emergency_contact_name=request.emergency_contact_name,
74
- emergency_contact_phone=request.emergency_contact_phone
75
- )
76
-
77
- # Create patient profile linked to user_id
78
- patient_id = profile_store.create_patient(
79
- name=request.name,
80
- age=request.age,
81
- gender=request.gender,
82
- primary_concern=request.primary_concern,
83
- user_id=user_id
84
- )
85
-
86
- # Generate token
87
- access_token = create_access_token(data={"sub": user_id, "username": request.username})
88
-
89
- # Delete OTP to prevent reuse
90
- user_store.delete_otp(request.email)
91
-
92
- return TokenResponse(access_token=access_token, user_id=user_id)
93
-
94
-
95
- @router.post("/login", response_model=TokenResponse)
96
- def login(request: LoginRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
97
- """
98
- Authenticate a user using username or email and password.
99
- Returns a JWT access token.
100
- """
101
- if "@" in request.username:
102
- user = user_store.get_user_by_email(request.username)
103
- else:
104
- user = user_store.get_user_by_username(request.username)
105
-
106
- if not user:
107
- raise HTTPException(
108
- status_code=status.HTTP_401_UNAUTHORIZED,
109
- detail="Incorrect username or password",
110
- )
111
-
112
- if not verify_password(request.password, user["password_hash"]):
113
- raise HTTPException(
114
- status_code=status.HTTP_401_UNAUTHORIZED,
115
- detail="Incorrect username or password",
116
- )
117
-
118
- access_token = create_access_token(data={"sub": user["id"], "username": user["username"]})
119
- return TokenResponse(access_token=access_token, user_id=user["id"])
120
-
121
- @router.post("/forgot-password")
122
- def forgot_password(request: ForgotPasswordRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
123
- """
124
- Initiates the password reset process by generating a 6-digit OTP code and sending it via email.
125
- """
126
- user = user_store.get_user_by_email(request.email)
127
- if not user:
128
- raise HTTPException(status_code=404, detail="No account found with that email address.")
129
-
130
- # Generate 6 digit secure OTP
131
- otp_code = str(secrets.randbelow(1000000)).zfill(6)
132
- expires_at = datetime.now(timezone.utc) + timedelta(minutes=10)
133
-
134
- user_store.store_otp(request.email, otp_code, expires_at)
135
-
136
- send_otp_email(
137
- to_email=request.email,
138
- subject="Your Password Reset OTP",
139
- otp_code=otp_code,
140
- body_text=f"Your verification code to reset your password is: {otp_code}"
141
- )
142
-
143
- return {"message": "If that email exists, an OTP has been sent."}
144
-
145
- @router.post("/reset-password")
146
- def reset_password(request: ResetPasswordRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
147
- otp_record = user_store.get_otp(request.email)
148
-
149
- if not otp_record or otp_record["otp_code"] != request.otp_code:
150
- raise HTTPException(status_code=400, detail="Invalid or expired OTP")
151
-
152
- expires_at = datetime.fromisoformat(otp_record["expires_at"])
153
- if datetime.now(timezone.utc) > expires_at:
154
- user_store.delete_otp(request.email)
155
- raise HTTPException(status_code=400, detail="OTP has expired")
156
-
157
- # Hash new password
158
- hashed_password = get_password_hash(request.new_password)
159
- user_store.update_password(request.email, hashed_password)
160
-
161
- # Delete OTP to prevent reuse
162
- user_store.delete_otp(request.email)
163
-
164
- @router.post("/verify-otp")
165
- def verify_otp_only(request: VerifyOtpRequest, user_store: SQLiteUserStore = Depends(get_user_store)):
166
- """Verify OTP only (no password change) — gates the new-password step on the frontend."""
167
- otp_record = user_store.get_otp(request.email)
168
- if not otp_record or otp_record["otp_code"] != request.otp_code:
169
- raise HTTPException(status_code=400, detail="Invalid or expired OTP")
170
- expires_at = datetime.fromisoformat(otp_record["expires_at"])
171
- if datetime.now(timezone.utc) > expires_at:
172
- user_store.delete_otp(request.email)
173
- raise HTTPException(status_code=400, detail="OTP has expired")
174
- return {"message": "OTP verified. You may now set a new password."}
175
-
176
-
177
- @router.post("/delete-account/request-otp")
178
- def request_delete_account_otp(
179
- user_store: SQLiteUserStore = Depends(get_user_store),
180
- current_user: dict = Depends(get_current_user)
181
- ):
182
- user = user_store.get_user_by_id(current_user["id"])
183
- if not user:
184
- raise HTTPException(status_code=404, detail="User not found")
185
-
186
- otp_code = str(secrets.randbelow(1000000)).zfill(6)
187
- expires_at = datetime.now(timezone.utc) + timedelta(minutes=10)
188
-
189
- user_store.store_otp(user["email"], otp_code, expires_at)
190
-
191
- send_otp_email(
192
- to_email=user["email"],
193
- subject="Account Deletion OTP",
194
- otp_code=otp_code,
195
- body_text=f"Your verification code to delete your account is: {otp_code}\nIf you did not request this, please ignore this email."
196
- )
197
-
198
- return {"message": "OTP has been sent to your email."}
199
-
200
- @router.post("/delete-account/verify")
201
- def verify_delete_account(
202
- request: DeleteAccountVerifyRequest,
203
- user_store: SQLiteUserStore = Depends(get_user_store),
204
- current_user: dict = Depends(get_current_user)
205
- ):
206
- user = user_store.get_user_by_id(current_user["id"])
207
- if not user:
208
- raise HTTPException(status_code=404, detail="User not found")
209
-
210
- otp_record = user_store.get_otp(user["email"])
211
- if not otp_record or otp_record["otp_code"] != request.otp_code:
212
- raise HTTPException(status_code=400, detail="Invalid or expired OTP")
213
-
214
- expires_at = datetime.fromisoformat(otp_record["expires_at"])
215
- if datetime.now(timezone.utc) > expires_at:
216
- user_store.delete_otp(user["email"])
217
- raise HTTPException(status_code=400, detail="OTP has expired")
218
-
219
- # Delete patient associated with user first
220
- patients = profile_store.list_patients_for_user(user["id"])
221
- for p in patients:
222
- profile_store.delete_patient(p["patient_id"])
223
-
224
- # Delete user
225
- user_store.delete_user(user["id"])
226
-
227
- # Clear OTP
228
- user_store.delete_otp(user["email"])
229
-
230
- return {"message": "Account has been successfully deleted."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routes.py DELETED
@@ -1,226 +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
- session_id, opening_message, patient_id = patient_service.create_new_session(request.patient_id)
132
- return {
133
- "assistant_message": opening_message,
134
- "session_id": session_id,
135
- "patient_id": patient_id,
136
- }
137
-
138
-
139
- @router.post("/chat_text")
140
- def chat_text(
141
- request: ChatRequest,
142
- orchestrator: ConversationOrchestrator = Depends(get_orchestrator),
143
- patient_service: PatientService = Depends(get_patient_service),
144
- session_store: SessionStore = Depends(get_session_store),
145
- profile_store: ProfileStore = Depends(get_profile_store),
146
- user: dict = Depends(get_current_user)
147
- ):
148
- """
149
- Process a user's chat message through the core orchestrator.
150
- LLM2 analysis is run synchronously within the orchestrator if triggered.
151
- """
152
- if not session_store.session_exists(request.session_id):
153
- # Session expired, create a new one
154
- session_id, opening_message, patient_id = patient_service.create_new_session(request.patient_id)
155
- # Instead of dropping the user's message and returning the greeting, pipe the user's message into the new session
156
- request.session_id = session_id
157
- request.patient_id = patient_id
158
-
159
- try:
160
- chat_result = orchestrator.handle_message(
161
- session_id=request.session_id,
162
- message=request.message,
163
- emotion=request.emotion,
164
- default_patient_id=request.patient_id
165
- )
166
- except Exception as e:
167
- error_str = str(e).lower()
168
- error_type = type(e).__name__.lower()
169
- if "rate limit" in error_str or "ratelimit" in error_str or "429" in error_str or "ratelimit" in error_type:
170
- raise HTTPException(status_code=429, detail="Tokens Exhausted")
171
- raise e
172
-
173
-
174
- return {
175
- "assistant_message": chat_result.assistant_message,
176
- "intent": chat_result.intent,
177
- "risk_flagged": chat_result.risk_flagged,
178
- "session_id": request.session_id,
179
- }
180
-
181
- @router.post("/transcribe")
182
- async def transcribe(
183
- audio: UploadFile = File(...),
184
- stt_provider: STTProvider = Depends(get_stt_provider)
185
- ):
186
- """
187
- Accepts raw audio bytes from the frontend and passes them to the STTProvider
188
- for speech-to-text and emotional tone extraction.
189
- """
190
- audio_bytes = await audio.read()
191
- # Run the CPU-bound transcription in a threadpool to prevent blocking the async event loop
192
- result = await run_in_threadpool(stt_provider.transcribe, audio_bytes)
193
- return {
194
- "text": result.get("text", ""),
195
- "emotion": result.get("emotion", "unknown"),
196
- "event": result.get("event", None),
197
- }
198
-
199
- @router.get("/patients/{patient_id}/active_session")
200
- def get_active_session(
201
- patient_id: str,
202
- patient_service: PatientService = Depends(get_patient_service),
203
- user: dict = Depends(get_current_user)
204
- ):
205
- """Check if the patient currently has an active session."""
206
- session_id = patient_service.get_active_session(patient_id)
207
- return {"session_id": session_id}
208
-
209
- @router.get("/sessions/{session_id}/messages")
210
- def get_session_messages(
211
- session_id: str,
212
- patient_service: PatientService = Depends(get_patient_service),
213
- user: dict = Depends(get_current_user)
214
- ):
215
- """Retrieve all raw messages for a given session to continue a chat."""
216
- messages = patient_service.get_session_messages(session_id)
217
- return {"messages": messages}
218
-
219
- @router.get("/{full_path:path}", response_class=HTMLResponse)
220
- def catch_all(request: Request, full_path: str):
221
- """
222
- Catch-all route to support History API (clean URLs) in the frontend SPA.
223
- If the user navigates directly to /profiles or /dashboard, serve index.html
224
- so the frontend JS can handle the routing.
225
- """
226
- return templates.TemplateResponse(request, "index.html")