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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -40
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="", pdf_filepath=""):
164
  from datetime import datetime
165
  current_date = datetime.now().strftime("%B %d, %Y")
166
 
@@ -203,11 +203,12 @@ def build_health_card(profile_image, test_results, summary, patient_name="", pat
203
  </div>
204
 
205
  <div style="display: flex; gap: 15px; justify-content: center; flex-wrap: wrap;">
206
- <a href="{pdf_filepath}" download="Health_Report.pdf">
207
- <button style="padding: 12px 24px; background: linear-gradient(135deg, #4caf50, #45a049); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px; box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3); transition: all 0.3s;">
208
- 📥 Download Report
209
- </button>
210
- </a>
 
211
  </div>
212
  </div>
213
  """
@@ -217,27 +218,28 @@ def build_health_card(profile_image, test_results, summary, patient_name="", pat
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,6 +253,21 @@ def analyze_face(inputs):
251
  test_values[label] = value
252
  r2_scores[label] = 0.0
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  test_results = {
255
  "Hematology":
256
  build_table("🩸 Hematology",
@@ -274,9 +291,12 @@ def analyze_face(inputs):
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,32 +304,53 @@ def analyze_face(inputs):
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,8 +371,8 @@ with gr.Blocks() as demo:
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
 
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
 
 
203
  </div>
204
 
205
  <div style="display: flex; gap: 15px; justify-content: center; flex-wrap: wrap;">
206
+ <button onclick="window.print()" style="padding: 12px 24px; background: linear-gradient(135deg, #4caf50, #45a049); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px; box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3); transition: all 0.3s;">
207
+ 📥 Download Report
208
+ </button>
209
+ <button style="padding: 12px 24px; background: linear-gradient(135deg, #2196f3, #1976d2); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 14px; box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);">
210
+ 📞 Find Labs Near Me
211
+ </button>
212
  </div>
213
  </div>
214
  """
 
218
  current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
219
 
220
  # Modified analyze_face function
221
+ def analyze_face(input_data):
222
+ if isinstance(input_data, str): # Video input (file path in Replit)
223
+ cap = cv2.VideoCapture(input_data)
224
+ if not cap.isOpened():
225
+ return "<div style='color:red;'>⚠️ Error: Could not open video.</div>", None
226
+ ret, frame = cap.read()
227
+ cap.release()
228
+ if not ret:
229
+ return "<div style='color:red;'>⚠️ Error: Could not read video frame.</div>", None
230
+ else: # Image input
231
+ frame = input_data
232
+ if frame is None:
233
+ return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
234
 
235
  # Resize image to reduce processing time
236
+ frame = cv2.resize(frame, (640, 480)) # Adjust resolution for Replit
237
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
238
  result = face_mesh.process(frame_rgb)
 
239
  if not result.multi_face_landmarks:
240
  return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
241
  landmarks = result.multi_face_landmarks[0].landmark # Fixed: Use integer index
242
  features = extract_features(frame_rgb, landmarks)
 
243
  test_values = {}
244
  r2_scores = {}
245
 
 
253
  test_values[label] = value
254
  r2_scores[label] = 0.0
255
 
256
+ gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
257
+ green_std = np.std(frame_rgb[:, :, 1]) / 255
258
+ brightness_std = np.std(gray) / 255
259
+ tone_index = np.mean(frame_rgb[100:150, 100:150]) / 255 if frame_rgb[
260
+ 100:150, 100:150].size else 0.5
261
+ hr_features = [brightness_std, green_std, tone_index]
262
+ heart_rate = float(np.clip(hr_model.predict([hr_features])[0], 60, 100))
263
+ skin_patch = frame_rgb[100:150, 100:150]
264
+ skin_tone_index = np.mean(skin_patch) / 255 if skin_patch.size else 0.5
265
+ brightness_variation = np.std(cv2.cvtColor(frame_rgb,
266
+ cv2.COLOR_RGB2GRAY)) / 255
267
+ spo2_features = [heart_rate, brightness_variation, skin_tone_index]
268
+ spo2 = spo2_model.predict([spo2_features])[0]
269
+ rr = int(12 + abs(heart_rate % 5 - 2))
270
+
271
  test_results = {
272
  "Hematology":
273
  build_table("🩸 Hematology",
 
291
  ("Potassium", test_values["Potassium"], (3.5, 5.1))]),
292
  "Vitals":
293
  build_table("❤️ Vitals",
294
+ [("SpO2", spo2, (95, 100)),
295
+ ("Heart Rate", heart_rate, (60, 100)),
296
+ ("Respiratory Rate", rr, (12, 20)),
297
+ ("Temperature", test_values["Temperature"], (97, 99)),
298
+ ("BP Systolic", test_values["BP Systolic"], (90, 120)),
299
+ ("BP Diastolic", test_values["BP Diastolic"], (60, 80))])
300
  }
301
 
302
  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>"
 
304
  _, buffer = cv2.imencode('.png', frame_rgb)
305
  profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
306
 
 
 
 
 
 
 
 
307
  # Use global patient details
308
+ global current_patient_details
309
  health_card_html = build_health_card(
310
  profile_image_base64,
311
  test_results,
312
  summary,
313
+ current_patient_details['name'],
314
+ current_patient_details['age'],
315
+ current_patient_details['gender'],
316
+ current_patient_details['id']
 
317
  )
318
 
319
+ # Generate PDF and return for download
320
+ pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
321
+ pdf_result, pdf_filepath = save_results_to_pdf(test_results, pdf_filename)
322
+
323
+ if pdf_filepath:
324
+ # Copy the PDF to a temporary directory for Gradio to serve it
325
+ temp_pdf_path = "/tmp/" + os.path.basename(pdf_filepath)
326
+ shutil.copy(pdf_filepath, temp_pdf_path)
327
+
328
+ return health_card_html, temp_pdf_path
329
 
330
 
331
+ # Modified route_inputs function
332
+ def route_inputs(mode, image, video, patient_name, patient_age, patient_gender, patient_id):
333
+ if mode == "Image" and image is None:
334
+ return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
335
+ if mode == "Video" and video is None:
336
+ return "<div style='color:red;'>⚠️ Error: No video provided.</div>", None
337
 
338
+ # Store patient details globally for use in analyze_face
339
+ global current_patient_details
340
+ current_patient_details = {
341
+ 'name': patient_name,
342
+ 'age': patient_age,
343
+ 'gender': patient_gender,
344
+ 'id': patient_id
345
+ }
346
+
347
+ health_card_html, pdf_file_path = analyze_face(image if mode == "Image" else video)
348
+ return health_card_html, pdf_file_path
349
+
350
+
351
+ # Create Gradio interface
352
+ with gr.Blocks() as demo:
353
+ gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
354
  with gr.Row():
355
  with gr.Column():
356
  gr.Markdown("### Patient Information")
 
371
  result_html = gr.HTML(label="🧪 Health Report Table")
372
  result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
373
 
374
+ submit_btn.click(fn=route_inputs,
375
+ inputs=[mode_selector, image_input, video_input, patient_name, patient_age, patient_gender, patient_id],
376
  outputs=[result_html, result_pdf])
377
 
378
  # Launch Gradio for Replit