Spaces:
Sleeping
Sleeping
| 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=4.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**. | |
| ⚠️ 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 | |
| """ | |
| 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 (mild abnormalities) | |
| gr.Number(label="Urea", value=32.0), gr.Number(label="Creatinine", value=1.3), | |
| gr.Number(label="Uric Acid", value=7.2), gr.Number(label="Calcium", value=10.4), | |
| gr.Number(label="Phosphorus", value=4.8), gr.Number(label="Sodium", value=147.0), | |
| gr.Number(label="Potassium", value=5.1), gr.Number(label="Chloride", value=108.0), | |
| gr.Number(label="Bicarbonate", value=21.0), gr.Number(label="eGFR", value=78.0), | |
| gr.Number(label="Serum Osmolality", value=295.0), gr.Number(label="Ionized Calcium", value=1.35), | |
| gr.Number(label="Amylase", value=110.0), gr.Number(label="Lipase", value=95.0), | |
| # Hematology | |
| gr.Number(label="WBC", value=11.0), gr.Number(label="Hemoglobin", value=13.1), | |
| gr.Number(label="MCV", value=101.0), gr.Number(label="RDW", value=15.2), | |
| gr.Number(label="Lymphocytes", value=18.0), | |
| # Glycemic / Metabolic | |
| gr.Number(label="Fasting Blood Sugar", value=112.0), gr.Number(label="HbA1c", value=6.1), | |
| gr.Number(label="Insulin", value=18.0), gr.Number(label="C-Peptide", value=2.8), | |
| gr.Number(label="HOMA-IR", value=3.5), | |
| # Lipid Profile | |
| gr.Number(label="Total Cholesterol", value=230.0), gr.Number(label="LDL", value=145.0), | |
| gr.Number(label="HDL", value=38.0), gr.Number(label="Cholesterol/HDL Ratio", value=5.2), | |
| gr.Number(label="Triglycerides", value=180.0), gr.Number(label="Apo A1", value=110.0), | |
| gr.Number(label="Apo B", value=110.0), gr.Number(label="Apo Ratio", value=0.9), | |
| # Liver | |
| gr.Number(label="Albumin", value=3.4), gr.Number(label="Total Protein", value=8.5), | |
| gr.Number(label="ALT", value=48.0), gr.Number(label="AST", value=42.0), | |
| gr.Number(label="ALP", value=130.0), gr.Number(label="GGT", value=45.0), | |
| gr.Number(label="LD", value=260.0), gr.Number(label="Globulin", value=3.8), | |
| gr.Number(label="Albumin/Globulin Ratio", value=0.9), gr.Number(label="Magnesium", value=1.5), | |
| gr.Number(label="Total Bilirubin", value=1.4), gr.Number(label="Direct Bilirubin", value=0.4), | |
| gr.Number(label="Indirect Bilirubin", value=1.0), gr.Number(label="Ammonia", value=55.0), | |
| # Cardiac / Inflammation | |
| gr.Number(label="hs-CRP", value=4.8), gr.Number(label="CK", value=210.0), | |
| gr.Number(label="CK-MB", value=18.0), gr.Number(label="Homocysteine", value=17.0), | |
| gr.Number(label="Zinc", value=65.0), gr.Number(label="Copper", value=145.0), | |
| gr.Number(label="Selenium", value=55.0), | |
| # Iron / Minerals | |
| gr.Number(label="Iron", value=45.0), gr.Number(label="TIBC", value=410.0), | |
| gr.Number(label="Transferrin", value=320.0), | |
| # Vitamins | |
| gr.Number(label="Vitamin D", value=18.0), gr.Number(label="Vitamin B12", value=250.0), | |
| # Sex Hormones | |
| gr.Number(label="Total Testosterone", value=310.0), gr.Number(label="Free Testosterone", value=7.0), | |
| gr.Number(label="Estrogen", value=180.0), gr.Number(label="Progesterone", value=0.4), | |
| gr.Number(label="DHEA-S", value=380.0), gr.Number(label="SHBG", value=65.0), | |
| gr.Number(label="LH", value=10.0), gr.Number(label="FSH", value=14.0), | |
| # Thyroid | |
| gr.Number(label="TSH", value=4.9), gr.Number(label="Free T3", value=2.5), | |
| gr.Number(label="Free T4", value=0.8), | |
| gr.Number(label="Total T3", value=70.0), gr.Number(label="Total T4", value=4.2), | |
| gr.Number(label="Reverse T3", value=22.0), | |
| gr.Number(label="TPO-Ab", value=45.0), gr.Number(label="TG-Ab", value=35.0), | |
| # Adrenal / Stress | |
| gr.Number(label="Cortisol", value=20.0), gr.Number(label="ACTH", value=55.0), | |
| gr.Number(label="IGF-1", value=105.0), gr.Number(label="Leptin", value=28.0), | |
| gr.Number(label="Adiponectin", value=7.0), | |
| # Cancer markers | |
| gr.Number(label="CA125", value=48.0), gr.Number(label="CA15-3", value=32.0), | |
| gr.Number(label="CA19-9", value=42.0), | |
| gr.Number(label="PSA", value=3.9), gr.Number(label="CEA", value=4.8), | |
| gr.Number(label="Calcitonin", value=16.0), | |
| gr.Number(label="AFP", value=12.0), gr.Number(label="TNF", value=9.0), | |
| # Immune / Autoimmune | |
| gr.Number(label="ANA", value=1.0), gr.Number(label="IgE", value=160.0), | |
| gr.Number(label="IgG", value=1650.0), | |
| gr.Number(label="Anti-CCP", value=28.0), gr.Number(label="dsDNA", value=18.0), | |
| gr.Number(label="SSA/SSB", value=3.0), gr.Number(label="RNP", value=2.0), | |
| gr.Number(label="Sm Antibodies", value=1.5), gr.Number(label="ANCA", value=1.2), | |
| gr.Number(label="Anti-ENA", value=1.8), gr.Number(label="IL6", value=9.0), | |
| gr.Number(label="Allergy Panel", value=4.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) | |