Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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,7 +159,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 |
|
@@ -224,121 +223,31 @@ def build_health_card(profile_image, test_results, summary, patient_name="", pat
|
|
224 |
# Initialize global variable for patient details
|
225 |
current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
|
226 |
|
227 |
-
#
|
228 |
-
def
|
229 |
-
if
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
ret, frame = cap.read()
|
234 |
-
cap.release()
|
235 |
-
if not ret:
|
236 |
-
return "<div style='color:red;'>⚠️ Error: Could not read video frame.</div>", None
|
237 |
-
else: # Image input
|
238 |
-
frame = input_data
|
239 |
-
if frame is None:
|
240 |
-
return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
|
241 |
-
|
242 |
-
# Resize image to reduce processing time
|
243 |
-
frame = cv2.resize(frame, (640, 480)) # Adjust resolution for Replit
|
244 |
-
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
245 |
-
result = face_mesh.process(frame_rgb)
|
246 |
-
if not result.multi_face_landmarks:
|
247 |
-
return "<div style='color:red;'>⚠️ Error: Face not detected.</div>", None
|
248 |
-
landmarks = result.multi_face_landmarks[0].landmark # Fixed: Use integer index
|
249 |
-
features = extract_features(frame_rgb, landmarks)
|
250 |
-
test_values = {}
|
251 |
-
r2_scores = {}
|
252 |
-
|
253 |
-
for label in models:
|
254 |
-
if label == "Hemoglobin":
|
255 |
-
prediction = models[label].predict([features])[0]
|
256 |
-
test_values[label] = prediction
|
257 |
-
r2_scores[label] = 0.385
|
258 |
-
else:
|
259 |
-
value = models[label].predict([[random.uniform(0.2, 0.5) for _ in range(7)]])[0]
|
260 |
-
test_values[label] = value
|
261 |
-
r2_scores[label] = 0.0
|
262 |
-
|
263 |
-
gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
|
264 |
-
green_std = np.std(frame_rgb[:, :, 1]) / 255
|
265 |
-
brightness_std = np.std(gray) / 255
|
266 |
-
tone_index = np.mean(frame_rgb[100:150, 100:150]) / 255 if frame_rgb[
|
267 |
-
100:150, 100:150].size else 0.5
|
268 |
-
hr_features = [brightness_std, green_std, tone_index]
|
269 |
-
heart_rate = float(np.clip(hr_model.predict([hr_features])[0], 60, 100))
|
270 |
-
skin_patch = frame_rgb[100:150, 100:150]
|
271 |
-
skin_tone_index = np.mean(skin_patch) / 255 if skin_patch.size else 0.5
|
272 |
-
brightness_variation = np.std(cv2.cvtColor(frame_rgb,
|
273 |
-
cv2.COLOR_RGB2GRAY)) / 255
|
274 |
-
spo2_features = [heart_rate, brightness_variation, skin_tone_index]
|
275 |
-
spo2 = spo2_model.predict([spo2_features])[0]
|
276 |
-
rr = int(12 + abs(heart_rate % 5 - 2))
|
277 |
-
|
278 |
-
test_results = {
|
279 |
-
"Hematology":
|
280 |
-
build_table("🩸 Hematology",
|
281 |
-
[("Hemoglobin", test_values["Hemoglobin"], (13.5, 17.5)),
|
282 |
-
("WBC Count", test_values["WBC Count"], (4.0, 11.0)),
|
283 |
-
("Platelet Count", test_values["Platelet Count"],
|
284 |
-
(150, 450))]),
|
285 |
-
"Iron Panel":
|
286 |
-
build_table("🧬 Iron Panel",
|
287 |
-
[("Iron", test_values["Iron"], (60, 170)),
|
288 |
-
("Ferritin", test_values["Ferritin"], (30, 300)),
|
289 |
-
("TIBC", test_values["TIBC"], (250, 400))]),
|
290 |
-
"Liver & Kidney":
|
291 |
-
build_table("🧬 Liver & Kidney",
|
292 |
-
[("Bilirubin", test_values["Bilirubin"], (0.3, 1.2)),
|
293 |
-
("Creatinine", test_values["Creatinine"], (0.6, 1.2)),
|
294 |
-
("Urea", test_values["Urea"], (7, 20))]),
|
295 |
-
"Electrolytes":
|
296 |
-
build_table("🧪 Electrolytes",
|
297 |
-
[("Sodium", test_values["Sodium"], (135, 145)),
|
298 |
-
("Potassium", test_values["Potassium"], (3.5, 5.1))]),
|
299 |
-
"Vitals":
|
300 |
-
build_table("❤️ Vitals",
|
301 |
-
[("SpO2", spo2, (95, 100)),
|
302 |
-
("Heart Rate", heart_rate, (60, 100)),
|
303 |
-
("Temperature", test_values["Temperature"], (97, 99)),
|
304 |
-
("BP Systolic", test_values["BP Systolic"], (90, 120)),
|
305 |
-
("BP Diastolic", test_values["BP Diastolic"], (60, 80))])
|
306 |
-
}
|
307 |
-
|
308 |
-
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 |
-
|
310 |
-
_, buffer = cv2.imencode('.png', frame_rgb)
|
311 |
-
profile_image_base64 = base64.b64encode(buffer).decode('utf-8')
|
312 |
-
|
313 |
-
# Use global patient details
|
314 |
-
global current_patient_details
|
315 |
-
health_card_html = build_health_card(
|
316 |
-
profile_image_base64,
|
317 |
-
test_results,
|
318 |
-
summary,
|
319 |
-
current_patient_details['name'],
|
320 |
-
current_patient_details['age'],
|
321 |
-
current_patient_details['gender'],
|
322 |
-
current_patient_details['id']
|
323 |
-
)
|
324 |
|
325 |
-
#
|
326 |
-
|
327 |
-
|
|
|
|
|
|
|
|
|
|
|
328 |
|
329 |
-
if
|
330 |
-
|
331 |
-
temp_pdf_path = "/tmp/" + os.path.basename(pdf_filepath)
|
332 |
-
shutil.copy(pdf_filepath, temp_pdf_path)
|
333 |
-
|
334 |
-
return health_card_html, temp_pdf_path
|
335 |
|
336 |
|
337 |
# Create Gradio interface
|
338 |
with gr.Blocks() as demo:
|
339 |
gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
|
340 |
with gr.Row():
|
341 |
-
with gr.Column():
|
342 |
gr.Markdown("### Patient Information")
|
343 |
patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
|
344 |
patient_age = gr.Number(label="Age", value=25, minimum=1, maximum=120)
|
@@ -353,10 +262,13 @@ with gr.Blocks() as demo:
|
|
353 |
video_input = gr.Video(label="Upload Face Video",
|
354 |
sources=["upload", "webcam"])
|
355 |
submit_btn = gr.Button("🔍 Analyze")
|
356 |
-
with gr.Column():
|
357 |
result_html = gr.HTML(label="🧪 Health Report Table")
|
358 |
result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
|
359 |
|
360 |
-
|
|
|
|
|
|
|
361 |
# Launch Gradio for Replit
|
362 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
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, patient_name="", patient_age="", patient_gender="", patient_id="", pdf_filepath=""):
|
163 |
from datetime import datetime
|
164 |
current_date = datetime.now().strftime("%B %d, %Y")
|
165 |
|
|
|
223 |
# Initialize global variable for patient details
|
224 |
current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
|
225 |
|
226 |
+
# Route the inputs to the correct function
|
227 |
+
def route_inputs(mode, image, video, patient_name, patient_age, patient_gender, patient_id):
|
228 |
+
if mode == "Image" and image is None:
|
229 |
+
return "<div style='color:red;'>⚠️ Error: No image provided.</div>", None
|
230 |
+
if mode == "Video" and video is None:
|
231 |
+
return "<div style='color:red;'>⚠️ Error: No video provided.</div>", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
|
233 |
+
# Store patient details globally for use in analyze_face
|
234 |
+
global current_patient_details
|
235 |
+
current_patient_details = {
|
236 |
+
'name': patient_name,
|
237 |
+
'age': patient_age,
|
238 |
+
'gender': patient_gender,
|
239 |
+
'id': patient_id
|
240 |
+
}
|
241 |
|
242 |
+
health_card_html, pdf_file_path = analyze_face(image if mode == "Image" else video)
|
243 |
+
return health_card_html, pdf_file_path
|
|
|
|
|
|
|
|
|
244 |
|
245 |
|
246 |
# Create Gradio interface
|
247 |
with gr.Blocks() as demo:
|
248 |
gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
|
249 |
with gr.Row():
|
250 |
+
with gr.Column(elem_id="input-container"):
|
251 |
gr.Markdown("### Patient Information")
|
252 |
patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
|
253 |
patient_age = gr.Number(label="Age", value=25, minimum=1, maximum=120)
|
|
|
262 |
video_input = gr.Video(label="Upload Face Video",
|
263 |
sources=["upload", "webcam"])
|
264 |
submit_btn = gr.Button("🔍 Analyze")
|
265 |
+
with gr.Column(elem_id="output-container"):
|
266 |
result_html = gr.HTML(label="🧪 Health Report Table")
|
267 |
result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
|
268 |
|
269 |
+
submit_btn.click(fn=route_inputs,
|
270 |
+
inputs=[mode_selector, image_input, video_input, patient_name, patient_age, patient_gender, patient_id],
|
271 |
+
outputs=[result_html, result_pdf])
|
272 |
+
|
273 |
# Launch Gradio for Replit
|
274 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|