Muhammadidrees commited on
Commit
04977a2
Β·
verified Β·
1 Parent(s): bcb2991

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -0
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
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
+ import gradio as gr
8
+ from typing import Dict, Any, Union, List
9
+
10
+
11
+ # ---------------- Initialize ----------------
12
+
13
+ app = FastAPI(title="LLM Model API + Gradio UI", version="4.0")
14
+
15
+ GEMINI_API_KEY='AIzaSyC0XU6yLCILZFUVhKoIcqoy2k5qwQmnDsc'
16
+ if not GEMINI_API_KEY:
17
+ raise ValueError("❌ GEMINI_API_KEY not found. Please set it in your .env file.")
18
+
19
+ genai.configure(api_key=GEMINI_API_KEY)
20
+ MODEL_ID = "gemini-2.5-flash"
21
+
22
+
23
+ # ---------------- Schema ----------------
24
+ class BiomarkerRequest(BaseModel):
25
+ albumin: float = Field(default=3.2)
26
+ creatinine: float = Field(default=1.4)
27
+ glucose: float = Field(default=145)
28
+ crp: float = Field(default=12.0)
29
+ mcv: float = Field(default=88)
30
+ rdw: float = Field(default=15.5)
31
+ alp: float = Field(default=120)
32
+ wbc: float = Field(default=11.8)
33
+ lymphocytes: float = Field(default=20)
34
+ hb: float = Field(default=13.0)
35
+ pv: float = Field(default=2.1)
36
+ age: int = Field(default=52)
37
+ gender: str = Field(default="female")
38
+ height: float = Field(default=165)
39
+ weight: float = Field(default=70)
40
+
41
+
42
+ # ---------------- Utility ----------------
43
+ def clean_json(data: Union[Dict, List, str]) -> Union[Dict, List, str]:
44
+ if isinstance(data, str):
45
+ text = re.sub(r"-{3,}", "", data)
46
+ text = re.sub(r"\s+", " ", text)
47
+ text = text.strip(" -\n\t\r")
48
+ return text
49
+ elif isinstance(data, list):
50
+ return [clean_json(i) for i in data if i and clean_json(i)]
51
+ elif isinstance(data, dict):
52
+ return {k.strip(): clean_json(v) for k, v in data.items()}
53
+ return data
54
+
55
+
56
+ # ---------------- Core Gemini Logic ----------------
57
+ def generate_report(data: BiomarkerRequest) -> str:
58
+ """Main logic β€” uses Gemini to generate markdown medical report"""
59
+ prompt = """
60
+ You are an advanced **Medical Insight Generation AI** trained to analyze **biomarkers and lab results**.
61
+ ⚠️ IMPORTANT β€” OUTPUT FORMAT INSTRUCTIONS:
62
+ Return your report in this strict markdown structure.
63
+ ------------------------------
64
+ ### Executive Summary
65
+ **Top 3 Health Priorities:**
66
+ 1. ...
67
+ 2. ...
68
+ 3. ...
69
+ **Key Strengths:**
70
+ - ...
71
+ - ...
72
+ ------------------------------
73
+ ### System-Specific Analysis
74
+ **Cardiovascular System**
75
+ Status: Normal. Explanation: ...
76
+ **Liver Function**
77
+ Status: Elevated ALP. Explanation: ...
78
+ ------------------------------
79
+ ### Personalized Action Plan
80
+ ### Nutrition:** ...
81
+ ### **Lifestyle:** ...
82
+ ### **Testing:** ...
83
+ ### **Medical Consultation:** ...
84
+ ------------------------------
85
+ ### Interaction Alerts
86
+ - ...
87
+ - ...
88
+ ------------------------------
89
+ ### Normal Ranges
90
+ - Albumin: 3.5–5.0 g/dL
91
+ - Creatinine: 0.7–1.3 mg/dL
92
+ - Glucose: 70–100 mg/dL
93
+ - CRP: 0–10 mg/L
94
+ - MCV: 80–100 fL
95
+ - RDW: 11.5–14.5 %
96
+ - ALP: 44–147 U/L
97
+ - WBC: 4.0–10.0 Γ—10^3/ΞΌL
98
+ - Lymphocytes: 20–40 %
99
+ - Hemoglobin: 13–17 g/dL
100
+ - PV: 2500–3000 mL
101
+ ------------------------------
102
+ ### Tabular Mapping
103
+ | Biomarker | Value | Status | Insight | Reference Range |
104
+ | Albumin | X | Normal | ... | 3.5–5.0 g/dL |
105
+ | Creatinine | X | High | ... | 0.7–1.3 mg/dL |
106
+ | Glucose | X | ... | ... | 70–100 mg/dL |
107
+ ------------------------------
108
+ """
109
+
110
+ user_message = f"""
111
+ Patient Info:
112
+ - Age: {data.age}
113
+ - Gender: {data.gender}
114
+ - Height: {data.height} cm
115
+ - Weight: {data.weight} kg
116
+ Biomarkers:
117
+ - Albumin: {data.albumin} g/dL
118
+ - Creatinine: {data.creatinine} mg/dL
119
+ - Glucose: {data.glucose} mg/dL
120
+ - CRP: {data.crp} mg/L
121
+ - MCV: {data.mcv} fL
122
+ - RDW: {data.rdw} %
123
+ - ALP: {data.alp} U/L
124
+ - WBC: {data.wbc} Γ—10^3/ΞΌL
125
+ - Lymphocytes: {data.lymphocytes} %
126
+ - Hemoglobin: {data.hb} g/dL
127
+ - Plasma Volume (PV): {data.pv} L
128
+ """
129
+
130
+ model = genai.GenerativeModel(MODEL_ID)
131
+ response = model.generate_content(f"{prompt}\n\n{user_message}")
132
+
133
+ if not response or not getattr(response, "text", None):
134
+ return "⚠️ Gemini returned an empty response."
135
+
136
+ return response.text.strip()
137
+
138
+
139
+ # ---------------- Gradio Function ----------------
140
+ def gradio_interface(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
141
+ lymphocytes, hb, pv, age, gender, height, weight):
142
+ req = BiomarkerRequest(
143
+ albumin=albumin, creatinine=creatinine, glucose=glucose, crp=crp,
144
+ mcv=mcv, rdw=rdw, alp=alp, wbc=wbc, lymphocytes=lymphocytes,
145
+ hb=hb, pv=pv, age=int(age), gender=gender, height=height, weight=weight
146
+ )
147
+ return generate_report(req)
148
+
149
+
150
+ # ---------------- Gradio UI (Vertical Layout) ----------------
151
+ with gr.Blocks(theme="soft", title="LLM Biomarker Analyzer") as iface:
152
+ gr.Markdown("## 🧬 LLM Biomarker Analyzer")
153
+ gr.Markdown("Enter your biomarker and demographic data below to generate a **Gemini-powered medical insight report**:")
154
+
155
+ with gr.Column():
156
+ with gr.Row():
157
+ age = gr.Number(label="Age (years)", value=52)
158
+ gender = gr.Radio(["male", "female"], label="Gender", value="female")
159
+
160
+ with gr.Row():
161
+ height = gr.Number(label="Height (cm)", value=165)
162
+ weight = gr.Number(label="Weight (kg)", value=70)
163
+
164
+ gr.Markdown("### πŸ”¬ Biomarker Values")
165
+
166
+ grid_inputs = [
167
+ gr.Number(label="Albumin (g/dL)", value=3.2),
168
+ gr.Number(label="Creatinine (mg/dL)", value=1.4),
169
+ gr.Number(label="Glucose (mg/dL)", value=145),
170
+ gr.Number(label="CRP (mg/L)", value=12.0),
171
+ gr.Number(label="MCV (fL)", value=88),
172
+ gr.Number(label="RDW (%)", value=15.5),
173
+ gr.Number(label="ALP (U/L)", value=120),
174
+ gr.Number(label="WBC (Γ—10Β³/ΞΌL)", value=11.8),
175
+ gr.Number(label="Lymphocytes (%)", value=20),
176
+ gr.Number(label="Hemoglobin (g/dL)", value=13.0),
177
+ gr.Number(label="Plasma Volume (mL)", value=2100)
178
+ ]
179
+
180
+ submit_btn = gr.Button("🧠 Generate Medical Report", variant="primary")
181
+
182
+ output_md = gr.Markdown(label="AI-Generated Medical Report")
183
+
184
+ submit_btn.click(
185
+ fn=gradio_interface,
186
+ inputs=grid_inputs + [age, gender, height, weight],
187
+ outputs=output_md
188
+ )
189
+
190
+ # ---------------- Launch ----------------
191
+ if __name__ == "__main__":
192
+ iface.launch(server_name="0.0.0.0", server_port=7860)