ftx7go commited on
Commit
5b60b58
·
verified ·
1 Parent(s): e61805d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -62
app.py CHANGED
@@ -1,9 +1,9 @@
1
  import os
2
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Force TensorFlow to use CPU
3
-
4
  import gradio as gr
5
  import tensorflow as tf
6
  import numpy as np
 
7
  from tensorflow.keras.preprocessing import image
8
  from PIL import Image
9
  from reportlab.lib.pagesizes import letter
@@ -14,6 +14,10 @@ from reportlab.platypus import Table, TableStyle
14
  # Load the trained model
15
  model = tf.keras.models.load_model("my_keras_model.h5")
16
 
 
 
 
 
17
  # Read HTML content from `re.html`
18
  with open("templates/re.html", "r", encoding="utf-8") as file:
19
  html_content = file.read()
@@ -22,7 +26,7 @@ with open("templates/re.html", "r", encoding="utf-8") as file:
22
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
23
 
24
  # Function to process X-ray and generate a PDF report
25
- def generate_report(name, age, gender, weight, height, allergies, cause, xray):
26
  image_size = (224, 224)
27
 
28
  def predict_fracture(xray_path):
@@ -34,55 +38,30 @@ def generate_report(name, age, gender, weight, height, allergies, cause, xray):
34
 
35
  # Predict fracture
36
  prediction = predict_fracture(xray)
37
- diagnosed_class = "normal" if prediction > 0.5 else "Fractured"
38
-
39
- # Injury severity classification
40
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
41
 
42
- # Treatment details table
43
- treatment_data = [
44
- ["Severity Level", "Recommended Treatment", "Recovery Duration"],
45
- ["Mild", "Rest, pain relievers, and follow-up X-ray", "4-6 weeks"],
46
- ["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
47
- ["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
48
- ]
49
-
50
- # Estimated cost & duration table
51
- cost_duration_data = [
52
- ["Hospital Type", "Estimated Cost", "Recovery Time"],
53
- ["Government Hospital", f"₹{2000 if severity == 'Mild' else 8000 if severity == 'Moderate' else 20000} - ₹{5000 if severity == 'Mild' else 15000 if severity == 'Moderate' else 50000}", "4-12 weeks"],
54
- ["Private Hospital", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
55
- ]
56
-
57
- # Save X-ray image for report
58
- img = Image.open(xray).resize((300, 300))
59
- img_path = f"{name}_xray.png"
60
- img.save(img_path)
61
 
62
  # Generate PDF report
63
- report_path = f"{name}_fracture_report.pdf"
64
  c = canvas.Canvas(report_path, pagesize=letter)
65
-
66
- # Report title
67
  c.setFont("Helvetica-Bold", 16)
68
  c.drawString(200, 770, "Bone Fracture Detection Report")
69
 
70
- # Patient details table
71
  patient_data = [
72
- ["Patient Name", name],
73
- ["Age", age],
74
- ["Gender", gender],
75
- ["Weight", f"{weight} kg"],
76
- ["Height", f"{height} cm"],
77
  ["Allergies", allergies if allergies else "None"],
78
  ["Cause of Injury", cause if cause else "Not Provided"],
79
- ["Diagnosis", diagnosed_class],
80
- ["Injury Severity", severity]
81
  ]
82
 
83
- # Format and align tables
84
  def format_table(data):
85
- table = Table(data, colWidths=[270, 270]) # Set 90% width
86
  table.setStyle(TableStyle([
87
  ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
88
  ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
@@ -99,61 +78,80 @@ def generate_report(name, age, gender, weight, height, allergies, cause, xray):
99
  patient_table.wrapOn(c, 480, 500)
100
  patient_table.drawOn(c, 50, 620)
101
 
102
- # Load and insert X-ray image
103
- c.drawInlineImage(img_path, 50, 320, width=250, height=250)
104
- c.setFont("Helvetica-Bold", 12)
105
- c.drawString(120, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
106
-
107
- # Draw treatment and cost tables
108
- treatment_table = format_table(treatment_data)
109
- treatment_table.wrapOn(c, 480, 200)
110
- treatment_table.drawOn(c, 50, 200)
111
-
112
- cost_table = format_table(cost_duration_data)
113
- cost_table.wrapOn(c, 480, 150)
114
- cost_table.drawOn(c, 50, 80)
115
-
116
  c.save()
117
-
118
- return report_path # Return path for auto-download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  # Function to select a sample image
121
  def use_sample_image(sample_image_path):
122
- return sample_image_path # Returns selected sample image filepath
123
 
124
  # Define Gradio Interface
125
  with gr.Blocks() as app:
126
- gr.HTML(html_content) # Display `re.html` content in Gradio
127
  gr.Markdown("## Bone Fracture Detection System")
128
-
129
  with gr.Row():
130
  name = gr.Textbox(label="Patient Name")
131
  age = gr.Number(label="Age")
132
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
133
-
134
  with gr.Row():
135
  weight = gr.Number(label="Weight (kg)")
136
  height = gr.Number(label="Height (cm)")
137
-
138
  with gr.Row():
139
  allergies = gr.Textbox(label="Allergies (if any)")
140
  cause = gr.Textbox(label="Cause of Injury")
141
 
142
  with gr.Row():
143
- xray = gr.Image(type="filepath", label="Upload X-ray Image")
144
 
 
 
 
145
  with gr.Row():
146
  sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
147
  select_button = gr.Button("Load Sample Image")
148
 
149
- submit_button = gr.Button("Generate Report")
150
  output_file = gr.File(label="Download Report")
151
 
152
  select_button.click(use_sample_image, inputs=[sample_selector], outputs=[xray])
153
 
154
  submit_button.click(
155
  generate_report,
156
- inputs=[name, age, gender, weight, height, allergies, cause, xray],
157
  outputs=[output_file],
158
  )
159
 
 
1
  import os
2
+ import smtplib
 
3
  import gradio as gr
4
  import tensorflow as tf
5
  import numpy as np
6
+ from email.message import EmailMessage
7
  from tensorflow.keras.preprocessing import image
8
  from PIL import Image
9
  from reportlab.lib.pagesizes import letter
 
14
  # Load the trained model
15
  model = tf.keras.models.load_model("my_keras_model.h5")
16
 
17
+ # Ensure the reports directory exists
18
+ REPORTS_DIR = "reports"
19
+ os.makedirs(REPORTS_DIR, exist_ok=True)
20
+
21
  # Read HTML content from `re.html`
22
  with open("templates/re.html", "r", encoding="utf-8") as file:
23
  html_content = file.read()
 
26
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
27
 
28
  # Function to process X-ray and generate a PDF report
29
+ def generate_report(name, age, gender, weight, height, allergies, cause, xray, email):
30
  image_size = (224, 224)
31
 
32
  def predict_fracture(xray_path):
 
38
 
39
  # Predict fracture
40
  prediction = predict_fracture(xray)
41
+ diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
 
 
42
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
43
 
44
+ # File paths
45
+ report_filename = f"{name}_fracture_report.pdf"
46
+ report_path = os.path.join(REPORTS_DIR, report_filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Generate PDF report
 
49
  c = canvas.Canvas(report_path, pagesize=letter)
 
 
50
  c.setFont("Helvetica-Bold", 16)
51
  c.drawString(200, 770, "Bone Fracture Detection Report")
52
 
53
+ # Patient details
54
  patient_data = [
55
+ ["Patient Name", name], ["Age", age], ["Gender", gender],
56
+ ["Weight", f"{weight} kg"], ["Height", f"{height} cm"],
 
 
 
57
  ["Allergies", allergies if allergies else "None"],
58
  ["Cause of Injury", cause if cause else "Not Provided"],
59
+ ["Diagnosis", diagnosed_class], ["Injury Severity", severity]
 
60
  ]
61
 
62
+ # Format table function
63
  def format_table(data):
64
+ table = Table(data, colWidths=[270, 270])
65
  table.setStyle(TableStyle([
66
  ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
67
  ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
 
78
  patient_table.wrapOn(c, 480, 500)
79
  patient_table.drawOn(c, 50, 620)
80
 
81
+ # Save and return report path
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  c.save()
83
+
84
+ # Send email with report
85
+ send_email_with_attachment(email, report_path, name)
86
+
87
+ return report_path # For download
88
+
89
+ # Function to send email with PDF attachment
90
+ def send_email_with_attachment(to_email, file_path, patient_name):
91
+ sender_email = "[email protected]" # Replace with your email
92
+ sender_password = "your-email-password" # Use App Passwords if using Gmail
93
+
94
+ msg = EmailMessage()
95
+ msg["Subject"] = f"Bone Fracture Report for {patient_name}"
96
+ msg["From"] = sender_email
97
+ msg["To"] = to_email
98
+ msg.set_content(f"Dear {patient_name},\n\nAttached is your bone fracture detection report.\n\nThank you!")
99
+
100
+ # Attach PDF file
101
+ with open(file_path, "rb") as f:
102
+ file_data = f.read()
103
+ file_name = os.path.basename(file_path)
104
+ msg.add_attachment(file_data, maintype="application", subtype="pdf", filename=file_name)
105
+
106
+ # Send email
107
+ try:
108
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
109
+ server.login(sender_email, sender_password)
110
+ server.send_message(msg)
111
+ print(f"Email sent to {to_email}")
112
+ except Exception as e:
113
+ print(f"Failed to send email: {e}")
114
 
115
  # Function to select a sample image
116
  def use_sample_image(sample_image_path):
117
+ return sample_image_path
118
 
119
  # Define Gradio Interface
120
  with gr.Blocks() as app:
121
+ gr.HTML(html_content)
122
  gr.Markdown("## Bone Fracture Detection System")
123
+
124
  with gr.Row():
125
  name = gr.Textbox(label="Patient Name")
126
  age = gr.Number(label="Age")
127
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
128
+
129
  with gr.Row():
130
  weight = gr.Number(label="Weight (kg)")
131
  height = gr.Number(label="Height (cm)")
132
+
133
  with gr.Row():
134
  allergies = gr.Textbox(label="Allergies (if any)")
135
  cause = gr.Textbox(label="Cause of Injury")
136
 
137
  with gr.Row():
138
+ email = gr.Textbox(label="Patient Email")
139
 
140
+ with gr.Row():
141
+ xray = gr.Image(type="filepath", label="Upload X-ray Image")
142
+
143
  with gr.Row():
144
  sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
145
  select_button = gr.Button("Load Sample Image")
146
 
147
+ submit_button = gr.Button("Generate Report & Send Email")
148
  output_file = gr.File(label="Download Report")
149
 
150
  select_button.click(use_sample_image, inputs=[sample_selector], outputs=[xray])
151
 
152
  submit_button.click(
153
  generate_report,
154
+ inputs=[name, age, gender, weight, height, allergies, cause, xray, email],
155
  outputs=[output_file],
156
  )
157