Muhammadidrees commited on
Commit
84e8f17
·
verified ·
1 Parent(s): 0c52dfa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -91
app.py CHANGED
@@ -70,11 +70,7 @@ def analyze(
70
  albumin, creatinine, glucose, crp, mcv, rdw, alp,
71
  wbc, lymph, age, gender, height, weight
72
  ):
73
- # Validate/constrain inputs
74
- try:
75
- age = int(age)
76
- except Exception:
77
- age = age
78
  try:
79
  height = float(height)
80
  weight = float(weight)
@@ -82,73 +78,30 @@ def analyze(
82
  except Exception:
83
  bmi = "N/A"
84
 
 
 
 
85
  system_prompt = (
86
  "You are a professional AI Medical Assistant.\n"
87
- "You are analyzing patient demographics (age, height, weight) and Levine biomarker panel values.\n\n"
88
-
89
- "The Levine biomarker panel includes:\n"
90
- "- Albumin\n"
91
- "- Creatinine\n"
92
- "- Glucose\n"
93
- "- C-reactive protein (CRP)\n"
94
- "- Mean Cell Volume (MCV)\n"
95
- "- Red Cell Distribution Width (RDW)\n"
96
- "- Alkaline Phosphatase (ALP)\n"
97
- "- White Blood Cell count (WBC)\n"
98
- "- Lymphocyte percentage\n\n"
99
 
100
  "STRICT RULES:\n"
101
- "- Use ONLY the 9 biomarkers above + age, height, weight.\n"
102
- "- DO NOT use or invent other lab results (e.g., cholesterol, vitamin D, ferritin, ALT, AST, urine results).\n"
103
- "- If a section cannot be addressed with available data, explicitly state: 'Not available from current biomarkers.'\n"
104
- "- Do not give absolute longevity scores. Instead, summarize trends (e.g., 'No major abnormalities suggesting elevated short-term risk.').\n"
105
- "- Nutrient status (Iron, B12, Folate) can only be suggested as possible IF supported by MCV + RDW patterns, but never stated as confirmed.\n"
106
- "- Interpret ALP cautiously: mention bone vs liver as possible sources, but highlight that more tests would be required to confirm.\n"
107
- "- Always highlight limitations where applicable.\n\n"
108
-
109
- "OUTPUT FORMAT (strict, structured, and client-friendly):\n\n"
110
-
111
- "1. Executive Summary\n"
112
- " - Top Priority Issues (based only on provided biomarkers)\n"
113
- " - Key Strengths\n\n"
114
-
115
- "2. System-Specific Analysis\n"
116
- " - Blood Health (MCV, RDW, Lymphocytes, WBC)\n"
117
- " - Protein & Liver Health (Albumin, ALP)\n"
118
- " - Kidney Health (Creatinine)\n"
119
- " - Metabolic Health (Glucose, CRP)\n"
120
- " - Anthropometrics (Age, Height, Weight, BMI)\n"
121
- " - Other systems: Always state 'Not available from current biomarkers.' if data missing\n\n"
122
-
123
- "3. Personalized Action Plan\n"
124
- " - Medical (tests/consults related only to biomarkers — e.g., repeat CBC, iron studies if anemia suspected)\n"
125
- " - Nutrition (diet & supplements grounded ONLY in biomarker findings — e.g., protein intake if albumin low, anti-inflammatory foods if CRP elevated)\n"
126
- " - Lifestyle (hydration, exercise, sleep — general guidance contextualized by BMI and biomarkers)\n"
127
- " - Testing (only mention ferritin, B12, folate, GGT, etc. as follow-up — but clarify these are NOT part of current data)\n\n"
128
-
129
- "4. Interaction Alerts\n"
130
- " - 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"
131
-
132
- "5. Tabular Mapping\n"
133
- " - Present a Markdown table: Biomarker → Value → Status (Low/Normal/High) → AI-Inferred Insight → Client-Friendly Message\n"
134
- " - Include ONLY the 9 Levine biomarkers, no extras\n\n"
135
-
136
- "6. Enhanced AI Insights & Longitudinal Risk\n"
137
- " - Subclinical nutrient predictions ONLY if patterns (MCV + RDW) suggest it — state as possible, not confirmed\n"
138
- " - ALP interpretation limited to bone vs liver origin (uncertain without further tests)\n"
139
- " - WBC & lymphocyte balance for immunity\n"
140
- " - Risk framing: Highlight if biomarkers suggest resilience or potential stress, but avoid absolute longevity claims\n\n"
141
-
142
- "STYLE REQUIREMENTS:\n"
143
- "- Use clear section headings and bullet points.\n"
144
- "- Keep language professional but client-friendly.\n"
145
- "- Format tables cleanly in Markdown.\n"
146
- "- Present output beautifully, like a polished medical summary.\n"
147
- )
148
-
149
-
150
-
151
 
 
152
  patient_input = (
153
  f"Patient Profile:\n"
154
  f"- Age: {age}\n"
@@ -170,39 +123,40 @@ def analyze(
170
 
171
  prompt = system_prompt + "\n" + patient_input
172
 
173
- # Generate
174
- # Keep generation parameters conservative for Spaces
175
- gen = pipe(prompt,
176
- max_new_tokens=2500,
177
- do_sample=True,
178
- temperature=0.001,
179
- top_p=0.9,
180
- return_full_text=False)
181
-
182
- # Extract generated text
183
- generated = gen[0].get("generated_text") or gen[0].get("text") or str(gen[0])
 
 
 
 
184
  generated = generated.strip()
185
 
186
- # Clean: some models repeat prompt — attempt to strip prompt if present
187
- # Remove leading prompt echo if it appears
188
- if patient_input.strip() in generated:
189
- generated = generated.split(patient_input.strip())[-1].strip()
190
- # Also remove repeated instructions
191
- if system_prompt.strip() in generated:
192
- generated = generated.split(system_prompt.strip())[-1].strip()
193
 
194
- # Split into left/right panels
195
  left_md, right_md = split_report(generated)
196
 
197
- # If the model output is empty or too short, return a helpful fallback
198
  if len(left_md) < 50 and len(right_md) < 50:
199
- fallback = (
200
- "⚠️ The model returned an unexpectedly short response. Try re-running the report.\n\n"
201
- "**Patient Profile:**\n" + patient_input
202
  )
203
- return fallback, ""
204
  return left_md, right_md
205
 
 
206
  # -----------------------
207
  # Build Gradio app
208
  # -----------------------
 
70
  albumin, creatinine, glucose, crp, mcv, rdw, alp,
71
  wbc, lymph, age, gender, height, weight
72
  ):
73
+ # Validate BMI
 
 
 
 
74
  try:
75
  height = float(height)
76
  weight = float(weight)
 
78
  except Exception:
79
  bmi = "N/A"
80
 
81
+ # -------------------------
82
+ # System prompt (enforce 6 headings)
83
+ # -------------------------
84
  system_prompt = (
85
  "You are a professional AI Medical Assistant.\n"
86
+ "You are analyzing patient demographics (age, height, weight) and the Levine biomarker panel.\n\n"
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  "STRICT RULES:\n"
89
+ "- Use ONLY the 9 biomarkers (Albumin, Creatinine, Glucose, CRP, MCV, RDW, ALP, WBC, Lymphocytes) + Age/Height/Weight.\n"
90
+ "- Do NOT use or invent other labs (cholesterol, ferritin, vitamin D, etc.).\n"
91
+ "- If data missing: explicitly write 'Not available from current biomarkers.'\n"
92
+ "- Always cover ALL SIX SECTIONS with detail:\n"
93
+ " 1. Executive Summary\n"
94
+ " 2. System-Specific Analysis\n"
95
+ " 3. Personalized Action Plan\n"
96
+ " 4. Interaction Alerts\n"
97
+ " 5. Tabular Mapping\n"
98
+ " 6. Enhanced AI Insights & Longitudinal Risk\n"
99
+ "- Use Markdown formatting for readability.\n"
100
+ "- Keep tone professional, clear, and client-friendly.\n"
101
+ "- Tables must be clean Markdown tables.\n"
102
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ # Patient input block
105
  patient_input = (
106
  f"Patient Profile:\n"
107
  f"- Age: {age}\n"
 
123
 
124
  prompt = system_prompt + "\n" + patient_input
125
 
126
+ # -------------------------
127
+ # Generate with strong control
128
+ # -------------------------
129
+ gen = pipe(
130
+ prompt,
131
+ max_new_tokens=3000,
132
+ do_sample=False, # deterministic
133
+ temperature=0.0, # no randomness
134
+ top_p=1.0, # cover all tokens
135
+ repetition_penalty=1.1, # reduce repetition
136
+ return_full_text=False
137
+ )
138
+
139
+ # Extract text
140
+ generated = gen[0].get("generated_text") or gen[0].get("text") or ""
141
  generated = generated.strip()
142
 
143
+ # Remove possible echoes
144
+ for chunk in [patient_input, system_prompt]:
145
+ if chunk.strip() in generated:
146
+ generated = generated.split(chunk.strip())[-1].strip()
 
 
 
147
 
148
+ # Split into panels
149
  left_md, right_md = split_report(generated)
150
 
151
+ # Fallback if empty
152
  if len(left_md) < 50 and len(right_md) < 50:
153
+ return (
154
+ "⚠️ Model response too short. Please re-run.\n\n**Patient Profile:**\n" + patient_input,
155
+ ""
156
  )
 
157
  return left_md, right_md
158
 
159
+
160
  # -----------------------
161
  # Build Gradio app
162
  # -----------------------