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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -112
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.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("my_keras_model.h5")
20
 
21
- # Email sender credentials (Set your own credentials here)
22
- SENDER_EMAIL = "your_email@gmail.com"
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()
 
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()