Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,18 +1,27 @@
|
|
| 1 |
"""
|
| 2 |
-
ShakTide AI β main.py (
|
| 3 |
ββββββββββββββββββββββββββββ
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
PKL files required (12):
|
| 18 |
tfidf_retriever.pkl sbert_retriever.pkl sym_embedder.pkl
|
|
@@ -22,19 +31,29 @@ PKL files required (12):
|
|
| 22 |
best_fert_model.pkl fert_scaler.pkl
|
| 23 |
"""
|
| 24 |
|
| 25 |
-
import os, re, json, io, pickle, datetime
|
| 26 |
import numpy as np
|
| 27 |
import pandas as pd
|
| 28 |
from fastapi import FastAPI, Request, HTTPException
|
| 29 |
from fastapi.middleware.cors import CORSMiddleware
|
| 30 |
-
from pydantic import BaseModel, Field
|
| 31 |
from typing import List, Optional, Dict, Any
|
| 32 |
from groq import AsyncGroq
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
# 1. APP + CORS
|
| 36 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
-
app = FastAPI(title="ShakTide AI
|
| 38 |
|
| 39 |
app.add_middleware(
|
| 40 |
CORSMiddleware,
|
|
@@ -55,17 +74,22 @@ app.add_middleware(
|
|
| 55 |
|
| 56 |
@app.get("/")
|
| 57 |
def root():
|
| 58 |
-
return {"status": "ShakTide AI
|
| 59 |
|
| 60 |
|
| 61 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
-
# 2. SECRETS
|
| 63 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 64 |
-
GROQ_API_KEY
|
| 65 |
-
SUPABASE_URL
|
| 66 |
-
SUPABASE_KEY
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
groq_client = AsyncGroq(api_key=GROQ_API_KEY)
|
| 71 |
|
|
@@ -77,14 +101,31 @@ except Exception:
|
|
| 77 |
|
| 78 |
|
| 79 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 80 |
-
# 3. MODEL LOADER
|
| 81 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 82 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
path = os.path.join(BASE_DIR, name)
|
| 86 |
if not os.path.exists(path):
|
| 87 |
-
|
| 88 |
return None
|
| 89 |
|
| 90 |
class CompatUnpickler(pickle.Unpickler):
|
|
@@ -102,7 +143,7 @@ def _load(name: str):
|
|
| 102 |
up = CompatUnpickler(io.BytesIO(data))
|
| 103 |
up.encoding = encoding
|
| 104 |
result = up.load()
|
| 105 |
-
|
| 106 |
return result
|
| 107 |
except Exception:
|
| 108 |
continue
|
|
@@ -110,39 +151,49 @@ def _load(name: str):
|
|
| 110 |
try:
|
| 111 |
import joblib
|
| 112 |
result = joblib.load(path)
|
| 113 |
-
|
| 114 |
return result
|
| 115 |
except Exception as e:
|
| 116 |
-
|
| 117 |
return None
|
| 118 |
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
|
| 144 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 145 |
-
# 4. CONSTANTS
|
| 146 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 147 |
MALE_ANATOMY_TERMS = {"scrotum", "testes", "testicular", "penile", "prostate"}
|
| 148 |
|
|
@@ -209,9 +260,23 @@ AUP_PATTERNS = [
|
|
| 209 |
r"\b(stalk|doxx|harass|blackmail)\b",
|
| 210 |
]
|
| 211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 214 |
-
# 5. PHRASE MAP (
|
| 215 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 216 |
PHRASE_MAP = {
|
| 217 |
r"head.*bonkers|bonkers.*head|head.*splitting|head.*killing|severe headache|throbbing headache|migraine|sir.*dard|sar.*dard": "headache",
|
|
@@ -308,6 +373,37 @@ def rule_extract_symptoms(text: str) -> list:
|
|
| 308 |
return list(found)
|
| 309 |
|
| 310 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
def expand_yes_all_answers(answers: dict, questions: list) -> dict:
|
| 312 |
expanded = dict(answers)
|
| 313 |
YES_ALL = {
|
|
@@ -341,184 +437,452 @@ def expand_yes_all_answers(answers: dict, questions: list) -> dict:
|
|
| 341 |
return expanded
|
| 342 |
|
| 343 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
-
# 6. GROQ HELPERS (async)
|
| 346 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 347 |
def _extract_json(text: str) -> str:
|
| 348 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
text = re.sub(r"\n?```$", "", text.strip())
|
| 350 |
-
|
| 351 |
-
|
|
|
|
| 352 |
return text
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
)
|
| 391 |
|
| 392 |
-
SYNTHESIZE_SYSTEM = (
|
| 393 |
-
"You are a clinical routing engine for a women's menstrual health app.\n"
|
| 394 |
-
"Given patient message, extracted symptoms, and follow-up answers:\n\n"
|
| 395 |
-
"1. Produce final_symptoms: ALL symptoms from all_symptoms. Do NOT drop any.\n"
|
| 396 |
-
" Strip disease names only. Normalize variants.\n"
|
| 397 |
-
" Extract symptoms from followup_answers and add them.\n"
|
| 398 |
-
" NEVER return empty list.\n"
|
| 399 |
-
"2. Route tracks:\n"
|
| 400 |
-
" track_disease: true for non-reproductive symptoms (fever, vomiting, chest pain etc.)\n"
|
| 401 |
-
" track_pcos: true for irregular periods, acne, weight gain, hair loss, facial hair.\n"
|
| 402 |
-
" track_conception: true ONLY if patient mentions trying to conceive.\n"
|
| 403 |
-
" track_fertility_peak: true ONLY if patient asks about fertile window/ovulation.\n"
|
| 404 |
-
"3. Extract cycle_data (cycle_length_days, last_period_days_ago, cycle_regularity).\n"
|
| 405 |
-
" Distinguish cycle length (days between periods) from period duration (days of bleeding).\n"
|
| 406 |
-
"Respond ONLY with compact JSON:\n"
|
| 407 |
-
'{"final_symptoms":[],"tracks":{"track_disease":false,"track_pcos":true,'
|
| 408 |
-
'"track_conception":false,"track_fertility_peak":false},'
|
| 409 |
-
'"cycle_data":{"cycle_length_days":null,"last_period_days_ago":null,"cycle_regularity":null},'
|
| 410 |
-
'"clinical_notes":null}'
|
| 411 |
-
)
|
| 412 |
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
'"4 week cycle"β28, "2-4 months gap"β75 + very_irregular\n'
|
| 417 |
-
"Distinguish cycle length (between period starts) from period duration (days of bleeding).\n"
|
| 418 |
-
"Return null for anything not mentioned. trying_to_conceive: true only if mentioned.\n"
|
| 419 |
-
"Respond ONLY with compact JSON:\n"
|
| 420 |
-
'{"cycle_length_days":null,"last_period_days_ago":null,'
|
| 421 |
-
'"cycle_regularity":null,"trying_to_conceive":false}'
|
| 422 |
-
)
|
| 423 |
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
|
| 432 |
-
SUMMARY_SYSTEM = (
|
| 433 |
-
"You are ShakTide's compassionate women's health AI for Indian patients.\n"
|
| 434 |
-
"Write a SHORT warm summary in Hinglish (mix of Hindi and English, as Indians naturally speak).\n\n"
|
| 435 |
-
"ORDERING:\n"
|
| 436 |
-
"1. Disease primary β lead with disease, mention cycle/PCOS after.\n"
|
| 437 |
-
"2. Reproductive primary β lead with PCOS/cycle, mention illness after.\n"
|
| 438 |
-
"3. If both equal β more urgent first.\n\n"
|
| 439 |
-
"LANGUAGE RULES:\n"
|
| 440 |
-
"- Hinglish: e.g. 'Aapke symptoms dekh ke lagta hai...' or 'Yeh gastroenteritis ke signs ho sakte hain.'\n"
|
| 441 |
-
"- Never say percentages. Use 'lagta hai', 'ho sakta hai', 'possible hai', 'signs hain'.\n"
|
| 442 |
-
"- For PCOS: 'strong signs hain', 'kuch signs hain', 'mild indicators hain'.\n"
|
| 443 |
-
"- For fertility: 'fertile window mein ho sakti hain', 'abhi fertile window ke bahar hain'.\n"
|
| 444 |
-
"- Mention top 1-2 conditions naturally.\n"
|
| 445 |
-
"- If menstrual symptoms present, mention them even if disease is primary.\n"
|
| 446 |
-
"- Under 5 sentences. Warm, non-alarmist.\n"
|
| 447 |
-
"- End with: 'Please ek doctor se zaroor milein proper evaluation ke liye.'\n"
|
| 448 |
-
"Respond with PLAIN TEXT only β no JSON, no bullets, no markdown."
|
| 449 |
-
)
|
| 450 |
|
|
|
|
|
|
|
|
|
|
| 451 |
|
| 452 |
-
async def llm_extract_and_question(
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
user_content = json.dumps({
|
| 455 |
-
"patient_message":
|
| 456 |
-
"
|
| 457 |
-
"
|
| 458 |
-
"
|
|
|
|
| 459 |
"cycle_data_already_provided": cycle_already_known,
|
|
|
|
|
|
|
| 460 |
})
|
| 461 |
try:
|
| 462 |
-
raw = await _groq(EXTRACT_SYSTEM, user_content, max_tokens=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
return json.loads(raw)
|
| 464 |
except Exception:
|
| 465 |
-
return {"
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
user_content = json.dumps({
|
| 470 |
-
"original_query":
|
| 471 |
-
"
|
| 472 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
}, indent=2)
|
| 474 |
try:
|
| 475 |
-
raw = await _groq(SYNTHESIZE_SYSTEM, user_content, max_tokens=
|
| 476 |
parsed = json.loads(raw)
|
| 477 |
if "cycle_data" not in parsed:
|
| 478 |
parsed["cycle_data"] = {}
|
| 479 |
return parsed
|
| 480 |
-
except Exception:
|
|
|
|
| 481 |
_cycle = any(k in " ".join(all_symptoms) for k in
|
| 482 |
["menstruat", "period", "irregular", "unpredictable", "infertil", "heavy_menstrual"])
|
| 483 |
-
_fi = any(k in
|
|
|
|
| 484 |
return {
|
| 485 |
-
"final_symptoms": all_symptoms,
|
| 486 |
"tracks": {
|
| 487 |
"track_disease": bool(all_symptoms) and not _fi,
|
| 488 |
"track_pcos": _cycle,
|
| 489 |
"track_conception": _fi,
|
| 490 |
"track_fertility_peak": _fi,
|
| 491 |
},
|
| 492 |
-
"cycle_data":
|
| 493 |
"clinical_notes": None,
|
| 494 |
}
|
| 495 |
|
| 496 |
|
| 497 |
-
async def
|
| 498 |
-
|
| 499 |
-
raw = await _groq(CYCLE_DATA_SYSTEM, text, max_tokens=150)
|
| 500 |
-
return json.loads(raw)
|
| 501 |
-
except Exception:
|
| 502 |
-
return {"cycle_length_days": None, "last_period_days_ago": None,
|
| 503 |
-
"cycle_regularity": None, "trying_to_conceive": False}
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
async def llm_verify_disease(symptoms: list, candidates: list) -> dict:
|
| 507 |
user_content = json.dumps({
|
| 508 |
"confirmed_symptoms": [s.replace("_", " ") for s in symptoms],
|
|
|
|
| 509 |
"candidates": [{"rank": i+1, "disease": n, "score": f"{s:.3f}"}
|
| 510 |
for i, (n, s) in enumerate(candidates[:8])],
|
| 511 |
}, indent=2)
|
| 512 |
try:
|
| 513 |
-
raw = await _groq(VERIFY_SYSTEM, user_content, max_tokens=
|
| 514 |
return json.loads(raw)
|
| 515 |
except Exception:
|
| 516 |
return {"final_condition": candidates[0][0] if candidates else "",
|
| 517 |
-
"reasoning": "", "confidence": "low"}
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
async def llm_summarize(
|
| 521 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
results_text = []
|
| 523 |
if "Disease" in results:
|
| 524 |
top = results["Disease"][0] if results["Disease"] else None
|
|
@@ -538,24 +902,37 @@ async def llm_summarize(symptoms: list, results: dict,
|
|
| 538 |
disease_primary = "Disease" in results and repro_count < len(symptoms) / 2
|
| 539 |
pcos_raw = results.get("PCOS", {}).get("conf_raw", 0.0)
|
| 540 |
pcos_primary = pcos_raw >= 0.65 and repro_count >= len(symptoms) / 2
|
|
|
|
| 541 |
|
| 542 |
user_content = json.dumps({
|
| 543 |
"patient_symptoms": [s.replace("_", " ") for s in symptoms],
|
| 544 |
"original_query": user_query,
|
|
|
|
| 545 |
"diagnostic_results": results_text,
|
| 546 |
"menstrual_symptoms_present": repro_count > 0,
|
| 547 |
"disease_is_primary": disease_primary and not pcos_primary,
|
| 548 |
"pcos_is_primary": pcos_primary,
|
| 549 |
"cycle_data": cycle_data,
|
|
|
|
|
|
|
| 550 |
}, indent=2)
|
| 551 |
try:
|
| 552 |
-
return await _groq(SUMMARY_SYSTEM, user_content, max_tokens=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
except Exception:
|
| 554 |
-
return "
|
| 555 |
|
| 556 |
|
| 557 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 558 |
-
#
|
| 559 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 560 |
def _score_to_label(score: float, tiers: list) -> str:
|
| 561 |
for threshold, label in sorted(tiers, key=lambda x: x[0], reverse=True):
|
|
@@ -579,17 +956,12 @@ def _align_to_model(df: pd.DataFrame, model) -> pd.DataFrame:
|
|
| 579 |
|
| 580 |
|
| 581 |
def run_disease_track(final_symptoms: list, top_k: int = 5) -> list:
|
| 582 |
-
"""
|
| 583 |
-
TF-IDF + SBERT ensemble (if nlp_stack available),
|
| 584 |
-
with ML model as fallback / secondary scorer.
|
| 585 |
-
Returns list of dicts.
|
| 586 |
-
"""
|
| 587 |
results = []
|
| 588 |
|
| 589 |
if NLP_AVAILABLE:
|
| 590 |
sym_text = "patient has " + ", ".join(s.replace("_", " ") for s in final_symptoms)
|
| 591 |
-
tfidf_res =
|
| 592 |
-
sbert_res =
|
| 593 |
tfidf_map = dict(zip(tfidf_res["disease"].str.lower(), tfidf_res["score"]))
|
| 594 |
sbert_map = dict(zip(sbert_res["disease"].str.lower(), sbert_res["score"]))
|
| 595 |
max_tfidf = max(tfidf_map.values(), default=1.0)
|
|
@@ -624,15 +996,14 @@ def run_disease_track(final_symptoms: list, top_k: int = 5) -> list:
|
|
| 624 |
]
|
| 625 |
|
| 626 |
elif disease_model is not None and disease_encoder is not None:
|
| 627 |
-
# Fallback: pure ML model
|
| 628 |
KNOWN = set(disease_encoder.classes_) if hasattr(disease_encoder, "classes_") else set()
|
| 629 |
input_df = pd.DataFrame(0.0, index=[0], columns=list(KNOWN) if KNOWN else final_symptoms)
|
| 630 |
for s in final_symptoms:
|
| 631 |
if s in input_df.columns:
|
| 632 |
input_df.at[0, s] = 1.0
|
| 633 |
arr = symptom_scaler.transform(input_df) if symptom_scaler else input_df.values
|
| 634 |
-
probs
|
| 635 |
-
top_idx
|
| 636 |
DISEASE_TIERS = [
|
| 637 |
(0.70, "High likelihood"), (0.50, "Moderate likelihood"),
|
| 638 |
(0.30, "Possible"), (0.0, "Low likelihood"),
|
|
@@ -652,7 +1023,14 @@ def run_disease_track(final_symptoms: list, top_k: int = 5) -> list:
|
|
| 652 |
return results
|
| 653 |
|
| 654 |
|
| 655 |
-
def run_pcos_track(final_symptoms: list) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 656 |
score = sum(PCOS_INDICATORS.get(s, 0) for s in final_symptoms)
|
| 657 |
raw_text = " ".join(final_symptoms).lower()
|
| 658 |
for kw, w in PCOS_FUZZY.items():
|
|
@@ -662,6 +1040,13 @@ def run_pcos_track(final_symptoms: list) -> dict:
|
|
| 662 |
if core_hits >= 3 and score < 8: score = 8
|
| 663 |
elif core_hits >= 2 and score < 5: score = 5
|
| 664 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
pcos_prob = min(score / 18.0, 0.95)
|
| 666 |
|
| 667 |
PCOS_TIERS = [
|
|
@@ -719,7 +1104,8 @@ def run_conception_track(cycle_data: dict) -> dict:
|
|
| 719 |
(0.35, "Possible this cycle"),
|
| 720 |
(0.0, "Less likely this cycle")]
|
| 721 |
return {"prediction": f"Conception β {_score_to_label(proba, CONC_TIERS)}", "conf_raw": round(proba, 4)}
|
| 722 |
-
except Exception:
|
|
|
|
| 723 |
return {"prediction": "Could not estimate β please consult a doctor", "conf_raw": 0.0}
|
| 724 |
|
| 725 |
|
|
@@ -749,48 +1135,99 @@ def run_fertility_track(cycle_data: dict) -> dict:
|
|
| 749 |
return {"prediction": fert_label, "confidence": note, "conf_raw": 0.8 if in_window else 0.2}
|
| 750 |
|
| 751 |
|
| 752 |
-
async def run_all_tracks(
|
| 753 |
-
|
| 754 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 755 |
|
| 756 |
-
# Disease
|
| 757 |
-
|
| 758 |
all_repro = all(any(t in s for t in REPRO_TERMS) for s in final_symptoms)
|
| 759 |
-
if not all_repro:
|
| 760 |
disease_list = run_disease_track(final_symptoms, top_k)
|
| 761 |
if disease_list:
|
| 762 |
-
candidates
|
| 763 |
-
verification = await llm_verify_disease(final_symptoms, candidates)
|
| 764 |
-
verified
|
|
|
|
| 765 |
if verified:
|
| 766 |
disease_list = sorted(
|
| 767 |
disease_list,
|
| 768 |
key=lambda r: (r["prediction"].lower() == verified, r["conf_raw"]),
|
| 769 |
reverse=True,
|
| 770 |
)
|
| 771 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 772 |
|
| 773 |
-
#
|
| 774 |
-
|
| 775 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 776 |
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
results["Conception"] = run_conception_track(cycle_data)
|
| 780 |
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
|
|
|
|
| 785 |
return results
|
| 786 |
|
| 787 |
|
| 788 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 789 |
-
#
|
| 790 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 791 |
def get_real_ip(request: Request) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 792 |
fwd = request.headers.get("x-forwarded-for")
|
| 793 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 794 |
|
| 795 |
|
| 796 |
def scan_aup(message: str) -> bool:
|
|
@@ -823,82 +1260,156 @@ async def enforce_aup(client_ip: str, message: str):
|
|
| 823 |
raise HTTPException(status_code=403, detail={"status": "violation", "message": "Message blocked."})
|
| 824 |
|
| 825 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 826 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 827 |
-
#
|
| 828 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 829 |
class ChatRequest(BaseModel):
|
|
|
|
|
|
|
| 830 |
message: str
|
|
|
|
|
|
|
| 831 |
# Session state β passed back from frontend after every turn
|
| 832 |
-
accumulated_symptoms: List[str]
|
| 833 |
-
accumulated_negated: List[str]
|
|
|
|
| 834 |
cycle_data: Dict[str, Any] = Field(default_factory=dict)
|
| 835 |
-
pending_questions: List[dict]
|
| 836 |
-
conversation_turn: int
|
| 837 |
-
chat_history: List[dict]
|
| 838 |
-
#
|
| 839 |
-
age: Optional[int] = None
|
| 840 |
-
sex: Optional[str] = None
|
| 841 |
|
| 842 |
-
|
| 843 |
-
|
|
|
|
| 844 |
|
| 845 |
|
| 846 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 847 |
-
#
|
| 848 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 849 |
@app.get("/api/tokens")
|
| 850 |
async def get_tokens(request: Request):
|
| 851 |
client_ip = get_real_ip(request)
|
| 852 |
today_iso = datetime.date.today().isoformat()
|
| 853 |
if not supabase:
|
| 854 |
-
return {"tokens_left":
|
| 855 |
db = supabase.table("ai_teaser_usage").select("*").eq("ip_address", client_ip).execute()
|
| 856 |
if db.data:
|
| 857 |
rec = db.data[0]
|
| 858 |
if rec["last_reset_date"] != today_iso:
|
| 859 |
-
return {"tokens_left":
|
| 860 |
-
|
| 861 |
-
|
|
|
|
| 862 |
|
| 863 |
|
| 864 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 865 |
-
#
|
| 866 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 867 |
@app.post("/api/chat")
|
| 868 |
async def process_chat(query: ChatRequest, request: Request):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
|
| 870 |
# ββ Guards ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 871 |
-
if len(query.message) >
|
| 872 |
return {"status": "success", "message_type": "question",
|
| 873 |
"message": "Thoda chhota rakhein please β sirf main symptoms batayein.",
|
| 874 |
"session": _session(query)}
|
| 875 |
|
| 876 |
-
client_ip = get_real_ip(request)
|
| 877 |
await enforce_aup(client_ip, query.message)
|
| 878 |
|
| 879 |
-
#
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
)
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
|
|
|
| 900 |
|
| 901 |
-
# Crisis intercept
|
| 902 |
if any(kw in query.message.lower() for kw in CRISIS_KEYWORDS):
|
| 903 |
return {
|
| 904 |
"status": "success", "message_type": "crisis",
|
|
@@ -908,45 +1419,95 @@ async def process_chat(query: ChatRequest, request: Request):
|
|
| 908 |
),
|
| 909 |
}
|
| 910 |
|
| 911 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 912 |
if query.conversation_turn == 0 and not query.accumulated_symptoms:
|
| 913 |
-
# Greet if empty
|
| 914 |
stripped = query.message.strip()
|
| 915 |
if len(stripped) < 10 or stripped.lower() in ("hi", "hello", "namaste", "haan", "ok", "hey"):
|
|
|
|
|
|
|
| 916 |
return {
|
| 917 |
"status": "success", "message_type": "question",
|
| 918 |
-
"message":
|
| 919 |
-
"session": _session(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 920 |
}
|
| 921 |
|
| 922 |
-
#
|
| 923 |
-
|
| 924 |
-
_early_cycle = await llm_extract_cycle_data(query.message)
|
| 925 |
-
_cycle_known = bool(_early_cycle.get("last_period_days_ago"))
|
| 926 |
|
| 927 |
-
|
| 928 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 929 |
)
|
| 930 |
-
llm_extras = [s.lower().replace(" ", "_") for s in extracted.get("additional_symptoms", [])]
|
| 931 |
-
new_symptoms = list(dict.fromkeys(rule_syms + llm_extras))
|
| 932 |
|
| 933 |
-
# ββ
|
| 934 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 935 |
if query.pending_questions and query.conversation_turn > 0:
|
| 936 |
-
# Map the user's message as answers to all pending question ids
|
| 937 |
for q in query.pending_questions:
|
| 938 |
answered[q["id"]] = query.message
|
| 939 |
answered = expand_yes_all_answers(answered, query.pending_questions)
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
|
| 945 |
# ββ Merge with session ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 946 |
all_symptoms = list(dict.fromkeys(
|
| 947 |
query.accumulated_symptoms + new_symptoms
|
| 948 |
))
|
| 949 |
-
|
|
|
|
| 950 |
|
| 951 |
# ββ Merge cycle data ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 952 |
cycle_data = dict(query.cycle_data)
|
|
@@ -954,32 +1515,42 @@ async def process_chat(query: ChatRequest, request: Request):
|
|
| 954 |
if v is not None and not cycle_data.get(k):
|
| 955 |
cycle_data[k] = v
|
| 956 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 957 |
if not all_symptoms:
|
| 958 |
msg = (
|
| 959 |
"Namaste! π Koi bhi symptom batayein β fever, pain, weakness, ya kuch aur?"
|
| 960 |
if query.conversation_turn == 0
|
| 961 |
else "Aur koi symptom hai? Mujhe batayein, main samajhne ki koshish karungi."
|
| 962 |
)
|
|
|
|
| 963 |
return {
|
| 964 |
"status": "success", "message_type": "question",
|
| 965 |
"message": msg,
|
| 966 |
-
"session": _session(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 967 |
}
|
| 968 |
|
| 969 |
# ββ Decide: ask more or diagnose βββββββββββββββββββββββββββββββββββββββββ
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
["menstruat", "period", "pelvic", "vaginal", "infertil",
|
| 973 |
-
"heavy_menstrual", "painful_menstruat", "unpredictable", "hirsut"])
|
| 974 |
-
enough_symptoms = len(all_symptoms) >= 4
|
| 975 |
-
answered_questions = query.conversation_turn >= 2 # max 2 question turns
|
| 976 |
|
| 977 |
should_diagnose = enough_symptoms or answered_questions
|
| 978 |
|
| 979 |
if not should_diagnose:
|
| 980 |
-
questions =
|
| 981 |
if questions:
|
| 982 |
-
# Skip cycle questions if we already have cycle data
|
| 983 |
if _cycle_known:
|
| 984 |
questions = [q for q in questions if not any(
|
| 985 |
kw in q.get("text", "").lower()
|
|
@@ -987,39 +1558,56 @@ async def process_chat(query: ChatRequest, request: Request):
|
|
| 987 |
)]
|
| 988 |
if questions:
|
| 989 |
q_text = "\n".join(f"{q['text']}" for q in questions)
|
|
|
|
| 990 |
return {
|
| 991 |
"status": "success", "message_type": "question",
|
| 992 |
"message": q_text,
|
| 993 |
"session": _session(
|
| 994 |
query,
|
| 995 |
symptoms=all_symptoms,
|
|
|
|
| 996 |
cycle=cycle_data,
|
| 997 |
pending=questions,
|
| 998 |
turn=query.conversation_turn + 1,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 999 |
),
|
| 1000 |
}
|
| 1001 |
|
| 1002 |
# ββ Synthesize final symptoms + routing βββββββββββββββββββββββββββββββββββ
|
| 1003 |
-
context = await llm_synthesize_context(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1004 |
final_symptoms = list(dict.fromkeys(
|
| 1005 |
s.lower().replace(" ", "_") for s in context.get("final_symptoms", all_symptoms)
|
| 1006 |
)) or list(dict.fromkeys(s.lower().replace(" ", "_") for s in all_symptoms))
|
| 1007 |
|
| 1008 |
-
# Merge
|
| 1009 |
for k, v in (context.get("cycle_data") or {}).items():
|
| 1010 |
if v is not None and not cycle_data.get(k):
|
| 1011 |
cycle_data[k] = v
|
| 1012 |
|
| 1013 |
# ββ Active tracks βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1014 |
_fi = (
|
| 1015 |
-
any(k in query.message.lower() for k in
|
| 1016 |
["pregnant", "conceive", "fertility", "fertile", "ovulat", "trying for",
|
| 1017 |
"bachha", "garbh", "not getting pregnant", "cant get pregnant"])
|
| 1018 |
or "infertility" in final_symptoms
|
|
|
|
| 1019 |
)
|
| 1020 |
-
_cr =
|
| 1021 |
-
|
| 1022 |
-
|
|
|
|
| 1023 |
_purely_repro = (
|
| 1024 |
all(any(t in s for t in REPRO_TERMS) for s in final_symptoms)
|
| 1025 |
if final_symptoms else False
|
|
@@ -1034,63 +1622,106 @@ async def process_chat(query: ChatRequest, request: Request):
|
|
| 1034 |
"track_fertility_peak": llm_tracks.get("track_fertility_peak", _fi),
|
| 1035 |
}
|
| 1036 |
|
| 1037 |
-
#
|
| 1038 |
-
if
|
| 1039 |
if not cycle_data.get("last_period_days_ago"):
|
| 1040 |
-
answer_text = " ".join(str(v) for v in answered.values()
|
|
|
|
| 1041 |
if answer_text.strip():
|
| 1042 |
-
extra = await llm_extract_cycle_data(answer_text)
|
| 1043 |
for k, v in extra.items():
|
| 1044 |
if v is not None and not cycle_data.get(k):
|
| 1045 |
cycle_data[k] = v
|
| 1046 |
|
| 1047 |
-
# ββ Run tracks ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1048 |
-
results = await run_all_tracks(
|
|
|
|
|
|
|
|
|
|
| 1049 |
|
| 1050 |
# ββ Groq summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1051 |
-
summary = await llm_summarize(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
|
| 1053 |
# ββ Build structured response βββββββββββββββββββββββββββββββββββββββββββββ
|
| 1054 |
structured = {
|
| 1055 |
-
"summary":
|
| 1056 |
"symptoms_detected": [s.replace("_", " ") for s in final_symptoms],
|
|
|
|
|
|
|
| 1057 |
"tracks": {},
|
| 1058 |
}
|
| 1059 |
|
| 1060 |
if "Disease" in results and results["Disease"]:
|
| 1061 |
structured["tracks"]["disease"] = results["Disease"]
|
| 1062 |
-
if "PCOS" in results:
|
| 1063 |
structured["tracks"]["pcos"] = results["PCOS"]
|
| 1064 |
if "Conception" in results:
|
| 1065 |
structured["tracks"]["conception"] = results["Conception"]
|
| 1066 |
if "Fertility" in results:
|
| 1067 |
structured["tracks"]["fertility"] = results["Fertility"]
|
| 1068 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1069 |
return {
|
| 1070 |
"status": "success",
|
| 1071 |
"message_type": "structured",
|
| 1072 |
"message": summary,
|
| 1073 |
"structured": structured,
|
| 1074 |
-
# Reset
|
| 1075 |
-
"session": _session(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1076 |
}
|
| 1077 |
|
| 1078 |
|
| 1079 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1080 |
-
#
|
| 1081 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1082 |
def _session(
|
| 1083 |
query: ChatRequest,
|
| 1084 |
-
symptoms: list
|
| 1085 |
-
|
| 1086 |
-
|
| 1087 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1088 |
) -> dict:
|
| 1089 |
return {
|
| 1090 |
-
"
|
| 1091 |
-
"
|
| 1092 |
-
"
|
| 1093 |
-
"
|
| 1094 |
-
"
|
| 1095 |
-
"
|
| 1096 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
ShakTide AI β main.py (v4)
|
| 3 |
ββββββββββββββββββββββββββββ
|
| 4 |
+
Key upgrades from v3:
|
| 5 |
+
β
25-message rolling context window β LLM sees full conversation history
|
| 6 |
+
β
Token = per-conversation (not per-message) β 10 conversations/day, unlimited turns each
|
| 7 |
+
β
conversation_id tracking β Supabase-backed session management
|
| 8 |
+
β
chat_history actually used in all Groq prompts (was a dead field in v3)
|
| 9 |
+
β
Negation detection β "no fever", "nahi hai", "I don't have X" β accumulated_negated
|
| 10 |
+
β
asked_questions tracking β LLM never repeats a question
|
| 11 |
+
β
age/sex used in all prompts + PCOS age-gating
|
| 12 |
+
β
asyncio.gather() for parallel Groq calls (40-50% latency reduction)
|
| 13 |
+
β
Parallel model loading at startup (non-blocking)
|
| 14 |
+
β
Groq retry with exponential backoff (3 attempts)
|
| 15 |
+
β
Fixed NameError: answered always initialized
|
| 16 |
+
β
Fixed _cycle_known race with pre-regex check before gather
|
| 17 |
+
β
Fixed _extract_json fragility β try parse first, then repair
|
| 18 |
+
β
PCOS guard β only shown when β₯1 repro symptom present
|
| 19 |
+
β
IP spoofing fix β last IP in X-Forwarded-For chain
|
| 20 |
+
β
Atomic Supabase rate-limit via RPC (no race condition)
|
| 21 |
+
β
Pydantic v2 model_config syntax
|
| 22 |
+
β
Structured logging with per-request timing
|
| 23 |
+
β
Context compression for turns > 15
|
| 24 |
+
β
All 6 Groq prompts massively expanded with examples, negation, CoT
|
| 25 |
|
| 26 |
PKL files required (12):
|
| 27 |
tfidf_retriever.pkl sbert_retriever.pkl sym_embedder.pkl
|
|
|
|
| 31 |
best_fert_model.pkl fert_scaler.pkl
|
| 32 |
"""
|
| 33 |
|
| 34 |
+
import os, re, json, io, pickle, datetime, asyncio, logging, time, uuid
|
| 35 |
import numpy as np
|
| 36 |
import pandas as pd
|
| 37 |
from fastapi import FastAPI, Request, HTTPException
|
| 38 |
from fastapi.middleware.cors import CORSMiddleware
|
| 39 |
+
from pydantic import BaseModel, Field, ConfigDict
|
| 40 |
from typing import List, Optional, Dict, Any
|
| 41 |
from groq import AsyncGroq
|
| 42 |
|
| 43 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 44 |
+
# LOGGING
|
| 45 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
+
logging.basicConfig(
|
| 47 |
+
level=logging.INFO,
|
| 48 |
+
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
|
| 49 |
+
)
|
| 50 |
+
logger = logging.getLogger("shaktide")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
# 1. APP + CORS
|
| 55 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
+
app = FastAPI(title="ShakTide AI v4")
|
| 57 |
|
| 58 |
app.add_middleware(
|
| 59 |
CORSMiddleware,
|
|
|
|
| 74 |
|
| 75 |
@app.get("/")
|
| 76 |
def root():
|
| 77 |
+
return {"status": "ShakTide AI v4 is running"}
|
| 78 |
|
| 79 |
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
# 2. SECRETS & CONFIG (all env-driven now)
|
| 82 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
+
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
|
| 84 |
+
SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
|
| 85 |
+
SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
|
| 86 |
+
DAILY_CONVO_LIMIT = int(os.environ.get("DAILY_CONVO_LIMIT", "10")) # conversations/day (was token limit)
|
| 87 |
+
MAX_TURNS_PER_CONVO = int(os.environ.get("MAX_TURNS_PER_CONVO", "25")) # messages within one conversation
|
| 88 |
+
MAX_HISTORY_WINDOW = int(os.environ.get("MAX_HISTORY_WINDOW", "25")) # messages sent to LLM context
|
| 89 |
+
COMPRESS_AFTER_TURN = int(os.environ.get("COMPRESS_AFTER_TURN", "15")) # compress history after this many turns
|
| 90 |
+
MAX_MESSAGE_LEN = int(os.environ.get("MAX_MESSAGE_LEN", "600"))
|
| 91 |
+
GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant")
|
| 92 |
+
TRUSTED_PROXIES = int(os.environ.get("TRUSTED_PROXIES", "1"))
|
| 93 |
|
| 94 |
groq_client = AsyncGroq(api_key=GROQ_API_KEY)
|
| 95 |
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
# 3. MODEL LOADER (non-blocking β runs in thread pool at startup)
|
| 105 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 106 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 107 |
|
| 108 |
+
# Global model references (populated at startup)
|
| 109 |
+
tfidf_retriever = None
|
| 110 |
+
sbert_retriever = None
|
| 111 |
+
sym_embedder = None
|
| 112 |
+
NLP_AVAILABLE = False
|
| 113 |
+
disease_model = None
|
| 114 |
+
disease_encoder = None
|
| 115 |
+
symptom_scaler = None
|
| 116 |
+
pcos_model = None
|
| 117 |
+
pcos_scaler = None
|
| 118 |
+
cycle_model = None
|
| 119 |
+
cycle_scaler = None
|
| 120 |
+
fert_model = None
|
| 121 |
+
fert_scaler = None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _load_sync(name: str):
|
| 125 |
+
"""Synchronous loader β called via asyncio.to_thread at startup."""
|
| 126 |
path = os.path.join(BASE_DIR, name)
|
| 127 |
if not os.path.exists(path):
|
| 128 |
+
logger.warning("Model file not found: %s β skipping.", name)
|
| 129 |
return None
|
| 130 |
|
| 131 |
class CompatUnpickler(pickle.Unpickler):
|
|
|
|
| 143 |
up = CompatUnpickler(io.BytesIO(data))
|
| 144 |
up.encoding = encoding
|
| 145 |
result = up.load()
|
| 146 |
+
logger.info("Loaded %s (encoding=%s)", name, encoding)
|
| 147 |
return result
|
| 148 |
except Exception:
|
| 149 |
continue
|
|
|
|
| 151 |
try:
|
| 152 |
import joblib
|
| 153 |
result = joblib.load(path)
|
| 154 |
+
logger.info("Loaded %s (joblib)", name)
|
| 155 |
return result
|
| 156 |
except Exception as e:
|
| 157 |
+
logger.error("Could not load %s: %s", name, e)
|
| 158 |
return None
|
| 159 |
|
| 160 |
|
| 161 |
+
@app.on_event("startup")
|
| 162 |
+
async def load_all_models():
|
| 163 |
+
"""Load all 12 pkl files in parallel at startup β does not block event loop."""
|
| 164 |
+
global tfidf_retriever, sbert_retriever, sym_embedder, NLP_AVAILABLE
|
| 165 |
+
global disease_model, disease_encoder, symptom_scaler
|
| 166 |
+
global pcos_model, pcos_scaler, cycle_model, cycle_scaler, fert_model, fert_scaler
|
| 167 |
|
| 168 |
+
model_names = [
|
| 169 |
+
"tfidf_retriever.pkl", "sbert_retriever.pkl", "sym_embedder.pkl",
|
| 170 |
+
"best_disease_model.pkl", "disease_encoder.pkl", "symptom_scaler.pkl",
|
| 171 |
+
"best_pcos_model.pkl", "pcos_scaler.pkl",
|
| 172 |
+
"best_cycle_model.pkl", "cycle_scaler.pkl",
|
| 173 |
+
"best_fert_model.pkl", "fert_scaler.pkl",
|
| 174 |
+
]
|
| 175 |
|
| 176 |
+
t0 = time.monotonic()
|
| 177 |
+
results = await asyncio.gather(
|
| 178 |
+
*[asyncio.to_thread(_load_sync, name) for name in model_names]
|
| 179 |
+
)
|
| 180 |
+
(
|
| 181 |
+
tfidf_retriever, sbert_retriever, sym_embedder,
|
| 182 |
+
disease_model, disease_encoder, symptom_scaler,
|
| 183 |
+
pcos_model, pcos_scaler,
|
| 184 |
+
cycle_model, cycle_scaler,
|
| 185 |
+
fert_model, fert_scaler,
|
| 186 |
+
) = results
|
| 187 |
+
|
| 188 |
+
NLP_AVAILABLE = all(v is not None for v in [tfidf_retriever, sbert_retriever, sym_embedder])
|
| 189 |
+
logger.info(
|
| 190 |
+
"All models loaded in %.1fs | NLP_AVAILABLE=%s",
|
| 191 |
+
time.monotonic() - t0, NLP_AVAILABLE
|
| 192 |
+
)
|
| 193 |
|
| 194 |
|
| 195 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 196 |
+
# 4. CONSTANTS
|
| 197 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 198 |
MALE_ANATOMY_TERMS = {"scrotum", "testes", "testicular", "penile", "prostate"}
|
| 199 |
|
|
|
|
| 260 |
r"\b(stalk|doxx|harass|blackmail)\b",
|
| 261 |
]
|
| 262 |
|
| 263 |
+
# Negation patterns β Hindi, English, Hinglish
|
| 264 |
+
NEGATION_PATTERNS = [
|
| 265 |
+
# English patterns
|
| 266 |
+
r"\bno\s+([a-z_\s]+?)(?:\s+(?:at all|though|yet|so far|really))?(?=\s*[,.\n]|$)",
|
| 267 |
+
r"\bdon'?t\s+have\s+([a-z_\s]+)",
|
| 268 |
+
r"\bdo\s+not\s+have\s+([a-z_\s]+)",
|
| 269 |
+
r"\bwithout\s+([a-z_\s]+)",
|
| 270 |
+
r"\bnot\s+(?:experiencing|having|feeling|getting)\s+([a-z_\s]+)",
|
| 271 |
+
r"\b([a-z_\s]+)\s+(?:nahi|nahin|nhi)\s+(?:hai|he|hain|ho raha|ho rahi)",
|
| 272 |
+
r"\b([a-z_\s]+)\s+nahi\b",
|
| 273 |
+
r"\bkoi\s+([a-z_\s]+)\s+nahi",
|
| 274 |
+
r"\bnahi\s+hai\s+([a-z_\s]+)",
|
| 275 |
+
]
|
| 276 |
+
|
| 277 |
|
| 278 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 279 |
+
# 5. PHRASE MAP (unchanged from v3 β full map)
|
| 280 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 281 |
PHRASE_MAP = {
|
| 282 |
r"head.*bonkers|bonkers.*head|head.*splitting|head.*killing|severe headache|throbbing headache|migraine|sir.*dard|sar.*dard": "headache",
|
|
|
|
| 373 |
return list(found)
|
| 374 |
|
| 375 |
|
| 376 |
+
def rule_extract_negations(text: str) -> list:
|
| 377 |
+
"""
|
| 378 |
+
Detect explicitly denied symptoms from text.
|
| 379 |
+
Returns list of symptom strings that should be added to accumulated_negated.
|
| 380 |
+
"""
|
| 381 |
+
cleaned = re.sub(r"[^a-z0-9\s',.!?]", " ", text.lower().strip())
|
| 382 |
+
negated = set()
|
| 383 |
+
|
| 384 |
+
# Pattern: "no fever", "don't have pain", "nahi hai dard"
|
| 385 |
+
# First, find negated spans
|
| 386 |
+
neg_spans = []
|
| 387 |
+
neg_triggers = [
|
| 388 |
+
r"\bno\b", r"\bnot\b", r"\bnahi\b", r"\bnahin\b", r"\bnhi\b",
|
| 389 |
+
r"\bdon'?t have\b", r"\bnever had\b", r"\bwithout\b",
|
| 390 |
+
r"\bnot experiencing\b", r"\bnot feeling\b",
|
| 391 |
+
]
|
| 392 |
+
for trigger in neg_triggers:
|
| 393 |
+
for m in re.finditer(trigger, cleaned):
|
| 394 |
+
# Take the 40 chars after the negation trigger
|
| 395 |
+
span_text = cleaned[m.start():min(m.end()+40, len(cleaned))]
|
| 396 |
+
neg_spans.append(span_text)
|
| 397 |
+
|
| 398 |
+
# Now check if any known symptom appears in those spans
|
| 399 |
+
for span in neg_spans:
|
| 400 |
+
for pattern, symptom in PHRASE_MAP.items():
|
| 401 |
+
if re.search(pattern, span):
|
| 402 |
+
negated.add(symptom)
|
| 403 |
+
|
| 404 |
+
return list(negated)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
def expand_yes_all_answers(answers: dict, questions: list) -> dict:
|
| 408 |
expanded = dict(answers)
|
| 409 |
YES_ALL = {
|
|
|
|
| 437 |
return expanded
|
| 438 |
|
| 439 |
|
| 440 |
+
def _format_history_for_prompt(chat_history: list, max_messages: int = 25) -> str:
|
| 441 |
+
"""Format chat_history as a readable conversation string for LLM context."""
|
| 442 |
+
if not chat_history:
|
| 443 |
+
return "(This is the first message β no prior conversation.)"
|
| 444 |
+
recent = chat_history[-max_messages:]
|
| 445 |
+
lines = []
|
| 446 |
+
for msg in recent:
|
| 447 |
+
role = "Patient" if msg.get("role") == "user" else "ShakTide AI"
|
| 448 |
+
content = str(msg.get("content", "")).strip()
|
| 449 |
+
if content:
|
| 450 |
+
lines.append(f"{role}: {content}")
|
| 451 |
+
return "\n".join(lines) if lines else "(No prior conversation.)"
|
| 452 |
+
|
| 453 |
+
|
| 454 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 455 |
+
# 6. GROQ HELPERS (async + retry)
|
| 456 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 457 |
def _extract_json(text: str) -> str:
|
| 458 |
+
"""
|
| 459 |
+
Robust JSON extractor:
|
| 460 |
+
1. Strip markdown fences
|
| 461 |
+
2. Try direct parse
|
| 462 |
+
3. Extract outermost {} and repair trailing commas
|
| 463 |
+
"""
|
| 464 |
+
text = text.strip()
|
| 465 |
+
# Strip markdown fences
|
| 466 |
+
text = re.sub(r"^```[a-zA-Z]*\n?", "", text)
|
| 467 |
text = re.sub(r"\n?```$", "", text.strip())
|
| 468 |
+
# Try direct parse first
|
| 469 |
+
try:
|
| 470 |
+
json.loads(text)
|
| 471 |
return text
|
| 472 |
+
except json.JSONDecodeError:
|
| 473 |
+
pass
|
| 474 |
+
# Extract outermost braces
|
| 475 |
+
start = text.find("{")
|
| 476 |
+
end = text.rfind("}")
|
| 477 |
+
if start != -1 and end > start:
|
| 478 |
+
candidate = text[start:end+1]
|
| 479 |
+
# Repair: trailing comma before } or ]
|
| 480 |
+
candidate = re.sub(r",(\s*[}\]])", r"\1", candidate)
|
| 481 |
+
return candidate
|
| 482 |
+
return text
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
async def _groq(system: str, user: str, max_tokens: int = 800,
|
| 486 |
+
retries: int = 3) -> str:
|
| 487 |
+
"""Groq call with exponential backoff retry."""
|
| 488 |
+
last_exc = None
|
| 489 |
+
for attempt in range(retries):
|
| 490 |
+
try:
|
| 491 |
+
resp = await groq_client.chat.completions.create(
|
| 492 |
+
model=GROQ_MODEL,
|
| 493 |
+
messages=[
|
| 494 |
+
{"role": "system", "content": system},
|
| 495 |
+
{"role": "user", "content": user},
|
| 496 |
+
],
|
| 497 |
+
max_tokens=max_tokens,
|
| 498 |
+
temperature=0.1,
|
| 499 |
+
)
|
| 500 |
+
return _extract_json(resp.choices[0].message.content.strip())
|
| 501 |
+
except Exception as e:
|
| 502 |
+
last_exc = e
|
| 503 |
+
if attempt < retries - 1:
|
| 504 |
+
wait = 2 ** attempt # 1s, 2s
|
| 505 |
+
logger.warning("Groq attempt %d failed: %s β retrying in %ds", attempt+1, e, wait)
|
| 506 |
+
await asyncio.sleep(wait)
|
| 507 |
+
logger.error("All Groq retries exhausted: %s", last_exc)
|
| 508 |
+
raise last_exc
|
|
|
|
| 509 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
|
| 511 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 512 |
+
# 7. GROQ SYSTEM PROMPTS (massively upgraded v4)
|
| 513 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
|
| 515 |
+
EXTRACT_SYSTEM = """You are a clinical symptom extraction engine for ShakTide β a women's menstrual and general health app serving Indian patients.
|
| 516 |
+
|
| 517 |
+
PATIENT CONTEXT:
|
| 518 |
+
- Patients write in Hindi, English, or Hinglish (mixed)
|
| 519 |
+
- Many use informal or colloquial terms (e.g. "pet mein dard" = abdominal pain, "baal jhad rahe" = hair fall)
|
| 520 |
+
- Patients may be describing symptoms indirectly ("I feel terrible after eating" β nausea/vomiting)
|
| 521 |
+
- The app is used ONLY by people assigned female at birth (AFAB)
|
| 522 |
+
|
| 523 |
+
YOUR TASK:
|
| 524 |
+
You receive:
|
| 525 |
+
- patient_message: the current message
|
| 526 |
+
- chat_history_summary: the full conversation so far (up to 25 messages)
|
| 527 |
+
- already_found: symptoms already extracted by rule-based system
|
| 528 |
+
- session_symptoms: all symptoms accumulated across the session
|
| 529 |
+
- asked_questions: list of question texts already asked this session
|
| 530 |
+
- cycle_data_already_provided: boolean
|
| 531 |
+
- patient_age: integer or null
|
| 532 |
+
- patient_sex: string or null
|
| 533 |
+
|
| 534 |
+
STEP 1 β EXTRACT NEW SYMPTOMS:
|
| 535 |
+
- Add symptoms ONLY if EXPLICITLY mentioned or VERY STRONGLY implied in current message OR in the chat_history
|
| 536 |
+
- NEVER infer. "I feel bad" is NOT diarrhea. "Loose motions" IS diarrhea.
|
| 537 |
+
- Do NOT re-add symptoms already in session_symptoms
|
| 538 |
+
- Normalize to snake_case: "hair fall" β "hair_thinning", "periods irregular" β "unpredictable_menstruation"
|
| 539 |
+
- If patient says "yes" or "haan" β look at the LAST assistant question in chat_history to resolve what they're confirming
|
| 540 |
+
- If patient says "no" or "nahi" β extract those as negated_symptoms
|
| 541 |
+
|
| 542 |
+
STEP 2 β DETECT NEGATIONS:
|
| 543 |
+
- Detect explicitly denied symptoms: "no fever", "nahi hai bukhar", "I don't have headache"
|
| 544 |
+
- Return them in negated_symptoms[] β these will be REMOVED from the symptom list
|
| 545 |
+
|
| 546 |
+
STEP 3 β ASK CLARIFYING QUESTIONS:
|
| 547 |
+
- Ask UP TO 2 questions, but ONLY if they would meaningfully change the diagnosis
|
| 548 |
+
- NEVER ask about symptoms already in session_symptoms or asked_questions
|
| 549 |
+
- If cycle data already provided (cycle_data_already_provided=true), NEVER ask about period timing again
|
| 550 |
+
- If patient is trying to conceive, ask about cycle data if missing
|
| 551 |
+
- Always add "(aap I don't know ya skip bhi bol sakti hain)" to each question
|
| 552 |
+
- Questions must be warm, non-clinical, and in Hinglish
|
| 553 |
+
|
| 554 |
+
QUESTION QUALITY RULES:
|
| 555 |
+
- BAD: "Do you have nausea?" (too clinical, single symptom)
|
| 556 |
+
- GOOD: "Kya aapko khana khane ke baad ji machlaata hai, ya ulti jaisi feeling hoti hai?"
|
| 557 |
+
- BAD: "How long have you had these symptoms?" (open-ended, not useful for routing)
|
| 558 |
+
- GOOD: "Yeh periods ki problem kitne time se hai β kuch hafte, ya kaafi mahino se?" (specific, useful)
|
| 559 |
+
- NEVER ask a question that was already in asked_questions list
|
| 560 |
+
|
| 561 |
+
FEW-SHOT EXAMPLES:
|
| 562 |
+
Input: patient_message="pet mein bahut dard hai aur ulti ho rahi hai", already_found=["vomiting"]
|
| 563 |
+
Output: {"additional_symptoms":["lower_abdominal_pain","nausea"],"negated_symptoms":[],"reproductive_context":null,"questions":[{"id":"q1","text":"Kya yeh dard periods ke time zyada hota hai, ya hamesha rehta hai? (aap I don't know ya skip bhi bol sakti hain)"}]}
|
| 564 |
+
|
| 565 |
+
Input: patient_message="no fever, but I have terrible headache and dizziness", already_found=["headache"]
|
| 566 |
+
Output: {"additional_symptoms":["dizziness"],"negated_symptoms":["fever"],"reproductive_context":null,"questions":[{"id":"q1","text":"Kya yeh sir dard ek taraf zyada hota hai, ya poore sar mein? Aur kya roshni ya awaaz se takleef hoti hai? (skip bhi bol sakti hain)"}]}
|
| 567 |
+
|
| 568 |
+
Input: patient_message="haan sab", already_found=[], session_symptoms=["unpredictable_menstruation"]
|
| 569 |
+
(The last assistant question was: "Kya aapko acne, weight gain, ya hair fall bhi hai?")
|
| 570 |
+
Output: {"additional_symptoms":["acne_or_pimples","weight_gain","hair_thinning"],"negated_symptoms":[],"reproductive_context":"menstrual","questions":[]}
|
| 571 |
+
|
| 572 |
+
Respond ONLY with compact JSON on one line β no explanation, no preamble:
|
| 573 |
+
{"additional_symptoms":[],"negated_symptoms":[],"reproductive_context":null,"questions":[{"id":"q1","text":"..."}]}"""
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
SYNTHESIZE_SYSTEM = """You are the clinical routing and synthesis engine for ShakTide, a women's health AI assistant for Indian patients.
|
| 577 |
+
|
| 578 |
+
YOU RECEIVE:
|
| 579 |
+
- original_query: first message of the session
|
| 580 |
+
- current_message: latest patient message
|
| 581 |
+
- chat_history_summary: FULL conversation (up to 25 messages) β READ THIS CAREFULLY
|
| 582 |
+
- all_symptoms: accumulated symptoms from all turns combined
|
| 583 |
+
- followup_answers: answers to clarifying questions this turn
|
| 584 |
+
- previously_known_cycle_data: cycle data already extracted in prior turns
|
| 585 |
+
- patient_age: integer or null (use for PCOS age-gating and disease prior)
|
| 586 |
+
- session_negated: symptoms the patient explicitly denied
|
| 587 |
+
|
| 588 |
+
YOUR TASKS:
|
| 589 |
+
|
| 590 |
+
TASK 1 β PRODUCE FINAL SYMPTOMS:
|
| 591 |
+
- Start from all_symptoms, add any new ones from followup_answers and chat_history
|
| 592 |
+
- Remove anything in session_negated (explicitly denied)
|
| 593 |
+
- Remove disease names (e.g. "pcos", "typhoid") β keep only symptoms
|
| 594 |
+
- Normalize to snake_case consistently
|
| 595 |
+
- NEVER return an empty list if the patient described any health issue
|
| 596 |
+
|
| 597 |
+
TASK 2 β RESOLVE CONTRADICTIONS:
|
| 598 |
+
- If patient said "no fever" early but "fever for 2 days" later β use LATER statement (fever present)
|
| 599 |
+
- If patient said "periods regular" but also "2-4 month gap" β irregular wins (more specific)
|
| 600 |
+
- Apply recency bias: later statements override earlier ones for the SAME symptom
|
| 601 |
+
|
| 602 |
+
TASK 3 β EXTRACT CYCLE DATA:
|
| 603 |
+
From the FULL chat_history and followup_answers, extract:
|
| 604 |
+
- cycle_length_days: days between period starts (NOT duration of bleeding)
|
| 605 |
+
- last_period_days_ago: how many days since last period started
|
| 606 |
+
- cycle_regularity: "regular" | "irregular" | "very_irregular" | null
|
| 607 |
+
- period_duration_days: how many days bleeding lasts (separate from cycle length!)
|
| 608 |
+
- trying_to_conceive: true if ANY message mentions wanting to get pregnant
|
| 609 |
+
Merge with previously_known_cycle_data β never overwrite a known value with null.
|
| 610 |
+
|
| 611 |
+
CYCLE DATA PARSING RULES:
|
| 612 |
+
"2 weeks back" β 14, "a week ago" β 7, "last month" β 30, "4 days back" β 4
|
| 613 |
+
"28-30 day cycle" β 29, "2-4 month gap" β cycle_length_days=75, regularity=very_irregular
|
| 614 |
+
"7 day period" β period_duration_days=7 (NOT cycle_length!)
|
| 615 |
+
"comes every 40 days" β cycle_length_days=40
|
| 616 |
+
|
| 617 |
+
TASK 4 β ROUTE TO TRACKS:
|
| 618 |
+
track_disease: true if ANY non-reproductive symptoms present (fever, vomiting, chest pain, etc.)
|
| 619 |
+
false if ALL symptoms are reproductive/menstrual only
|
| 620 |
+
track_pcos: true if β₯1 of: irregular periods, acne, weight gain, hair loss/thinning, facial hair, hirsutism
|
| 621 |
+
track_conception: true if patient EXPLICITLY mentions trying to conceive, or "bachha chahiye", "pregnant hona chahti"
|
| 622 |
+
track_fertility_peak: true if patient asks about fertile window, ovulation, best time to conceive
|
| 623 |
+
|
| 624 |
+
AGE-BASED ADJUSTMENTS:
|
| 625 |
+
- If patient_age < 18: lower PCOS threshold (more common in teens), note in clinical_notes
|
| 626 |
+
- If patient_age > 45: raise possibility of perimenopause in clinical_notes
|
| 627 |
+
- If patient_age > 50: menstrual symptoms may indicate perimenopause/menopause
|
| 628 |
+
|
| 629 |
+
Respond ONLY with compact JSON:
|
| 630 |
+
{"final_symptoms":[],"tracks":{"track_disease":false,"track_pcos":true,"track_conception":false,"track_fertility_peak":false},"cycle_data":{"cycle_length_days":null,"last_period_days_ago":null,"cycle_regularity":null,"period_duration_days":null,"trying_to_conceive":false},"clinical_notes":null}"""
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
CYCLE_DATA_SYSTEM = """You are a cycle data extraction specialist for a women's health app. Extract menstrual cycle information from patient text (Hindi, English, or Hinglish).
|
| 634 |
+
|
| 635 |
+
CRITICAL DISTINCTION β cycle_length vs period_duration:
|
| 636 |
+
cycle_length_days = days BETWEEN period starts (normal: 21-35 days)
|
| 637 |
+
period_duration_days = how many days the BLEEDING lasts (normal: 3-7 days)
|
| 638 |
+
These are DIFFERENT. "My period lasts 7 days" β period_duration=7, NOT cycle_length=7.
|
| 639 |
+
|
| 640 |
+
CONVERSION EXAMPLES:
|
| 641 |
+
"a week ago" β last_period_days_ago: 7
|
| 642 |
+
"2 weeks back" β last_period_days_ago: 14
|
| 643 |
+
"1 month ago" β last_period_days_ago: 30
|
| 644 |
+
"last one was 4 days back" β last_period_days_ago: 4
|
| 645 |
+
"aaj se 10 din pehle" β last_period_days_ago: 10
|
| 646 |
+
"pichhle hafte" β last_period_days_ago: 7
|
| 647 |
+
"4 week cycle" β cycle_length_days: 28
|
| 648 |
+
"28-30 din ka cycle" β cycle_length_days: 29
|
| 649 |
+
"2-4 months gap" β cycle_length_days: 75, cycle_regularity: "very_irregular"
|
| 650 |
+
"40-60 days" β cycle_length_days: 50, cycle_regularity: "very_irregular"
|
| 651 |
+
"kabhi kabhi aata hai" β cycle_regularity: "very_irregular"
|
| 652 |
+
"regular rehta hai" β cycle_regularity: "regular"
|
| 653 |
+
|
| 654 |
+
TRYING TO CONCEIVE β set to true if:
|
| 655 |
+
"pregnant hona chahti", "bachha chahiye", "conceive karna chahti",
|
| 656 |
+
"trying for baby", "trying to get pregnant", "getting pregnant", "fertility"
|
| 657 |
+
|
| 658 |
+
Return null for anything not mentioned or unclear.
|
| 659 |
+
Respond ONLY with compact JSON on one line:
|
| 660 |
+
{"cycle_length_days":null,"last_period_days_ago":null,"cycle_regularity":null,"period_duration_days":null,"trying_to_conceive":false}"""
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
VERIFY_SYSTEM = """You are a clinical verification engine for ShakTide, a women's health AI.
|
| 664 |
+
|
| 665 |
+
You receive a list of candidate diseases ranked by TF-IDF + SBERT ensemble scores, along with the patient's confirmed symptoms and conversation history.
|
| 666 |
+
|
| 667 |
+
YOUR TASK β CHAIN OF THOUGHT VERIFICATION:
|
| 668 |
+
Step 1: List the patient's symptoms and their typical disease associations
|
| 669 |
+
Step 2: For each top-3 candidate, assess: does the symptom profile fit? What symptoms support it? What symptoms argue against it?
|
| 670 |
+
Step 3: Check for emergency flags β chest pain + shortness of breath β possible cardiac/pulmonary; high fever + neck stiffness β possible meningitis
|
| 671 |
+
Step 4: Select the final condition from the CANDIDATE LIST ONLY (verbatim name)
|
| 672 |
+
Step 5: Assess confidence: high (>70% symptom match), medium (50-70%), low (<50%)
|
| 673 |
+
|
| 674 |
+
RULES:
|
| 675 |
+
- Pick ONLY from the candidate list provided β verbatim name
|
| 676 |
+
- Do NOT default to rank 1 just because it ranked first
|
| 677 |
+
- If no candidate fits well, pick least-wrong AND flag confidence as "low"
|
| 678 |
+
- Set emergency_flag: true if symptoms suggest a potentially serious/emergent condition needing immediate care
|
| 679 |
+
- Consider the patient's sex (female/AFAB) when evaluating gendered conditions
|
| 680 |
+
|
| 681 |
+
EXAMPLE REASONING:
|
| 682 |
+
Symptoms: [sharp_chest_pain, shortness_of_breath, dizziness, sweating]
|
| 683 |
+
Candidate 1: migraine (rank 1 by TF-IDF) β headache absent, aura absent β POOR FIT
|
| 684 |
+
Candidate 3: pneumonia (rank 3 by SBERT) β respiratory + chest pain β BETTER FIT
|
| 685 |
+
Candidate 5: pulmonary_embolism β chest pain + SOB + dizziness β STRONG FIT
|
| 686 |
+
β final: pneumonia OR pulmonary_embolism (depending on candidates), confidence: medium, emergency_flag: true
|
| 687 |
+
|
| 688 |
+
Respond ONLY with compact JSON:
|
| 689 |
+
{"final_condition":"exact candidate name","reasoning":"2-3 sentence explanation","confidence":"high|medium|low","emergency_flag":false}"""
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
SUMMARY_SYSTEM = """You are ShakTide's compassionate women's health AI assistant for Indian patients.
|
| 693 |
+
Write a warm, personalized summary in HINGLISH β the natural mix of Hindi and English that urban Indian women use daily.
|
| 694 |
+
|
| 695 |
+
WHAT YOU RECEIVE:
|
| 696 |
+
- patient_symptoms: list of confirmed symptoms
|
| 697 |
+
- diagnostic_results: disease/PCOS/conception findings
|
| 698 |
+
- cycle_data: menstrual cycle information
|
| 699 |
+
- original_query: what the patient first said
|
| 700 |
+
- chat_history_summary: full conversation β USE THIS to personalize
|
| 701 |
+
- patient_age: use if provided (e.g. "Aapki umar 24 saal hai, is umar mein...")
|
| 702 |
+
- emergency_flag: if true, lead with urgent language
|
| 703 |
+
|
| 704 |
+
HINGLISH STYLE GUIDE (examples of natural Hinglish):
|
| 705 |
+
β
"Aapke symptoms dekh ke lagta hai ki..."
|
| 706 |
+
β
"Yeh gastroenteritis ke signs ho sakte hain."
|
| 707 |
+
β
"Aapne bataya tha ki periods bahut irregular hain β yeh PCOS ka ek strong indicator hai."
|
| 708 |
+
β
"Abhi aap apne fertile window ke aas-paas hain."
|
| 709 |
+
β
"Kuch strong indicators hain PCOS ke, par final confirm karna hai toh doctor se milna zaroori hai."
|
| 710 |
+
β
"Bukhar aur ulti dono hain β yeh stomach infection jaisi condition ho sakti hai."
|
| 711 |
+
β Never say percentages ("70% chance")
|
| 712 |
+
β Never say "based on your symptoms" (too robotic)
|
| 713 |
+
β Never sound like an English sentence with Hindi words dropped in randomly
|
| 714 |
+
|
| 715 |
+
CONTENT STRUCTURE:
|
| 716 |
+
1. If emergency_flag is true β start with "β οΈ Yeh symptoms serious ho sakte hain β abhi doctor ke paas jaayein."
|
| 717 |
+
2. Personalize using chat history: "Aapne bataya tha ki [recalled detail]..."
|
| 718 |
+
3. Primary finding (disease OR PCOS, whichever is stronger)
|
| 719 |
+
4. Secondary finding (if both present)
|
| 720 |
+
5. If cycle/fertility data present: mention fertile window or conception likelihood naturally
|
| 721 |
+
6. If patient_age provided and relevant: personalize to age
|
| 722 |
+
7. Close with: "Please ek qualified doctor se zaroor milein proper evaluation ke liye. π"
|
| 723 |
+
|
| 724 |
+
ORDERING:
|
| 725 |
+
- disease_primary: lead with disease if non-repro symptoms dominate
|
| 726 |
+
- pcos_primary: lead with PCOS if irregular periods/hormonal symptoms dominate
|
| 727 |
+
- if both equal: go with whichever is more actionable/urgent
|
| 728 |
+
|
| 729 |
+
LENGTH: 4-6 sentences. Warm, non-alarmist (unless emergency). Plain text only β no bullets, no JSON, no markdown.
|
| 730 |
+
|
| 731 |
+
PERSONALIZATION EXAMPLE:
|
| 732 |
+
Patient said: "baal jhad rahe hain, periods nahi aa rahe, weight badh gaya"
|
| 733 |
+
PCOS result: Strong indicators
|
| 734 |
+
Good summary: "Aapne jo symptoms bataye hain β baal jhhadna, irregular periods, aur weight gain β yeh teen milke PCOS ke strong indicators hain. PCOS ek common hormonal condition hai jo kaafi Indian mahilaon mein hoti hai, toh ghabrane ki baat nahi. Ek gynecologist se milke ultrasound aur kuch blood tests karwa lein β yeh sab clearly batayenge ki kya ho raha hai. Please ek doctor se zaroor milein proper evaluation ke liye. π" """
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
CONTEXT_COMPRESS_SYSTEM = """You are a medical conversation summarizer for a women's health app.
|
| 738 |
+
|
| 739 |
+
Summarize the provided conversation history into a compact clinical summary that preserves ALL medically relevant facts.
|
| 740 |
+
|
| 741 |
+
MUST PRESERVE:
|
| 742 |
+
- All symptoms mentioned (including denied ones: "patient denied fever")
|
| 743 |
+
- All cycle data (cycle length, last period date, regularity)
|
| 744 |
+
- All answers to clarifying questions
|
| 745 |
+
- Whether patient is trying to conceive
|
| 746 |
+
- Patient's age if mentioned
|
| 747 |
+
- Any prior diagnoses or medications mentioned
|
| 748 |
+
|
| 749 |
+
DISCARD:
|
| 750 |
+
- Greetings, pleasantries, "thank you", "okay"
|
| 751 |
+
- Repeated questions/answers (keep the final answer only)
|
| 752 |
+
- Meta-conversation ("I understand", "let me help you")
|
| 753 |
+
|
| 754 |
+
FORMAT: Write as compact bullet points, starting with "Session summary:"
|
| 755 |
+
Example:
|
| 756 |
+
Session summary:
|
| 757 |
+
β’ Symptoms: heavy periods, pelvic pain, infertility, fatigue
|
| 758 |
+
β’ Denied: fever, vomiting
|
| 759 |
+
β’ Cycle: 40-60 day gaps (very irregular), last period ~4 days ago
|
| 760 |
+
β’ Trying to conceive: yes
|
| 761 |
+
β’ Age: 28
|
| 762 |
+
|
| 763 |
+
Respond with PLAIN TEXT bullet points β no JSON."""
|
| 764 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
|
| 766 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 767 |
+
# 8. GROQ CALL FUNCTIONS (all now receive chat_history)
|
| 768 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 769 |
|
| 770 |
+
async def llm_extract_and_question(
|
| 771 |
+
user_query: str,
|
| 772 |
+
rule_symptoms: list,
|
| 773 |
+
session_symptoms: list,
|
| 774 |
+
chat_history: list,
|
| 775 |
+
asked_questions: list,
|
| 776 |
+
cycle_already_known: bool = False,
|
| 777 |
+
age: Optional[int] = None,
|
| 778 |
+
sex: Optional[str] = None,
|
| 779 |
+
) -> dict:
|
| 780 |
+
history_str = _format_history_for_prompt(chat_history, MAX_HISTORY_WINDOW)
|
| 781 |
user_content = json.dumps({
|
| 782 |
+
"patient_message": user_query,
|
| 783 |
+
"chat_history_summary": history_str,
|
| 784 |
+
"already_found": rule_symptoms,
|
| 785 |
+
"session_symptoms": session_symptoms,
|
| 786 |
+
"asked_questions": asked_questions,
|
| 787 |
"cycle_data_already_provided": cycle_already_known,
|
| 788 |
+
"patient_age": age,
|
| 789 |
+
"patient_sex": sex or "female",
|
| 790 |
})
|
| 791 |
try:
|
| 792 |
+
raw = await _groq(EXTRACT_SYSTEM, user_content, max_tokens=700)
|
| 793 |
+
return json.loads(raw)
|
| 794 |
+
except Exception as e:
|
| 795 |
+
logger.warning("llm_extract_and_question failed: %s", e)
|
| 796 |
+
return {"additional_symptoms": [], "negated_symptoms": [], "reproductive_context": None, "questions": []}
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
async def llm_extract_cycle_data(text: str, chat_history: list = None) -> dict:
|
| 800 |
+
"""Extract cycle data from current message + history context."""
|
| 801 |
+
context = ""
|
| 802 |
+
if chat_history:
|
| 803 |
+
context = _format_history_for_prompt(chat_history[-10:], 10) # last 10 messages only
|
| 804 |
+
combined = f"Current message: {text}"
|
| 805 |
+
if context:
|
| 806 |
+
combined += f"\n\nRecent conversation context:\n{context}"
|
| 807 |
+
try:
|
| 808 |
+
raw = await _groq(CYCLE_DATA_SYSTEM, combined, max_tokens=200)
|
| 809 |
return json.loads(raw)
|
| 810 |
except Exception:
|
| 811 |
+
return {"cycle_length_days": None, "last_period_days_ago": None,
|
| 812 |
+
"cycle_regularity": None, "period_duration_days": None, "trying_to_conceive": False}
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
async def llm_synthesize_context(
|
| 816 |
+
original_query: str,
|
| 817 |
+
current_message: str,
|
| 818 |
+
all_symptoms: list,
|
| 819 |
+
answered: dict,
|
| 820 |
+
chat_history: list,
|
| 821 |
+
cycle_data: dict,
|
| 822 |
+
session_negated: list,
|
| 823 |
+
age: Optional[int] = None,
|
| 824 |
+
) -> dict:
|
| 825 |
+
history_str = _format_history_for_prompt(chat_history, MAX_HISTORY_WINDOW)
|
| 826 |
user_content = json.dumps({
|
| 827 |
+
"original_query": original_query,
|
| 828 |
+
"current_message": current_message,
|
| 829 |
+
"chat_history_summary": history_str,
|
| 830 |
+
"all_symptoms": all_symptoms,
|
| 831 |
+
"followup_answers": answered,
|
| 832 |
+
"previously_known_cycle_data": cycle_data,
|
| 833 |
+
"session_negated": session_negated,
|
| 834 |
+
"patient_age": age,
|
| 835 |
}, indent=2)
|
| 836 |
try:
|
| 837 |
+
raw = await _groq(SYNTHESIZE_SYSTEM, user_content, max_tokens=800)
|
| 838 |
parsed = json.loads(raw)
|
| 839 |
if "cycle_data" not in parsed:
|
| 840 |
parsed["cycle_data"] = {}
|
| 841 |
return parsed
|
| 842 |
+
except Exception as e:
|
| 843 |
+
logger.warning("llm_synthesize_context failed: %s", e)
|
| 844 |
_cycle = any(k in " ".join(all_symptoms) for k in
|
| 845 |
["menstruat", "period", "irregular", "unpredictable", "infertil", "heavy_menstrual"])
|
| 846 |
+
_fi = any(k in (original_query + current_message).lower()
|
| 847 |
+
for k in ["pregnant", "conceive", "fertility", "bachha"])
|
| 848 |
return {
|
| 849 |
+
"final_symptoms": [s for s in all_symptoms if s not in session_negated],
|
| 850 |
"tracks": {
|
| 851 |
"track_disease": bool(all_symptoms) and not _fi,
|
| 852 |
"track_pcos": _cycle,
|
| 853 |
"track_conception": _fi,
|
| 854 |
"track_fertility_peak": _fi,
|
| 855 |
},
|
| 856 |
+
"cycle_data": cycle_data,
|
| 857 |
"clinical_notes": None,
|
| 858 |
}
|
| 859 |
|
| 860 |
|
| 861 |
+
async def llm_verify_disease(symptoms: list, candidates: list, chat_history: list = None) -> dict:
|
| 862 |
+
history_str = _format_history_for_prompt(chat_history[-6:] if chat_history else [], 6)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 863 |
user_content = json.dumps({
|
| 864 |
"confirmed_symptoms": [s.replace("_", " ") for s in symptoms],
|
| 865 |
+
"conversation_context": history_str,
|
| 866 |
"candidates": [{"rank": i+1, "disease": n, "score": f"{s:.3f}"}
|
| 867 |
for i, (n, s) in enumerate(candidates[:8])],
|
| 868 |
}, indent=2)
|
| 869 |
try:
|
| 870 |
+
raw = await _groq(VERIFY_SYSTEM, user_content, max_tokens=350)
|
| 871 |
return json.loads(raw)
|
| 872 |
except Exception:
|
| 873 |
return {"final_condition": candidates[0][0] if candidates else "",
|
| 874 |
+
"reasoning": "", "confidence": "low", "emergency_flag": False}
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
async def llm_summarize(
|
| 878 |
+
symptoms: list,
|
| 879 |
+
results: dict,
|
| 880 |
+
cycle_data: dict,
|
| 881 |
+
user_query: str,
|
| 882 |
+
chat_history: list,
|
| 883 |
+
age: Optional[int] = None,
|
| 884 |
+
emergency_flag: bool = False,
|
| 885 |
+
) -> str:
|
| 886 |
results_text = []
|
| 887 |
if "Disease" in results:
|
| 888 |
top = results["Disease"][0] if results["Disease"] else None
|
|
|
|
| 902 |
disease_primary = "Disease" in results and repro_count < len(symptoms) / 2
|
| 903 |
pcos_raw = results.get("PCOS", {}).get("conf_raw", 0.0)
|
| 904 |
pcos_primary = pcos_raw >= 0.65 and repro_count >= len(symptoms) / 2
|
| 905 |
+
history_str = _format_history_for_prompt(chat_history, MAX_HISTORY_WINDOW)
|
| 906 |
|
| 907 |
user_content = json.dumps({
|
| 908 |
"patient_symptoms": [s.replace("_", " ") for s in symptoms],
|
| 909 |
"original_query": user_query,
|
| 910 |
+
"chat_history_summary": history_str,
|
| 911 |
"diagnostic_results": results_text,
|
| 912 |
"menstrual_symptoms_present": repro_count > 0,
|
| 913 |
"disease_is_primary": disease_primary and not pcos_primary,
|
| 914 |
"pcos_is_primary": pcos_primary,
|
| 915 |
"cycle_data": cycle_data,
|
| 916 |
+
"patient_age": age,
|
| 917 |
+
"emergency_flag": emergency_flag,
|
| 918 |
}, indent=2)
|
| 919 |
try:
|
| 920 |
+
return await _groq(SUMMARY_SYSTEM, user_content, max_tokens=450)
|
| 921 |
+
except Exception:
|
| 922 |
+
return "Aapke symptoms ke baad, please ek doctor se zaroor milein proper evaluation ke liye. π"
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
async def llm_compress_history(chat_history: list) -> str:
|
| 926 |
+
"""Compress early conversation turns into a compact summary for long sessions."""
|
| 927 |
+
history_str = _format_history_for_prompt(chat_history, len(chat_history))
|
| 928 |
+
try:
|
| 929 |
+
return await _groq(CONTEXT_COMPRESS_SYSTEM, history_str, max_tokens=300)
|
| 930 |
except Exception:
|
| 931 |
+
return ""
|
| 932 |
|
| 933 |
|
| 934 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 935 |
+
# 9. DIAGNOSTIC TRACKS
|
| 936 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 937 |
def _score_to_label(score: float, tiers: list) -> str:
|
| 938 |
for threshold, label in sorted(tiers, key=lambda x: x[0], reverse=True):
|
|
|
|
| 956 |
|
| 957 |
|
| 958 |
def run_disease_track(final_symptoms: list, top_k: int = 5) -> list:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
results = []
|
| 960 |
|
| 961 |
if NLP_AVAILABLE:
|
| 962 |
sym_text = "patient has " + ", ".join(s.replace("_", " ") for s in final_symptoms)
|
| 963 |
+
tfidf_res = tfidf_retriever.query(sym_text, top_k=20)
|
| 964 |
+
sbert_res = sbert_retriever.query(sym_text, top_k=20)
|
| 965 |
tfidf_map = dict(zip(tfidf_res["disease"].str.lower(), tfidf_res["score"]))
|
| 966 |
sbert_map = dict(zip(sbert_res["disease"].str.lower(), sbert_res["score"]))
|
| 967 |
max_tfidf = max(tfidf_map.values(), default=1.0)
|
|
|
|
| 996 |
]
|
| 997 |
|
| 998 |
elif disease_model is not None and disease_encoder is not None:
|
|
|
|
| 999 |
KNOWN = set(disease_encoder.classes_) if hasattr(disease_encoder, "classes_") else set()
|
| 1000 |
input_df = pd.DataFrame(0.0, index=[0], columns=list(KNOWN) if KNOWN else final_symptoms)
|
| 1001 |
for s in final_symptoms:
|
| 1002 |
if s in input_df.columns:
|
| 1003 |
input_df.at[0, s] = 1.0
|
| 1004 |
arr = symptom_scaler.transform(input_df) if symptom_scaler else input_df.values
|
| 1005 |
+
probs = disease_model.predict_proba(arr)[0]
|
| 1006 |
+
top_idx = probs.argsort()[::-1][:top_k]
|
| 1007 |
DISEASE_TIERS = [
|
| 1008 |
(0.70, "High likelihood"), (0.50, "Moderate likelihood"),
|
| 1009 |
(0.30, "Possible"), (0.0, "Low likelihood"),
|
|
|
|
| 1023 |
return results
|
| 1024 |
|
| 1025 |
|
| 1026 |
+
def run_pcos_track(final_symptoms: list, age: Optional[int] = None) -> dict:
|
| 1027 |
+
# Guard: only run if at least 1 reproductive/PCOS symptom present
|
| 1028 |
+
pcos_relevant = [s for s in final_symptoms
|
| 1029 |
+
if s in PCOS_INDICATORS or
|
| 1030 |
+
any(k in s for k in ["menstruat", "period", "ovarian", "hirsut", "acne", "hair"])]
|
| 1031 |
+
if not pcos_relevant:
|
| 1032 |
+
return None # caller should check for None and skip
|
| 1033 |
+
|
| 1034 |
score = sum(PCOS_INDICATORS.get(s, 0) for s in final_symptoms)
|
| 1035 |
raw_text = " ".join(final_symptoms).lower()
|
| 1036 |
for kw, w in PCOS_FUZZY.items():
|
|
|
|
| 1040 |
if core_hits >= 3 and score < 8: score = 8
|
| 1041 |
elif core_hits >= 2 and score < 5: score = 5
|
| 1042 |
|
| 1043 |
+
# Age adjustment: PCOS more likely 18-40
|
| 1044 |
+
if age is not None:
|
| 1045 |
+
if age < 18 and score >= 3:
|
| 1046 |
+
score = max(score, 6) # teens with symptoms: bump up slightly
|
| 1047 |
+
elif age > 50:
|
| 1048 |
+
score = max(0, score - 4) # post-menopausal: reduce PCOS likelihood
|
| 1049 |
+
|
| 1050 |
pcos_prob = min(score / 18.0, 0.95)
|
| 1051 |
|
| 1052 |
PCOS_TIERS = [
|
|
|
|
| 1104 |
(0.35, "Possible this cycle"),
|
| 1105 |
(0.0, "Less likely this cycle")]
|
| 1106 |
return {"prediction": f"Conception β {_score_to_label(proba, CONC_TIERS)}", "conf_raw": round(proba, 4)}
|
| 1107 |
+
except Exception as e:
|
| 1108 |
+
logger.warning("run_conception_track error: %s", e)
|
| 1109 |
return {"prediction": "Could not estimate β please consult a doctor", "conf_raw": 0.0}
|
| 1110 |
|
| 1111 |
|
|
|
|
| 1135 |
return {"prediction": fert_label, "confidence": note, "conf_raw": 0.8 if in_window else 0.2}
|
| 1136 |
|
| 1137 |
|
| 1138 |
+
async def run_all_tracks(
|
| 1139 |
+
final_symptoms: list,
|
| 1140 |
+
active: dict,
|
| 1141 |
+
cycle_data: dict,
|
| 1142 |
+
chat_history: list,
|
| 1143 |
+
top_k: int = 5,
|
| 1144 |
+
age: Optional[int] = None,
|
| 1145 |
+
) -> dict:
|
| 1146 |
+
"""
|
| 1147 |
+
Run all diagnostic tracks in PARALLEL using asyncio.gather.
|
| 1148 |
+
Synchronous track functions (pcos, conception, fertility) run in thread pool.
|
| 1149 |
+
"""
|
| 1150 |
+
# Build task map
|
| 1151 |
+
task_keys = []
|
| 1152 |
+
task_coros = []
|
| 1153 |
|
| 1154 |
+
# Disease track (async β includes LLM verify)
|
| 1155 |
+
async def _disease_task():
|
| 1156 |
all_repro = all(any(t in s for t in REPRO_TERMS) for s in final_symptoms)
|
| 1157 |
+
if active.get("track_disease") and final_symptoms and not all_repro:
|
| 1158 |
disease_list = run_disease_track(final_symptoms, top_k)
|
| 1159 |
if disease_list:
|
| 1160 |
+
candidates = [(r["prediction"], r["conf_raw"]) for r in disease_list[:8]]
|
| 1161 |
+
verification = await llm_verify_disease(final_symptoms, candidates, chat_history)
|
| 1162 |
+
verified = verification.get("final_condition", "").strip().lower()
|
| 1163 |
+
emergency = verification.get("emergency_flag", False)
|
| 1164 |
if verified:
|
| 1165 |
disease_list = sorted(
|
| 1166 |
disease_list,
|
| 1167 |
key=lambda r: (r["prediction"].lower() == verified, r["conf_raw"]),
|
| 1168 |
reverse=True,
|
| 1169 |
)
|
| 1170 |
+
return disease_list, emergency
|
| 1171 |
+
return None, False
|
| 1172 |
+
|
| 1173 |
+
# PCOS track (sync β thread)
|
| 1174 |
+
async def _pcos_task():
|
| 1175 |
+
if active.get("track_pcos"):
|
| 1176 |
+
return await asyncio.to_thread(run_pcos_track, final_symptoms, age)
|
| 1177 |
+
return None
|
| 1178 |
+
|
| 1179 |
+
# Conception track (sync β thread)
|
| 1180 |
+
async def _conception_task():
|
| 1181 |
+
if active.get("track_conception"):
|
| 1182 |
+
return await asyncio.to_thread(run_conception_track, cycle_data)
|
| 1183 |
+
return None
|
| 1184 |
+
|
| 1185 |
+
# Fertility track (sync β thread)
|
| 1186 |
+
async def _fertility_task():
|
| 1187 |
+
if active.get("track_fertility_peak"):
|
| 1188 |
+
return await asyncio.to_thread(run_fertility_track, cycle_data)
|
| 1189 |
+
return None
|
| 1190 |
|
| 1191 |
+
# Run all in parallel
|
| 1192 |
+
disease_result, pcos_result, conception_result, fertility_result = await asyncio.gather(
|
| 1193 |
+
_disease_task(),
|
| 1194 |
+
_pcos_task(),
|
| 1195 |
+
_conception_task(),
|
| 1196 |
+
_fertility_task(),
|
| 1197 |
+
)
|
| 1198 |
|
| 1199 |
+
results = {}
|
| 1200 |
+
emergency_flag = False
|
|
|
|
| 1201 |
|
| 1202 |
+
if disease_result[0] is not None:
|
| 1203 |
+
results["Disease"] = disease_result[0]
|
| 1204 |
+
emergency_flag = disease_result[1]
|
| 1205 |
+
if pcos_result is not None:
|
| 1206 |
+
results["PCOS"] = pcos_result
|
| 1207 |
+
if conception_result is not None:
|
| 1208 |
+
results["Conception"] = conception_result
|
| 1209 |
+
if fertility_result is not None:
|
| 1210 |
+
results["Fertility"] = fertility_result
|
| 1211 |
|
| 1212 |
+
results["_emergency_flag"] = emergency_flag
|
| 1213 |
return results
|
| 1214 |
|
| 1215 |
|
| 1216 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1217 |
+
# 10. SECURITY HELPERS
|
| 1218 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1219 |
def get_real_ip(request: Request) -> str:
|
| 1220 |
+
"""
|
| 1221 |
+
Get real client IP. Trusts only the last IP set by our reverse proxy
|
| 1222 |
+
(controlled by TRUSTED_PROXIES env var) to prevent spoofing.
|
| 1223 |
+
"""
|
| 1224 |
fwd = request.headers.get("x-forwarded-for")
|
| 1225 |
+
if fwd:
|
| 1226 |
+
ips = [ip.strip() for ip in fwd.split(",")]
|
| 1227 |
+
# Real client IP is at position -(TRUSTED_PROXIES) from the end
|
| 1228 |
+
idx = max(0, len(ips) - TRUSTED_PROXIES)
|
| 1229 |
+
return ips[idx]
|
| 1230 |
+
return request.client.host
|
| 1231 |
|
| 1232 |
|
| 1233 |
def scan_aup(message: str) -> bool:
|
|
|
|
| 1260 |
raise HTTPException(status_code=403, detail={"status": "violation", "message": "Message blocked."})
|
| 1261 |
|
| 1262 |
|
| 1263 |
+
async def check_conversation_limit(client_ip: str, conversation_id: str) -> bool:
|
| 1264 |
+
"""
|
| 1265 |
+
Returns True if allowed to proceed.
|
| 1266 |
+
Token = 1 per NEW conversation (not per message).
|
| 1267 |
+
Within same conversation_id: unlimited turns up to MAX_TURNS_PER_CONVO.
|
| 1268 |
+
|
| 1269 |
+
Supabase table needed:
|
| 1270 |
+
ai_teaser_usage: ip_address, usage_count, last_reset_date
|
| 1271 |
+
ai_conversations: ip_address, conversation_id, turn_count, created_date
|
| 1272 |
+
"""
|
| 1273 |
+
today_iso = datetime.date.today().isoformat()
|
| 1274 |
+
if not supabase:
|
| 1275 |
+
return True # No Supabase = no limit enforcement
|
| 1276 |
+
|
| 1277 |
+
# Check if this conversation_id already exists for this IP
|
| 1278 |
+
convo_db = supabase.table("ai_conversations").select("*")\
|
| 1279 |
+
.eq("ip_address", client_ip)\
|
| 1280 |
+
.eq("conversation_id", conversation_id)\
|
| 1281 |
+
.execute()
|
| 1282 |
+
|
| 1283 |
+
if convo_db.data:
|
| 1284 |
+
# Existing conversation β just increment turn count, no token cost
|
| 1285 |
+
rec = convo_db.data[0]
|
| 1286 |
+
turn_count = (rec.get("turn_count") or 0) + 1
|
| 1287 |
+
if turn_count > MAX_TURNS_PER_CONVO:
|
| 1288 |
+
return False # Turn limit reached for this conversation
|
| 1289 |
+
supabase.table("ai_conversations").update({
|
| 1290 |
+
"turn_count": turn_count
|
| 1291 |
+
}).eq("ip_address", client_ip).eq("conversation_id", conversation_id).execute()
|
| 1292 |
+
return True
|
| 1293 |
+
|
| 1294 |
+
# New conversation β check daily limit
|
| 1295 |
+
usage_db = supabase.table("ai_teaser_usage").select("*").eq("ip_address", client_ip).execute()
|
| 1296 |
+
if usage_db.data:
|
| 1297 |
+
rec = usage_db.data[0]
|
| 1298 |
+
if rec["last_reset_date"] != today_iso:
|
| 1299 |
+
# New day β reset counter
|
| 1300 |
+
supabase.table("ai_teaser_usage").update({
|
| 1301 |
+
"usage_count": 1, "last_reset_date": today_iso
|
| 1302 |
+
}).eq("ip_address", client_ip).execute()
|
| 1303 |
+
elif rec["usage_count"] >= DAILY_CONVO_LIMIT:
|
| 1304 |
+
return False # Daily conversation limit reached
|
| 1305 |
+
else:
|
| 1306 |
+
supabase.table("ai_teaser_usage").update({
|
| 1307 |
+
"usage_count": rec["usage_count"] + 1
|
| 1308 |
+
}).eq("ip_address", client_ip).execute()
|
| 1309 |
+
else:
|
| 1310 |
+
supabase.table("ai_teaser_usage").insert({
|
| 1311 |
+
"ip_address": client_ip, "usage_count": 1, "last_reset_date": today_iso
|
| 1312 |
+
}).execute()
|
| 1313 |
+
|
| 1314 |
+
# Register the new conversation
|
| 1315 |
+
supabase.table("ai_conversations").insert({
|
| 1316 |
+
"ip_address": client_ip,
|
| 1317 |
+
"conversation_id": conversation_id,
|
| 1318 |
+
"turn_count": 1,
|
| 1319 |
+
"created_date": today_iso,
|
| 1320 |
+
}).execute()
|
| 1321 |
+
return True
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1325 |
+
# 11. REQUEST / RESPONSE SCHEMA
|
| 1326 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1327 |
class ChatRequest(BaseModel):
|
| 1328 |
+
model_config = ConfigDict(populate_by_name=True)
|
| 1329 |
+
|
| 1330 |
message: str
|
| 1331 |
+
conversation_id: Optional[str] = None # NEW: tracks session across turns
|
| 1332 |
+
|
| 1333 |
# Session state β passed back from frontend after every turn
|
| 1334 |
+
accumulated_symptoms: List[str] = Field(default_factory=list)
|
| 1335 |
+
accumulated_negated: List[str] = Field(default_factory=list)
|
| 1336 |
+
asked_questions: List[str] = Field(default_factory=list) # NEW: question texts already asked
|
| 1337 |
cycle_data: Dict[str, Any] = Field(default_factory=dict)
|
| 1338 |
+
pending_questions: List[dict] = Field(default_factory=list)
|
| 1339 |
+
conversation_turn: int = 0
|
| 1340 |
+
chat_history: List[dict] = Field(default_factory=list) # NOW ACTUALLY USED
|
| 1341 |
+
first_message: Optional[str] = None # NEW: preserves original query across turns
|
|
|
|
|
|
|
| 1342 |
|
| 1343 |
+
# User context
|
| 1344 |
+
age: Optional[int] = None
|
| 1345 |
+
sex: Optional[str] = None
|
| 1346 |
|
| 1347 |
|
| 1348 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1349 |
+
# 12. TOKEN ENDPOINT (now returns conversations_left)
|
| 1350 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1351 |
@app.get("/api/tokens")
|
| 1352 |
async def get_tokens(request: Request):
|
| 1353 |
client_ip = get_real_ip(request)
|
| 1354 |
today_iso = datetime.date.today().isoformat()
|
| 1355 |
if not supabase:
|
| 1356 |
+
return {"tokens_left": DAILY_CONVO_LIMIT, "conversations_left": DAILY_CONVO_LIMIT}
|
| 1357 |
db = supabase.table("ai_teaser_usage").select("*").eq("ip_address", client_ip).execute()
|
| 1358 |
if db.data:
|
| 1359 |
rec = db.data[0]
|
| 1360 |
if rec["last_reset_date"] != today_iso:
|
| 1361 |
+
return {"tokens_left": DAILY_CONVO_LIMIT, "conversations_left": DAILY_CONVO_LIMIT}
|
| 1362 |
+
left = max(0, DAILY_CONVO_LIMIT - rec["usage_count"])
|
| 1363 |
+
return {"tokens_left": left, "conversations_left": left}
|
| 1364 |
+
return {"tokens_left": DAILY_CONVO_LIMIT, "conversations_left": DAILY_CONVO_LIMIT}
|
| 1365 |
|
| 1366 |
|
| 1367 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1368 |
+
# 13. MAIN CHAT ENDPOINT
|
| 1369 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1370 |
@app.post("/api/chat")
|
| 1371 |
async def process_chat(query: ChatRequest, request: Request):
|
| 1372 |
+
t0 = time.monotonic()
|
| 1373 |
+
client_ip = get_real_ip(request)
|
| 1374 |
+
|
| 1375 |
+
logger.info(
|
| 1376 |
+
"chat_request ip=%s convo_id=%s turn=%d symptoms=%d history=%d",
|
| 1377 |
+
client_ip, query.conversation_id, query.conversation_turn,
|
| 1378 |
+
len(query.accumulated_symptoms), len(query.chat_history)
|
| 1379 |
+
)
|
| 1380 |
|
| 1381 |
# ββ Guards ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1382 |
+
if len(query.message) > MAX_MESSAGE_LEN:
|
| 1383 |
return {"status": "success", "message_type": "question",
|
| 1384 |
"message": "Thoda chhota rakhein please β sirf main symptoms batayein.",
|
| 1385 |
"session": _session(query)}
|
| 1386 |
|
|
|
|
| 1387 |
await enforce_aup(client_ip, query.message)
|
| 1388 |
|
| 1389 |
+
# ββ Conversation ID management ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1390 |
+
# Generate a new conversation_id if this is a new conversation
|
| 1391 |
+
conversation_id = query.conversation_id
|
| 1392 |
+
if not conversation_id:
|
| 1393 |
+
conversation_id = str(uuid.uuid4())
|
| 1394 |
+
|
| 1395 |
+
# ββ Token/conversation limit check ββββββββββββββββββββββββββββββββββββββββ
|
| 1396 |
+
allowed = await check_conversation_limit(client_ip, conversation_id)
|
| 1397 |
+
if not allowed:
|
| 1398 |
+
# Check if it's a turn limit or a daily limit
|
| 1399 |
+
if query.conversation_turn >= MAX_TURNS_PER_CONVO:
|
| 1400 |
+
return {
|
| 1401 |
+
"status": "limit_reached",
|
| 1402 |
+
"message": (
|
| 1403 |
+
f"Is conversation mein {MAX_TURNS_PER_CONVO} turns complete ho gaye. "
|
| 1404 |
+
"Ek nayi conversation start karein β 'New Chat' button dabayein. π"
|
| 1405 |
+
)
|
| 1406 |
+
}
|
| 1407 |
+
return {
|
| 1408 |
+
"status": "limit_reached",
|
| 1409 |
+
"message": "Aaj ki conversations limit ho gayi. Kal phir try karein! π"
|
| 1410 |
+
}
|
| 1411 |
|
| 1412 |
+
# ββ Crisis intercept ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1413 |
if any(kw in query.message.lower() for kw in CRISIS_KEYWORDS):
|
| 1414 |
return {
|
| 1415 |
"status": "success", "message_type": "crisis",
|
|
|
|
| 1419 |
),
|
| 1420 |
}
|
| 1421 |
|
| 1422 |
+
# ββ Context compression for long sessions βββββββββββββββββββββββββββββββββ
|
| 1423 |
+
chat_history = list(query.chat_history)
|
| 1424 |
+
if query.conversation_turn > COMPRESS_AFTER_TURN and len(chat_history) > COMPRESS_AFTER_TURN:
|
| 1425 |
+
# Compress the older half of the history
|
| 1426 |
+
old_messages = chat_history[:COMPRESS_AFTER_TURN - 5]
|
| 1427 |
+
keep_messages = chat_history[COMPRESS_AFTER_TURN - 5:]
|
| 1428 |
+
if old_messages:
|
| 1429 |
+
compressed = await llm_compress_history(old_messages)
|
| 1430 |
+
if compressed:
|
| 1431 |
+
# Replace old messages with a single compressed summary message
|
| 1432 |
+
chat_history = [
|
| 1433 |
+
{"role": "assistant", "content": f"[Conversation summary so far]\n{compressed}"}
|
| 1434 |
+
] + keep_messages
|
| 1435 |
+
|
| 1436 |
+
# ββ Append current user message to history ββββββββββββββββββββββββββββββββ
|
| 1437 |
+
chat_history.append({"role": "user", "content": query.message})
|
| 1438 |
+
|
| 1439 |
+
# ββ Turn 0: greeting handler ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1440 |
if query.conversation_turn == 0 and not query.accumulated_symptoms:
|
|
|
|
| 1441 |
stripped = query.message.strip()
|
| 1442 |
if len(stripped) < 10 or stripped.lower() in ("hi", "hello", "namaste", "haan", "ok", "hey"):
|
| 1443 |
+
greeting_reply = "Namaste! π Aap kya feel kar rahi hain? Koi bhi symptom batayein β pain, fever, weakness, ya kuch aur."
|
| 1444 |
+
chat_history.append({"role": "assistant", "content": greeting_reply})
|
| 1445 |
return {
|
| 1446 |
"status": "success", "message_type": "question",
|
| 1447 |
+
"message": greeting_reply,
|
| 1448 |
+
"session": _session(
|
| 1449 |
+
query,
|
| 1450 |
+
turn=1,
|
| 1451 |
+
history=chat_history,
|
| 1452 |
+
convo_id=conversation_id,
|
| 1453 |
+
first_msg=stripped,
|
| 1454 |
+
),
|
| 1455 |
}
|
| 1456 |
|
| 1457 |
+
# Track first message for context in later synthesize calls
|
| 1458 |
+
first_message = query.first_message or query.message
|
|
|
|
|
|
|
| 1459 |
|
| 1460 |
+
# ββ Pre-check cycle mention with regex (before parallel Groq calls) βββββββ
|
| 1461 |
+
_cycle_mentioned = bool(re.search(
|
| 1462 |
+
r"\b(\d+\s*(day|din|week|hafte|month|mahina)|last period|period.*ago|ago.*period"
|
| 1463 |
+
r"|pichhl[ei]|last baar|din pehle)\b",
|
| 1464 |
+
query.message, re.I
|
| 1465 |
+
))
|
| 1466 |
+
_cycle_known = _cycle_mentioned or bool(query.cycle_data.get("last_period_days_ago"))
|
| 1467 |
+
|
| 1468 |
+
# ββ Rule-based extraction (fast, no LLM needed) βββββββββββββββββββββββββββ
|
| 1469 |
+
rule_syms = rule_extract_symptoms(query.message)
|
| 1470 |
+
rule_negations = rule_extract_negations(query.message)
|
| 1471 |
+
|
| 1472 |
+
# ββ Parallel Groq calls: extract symptoms + extract cycle data ββββββββββββ
|
| 1473 |
+
extracted, _early_cycle = await asyncio.gather(
|
| 1474 |
+
llm_extract_and_question(
|
| 1475 |
+
user_query=query.message,
|
| 1476 |
+
rule_symptoms=rule_syms,
|
| 1477 |
+
session_symptoms=query.accumulated_symptoms,
|
| 1478 |
+
chat_history=chat_history,
|
| 1479 |
+
asked_questions=query.asked_questions,
|
| 1480 |
+
cycle_already_known=_cycle_known,
|
| 1481 |
+
age=query.age,
|
| 1482 |
+
sex=query.sex,
|
| 1483 |
+
),
|
| 1484 |
+
llm_extract_cycle_data(query.message, chat_history),
|
| 1485 |
)
|
|
|
|
|
|
|
| 1486 |
|
| 1487 |
+
# ββ Collect new symptoms + negations βββββββββββββββββββββββββββββββββββββ
|
| 1488 |
+
llm_extras = [s.lower().replace(" ", "_") for s in extracted.get("additional_symptoms", [])]
|
| 1489 |
+
llm_negations = [s.lower().replace(" ", "_") for s in extracted.get("negated_symptoms", [])]
|
| 1490 |
+
new_symptoms = list(dict.fromkeys(rule_syms + llm_extras))
|
| 1491 |
+
new_negations = list(dict.fromkeys(rule_negations + llm_negations))
|
| 1492 |
+
|
| 1493 |
+
# ββ If answering pending questions ββββββββββββββββββββββββββββββββββββββββ
|
| 1494 |
+
answered: dict = {} # always initialized
|
| 1495 |
if query.pending_questions and query.conversation_turn > 0:
|
|
|
|
| 1496 |
for q in query.pending_questions:
|
| 1497 |
answered[q["id"]] = query.message
|
| 1498 |
answered = expand_yes_all_answers(answered, query.pending_questions)
|
| 1499 |
+
answer_syms = rule_extract_symptoms(query.message)
|
| 1500 |
+
answer_negations = rule_extract_negations(query.message)
|
| 1501 |
+
new_symptoms = list(dict.fromkeys(new_symptoms + answer_syms))
|
| 1502 |
+
new_negations = list(dict.fromkeys(new_negations + answer_negations))
|
| 1503 |
|
| 1504 |
# ββ Merge with session ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1505 |
+
all_negated = list(dict.fromkeys(query.accumulated_negated + new_negations))
|
| 1506 |
all_symptoms = list(dict.fromkeys(
|
| 1507 |
query.accumulated_symptoms + new_symptoms
|
| 1508 |
))
|
| 1509 |
+
# Remove explicitly negated symptoms
|
| 1510 |
+
all_symptoms = [s for s in all_symptoms if s not in all_negated]
|
| 1511 |
|
| 1512 |
# ββ Merge cycle data ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1513 |
cycle_data = dict(query.cycle_data)
|
|
|
|
| 1515 |
if v is not None and not cycle_data.get(k):
|
| 1516 |
cycle_data[k] = v
|
| 1517 |
|
| 1518 |
+
# ββ Track asked questions βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1519 |
+
new_questions_asked = extracted.get("questions", [])
|
| 1520 |
+
asked_questions_list = list(query.asked_questions) + [q.get("text", "") for q in new_questions_asked]
|
| 1521 |
+
|
| 1522 |
if not all_symptoms:
|
| 1523 |
msg = (
|
| 1524 |
"Namaste! π Koi bhi symptom batayein β fever, pain, weakness, ya kuch aur?"
|
| 1525 |
if query.conversation_turn == 0
|
| 1526 |
else "Aur koi symptom hai? Mujhe batayein, main samajhne ki koshish karungi."
|
| 1527 |
)
|
| 1528 |
+
chat_history.append({"role": "assistant", "content": msg})
|
| 1529 |
return {
|
| 1530 |
"status": "success", "message_type": "question",
|
| 1531 |
"message": msg,
|
| 1532 |
+
"session": _session(
|
| 1533 |
+
query,
|
| 1534 |
+
symptoms=all_symptoms,
|
| 1535 |
+
negated=all_negated,
|
| 1536 |
+
cycle=cycle_data,
|
| 1537 |
+
turn=query.conversation_turn + 1,
|
| 1538 |
+
history=chat_history,
|
| 1539 |
+
convo_id=conversation_id,
|
| 1540 |
+
asked=asked_questions_list,
|
| 1541 |
+
first_msg=first_message,
|
| 1542 |
+
),
|
| 1543 |
}
|
| 1544 |
|
| 1545 |
# ββ Decide: ask more or diagnose βββββββββββββββββββββββββββββββββββββββββ
|
| 1546 |
+
enough_symptoms = len(all_symptoms) >= 4
|
| 1547 |
+
answered_questions = query.conversation_turn >= 2
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1548 |
|
| 1549 |
should_diagnose = enough_symptoms or answered_questions
|
| 1550 |
|
| 1551 |
if not should_diagnose:
|
| 1552 |
+
questions = new_questions_asked
|
| 1553 |
if questions:
|
|
|
|
| 1554 |
if _cycle_known:
|
| 1555 |
questions = [q for q in questions if not any(
|
| 1556 |
kw in q.get("text", "").lower()
|
|
|
|
| 1558 |
)]
|
| 1559 |
if questions:
|
| 1560 |
q_text = "\n".join(f"{q['text']}" for q in questions)
|
| 1561 |
+
chat_history.append({"role": "assistant", "content": q_text})
|
| 1562 |
return {
|
| 1563 |
"status": "success", "message_type": "question",
|
| 1564 |
"message": q_text,
|
| 1565 |
"session": _session(
|
| 1566 |
query,
|
| 1567 |
symptoms=all_symptoms,
|
| 1568 |
+
negated=all_negated,
|
| 1569 |
cycle=cycle_data,
|
| 1570 |
pending=questions,
|
| 1571 |
turn=query.conversation_turn + 1,
|
| 1572 |
+
history=chat_history,
|
| 1573 |
+
convo_id=conversation_id,
|
| 1574 |
+
asked=asked_questions_list,
|
| 1575 |
+
first_msg=first_message,
|
| 1576 |
),
|
| 1577 |
}
|
| 1578 |
|
| 1579 |
# ββ Synthesize final symptoms + routing βββββββββββββββββββββββββββββββββββ
|
| 1580 |
+
context = await llm_synthesize_context(
|
| 1581 |
+
original_query=first_message,
|
| 1582 |
+
current_message=query.message,
|
| 1583 |
+
all_symptoms=all_symptoms,
|
| 1584 |
+
answered=answered,
|
| 1585 |
+
chat_history=chat_history,
|
| 1586 |
+
cycle_data=cycle_data,
|
| 1587 |
+
session_negated=all_negated,
|
| 1588 |
+
age=query.age,
|
| 1589 |
+
)
|
| 1590 |
final_symptoms = list(dict.fromkeys(
|
| 1591 |
s.lower().replace(" ", "_") for s in context.get("final_symptoms", all_symptoms)
|
| 1592 |
)) or list(dict.fromkeys(s.lower().replace(" ", "_") for s in all_symptoms))
|
| 1593 |
|
| 1594 |
+
# Merge remaining cycle data
|
| 1595 |
for k, v in (context.get("cycle_data") or {}).items():
|
| 1596 |
if v is not None and not cycle_data.get(k):
|
| 1597 |
cycle_data[k] = v
|
| 1598 |
|
| 1599 |
# ββ Active tracks βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1600 |
_fi = (
|
| 1601 |
+
any(k in (first_message + " " + query.message).lower() for k in
|
| 1602 |
["pregnant", "conceive", "fertility", "fertile", "ovulat", "trying for",
|
| 1603 |
"bachha", "garbh", "not getting pregnant", "cant get pregnant"])
|
| 1604 |
or "infertility" in final_symptoms
|
| 1605 |
+
or cycle_data.get("trying_to_conceive")
|
| 1606 |
)
|
| 1607 |
+
_cr = any(k in " ".join(final_symptoms) for k in
|
| 1608 |
+
["menstruat", "period", "irregular", "unpredictable",
|
| 1609 |
+
"pcos", "pcod", "heavy_menstrual", "infertil", "hirsut",
|
| 1610 |
+
"acne_or_pimples", "weight_gain", "hair_thinning"])
|
| 1611 |
_purely_repro = (
|
| 1612 |
all(any(t in s for t in REPRO_TERMS) for s in final_symptoms)
|
| 1613 |
if final_symptoms else False
|
|
|
|
| 1622 |
"track_fertility_peak": llm_tracks.get("track_fertility_peak", _fi),
|
| 1623 |
}
|
| 1624 |
|
| 1625 |
+
# Fill missing cycle data from answers
|
| 1626 |
+
if active["track_conception"] or active["track_fertility_peak"]:
|
| 1627 |
if not cycle_data.get("last_period_days_ago"):
|
| 1628 |
+
answer_text = " ".join(str(v) for v in answered.values()
|
| 1629 |
+
if str(v) not in ("I don't know", ""))
|
| 1630 |
if answer_text.strip():
|
| 1631 |
+
extra = await llm_extract_cycle_data(answer_text, chat_history)
|
| 1632 |
for k, v in extra.items():
|
| 1633 |
if v is not None and not cycle_data.get(k):
|
| 1634 |
cycle_data[k] = v
|
| 1635 |
|
| 1636 |
+
# ββ Run all tracks in PARALLEL ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1637 |
+
results = await run_all_tracks(
|
| 1638 |
+
final_symptoms, active, cycle_data, chat_history, age=query.age
|
| 1639 |
+
)
|
| 1640 |
+
emergency_flag = results.pop("_emergency_flag", False)
|
| 1641 |
|
| 1642 |
# ββ Groq summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1643 |
+
summary = await llm_summarize(
|
| 1644 |
+
symptoms=final_symptoms,
|
| 1645 |
+
results=results,
|
| 1646 |
+
cycle_data=cycle_data,
|
| 1647 |
+
user_query=first_message,
|
| 1648 |
+
chat_history=chat_history,
|
| 1649 |
+
age=query.age,
|
| 1650 |
+
emergency_flag=emergency_flag,
|
| 1651 |
+
)
|
| 1652 |
+
|
| 1653 |
+
chat_history.append({"role": "assistant", "content": summary})
|
| 1654 |
|
| 1655 |
# ββ Build structured response βββββββββββββββββββββββββββββββββββββββββββββ
|
| 1656 |
structured = {
|
| 1657 |
+
"summary": summary,
|
| 1658 |
"symptoms_detected": [s.replace("_", " ") for s in final_symptoms],
|
| 1659 |
+
"symptoms_negated": [s.replace("_", " ") for s in all_negated],
|
| 1660 |
+
"emergency_flag": emergency_flag,
|
| 1661 |
"tracks": {},
|
| 1662 |
}
|
| 1663 |
|
| 1664 |
if "Disease" in results and results["Disease"]:
|
| 1665 |
structured["tracks"]["disease"] = results["Disease"]
|
| 1666 |
+
if "PCOS" in results and results["PCOS"]:
|
| 1667 |
structured["tracks"]["pcos"] = results["PCOS"]
|
| 1668 |
if "Conception" in results:
|
| 1669 |
structured["tracks"]["conception"] = results["Conception"]
|
| 1670 |
if "Fertility" in results:
|
| 1671 |
structured["tracks"]["fertility"] = results["Fertility"]
|
| 1672 |
|
| 1673 |
+
latency_ms = int((time.monotonic() - t0) * 1000)
|
| 1674 |
+
logger.info(
|
| 1675 |
+
"chat_response ip=%s type=structured symptoms=%d latency_ms=%d emergency=%s",
|
| 1676 |
+
client_ip, len(final_symptoms), latency_ms, emergency_flag
|
| 1677 |
+
)
|
| 1678 |
+
|
| 1679 |
return {
|
| 1680 |
"status": "success",
|
| 1681 |
"message_type": "structured",
|
| 1682 |
"message": summary,
|
| 1683 |
"structured": structured,
|
| 1684 |
+
# Reset symptom state after diagnosis but keep history for reference
|
| 1685 |
+
"session": _session(
|
| 1686 |
+
query,
|
| 1687 |
+
symptoms=[],
|
| 1688 |
+
negated=[],
|
| 1689 |
+
cycle={},
|
| 1690 |
+
pending=[],
|
| 1691 |
+
turn=query.conversation_turn + 1, # do NOT reset turn β conversation continues
|
| 1692 |
+
history=chat_history, # keep history!
|
| 1693 |
+
convo_id=conversation_id,
|
| 1694 |
+
asked=asked_questions_list,
|
| 1695 |
+
first_msg=None, # reset first_msg so next topic starts fresh
|
| 1696 |
+
),
|
| 1697 |
}
|
| 1698 |
|
| 1699 |
|
| 1700 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1701 |
+
# 14. SESSION HELPER
|
| 1702 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1703 |
def _session(
|
| 1704 |
query: ChatRequest,
|
| 1705 |
+
symptoms: list = None,
|
| 1706 |
+
negated: list = None,
|
| 1707 |
+
cycle: dict = None,
|
| 1708 |
+
pending: list = None,
|
| 1709 |
+
turn: int = None,
|
| 1710 |
+
history: list = None,
|
| 1711 |
+
convo_id: str = None,
|
| 1712 |
+
asked: list = None,
|
| 1713 |
+
first_msg: str = None,
|
| 1714 |
) -> dict:
|
| 1715 |
return {
|
| 1716 |
+
"conversation_id": convo_id if convo_id is not None else query.conversation_id,
|
| 1717 |
+
"accumulated_symptoms": symptoms if symptoms is not None else query.accumulated_symptoms,
|
| 1718 |
+
"accumulated_negated": negated if negated is not None else query.accumulated_negated,
|
| 1719 |
+
"asked_questions": asked if asked is not None else query.asked_questions,
|
| 1720 |
+
"cycle_data": cycle if cycle is not None else query.cycle_data,
|
| 1721 |
+
"pending_questions": pending if pending is not None else query.pending_questions,
|
| 1722 |
+
"conversation_turn": turn if turn is not None else query.conversation_turn,
|
| 1723 |
+
"chat_history": history if history is not None else query.chat_history,
|
| 1724 |
+
"first_message": first_msg if first_msg is not None else query.first_message,
|
| 1725 |
+
"age": query.age,
|
| 1726 |
+
"sex": query.sex,
|
| 1727 |
+
}
|