Muhammadidrees commited on
Commit
3cbdd87
Β·
verified Β·
1 Parent(s): 184241f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -74
app.py CHANGED
@@ -55,7 +55,7 @@ def classify(value, biomarker, gender="Male"):
55
  return "Normal"
56
 
57
  # -----------------------
58
- # Splitter helper (unchanged)
59
  # -----------------------
60
  def split_report(text):
61
  text = text.strip()
@@ -69,6 +69,19 @@ def split_report(text):
69
  return text, ""
70
  return text[:idx].strip(), text[idx:].strip()
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # -----------------------
73
  # Analyze Function
74
  # -----------------------
@@ -121,91 +134,41 @@ def analyze(albumin, creatinine, glucose, crp, mcv, rdw, alp,
121
  patient_input += f"- {biomarker}: {value} {unit} β†’ {statuses[biomarker]}\n"
122
 
123
  system_prompt = (
124
- "You are a professional AI Medical Assistant.\n"
125
- "You are analyzing patient demographics (age, height, weight) and Levine biomarker panel values.\n\n"
126
-
127
- "The Levine biomarker panel includes:\n"
128
- "- Albumin\n"
129
- "- Creatinine\n"
130
- "- Glucose\n"
131
- "- C-reactive protein (CRP)\n"
132
- "- Mean Cell Volume (MCV)\n"
133
- "- Red Cell Distribution Width (RDW)\n"
134
- "- Alkaline Phosphatase (ALP)\n"
135
- "- White Blood Cell count (WBC)\n"
136
- "- Lymphocyte percentage\n\n"
137
-
138
- "STRICT RULES:\n"
139
- "- Use ONLY the 9 biomarkers above + age, height, weight.\n"
140
- "- DO NOT use or invent other lab results (e.g., cholesterol, vitamin D, ferritin, ALT, AST, urine results).\n"
141
- "- If a section cannot be addressed with available data, explicitly state: 'Not available from current biomarkers.'\n"
142
- "- Do not give absolute longevity scores. Instead, summarize trends (e.g., 'No major abnormalities suggesting elevated short-term risk.').\n"
143
- "- Nutrient status (Iron, B12, Folate) can only be suggested as possible IF supported by MCV + RDW patterns, but never stated as confirmed.\n"
144
- "- Interpret ALP cautiously: mention bone vs liver as possible sources, but highlight that more tests would be required to confirm.\n"
145
- "- Always highlight limitations where applicable.\n\n"
146
-
147
- "OUTPUT FORMAT (strict, structured, and professional):\n\n"
148
-
149
- "1. Executive Summary\n"
150
- " - Top Priority Issues (based only on provided biomarkers)\n"
151
- " - Key Strengths\n\n"
152
-
153
- "2. System-Specific Analysis\n"
154
- " - Blood Health (MCV, RDW, Lymphocytes, WBC)\n"
155
- " - Protein & Liver Health (Albumin, ALP)\n"
156
- " - Kidney Health (Creatinine)\n"
157
- " - Metabolic Health (Glucose, CRP)\n"
158
- " - Anthropometrics (Age, Height, Weight, BMI)\n"
159
- " - Other systems: Always state 'Not available from current biomarkers.' if data missing\n\n"
160
-
161
- "3. Personalized Action Plan\n"
162
- " - Medical (tests/consults related only to biomarkers β€” e.g., repeat CBC, iron studies if anemia suspected)\n"
163
- " - Nutrition (diet & supplements grounded ONLY in biomarker findings β€” e.g., protein intake if albumin low, anti-inflammatory foods if CRP elevated)\n"
164
- " - Lifestyle (hydration, exercise, sleep β€” general guidance contextualized by BMI and biomarkers)\n"
165
- " - Testing (only mention ferritin, B12, folate, GGT, etc. as follow-up β€” but clarify these are NOT part of current data)\n\n"
166
-
167
- "4. Interaction Alerts\n"
168
- " - Describe ONLY interactions among provided biomarkers (e.g., RDW with MCV for anemia trends, ALP bone/liver origin, WBC with CRP for infection/inflammation)\n\n"
169
-
170
- "5. Tabular Mapping\n"
171
- " - This section must always include a Markdown table.\n"
172
- " - The table must contain exactly four columns:\n"
173
- " | Biomarker | Value | Status (Low/Normal/High) | AI-Inferred Insight |\n"
174
- " - Include ALL 9 Levine biomarkers (Albumin, Creatinine, Glucose, CRP, MCV, RDW, ALP, WBC, Lymphocytes).\n"
175
- " - The first row after the header must begin directly with 'Albumin'.\n"
176
- " - Do NOT add any index numbers (0,1,2...) or empty rows.\n"
177
- " - Each biomarker must appear exactly once as a separate row.\n\n"
178
-
179
- "6. Enhanced AI Insights & Longitudinal Risk\n"
180
- " - Subclinical nutrient predictions ONLY if patterns (MCV + RDW) suggest it β€” state as possible, not confirmed.\n"
181
- " - ALP interpretation limited to bone vs liver origin (uncertain without further tests).\n"
182
- " - WBC & lymphocyte balance for immunity.\n"
183
- " - Risk framing: Highlight if biomarkers suggest resilience or potential stress, but avoid absolute longevity claims.\n\n"
184
-
185
- "STYLE REQUIREMENTS:\n"
186
- "- Use clear section headings and bullet points.\n"
187
- "- Keep language professional, concise, and client-friendly.\n"
188
- "- Format tables cleanly in Markdown.\n"
189
- "- Present output beautifully, like a polished medical summary.\n"
190
- )
191
-
192
 
193
  prompt = system_prompt + "\n" + patient_input
194
 
 
195
  gen = pipe(
196
  prompt,
197
- max_new_tokens=2000,
198
- do_sample=False,
199
- temperature=0.0,
 
 
 
200
  return_full_text=False,
201
  )
202
 
203
- generated = gen[0]["generated_text"].strip()
204
  left, right = split_report(generated)
205
  return left, right
206
 
207
  # -----------------------
208
- # Gradio UI (unchanged)
209
  # -----------------------
210
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
211
  gr.Markdown("# πŸ₯ AI Medical Biomarker Dashboard")
 
55
  return "Normal"
56
 
57
  # -----------------------
58
+ # Splitter helper
59
  # -----------------------
60
  def split_report(text):
61
  text = text.strip()
 
69
  return text, ""
70
  return text[:idx].strip(), text[idx:].strip()
71
 
72
+ # -----------------------
73
+ # Post-processing cleaner (remove repeated lines)
74
+ # -----------------------
75
+ def clean_output(text):
76
+ lines = text.split("\n")
77
+ cleaned = []
78
+ prev_line = None
79
+ for line in lines:
80
+ if line.strip() and line != prev_line: # remove duplicates
81
+ cleaned.append(line)
82
+ prev_line = line
83
+ return "\n".join(cleaned)
84
+
85
  # -----------------------
86
  # Analyze Function
87
  # -----------------------
 
134
  patient_input += f"- {biomarker}: {value} {unit} β†’ {statuses[biomarker]}\n"
135
 
136
  system_prompt = (
137
+ "You are a professional AI Medical Assistant.\n"
138
+ "Generate a structured medical report ONLY using the 9 Levine biomarkers, age, height, and weight.\n"
139
+ "Follow this structure:\n\n"
140
+ "1. Executive Summary\n"
141
+ "2. System-Specific Analysis\n"
142
+ "3. Personalized Action Plan\n"
143
+ "4. Interaction Alerts\n"
144
+ "5. Tabular Mapping (with 4 columns: Biomarker | Value | Status | AI-Inferred Insight)\n"
145
+ "6. Enhanced AI Insights & Longitudinal Risk\n\n"
146
+ "Rules:\n"
147
+ "- Always include all 9 biomarkers in the table.\n"
148
+ "- Do not repeat lines or add unrelated labs.\n"
149
+ "- Keep responses concise, professional, and readable.\n"
150
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  prompt = system_prompt + "\n" + patient_input
153
 
154
+ # ---- FIXED PIPE CALL ----
155
  gen = pipe(
156
  prompt,
157
+ max_new_tokens=1200,
158
+ do_sample=True, # controlled sampling
159
+ temperature=0.3,
160
+ top_p=0.9,
161
+ repetition_penalty=1.2, # prevent loops
162
+ eos_token_id=tokenizer.eos_token_id,
163
  return_full_text=False,
164
  )
165
 
166
+ generated = clean_output(gen[0]["generated_text"].strip())
167
  left, right = split_report(generated)
168
  return left, right
169
 
170
  # -----------------------
171
+ # Gradio UI
172
  # -----------------------
173
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
174
  gr.Markdown("# πŸ₯ AI Medical Biomarker Dashboard")