Update app.py
Browse files
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.
|
|
|
|
|
|
|
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
|
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 |
-
#
|
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 |
-
#
|
25 |
-
def send_email(
|
26 |
-
sender_email = "your_email@
|
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 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
except Exception as e:
|
46 |
-
return f"Error sending email: {e}"
|
47 |
|
48 |
-
#
|
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 |
-
#
|
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 |
-
#
|
91 |
report_path = f"{name}_fracture_report.pdf"
|
92 |
c = canvas.Canvas(report_path, pagesize=letter)
|
93 |
-
|
94 |
-
#
|
95 |
c.setFont("Helvetica-Bold", 16)
|
96 |
-
c.drawCentredString(300, 770, "
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
|
|
|
|
|
|
109 |
]
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
c.
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
#
|
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.
|
158 |
-
|
159 |
-
|
160 |
with gr.Row():
|
161 |
-
name = gr.Textbox(label="Patient Name",
|
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 |
-
|
|
|
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()
|