Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
|
@@ -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 |
-
<
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
|
|
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(
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
|
|
|
|
|
|
230 |
|
231 |
# Resize image to reduce processing time
|
232 |
-
frame = cv2.resize(
|
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,12 +253,28 @@ 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",
|
257 |
[("Hemoglobin", test_values["Hemoglobin"], (13.5, 17.5)),
|
258 |
("WBC Count", test_values["WBC Count"], (4.0, 11.0)),
|
259 |
-
("Platelet Count", test_values["Platelet Count"],
|
|
|
260 |
"Iron Panel":
|
261 |
build_table("🧬 Iron Panel",
|
262 |
[("Iron", test_values["Iron"], (60, 170)),
|
@@ -273,9 +291,12 @@ def analyze_face(inputs):
|
|
273 |
("Potassium", test_values["Potassium"], (3.5, 5.1))]),
|
274 |
"Vitals":
|
275 |
build_table("❤️ Vitals",
|
276 |
-
[("SpO2",
|
277 |
-
("Heart Rate",
|
278 |
-
("
|
|
|
|
|
|
|
279 |
}
|
280 |
|
281 |
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>"
|
@@ -283,32 +304,53 @@ def analyze_face(inputs):
|
|
283 |
_, buffer = cv2.imencode('.png', frame_rgb)
|
284 |
profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
|
285 |
|
286 |
-
# Create a temporary file path for the PDF
|
287 |
-
pdf_filename = f"Health_Report_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
|
288 |
-
pdf_filepath = f"/tmp/{pdf_filename}"
|
289 |
-
|
290 |
-
# Save the PDF
|
291 |
-
pdf_result, _ = save_results_to_pdf(test_results, pdf_filepath)
|
292 |
-
|
293 |
# Use global patient details
|
|
|
294 |
health_card_html = build_health_card(
|
295 |
profile_image_base64,
|
296 |
test_results,
|
297 |
summary,
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
pdf_filepath=pdf_filepath
|
303 |
)
|
304 |
|
305 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
306 |
|
307 |
|
308 |
-
#
|
309 |
-
|
310 |
-
|
|
|
|
|
|
|
311 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
312 |
with gr.Row():
|
313 |
with gr.Column():
|
314 |
gr.Markdown("### Patient Information")
|
@@ -329,8 +371,8 @@ with gr.Blocks() as demo:
|
|
329 |
result_html = gr.HTML(label="🧪 Health Report Table")
|
330 |
result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
|
331 |
|
332 |
-
submit_btn.click(fn=
|
333 |
-
inputs=[image_input, patient_name, patient_age, patient_gender, patient_id
|
334 |
outputs=[result_html, result_pdf])
|
335 |
|
336 |
# 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",
|
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"],
|
277 |
+
(150, 450))]),
|
278 |
"Iron Panel":
|
279 |
build_table("🧬 Iron Panel",
|
280 |
[("Iron", test_values["Iron"], (60, 170)),
|
|
|
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
|