Rammohan0504 commited on
Commit
3928155
·
verified ·
1 Parent(s): 4158201

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -81
app.py CHANGED
@@ -160,7 +160,7 @@ def save_results_to_pdf(test_results, filename):
160
  return f"Error saving PDF: {str(e)}", None
161
 
162
  # Build health card layout
163
- def build_health_card(profile_image, test_results, summary, patient_name="", patient_age="", patient_gender="", patient_id=""):
164
  from datetime import datetime
165
  current_date = datetime.now().strftime("%B %d, %Y")
166
 
@@ -210,12 +210,6 @@ def build_health_card(profile_image, test_results, summary, patient_name="", pat
210
  </a>
211
  </div>
212
  </div>
213
- <style>
214
- @media print {{
215
- /* Hide input sections during print */
216
- .gradio-container {{ display: none; }}
217
- }}
218
- </style>
219
  """
220
  return html
221
 
@@ -223,28 +217,27 @@ def build_health_card(profile_image, test_results, summary, patient_name="", pat
223
  current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
224
 
225
  # Modified analyze_face function
226
- def analyze_face(input_data):
227
- if isinstance(input_data, str): # Video input (file path in Replit)
228
- cap = cv2.VideoCapture(input_data)
229
- if not cap.isOpened():
230
- return "<div style='color:red;'>⚠️ Error: Could not open video.</div>", None
231
- ret, frame = cap.read()
232
- cap.release()
233
- if not ret:
234
- return "<div style='color:red;'>⚠️ Error: Could not read video frame.</div>", None
235
- else: # Image input
236
- frame = input_data
237
- if frame is None:
238
- return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
239
 
240
  # Resize image to reduce processing time
241
- frame = cv2.resize(frame, (640, 480)) # Adjust resolution for Replit
242
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
243
  result = face_mesh.process(frame_rgb)
 
244
  if not result.multi_face_landmarks:
245
  return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
246
  landmarks = result.multi_face_landmarks[0].landmark # Fixed: Use integer index
247
  features = extract_features(frame_rgb, landmarks)
 
248
  test_values = {}
249
  r2_scores = {}
250
 
@@ -258,21 +251,6 @@ def analyze_face(input_data):
258
  test_values[label] = value
259
  r2_scores[label] = 0.0
260
 
261
- gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
262
- green_std = np.std(frame_rgb[:, :, 1]) / 255
263
- brightness_std = np.std(gray) / 255
264
- tone_index = np.mean(frame_rgb[100:150, 100:150]) / 255 if frame_rgb[
265
- 100:150, 100:150].size else 0.5
266
- hr_features = [brightness_std, green_std, tone_index]
267
- heart_rate = float(np.clip(hr_model.predict([hr_features])[0], 60, 100))
268
- skin_patch = frame_rgb[100:150, 100:150]
269
- skin_tone_index = np.mean(skin_patch) / 255 if skin_patch.size else 0.5
270
- brightness_variation = np.std(cv2.cvtColor(frame_rgb,
271
- cv2.COLOR_RGB2GRAY)) / 255
272
- spo2_features = [heart_rate, brightness_variation, skin_tone_index]
273
- spo2 = spo2_model.predict([spo2_features])[0]
274
- rr = int(12 + abs(heart_rate % 5 - 2))
275
-
276
  test_results = {
277
  "Hematology":
278
  build_table("🩸 Hematology",
@@ -296,12 +274,9 @@ def analyze_face(input_data):
296
  ("Potassium", test_values["Potassium"], (3.5, 5.1))]),
297
  "Vitals":
298
  build_table("❤️ Vitals",
299
- [("SpO2", spo2, (95, 100)),
300
- ("Heart Rate", heart_rate, (60, 100)),
301
- ("Respiratory Rate", rr, (12, 20)),
302
- ("Temperature", test_values["Temperature"], (97, 99)),
303
- ("BP Systolic", test_values["BP Systolic"], (90, 120)),
304
- ("BP Diastolic", test_values["BP Diastolic"], (60, 80))])
305
  }
306
 
307
  summary = "<ul><li>Your hemoglobin is a bit low — this could mean mild anemia.</li><li>Low iron storage detected — consider an iron profile test.</li><li>Elevated bilirubin — possible jaundice. Recommend LFT.</li><li>High HbA1c — prediabetes indication. Recommend glucose check.</li><li>Low SpO₂ — suggest retesting with a pulse oximeter.</li></ul>"
@@ -309,53 +284,32 @@ def analyze_face(input_data):
309
  _, buffer = cv2.imencode('.png', frame_rgb)
310
  profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
311
 
 
 
 
 
 
 
 
312
  # Use global patient details
313
- global current_patient_details
314
  health_card_html = build_health_card(
315
  profile_image_base64,
316
  test_results,
317
  summary,
318
- current_patient_details['name'],
319
- current_patient_details['age'],
320
- current_patient_details['gender'],
321
- current_patient_details['id']
 
322
  )
323
 
324
- # Generate PDF and return for download
325
- pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
326
- pdf_result, pdf_filepath = save_results_to_pdf(test_results, pdf_filename)
327
-
328
- if pdf_filepath:
329
- # Copy the PDF to a temporary directory for Gradio to serve it
330
- temp_pdf_path = "/tmp/" + os.path.basename(pdf_filepath)
331
- shutil.copy(pdf_filepath, temp_pdf_path)
332
-
333
- return health_card_html, temp_pdf_path
334
-
335
-
336
- # Modified route_inputs function
337
- def route_inputs(mode, image, video, patient_name, patient_age, patient_gender, patient_id):
338
- if mode == "Image" and image is None:
339
- return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
340
- if mode == "Video" and video is None:
341
- return "<div style='color:red;'>⚠️ Error: No video provided.</div>", None
342
-
343
- # Store patient details globally for use in analyze_face
344
- global current_patient_details
345
- current_patient_details = {
346
- 'name': patient_name,
347
- 'age': patient_age,
348
- 'gender': patient_gender,
349
- 'id': patient_id
350
- }
351
-
352
- health_card_html, pdf_file_path = analyze_face(image if mode == "Image" else video)
353
- return health_card_html, pdf_file_path
354
 
355
 
356
- # Create Gradio interface
357
  with gr.Blocks() as demo:
358
- gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
 
359
  with gr.Row():
360
  with gr.Column():
361
  gr.Markdown("### Patient Information")
@@ -376,8 +330,8 @@ with gr.Blocks() as demo:
376
  result_html = gr.HTML(label="🧪 Health Report Table")
377
  result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
378
 
379
- submit_btn.click(fn=route_inputs,
380
- inputs=[mode_selector, image_input, video_input, patient_name, patient_age, patient_gender, patient_id],
381
  outputs=[result_html, result_pdf])
382
 
383
  # Launch Gradio for Replit
 
160
  return f"Error saving PDF: {str(e)}", None
161
 
162
  # Build health card layout
163
+ def build_health_card(profile_image, test_results, summary, patient_name="", patient_age="", patient_gender="", patient_id="", pdf_filepath=""):
164
  from datetime import datetime
165
  current_date = datetime.now().strftime("%B %d, %Y")
166
 
 
210
  </a>
211
  </div>
212
  </div>
 
 
 
 
 
 
213
  """
214
  return html
215
 
 
217
  current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
218
 
219
  # Modified analyze_face function
220
+ def analyze_face(inputs):
221
+ image = inputs[0]
222
+ patient_name = inputs[1]
223
+ patient_age = inputs[2]
224
+ patient_gender = inputs[3]
225
+ patient_id = inputs[4]
226
+ mode = inputs[5]
227
+
228
+ if mode == "Image" and image is None:
229
+ return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
 
 
 
230
 
231
  # Resize image to reduce processing time
232
+ frame = cv2.resize(image, (640, 480)) # Adjust resolution for Replit
233
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
234
  result = face_mesh.process(frame_rgb)
235
+
236
  if not result.multi_face_landmarks:
237
  return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
238
  landmarks = result.multi_face_landmarks[0].landmark # Fixed: Use integer index
239
  features = extract_features(frame_rgb, landmarks)
240
+
241
  test_values = {}
242
  r2_scores = {}
243
 
 
251
  test_values[label] = value
252
  r2_scores[label] = 0.0
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  test_results = {
255
  "Hematology":
256
  build_table("🩸 Hematology",
 
274
  ("Potassium", test_values["Potassium"], (3.5, 5.1))]),
275
  "Vitals":
276
  build_table("❤️ Vitals",
277
+ [("SpO2", 98, (95, 100)),
278
+ ("Heart Rate", 72, (60, 100)),
279
+ ("Temperature", 98.6, (97, 99))])
 
 
 
280
  }
281
 
282
  summary = "<ul><li>Your hemoglobin is a bit low — this could mean mild anemia.</li><li>Low iron storage detected — consider an iron profile test.</li><li>Elevated bilirubin — possible jaundice. Recommend LFT.</li><li>High HbA1c — prediabetes indication. Recommend glucose check.</li><li>Low SpO₂ — suggest retesting with a pulse oximeter.</li></ul>"
 
284
  _, buffer = cv2.imencode('.png', frame_rgb)
285
  profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
286
 
287
+ # Create a temporary file path for the PDF
288
+ pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
289
+ pdf_filepath = f"/tmp/{pdf_filename}"
290
+
291
+ # Save the PDF
292
+ pdf_result, _ = save_results_to_pdf(test_results, pdf_filepath)
293
+
294
  # Use global patient details
 
295
  health_card_html = build_health_card(
296
  profile_image_base64,
297
  test_results,
298
  summary,
299
+ patient_name,
300
+ patient_age,
301
+ patient_gender,
302
+ patient_id,
303
+ pdf_filepath=pdf_filepath
304
  )
305
 
306
+ return health_card_html, pdf_filepath
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
 
308
 
309
+ # Gradio interface setup
310
  with gr.Blocks() as demo:
311
+ gr.Markdown("""# 🧠 Face-Based Lab Test AI Report""")
312
+
313
  with gr.Row():
314
  with gr.Column():
315
  gr.Markdown("### Patient Information")
 
330
  result_html = gr.HTML(label="🧪 Health Report Table")
331
  result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
332
 
333
+ submit_btn.click(fn=analyze_face,
334
+ inputs=[image_input, patient_name, patient_age, patient_gender, patient_id, mode_selector],
335
  outputs=[result_html, result_pdf])
336
 
337
  # Launch Gradio for Replit