Update app.py
Browse files
app.py
CHANGED
@@ -1,141 +1,197 @@
|
|
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
|
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("my_keras_model.h5")
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
-
|
24 |
|
|
|
|
|
|
|
|
|
25 |
def send_email(receiver_email, file_path):
|
26 |
-
|
|
|
|
|
27 |
msg = EmailMessage()
|
28 |
-
msg["Subject"] = "Bone Fracture
|
29 |
-
msg["From"] =
|
30 |
msg["To"] = receiver_email
|
31 |
-
msg.set_content("Please find
|
32 |
|
33 |
-
# Attach PDF file
|
34 |
with open(file_path, "rb") as f:
|
35 |
file_data = f.read()
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
-
#
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
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 |
-
|
77 |
-
|
|
|
|
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
-
#
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
-
# Close and save the PDF
|
92 |
c.save()
|
93 |
|
94 |
# Send email
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
def
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
gr.
|
123 |
-
|
124 |
-
|
125 |
-
gr.
|
126 |
-
|
127 |
-
|
128 |
-
gr.
|
129 |
-
gr.
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
],
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
140 |
if __name__ == "__main__":
|
141 |
-
|
|
|
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
|
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 = "[email protected]"
|
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):
|
57 |
+
img = Image.open(xray_path).resize(image_size)
|
58 |
+
img_array = image.img_to_array(img) / 255.0
|
59 |
+
img_array = np.expand_dims(img_array, axis=0)
|
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()
|