ftx7go commited on
Commit
d3e64aa
·
verified ·
1 Parent(s): 18668ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -126
app.py CHANGED
@@ -3,54 +3,55 @@ 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
10
  from reportlab.pdfgen import canvas
11
- from reportlab.lib import colors
12
- from reportlab.platypus import Table, TableStyle
13
 
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()
20
-
21
- # List of sample images
22
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
23
 
24
- # Function to send email
25
- def send_email(receiver_email, file_path):
26
- sender_email = "your_email@example.com"
27
  sender_password = "your_email_password"
28
-
29
- msg = EmailMessage()
30
- msg["Subject"] = "Bone Fracture Detection Report"
31
- msg["From"] = sender_email
32
- msg["To"] = receiver_email
33
- msg.set_content("Please find attached your bone fracture detection report.")
34
-
35
- with open(file_path, "rb") as f:
36
- file_data = f.read()
37
- file_name = os.path.basename(file_path)
38
- msg.add_attachment(file_data, maintype="application", subtype="pdf", filename=file_name)
39
-
40
  try:
41
- with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
42
- server.login(sender_email, sender_password)
43
- server.send_message(msg)
44
- return "Report sent successfully."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  except Exception as e:
46
- return f"Error sending email: {e}"
47
 
48
- # Function to process X-ray and generate a PDF report
49
  def generate_report(name, age, gender, weight, height, allergies, cause, xray, email):
50
- # Validate inputs
51
- name = name[:50]
52
- cause = " ".join(cause.split()[:100]) # Limit to 100 words
53
-
54
  image_size = (224, 224)
55
 
56
  def predict_fracture(xray_path):
@@ -60,138 +61,125 @@ def generate_report(name, age, gender, weight, height, allergies, cause, xray, e
60
  prediction = model.predict(img_array)[0][0]
61
  return prediction
62
 
63
- # Predict fracture
64
  prediction = predict_fracture(xray)
65
  diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
66
-
67
- # Injury severity classification
68
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
69
 
70
- # Treatment details
71
- treatment_data = [
72
- ["Severity Level", "Recommended Treatment", "Recovery Duration"],
73
- ["Mild", "Rest, pain relievers, follow-up X-ray", "4-6 weeks"],
74
- ["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
75
- ["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
76
- ]
77
-
78
- # Cost & duration estimation
79
- cost_duration_data = [
80
- ["Hospital Type", "Estimated Cost", "Recovery Time"],
81
- ["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"],
82
- ["Private Hospital", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
83
- ]
84
-
85
- # Save resized X-ray image
86
  img = Image.open(xray).resize((300, 300))
87
  img_path = f"{name}_xray.png"
88
  img.save(img_path)
89
 
90
- # Generate PDF report
91
  report_path = f"{name}_fracture_report.pdf"
92
  c = canvas.Canvas(report_path, pagesize=letter)
93
-
94
- # Report title
95
  c.setFont("Helvetica-Bold", 16)
96
- c.drawCentredString(300, 770, "Bone Fracture Detection Report")
97
-
98
- # Patient details
99
- patient_data = [
100
- ["Patient Name", name],
101
- ["Age", age],
102
- ["Gender", gender],
103
- ["Weight", f"{weight} kg"],
104
- ["Height", f"{height} cm"],
105
- ["Allergies", allergies if allergies else "None"],
106
- ["Cause of Injury", cause if cause else "Not Provided"],
107
- ["Diagnosis", diagnosed_class],
108
- ["Injury Severity", severity]
 
 
 
 
109
  ]
110
-
111
- # Format and align tables
112
- def format_table(data):
113
- table = Table(data, colWidths=[270, 270]) # 90% width
114
- table.setStyle(TableStyle([
115
- ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
116
- ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
117
- ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
118
- ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
119
- ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
120
- ('GRID', (0, 0), (-1, -1), 1, colors.black),
121
- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
122
- ]))
123
- return table
124
-
125
- # Draw patient details table
126
- patient_table = format_table(patient_data)
127
- patient_table.wrapOn(c, 480, 500)
128
- patient_table.drawOn(c, 50, 620)
129
-
130
- # Center X-ray image
131
- c.drawInlineImage(img_path, 150, 320, width=300, height=300)
132
- c.setFont("Helvetica-Bold", 12)
133
- c.drawCentredString(300, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
134
-
135
- # Draw treatment & cost tables
136
- treatment_table = format_table(treatment_data)
137
- treatment_table.wrapOn(c, 480, 200)
138
- treatment_table.drawOn(c, 50, 200)
139
-
140
- cost_table = format_table(cost_duration_data)
141
- cost_table.wrapOn(c, 480, 150)
142
- cost_table.drawOn(c, 50, 80)
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  c.save()
145
 
146
- # Send email
147
- email_status = send_email(email, report_path)
148
 
149
  return report_path, email_status
150
 
151
- # Function to select a sample image
152
- def use_sample_image(sample_image_path):
153
- return sample_image_path
154
-
155
- # Define Gradio Interface
156
  with gr.Blocks() as app:
157
- gr.HTML(html_content)
158
- gr.Markdown("## Bone Fracture Detection System")
159
-
160
  with gr.Row():
161
- name = gr.Textbox(label="Patient Name", max_length=50)
162
  age = gr.Number(label="Age")
 
 
163
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
164
-
 
165
  with gr.Row():
166
  weight = gr.Number(label="Weight (kg)")
167
  height = gr.Number(label="Height (cm)")
168
-
169
- with gr.Row():
170
- allergies = gr.Textbox(label="Allergies (if any)")
171
- cause = gr.Textbox(label="Cause of Injury", max_lines=5)
172
 
173
  with gr.Row():
174
- email = gr.Textbox(label="Email Address")
 
175
 
176
  with gr.Row():
177
  xray = gr.Image(type="filepath", label="Upload X-ray Image")
178
-
179
- with gr.Row():
180
- sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
181
- select_button = gr.Button("Load Sample Image")
182
 
183
  submit_button = gr.Button("Generate Report")
184
  output_file = gr.File(label="Download Report")
185
  email_status = gr.Textbox(label="Email Status", interactive=False)
186
 
187
- select_button.click(use_sample_image, inputs=[sample_selector], outputs=[xray])
188
-
189
  submit_button.click(
190
  generate_report,
191
  inputs=[name, age, gender, weight, height, allergies, cause, xray, email],
192
- outputs=[output_file, email_status],
193
  )
194
 
195
- # Launch the Gradio app
196
  if __name__ == "__main__":
197
  app.launch()
 
3
  import gradio as gr
4
  import tensorflow as tf
5
  import numpy as np
6
+ from email.mime.multipart import MIMEMultipart
7
+ from email.mime.text import MIMEText
8
+ from email.mime.base import MIMEBase
9
+ from email import encoders
10
  from tensorflow.keras.preprocessing import image
11
  from PIL import Image
12
  from reportlab.lib.pagesizes import letter
13
  from reportlab.pdfgen import canvas
14
+ from reportlab.lib.utils import simpleSplit
 
15
 
16
  # Load the trained model
17
  model = tf.keras.models.load_model("my_keras_model.h5")
18
 
19
+ # Sample images
 
 
 
 
20
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
21
 
22
+ # Email function
23
+ def send_email(patient_email, patient_name, pdf_path):
24
+ sender_email = "your_email@gmail.com"
25
  sender_password = "your_email_password"
26
+
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
+ msg = MIMEMultipart()
29
+ msg["From"] = sender_email
30
+ msg["To"] = patient_email
31
+ msg["Subject"] = "Your Bone Fracture Report"
32
+
33
+ body = f"Hello {patient_name},\n\nPlease find attached your bone fracture detection report from XYZ Hospital.\n\nBest regards,\nXYZ Hospital"
34
+ msg.attach(MIMEText(body, "plain"))
35
+
36
+ with open(pdf_path, "rb") as attachment:
37
+ part = MIMEBase("application", "octet-stream")
38
+ part.set_payload(attachment.read())
39
+ encoders.encode_base64(part)
40
+ part.add_header("Content-Disposition", f"attachment; filename={pdf_path}")
41
+ msg.attach(part)
42
+
43
+ server = smtplib.SMTP("smtp.gmail.com", 587)
44
+ server.starttls()
45
+ server.login(sender_email, sender_password)
46
+ server.sendmail(sender_email, patient_email, msg.as_string())
47
+ server.quit()
48
+
49
+ return "Report sent successfully!"
50
  except Exception as e:
51
+ return f"Error sending email: {str(e)}"
52
 
53
+ # Generate PDF report
54
  def generate_report(name, age, gender, weight, height, allergies, cause, xray, email):
 
 
 
 
55
  image_size = (224, 224)
56
 
57
  def predict_fracture(xray_path):
 
61
  prediction = model.predict(img_array)[0][0]
62
  return prediction
63
 
 
64
  prediction = predict_fracture(xray)
65
  diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
 
 
66
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
67
 
68
+ # Save X-ray image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  img = Image.open(xray).resize((300, 300))
70
  img_path = f"{name}_xray.png"
71
  img.save(img_path)
72
 
73
+ # PDF Report
74
  report_path = f"{name}_fracture_report.pdf"
75
  c = canvas.Canvas(report_path, pagesize=letter)
76
+
77
+ # Header
78
  c.setFont("Helvetica-Bold", 16)
79
+ c.drawCentredString(300, 770, "XYZ Hospital, New Delhi")
80
+ c.setFont("Helvetica", 12)
81
+ c.drawCentredString(300, 750, "123 Health Street, New Delhi, India")
82
+ c.line(50, 740, 550, 740)
83
+
84
+ # Patient Details
85
+ c.setFont("Helvetica-Bold", 14)
86
+ c.drawString(50, 710, "Patient Information:")
87
+ c.setFont("Helvetica", 12)
88
+ details = [
89
+ f"Name: {name}",
90
+ f"Age: {age}",
91
+ f"Gender: {gender}",
92
+ f"Weight: {weight} kg",
93
+ f"Height: {height} cm",
94
+ f"Allergies: {allergies if allergies else 'None'}",
95
+ f"Cause of Injury: {cause if cause else 'Not Provided'}"
96
  ]
97
+ y = 690
98
+ for detail in details:
99
+ c.drawString(50, y, detail)
100
+ y -= 20
101
+
102
+ # Diagnosis
103
+ c.setFont("Helvetica-Bold", 14)
104
+ c.drawString(50, y, "Diagnosis:")
105
+ c.setFont("Helvetica", 12)
106
+ y -= 20
107
+ c.drawString(50, y, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
108
+ y -= 20
109
+ c.drawString(50, y, f"Injury Severity: {severity}")
110
+
111
+ # X-ray Image
112
+ c.drawInlineImage(img_path, 150, y - 260, width=300, height=300)
113
+ y -= 280
114
+
115
+ # Treatment & Recommendations
116
+ c.setFont("Helvetica-Bold", 14)
117
+ c.drawString(50, y, "Recommended Treatment:")
118
+ c.setFont("Helvetica", 12)
119
+ y -= 20
120
+ recommendations = {
121
+ "Mild": "Rest, pain relievers, and follow-up X-ray.",
122
+ "Moderate": "Plaster cast, minor surgery if needed.",
123
+ "Severe": "Major surgery, metal implants, and physiotherapy."
124
+ }
125
+ treatment_text = recommendations[severity]
126
+ for line in simpleSplit(treatment_text, "Helvetica", 12, 480):
127
+ c.drawString(50, y, line)
128
+ y -= 20
129
+
130
+ # Estimated Cost
131
+ c.setFont("Helvetica-Bold", 14)
132
+ c.drawString(50, y, "Estimated Treatment Cost:")
133
+ c.setFont("Helvetica", 12)
134
+ y -= 20
135
+ cost_gov = f"Government Hospital: ₹{2000 if severity == 'Mild' else 8000 if severity == 'Moderate' else 20000} - ₹{5000 if severity == 'Mild' else 15000 if severity == 'Moderate' else 50000}"
136
+ cost_priv = f"Private Hospital: ₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+"
137
+ for line in simpleSplit(cost_gov, "Helvetica", 12, 480):
138
+ c.drawString(50, y, line)
139
+ y -= 20
140
+ for line in simpleSplit(cost_priv, "Helvetica", 12, 480):
141
+ c.drawString(50, y, line)
142
+ y -= 20
143
 
144
  c.save()
145
 
146
+ # Send email with report
147
+ email_status = send_email(email, name, report_path)
148
 
149
  return report_path, email_status
150
 
151
+ # Gradio Interface
 
 
 
 
152
  with gr.Blocks() as app:
153
+ gr.Markdown("# Bone Fracture Detection System\n### AI-powered diagnosis and treatment recommendations")
154
+
 
155
  with gr.Row():
156
+ name = gr.Textbox(label="Patient Name", max_chars=50)
157
  age = gr.Number(label="Age")
158
+
159
+ with gr.Row():
160
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
161
+ email = gr.Textbox(label="Patient Email")
162
+
163
  with gr.Row():
164
  weight = gr.Number(label="Weight (kg)")
165
  height = gr.Number(label="Height (cm)")
 
 
 
 
166
 
167
  with gr.Row():
168
+ allergies = gr.Textbox(label="Allergies (if any)")
169
+ cause = gr.Textbox(label="Cause of Injury (Max 100 words)", max_chars=500)
170
 
171
  with gr.Row():
172
  xray = gr.Image(type="filepath", label="Upload X-ray Image")
 
 
 
 
173
 
174
  submit_button = gr.Button("Generate Report")
175
  output_file = gr.File(label="Download Report")
176
  email_status = gr.Textbox(label="Email Status", interactive=False)
177
 
 
 
178
  submit_button.click(
179
  generate_report,
180
  inputs=[name, age, gender, weight, height, allergies, cause, xray, email],
181
+ outputs=[output_file, email_status]
182
  )
183
 
 
184
  if __name__ == "__main__":
185
  app.launch()