Update app.py
Browse files
app.py
CHANGED
@@ -1,182 +1,141 @@
|
|
1 |
import os
|
2 |
-
import smtplib
|
3 |
-
import mimetypes
|
4 |
-
from email.message import EmailMessage
|
5 |
import gradio as gr
|
6 |
import tensorflow as tf
|
7 |
import numpy as np
|
8 |
-
|
|
|
|
|
|
|
9 |
from PIL import Image
|
10 |
from reportlab.lib.pagesizes import letter
|
11 |
from reportlab.pdfgen import canvas
|
12 |
-
from reportlab.lib import
|
13 |
-
from reportlab.platypus import Table, TableStyle
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
# List of sample images
|
19 |
-
sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
|
20 |
-
|
21 |
-
# Function to process X-ray and generate a PDF report
|
22 |
-
def generate_report(name, age, gender, weight, height, address, parents, allergies, cause, email, xray):
|
23 |
-
# Input validation
|
24 |
-
name = name[:50]
|
25 |
-
address = address[:100]
|
26 |
-
parents = parents[:50]
|
27 |
-
cause = ' '.join(cause.split()[:100])
|
28 |
-
|
29 |
-
image_size = (224, 224)
|
30 |
-
|
31 |
-
def predict_fracture(xray_path):
|
32 |
-
img = Image.open(xray_path).resize(image_size)
|
33 |
-
img_array = image.img_to_array(img) / 255.0
|
34 |
-
img_array = np.expand_dims(img_array, axis=0)
|
35 |
-
prediction = model.predict(img_array)[0][0]
|
36 |
-
return prediction
|
37 |
-
|
38 |
-
prediction = predict_fracture(xray)
|
39 |
-
diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
|
40 |
-
severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
|
41 |
-
|
42 |
-
treatment_data = [
|
43 |
-
["Severity Level", "Recommended Treatment", "Recovery Duration"],
|
44 |
-
["Mild", "Rest, pain relievers, follow-up X-ray", "4-6 weeks"],
|
45 |
-
["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
|
46 |
-
["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
|
47 |
-
]
|
48 |
|
49 |
-
|
50 |
-
|
51 |
-
["Government", 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"],
|
52 |
-
["Private", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
|
53 |
-
]
|
54 |
-
|
55 |
-
img = Image.open(xray).resize((300, 300))
|
56 |
-
img_path = f"{name}_xray.png"
|
57 |
-
img.save(img_path)
|
58 |
-
|
59 |
-
report_path = f"{name}_fracture_report.pdf"
|
60 |
-
c = canvas.Canvas(report_path, pagesize=letter)
|
61 |
-
|
62 |
-
c.setFont("Helvetica-Bold", 16)
|
63 |
-
c.drawString(200, 770, "Bone Fracture Detection Report")
|
64 |
-
|
65 |
-
patient_data = [
|
66 |
-
["Patient Name", name],
|
67 |
-
["Age", age],
|
68 |
-
["Gender", gender],
|
69 |
-
["Weight", f"{weight} kg"],
|
70 |
-
["Height", f"{height} cm"],
|
71 |
-
["Address", address],
|
72 |
-
["Parent's Name", parents],
|
73 |
-
["Allergies", allergies if allergies else "None"],
|
74 |
-
["Cause of Injury", cause],
|
75 |
-
["Diagnosis", diagnosed_class],
|
76 |
-
["Injury Severity", severity]
|
77 |
-
]
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
|
83 |
-
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
84 |
-
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
|
85 |
-
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
86 |
-
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
|
87 |
-
('GRID', (0, 0), (-1, -1), 1, colors.black),
|
88 |
-
('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
|
89 |
-
]))
|
90 |
-
return table
|
91 |
-
|
92 |
-
patient_table = format_table(patient_data)
|
93 |
-
patient_table.wrapOn(c, 480, 500)
|
94 |
-
patient_table.drawOn(c, 50, 620)
|
95 |
-
|
96 |
-
c.drawInlineImage(img_path, 170, 320, width=250, height=250)
|
97 |
-
c.setFont("Helvetica-Bold", 12)
|
98 |
-
c.drawString(250, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
|
99 |
-
|
100 |
-
treatment_table = format_table(treatment_data)
|
101 |
-
treatment_table.wrapOn(c, 480, 200)
|
102 |
-
treatment_table.drawOn(c, 50, 200)
|
103 |
-
|
104 |
-
cost_table = format_table(cost_duration_data)
|
105 |
-
cost_table.wrapOn(c, 480, 150)
|
106 |
-
cost_table.drawOn(c, 50, 80)
|
107 |
|
108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
-
|
|
|
|
|
|
|
111 |
|
112 |
-
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
msg["From"] = sender_email
|
122 |
-
msg["To"] = receiver_email
|
123 |
-
msg.set_content("Please find attached your bone fracture diagnosis report.")
|
124 |
|
125 |
-
|
126 |
-
|
|
|
127 |
|
128 |
-
|
129 |
-
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
-
|
132 |
-
|
133 |
-
server.send_message(msg)
|
134 |
|
135 |
-
#
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
|
181 |
if __name__ == "__main__":
|
182 |
-
|
|
|
1 |
import os
|
|
|
|
|
|
|
2 |
import gradio as gr
|
3 |
import tensorflow as tf
|
4 |
import numpy as np
|
5 |
+
import cv2
|
6 |
+
import smtplib
|
7 |
+
import ssl
|
8 |
+
from email.message import EmailMessage
|
9 |
from PIL import Image
|
10 |
from reportlab.lib.pagesizes import letter
|
11 |
from reportlab.pdfgen import canvas
|
12 |
+
from reportlab.lib.utils import ImageReader
|
|
|
13 |
|
14 |
+
# Disable GPU to avoid CUDA errors
|
15 |
+
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
16 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
# Load the trained model
|
19 |
+
model = tf.keras.models.load_model("model.h5")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# Email sender credentials (Set your own credentials here)
|
22 |
+
SENDER_EMAIL = "[email protected]"
|
23 |
+
SENDER_PASSWORD = "your_email_password"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
def send_email(receiver_email, file_path):
|
26 |
+
"""Function to send an email with the generated PDF attached"""
|
27 |
+
msg = EmailMessage()
|
28 |
+
msg["Subject"] = "Bone Fracture Patient Report"
|
29 |
+
msg["From"] = SENDER_EMAIL
|
30 |
+
msg["To"] = receiver_email
|
31 |
+
msg.set_content("Please find the attached bone fracture report.")
|
32 |
|
33 |
+
# Attach PDF file
|
34 |
+
with open(file_path, "rb") as f:
|
35 |
+
file_data = f.read()
|
36 |
+
msg.add_attachment(file_data, maintype="application", subtype="pdf", filename="Fracture_Report.pdf")
|
37 |
|
38 |
+
# Send email
|
39 |
+
context = ssl.create_default_context()
|
40 |
+
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
|
41 |
+
server.login(SENDER_EMAIL, SENDER_PASSWORD)
|
42 |
+
server.send_message(msg)
|
43 |
|
44 |
+
def preprocess_image(image):
|
45 |
+
"""Preprocess the image for model prediction"""
|
46 |
+
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
|
47 |
+
image = cv2.resize(image, (224, 224))
|
48 |
+
image = np.expand_dims(image, axis=-1)
|
49 |
+
image = np.expand_dims(image, axis=0) / 255.0
|
50 |
+
return image
|
51 |
+
|
52 |
+
def generate_pdf(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email):
|
53 |
+
"""Generate a PDF report"""
|
54 |
+
file_path = "Fracture_Report.pdf"
|
55 |
+
c = canvas.Canvas(file_path, pagesize=letter)
|
56 |
+
width, height = letter
|
57 |
+
|
58 |
+
# Title
|
59 |
+
c.setFont("Helvetica-Bold", 16)
|
60 |
+
c.drawCentredString(width / 2, height - 50, "Bone Fracture Patient Report")
|
61 |
+
|
62 |
+
# Patient Info Table
|
63 |
+
c.setFont("Helvetica", 12)
|
64 |
+
data = [
|
65 |
+
["Patient Name:", name[:50]],
|
66 |
+
["Age:", age],
|
67 |
+
["Gender:", gender],
|
68 |
+
["Weight (kg):", weight],
|
69 |
+
["Height (cm):", height],
|
70 |
+
["Allergies:", allergies[:100]],
|
71 |
+
["Injury Cause:", " ".join(injury_cause.split()[:100])], # Limit to 100 words
|
72 |
+
["Address:", address[:100]],
|
73 |
+
["Parent/Guardian Name:", parent_name[:50]],
|
74 |
+
]
|
75 |
|
76 |
+
x_start, y_start = 50, height - 100
|
77 |
+
line_spacing = 20
|
|
|
|
|
|
|
78 |
|
79 |
+
for row in data:
|
80 |
+
c.drawString(x_start, y_start, f"{row[0]} {row[1]}")
|
81 |
+
y_start -= line_spacing
|
82 |
|
83 |
+
# Add X-ray image
|
84 |
+
if image:
|
85 |
+
img = Image.open(image)
|
86 |
+
img.thumbnail((250, 250))
|
87 |
+
img_path = "temp_image.jpg"
|
88 |
+
img.save(img_path)
|
89 |
+
c.drawImage(ImageReader(img_path), width / 2 - 125, y_start - 250, 250, 250)
|
90 |
|
91 |
+
# Close and save the PDF
|
92 |
+
c.save()
|
|
|
93 |
|
94 |
+
# Send email
|
95 |
+
if email:
|
96 |
+
send_email(email, file_path)
|
97 |
+
|
98 |
+
return file_path
|
99 |
+
|
100 |
+
def predict_and_generate_report(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email):
|
101 |
+
"""Make a prediction and generate a report"""
|
102 |
+
if image is None:
|
103 |
+
return "Please upload an X-ray image."
|
104 |
+
|
105 |
+
# Preprocess and make a prediction
|
106 |
+
processed_image = preprocess_image(image)
|
107 |
+
prediction = model.predict(processed_image)
|
108 |
+
confidence = float(prediction[0][0]) * 100
|
109 |
+
fracture_status = "Yes" if confidence > 50 else "No"
|
110 |
+
|
111 |
+
# Generate PDF report
|
112 |
+
pdf_path = generate_pdf(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email)
|
113 |
+
|
114 |
+
return f"Fractured: {fracture_status} (Confidence: {confidence:.2f}%)", pdf_path
|
115 |
+
|
116 |
+
# Define the Gradio Interface
|
117 |
+
iface = gr.Interface(
|
118 |
+
fn=predict_and_generate_report,
|
119 |
+
inputs=[
|
120 |
+
gr.Textbox(label="Patient Name (Max 50 chars)"),
|
121 |
+
gr.Number(label="Age", precision=0),
|
122 |
+
gr.Radio(label="Gender", choices=["Male", "Female", "Other"]),
|
123 |
+
gr.Number(label="Weight (kg)"),
|
124 |
+
gr.Number(label="Height (cm)"),
|
125 |
+
gr.Textbox(label="Allergies (Max 100 chars)"),
|
126 |
+
gr.Textbox(label="Cause of Injury (Max 100 words)"),
|
127 |
+
gr.Textbox(label="Address (Max 100 chars)"),
|
128 |
+
gr.Textbox(label="Parent/Guardian Name (Max 50 chars)"),
|
129 |
+
gr.Image(type="pil", label="Upload X-ray Image"),
|
130 |
+
gr.Textbox(label="Email Address (for Report)"),
|
131 |
+
],
|
132 |
+
outputs=[
|
133 |
+
gr.Textbox(label="Fracture Prediction"),
|
134 |
+
gr.File(label="Download Report"),
|
135 |
+
],
|
136 |
+
title="Bone Fracture Detection System",
|
137 |
+
description="Upload an X-ray image, enter patient details, and generate a fracture report."
|
138 |
+
)
|
139 |
|
140 |
if __name__ == "__main__":
|
141 |
+
iface.launch()
|