Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,206 +1,78 @@
|
|
| 1 |
-
|
| 2 |
-
from pydantic import BaseModel,Field
|
|
|
|
|
|
|
|
|
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
import google.generativeai as genai
|
| 5 |
-
import os
|
| 6 |
-
import re
|
| 7 |
-
from typing import Dict, Any, Union, List
|
| 8 |
-
from your_fastapi_module import gradio_interface # your predict function
|
| 9 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
-
import gradio as gr
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# ---------------- Initialize ----------------
|
| 15 |
-
app = FastAPI(title="LLM Model API", version="3.4")
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
app.add_middleware(
|
| 19 |
-
CORSMiddleware,
|
| 20 |
-
allow_origins=["*"], # Or your domain
|
| 21 |
-
allow_methods=["*"],
|
| 22 |
-
allow_headers=["*"],
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
|
| 26 |
-
#
|
| 27 |
# load_dotenv()
|
| 28 |
-
|
| 29 |
-
# ✅ Fetch Gemini API Key
|
| 30 |
GEMINI_API_KEY = "AIzaSyAJ3aMnwOHsLtU1JoudCRIFdZhm6s4oNhY"
|
| 31 |
if not GEMINI_API_KEY:
|
| 32 |
-
raise ValueError("❌ GEMINI_API_KEY not found.
|
| 33 |
|
| 34 |
-
# ✅ Configure Gemini Client
|
| 35 |
genai.configure(api_key=GEMINI_API_KEY)
|
| 36 |
MODEL_ID = "gemini-2.5-flash"
|
| 37 |
|
| 38 |
-
|
| 39 |
# ---------------- Schema ----------------
|
| 40 |
class BiomarkerRequest(BaseModel):
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
ldl: float = Field(default=90.0, description="LDL Cholesterol (mg/dL)")
|
| 81 |
-
hdl: float = Field(default=50.0, description="HDL Direct (mg/dL)")
|
| 82 |
-
cholesterol_hdl_ratio: float = Field(default=3.0, description="Cholesterol/HDL Ratio")
|
| 83 |
-
triglycerides: float = Field(default=120.0, description="Triglycerides (mg/dL)")
|
| 84 |
-
apo_a1: float = Field(default=140.0, description="Apo A-1 (mg/dL)")
|
| 85 |
-
apo_b: float = Field(default=70.0, description="Apo B (mg/dL)")
|
| 86 |
-
apo_ratio: float = Field(default=0.5, description="Apo B : Apo A-1 ratio")
|
| 87 |
-
|
| 88 |
-
# ---------------- Liver Function ----------------
|
| 89 |
-
albumin: float = Field(default=4.2, description="Albumin (g/dL)")
|
| 90 |
-
total_protein: float = Field(default=7.0, description="Total Protein (g/dL)")
|
| 91 |
-
alt: float = Field(default=25.0, description="ALT (U/L)")
|
| 92 |
-
ast: float = Field(default=24.0, description="AST (U/L)")
|
| 93 |
-
alp: float = Field(default=120.0, description="ALP (U/L)")
|
| 94 |
-
ggt: float = Field(default=20.0, description="GGT (U/L)")
|
| 95 |
-
ld: float = Field(default=180.0, description="LDH (U/L)")
|
| 96 |
-
globulin: float = Field(default=3.0, description="Globulin (g/dL)")
|
| 97 |
-
albumin_globulin_ratio: float = Field(default=1.4, description="Albumin/Globulin Ratio")
|
| 98 |
-
magnesium: float = Field(default=2.0, description="Magnesium (mg/dL)")
|
| 99 |
-
total_bilirubin: float = Field(default=0.7, description="Total Bilirubin (mg/dL)")
|
| 100 |
-
direct_bilirubin: float = Field(default=0.3, description="Direct Bilirubin (mg/dL)")
|
| 101 |
-
indirect_bilirubin: float = Field(default=0.4, description="Indirect Bilirubin (mg/dL)")
|
| 102 |
-
ammonia: float = Field(default=35.0, description="Ammonia (NH3) (µmol/L)")
|
| 103 |
-
|
| 104 |
-
# ---------------- Cardiac Profile ----------------
|
| 105 |
-
hs_crp: float = Field(default=1.0, description="High-Sensitivity CRP (mg/L)")
|
| 106 |
-
ck: float = Field(default=150.0, description="Creatine Kinase (U/L)")
|
| 107 |
-
ck_mb: float = Field(default=20.0, description="CK-MB (U/L)")
|
| 108 |
-
homocysteine: float = Field(default=10.0, description="Homocysteine (µmol/L)")
|
| 109 |
-
|
| 110 |
-
# ---------------- Mineral & Heavy Metal ----------------
|
| 111 |
-
zinc: float = Field(default=90.0, description="Zinc (µg/dL)")
|
| 112 |
-
copper: float = Field(default=100.0, description="Copper (µg/dL)")
|
| 113 |
-
selenium: float = Field(default=120.0, description="Selenium (µg/L)")
|
| 114 |
-
|
| 115 |
-
# ---------------- Iron Profile ----------------
|
| 116 |
-
iron: float = Field(default=100.0, description="Iron (µg/dL)")
|
| 117 |
-
tibc: float = Field(default=300.0, description="TIBC (µg/dL)")
|
| 118 |
-
transferrin: float = Field(default=250.0, description="Transferrin (mg/dL)")
|
| 119 |
-
|
| 120 |
-
# ---------------- Vitamins ----------------
|
| 121 |
-
vitamin_d: float = Field(default=35.0, description="Vitamin D (ng/mL)")
|
| 122 |
-
vitamin_b12: float = Field(default=500.0, description="Vitamin B12 (pg/mL)")
|
| 123 |
-
|
| 124 |
-
# ---------------- Hormone Profile ----------------
|
| 125 |
-
total_testosterone: float = Field(default=450.0, description="Total Testosterone (ng/dL)")
|
| 126 |
-
free_testosterone: float = Field(default=15.0, description="Free Testosterone (pg/mL)")
|
| 127 |
-
estrogen: float = Field(default=60.0, description="Estrogen / Estradiol (pg/mL)")
|
| 128 |
-
progesterone: float = Field(default=1.0, description="Progesterone (ng/mL)")
|
| 129 |
-
dhea_s: float = Field(default=250.0, description="DHEA-S (µg/dL)")
|
| 130 |
-
shbg: float = Field(default=40.0, description="SHBG (nmol/L)")
|
| 131 |
-
lh: float = Field(default=5.0, description="LH (IU/L)")
|
| 132 |
-
fsh: float = Field(default=6.0, description="FSH (IU/L)")
|
| 133 |
-
|
| 134 |
-
# ---------------- Thyroid Profile ----------------
|
| 135 |
-
tsh: float = Field(default=2.0, description="TSH (µIU/mL)")
|
| 136 |
-
free_t3: float = Field(default=3.2, description="Free T3 (pg/mL)")
|
| 137 |
-
free_t4: float = Field(default=1.2, description="Free T4 (ng/dL)")
|
| 138 |
-
total_t3: float = Field(default=120.0, description="Total T3 (ng/dL)")
|
| 139 |
-
total_t4: float = Field(default=8.0, description="Total T4 (µg/dL)")
|
| 140 |
-
reverse_t3: float = Field(default=15.0, description="Reverse T3 (ng/dL)")
|
| 141 |
-
tpo_ab: float = Field(default=5.0, description="Thyroid Antibodies – TPO Ab (IU/mL)")
|
| 142 |
-
tg_ab: float = Field(default=3.0, description="Thyroid Antibodies – TG Ab (IU/mL)")
|
| 143 |
-
|
| 144 |
-
# ---------------- Adrenal / Stress / Other Hormones ----------------
|
| 145 |
-
cortisol: float = Field(default=12.0, description="Cortisol (µg/dL)")
|
| 146 |
-
acth: float = Field(default=25.0, description="ACTH (pg/mL)")
|
| 147 |
-
igf1: float = Field(default=200.0, description="IGF-1 (ng/mL)")
|
| 148 |
-
leptin: float = Field(default=10.0, description="Leptin (ng/mL)")
|
| 149 |
-
adiponectin: float = Field(default=10.0, description="Adiponectin (µg/mL)")
|
| 150 |
-
|
| 151 |
-
# ---------------- Blood Marker Cancer Profile ----------------
|
| 152 |
-
ca125: float = Field(default=20.0, description="CA125 (U/mL)")
|
| 153 |
-
ca15_3: float = Field(default=25.0, description="CA15-3 (U/mL)")
|
| 154 |
-
ca19_9: float = Field(default=30.0, description="CA19-9 (U/mL)")
|
| 155 |
-
psa: float = Field(default=1.0, description="PSA (ng/mL)")
|
| 156 |
-
cea: float = Field(default=2.0, description="CEA (ng/mL)")
|
| 157 |
-
calcitonin: float = Field(default=5.0, description="Calcitonin (pg/mL)")
|
| 158 |
-
afp: float = Field(default=5.0, description="AFP (ng/mL)")
|
| 159 |
-
tnf: float = Field(default=2.0, description="Tumor Necrosis Factor (pg/mL)")
|
| 160 |
-
|
| 161 |
-
# ---------------- Immune Profile ----------------
|
| 162 |
-
ana: float = Field(default=0.5, description="ANA (IU/mL)")
|
| 163 |
-
ige: float = Field(default=100.0, description="IgE (IU/mL)")
|
| 164 |
-
igg: float = Field(default=1200.0, description="IgG (mg/dL)")
|
| 165 |
-
anti_ccp: float = Field(default=10.0, description="Anti-CCP (U/mL)")
|
| 166 |
-
dsdna: float = Field(default=0.5, description="dsDNA (IU/mL)")
|
| 167 |
-
ssa_ssb: float = Field(default=5.0, description="SSA/SSB (IU/mL)")
|
| 168 |
-
rnp: float = Field(default=1.0, description="RNP (IU/mL)")
|
| 169 |
-
sm_antibodies: float = Field(default=0.5, description="Sm Antibodies (IU/mL)")
|
| 170 |
-
anca: float = Field(default=0.5, description="ANCA (IU/mL)")
|
| 171 |
-
anti_ena: float = Field(default=0.5, description="Anti-ENA (IU/mL)")
|
| 172 |
-
il6: float = Field(default=3.0, description="IL-6 (pg/mL)")
|
| 173 |
-
allergy_panel: float = Field(default=10.0, description="Comprehensive Allergy Profile (IgE & Food Sensitivity IgG)")
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
# ---------------- Cleaning Utility ----------------
|
| 179 |
def clean_json(data: Union[Dict, List, str]) -> Union[Dict, List, str]:
|
| 180 |
-
"""Recursively removes separators, extra whitespace, and artifacts from all string values."""
|
| 181 |
if isinstance(data, str):
|
| 182 |
text = re.sub(r"-{3,}", "", data)
|
| 183 |
text = re.sub(r"\s+", " ", text)
|
| 184 |
-
|
| 185 |
-
return text
|
| 186 |
elif isinstance(data, list):
|
| 187 |
return [clean_json(i) for i in data if i and clean_json(i)]
|
| 188 |
elif isinstance(data, dict):
|
| 189 |
return {k.strip(): clean_json(v) for k, v in data.items()}
|
| 190 |
return data
|
| 191 |
|
| 192 |
-
|
| 193 |
# ---------------- Parser ----------------
|
| 194 |
def parse_medical_report(text: str):
|
| 195 |
-
"""
|
| 196 |
-
Parses Gemini markdown response → structured JSON.
|
| 197 |
-
Detects section headers, **bold keys**, and table entries.
|
| 198 |
-
"""
|
| 199 |
def clean_line(line: str) -> str:
|
| 200 |
return re.sub(r"[\-\*\u2022]+\s*", "", line.strip())
|
| 201 |
|
| 202 |
def parse_bold_entities(block: str) -> Dict[str, str]:
|
| 203 |
-
"""Extracts **bold** entities and maps text until next bold or section."""
|
| 204 |
entities = {}
|
| 205 |
pattern = re.compile(r"\*\*(.*?)\*\*(.*?)(?=\*\*|###|$)", re.S)
|
| 206 |
for match in pattern.finditer(block):
|
|
@@ -220,7 +92,6 @@ def parse_medical_report(text: str):
|
|
| 220 |
"biomarker_table": []
|
| 221 |
}
|
| 222 |
|
| 223 |
-
# --- Executive Summary ---
|
| 224 |
exec_match = re.search(r"###\s*Executive Summary(.*?)(?=###|$)", text, re.S | re.I)
|
| 225 |
if exec_match:
|
| 226 |
block = exec_match.group(1)
|
|
@@ -233,85 +104,66 @@ def parse_medical_report(text: str):
|
|
| 233 |
strengths = [clean_line(s) for s in strengths_text.splitlines() if clean_line(s)]
|
| 234 |
data["executive_summary"]["key_strengths"] = strengths
|
| 235 |
|
| 236 |
-
# --- System Analysis ---
|
| 237 |
sys_match = re.search(r"###\s*System[- ]Specific Analysis(.*?)(?=###|$)", text, re.S | re.I)
|
| 238 |
if sys_match:
|
| 239 |
sys_block = sys_match.group(1)
|
| 240 |
data["system_analysis"] = parse_bold_entities(sys_block)
|
| 241 |
|
| 242 |
-
# --- Personalized Action Plan ---
|
| 243 |
plan_match = re.search(r"###\s*Personalized Action Plan(.*?)(?=###|$)", text, re.S | re.I)
|
| 244 |
if plan_match:
|
| 245 |
plan_block = plan_match.group(1)
|
| 246 |
data["personalized_action_plan"] = parse_bold_entities(plan_block)
|
| 247 |
|
| 248 |
-
# --- Interaction Alerts ---
|
| 249 |
alerts_match = re.search(r"###\s*Interaction Alerts(.*?)(?=###|$)", text, re.S | re.I)
|
| 250 |
if alerts_match:
|
| 251 |
alerts_block = alerts_match.group(1)
|
| 252 |
-
|
| 253 |
-
data["interaction_alerts"] = alerts
|
| 254 |
-
|
| 255 |
-
# --- Normal Ranges ---
|
| 256 |
-
normal_match = re.search(r"###\s*Normal Ranges(.*?)(?=###|$)", text, re.S | re.I)
|
| 257 |
-
if normal_match:
|
| 258 |
-
normal_block = normal_match.group(1)
|
| 259 |
-
for match in re.findall(r"-\s*([^:]+):\s*([^\n]+)", normal_block):
|
| 260 |
-
biomarker, rng = match
|
| 261 |
-
data["normal_ranges"][biomarker.strip()] = rng.strip()
|
| 262 |
-
|
| 263 |
-
# --- Tabular Mapping ---
|
| 264 |
-
table_match = re.search(r"###\s*Tabular Mapping(.*)", text, re.S | re.I)
|
| 265 |
-
if table_match:
|
| 266 |
-
table_block = table_match.group(1)
|
| 267 |
-
# robust row matcher: capture any table rows with 5 pipe-separated columns
|
| 268 |
-
table_pattern = r"\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|"
|
| 269 |
-
for biomarker, value, status, insight, ref in re.findall(table_pattern, table_block):
|
| 270 |
-
# normalize
|
| 271 |
-
biomarker_s = biomarker.strip()
|
| 272 |
-
value_s = value.strip()
|
| 273 |
-
status_s = status.strip()
|
| 274 |
-
insight_s = insight.strip()
|
| 275 |
-
ref_s = ref.strip()
|
| 276 |
|
| 277 |
-
|
| 278 |
-
if not any([biomarker_s, value_s, status_s, insight_s, ref_s]):
|
| 279 |
-
# This is the empty-row you showed: skip it and continue
|
| 280 |
-
continue
|
| 281 |
-
|
| 282 |
-
# ---------- ALSO SKIP rows that are pure separator artifacts ----------
|
| 283 |
-
# e.g., ":-----------" or "--------" in biomarker column (common AI artifacts)
|
| 284 |
-
def is_separator_cell(s: str) -> bool:
|
| 285 |
-
# treat as separator if contains no alphanumeric chars
|
| 286 |
-
return not bool(re.search(r"[A-Za-z0-9]", s))
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
})
|
| 299 |
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
# --- Prompt Template ---
|
| 309 |
prompt = """
|
| 310 |
You are an advanced **Medical Insight Generation AI** trained to analyze **biomarkers and lab results**.
|
| 311 |
-
|
| 312 |
⚠️ IMPORTANT — OUTPUT FORMAT INSTRUCTIONS:
|
| 313 |
Return your report in this strict markdown structure.
|
| 314 |
-
|
| 315 |
------------------------------
|
| 316 |
### Executive Summary
|
| 317 |
**Top 3 Health Priorities:**
|
|
@@ -319,47 +171,34 @@ Return your report in this strict markdown structure.
|
|
| 319 |
2. ...
|
| 320 |
3. ...
|
| 321 |
make it more detailed
|
| 322 |
-
|
| 323 |
**Key Strengths:**
|
| 324 |
- ...
|
| 325 |
- ...
|
| 326 |
make it detailed
|
| 327 |
------------------------------
|
| 328 |
### System-Specific Analysis
|
| 329 |
-
|
| 330 |
**Cardiovascular System**
|
| 331 |
Status: Normal. Explanation: Lipid profile including Total Cholesterol, LDL, HDL, Triglycerides, Apo A-1, Apo B, Apo Ratio, and Cholesterol/HDL Ratio are within reference ranges, indicating low risk of atherosclerosis, coronary artery disease, and other cardiovascular disorders. hs-CRP, CK, CK-MB, and Homocysteine levels are normal, reflecting minimal systemic inflammation and proper myocardial health.
|
| 332 |
-
|
| 333 |
**Metabolic & Glycemic Control**
|
| 334 |
Status: Normal. Explanation: Fasting Blood Sugar, HbA1c, Insulin, C-Peptide, and HOMA-IR are within healthy ranges, suggesting effective glucose metabolism, insulin sensitivity, and low risk of prediabetes or diabetes.
|
| 335 |
-
|
| 336 |
**Liver Function**
|
| 337 |
Status: Normal. Explanation: ALT, AST, ALP, GGT, LDH, Total Bilirubin, Direct and Indirect Bilirubin, Albumin, Globulin, Albumin/Globulin Ratio, Total Protein, Ammonia, and Magnesium are within reference ranges, reflecting normal hepatocellular integrity, protein synthesis, and biliary excretion. Abnormalities could indicate hepatic injury, cholestasis, or metabolic liver disorders.
|
| 338 |
-
|
| 339 |
**Renal Function**
|
| 340 |
Status: Normal. Explanation: Urea, Creatinine, eGFR, Uric Acid, Sodium, Potassium, Chloride, Phosphorus, Calcium, Ionized Calcium, Bicarbonate, Serum Osmolality, Amylase, and Lipase are within expected ranges, suggesting proper kidney filtration, electrolyte balance, and pancreatic enzyme activity. Deviations may indicate renal impairment, electrolyte disorders, or pancreatitis risk.
|
| 341 |
-
|
| 342 |
**Thyroid Function**
|
| 343 |
Status: Normal. Explanation: TSH, Free T3, Free T4, Total T3, Total T4, Reverse T3, TPO Ab, and TG Ab are within reference limits, showing normal thyroid hormone production, peripheral conversion, and autoimmune status. Abnormal levels may indicate hypothyroidism, hyperthyroidism, or thyroid autoimmunity.
|
| 344 |
-
|
| 345 |
**Adrenal & Stress Hormones**
|
| 346 |
Status: Normal. Explanation: Cortisol, ACTH, DHEA-S, IGF-1, Leptin, and Adiponectin are within normal ranges, reflecting healthy adrenal function, stress response, metabolic regulation, and energy homeostasis. Abnormalities could indicate adrenal insufficiency, Cushing’s syndrome, metabolic disorders, or leptin/adiponectin imbalance.
|
| 347 |
-
|
| 348 |
**Sex Hormones & Reproductive Health**
|
| 349 |
Status: Normal. Explanation: Total Testosterone, Free Testosterone, SHBG, Estrogen, Progesterone, LH, and FSH are within expected ranges based on gender and menstrual cycle, indicating balanced gonadal function, fertility potential, and hormonal homeostasis. Deviations may impact reproductive function, libido, or secondary sexual characteristics.
|
| 350 |
-
|
| 351 |
**Vitamins & Minerals**
|
| 352 |
Status: Normal. Explanation: Vitamin D, Vitamin B12, Iron, TIBC, Transferrin, Zinc, Copper, Selenium, and Magnesium are within reference ranges, supporting optimal hematologic function, enzymatic reactions, immune defense, and bone health. Deficiencies may lead to anemia, metabolic disturbances, or immune dysfunction.
|
| 353 |
-
|
| 354 |
**Hematology & Immune Function**
|
| 355 |
Status: Normal. Explanation: Hemoglobin, MCV, RDW, WBC, Lymphocytes, Albumin, Globulin, ANA, IgE, IgG, Anti-CCP, dsDNA, SSA/SSB, RNP, Sm Antibodies, ANCA, Anti-ENA, IL-6, and Allergy Panel are within normal limits, indicating proper oxygen transport, red blood cell morphology, and immune competence. Deviations could indicate anemia, infection, inflammation, or autoimmune conditions.
|
| 356 |
-
|
| 357 |
**Cancer Markers**
|
| 358 |
Status: Normal. Explanation: CA125, CA15-3, CA19-9, PSA, CEA, AFP, Calcitonin, and TNF are within reference ranges, suggesting low risk for malignancy or tumor activity. Elevated values may require further imaging or diagnostic evaluation.
|
| 359 |
-
|
| 360 |
**Inflammatory Markers**
|
| 361 |
Status: Normal. Explanation: hs-CRP, IL-6, and Homocysteine are within recommended ranges, reflecting low systemic inflammation and minimal cardiovascular or metabolic risk. Elevations may indicate chronic inflammation, autoimmune activity, or thrombotic risk.
|
| 362 |
-
|
| 363 |
------------------------------
|
| 364 |
### Personalized Action Plan
|
| 365 |
**Nutrition:** ...
|
|
@@ -394,21 +233,18 @@ make it detailed
|
|
| 394 |
- Ionized Calcium: 1.12–1.32 mmol/L
|
| 395 |
- Amylase (S): 23–85 U/L
|
| 396 |
- Lipase (S): 0–160 U/L
|
| 397 |
-
|
| 398 |
# Basic Checkup
|
| 399 |
- WBC: 4–10 ×10^3/μL
|
| 400 |
- Hemoglobin: 13–17 g/dL
|
| 401 |
- MCV: 80–100 fL
|
| 402 |
- RDW: 11.5–14.5 %
|
| 403 |
- Lymphocytes: 20–40 %
|
| 404 |
-
|
| 405 |
# Diabetic Profile
|
| 406 |
- Fasting Blood Sugar: 70–99 mg/dL
|
| 407 |
- HbA1c: <5.7 %
|
| 408 |
- Insulin: 2–20 µIU/mL
|
| 409 |
- C-Peptide: 0.5–2.0 ng/mL
|
| 410 |
- HOMA-IR: <1 Optimal, 1–2 Normal, >2 Insulin Resistance
|
| 411 |
-
|
| 412 |
# Lipid Profile
|
| 413 |
- Total Cholesterol: <200 mg/dL
|
| 414 |
- LDL: <100 mg/dL
|
|
@@ -419,7 +255,6 @@ make it detailed
|
|
| 419 |
- Apo B: <90 mg/dL
|
| 420 |
- Apo B/A1 ratio: 0.3–0.7
|
| 421 |
- Cholesterol/HDL Ratio: <3.5 Optimal
|
| 422 |
-
|
| 423 |
# Liver Function
|
| 424 |
- Albumin: 3.5–5.0 g/dL
|
| 425 |
- Total Protein: 6.0–8.3 g/dL
|
|
@@ -435,28 +270,23 @@ make it detailed
|
|
| 435 |
- Direct Bilirubin: 0.0–0.3 mg/dL
|
| 436 |
- Indirect Bilirubin: 0.2–0.9 mg/dL
|
| 437 |
- Ammonia: 15–45 µmol/L
|
| 438 |
-
|
| 439 |
# Cardiac Profile
|
| 440 |
- hs-CRP: 1–3 mg/L
|
| 441 |
- CK: 40–200 U/L
|
| 442 |
- CK-MB: 0–25 U/L
|
| 443 |
- Homocysteine: 5–15 µmol/L
|
| 444 |
-
|
| 445 |
# Minerals & Heavy Metals
|
| 446 |
- Zinc: 70–120 µg/dL
|
| 447 |
- Copper: 70–140 µg/dL
|
| 448 |
- Selenium: 70–150 µg/L
|
| 449 |
-
|
| 450 |
# Iron Profile
|
| 451 |
- Iron (Men): 60–170 µg/dL
|
| 452 |
- Iron (Women): 50–170 µg/dL
|
| 453 |
- TIBC: 250–450 µg/dL
|
| 454 |
- Transferrin: 200–360 mg/dL
|
| 455 |
-
|
| 456 |
# Vitamins
|
| 457 |
- Vitamin D: 30–60 ng/mL
|
| 458 |
- Vitamin B12: 200–900 pg/mL
|
| 459 |
-
|
| 460 |
# Hormones
|
| 461 |
- Total Testosterone (Men): 300–1000 ng/dL
|
| 462 |
- Total Testosterone (Women): 15–70 ng/dL
|
|
@@ -480,7 +310,6 @@ make it detailed
|
|
| 480 |
- Leptin (Men): 0.5–8 ng/mL
|
| 481 |
- Leptin (Women): 5–25 ng/mL
|
| 482 |
- Adiponectin: 5–30 µg/mL
|
| 483 |
-
|
| 484 |
# Thyroid
|
| 485 |
- TSH: 0.4–4.0 µIU/mL
|
| 486 |
- Free T3: 2.0–4.4 pg/mL
|
|
@@ -490,7 +319,6 @@ make it detailed
|
|
| 490 |
- Reverse T3: 9–24 ng/dL
|
| 491 |
- TPO Ab: <35 IU/mL
|
| 492 |
- TG Ab: <40 IU/mL
|
| 493 |
-
|
| 494 |
# Cancer Markers
|
| 495 |
- CA125: <35 U/mL
|
| 496 |
- CA15-3: <30 U/mL
|
|
@@ -500,9 +328,6 @@ make it detailed
|
|
| 500 |
- Calcitonin: <10 pg/mL
|
| 501 |
- AFP: <10 ng/mL
|
| 502 |
- TNF: <8 pg/m
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
------------------------------
|
| 507 |
### Tabular Mapping
|
| 508 |
| Biomarker | Value | Status | Insight | Reference Range |
|
|
@@ -512,247 +337,27 @@ make it detailed
|
|
| 512 |
------------------------------
|
| 513 |
"""
|
| 514 |
|
| 515 |
-
# --- Format User Data ---
|
| 516 |
-
user_message = f"""
|
| 517 |
-
**Patient Info**
|
| 518 |
-
- Id: {data.id}
|
| 519 |
-
- Age: {data.age}
|
| 520 |
-
- Gender: {data.gender}
|
| 521 |
-
- Height: {data.height} cm
|
| 522 |
-
- Weight: {data.weight} kg
|
| 523 |
-
|
| 524 |
-
**Metabolic & Glycemic Control**
|
| 525 |
-
- Fasting Blood Sugar: {data.fasting_blood_sugar} mg/dL
|
| 526 |
-
- HbA1c: {data.hb1ac} %
|
| 527 |
-
- Insulin: {data.insulin} µIU/mL
|
| 528 |
-
- C-Peptide: {data.c_peptide} ng/mL
|
| 529 |
-
- HOMA-IR: {data.homa_ir}
|
| 530 |
-
- Leptin: {data.leptin} ng/mL
|
| 531 |
-
|
| 532 |
-
**Cardiovascular System**
|
| 533 |
-
- Total Cholesterol: {data.total_cholesterol} mg/dL
|
| 534 |
-
- LDL: {data.ldl} mg/dL
|
| 535 |
-
- HDL: {data.hdl} mg/dL
|
| 536 |
-
- Triglycerides: {data.triglycerides} mg/dL
|
| 537 |
-
- ApoB: {data.apo_b} mg/dL
|
| 538 |
-
- Cholesterol/HDL Ratio: {data.cholesterol_hdl_ratio}
|
| 539 |
-
- hs-CRP: {data.hs_crp} mg/L
|
| 540 |
-
- Homocysteine: {data.homocysteine} µmol/L
|
| 541 |
-
|
| 542 |
-
**Liver Function**
|
| 543 |
-
- ALT: {data.alt} U/L
|
| 544 |
-
- AST: {data.ast} U/L
|
| 545 |
-
- GGT: {data.ggt} U/L
|
| 546 |
-
- Total Bilirubin: {data.total_bilirubin} mg/dL
|
| 547 |
-
- Total Protein: {data.total_protein} g/dL
|
| 548 |
-
|
| 549 |
-
**Renal Function**
|
| 550 |
-
- Creatinine: {data.creatinine} mg/dL
|
| 551 |
-
- eGFR: {data.egfr} mL/min/1.73m2
|
| 552 |
-
- Uric Acid: {data.uric_acid} mg/dL
|
| 553 |
-
|
| 554 |
-
**Vitamins & Minerals**
|
| 555 |
-
- Vitamin D: {data.vitamin_d} ng/mL
|
| 556 |
-
- Vitamin B12: {data.vitamin_b12} pg/mL
|
| 557 |
-
- Iron: {data.iron} µg/dL
|
| 558 |
-
- Zinc: {data.zinc} µg/dL
|
| 559 |
-
|
| 560 |
-
**Thyroid Function**
|
| 561 |
-
- TSH: {data.tsh} µIU/mL
|
| 562 |
-
- Free T3: {data.free_t3} pg/mL
|
| 563 |
-
- Free T4: {data.free_t4} ng/dL
|
| 564 |
-
|
| 565 |
-
**Sex Hormones & Reproductive Health**
|
| 566 |
-
- Total Testosterone: {data.total_testosterone} ng/dL
|
| 567 |
-
- Free Testosterone: {data.free_testosterone} pg/mL
|
| 568 |
-
- Estrogen (Estradiol): {data.estrogen} pg/mL
|
| 569 |
-
- SHBG: {data.shbg} nmol/L
|
| 570 |
-
|
| 571 |
-
**Adrenal & Stress Hormones**
|
| 572 |
-
- Cortisol: {data.cortisol} µg/dL
|
| 573 |
-
- DHEA-S: {data.dhea_s} µg/dL
|
| 574 |
-
|
| 575 |
-
**Autoimmune / Inflammatory Markers**
|
| 576 |
-
- Anti-CCP: {data.anti_ccp} U/mL
|
| 577 |
-
"""
|
| 578 |
-
|
| 579 |
-
# --- Gemini Call ---
|
| 580 |
model = genai.GenerativeModel(MODEL_ID)
|
| 581 |
response = model.generate_content(f"{prompt}\n\n{user_message}")
|
| 582 |
-
|
| 583 |
if not response or not getattr(response, "text", None):
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
report_text = response.text.strip()
|
| 587 |
-
|
| 588 |
-
# --- Parse + Clean ---
|
| 589 |
-
parsed_output = parse_medical_report(report_text)
|
| 590 |
-
cleaned_output = clean_json(parsed_output)
|
| 591 |
-
|
| 592 |
-
return cleaned_output
|
| 593 |
|
|
|
|
|
|
|
|
|
|
| 594 |
except Exception as e:
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
weight = gr.Number(label="Weight (kg)", value=70)
|
| 611 |
-
|
| 612 |
-
with gr.Accordion("🩸 Basic Chemistry & Kidney Function", open=False):
|
| 613 |
-
urea = gr.Number(label="Urea (mg/dL)", value=30)
|
| 614 |
-
creatinine = gr.Number(label="Creatinine (mg/dL)", value=1.0)
|
| 615 |
-
uric_acid = gr.Number(label="Uric Acid (mg/dL)", value=5.0)
|
| 616 |
-
egfr = gr.Number(label="eGFR (mL/min)", value=100)
|
| 617 |
-
amylase = gr.Number(label="Amylase (U/L)", value=70)
|
| 618 |
-
lipase = gr.Number(label="Lipase (U/L)", value=50)
|
| 619 |
-
bicarbonate = gr.Number(label="Bicarbonate (mmol/L)", value=24)
|
| 620 |
-
serum_osmolality = gr.Number(label="Serum Osmolality (mOsm/kg)", value=290)
|
| 621 |
-
|
| 622 |
-
with gr.Accordion("⚡ Electrolytes & Minerals", open=False):
|
| 623 |
-
sodium = gr.Number(label="Sodium (mEq/L)", value=140)
|
| 624 |
-
potassium = gr.Number(label="Potassium (mEq/L)", value=4.2)
|
| 625 |
-
chloride = gr.Number(label="Chloride (mEq/L)", value=102)
|
| 626 |
-
calcium = gr.Number(label="Calcium (mg/dL)", value=9.5)
|
| 627 |
-
phosphorus = gr.Number(label="Phosphorus (mg/dL)", value=3.5)
|
| 628 |
-
magnesium = gr.Number(label="Magnesium (mg/dL)", value=2.0)
|
| 629 |
-
ionized_calcium = gr.Number(label="Ionized Calcium (mmol/L)", value=1.25)
|
| 630 |
-
|
| 631 |
-
with gr.Accordion("🥼 Liver & Proteins", open=False):
|
| 632 |
-
albumin = gr.Number(label="Albumin (g/dL)", value=4.2)
|
| 633 |
-
total_protein = gr.Number(label="Total Protein (g/dL)", value=7.0)
|
| 634 |
-
globulin = gr.Number(label="Globulin (g/dL)", value=3.0)
|
| 635 |
-
albumin_globulin_ratio = gr.Number(label="A/G Ratio", value=1.4)
|
| 636 |
-
alt = gr.Number(label="ALT (U/L)", value=25)
|
| 637 |
-
ast = gr.Number(label="AST (U/L)", value=24)
|
| 638 |
-
alp = gr.Number(label="ALP (U/L)", value=120)
|
| 639 |
-
ggt = gr.Number(label="GGT (U/L)", value=20)
|
| 640 |
-
ld = gr.Number(label="LD (U/L)", value=180)
|
| 641 |
-
total_bilirubin = gr.Number(label="Total Bilirubin (mg/dL)", value=1.0)
|
| 642 |
-
direct_bilirubin = gr.Number(label="Direct Bilirubin (mg/dL)", value=0.3)
|
| 643 |
-
indirect_bilirubin = gr.Number(label="Indirect Bilirubin (mg/dL)", value=0.7)
|
| 644 |
-
ammonia = gr.Number(label="Ammonia (µmol/L)", value=35)
|
| 645 |
-
|
| 646 |
-
with gr.Accordion("🩺 Hematology", open=False):
|
| 647 |
-
wbc = gr.Number(label="WBC (×10³/μL)", value=6.0)
|
| 648 |
-
hemoglobin = gr.Number(label="Hemoglobin (g/dL)", value=14.0)
|
| 649 |
-
mcv = gr.Number(label="MCV (fL)", value=90)
|
| 650 |
-
rdw = gr.Number(label="RDW (%)", value=13.5)
|
| 651 |
-
lymphocytes = gr.Number(label="Lymphocytes (%)", value=30)
|
| 652 |
-
|
| 653 |
-
with gr.Accordion("🍬 Diabetes & Insulin Resistance", open=False):
|
| 654 |
-
fasting_blood_sugar = gr.Number(label="Fasting Blood Sugar (mg/dL)", value=85)
|
| 655 |
-
hb1ac = gr.Number(label="HbA1c (%)", value=5.4)
|
| 656 |
-
insulin = gr.Number(label="Insulin (μU/mL)", value=10)
|
| 657 |
-
c_peptide = gr.Number(label="C-Peptide (ng/mL)", value=1.2)
|
| 658 |
-
homa_ir = gr.Number(label="HOMA-IR", value=1.2)
|
| 659 |
-
|
| 660 |
-
with gr.Accordion("❤️ Lipids", open=False):
|
| 661 |
-
total_cholesterol = gr.Number(label="Total Cholesterol (mg/dL)", value=180)
|
| 662 |
-
ldl = gr.Number(label="LDL (mg/dL)", value=90)
|
| 663 |
-
hdl = gr.Number(label="HDL (mg/dL)", value=50)
|
| 664 |
-
triglycerides = gr.Number(label="Triglycerides (mg/dL)", value=120)
|
| 665 |
-
cholesterol_hdl_ratio = gr.Number(label="Chol/HDL Ratio", value=3.0)
|
| 666 |
-
apo_a1 = gr.Number(label="Apo A1 (mg/dL)", value=140)
|
| 667 |
-
apo_b = gr.Number(label="Apo B (mg/dL)", value=90)
|
| 668 |
-
apo_ratio = gr.Number(label="Apo A1/B Ratio", value=1.55)
|
| 669 |
-
|
| 670 |
-
with gr.Accordion("🔥 Inflammation & Others", open=False):
|
| 671 |
-
hs_crp = gr.Number(label="hs-CRP (mg/L)", value=1.0)
|
| 672 |
-
homocysteine = gr.Number(label="Homocysteine (μmol/L)", value=10)
|
| 673 |
-
ferritin = gr.Number(label="Ferritin (ng/mL)", value=100)
|
| 674 |
-
ck = gr.Number(label="CK (U/L)", value=150)
|
| 675 |
-
ck_mb = gr.Number(label="CK-MB (ng/mL)", value=5)
|
| 676 |
-
zinc = gr.Number(label="Zinc (µg/dL)", value=90)
|
| 677 |
-
copper = gr.Number(label="Copper (µg/dL)", value=110)
|
| 678 |
-
selenium = gr.Number(label="Selenium (µg/L)", value=120)
|
| 679 |
-
iron = gr.Number(label="Iron (µg/dL)", value=80)
|
| 680 |
-
tibc = gr.Number(label="TIBC (µg/dL)", value=300)
|
| 681 |
-
transferrin = gr.Number(label="Transferrin (mg/dL)", value=250)
|
| 682 |
-
allergy_panel = gr.Number(label="Allergy Panel Score", value=0)
|
| 683 |
-
|
| 684 |
-
with gr.Accordion("🌡️ Hormones & Vitamins", open=False):
|
| 685 |
-
tsh = gr.Number(label="TSH (μIU/mL)", value=2.0)
|
| 686 |
-
free_t3 = gr.Number(label="Free T3 (pg/mL)", value=3.2)
|
| 687 |
-
free_t4 = gr.Number(label="Free T4 (ng/dL)", value=1.2)
|
| 688 |
-
total_t3 = gr.Number(label="Total T3 (ng/dL)", value=1.3)
|
| 689 |
-
total_t4 = gr.Number(label="Total T4 (µg/dL)", value=7.8)
|
| 690 |
-
reverse_t3 = gr.Number(label="Reverse T3 (ng/dL)", value=15)
|
| 691 |
-
tpo_ab = gr.Number(label="TPO Ab (IU/mL)", value=10)
|
| 692 |
-
tg_ab = gr.Number(label="TG Ab (IU/mL)", value=12)
|
| 693 |
-
total_testosterone = gr.Number(label="Total Testosterone (ng/dL)", value=500)
|
| 694 |
-
free_testosterone = gr.Number(label="Free Testosterone (ng/dL)", value=15)
|
| 695 |
-
estrogen = gr.Number(label="Estrogen (pg/mL)", value=50)
|
| 696 |
-
progesterone = gr.Number(label="Progesterone (ng/mL)", value=1.2)
|
| 697 |
-
dhea_s = gr.Number(label="DHEA-S (µg/dL)", value=200)
|
| 698 |
-
shbg = gr.Number(label="SHBG (nmol/L)", value=40)
|
| 699 |
-
lh = gr.Number(label="LH (mIU/mL)", value=5)
|
| 700 |
-
fsh = gr.Number(label="FSH (mIU/mL)", value=6)
|
| 701 |
-
cortisol = gr.Number(label="Cortisol (µg/dL)", value=12)
|
| 702 |
-
acth = gr.Number(label="ACTH (pg/mL)", value=25)
|
| 703 |
-
igf1 = gr.Number(label="IGF-1 (ng/mL)", value=150)
|
| 704 |
-
leptin = gr.Number(label="Leptin (ng/mL)", value=10)
|
| 705 |
-
adiponectin = gr.Number(label="Adiponectin (µg/mL)", value=8)
|
| 706 |
-
|
| 707 |
-
with gr.Accordion("🧬 Tumor Markers", open=False):
|
| 708 |
-
ca125 = gr.Number(label="CA-125 (U/mL)", value=20)
|
| 709 |
-
ca15_3 = gr.Number(label="CA 15-3 (U/mL)", value=25)
|
| 710 |
-
ca19_9 = gr.Number(label="CA 19-9 (U/mL)", value=15)
|
| 711 |
-
psa = gr.Number(label="PSA (ng/mL)", value=2.0)
|
| 712 |
-
cea = gr.Number(label="CEA (ng/mL)", value=3.0)
|
| 713 |
-
calcitonin = gr.Number(label="Calcitonin (pg/mL)", value=5)
|
| 714 |
-
afp = gr.Number(label="AFP (ng/mL)", value=10)
|
| 715 |
-
|
| 716 |
-
with gr.Accordion("🧪 Immunology", open=False):
|
| 717 |
-
tnf = gr.Number(label="TNF-α (pg/mL)", value=10)
|
| 718 |
-
ana = gr.Number(label="ANA (IU/mL)", value=5)
|
| 719 |
-
ige = gr.Number(label="IgE (IU/mL)", value=100)
|
| 720 |
-
igg = gr.Number(label="IgG (IU/mL)", value=1200)
|
| 721 |
-
anti_ccp = gr.Number(label="Anti-CCP (U/mL)", value=5)
|
| 722 |
-
dsdna = gr.Number(label="dsDNA (IU/mL)", value=10)
|
| 723 |
-
ssa_ssb = gr.Number(label="SSA/SSB (U/mL)", value=10)
|
| 724 |
-
rnp = gr.Number(label="RNP (U/mL)", value=5)
|
| 725 |
-
sm_antibodies = gr.Number(label="Sm Antibodies (U/mL)", value=5)
|
| 726 |
-
anca = gr.Number(label="ANCA (U/mL)", value=5)
|
| 727 |
-
anti_ena = gr.Number(label="Anti-ENA (U/mL)", value=5)
|
| 728 |
-
il6 = gr.Number(label="IL-6 (pg/mL)", value=5)
|
| 729 |
-
|
| 730 |
-
submit_btn = gr.Button("🧠 Generate Comprehensive Medical Report", variant="primary", size="lg")
|
| 731 |
-
output_md = gr.Markdown(label="AI-Generated Medical Report")
|
| 732 |
-
|
| 733 |
-
submit_btn.click(
|
| 734 |
-
fn=gradio_interface,
|
| 735 |
-
inputs=[
|
| 736 |
-
age, gender, height, weight,
|
| 737 |
-
urea, creatinine, uric_acid, calcium, phosphorus, sodium, potassium, chloride,
|
| 738 |
-
amylase, lipase, bicarbonate, egfr, serum_osmolality, ionized_calcium,
|
| 739 |
-
wbc, hemoglobin, mcv, rdw, lymphocytes,
|
| 740 |
-
fasting_blood_sugar, hb1ac, insulin, c_peptide, homa_ir,
|
| 741 |
-
total_cholesterol, ldl, hdl, cholesterol_hdl_ratio, triglycerides, apo_a1, apo_b, apo_ratio,
|
| 742 |
-
albumin, total_protein, alt, ast, alp, ggt, ld, globulin, albumin_globulin_ratio,
|
| 743 |
-
magnesium, total_bilirubin, direct_bilirubin, indirect_bilirubin, ammonia,
|
| 744 |
-
hs_crp, ck, ck_mb, homocysteine, zinc, copper, selenium,
|
| 745 |
-
iron, tibc, transferrin,
|
| 746 |
-
vitamin_d, vitamin_b12,
|
| 747 |
-
total_testosterone, free_testosterone, estrogen, progesterone, dhea_s, shbg,
|
| 748 |
-
lh, fsh, tsh, free_t3, free_t4, total_t3, total_t4, reverse_t3, tpo_ab, tg_ab,
|
| 749 |
-
cortisol, acth, igf1, leptin, adiponectin,
|
| 750 |
-
ca125, ca15_3, ca19_9, psa, cea, calcitonin, afp,
|
| 751 |
-
tnf, ana, ige, igg, anti_ccp, dsdna, ssa_ssb, rnp, sm_antibodies, anca, anti_ena,
|
| 752 |
-
il6, allergy_panel
|
| 753 |
-
],
|
| 754 |
-
outputs=output_md
|
| 755 |
-
)
|
| 756 |
-
|
| 757 |
-
if __name__ == "__main__":
|
| 758 |
-
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from pydantic import BaseModel, Field
|
| 3 |
+
from typing import Dict, Any, Union, List
|
| 4 |
+
import re
|
| 5 |
+
import os
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
import google.generativeai as genai
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# ---------------- Load env ----------------
|
| 10 |
# load_dotenv()
|
|
|
|
|
|
|
| 11 |
GEMINI_API_KEY = "AIzaSyAJ3aMnwOHsLtU1JoudCRIFdZhm6s4oNhY"
|
| 12 |
if not GEMINI_API_KEY:
|
| 13 |
+
raise ValueError("❌ GEMINI_API_KEY not found.")
|
| 14 |
|
|
|
|
| 15 |
genai.configure(api_key=GEMINI_API_KEY)
|
| 16 |
MODEL_ID = "gemini-2.5-flash"
|
| 17 |
|
|
|
|
| 18 |
# ---------------- Schema ----------------
|
| 19 |
class BiomarkerRequest(BaseModel):
|
| 20 |
+
age: int = Field(default=52)
|
| 21 |
+
gender: str = Field(default="female")
|
| 22 |
+
fasting_blood_sugar: float = Field(default=85.0)
|
| 23 |
+
hb1ac: float = Field(default=5.4)
|
| 24 |
+
insulin: float = Field(default=10.0)
|
| 25 |
+
c_peptide: float = Field(default=1.2)
|
| 26 |
+
homa_ir: float = Field(default=1.2)
|
| 27 |
+
total_cholesterol: float = Field(default=180.0)
|
| 28 |
+
ldl: float = Field(default=90.0)
|
| 29 |
+
hdl: float = Field(default=50.0)
|
| 30 |
+
triglycerides: float = Field(default=120.0)
|
| 31 |
+
apo_b: float = Field(default=70.0)
|
| 32 |
+
cholesterol_hdl_ratio: float = Field(default=3.0)
|
| 33 |
+
hs_crp: float = Field(default=1.0)
|
| 34 |
+
homocysteine: float = Field(default=10.0)
|
| 35 |
+
alt: float = Field(default=25.0)
|
| 36 |
+
ast: float = Field(default=24.0)
|
| 37 |
+
ggt: float = Field(default=20.0)
|
| 38 |
+
total_bilirubin: float = Field(default=0.7)
|
| 39 |
+
total_protein: float = Field(default=7.0)
|
| 40 |
+
creatinine: float = Field(default=1.0)
|
| 41 |
+
egfr: float = Field(default=100.0)
|
| 42 |
+
uric_acid: float = Field(default=5.0)
|
| 43 |
+
vitamin_d: float = Field(default=35.0)
|
| 44 |
+
vitamin_b12: float = Field(default=500.0)
|
| 45 |
+
iron: float = Field(default=100.0)
|
| 46 |
+
zinc: float = Field(default=90.0)
|
| 47 |
+
tsh: float = Field(default=2.0)
|
| 48 |
+
free_t3: float = Field(default=3.2)
|
| 49 |
+
free_t4: float = Field(default=1.2)
|
| 50 |
+
total_testosterone: float = Field(default=450.0)
|
| 51 |
+
free_testosterone: float = Field(default=15.0)
|
| 52 |
+
estrogen: float = Field(default=60.0)
|
| 53 |
+
shbg: float = Field(default=40.0)
|
| 54 |
+
cortisol: float = Field(default=12.0)
|
| 55 |
+
dhea_s: float = Field(default=250.0)
|
| 56 |
+
anti_ccp: float = Field(default=10.0)
|
| 57 |
+
|
| 58 |
+
# ---------------- Cleaning ----------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
def clean_json(data: Union[Dict, List, str]) -> Union[Dict, List, str]:
|
|
|
|
| 60 |
if isinstance(data, str):
|
| 61 |
text = re.sub(r"-{3,}", "", data)
|
| 62 |
text = re.sub(r"\s+", " ", text)
|
| 63 |
+
return text.strip(" -\n\t\r")
|
|
|
|
| 64 |
elif isinstance(data, list):
|
| 65 |
return [clean_json(i) for i in data if i and clean_json(i)]
|
| 66 |
elif isinstance(data, dict):
|
| 67 |
return {k.strip(): clean_json(v) for k, v in data.items()}
|
| 68 |
return data
|
| 69 |
|
|
|
|
| 70 |
# ---------------- Parser ----------------
|
| 71 |
def parse_medical_report(text: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def clean_line(line: str) -> str:
|
| 73 |
return re.sub(r"[\-\*\u2022]+\s*", "", line.strip())
|
| 74 |
|
| 75 |
def parse_bold_entities(block: str) -> Dict[str, str]:
|
|
|
|
| 76 |
entities = {}
|
| 77 |
pattern = re.compile(r"\*\*(.*?)\*\*(.*?)(?=\*\*|###|$)", re.S)
|
| 78 |
for match in pattern.finditer(block):
|
|
|
|
| 92 |
"biomarker_table": []
|
| 93 |
}
|
| 94 |
|
|
|
|
| 95 |
exec_match = re.search(r"###\s*Executive Summary(.*?)(?=###|$)", text, re.S | re.I)
|
| 96 |
if exec_match:
|
| 97 |
block = exec_match.group(1)
|
|
|
|
| 104 |
strengths = [clean_line(s) for s in strengths_text.splitlines() if clean_line(s)]
|
| 105 |
data["executive_summary"]["key_strengths"] = strengths
|
| 106 |
|
|
|
|
| 107 |
sys_match = re.search(r"###\s*System[- ]Specific Analysis(.*?)(?=###|$)", text, re.S | re.I)
|
| 108 |
if sys_match:
|
| 109 |
sys_block = sys_match.group(1)
|
| 110 |
data["system_analysis"] = parse_bold_entities(sys_block)
|
| 111 |
|
|
|
|
| 112 |
plan_match = re.search(r"###\s*Personalized Action Plan(.*?)(?=###|$)", text, re.S | re.I)
|
| 113 |
if plan_match:
|
| 114 |
plan_block = plan_match.group(1)
|
| 115 |
data["personalized_action_plan"] = parse_bold_entities(plan_block)
|
| 116 |
|
|
|
|
| 117 |
alerts_match = re.search(r"###\s*Interaction Alerts(.*?)(?=###|$)", text, re.S | re.I)
|
| 118 |
if alerts_match:
|
| 119 |
alerts_block = alerts_match.group(1)
|
| 120 |
+
data["interaction_alerts"] = [clean_line(a) for a in alerts_block.splitlines() if clean_line(a)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
return data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
# ---------------- Gradio Function ----------------
|
| 125 |
+
def run_biomarker_analysis(**inputs):
|
| 126 |
+
try:
|
| 127 |
+
user_data = BiomarkerRequest(**inputs)
|
| 128 |
+
user_message = f"""
|
| 129 |
+
**Patient Info**
|
| 130 |
+
- Age: {user_data.age}
|
| 131 |
+
- Gender: {user_data.gender}
|
| 132 |
|
| 133 |
+
**Metabolic & Glycemic Control**
|
| 134 |
+
- Fasting Blood Sugar: {user_data.fasting_blood_sugar} mg/dL
|
| 135 |
+
- HbA1c: {user_data.hb1ac} %
|
| 136 |
+
- Insulin: {user_data.insulin} µIU/mL
|
| 137 |
+
- C-Peptide: {user_data.c_peptide} ng/mL
|
| 138 |
+
- HOMA-IR: {user_data.homa_ir}
|
| 139 |
+
- Leptin: {user_data.leptin} ng/mL
|
|
|
|
| 140 |
|
| 141 |
+
**Cardiovascular System**
|
| 142 |
+
- Total Cholesterol: {user_data.total_cholesterol} mg/dL
|
| 143 |
+
- LDL: {user_data.ldl} mg/dL
|
| 144 |
+
- HDL: {user_data.hdl} mg/dL
|
| 145 |
+
- Triglycerides: {user_data.triglycerides} mg/dL
|
| 146 |
+
- ApoB: {user_data.apo_b} mg/dL
|
| 147 |
+
- Cholesterol/HDL Ratio: {user_data.cholesterol_hdl_ratio}
|
| 148 |
+
- hs-CRP: {user_data.hs_crp} mg/L
|
| 149 |
+
- Homocysteine: {user_data.homocysteine} µmol/L
|
| 150 |
|
| 151 |
+
**Liver Function**
|
| 152 |
+
- ALT: {user_data.alt} U/L
|
| 153 |
+
- AST: {user_data.ast} U/L
|
| 154 |
+
- GGT: {user_data.ggt} U/L
|
| 155 |
+
- Total Bilirubin: {user_data.total_bilirubin} mg/dL
|
| 156 |
+
- Total Protein: {user_data.total_protein} g/dL
|
| 157 |
|
| 158 |
+
**Renal Function**
|
| 159 |
+
- Creatinine: {user_data.creatinine} mg/dL
|
| 160 |
+
- eGFR: {user_data.egfr} mL/min/1.73m2
|
| 161 |
+
- Uric Acid: {user_data.uric_acid} mg/dL
|
| 162 |
+
"""
|
|
|
|
| 163 |
prompt = """
|
| 164 |
You are an advanced **Medical Insight Generation AI** trained to analyze **biomarkers and lab results**.
|
|
|
|
| 165 |
⚠️ IMPORTANT — OUTPUT FORMAT INSTRUCTIONS:
|
| 166 |
Return your report in this strict markdown structure.
|
|
|
|
| 167 |
------------------------------
|
| 168 |
### Executive Summary
|
| 169 |
**Top 3 Health Priorities:**
|
|
|
|
| 171 |
2. ...
|
| 172 |
3. ...
|
| 173 |
make it more detailed
|
|
|
|
| 174 |
**Key Strengths:**
|
| 175 |
- ...
|
| 176 |
- ...
|
| 177 |
make it detailed
|
| 178 |
------------------------------
|
| 179 |
### System-Specific Analysis
|
|
|
|
| 180 |
**Cardiovascular System**
|
| 181 |
Status: Normal. Explanation: Lipid profile including Total Cholesterol, LDL, HDL, Triglycerides, Apo A-1, Apo B, Apo Ratio, and Cholesterol/HDL Ratio are within reference ranges, indicating low risk of atherosclerosis, coronary artery disease, and other cardiovascular disorders. hs-CRP, CK, CK-MB, and Homocysteine levels are normal, reflecting minimal systemic inflammation and proper myocardial health.
|
|
|
|
| 182 |
**Metabolic & Glycemic Control**
|
| 183 |
Status: Normal. Explanation: Fasting Blood Sugar, HbA1c, Insulin, C-Peptide, and HOMA-IR are within healthy ranges, suggesting effective glucose metabolism, insulin sensitivity, and low risk of prediabetes or diabetes.
|
|
|
|
| 184 |
**Liver Function**
|
| 185 |
Status: Normal. Explanation: ALT, AST, ALP, GGT, LDH, Total Bilirubin, Direct and Indirect Bilirubin, Albumin, Globulin, Albumin/Globulin Ratio, Total Protein, Ammonia, and Magnesium are within reference ranges, reflecting normal hepatocellular integrity, protein synthesis, and biliary excretion. Abnormalities could indicate hepatic injury, cholestasis, or metabolic liver disorders.
|
|
|
|
| 186 |
**Renal Function**
|
| 187 |
Status: Normal. Explanation: Urea, Creatinine, eGFR, Uric Acid, Sodium, Potassium, Chloride, Phosphorus, Calcium, Ionized Calcium, Bicarbonate, Serum Osmolality, Amylase, and Lipase are within expected ranges, suggesting proper kidney filtration, electrolyte balance, and pancreatic enzyme activity. Deviations may indicate renal impairment, electrolyte disorders, or pancreatitis risk.
|
|
|
|
| 188 |
**Thyroid Function**
|
| 189 |
Status: Normal. Explanation: TSH, Free T3, Free T4, Total T3, Total T4, Reverse T3, TPO Ab, and TG Ab are within reference limits, showing normal thyroid hormone production, peripheral conversion, and autoimmune status. Abnormal levels may indicate hypothyroidism, hyperthyroidism, or thyroid autoimmunity.
|
|
|
|
| 190 |
**Adrenal & Stress Hormones**
|
| 191 |
Status: Normal. Explanation: Cortisol, ACTH, DHEA-S, IGF-1, Leptin, and Adiponectin are within normal ranges, reflecting healthy adrenal function, stress response, metabolic regulation, and energy homeostasis. Abnormalities could indicate adrenal insufficiency, Cushing’s syndrome, metabolic disorders, or leptin/adiponectin imbalance.
|
|
|
|
| 192 |
**Sex Hormones & Reproductive Health**
|
| 193 |
Status: Normal. Explanation: Total Testosterone, Free Testosterone, SHBG, Estrogen, Progesterone, LH, and FSH are within expected ranges based on gender and menstrual cycle, indicating balanced gonadal function, fertility potential, and hormonal homeostasis. Deviations may impact reproductive function, libido, or secondary sexual characteristics.
|
|
|
|
| 194 |
**Vitamins & Minerals**
|
| 195 |
Status: Normal. Explanation: Vitamin D, Vitamin B12, Iron, TIBC, Transferrin, Zinc, Copper, Selenium, and Magnesium are within reference ranges, supporting optimal hematologic function, enzymatic reactions, immune defense, and bone health. Deficiencies may lead to anemia, metabolic disturbances, or immune dysfunction.
|
|
|
|
| 196 |
**Hematology & Immune Function**
|
| 197 |
Status: Normal. Explanation: Hemoglobin, MCV, RDW, WBC, Lymphocytes, Albumin, Globulin, ANA, IgE, IgG, Anti-CCP, dsDNA, SSA/SSB, RNP, Sm Antibodies, ANCA, Anti-ENA, IL-6, and Allergy Panel are within normal limits, indicating proper oxygen transport, red blood cell morphology, and immune competence. Deviations could indicate anemia, infection, inflammation, or autoimmune conditions.
|
|
|
|
| 198 |
**Cancer Markers**
|
| 199 |
Status: Normal. Explanation: CA125, CA15-3, CA19-9, PSA, CEA, AFP, Calcitonin, and TNF are within reference ranges, suggesting low risk for malignancy or tumor activity. Elevated values may require further imaging or diagnostic evaluation.
|
|
|
|
| 200 |
**Inflammatory Markers**
|
| 201 |
Status: Normal. Explanation: hs-CRP, IL-6, and Homocysteine are within recommended ranges, reflecting low systemic inflammation and minimal cardiovascular or metabolic risk. Elevations may indicate chronic inflammation, autoimmune activity, or thrombotic risk.
|
|
|
|
| 202 |
------------------------------
|
| 203 |
### Personalized Action Plan
|
| 204 |
**Nutrition:** ...
|
|
|
|
| 233 |
- Ionized Calcium: 1.12–1.32 mmol/L
|
| 234 |
- Amylase (S): 23–85 U/L
|
| 235 |
- Lipase (S): 0–160 U/L
|
|
|
|
| 236 |
# Basic Checkup
|
| 237 |
- WBC: 4–10 ×10^3/μL
|
| 238 |
- Hemoglobin: 13–17 g/dL
|
| 239 |
- MCV: 80–100 fL
|
| 240 |
- RDW: 11.5–14.5 %
|
| 241 |
- Lymphocytes: 20–40 %
|
|
|
|
| 242 |
# Diabetic Profile
|
| 243 |
- Fasting Blood Sugar: 70–99 mg/dL
|
| 244 |
- HbA1c: <5.7 %
|
| 245 |
- Insulin: 2–20 µIU/mL
|
| 246 |
- C-Peptide: 0.5–2.0 ng/mL
|
| 247 |
- HOMA-IR: <1 Optimal, 1–2 Normal, >2 Insulin Resistance
|
|
|
|
| 248 |
# Lipid Profile
|
| 249 |
- Total Cholesterol: <200 mg/dL
|
| 250 |
- LDL: <100 mg/dL
|
|
|
|
| 255 |
- Apo B: <90 mg/dL
|
| 256 |
- Apo B/A1 ratio: 0.3–0.7
|
| 257 |
- Cholesterol/HDL Ratio: <3.5 Optimal
|
|
|
|
| 258 |
# Liver Function
|
| 259 |
- Albumin: 3.5–5.0 g/dL
|
| 260 |
- Total Protein: 6.0–8.3 g/dL
|
|
|
|
| 270 |
- Direct Bilirubin: 0.0–0.3 mg/dL
|
| 271 |
- Indirect Bilirubin: 0.2–0.9 mg/dL
|
| 272 |
- Ammonia: 15–45 µmol/L
|
|
|
|
| 273 |
# Cardiac Profile
|
| 274 |
- hs-CRP: 1–3 mg/L
|
| 275 |
- CK: 40–200 U/L
|
| 276 |
- CK-MB: 0–25 U/L
|
| 277 |
- Homocysteine: 5–15 µmol/L
|
|
|
|
| 278 |
# Minerals & Heavy Metals
|
| 279 |
- Zinc: 70–120 µg/dL
|
| 280 |
- Copper: 70–140 µg/dL
|
| 281 |
- Selenium: 70–150 µg/L
|
|
|
|
| 282 |
# Iron Profile
|
| 283 |
- Iron (Men): 60–170 µg/dL
|
| 284 |
- Iron (Women): 50–170 µg/dL
|
| 285 |
- TIBC: 250–450 µg/dL
|
| 286 |
- Transferrin: 200–360 mg/dL
|
|
|
|
| 287 |
# Vitamins
|
| 288 |
- Vitamin D: 30–60 ng/mL
|
| 289 |
- Vitamin B12: 200–900 pg/mL
|
|
|
|
| 290 |
# Hormones
|
| 291 |
- Total Testosterone (Men): 300–1000 ng/dL
|
| 292 |
- Total Testosterone (Women): 15–70 ng/dL
|
|
|
|
| 310 |
- Leptin (Men): 0.5–8 ng/mL
|
| 311 |
- Leptin (Women): 5–25 ng/mL
|
| 312 |
- Adiponectin: 5–30 µg/mL
|
|
|
|
| 313 |
# Thyroid
|
| 314 |
- TSH: 0.4–4.0 µIU/mL
|
| 315 |
- Free T3: 2.0–4.4 pg/mL
|
|
|
|
| 319 |
- Reverse T3: 9–24 ng/dL
|
| 320 |
- TPO Ab: <35 IU/mL
|
| 321 |
- TG Ab: <40 IU/mL
|
|
|
|
| 322 |
# Cancer Markers
|
| 323 |
- CA125: <35 U/mL
|
| 324 |
- CA15-3: <30 U/mL
|
|
|
|
| 328 |
- Calcitonin: <10 pg/mL
|
| 329 |
- AFP: <10 ng/mL
|
| 330 |
- TNF: <8 pg/m
|
|
|
|
|
|
|
|
|
|
| 331 |
------------------------------
|
| 332 |
### Tabular Mapping
|
| 333 |
| Biomarker | Value | Status | Insight | Reference Range |
|
|
|
|
| 337 |
------------------------------
|
| 338 |
"""
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
model = genai.GenerativeModel(MODEL_ID)
|
| 341 |
response = model.generate_content(f"{prompt}\n\n{user_message}")
|
|
|
|
| 342 |
if not response or not getattr(response, "text", None):
|
| 343 |
+
return "❌ Empty response from model."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
+
parsed = parse_medical_report(response.text)
|
| 346 |
+
cleaned = clean_json(parsed)
|
| 347 |
+
return cleaned
|
| 348 |
except Exception as e:
|
| 349 |
+
return f"Error: {str(e)}"
|
| 350 |
+
|
| 351 |
+
# ---------------- Gradio Interface ----------------
|
| 352 |
+
# Create input widgets dynamically based on BiomarkerRequest fields
|
| 353 |
+
inputs = {field: gr.Number(value=getattr(BiomarkerRequest, field).default)
|
| 354 |
+
for field in BiomarkerRequest.__fields__}
|
| 355 |
+
|
| 356 |
+
gr.Interface(
|
| 357 |
+
fn=run_biomarker_analysis,
|
| 358 |
+
inputs=inputs,
|
| 359 |
+
outputs=gr.JSON(label="Medical Insights"),
|
| 360 |
+
title="Complete Biomarker AI Medical Analyzer",
|
| 361 |
+
description="Input patient biomarker values and receive detailed AI-generated medical insights.",
|
| 362 |
+
live=False
|
| 363 |
+
).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|