Rammohan0504 commited on
Commit
7149a12
·
verified ·
1 Parent(s): ff02b4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -30
app.py CHANGED
@@ -16,9 +16,15 @@ import glob
16
  # Cleanup temporary files on exit
17
  def cleanup_temp_files():
18
  for temp_file in glob.glob("/tmp/Health_Report_*.pdf"):
19
- os.remove(temp_file)
20
- for temp_file in glob.glob("/tmp/health_card.html"):
21
- os.remove(temp_file)
 
 
 
 
 
 
22
  atexit.register(cleanup_temp_files)
23
 
24
  # Initialize the face mesh model
@@ -130,7 +136,7 @@ def build_table(title, rows):
130
  def save_results_to_pdf(profile_image_base64, test_results, summary, patient_name, patient_age, patient_gender, patient_id, filename):
131
  try:
132
  # Generate HTML content
133
- current_date = datetime.now().strftime("%B %d, %Y")
134
  health_card_html = f"""
135
  <!DOCTYPE html>
136
  <html>
@@ -195,36 +201,41 @@ def save_results_to_pdf(profile_image_base64, test_results, summary, patient_nam
195
 
196
  # Save HTML to a temporary file
197
  html_temp_path = "/tmp/health_card.html"
198
- os.makedirs(os.path.dirname(html_temp_path), exist_ok=True)
199
- with open(html_temp_path, "w", encoding="utf-8") as f:
200
- f.write(health_card_html)
201
- print(f"HTML saved to: {html_temp_path}")
 
 
 
 
202
 
203
  # Convert HTML to PDF using pdfkit
204
- pdfkit.from_file(html_temp_path, filename, options={"quiet": ""})
205
- print(f"PDF generated successfully at: {filename}") # Debug log
 
 
 
 
206
 
207
  # Move to /tmp for Gradio access
208
  temp_pdf_path = "/tmp/" + os.path.basename(filename)
209
- shutil.copy(filename, temp_pdf_path)
210
-
211
- if os.path.exists(temp_pdf_path) and os.access(temp_pdf_path, os.R_OK):
212
- return f"PDF saved successfully as {filename}", temp_pdf_path
213
- else:
214
- return "Error: PDF file not accessible.", None
 
 
 
215
  except Exception as e:
216
- print(f"Error saving PDF: {str(e)}") # Debug log
217
- # Fallback: Save HTML for manual conversion
218
- html_fallback_path = "/tmp/health_card_fallback.html"
219
- with open(html_fallback_path, "w", encoding="utf-8") as f:
220
- f.write(health_card_html)
221
- print(f"Fallback HTML saved to: {html_fallback_path}")
222
- return f"Error saving PDF: {str(e)}. Fallback HTML saved at {html_fallback_path}", None
223
 
224
  # Build health card layout
225
  def build_health_card(profile_image, test_results, summary, pdf_filepath, patient_name="", patient_age="", patient_gender="", patient_id=""):
226
- from datetime import datetime
227
- current_date = datetime.now().strftime("%B %d, %Y")
228
 
229
  pdf_filename = os.path.basename(pdf_filepath) if pdf_filepath else "health_report.pdf"
230
 
@@ -291,7 +302,7 @@ current_patient_details = {'name': '', 'age': '', 'gender': '', 'id': ''}
291
 
292
  # Modified analyze_face function
293
  def analyze_face(input_data):
294
- if isinstance(input_data, str): # Video input (file path in Replit)
295
  cap = cv2.VideoCapture(input_data)
296
  if not cap.isOpened():
297
  return "<div style='color:red;'>⚠️ Error: Could not open video.</div>", None
@@ -416,7 +427,7 @@ def route_inputs(mode, image, video, patient_name, patient_age, patient_gender,
416
 
417
  # Create Gradio interface
418
  with gr.Blocks() as demo:
419
- gr.Markdown("""# 🧠 Face-Based Lab Test AI Report (Video Mode)""")
420
  with gr.Row():
421
  with gr.Column():
422
  gr.Markdown("### Patient Information")
@@ -434,12 +445,12 @@ with gr.Blocks() as demo:
434
  sources=["upload", "webcam"])
435
  submit_btn = gr.Button("🔍 Analyze")
436
  with gr.Column():
437
- result_html = gr.HTML(label="🧪 Health Report Table")
438
  result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
439
 
440
  submit_btn.click(fn=route_inputs,
441
  inputs=[mode_selector, image_input, video_input, patient_name, patient_age, patient_gender, patient_id],
442
  outputs=[result_html, result_pdf])
443
 
444
- # Launch Gradio for Replit
445
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
16
  # Cleanup temporary files on exit
17
  def cleanup_temp_files():
18
  for temp_file in glob.glob("/tmp/Health_Report_*.pdf"):
19
+ try:
20
+ os.remove(temp_file)
21
+ except Exception as e:
22
+ print(f"Failed to clean up {temp_file}: {e}")
23
+ for temp_file in glob.glob("/tmp/health_card*.html"):
24
+ try:
25
+ os.remove(temp_file)
26
+ except Exception as e:
27
+ print(f"Failed to clean up {temp_file}: {e}")
28
  atexit.register(cleanup_temp_files)
29
 
30
  # Initialize the face mesh model
 
136
  def save_results_to_pdf(profile_image_base64, test_results, summary, patient_name, patient_age, patient_gender, patient_id, filename):
137
  try:
138
  # Generate HTML content
139
+ current_date = datetime.now().strftime("%B %d, %Y %I:%M %p IST") # Adjusted for IST
140
  health_card_html = f"""
141
  <!DOCTYPE html>
142
  <html>
 
201
 
202
  # Save HTML to a temporary file
203
  html_temp_path = "/tmp/health_card.html"
204
+ try:
205
+ os.makedirs(os.path.dirname(html_temp_path), exist_ok=True)
206
+ with open(html_temp_path, "w", encoding="utf-8") as f:
207
+ f.write(health_card_html)
208
+ print(f"HTML saved to: {html_temp_path}")
209
+ except Exception as e:
210
+ print(f"Error saving HTML: {e}")
211
+ return f"Error: Failed to save HTML - {str(e)}", None
212
 
213
  # Convert HTML to PDF using pdfkit
214
+ try:
215
+ pdfkit.from_file(html_temp_path, filename, options={"quiet": ""})
216
+ print(f"PDF generated successfully at: {filename}") # Debug log
217
+ except Exception as e:
218
+ print(f"Error converting to PDF: {str(e)}")
219
+ return f"Error: Failed to generate PDF - {str(e)}", None
220
 
221
  # Move to /tmp for Gradio access
222
  temp_pdf_path = "/tmp/" + os.path.basename(filename)
223
+ try:
224
+ shutil.copy(filename, temp_pdf_path)
225
+ if os.path.exists(temp_pdf_path) and os.access(temp_pdf_path, os.R_OK):
226
+ return f"PDF saved successfully as {filename}", temp_pdf_path
227
+ else:
228
+ return "Error: PDF file not accessible.", None
229
+ except Exception as e:
230
+ print(f"Error moving PDF: {e}")
231
+ return f"Error: Failed to move PDF - {str(e)}", None
232
  except Exception as e:
233
+ print(f"Unexpected error in save_results_to_pdf: {str(e)}")
234
+ return f"Error: Unexpected failure - {str(e)}", None
 
 
 
 
 
235
 
236
  # Build health card layout
237
  def build_health_card(profile_image, test_results, summary, pdf_filepath, patient_name="", patient_age="", patient_gender="", patient_id=""):
238
+ current_date = datetime.now().strftime("%B %d, %Y %I:%M %p IST") # Adjusted for IST
 
239
 
240
  pdf_filename = os.path.basename(pdf_filepath) if pdf_filepath else "health_report.pdf"
241
 
 
302
 
303
  # Modified analyze_face function
304
  def analyze_face(input_data):
305
+ if isinstance(input_data, str): # Video input (file path in Spaces)
306
  cap = cv2.VideoCapture(input_data)
307
  if not cap.isOpened():
308
  return "<div style='color:red;'>⚠️ Error: Could not open video.</div>", None
 
427
 
428
  # Create Gradio interface
429
  with gr.Blocks() as demo:
430
+ gr.Markdown("""# 🧠 Face-Based Lab Test AI Report""")
431
  with gr.Row():
432
  with gr.Column():
433
  gr.Markdown("### Patient Information")
 
445
  sources=["upload", "webcam"])
446
  submit_btn = gr.Button("🔍 Analyze")
447
  with gr.Column():
448
+ result_html = gr.HTML(label="🧪 Health Report")
449
  result_pdf = gr.File(label="Download Health Report PDF", interactive=False)
450
 
451
  submit_btn.click(fn=route_inputs,
452
  inputs=[mode_selector, image_input, video_input, patient_name, patient_age, patient_gender, patient_id],
453
  outputs=[result_html, result_pdf])
454
 
455
+ # Launch Gradio for Hugging Face Spaces
456
+ demo.launch()