Rammohan0504 commited on
Commit
bb72e08
·
verified ·
1 Parent(s): 07c76c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -33
app.py CHANGED
@@ -47,7 +47,6 @@ def train_model(output_range):
47
  model = LinearRegression().fit(X, y)
48
  return model
49
 
50
-
51
  # Load models
52
  try:
53
  hemoglobin_model = joblib.load("hemoglobin_model_from_anemia_dataset.pkl")
@@ -160,10 +159,13 @@ 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
 
 
 
 
167
  html = f"""
168
  <div id="health-card" style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 700px; margin: 20px auto; border-radius: 16px; background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%); border: 2px solid #ddd; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15); padding: 30px; color: #1a1a1a;">
169
 
@@ -203,22 +205,14 @@ 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
- <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
- <style>
215
- @media print {{
216
- /* Hide input sections during print */
217
- .gradio-container {{ display: block; }}
218
- /* Keep only the health card visible */
219
- #health-card {{ display: block; }}
220
- }}
221
- </style>
222
  """
223
  return html
224
 
@@ -246,7 +240,7 @@ def analyze_face(input_data):
246
  result = face_mesh.process(frame_rgb)
247
  if not result.multi_face_landmarks:
248
  return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
249
- landmarks = result.multi_face_landmarks[0].landmark # Fixed: Use integer index
250
  features = extract_features(frame_rgb, landmarks)
251
  test_values = {}
252
  r2_scores = {}
@@ -264,14 +258,12 @@ def analyze_face(input_data):
264
  gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
265
  green_std = np.std(frame_rgb[:, :, 1]) / 255
266
  brightness_std = np.std(gray) / 255
267
- tone_index = np.mean(frame_rgb[100:150, 100:150]) / 255 if frame_rgb[
268
- 100:150, 100:150].size else 0.5
269
  hr_features = [brightness_std, green_std, tone_index]
270
  heart_rate = float(np.clip(hr_model.predict([hr_features])[0], 60, 100))
271
  skin_patch = frame_rgb[100:150, 100:150]
272
  skin_tone_index = np.mean(skin_patch) / 255 if skin_patch.size else 0.5
273
- brightness_variation = np.std(cv2.cvtColor(frame_rgb,
274
- cv2.COLOR_RGB2GRAY)) / 255
275
  spo2_features = [heart_rate, brightness_variation, skin_tone_index]
276
  spo2 = spo2_model.predict([spo2_features])[0]
277
  rr = int(12 + abs(heart_rate % 5 - 2))
@@ -281,8 +273,7 @@ def analyze_face(input_data):
281
  build_table("🩸 Hematology",
282
  [("Hemoglobin", test_values["Hemoglobin"], (13.5, 17.5)),
283
  ("WBC Count", test_values["WBC Count"], (4.0, 11.0)),
284
- ("Platelet Count", test_values["Platelet Count"],
285
- (150, 450))]),
286
  "Iron Panel":
287
  build_table("🧬 Iron Panel",
288
  [("Iron", test_values["Iron"], (60, 170)),
@@ -312,18 +303,6 @@ def analyze_face(input_data):
312
  _, buffer = cv2.imencode('.png', frame_rgb)
313
  profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
314
 
315
- # Use global patient details
316
- global current_patient_details
317
- health_card_html = build_health_card(
318
- profile_image_base64,
319
- test_results,
320
- summary,
321
- current_patient_details['name'],
322
- current_patient_details['age'],
323
- current_patient_details['gender'],
324
- current_patient_details['id']
325
- )
326
-
327
  # Generate PDF and return for download
328
  pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
329
  pdf_result, pdf_filepath = save_results_to_pdf(test_results, pdf_filename)
@@ -333,9 +312,20 @@ def analyze_face(input_data):
333
  temp_pdf_path = "/tmp/" + os.path.basename(pdf_filepath)
334
  shutil.copy(pdf_filepath, temp_pdf_path)
335
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  return health_card_html, temp_pdf_path
337
 
338
-
339
  # Modified route_inputs function
340
  def route_inputs(mode, image, video, patient_name, patient_age, patient_gender, patient_id):
341
  if mode == "Image" and image is None:
@@ -355,7 +345,6 @@ def route_inputs(mode, image, video, patient_name, patient_age, patient_gender,
355
  health_card_html, pdf_file_path = analyze_face(image if mode == "Image" else video)
356
  return health_card_html, pdf_file_path
357
 
358
-
359
  # Create Gradio interface
360
  with gr.Blocks() as demo:
361
  gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
 
47
  model = LinearRegression().fit(X, y)
48
  return model
49
 
 
50
  # Load models
51
  try:
52
  hemoglobin_model = joblib.load("hemoglobin_model_from_anemia_dataset.pkl")
 
159
  return f"Error saving PDF: {str(e)}", None
160
 
161
  # Build health card layout
162
+ def build_health_card(profile_image, test_results, summary, pdf_filepath, patient_name="", patient_age="", patient_gender="", patient_id=""):
163
  from datetime import datetime
164
  current_date = datetime.now().strftime("%B %d, %Y")
165
 
166
+ # Use a relative path for the download link to work in Gradio
167
+ pdf_filename = os.path.basename(pdf_filepath) if pdf_filepath else "health_report.pdf"
168
+
169
  html = f"""
170
  <div id="health-card" style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 700px; margin: 20px auto; border-radius: 16px; background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%); border: 2px solid #ddd; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15); padding: 30px; color: #1a1a1a;">
171
 
 
205
  </div>
206
 
207
  <div style="display: flex; gap: 15px; justify-content: center; flex-wrap: wrap;">
208
+ <a href="/file=/tmp/{pdf_filename}" download="{pdf_filename}" 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; text-decoration: none;">
209
  📥 Download Report
210
+ </a>
211
  <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);">
212
  📞 Find Labs Near Me
213
  </button>
214
  </div>
215
  </div>
 
 
 
 
 
 
 
 
216
  """
217
  return html
218
 
 
240
  result = face_mesh.process(frame_rgb)
241
  if not result.multi_face_landmarks:
242
  return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
243
+ landmarks = result.multi_face_landmarks[0].landmark
244
  features = extract_features(frame_rgb, landmarks)
245
  test_values = {}
246
  r2_scores = {}
 
258
  gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
259
  green_std = np.std(frame_rgb[:, :, 1]) / 255
260
  brightness_std = np.std(gray) / 255
261
+ tone_index = np.mean(frame_rgb[100:150, 100:150]) / 255 if frame_rgb[100:150, 100:150].size else 0.5
 
262
  hr_features = [brightness_std, green_std, tone_index]
263
  heart_rate = float(np.clip(hr_model.predict([hr_features])[0], 60, 100))
264
  skin_patch = frame_rgb[100:150, 100:150]
265
  skin_tone_index = np.mean(skin_patch) / 255 if skin_patch.size else 0.5
266
+ brightness_variation = np.std(cv2.cvtColor(frame_rgb, 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))
 
273
  build_table("🩸 Hematology",
274
  [("Hemoglobin", test_values["Hemoglobin"], (13.5, 17.5)),
275
  ("WBC Count", test_values["WBC Count"], (4.0, 11.0)),
276
+ ("Platelet Count", test_values["Platelet Count"], (150, 450))]),
 
277
  "Iron Panel":
278
  build_table("🧬 Iron Panel",
279
  [("Iron", test_values["Iron"], (60, 170)),
 
303
  _, buffer = cv2.imencode('.png', frame_rgb)
304
  profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
305
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  # Generate PDF and return for download
307
  pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
308
  pdf_result, pdf_filepath = save_results_to_pdf(test_results, pdf_filename)
 
312
  temp_pdf_path = "/tmp/" + os.path.basename(pdf_filepath)
313
  shutil.copy(pdf_filepath, temp_pdf_path)
314
 
315
+ # Pass pdf_filepath to build_health_card
316
+ health_card_html = build_health_card(
317
+ profile_image_base64,
318
+ test_results,
319
+ summary,
320
+ temp_pdf_path, # Pass the PDF path
321
+ current_patient_details['name'],
322
+ current_patient_details['age'],
323
+ current_patient_details['gender'],
324
+ current_patient_details['id']
325
+ )
326
+
327
  return health_card_html, temp_pdf_path
328
 
 
329
  # Modified route_inputs function
330
  def route_inputs(mode, image, video, patient_name, patient_age, patient_gender, patient_id):
331
  if mode == "Image" and image is None:
 
345
  health_card_html, pdf_file_path = analyze_face(image if mode == "Image" else video)
346
  return health_card_html, pdf_file_path
347
 
 
348
  # Create Gradio interface
349
  with gr.Blocks() as demo:
350
  gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")