File size: 26,671 Bytes
d42153e
4964d3e
d42153e
dad7343
0fca7f9
d42153e
 
 
 
 
 
 
dad7343
 
 
d42153e
dad7343
f93852a
4964d3e
 
d42153e
 
f93852a
 
d42153e
 
 
 
 
 
 
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
f93852a
 
d42153e
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
f93852a
 
d42153e
 
 
f93852a
 
d42153e
 
f93852a
 
d42153e
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
 
f93852a
 
d42153e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3424ef
d42153e
 
 
 
 
e3424ef
 
 
77e66ec
 
 
 
 
e3424ef
 
 
 
 
821268e
e3424ef
 
 
 
 
 
 
 
 
 
 
 
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
e3424ef
77e66ec
 
 
 
 
 
 
 
 
 
67daaa7
a954590
e3424ef
94deb4e
 
e3424ef
94deb4e
e3424ef
94deb4e
e3424ef
94deb4e
e3424ef
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
36b91dc
e3424ef
 
 
 
36b91dc
e3424ef
 
 
 
 
36b91dc
e3424ef
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
36b91dc
e3424ef
 
 
 
 
 
 
 
 
36b91dc
e3af937
 
 
 
 
 
 
 
 
 
 
 
 
36b91dc
29b5702
 
 
 
 
 
 
 
 
e3424ef
 
 
77e66ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3424ef
 
 
 
d42153e
e3424ef
 
d42153e
 
 
f93852a
4964d3e
d42153e
f93852a
d42153e
 
f93852a
 
 
 
 
 
 
 
d42153e
f93852a
 
d42153e
 
f93852a
d42153e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3634697
d42153e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7e224
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
from fastapi import FastAPI
from pydantic import BaseModel, Field
import gradio as gr
import google.generativeai as genai

# ---------------- Initialize ----------------
app = FastAPI(title="LLM Model API + Gradio UI", version="4.0")

GEMINI_API_KEY='AIzaSyAtUi_DukKWIFVoze9cvlGnlP60eW0NzOg'
if not GEMINI_API_KEY:
    raise ValueError("❌ GEMINI_API_KEY not found.")

genai.configure(api_key=GEMINI_API_KEY)
MODEL_ID = "gemini-2.5-flash"

# ---------------- Schema ----------------
class BiomarkerRequest(BaseModel):
    # Demographics
    age: int = Field(default=52)
    gender: str = Field(default="female")
    height: float = Field(default=165)
    weight: float = Field(default=70)

    # Kidney / Electrolytes
    urea: float = Field(default=25.0)
    creatinine: float = Field(default=1.0)
    uric_acid: float = Field(default=5.0)
    calcium: float = Field(default=9.5)
    phosphorus: float = Field(default=3.5)
    sodium: float = Field(default=140.0)
    potassium: float = Field(default=4.2)
    chloride: float = Field(default=100.0)
    bicarbonate: float = Field(default=24.0)
    egfr: float = Field(default=100.0)
    serum_osmolality: float = Field(default=285.0)
    ionized_calcium: float = Field(default=1.2)
    amylase: float = Field(default=50.0)
    lipase: float = Field(default=50.0)

    # Hematology
    wbc: float = Field(default=6.0)
    hemoglobin: float = Field(default=14.0)
    mcv: float = Field(default=90.0)
    rdw: float = Field(default=13.0)
    lymphocytes: float = Field(default=30.0)

    # Glycemic / Metabolic
    fasting_blood_sugar: float = Field(default=85.0)
    hb1ac: float = Field(default=5.4)
    insulin: float = Field(default=10.0)
    c_peptide: float = Field(default=1.2)
    homa_ir: float = Field(default=1.2)

    # Lipid Profile
    total_cholesterol: float = Field(default=180.0)
    ldl: float = Field(default=90.0)
    hdl: float = Field(default=50.0)
    cholesterol_hdl_ratio: float = Field(default=3.0)
    triglycerides: float = Field(default=120.0)
    apo_a1: float = Field(default=150.0)
    apo_b: float = Field(default=70.0)
    apo_ratio: float = Field(default=0.5)

    # Liver
    albumin: float = Field(default=4.5)
    total_protein: float = Field(default=7.0)
    alt: float = Field(default=25.0)
    ast: float = Field(default=24.0)
    alp: float = Field(default=80.0)
    ggt: float = Field(default=20.0)
    ld: float = Field(default=180.0)
    globulin: float = Field(default=2.5)
    albumin_globulin_ratio: float = Field(default=1.8)
    magnesium: float = Field(default=2.0)
    total_bilirubin: float = Field(default=0.7)
    direct_bilirubin: float = Field(default=0.2)
    indirect_bilirubin: float = Field(default=0.5)
    ammonia: float = Field(default=30.0)

    # Cardiac / Inflammation
    hs_crp: float = Field(default=1.0)
    ck: float = Field(default=100.0)
    ck_mb: float = Field(default=10.0)
    homocysteine: float = Field(default=10.0)
    zinc: float = Field(default=90.0)
    copper: float = Field(default=100.0)
    selenium: float = Field(default=100.0)

    # Iron / Minerals
    iron: float = Field(default=100.0)
    tibc: float = Field(default=350.0)
    transferrin: float = Field(default=250.0)

    # Vitamins
    vitamin_d: float = Field(default=35.0)
    vitamin_b12: float = Field(default=500.0)

    # Sex Hormones
    total_testosterone: float = Field(default=450.0)
    free_testosterone: float = Field(default=15.0)
    estrogen: float = Field(default=60.0)
    progesterone: float = Field(default=1.0)
    dhea_s: float = Field(default=250.0)
    shbg: float = Field(default=40.0)
    lh: float = Field(default=5.0)
    fsh: float = Field(default=6.0)

    # Thyroid
    tsh: float = Field(default=2.0)
    free_t3: float = Field(default=3.2)
    free_t4: float = Field(default=1.2)
    total_t3: float = Field(default=120.0)
    total_t4: float = Field(default=8.0)
    reverse_t3: float = Field(default=15.0)
    tpo_ab: float = Field(default=20.0)
    tg_ab: float = Field(default=20.0)

    # Adrenal / Stress
    cortisol: float = Field(default=12.0)
    acth: float = Field(default=30.0)
    igf1: float = Field(default=200.0)
    leptin: float = Field(default=15.0)
    adiponectin: float = Field(default=15.0)

    # Cancer markers
    ca125: float = Field(default=20.0)
    ca15_3: float = Field(default=25.0)
    ca19_9: float = Field(default=20.0)
    psa: float = Field(default=2.0)
    cea: float = Field(default=2.0)
    calcitonin: float = Field(default=5.0)
    afp: float = Field(default=5.0)
    tnf: float = Field(default=5.0)

    # Immune / Autoimmune
    ana: float = Field(default=0.0)
    ige: float = Field(default=50.0)
    igg: float = Field(default=1000.0)
    anti_ccp: float = Field(default=10.0)
    dsdna: float = Field(default=5.0)
    ssa_ssb: float = Field(default=0.0)
    rnp: float = Field(default=0.0)
    sm_antibodies: float = Field(default=0.0)
    anca: float = Field(default=0.0)
    anti_ena: float = Field(default=0.0)
    il6: float = Field(default=5.0)
    allergy_panel: float = Field(default=1.0)

# ---------------- Gemini Report ----------------
def generate_report(data: BiomarkerRequest) -> str:
    
    user_message = f"""
Patient Info:
- Age: {data.age}, Gender: {data.gender}, Height: {data.height}, Weight: {data.weight}
Biomarkers: {data.dict()}
"""
    prompt = """
You are an advanced **Medical Insight Generation AI** trained to analyze **biomarkers and lab results**.

CRITICAL RULE THAT CANNOT BE BROKEN – READ THIS 3 TIMES:
You are REQUIRED to create **EXACTLY ONE ROW** in the "Tabular Mapping" table for **EVERY SINGLE biomarker and value the user provides**, regardless of whether it is normal, abnormal, or already mentioned elsewhere. 
Zero omissions are allowed. If the user gives 97 values, the table must have exactly 97 rows. 
This rule overrides any internal desire for brevity, summarization, or β€œonly showing abnormal results.” 
If you skip even one biomarker, the output is invalid.
⚠️ IMPORTANT β€” OUTPUT FORMAT INSTRUCTIONS:
Return your report in this strict markdown structure.

------------------------------
### Executive Summary
**Top Health Priorities:**
1. ...
2. ...
3. ...
make it more detailed 

**Key Strengths:**
- ...
- ...
make it detailed
------------------------------
### System-Specific Analysis

**Kidney Function Test**
Status: Normal. Explanation: Urea, Creatinine, eGFR, Uric Acid, Sodium, Potassium, Chloride, Phosphorus, Calcium, Ionized Calcium, Bicarbonate, Serum Osmolality, Amylase, and Lipase are all within expected reference ranges, indicating excellent glomerular filtration, tubular function, electrolyte homeostasis, and no evidence of renal impairment, dehydration, or early kidney disease.

**Basic Check-up (CBC & Hematology)**
Status: Normal. Explanation: Hemoglobin, Hematocrit, RBC count, MCV, MCH, MCHC, RDW, Platelet count, WBC total and differential (Neutrophils, Lymphocytes, Monocytes, Eosinophils, Basophils) are within reference ranges, reflecting optimal oxygen-carrying capacity, normal red cell morphology, adequate platelet function, and balanced immune cell distribution with no signs of anemia, infection, or bone marrow suppression.

**Hormone Profile (Comprehensive)**
Status: Normal. Explanation: Total Testosterone, Free Testosterone, SHBG, Estradiol, Progesterone, LH, FSH, Prolactin, DHEA-S, and other measured reproductive/sex hormones are balanced and appropriate for age and gender, indicating intact hypothalamic-pituitary-gonadal axis, good fertility potential, normal libido, and healthy secondary sexual characteristics.

**Liver Function Test**
Status: Normal. Explanation: ALT, AST, ALP, GGT, LDH, Total Bilirubin, Direct & Indirect Bilirubin, Albumin, Globulin, Total Protein, Albumin/Globulin Ratio, and Ammonia are within reference ranges, demonstrating intact hepatocyte integrity, normal synthetic function, protein metabolism, and biliary excretion with no evidence of hepatic injury, cholestasis, cirrhosis, or metabolic liver disease.

**Diabetic Profile**
Status: Normal. Explanation: Fasting Blood Glucose, HbA1c, Fasting Insulin, C-Peptide, and HOMA-IR are all within optimal ranges, confirming excellent glycemic control, high insulin sensitivity, proper pancreatic beta-cell function, and very low risk of prediabetes or type 2 diabetes.

**Lipid Profile**
Status: Normal. Explanation: Total Cholesterol, LDL-C, HDL-C, Triglycerides, Non-HDL Cholesterol, Apo A-1, Apo B, Apo B/Apo A-1 Ratio, and Cholesterol/HDL Ratio are optimal, indicating low atherogenic risk, excellent cardiovascular protection, and minimal likelihood of plaque formation or coronary artery disease.

**Cardiac Profile**
Status: Normal. Explanation: hs-CRP, CK, CK-MB, Homocysteine, NT-proBNP (if measured), and other cardiac injury/inflammation markers are within normal limits, reflecting minimal systemic inflammation, healthy myocardial tissue, low thrombotic risk, and excellent long-term cardiovascular prognosis.

**Mineral & Heavy Metal**
Status: Normal. Explanation: Zinc, Copper, Selenium, Magnesium, Manganese, and screened heavy metals (Lead, Mercury, Cadmium, Arsenic if tested) are within safe and optimal ranges, supporting enzymatic function, antioxidant defense, neurological health, and absence of toxic metal accumulation.

**Iron Profile**
Status: Normal. Explanation: Serum Iron, TIBC, Transferrin Saturation, Ferritin, and Soluble Transferrin Receptor are balanced, indicating healthy iron stores, normal transport capacity, and no evidence of iron deficiency anemia, hemochromatosis, or chronic inflammation-related anemia.

**Bone Health**
Status: Normal. Explanation: Vitamin D (25-OH), Calcium, Phosphorus, Magnesium, Alkaline Phosphatase (bone isoform if available), PTH, and bone turnover markers (if tested) are optimal, supporting strong bone mineralization, healthy remodeling, and low risk of osteoporosis or osteomalacia.

**Vitamins**
Status: Normal. Explanation: Vitamin D (25-OH), Vitamin B12, Folate, Vitamin B6, Vitamin C, Vitamin A, Vitamin E, and Vitamin K (if measured) are within optimal ranges, ensuring robust immune function, neurological health, methylation, antioxidant protection, and prevention of deficiency-related disorders.

**Thyroid Profile**
Status: Normal. Explanation: TSH, Free T4, Free T3, Total T3, Total T4, Reverse T3, Anti-TPO Antibodies, and Anti-Thyroglobulin Antibodies are all within reference limits, confirming euthyroid status, normal hormone production and conversion, and absence of autoimmune thyroid disease.

**Adrenal Function / Stress Hormones / Other Hormones**
Status: Normal. Explanation: Morning Cortisol, ACTH, DHEA-S, IGF-1, Leptin, Adiponectin, Aldosterone (if tested), and Catecholamines/Metonephrines (if tested) are appropriately balanced, indicating resilient HPA axis, healthy stress response, growth hormone axis integrity, and optimal metabolic regulation.

**Blood Marker Cancer Profile**
Status: Normal. Explanation: CEA, CA19-9, CA125, CA15-3, AFP, PSA (men), HE4, ROMA score (if applicable), Calcitonin, and other tumor markers are within reference ranges, suggesting very low probability of active malignancy at this time (note: tumor markers are not screening tools and must be interpreted in clinical context).

**Immune Profile**
Status: Normal. Explanation: Immunoglobulin levels (IgG, IgA, IgM, IgE), ANA, ENA panel, Anti-dsDNA, Anti-CCP, ANCA, Complement C3/C4, IL-6, and lymphocyte subsets (if tested) are within normal limits, indicating competent humoral and cellular immunity with no evidence of immunodeficiency, active autoimmunity, or chronic inflammatory states.

### Personalized Action Plan

**Nutrition:** 
make it detailed
**Lifestyle:** 
make it detailed
**Testing:** 
make it detailed
**Medical Consultation:** 
make it detailed
------------------------------
### Interaction Alerts
- ...
- ...
make it detailed
------------------------------
### Normal Ranges
#### Kidney Function
- Urea (S): 17–43 mg/dL
- Creatinine (Men): 0.74–1.35 mg/dL
- Creatinine (Women): 0.59–1.04 mg/dL
- Uric Acid (Men): 3.4–7.0 mg/dL
- Uric Acid (Women): 2.4–6.0 mg/dL
- Calcium (S): 8.5–10.5 mg/dL
- Phosphorus (S): 2.5–4.5 mg/dL
- Sodium (S): 135–145 mEq/L
- Potassium (S): 3.5–5.1 mEq/L
- Chloride (S): 98–107 mEq/L
- Bicarbonate (S): 22–28 mEq/L
- eGFR: β‰₯90 mL/min/1.73mΒ²
- Serum Osmolality: 275–295 mOsm/kg
- Ionized Calcium: 1.12–1.32 mmol/L
- Amylase (S): 23–85 U/L
- Lipase (S): 0–160 U/L

#### Basic Checkup
- WBC: 4–10 Γ—10^3/ΞΌL
- Hemoglobin: 13–17 g/dL
- MCV: 80–100 fL
- RDW: 11.5–14.5 %
- Lymphocytes: 20–40 %

#### Diabetic Profile
- Fasting Blood Sugar: 70–99 mg/dL
- HbA1c: <5.7 %
- Insulin: 2–20 Β΅IU/mL
- C-Peptide: 0.5–2.0 ng/mL
- HOMA-IR: <1 Optimal, 1–2 Normal, >2 Insulin Resistance

#### Lipid Profile
- Total Cholesterol: <200 mg/dL
- LDL: <100 mg/dL
- HDL (Men): β‰₯40 mg/dL
- HDL (Women): β‰₯50 mg/dL
- Triglycerides: <150 mg/dL
- Apo A-1: 120–160 mg/dL
- Apo B: <90 mg/dL
- Apo B/A1 ratio: 0.3–0.7
- Cholesterol/HDL Ratio: <3.5 Optimal

#### Liver Function
- Albumin: 3.5–5.0 g/dL
- Total Protein: 6.0–8.3 g/dL
- ALT: 10–40 U/L
- AST: 10–40 U/L
- ALP: 44–147 U/L
- GGT: 8–61 U/L
- LDH: 140–280 U/L
- Globulin: 2.0–3.5 g/dL
- Albumin/Globulin Ratio: 1.1–2.5
- Magnesium: 1.7–2.2 mg/dL
- Total Bilirubin: 0.1–1.2 mg/dL
- Direct Bilirubin: 0.0–0.3 mg/dL
- Indirect Bilirubin: 0.2–0.9 mg/dL
- Ammonia: 15–45 Β΅mol/L

#### Cardiac Profile
- hs-CRP: 1–3 mg/L
- CK: 40–200 U/L
- CK-MB: 0–25 U/L
- Homocysteine: 5–15 Β΅mol/L

#### Minerals & Heavy Metals
- Zinc: 70–120 Β΅g/dL
- Copper: 70–140 Β΅g/dL
- Selenium: 70–150 Β΅g/L

#### Iron Profile
- Iron (Men): 60–170 Β΅g/dL
- Iron (Women): 50–170 Β΅g/dL
- TIBC: 250–450 Β΅g/dL
- Transferrin: 200–360 mg/dL

#### Vitamins
- Vitamin D: 30–60 ng/mL
- Vitamin B12: 200–900 pg/mL

#### Hormones
- Total Testosterone (Men): 300–1000 ng/dL
- Total Testosterone (Women): 15–70 ng/dL
- Free Testosterone (Men): 5–21 pg/mL
- Free Testosterone (Women): 0.5–4.2 pg/mL
- Estrogen (Men): 10–40 pg/mL
- Estrogen (Women Follicular): 30–120 pg/mL
- Estrogen (Women Ovulation): 130–370 pg/mL
- Estrogen (Women Luteal): 70–250 pg/mL
- Estrogen (Women Postmenopause): <20–30 pg/mL
- Progesterone: 0.2–1.4 ng/mL
- SHBG (Men): 10–57 nmol/L
- SHBG (Women): 18–144 nmol/L
- LH: 1.7–8.6 IU/L
- FSH: 1.5–12.4 IU/L
- DHEA-S (Men): 280–640 Β΅g/dL
- DHEA-S (Women): 65–380 Β΅g/dL
- Cortisol (AM): 6–23 Β΅g/dL
- Cortisol (PM): 2–14 Β΅g/dL
- IGF-1: 100–300 ng/mL
- Leptin (Men): 0.5–8 ng/mL
- Leptin (Women): 5–25 ng/mL
- Adiponectin: 5–30 Β΅g/mL

#### Thyroid
- TSH: 0.4–4.0 Β΅IU/mL
- Free T3: 2.0–4.4 pg/mL
- Free T4: 0.8–1.8 ng/dL
- Total T3: 80–180 ng/dL
- Total T4: 4.5–12 Β΅g/dL
- Reverse T3: 9–24 ng/dL
- TPO Ab: <35 IU/mL
- TG Ab: <40 IU/mL

#### Cancer Markers
- CA125: <35 U/mL
- CA15-3: <30 U/mL
- CA19-9: <37 U/mL
- PSA: <4 ng/mL
- CEA: <5 ng/mL
- Calcitonin: <10 pg/mL
- AFP: <10 ng/mL
- TNF: <8 pg/m

#### Autoimmune & Immunology
- ANA: <1:80 titer (Negative)
- Anti-dsDNA: <10 IU/mL (Negative)
- SSA/SSB: <1.0 U (Negative)
- Sm Antibodies: <1.0 U (Negative)
- RNP: <1.0 U (Negative)
- Anti-CCP: <20 U/mL (Negative)
- ANCA: Negative
- Anti-ENA: Negative
- IL-6: <7 pg/mL
- IgE: 0–100 IU/mL (Normal adult)
- IgG: 700–1600 mg/dL
- Allergy Panel (Specific IgE): <0.35 kU/L = Negative

#### Adrenal & Pituitary Hormones
- ACTH (Morning 8–10 AM): 7–63 pg/mL  (β‰ˆ 1.6–13.9 pmol/L)
- ACTH (Afternoon): <30–50 pg/mL is still considered normal (levels drop throughout the day)
- Cortisol (Morning 8–10 AM): 6–23 Β΅g/dL (166–635 nmol/L)
- Cortisol (Afternoon 4–6 PM): 2–14 Β΅g/dL (55–386 nmol/L)
- DHEA-S (Men): 280–640 Β΅g/dL
- DHEA-S (Women): 65–380 Β΅g/dL (age-dependent; highest 20–30 yrs)
- IGF-1: Varies strongly by age (lab-specific reference provided)
- Leptin (Men): 0.5–8 ng/mL | (Women): 5–25 ng/mL
- Adiponectin: 5–30 Β΅g/mL (higher = better insulin sensitivity)

------------------------------
### Tabular Mapping
YOU MUST NOW LIST EVERY SINGLE BIOMARKER THE USER PROVIDED.
NO EXCEPTIONS. NO SUMMARIZING.

| Biomarker                  | Value          | Status   | Insight                                                                                   | Reference Range                  |
|----------------------------|----------------|----------|-------------------------------------------------------------------------------------------|----------------------------------|
{% for biomarker in all_user_biomarkers %}
| {{ biomarker.name }}       | {{ biomarker.value }} {{ biomarker.unit if biomarker.unit else "" }} | {{ biomarker.status }} | {{ biomarker.insight }} | {{ biomarker.reference }} |
{% for biomarker in all_user_biomarkers %}<!-- REPEAT THE LOOP SO THE MODEL SEES IT TWICE – THIS IS INTENTIONAL -->
{% endfor %}

<!-- BEGIN EXHAUSTIVE TABLE – START WRITING ALL ROWS HERE AND DO NOT STOP UNTIL EVERY USER BIOMARKER IS INCLUDED -->
<!-- Example of the first row the model will continue from (delete this line and the example row in real output): -->
| Hemoglobin                 | 14.8 g/dL      | Normal   | Optimal oxygen-carrying capacity.                                                         | 13–17 g/dL                       |
<!-- NOW CONTINUE WITH THE REMAINING {{ total_count }} BIOMARKERS THE USER PROVIDED -->

------------------------------
"""

    
    model = genai.GenerativeModel(MODEL_ID)
    response = model.generate_content(f"{prompt}\n\n{user_message}")
   ## response = model.generate_content(user_message)
    if not response or not getattr(response, "text", None):
        return "⚠️ Gemini returned empty response."
    return response.text.strip()

# ---------------- Gradio Function ----------------
def gradio_interface(
    age, gender, height, weight,
    urea, creatinine, uric_acid, calcium, phosphorus, sodium, potassium, chloride, bicarbonate, egfr, serum_osmolality, ionized_calcium,
    amylase, lipase,
    wbc, hemoglobin, mcv, rdw, lymphocytes,
    fasting_blood_sugar, hb1ac, insulin, c_peptide, homa_ir,
    total_cholesterol, ldl, hdl, cholesterol_hdl_ratio, triglycerides, apo_a1, apo_b, apo_ratio,
    albumin, total_protein, alt, ast, alp, ggt, ld, globulin, albumin_globulin_ratio,
    magnesium, total_bilirubin, direct_bilirubin, indirect_bilirubin, ammonia,
    hs_crp, ck, ck_mb, homocysteine, zinc, copper, selenium,
    iron, tibc, transferrin,
    vitamin_d, vitamin_b12,
    total_testosterone, free_testosterone, estrogen, progesterone, dhea_s, shbg, lh, fsh,
    tsh, free_t3, free_t4, total_t3, total_t4, reverse_t3, tpo_ab, tg_ab,
    cortisol, acth, igf1, leptin, adiponectin,
    ca125, ca15_3, ca19_9, psa, cea, calcitonin, afp, tnf,
    ana, ige, igg, anti_ccp, dsdna, ssa_ssb, rnp, sm_antibodies, anca, anti_ena, il6, allergy_panel
):
    req = BiomarkerRequest(
        age=age, gender=gender, height=height, weight=weight,
        urea=urea, creatinine=creatinine, uric_acid=uric_acid, calcium=calcium, phosphorus=phosphorus,
        sodium=sodium, potassium=potassium, chloride=chloride, bicarbonate=bicarbonate, egfr=egfr,
        serum_osmolality=serum_osmolality, ionized_calcium=ionized_calcium, amylase=amylase, lipase=lipase,
        wbc=wbc, hemoglobin=hemoglobin, mcv=mcv, rdw=rdw, lymphocytes=lymphocytes,
        fasting_blood_sugar=fasting_blood_sugar, hb1ac=hb1ac, insulin=insulin, c_peptide=c_peptide, homa_ir=homa_ir,
        total_cholesterol=total_cholesterol, ldl=ldl, hdl=hdl, cholesterol_hdl_ratio=cholesterol_hdl_ratio, triglycerides=triglycerides,
        apo_a1=apo_a1, apo_b=apo_b, apo_ratio=apo_ratio,
        albumin=albumin, total_protein=total_protein, alt=alt, ast=ast, alp=alp, ggt=ggt, ld=ld, globulin=globulin, albumin_globulin_ratio=albumin_globulin_ratio,
        magnesium=magnesium, total_bilirubin=total_bilirubin, direct_bilirubin=direct_bilirubin, indirect_bilirubin=indirect_bilirubin, ammonia=ammonia,
        hs_crp=hs_crp, ck=ck, ck_mb=ck_mb, homocysteine=homocysteine, zinc=zinc, copper=copper, selenium=selenium,
        iron=iron, tibc=tibc, transferrin=transferrin,
        vitamin_d=vitamin_d, vitamin_b12=vitamin_b12,
        total_testosterone=total_testosterone, free_testosterone=free_testosterone, estrogen=estrogen, progesterone=progesterone, dhea_s=dhea_s, shbg=shbg, lh=lh, fsh=fsh,
        tsh=tsh, free_t3=free_t3, free_t4=free_t4, total_t3=total_t3, total_t4=total_t4, reverse_t3=reverse_t3, tpo_ab=tpo_ab, tg_ab=tg_ab,
        cortisol=cortisol, acth=acth, igf1=igf1, leptin=leptin, adiponectin=adiponectin,
        ca125=ca125, ca15_3=ca15_3, ca19_9=ca19_9, psa=psa, cea=cea, calcitonin=calcitonin, afp=afp, tnf=tnf,
        ana=ana, ige=ige, igg=igg, anti_ccp=anti_ccp, dsdna=dsdna, ssa_ssb=ssa_ssb, rnp=rnp, sm_antibodies=sm_antibodies, anca=anca, anti_ena=anti_ena, il6=il6, allergy_panel=allergy_panel
    )
    return generate_report(req)

# ---------------- Gradio UI ----------------
with gr.Blocks(theme="soft", title="LLM Biomarker Analyzer") as iface:
    gr.Markdown("## 🧬 LLM Biomarker Analyzer")
    gr.Markdown("Enter your biomarker and demographic data below to generate :")

    # Individual inputs
    age = gr.Number(label="Age (years)", value=52)
    gender = gr.Radio(["male", "female"], label="Gender", value="female")
    height = gr.Number(label="Height (cm)", value=165)
    weight = gr.Number(label="Weight (kg)", value=70)

    biomarker_inputs = [
        # Kidney / Electrolytes
        gr.Number(label="Urea", value=25.0), gr.Number(label="Creatinine", value=1.0),
        gr.Number(label="Uric Acid", value=5.0), gr.Number(label="Calcium", value=9.5),
        gr.Number(label="Phosphorus", value=3.5), gr.Number(label="Sodium", value=140.0),
        gr.Number(label="Potassium", value=4.2), gr.Number(label="Chloride", value=100.0),
        gr.Number(label="Bicarbonate", value=24.0), gr.Number(label="eGFR", value=100.0),
        gr.Number(label="Serum Osmolality", value=285.0), gr.Number(label="Ionized Calcium", value=1.2),
        gr.Number(label="Amylase", value=50.0), gr.Number(label="Lipase", value=50.0),

        # Hematology
        gr.Number(label="WBC", value=6.0), gr.Number(label="Hemoglobin", value=14.0),
        gr.Number(label="MCV", value=90.0), gr.Number(label="RDW", value=13.0),
        gr.Number(label="Lymphocytes", value=30.0),

        # Glycemic / Metabolic
        gr.Number(label="Fasting Blood Sugar", value=85.0), gr.Number(label="HbA1c", value=5.4),
        gr.Number(label="Insulin", value=10.0), gr.Number(label="C-Peptide", value=1.2),
        gr.Number(label="HOMA-IR", value=1.2),

        # Lipid Profile
        gr.Number(label="Total Cholesterol", value=180.0), gr.Number(label="LDL", value=90.0),
        gr.Number(label="HDL", value=50.0), gr.Number(label="Cholesterol/HDL Ratio", value=3.0),
        gr.Number(label="Triglycerides", value=120.0), gr.Number(label="Apo A1", value=150.0),
        gr.Number(label="Apo B", value=70.0), gr.Number(label="Apo Ratio", value=0.5),

        # Liver
        gr.Number(label="Albumin", value=4.5), gr.Number(label="Total Protein", value=7.0),
        gr.Number(label="ALT", value=25.0), gr.Number(label="AST", value=24.0),
        gr.Number(label="ALP", value=80.0), gr.Number(label="GGT", value=20.0),
        gr.Number(label="LD", value=180.0), gr.Number(label="Globulin", value=2.5),
        gr.Number(label="Albumin/Globulin Ratio", value=1.8), gr.Number(label="Magnesium", value=2.0),
        gr.Number(label="Total Bilirubin", value=0.7), gr.Number(label="Direct Bilirubin", value=0.2),
        gr.Number(label="Indirect Bilirubin", value=0.5), gr.Number(label="Ammonia", value=30.0),

        # Cardiac / Inflammation
        gr.Number(label="hs-CRP", value=1.0), gr.Number(label="CK", value=100.0),
        gr.Number(label="CK-MB", value=10.0), gr.Number(label="Homocysteine", value=10.0),
        gr.Number(label="Zinc", value=90.0), gr.Number(label="Copper", value=100.0), gr.Number(label="Selenium", value=100.0),

        # Iron / Minerals
        gr.Number(label="Iron", value=100.0), gr.Number(label="TIBC", value=350.0), gr.Number(label="Transferrin", value=250.0),

        # Vitamins
        gr.Number(label="Vitamin D", value=35.0), gr.Number(label="Vitamin B12", value=500.0),

        # Sex Hormones
        gr.Number(label="Total Testosterone", value=450.0), gr.Number(label="Free Testosterone", value=15.0),
        gr.Number(label="Estrogen", value=60.0), gr.Number(label="Progesterone", value=1.0),
        gr.Number(label="DHEA-S", value=250.0), gr.Number(label="SHBG", value=40.0),
        gr.Number(label="LH", value=5.0), gr.Number(label="FSH", value=6.0),

        # Thyroid
        gr.Number(label="TSH", value=2.0), gr.Number(label="Free T3", value=3.2), gr.Number(label="Free T4", value=1.2),
        gr.Number(label="Total T3", value=120.0), gr.Number(label="Total T4", value=8.0), gr.Number(label="Reverse T3", value=15.0),
        gr.Number(label="TPO-Ab", value=20.0), gr.Number(label="TG-Ab", value=20.0),

        # Adrenal / Stress
        gr.Number(label="Cortisol", value=12.0), gr.Number(label="ACTH", value=30.0),
        gr.Number(label="IGF-1", value=200.0), gr.Number(label="Leptin", value=15.0), gr.Number(label="Adiponectin", value=15.0),

        # Cancer markers
        gr.Number(label="CA125", value=20.0), gr.Number(label="CA15-3", value=25.0), gr.Number(label="CA19-9", value=20.0),
        gr.Number(label="PSA", value=2.0), gr.Number(label="CEA", value=2.0), gr.Number(label="Calcitonin", value=5.0),
        gr.Number(label="AFP", value=5.0), gr.Number(label="TNF", value=5.0),

        # Immune / Autoimmune
        gr.Number(label="ANA", value=0.0), gr.Number(label="IgE", value=50.0), gr.Number(label="IgG", value=1000.0),
        gr.Number(label="Anti-CCP", value=10.0), gr.Number(label="dsDNA", value=5.0), gr.Number(label="SSA/SSB", value=0.0),
        gr.Number(label="RNP", value=0.0), gr.Number(label="Sm Antibodies", value=0.0), gr.Number(label="ANCA", value=0.0),
        gr.Number(label="Anti-ENA", value=0.0), gr.Number(label="IL6", value=5.0), gr.Number(label="Allergy Panel", value=1.0)
    ]

    submit_btn = gr.Button("🧠 Generate Medical Report", variant="primary")
    output_md = gr.Markdown(label="AI-Generated Medical Report")

    submit_btn.click(fn=gradio_interface, inputs=[age, gender, height, weight] + biomarker_inputs, outputs=output_md)

# ---------------- Launch ----------------
if __name__ == "__main__":
    iface.launch(server_name="0.0.0.0", server_port=None, share=True)