Initial commit - Diabetic Dost

This commit is contained in:
Sanika Gurav
2026-10-13 11:10:56 +05:30
commit 94d8257a6a
121 changed files with 21596 additions and 0 deletions
@@ -0,0 +1,3 @@
from .session_store import SehatSessionState, SessionStore, GLOBAL_SESSION_STORE
__all__ = ["SehatSessionState", "SessionStore", "GLOBAL_SESSION_STORE"]
@@ -0,0 +1,186 @@
import os
import re
import json
import logging
import threading
from typing import Dict, Any, List, Optional
from datetime import datetime, timezone
logger = logging.getLogger("sehat_patient_registry")
class PatientRegistry:
"""
Patient Longitudinal Health Record (EHR) Registry for Diabetes Dost AI.
Saves patient baseline demographics, diabetes history, past visit summaries,
blood sugar trends, and past medications across regular follow-up visits.
"""
def __init__(self, registry_dir: str = "outputs/reports/patients"):
self.registry_dir = registry_dir
self.lock = threading.RLock()
os.makedirs(self.registry_dir, exist_ok=True)
self._index = self._build_index()
def _normalize_name(self, name: str) -> str:
if not name:
return ""
clean = re.sub(r"[^\w\u0900-\u097F]", "", name.lower().strip())
return clean
def _sanitize_filename(self, name: str) -> str:
clean = re.sub(r"[^\w\-_]", "_", name.strip())
return clean or "patient"
def _build_index(self) -> Dict[str, str]:
index = {}
if not os.path.exists(self.registry_dir):
return index
for fname in os.listdir(self.registry_dir):
if fname.endswith(".json"):
fpath = os.path.join(self.registry_dir, fname)
try:
with open(fpath, "r", encoding="utf-8") as f:
data = json.load(f)
p_name = data.get("name", "")
norm_name = self._normalize_name(p_name)
p_id = data.get("patient_id", "")
if norm_name:
index[norm_name] = fpath
if p_id:
index[p_id.lower()] = fpath
except Exception as e:
logger.warning(f"Failed to read patient file {fname}: {e}")
return index
def find_patient(self, name_or_id: str) -> Optional[Dict[str, Any]]:
"""Look up a patient record by full name or patient ID."""
if not name_or_id:
return None
with self.lock:
key = self._normalize_name(name_or_id)
if not key:
return None
if key in self._index:
try:
with open(self._index[key], "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
# Only do multi-word match if the query itself has full name (e.g. 2+ words / >= 8 chars)
# Never loosely match a single first name like "गोविंद" against "गोविंद जोशी"
query_tokens = name_or_id.strip().split()
if len(query_tokens) >= 2 and len(key) >= 8:
for idx_key, fpath in self._index.items():
if key == idx_key:
try:
with open(fpath, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return None
def save_patient_visit(self, session_state) -> Dict[str, Any]:
"""Update or create a patient's longitudinal record after a completed session."""
d = session_state.demographics or {}
p_name = d.get("name", "").strip()
if not p_name:
return {}
with self.lock:
existing = self.find_patient(p_name)
p_id = existing.get("patient_id") if existing else f"DMH_PAT_{re.sub(r'[^a-zA-Z0-9]', '', p_name)[:6].upper()}_{int(datetime.now().timestamp()) % 10000:04d}"
now_iso = datetime.now(timezone.utc).isoformat()
# Past visits log
past_visits = existing.get("past_visits", []) if existing else []
# Extract recent sugar from this visit
sugars = session_state.blood_sugar_readings or []
current_sugar = sugars[-1]["value"] if sugars else None
visit_entry = {
"session_id": session_state.session_id,
"visit_date": now_iso,
"branch": session_state.branch,
"diabetes_type": getattr(session_state, "diabetes_type", None),
"blood_sugar_reading": current_sugar,
"symptoms_reported": session_state.symptoms_reported,
"medications": session_state.medications,
"recommended_urgency": session_state.recommended_urgency,
"summary_narrative": getattr(session_state, "generated_summary", {}).get("summary_narrative") if getattr(session_state, "generated_summary", None) else None
}
# Avoid duplicate visit entries for same session
if not any(v.get("session_id") == session_state.session_id for v in past_visits):
past_visits.append(visit_entry)
# Build aggregated patient profile
patient_record = {
"patient_id": p_id,
"name": p_name,
"age": d.get("age") or (existing.get("age") if existing else None),
"gender": d.get("gender") or (existing.get("gender") if existing else None),
"branch": session_state.branch if session_state.branch != "follow_up" else (existing.get("branch") if existing else "known_diabetic"),
"diabetes_type": getattr(session_state, "diabetes_type", None) or (existing.get("diabetes_type") if existing else None),
"baseline_diabetes_duration": session_state.diabetes_history or (existing.get("baseline_diabetes_duration") if existing else None),
"family_history": session_state.family_history if session_state.family_history is not None else (existing.get("family_history") if existing else None),
"active_medications": session_state.medications if session_state.medications else (existing.get("active_medications", []) if existing else []),
"last_blood_sugar": current_sugar if current_sugar is not None else (existing.get("last_blood_sugar") if existing else None),
"total_visits_count": len(past_visits),
"first_visit_date": existing.get("first_visit_date", now_iso) if existing else now_iso,
"last_visit_date": now_iso,
"past_visits": past_visits
}
# Persist to disk
safe_name = self._sanitize_filename(p_name)
filename = f"Patient_{safe_name}_{p_id}.json"
filepath = os.path.join(self.registry_dir, filename)
try:
with open(filepath, "w", encoding="utf-8") as f:
json.dump(patient_record, f, ensure_ascii=False, indent=2)
norm_name = self._normalize_name(p_name)
self._index[norm_name] = filepath
self._index[p_id.lower()] = filepath
logger.info(f"Saved patient record for '{p_name}' (ID: {p_id}) to {filepath}")
except Exception as e:
logger.error(f"Failed to persist patient record for '{p_name}': {e}")
return patient_record
def list_all_patients(self) -> List[Dict[str, Any]]:
"""List all registered patients with summary stats for UI selection."""
patients = []
seen_ids = set()
with self.lock:
for fpath in set(self._index.values()):
if os.path.exists(fpath):
try:
with open(fpath, "r", encoding="utf-8") as f:
p = json.load(f)
pid = p.get("patient_id")
if pid and pid not in seen_ids:
seen_ids.add(pid)
patients.append({
"patient_id": pid,
"name": p.get("name", "Unknown"),
"age": p.get("age"),
"gender": p.get("gender"),
"branch": p.get("branch"),
"diabetes_type": p.get("diabetes_type"),
"last_blood_sugar": p.get("last_blood_sugar"),
"total_visits_count": p.get("total_visits_count", 1),
"last_visit_date": p.get("last_visit_date")
})
except Exception:
pass
# Sort by last visit descending
patients.sort(key=lambda x: str(x.get("last_visit_date", "")), reverse=True)
return patients
# Global instance
GLOBAL_PATIENT_REGISTRY = PatientRegistry()
@@ -0,0 +1,160 @@
import os
import json
import time
import threading
import logging
from typing import Dict, Any, List, Optional
from datetime import datetime, timezone
logger = logging.getLogger("sehat_session_store")
class SehatSessionState:
"""Dataclass-like state container for a single Sehat AI session."""
def __init__(self, session_id: str):
self.session_id = session_id
self.created_at = datetime.now(timezone.utc).isoformat()
self.updated_at = self.created_at
# Demographics & Consent
self.demographics = {"name": "", "age": None, "gender": ""}
self.consent = False
self.consent_timestamp: Optional[str] = None
self.audio_recording_consent = False
self.consent_rejected = False
# Conversation State
self.questions_asked_count = 0
self.max_budget = 12
self.branch: str = "common" # common, known_diabetic, unsure, not_diabetic
self.current_question_id: str = "COM_CONSENT"
self.asked_question_ids: List[str] = []
self.completed_topics: List[str] = []
self.answers: List[Dict[str, Any]] = []
self.question_retry_count: Dict[str, int] = {}
self.demographic_retry_count: int = 0
self.status_retry_count: int = 0
# Clinical Findings & Context Memory
self.risk_signals: List[str] = []
self.symptoms_reported: List[str] = []
self.symptoms_denied: List[str] = []
self.diabetes_history: Dict[str, Any] = {}
self.medications: List[str] = []
self.blood_sugar_readings: List[Dict[str, Any]] = []
self.lifestyle_factors: List[str] = []
self.family_history: Optional[bool] = None
self.pregnancy_history: Optional[bool] = None
self.gestational_history: Optional[bool] = None
self.diabetes_type: Optional[str] = None
self.sugar_category: Optional[str] = None
self.medication_category: Optional[str] = None
self.context_memory: Dict[str, Any] = {}
self.volunteered_slots: List[str] = []
# Emergency & Urgency
self.emergency_escalation: bool = False
self.emergency_details: Optional[Dict[str, Any]] = None
self.recommended_urgency: str = "routine"
self.urgency_reasons: List[str] = []
# Completion & Summary
self.is_completed: bool = False
self.generated_summary: Optional[Dict[str, Any]] = None
self.audio_ref: Optional[str] = None
def record_answer(self, question_id: str, question_hi: str, patient_answer_hi: str, confidence: float = 0.95):
# If the last recorded answer was for the same question, update it with the latest corrected answer
if self.answers and self.answers[-1]["question_id"] == question_id:
self.answers[-1]["patient_answer_hi"] = patient_answer_hi
self.answers[-1]["question_asked_hi"] = question_hi
self.answers[-1]["timestamp"] = datetime.now(timezone.utc).isoformat()
self.answers[-1]["confidence"] = confidence
else:
self.answers.append({
"question_id": question_id,
"question_asked_hi": question_hi,
"patient_answer_hi": patient_answer_hi,
"timestamp": datetime.now(timezone.utc).isoformat(),
"confidence": confidence
})
if question_id not in self.asked_question_ids:
self.asked_question_ids.append(question_id)
self.updated_at = datetime.now(timezone.utc).isoformat()
def to_dict(self) -> Dict[str, Any]:
return {
"session_id": self.session_id,
"created_at": self.created_at,
"updated_at": self.updated_at,
"patient": self.demographics,
"consent": self.consent,
"consent_timestamp": self.consent_timestamp,
"audio_recording_consent": self.audio_recording_consent,
"consent_rejected": self.consent_rejected,
"questions_asked_count": self.questions_asked_count,
"max_budget": self.max_budget,
"branch": self.branch,
"current_question_id": self.current_question_id,
"asked_question_ids": self.asked_question_ids,
"completed_topics": self.completed_topics,
"answers": self.answers,
"risk_signals": self.risk_signals,
"symptoms_reported": self.symptoms_reported,
"symptoms_denied": self.symptoms_denied,
"diabetes_type": self.diabetes_type,
"diabetes_history": self.diabetes_history,
"medications": self.medications,
"blood_sugar_readings": self.blood_sugar_readings,
"lifestyle_factors": self.lifestyle_factors,
"family_history": self.family_history,
"pregnancy_history": self.pregnancy_history,
"gestational_history": self.gestational_history,
"sugar_category": self.sugar_category,
"medication_category": self.medication_category,
"context_memory": self.context_memory,
"volunteered_slots": self.volunteered_slots,
"emergency_escalation": self.emergency_escalation,
"emergency_details": self.emergency_details,
"recommended_urgency": self.recommended_urgency,
"urgency_reasons": self.urgency_reasons,
"is_completed": self.is_completed,
"generated_summary": self.generated_summary,
"audio_ref": self.audio_ref
}
class SessionStore:
"""Thread-safe storage manager for all Sehat AI sessions."""
def __init__(self, storage_dir: str = "outputs/reports/sessions"):
self.storage_dir = storage_dir
self.sessions: Dict[str, SehatSessionState] = {}
self.lock = threading.Lock()
os.makedirs(self.storage_dir, exist_ok=True)
def get_or_create(self, session_id: str) -> SehatSessionState:
with self.lock:
if session_id not in self.sessions:
self.sessions[session_id] = SehatSessionState(session_id)
return self.sessions[session_id]
def get(self, session_id: str) -> Optional[SehatSessionState]:
with self.lock:
return self.sessions.get(session_id)
def save(self, session: SehatSessionState):
with self.lock:
self.sessions[session.session_id] = session
try:
filepath = os.path.join(self.storage_dir, f"{session.session_id}.json")
with open(filepath, "w", encoding="utf-8") as f:
json.dump(session.to_dict(), f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Failed to persist session {session.session_id}: {e}")
def list_all_sessions(self) -> List[Dict[str, Any]]:
with self.lock:
return [s.to_dict() for s in self.sessions.values()]
# Global instance
GLOBAL_SESSION_STORE = SessionStore()