Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,7 +9,7 @@ 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'
|
|
@@ -39,7 +39,7 @@ class BiomarkerRequest(BaseModel):
|
|
| 39 |
weight: float = Field(default=70)
|
| 40 |
|
| 41 |
|
| 42 |
-
# ----------------
|
| 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)
|
|
@@ -53,85 +53,7 @@ def clean_json(data: Union[Dict, List, str]) -> Union[Dict, List, str]:
|
|
| 53 |
return data
|
| 54 |
|
| 55 |
|
| 56 |
-
# ----------------
|
| 57 |
-
def parse_medical_report(text: str):
|
| 58 |
-
def clean_line(line: str) -> str:
|
| 59 |
-
return re.sub(r"[\-\*\u2022]+\s*", "", line.strip())
|
| 60 |
-
|
| 61 |
-
def parse_bold_entities(block: str) -> Dict[str, str]:
|
| 62 |
-
entities = {}
|
| 63 |
-
pattern = re.compile(r"\*\*(.*?)\*\*(.*?)(?=\*\*|###|$)", re.S)
|
| 64 |
-
for match in pattern.finditer(block):
|
| 65 |
-
key = match.group(1).strip().strip(":")
|
| 66 |
-
val = match.group(2).strip().replace("\n", " ")
|
| 67 |
-
val = re.sub(r"\s+", " ", val)
|
| 68 |
-
if key:
|
| 69 |
-
entities[key] = val
|
| 70 |
-
return entities
|
| 71 |
-
|
| 72 |
-
data = {
|
| 73 |
-
"executive_summary": {"top_priorities": [], "key_strengths": []},
|
| 74 |
-
"system_analysis": {},
|
| 75 |
-
"personalized_action_plan": {},
|
| 76 |
-
"interaction_alerts": [],
|
| 77 |
-
"normal_ranges": {},
|
| 78 |
-
"biomarker_table": []
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
exec_match = re.search(r"###\s*Executive Summary(.*?)(?=###|$)", text, re.S | re.I)
|
| 82 |
-
if exec_match:
|
| 83 |
-
block = exec_match.group(1)
|
| 84 |
-
priorities = re.findall(r"\d+\.\s*(.*?)\n", block)
|
| 85 |
-
if priorities:
|
| 86 |
-
data["executive_summary"]["top_priorities"] = [clean_line(p) for p in priorities]
|
| 87 |
-
strengths_match = re.search(r"\*\*Key Strengths:\*\*(.*)", block, re.S)
|
| 88 |
-
if strengths_match:
|
| 89 |
-
strengths_text = strengths_match.group(1)
|
| 90 |
-
strengths = [clean_line(s) for s in strengths_text.splitlines() if clean_line(s)]
|
| 91 |
-
data["executive_summary"]["key_strengths"] = strengths
|
| 92 |
-
|
| 93 |
-
sys_match = re.search(r"###\s*System[- ]Specific Analysis(.*?)(?=###|$)", text, re.S | re.I)
|
| 94 |
-
if sys_match:
|
| 95 |
-
sys_block = sys_match.group(1)
|
| 96 |
-
data["system_analysis"] = parse_bold_entities(sys_block)
|
| 97 |
-
|
| 98 |
-
plan_match = re.search(r"###\s*Personalized Action Plan(.*?)(?=###|$)", text, re.S | re.I)
|
| 99 |
-
if plan_match:
|
| 100 |
-
plan_block = plan_match.group(1)
|
| 101 |
-
data["personalized_action_plan"] = parse_bold_entities(plan_block)
|
| 102 |
-
|
| 103 |
-
alerts_match = re.search(r"###\s*Interaction Alerts(.*?)(?=###|$)", text, re.S | re.I)
|
| 104 |
-
if alerts_match:
|
| 105 |
-
alerts_block = alerts_match.group(1)
|
| 106 |
-
alerts = [clean_line(a) for a in alerts_block.splitlines() if clean_line(a)]
|
| 107 |
-
data["interaction_alerts"] = alerts
|
| 108 |
-
|
| 109 |
-
normal_match = re.search(r"###\s*Normal Ranges(.*?)(?=###|$)", text, re.S | re.I)
|
| 110 |
-
if normal_match:
|
| 111 |
-
normal_block = normal_match.group(1)
|
| 112 |
-
for match in re.findall(r"-\s*([^:]+):\s*([^\n]+)", normal_block):
|
| 113 |
-
biomarker, rng = match
|
| 114 |
-
data["normal_ranges"][biomarker.strip()] = rng.strip()
|
| 115 |
-
|
| 116 |
-
table_match = re.search(r"###\s*Tabular Mapping(.*)", text, re.S | re.I)
|
| 117 |
-
if table_match:
|
| 118 |
-
table_block = table_match.group(1)
|
| 119 |
-
table_pattern = r"\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|"
|
| 120 |
-
for biomarker, value, status, insight, ref in re.findall(table_pattern, table_block):
|
| 121 |
-
if not any([biomarker, value, status, insight, ref]):
|
| 122 |
-
continue
|
| 123 |
-
data["biomarker_table"].append({
|
| 124 |
-
"biomarker": biomarker.strip(),
|
| 125 |
-
"value": value.strip(),
|
| 126 |
-
"status": status.strip(),
|
| 127 |
-
"insight": insight.strip(),
|
| 128 |
-
"reference_range": ref.strip(),
|
| 129 |
-
})
|
| 130 |
-
|
| 131 |
-
return data
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
# ---------------- Prediction Core ----------------
|
| 135 |
def generate_report(data: BiomarkerRequest) -> str:
|
| 136 |
"""Main logic — uses Gemini to generate markdown medical report"""
|
| 137 |
prompt = """
|
|
@@ -212,7 +134,7 @@ Biomarkers:
|
|
| 212 |
- WBC: {data.wbc} ×10^3/μL
|
| 213 |
- Lymphocytes: {data.lymphocytes} %
|
| 214 |
- Hemoglobin: {data.hb} g/dL
|
| 215 |
-
- Plasma Volume (PV): {data.pv}
|
| 216 |
"""
|
| 217 |
|
| 218 |
model = genai.GenerativeModel(MODEL_ID)
|
|
@@ -224,7 +146,7 @@ Biomarkers:
|
|
| 224 |
return response.text.strip()
|
| 225 |
|
| 226 |
|
| 227 |
-
# ---------------- Gradio
|
| 228 |
def gradio_interface(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
|
| 229 |
lymphocytes, hb, pv, age, gender, height, weight):
|
| 230 |
req = BiomarkerRequest(
|
|
@@ -232,35 +154,48 @@ def gradio_interface(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
|
|
| 232 |
mcv=mcv, rdw=rdw, alp=alp, wbc=wbc, lymphocytes=lymphocytes,
|
| 233 |
hb=hb, pv=pv, age=int(age), gender=gender, height=height, weight=weight
|
| 234 |
)
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
gr.
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
gr.
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
gr.
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
# ---------------- Launch ----------------
|
| 266 |
if __name__ == "__main__":
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
# ---------------- Initialize ----------------
|
| 12 |
+
|
| 13 |
app = FastAPI(title="LLM Model API + Gradio UI", version="4.0")
|
| 14 |
|
| 15 |
GEMINI_API_KEY='AIzaSyC0XU6yLCILZFUVhKoIcqoy2k5qwQmnDsc'
|
|
|
|
| 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)
|
|
|
|
| 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 = """
|
|
|
|
| 134 |
- WBC: {data.wbc} ×10^3/μL
|
| 135 |
- Lymphocytes: {data.lymphocytes} %
|
| 136 |
- Hemoglobin: {data.hb} g/dL
|
| 137 |
+
- Plasma Volume (PV): {data.pv} L
|
| 138 |
"""
|
| 139 |
|
| 140 |
model = genai.GenerativeModel(MODEL_ID)
|
|
|
|
| 146 |
return response.text.strip()
|
| 147 |
|
| 148 |
|
| 149 |
+
# ---------------- Gradio Function ----------------
|
| 150 |
def gradio_interface(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
|
| 151 |
lymphocytes, hb, pv, age, gender, height, weight):
|
| 152 |
req = BiomarkerRequest(
|
|
|
|
| 154 |
mcv=mcv, rdw=rdw, alp=alp, wbc=wbc, lymphocytes=lymphocytes,
|
| 155 |
hb=hb, pv=pv, age=int(age), gender=gender, height=height, weight=weight
|
| 156 |
)
|
| 157 |
+
return generate_report(req)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ---------------- Gradio UI (Vertical Layout) ----------------
|
| 161 |
+
with gr.Blocks(theme="soft", title="LLM Biomarker Analyzer") as iface:
|
| 162 |
+
gr.Markdown("## 🧬 LLM Biomarker Analyzer")
|
| 163 |
+
gr.Markdown("Enter your biomarker and demographic data below to generate a **Gemini-powered medical insight report**:")
|
| 164 |
+
|
| 165 |
+
with gr.Column():
|
| 166 |
+
with gr.Row():
|
| 167 |
+
age = gr.Number(label="Age (years)", value=52)
|
| 168 |
+
gender = gr.Radio(["male", "female"], label="Gender", value="female")
|
| 169 |
+
|
| 170 |
+
with gr.Row():
|
| 171 |
+
height = gr.Number(label="Height (cm)", value=165)
|
| 172 |
+
weight = gr.Number(label="Weight (kg)", value=70)
|
| 173 |
+
|
| 174 |
+
gr.Markdown("### 🔬 Biomarker Values")
|
| 175 |
+
|
| 176 |
+
grid_inputs = [
|
| 177 |
+
gr.Number(label="Albumin (g/dL)", value=3.2),
|
| 178 |
+
gr.Number(label="Creatinine (mg/dL)", value=1.4),
|
| 179 |
+
gr.Number(label="Glucose (mg/dL)", value=145),
|
| 180 |
+
gr.Number(label="CRP (mg/L)", value=12.0),
|
| 181 |
+
gr.Number(label="MCV (fL)", value=88),
|
| 182 |
+
gr.Number(label="RDW (%)", value=15.5),
|
| 183 |
+
gr.Number(label="ALP (U/L)", value=120),
|
| 184 |
+
gr.Number(label="WBC (×10³/μL)", value=11.8),
|
| 185 |
+
gr.Number(label="Lymphocytes (%)", value=20),
|
| 186 |
+
gr.Number(label="Hemoglobin (g/dL)", value=13.0),
|
| 187 |
+
gr.Number(label="Plasma Volume (L)", value=2.1)
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
submit_btn = gr.Button("🧠 Generate Medical Report", variant="primary")
|
| 191 |
+
|
| 192 |
+
output_md = gr.Markdown(label="AI-Generated Medical Report")
|
| 193 |
+
|
| 194 |
+
submit_btn.click(
|
| 195 |
+
fn=gradio_interface,
|
| 196 |
+
inputs=grid_inputs + [age, gender, height, weight],
|
| 197 |
+
outputs=output_md
|
| 198 |
+
)
|
| 199 |
|
| 200 |
# ---------------- Launch ----------------
|
| 201 |
if __name__ == "__main__":
|