aagahilabs Claude Sonnet 4.6 commited on
Commit
8a2f199
·
1 Parent(s): 5e2f8a3

feat: complete RAG integration with medical knowledge base

Browse files

- Add data/medical_knowledge.json: 40 curated clinical documents covering
emergency conditions (MI, stroke, sepsis, anaphylaxis), Pakistani endemic
diseases (dengue, malaria, typhoid, TB, cholera), and common presentations
- Add sentence-transformers to requirements.txt for embedding model
- Add _setup_rag() + retrieve_knowledge() using all-MiniLM-L6-v2 and numpy
cosine similarity (no ChromaDB — avoids HF Spaces dependency issues)
- Update generate_soap_report() to accept retrieved_context parameter and
inject RAG passages into the PLAN/ASSESSMENT section of the prompt
- Update run_pipeline() to build combined query (English text + symptom names),
call retrieve_knowledge(n=3), and pass results to SOAP generator
- RAG runs after dataset lookup; falls back gracefully if model unavailable

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. app.py +103 -4
  2. data/medical_knowledge.json +282 -0
  3. requirements.txt +1 -0
app.py CHANGED
@@ -11,6 +11,8 @@ import soundfile as sf
11
  from groq import Groq
12
  import gradio as gr
13
  import pandas as pd
 
 
14
 
15
  # =========================================
16
  # SETUP
@@ -114,6 +116,81 @@ def lookup_diseases(symptoms_list: list, top_n: int = 5) -> list[dict]:
114
  return results.to_dict(orient="records")
115
 
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  # =========================================
118
  # STEP 1: LANGUAGE DETECTION (no API call)
119
  #
@@ -489,10 +566,12 @@ def build_emergency_banner(score, analysis):
489
  # =========================================
490
  # STEP 7: SOAP REPORT GENERATOR (LLM)
491
  # =========================================
492
- def generate_soap_report(analysis, english_text, risk_score):
493
  """
494
  Generates a structured SOAP format clinical report using the LLM.
495
  Uses already-extracted JSON — no re-processing of the original text.
 
 
496
  """
497
  if not analysis or "error" in analysis:
498
  return "⚠️ Cannot generate report — symptom extraction failed."
@@ -503,6 +582,14 @@ def generate_soap_report(analysis, english_text, risk_score):
503
  ])
504
  conditions = ", ".join(analysis.get("possible_conditions", [])) or "None identified"
505
 
 
 
 
 
 
 
 
 
506
  prompt = f"""You are a clinical documentation assistant.
507
 
508
  Generate a concise SOAP format medical report based on the data below.
@@ -516,7 +603,7 @@ Possible Conditions: {conditions}
516
  Urgency : {analysis.get('urgency', 'N/A')}
517
  Risk Score : {risk_score}/100
518
  Original Statement: {english_text}
519
-
520
  FORMAT TO USE:
521
  SUBJECTIVE:
522
  [what the patient reports]
@@ -528,7 +615,7 @@ ASSESSMENT:
528
  [clinical interpretation, possible diagnoses]
529
 
530
  PLAN:
531
- [recommended next steps for the treating doctor]
532
 
533
  NOTE: This report is AI-generated and must be reviewed by a qualified health professional before any clinical decision is made."""
534
 
@@ -592,8 +679,20 @@ def run_pipeline(text, lang):
592
  else:
593
  analysis["dataset_match_detail"] = ["Dataset lookup returned no matches"]
594
 
 
 
 
 
 
 
 
 
 
 
 
 
595
  banner = build_emergency_banner(risk_score, analysis)
596
- soap_report = generate_soap_report(analysis, english_text, risk_score)
597
 
598
  return (
599
  english_text,
 
11
  from groq import Groq
12
  import gradio as gr
13
  import pandas as pd
14
+ import numpy as np
15
+ from sentence_transformers import SentenceTransformer
16
 
17
  # =========================================
18
  # SETUP
 
116
  return results.to_dict(orient="records")
117
 
118
 
119
+ # =========================================
120
+ # RAG — MEDICAL KNOWLEDGE BASE
121
+ #
122
+ # Uses sentence-transformers (all-MiniLM-L6-v2, 80MB) for embeddings
123
+ # and numpy cosine similarity for retrieval — no ChromaDB dependency.
124
+ #
125
+ # Loaded once at startup:
126
+ # 1. Load 40 clinical documents from data/medical_knowledge.json
127
+ # 2. Embed all documents into 384-dimension vectors
128
+ # 3. At query time: embed symptoms text, find top-N nearest docs
129
+ # 4. Retrieved text is passed as context into the SOAP report LLM call
130
+ # =========================================
131
+ _rag_model = None
132
+ _rag_embeddings = None # shape: (n_docs, 384)
133
+ _rag_docs = [] # list of dicts with title + text
134
+
135
+ def _setup_rag():
136
+ """Load embedding model and pre-compute document embeddings at startup."""
137
+ global _rag_model, _rag_embeddings, _rag_docs
138
+
139
+ knowledge_path = os.path.join(os.path.dirname(__file__), "data", "medical_knowledge.json")
140
+
141
+ try:
142
+ with open(knowledge_path, "r", encoding="utf-8") as f:
143
+ _rag_docs = json.load(f)
144
+
145
+ print(f"Loading embedding model (all-MiniLM-L6-v2)...")
146
+ _rag_model = SentenceTransformer("all-MiniLM-L6-v2")
147
+
148
+ texts = [f"{d['title']}. {d['text']}" for d in _rag_docs]
149
+ _rag_embeddings = _rag_model.encode(
150
+ texts,
151
+ normalize_embeddings=True, # enables fast dot-product cosine similarity
152
+ show_progress_bar=False
153
+ )
154
+
155
+ print(f"✓ RAG ready: {len(_rag_docs)} documents embedded")
156
+
157
+ except Exception as e:
158
+ print(f"⚠️ RAG setup failed: {e} — SOAP reports will run without retrieved context")
159
+
160
+
161
+ def retrieve_knowledge(query: str, n: int = 3) -> list[dict]:
162
+ """
163
+ Embed the query and return the top-N most relevant knowledge documents.
164
+ Returns list of dicts with 'title' and 'text' keys.
165
+ Falls back to empty list if RAG is not available.
166
+ """
167
+ if _rag_model is None or _rag_embeddings is None or not _rag_docs:
168
+ return []
169
+
170
+ query_emb = _rag_model.encode(
171
+ [query],
172
+ normalize_embeddings=True,
173
+ show_progress_bar=False
174
+ ) # shape: (1, 384)
175
+
176
+ scores = np.dot(_rag_embeddings, query_emb.T).flatten() # cosine similarity
177
+ top_idx = scores.argsort()[-n:][::-1] # highest first
178
+
179
+ return [
180
+ {
181
+ "title": _rag_docs[i]["title"],
182
+ "text": _rag_docs[i]["text"],
183
+ "score": float(scores[i])
184
+ }
185
+ for i in top_idx
186
+ if scores[i] > 0.2 # minimum relevance threshold
187
+ ]
188
+
189
+
190
+ # Run RAG setup at startup
191
+ _setup_rag()
192
+
193
+
194
  # =========================================
195
  # STEP 1: LANGUAGE DETECTION (no API call)
196
  #
 
566
  # =========================================
567
  # STEP 7: SOAP REPORT GENERATOR (LLM)
568
  # =========================================
569
+ def generate_soap_report(analysis, english_text, risk_score, retrieved_context=""):
570
  """
571
  Generates a structured SOAP format clinical report using the LLM.
572
  Uses already-extracted JSON — no re-processing of the original text.
573
+ retrieved_context: optional RAG passages injected into the prompt to
574
+ ground the PLAN section in evidence-based clinical knowledge.
575
  """
576
  if not analysis or "error" in analysis:
577
  return "⚠️ Cannot generate report — symptom extraction failed."
 
582
  ])
583
  conditions = ", ".join(analysis.get("possible_conditions", [])) or "None identified"
584
 
585
+ # Inject RAG context only when available
586
+ context_section = ""
587
+ if retrieved_context:
588
+ context_section = f"""
589
+ RETRIEVED MEDICAL KNOWLEDGE (use to inform the ASSESSMENT and PLAN):
590
+ {retrieved_context}
591
+ """
592
+
593
  prompt = f"""You are a clinical documentation assistant.
594
 
595
  Generate a concise SOAP format medical report based on the data below.
 
603
  Urgency : {analysis.get('urgency', 'N/A')}
604
  Risk Score : {risk_score}/100
605
  Original Statement: {english_text}
606
+ {context_section}
607
  FORMAT TO USE:
608
  SUBJECTIVE:
609
  [what the patient reports]
 
615
  [clinical interpretation, possible diagnoses]
616
 
617
  PLAN:
618
+ [recommended next steps for the treating doctor, informed by retrieved knowledge where relevant]
619
 
620
  NOTE: This report is AI-generated and must be reviewed by a qualified health professional before any clinical decision is made."""
621
 
 
679
  else:
680
  analysis["dataset_match_detail"] = ["Dataset lookup returned no matches"]
681
 
682
+ # Step 5: RAG — retrieve relevant clinical knowledge passages
683
+ # Query = English text + all extracted symptom names joined together
684
+ # This gives the embedder the richest signal to find matching docs
685
+ rag_query = english_text + " " + " ".join(
686
+ s.get("name", "") for s in symptoms_list
687
+ )
688
+ retrieved = retrieve_knowledge(rag_query, n=3)
689
+ retrieved_context = "\n\n".join(
690
+ f"[{r['title']}]\n{r['text']}"
691
+ for r in retrieved
692
+ ) if retrieved else ""
693
+
694
  banner = build_emergency_banner(risk_score, analysis)
695
+ soap_report = generate_soap_report(analysis, english_text, risk_score, retrieved_context)
696
 
697
  return (
698
  english_text,
data/medical_knowledge.json ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "doc_001",
4
+ "title": "Myocardial Infarction (Heart Attack)",
5
+ "text": "Myocardial infarction occurs when blood flow to part of the heart is blocked, causing tissue death. Classic presentation includes crushing central chest pain radiating to the left arm, jaw, or shoulder, accompanied by sweating, nausea, and shortness of breath. Atypical presentations occur in women, diabetics, and elderly patients, who may present with fatigue, jaw pain, or epigastric discomfort only. Immediate management: call emergency services, administer aspirin 300mg if not contraindicated, and arrange urgent transfer to a cardiac centre for reperfusion therapy.",
6
+ "urgency": "RED",
7
+ "category": "cardiovascular"
8
+ },
9
+ {
10
+ "id": "doc_002",
11
+ "title": "Stroke (Cerebrovascular Accident)",
12
+ "text": "Stroke results from sudden interruption of cerebral blood supply, either ischaemic (80%) or haemorrhagic (20%). Use the FAST tool: Face drooping, Arm weakness, Speech difficulty, Time to call emergency services. Additional features include sudden severe headache, vision disturbance, and loss of balance. Time is brain — every minute of delay destroys approximately 1.9 million neurons. Do not give aspirin until haemorrhagic stroke is excluded by CT scan. Transfer to a stroke unit within 4.5 hours for thrombolysis eligibility.",
13
+ "urgency": "RED",
14
+ "category": "neurological"
15
+ },
16
+ {
17
+ "id": "doc_003",
18
+ "title": "Dengue Fever",
19
+ "text": "Dengue fever is a mosquito-borne flavivirus infection endemic in Pakistan, particularly during and after monsoon season. Classic presentation: sudden high fever (39–40°C), severe headache, retro-orbital pain, myalgia, arthralgia, and a maculopapular rash appearing 3–5 days after fever onset. Warning signs of severe dengue include abdominal pain, persistent vomiting, bleeding gums, rapid breathing, and restlessness — these require immediate hospitalisation. Monitor platelet count and haematocrit daily. Management is supportive: oral rehydration, paracetamol for fever (avoid NSAIDs and aspirin due to bleeding risk).",
20
+ "urgency": "high",
21
+ "category": "infectious"
22
+ },
23
+ {
24
+ "id": "doc_004",
25
+ "title": "Malaria",
26
+ "text": "Malaria in Pakistan is caused predominantly by Plasmodium vivax (80%) and Plasmodium falciparum (20%). Cyclical fever with chills, rigors, and sweating occurring every 48–72 hours is classic but often absent in early stages. Falciparum malaria is life-threatening and can cause cerebral malaria (confusion, seizures), severe anaemia, and organ failure. Rapid diagnostic test (RDT) or blood film is required for diagnosis. Uncomplicated vivax: chloroquine followed by primaquine (check G6PD status first). Falciparum: artemisinin-based combination therapy. Severe malaria: IV artesunate.",
27
+ "urgency": "high",
28
+ "category": "infectious"
29
+ },
30
+ {
31
+ "id": "doc_005",
32
+ "title": "Typhoid Fever (Enteric Fever)",
33
+ "text": "Typhoid fever is caused by Salmonella typhi, transmitted via contaminated food and water — a significant public health problem in Pakistan. Presentation: sustained high fever rising in a stepwise pattern over 1–2 weeks, frontal headache, relative bradycardia, rose spots on the trunk, hepatosplenomegaly, and constipation (early) followed by diarrhoea. Complications include intestinal perforation and haemorrhage. Extensively drug-resistant (XDR) typhoid is prevalent in Pakistan: first-line treatment is azithromycin or ceftriaxone. Confirm with blood culture (first week) or Widal test.",
34
+ "urgency": "high",
35
+ "category": "infectious"
36
+ },
37
+ {
38
+ "id": "doc_006",
39
+ "title": "Tuberculosis (TB)",
40
+ "text": "Pakistan has one of the highest TB burdens globally. Pulmonary TB presents with productive cough lasting more than 2 weeks, haemoptysis, night sweats, unexplained weight loss, low-grade fever, and fatigue. Extrapulmonary TB can affect lymph nodes, spine (Pott's disease), meninges, and pleura. Diagnosis: sputum AFB smear, GeneXpert MTB/RIF for rapid diagnosis and rifampicin resistance detection. Treatment: 6-month regimen (HRZE x2 months + HR x4 months). Drug-resistant TB requires specialist management. Report all cases to the national TB programme.",
41
+ "urgency": "high",
42
+ "category": "infectious"
43
+ },
44
+ {
45
+ "id": "doc_007",
46
+ "title": "Sepsis and Septic Shock",
47
+ "text": "Sepsis is a life-threatening organ dysfunction caused by dysregulated host response to infection. Suspect sepsis when infection is accompanied by altered mental status, respiratory rate >22/min, or systolic BP <100 mmHg (qSOFA criteria). Septic shock: sepsis with vasopressor requirement and lactate >2 mmol/L despite fluid resuscitation — mortality exceeds 40%. Hour-1 bundle: blood cultures, broad-spectrum antibiotics (within 1 hour), 30ml/kg IV crystalloid bolus, vasopressors if hypotension persists, lactate measurement. Source control is essential.",
48
+ "urgency": "RED",
49
+ "category": "critical"
50
+ },
51
+ {
52
+ "id": "doc_008",
53
+ "title": "Anaphylaxis",
54
+ "text": "Anaphylaxis is a severe, life-threatening systemic allergic reaction. Onset is typically within minutes of exposure to an allergen. Features: urticaria, angioedema, bronchospasm (wheeze, stridor), hypotension, tachycardia, and loss of consciousness. Adrenaline (epinephrine) 0.5mg IM (anterolateral thigh) is the first-line treatment — do not delay. Lay patient flat, give high-flow oxygen, secure IV access, administer 1L crystalloid. Secondary treatment: antihistamines and corticosteroids. Observe for 6–12 hours after resolution due to risk of biphasic reaction.",
55
+ "urgency": "RED",
56
+ "category": "emergency"
57
+ },
58
+ {
59
+ "id": "doc_009",
60
+ "title": "Meningitis",
61
+ "text": "Bacterial meningitis is a medical emergency with mortality up to 30% if untreated. Classic triad: fever, severe headache, and neck stiffness (Kernig's and Brudzinski's signs). Additional features: photophobia, phonophobia, altered consciousness, and non-blanching petechial rash (suggests meningococcal disease). Do not delay antibiotics for lumbar puncture if patient is unstable. Give IV ceftriaxone 2g immediately and dexamethasone 0.15mg/kg to reduce inflammation. CT head before LP if focal neurological signs, papilloedema, or reduced GCS. Isolate patient and give antibiotic prophylaxis to close contacts.",
62
+ "urgency": "RED",
63
+ "category": "neurological"
64
+ },
65
+ {
66
+ "id": "doc_010",
67
+ "title": "Pulmonary Embolism",
68
+ "text": "Pulmonary embolism (PE) occurs when a thrombus — usually from deep vein thrombosis — lodges in pulmonary vasculature. Presents with sudden-onset dyspnoea, pleuritic chest pain, haemoptysis, and tachycardia. Risk factors: prolonged immobility, surgery, malignancy, pregnancy, and oral contraceptive use. Massive PE causes haemodynamic collapse. Wells score and D-dimer guide diagnostic pathway; CT pulmonary angiography (CTPA) confirms diagnosis. Treatment: anticoagulation with LMWH or NOAC. Massive PE: thrombolysis with alteplase if no contraindications.",
69
+ "urgency": "RED",
70
+ "category": "cardiovascular"
71
+ },
72
+ {
73
+ "id": "doc_011",
74
+ "title": "Pneumonia",
75
+ "text": "Pneumonia is infection of the lung parenchyma, most commonly caused by Streptococcus pneumoniae, Haemophilus influenzae, or atypical organisms (Mycoplasma, Legionella). Symptoms: productive cough, fever, pleuritic chest pain, dyspnoea, and reduced breath sounds with crepitations on auscultation. Assess severity using CURB-65 (Confusion, Urea, Respiratory rate, Blood pressure, Age ≥65) — score ≥2 indicates hospital admission. Chest X-ray confirms consolidation. Community-acquired pneumonia: amoxicillin ± clarithromycin. Hospital-acquired: broad-spectrum antibiotics. Ensure adequate oxygenation (SpO2 ≥94%).",
76
+ "urgency": "high",
77
+ "category": "respiratory"
78
+ },
79
+ {
80
+ "id": "doc_012",
81
+ "title": "COVID-19",
82
+ "text": "COVID-19 is caused by SARS-CoV-2. Presentation ranges from asymptomatic to critical illness. Common symptoms: fever, dry cough, fatigue, loss of smell (anosmia) and taste (ageusia), myalgia, and headache. Severe disease: dyspnoea, low oxygen saturation (SpO2 <94%), and bilateral pneumonia. High-risk groups: elderly, diabetic, hypertensive, obese, and immunocompromised individuals. Isolation and supportive care for mild cases. Hospitalisation for SpO2 <94%, prone positioning for severe hypoxia. Dexamethasone for patients requiring oxygen.",
83
+ "urgency": "high",
84
+ "category": "infectious"
85
+ },
86
+ {
87
+ "id": "doc_013",
88
+ "title": "Acute Asthma Attack",
89
+ "text": "Acute asthma is characterised by bronchospasm, mucosal oedema, and mucus plugging. Severity assessment: mild (PEFR >75%), moderate (50–75%), severe (<50% or RR >25, HR >110, unable to complete sentences), life-threatening (silent chest, cyanosis, altered consciousness, PEFR <33%). Treatment: salbutamol nebuliser 2.5–5mg, ipratropium 0.5mg, oxygen to maintain SpO2 94–98%, oral prednisolone 40–50mg. If no response, consider IV magnesium sulphate 1.2–2g and ICU referral. Failure to respond to initial bronchodilators indicates severe attack requiring urgent escalation.",
90
+ "urgency": "high",
91
+ "category": "respiratory"
92
+ },
93
+ {
94
+ "id": "doc_014",
95
+ "title": "Hypertensive Emergency",
96
+ "text": "Hypertensive emergency is defined as severely elevated blood pressure (usually >180/120 mmHg) with acute end-organ damage — encephalopathy, aortic dissection, acute MI, flash pulmonary oedema, or acute kidney injury. Distinguish from hypertensive urgency (no end-organ damage). Lower BP gradually by no more than 25% in the first hour to avoid ischaemia. IV labetalol or nitroprusside in ICU setting. Oral nifedipine is dangerous and should be avoided. Identify and treat the underlying cause.",
97
+ "urgency": "RED",
98
+ "category": "cardiovascular"
99
+ },
100
+ {
101
+ "id": "doc_015",
102
+ "title": "Diabetic Ketoacidosis (DKA)",
103
+ "text": "DKA is a life-threatening complication of diabetes characterised by hyperglycaemia, metabolic acidosis, and ketonaemia. Presentation: polyuria, polydipsia, nausea, vomiting, abdominal pain, Kussmaul breathing (deep sighing respiration), and fruity breath odour. Precipitants: infection, missed insulin, new-onset Type 1 diabetes. Management: IV fluid resuscitation (0.9% saline), fixed-rate insulin infusion (0.1 units/kg/hr), potassium replacement (monitor closely), identify and treat precipitating cause. Target: blood glucose <14 mmol/L, pH >7.3, bicarbonate >18 mmol/L.",
104
+ "urgency": "RED",
105
+ "category": "endocrine"
106
+ },
107
+ {
108
+ "id": "doc_016",
109
+ "title": "Acute Appendicitis",
110
+ "text": "Appendicitis is the most common surgical emergency, typically presenting in young adults. Classic progression: periumbilical pain migrating to the right iliac fossa (McBurney's point), anorexia, low-grade fever, and nausea. Rovsing's sign (RIF pain on LIF palpation) and rebound tenderness support diagnosis. Alvarado score aids risk stratification. USS or CT scan for confirmation. Risk of perforation increases after 72 hours. Treatment: urgent appendicectomy. Perforation presents with generalised peritonitis, high fever, and rigid abdomen — surgical emergency.",
111
+ "urgency": "high",
112
+ "category": "surgical"
113
+ },
114
+ {
115
+ "id": "doc_017",
116
+ "title": "Acute Gastroenteritis",
117
+ "text": "Acute gastroenteritis involves inflammation of the gastrointestinal tract, commonly caused by Rotavirus, Norovirus, or bacterial pathogens (Salmonella, E. coli, Campylobacter). Presents with nausea, vomiting, diarrhoea, abdominal cramps, and low-grade fever. Dehydration is the primary risk, especially in children and elderly. Assess dehydration severity: mild (thirsty), moderate (reduced skin turgor, dry mouth), severe (sunken eyes, lethargy, shock). Oral rehydration solution (ORS) is first-line. IV fluids for severe dehydration or inability to tolerate oral intake. Antibiotics rarely indicated except for cholera or severe Campylobacter.",
118
+ "urgency": "medium",
119
+ "category": "gastrointestinal"
120
+ },
121
+ {
122
+ "id": "doc_018",
123
+ "title": "Urinary Tract Infection (UTI)",
124
+ "text": "UTIs are common, especially in women. Lower UTI (cystitis): dysuria, frequency, urgency, and suprapubic pain without systemic features. Upper UTI (pyelonephritis): above symptoms plus flank pain, costovertebral tenderness, high fever, rigors, and vomiting — requires hospitalisation. Uncomplicated lower UTI: trimethoprim or nitrofurantoin for 3–7 days. Pyelonephritis: ciprofloxacin or co-amoxiclav for 7–14 days; IV ceftriaxone if systemically unwell. In Pakistan, antibiotic resistance is common — always send urine for culture before starting antibiotics if possible.",
125
+ "urgency": "medium",
126
+ "category": "urological"
127
+ },
128
+ {
129
+ "id": "doc_019",
130
+ "title": "Hepatitis A and E",
131
+ "text": "Hepatitis A and E are enterically transmitted viral hepatitis, common in Pakistan due to contaminated water and food. Presentation: prodromal illness (fatigue, anorexia, nausea), followed by jaundice, dark urine, pale stools, and tender hepatomegaly. Hepatitis E is particularly dangerous in pregnancy, causing fulminant hepatic failure with mortality up to 25% in the third trimester. Both are self-limiting in immunocompetent adults. Management: supportive care, rest, oral hydration, avoid hepatotoxic drugs and alcohol. Hepatitis A vaccine is available for prevention.",
132
+ "urgency": "medium",
133
+ "category": "hepatology"
134
+ },
135
+ {
136
+ "id": "doc_020",
137
+ "title": "Hepatitis B and C",
138
+ "text": "Hepatitis B (HBV) and C (HCV) are bloodborne viral infections causing chronic liver disease, cirrhosis, and hepatocellular carcinoma. Pakistan has high HCV prevalence (7–8%), largely due to unsafe injection practices. Acute HBV: jaundice, nausea, right upper quadrant pain, fatigue. Chronic infection is often asymptomatic until cirrhosis develops. Diagnose with serology (HBsAg, Anti-HCV). Chronic HBV: antiviral therapy (tenofovir, entecavir) for eligible patients. Chronic HCV: highly effective direct-acting antivirals (DAAs) achieve >95% cure rates. Screen close contacts and offer HBV vaccination.",
139
+ "urgency": "medium",
140
+ "category": "hepatology"
141
+ },
142
+ {
143
+ "id": "doc_021",
144
+ "title": "Peptic Ulcer Disease",
145
+ "text": "Peptic ulcers are mucosal defects in the stomach or duodenum caused by H. pylori infection (70%) or NSAID use. Symptoms: burning epigastric pain — duodenal ulcers typically relieved by food, gastric ulcers worsened by eating. Complications: bleeding (haematemesis, melaena), perforation (sudden severe abdominal pain, rigid abdomen — surgical emergency), and gastric outlet obstruction. Diagnosis: endoscopy with biopsy for H. pylori. Treatment: proton pump inhibitor (PPI) + H. pylori eradication (triple therapy: PPI + amoxicillin + clarithromycin for 7–14 days). Stop NSAIDs and advise smoking cessation.",
146
+ "urgency": "medium",
147
+ "category": "gastrointestinal"
148
+ },
149
+ {
150
+ "id": "doc_022",
151
+ "title": "Kidney Stones (Nephrolithiasis)",
152
+ "text": "Renal calculi cause severe colicky flank pain radiating to the groin ('loin to groin'), haematuria, nausea, and vomiting. Pain is typically severe and comes in waves. The patient is often restless (unlike peritonitis where patients lie still). Ureteric colic does not cause peritonism. Calcium oxalate stones are most common. CT KUB is the gold standard for diagnosis. Management: adequate analgesia (diclofenac or morphine), IV fluids, and alpha-blockers (tamsulosin) to facilitate passage. Stones >10mm or associated infection (pyonephrosis) require urgent urological intervention.",
153
+ "urgency": "high",
154
+ "category": "urological"
155
+ },
156
+ {
157
+ "id": "doc_023",
158
+ "title": "Anaemia",
159
+ "text": "Anaemia is defined as Hb <13.5 g/dL in men and <12 g/dL in women. Common causes in Pakistan: iron deficiency (most common, especially in women of reproductive age), thalassaemia, chronic disease, and folate/B12 deficiency. Symptoms: fatigue, pallor, dyspnoea on exertion, palpitations, and dizziness. Severe anaemia may cause high-output cardiac failure. Assess: full blood count, iron studies, peripheral smear, B12 and folate. Iron deficiency: oral ferrous sulphate 200mg TDS for 3 months. Investigate underlying cause (GI blood loss in adults).",
160
+ "urgency": "medium",
161
+ "category": "haematology"
162
+ },
163
+ {
164
+ "id": "doc_024",
165
+ "title": "Hypertension",
166
+ "text": "Hypertension is defined as sustained BP ≥140/90 mmHg and is a major risk factor for stroke, myocardial infarction, heart failure, and kidney disease. It is largely asymptomatic — hence called the 'silent killer'. Symptoms when present: headache (especially occipital, morning), epistaxis, and visual disturbance. Confirm with multiple readings over weeks or ambulatory monitoring. Lifestyle modifications: salt restriction (<5g/day), regular exercise, weight loss, smoking cessation. First-line medications: ACE inhibitors, ARBs, calcium channel blockers, or thiazide diuretics depending on patient profile.",
167
+ "urgency": "medium",
168
+ "category": "cardiovascular"
169
+ },
170
+ {
171
+ "id": "doc_025",
172
+ "title": "Type 2 Diabetes Mellitus",
173
+ "text": "Type 2 diabetes is characterised by insulin resistance and relative insulin deficiency, associated with obesity and sedentary lifestyle. Symptoms: polyuria, polydipsia, unexplained weight loss, fatigue, blurred vision, and recurrent infections. Many patients are asymptomatic at diagnosis. Complications: retinopathy, nephropathy, neuropathy, and cardiovascular disease. Diagnostic criteria: fasting glucose ≥7 mmol/L or HbA1c ≥48 mmol/mol. Management: lifestyle modification (diet, exercise), metformin first-line, escalation to other agents or insulin as required. Monitor HbA1c every 3 months.",
174
+ "urgency": "medium",
175
+ "category": "endocrine"
176
+ },
177
+ {
178
+ "id": "doc_026",
179
+ "title": "Migraine",
180
+ "text": "Migraine is a primary headache disorder characterised by recurrent episodes of moderate-to-severe unilateral pulsating headache lasting 4–72 hours, associated with nausea, vomiting, photophobia, and phonophobia. Aura (visual zigzag patterns, tingling) precedes headache in 30% of cases. Triggers: stress, certain foods, hormonal changes, dehydration, and sleep disruption. Acute treatment: triptans (sumatriptan) are most effective; NSAIDs and paracetamol for mild-moderate attacks. Preventive therapy (propranolol, topiramate, amitriptyline) for frequent attacks (>4/month). Red flag symptoms requiring urgent investigation: thunderclap headache, fever, neck stiffness, focal neurology.",
181
+ "urgency": "low",
182
+ "category": "neurological"
183
+ },
184
+ {
185
+ "id": "doc_027",
186
+ "title": "Cholera",
187
+ "text": "Cholera is caused by Vibrio cholerae, causing profuse watery 'rice-water' diarrhoea and vomiting leading to rapid severe dehydration. It spreads via contaminated water, particularly during floods — a major concern during Pakistan's monsoon seasons. Dehydration can be life-threatening within hours if untreated. Management: aggressive oral or IV rehydration is the cornerstone — WHO ORS or Ringer's lactate. Severe cases: IV fluid replacement of up to 10L in the first few hours. Antibiotics (doxycycline single dose) reduce duration but are secondary to rehydration. Notify public health authorities.",
188
+ "urgency": "RED",
189
+ "category": "infectious"
190
+ },
191
+ {
192
+ "id": "doc_028",
193
+ "title": "Rheumatoid Arthritis",
194
+ "text": "Rheumatoid arthritis (RA) is a chronic autoimmune inflammatory arthritis typically affecting small joints of hands and feet symmetrically. Morning stiffness lasting >1 hour is characteristic. Extra-articular manifestations: rheumatoid nodules, interstitial lung disease, anaemia, and vasculitis. Diagnosis: anti-CCP antibody and rheumatoid factor, X-ray, and clinical criteria. Early aggressive treatment prevents joint destruction. DMARDs (methotrexate first-line) should be started promptly. Biologics (anti-TNF) for refractory disease. NSAIDs for symptom relief. Regular monitoring for drug toxicity.",
195
+ "urgency": "medium",
196
+ "category": "rheumatology"
197
+ },
198
+ {
199
+ "id": "doc_029",
200
+ "title": "Panic Disorder and Anxiety",
201
+ "text": "Panic attacks are discrete episodes of intense fear with somatic symptoms: palpitations, chest tightness, dyspnoea, dizziness, paraesthesiae, sweating, and fear of dying. They mimic cardiac and respiratory emergencies — always exclude organic causes first (ECG, troponin, oxygen saturation). Reassurance and slow breathing techniques during the acute episode. Long-term management: CBT is most effective; SSRIs (sertraline, escitalopram) for pharmacological treatment. Avoid benzodiazepines as long-term treatment. Generalised anxiety disorder presents with persistent worry, muscle tension, and sleep disturbance.",
202
+ "urgency": "low",
203
+ "category": "psychiatric"
204
+ },
205
+ {
206
+ "id": "doc_030",
207
+ "title": "Pancreatitis",
208
+ "text": "Acute pancreatitis presents with severe epigastric pain radiating to the back, nausea, vomiting, and tenderness on palpation. Common causes: gallstones (most common in Pakistan) and alcohol. Serum amylase or lipase >3x upper limit of normal confirms diagnosis. Assess severity using Glasgow or Ranson criteria. Mild disease: supportive care, IV fluids, analgesia, and early oral feeding. Severe pancreatitis (necrosis, multi-organ failure) requires HDU/ICU care, nutritional support, and management of complications (infection, pseudocyst). CT abdomen for severity assessment if not improving.",
209
+ "urgency": "high",
210
+ "category": "gastrointestinal"
211
+ },
212
+ {
213
+ "id": "doc_031",
214
+ "title": "Deep Vein Thrombosis (DVT)",
215
+ "text": "DVT occurs when a blood clot forms in a deep vein, usually in the leg. Presents with unilateral leg pain, swelling, warmth, erythema, and dilated superficial veins. Risk factors: immobility, surgery, malignancy, pregnancy, thrombophilia, and long-haul travel. Wells score guides pre-test probability. D-dimer is sensitive but not specific; Doppler USS confirms diagnosis. Treatment: anticoagulation with LMWH followed by NOAC or warfarin for 3–6 months. PE prophylaxis in hospitalised patients is essential.",
216
+ "urgency": "high",
217
+ "category": "cardiovascular"
218
+ },
219
+ {
220
+ "id": "doc_032",
221
+ "title": "Urinary Retention and Prostate Disease",
222
+ "text": "Acute urinary retention is the sudden inability to pass urine despite a full bladder — a urological emergency causing severe suprapubic pain. Causes: benign prostatic hyperplasia (BPH), urethral stricture, and medications (anticholinergics). Immediate management: urethral catheterisation for relief. Chronic retention may be painless with overflow incontinence. BPH symptoms: hesitancy, weak stream, frequency, nocturia, and incomplete emptying. Investigations: PSA (after discussion regarding prostate cancer risk), USS, and flow rate. Alpha-blockers (tamsulosin) first-line for BPH.",
223
+ "urgency": "high",
224
+ "category": "urological"
225
+ },
226
+ {
227
+ "id": "doc_033",
228
+ "title": "Heart Failure",
229
+ "text": "Heart failure is the inability of the heart to pump sufficient blood to meet metabolic demands. Left heart failure: dyspnoea on exertion, orthopnoea, paroxysmal nocturnal dyspnoea, fine crepitations at lung bases. Right heart failure: peripheral oedema, raised JVP, hepatomegaly. Acute pulmonary oedema is life-threatening: patient sits upright, frothy pink sputum, severe dyspnoea. Immediate treatment: oxygen, IV furosemide, GTN. Chronic management: ACE inhibitor, beta-blocker, spironolactone, SGLT2 inhibitor. Echocardiography to assess ejection fraction.",
230
+ "urgency": "high",
231
+ "category": "cardiovascular"
232
+ },
233
+ {
234
+ "id": "doc_034",
235
+ "title": "Acute Kidney Injury (AKI)",
236
+ "text": "AKI is a rapid decline in renal function, defined by rise in serum creatinine ≥26 µmol/L in 48 hours or ≥1.5x baseline in 7 days. Causes: pre-renal (dehydration, sepsis, heart failure), intrinsic renal (glomerulonephritis, tubular necrosis), post-renal (obstruction). Symptoms: reduced urine output, fluid overload, confusion, uraemic symptoms. Hyperkalaemia (>6.5 mmol/L) is immediately life-threatening — ECG changes require urgent treatment with calcium gluconate, insulin-dextrose, and salbutamol. Identify and treat underlying cause. Dialysis for severe complications.",
237
+ "urgency": "RED",
238
+ "category": "renal"
239
+ },
240
+ {
241
+ "id": "doc_035",
242
+ "title": "Epilepsy and Seizures",
243
+ "text": "Status epilepticus is a seizure lasting >5 minutes or two seizures without return to baseline — a neurological emergency. Immediate management: secure airway, position patient safely, give high-flow oxygen, IV access. Benzodiazepines first-line (IV lorazepam 0.1mg/kg or IM midazolam). If seizures persist after two doses, second-line: IV levetiracetam, sodium valproate, or phenytoin. Refractory status epilepticus requires anaesthesia and ICU. After a first seizure: MRI brain, EEG, metabolic screen. Common precipitants: low anticonvulsant levels, CNS infection, metabolic disturbance, and sleep deprivation.",
244
+ "urgency": "RED",
245
+ "category": "neurological"
246
+ },
247
+ {
248
+ "id": "doc_036",
249
+ "title": "Childhood Fever and Febrile Convulsions",
250
+ "text": "Fever in children under 5 years requires careful assessment. Danger signs (WHO IMCI): inability to drink, convulsions, lethargy, central cyanosis, and severe respiratory distress. Febrile convulsions occur in 2–5% of children aged 6 months to 5 years — usually self-limiting (<5 minutes). Management: position safely, do not restrain, check blood glucose. Investigate underlying cause of fever (malaria, UTI, pneumonia). Simple febrile convulsions do not require anticonvulsant prophylaxis. Complex febrile convulsions (prolonged, focal, or recurrent within 24 hours) require further investigation.",
251
+ "urgency": "high",
252
+ "category": "paediatric"
253
+ },
254
+ {
255
+ "id": "doc_037",
256
+ "title": "Iron Deficiency Anaemia in Women",
257
+ "text": "Iron deficiency anaemia is highly prevalent in Pakistani women due to poor dietary intake, frequent pregnancies, and menorrhagia. Symptoms: fatigue, pallor, dyspnoea, pica (craving non-food substances), koilonychia (spoon-shaped nails), and angular stomatitis. In pregnancy, severe anaemia is associated with preterm birth and maternal mortality. Diagnosis: low MCV, low ferritin (<15 µg/L). Treat with oral ferrous sulphate 200mg twice daily for at least 3 months. IV iron for severe anaemia in pregnancy or intolerance. Address underlying cause.",
258
+ "urgency": "medium",
259
+ "category": "haematology"
260
+ },
261
+ {
262
+ "id": "doc_038",
263
+ "title": "Diarrhoeal Disease in Children (IMCI)",
264
+ "text": "Diarrhoea is a leading cause of child mortality in Pakistan. Assess dehydration: no dehydration (treat at home with ORS and zinc), some dehydration (ORS 75 ml/kg over 4 hours in clinic), severe dehydration (IV Ringer's lactate 100 ml/kg, urgent hospitalisation). Zinc supplementation (20mg for 10–14 days) reduces duration and severity. Antibiotics only for bloody diarrhoea (dysentery) or cholera. Continued feeding (breastfeeding, age-appropriate foods) during illness prevents malnutrition. Educate caregivers on handwashing and safe water storage.",
265
+ "urgency": "high",
266
+ "category": "paediatric"
267
+ },
268
+ {
269
+ "id": "doc_039",
270
+ "title": "Obstetric Emergencies — Pre-eclampsia and Eclampsia",
271
+ "text": "Pre-eclampsia is defined as hypertension (BP ≥140/90 mmHg) with proteinuria after 20 weeks gestation. Severe features: BP ≥160/110, severe headache, visual disturbances, epigastric pain, and HELLP syndrome (haemolysis, elevated liver enzymes, low platelets). Eclampsia is the occurrence of seizures in pre-eclampsia. MgSO4 4g IV loading dose is first-line for eclampsia and severe pre-eclampsia seizure prevention. Antihypertensives for BP control (labetalol, nifedipine). Definitive treatment is delivery — timing depends on gestational age and severity.",
272
+ "urgency": "RED",
273
+ "category": "obstetric"
274
+ },
275
+ {
276
+ "id": "doc_040",
277
+ "title": "Heat Stroke",
278
+ "text": "Heat stroke is a life-threatening emergency defined by core body temperature >40°C with central nervous system dysfunction (confusion, seizures, coma). Classic heat stroke occurs in elderly or ill patients during hot weather. Exertional heat stroke occurs in young people during intense physical activity. Immediate cooling is the priority: remove clothing, apply ice packs to neck, axillae, and groin, cool mist and fan, cold IV fluids. Target temperature: <39°C within 30 minutes. Monitor and treat complications: rhabdomyolysis, DIC, AKI, hepatic failure. Particularly relevant in Pakistan's summer months (May–August).",
279
+ "urgency": "RED",
280
+ "category": "emergency"
281
+ }
282
+ ]
requirements.txt CHANGED
@@ -2,3 +2,4 @@ groq
2
  soundfile
3
  numpy
4
  pandas
 
 
2
  soundfile
3
  numpy
4
  pandas
5
+ sentence-transformers