ftx7go commited on
Commit
21b103e
·
verified ·
1 Parent(s): 45b6651

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -184
app.py DELETED
@@ -1,184 +0,0 @@
1
- import os
2
- import smtplib
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 import colors
15
- from reportlab.platypus import Table, TableStyle
16
-
17
- # Ensure the "reports" directory exists
18
- if not os.path.exists("reports"):
19
- os.makedirs("reports")
20
-
21
- # Load the trained model
22
- model = tf.keras.models.load_model("my_keras_model.h5")
23
-
24
- # Read HTML content from `re.html`
25
- with open("templates/re.html", "r", encoding="utf-8") as file:
26
- html_content = file.read()
27
-
28
- # List of sample images
29
- sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
30
-
31
- # Function to generate and save the report
32
- def generate_report(name, age, gender, weight, height, allergies, cause, xray):
33
- image_size = (224, 224)
34
-
35
- def predict_fracture(xray_path):
36
- img = Image.open(xray_path).resize(image_size)
37
- img_array = image.img_to_array(img) / 255.0
38
- img_array = np.expand_dims(img_array, axis=0)
39
- prediction = model.predict(img_array)[0][0]
40
- return prediction
41
-
42
- # Predict fracture
43
- prediction = predict_fracture(xray)
44
- diagnosed_class = "normal" if prediction > 0.5 else "Fractured"
45
-
46
- # Injury severity classification
47
- severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
48
-
49
- # Treatment details table
50
- treatment_data = [
51
- ["Severity Level", "Recommended Treatment", "Recovery Duration"],
52
- ["Mild", "Rest, pain relievers, and follow-up X-ray", "4-6 weeks"],
53
- ["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
54
- ["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
55
- ]
56
-
57
- # Estimated cost & duration table
58
- cost_duration_data = [
59
- ["Hospital Type", "Estimated Cost", "Recovery Time"],
60
- ["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"],
61
- ["Private Hospital", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
62
- ]
63
-
64
- # Save X-ray image for report
65
- img = Image.open(xray).resize((300, 300))
66
- img_path = f"reports/{name}_xray.png"
67
- img.save(img_path)
68
-
69
- # Generate PDF report
70
- report_path = f"reports/{name}_fracture_report.pdf"
71
- c = canvas.Canvas(report_path, pagesize=letter)
72
-
73
- # Report title
74
- c.setFont("Helvetica-Bold", 16)
75
- c.drawString(200, 770, "Bone Fracture Detection Report")
76
-
77
- # Patient details table
78
- patient_data = [
79
- ["Patient Name", name],
80
- ["Age", age],
81
- ["Gender", gender],
82
- ["Weight", f"{weight} kg"],
83
- ["Height", f"{height} cm"],
84
- ["Allergies", allergies if allergies else "None"],
85
- ["Cause of Injury", cause if cause else "Not Provided"],
86
- ["Diagnosis", diagnosed_class],
87
- ["Injury Severity", severity]
88
- ]
89
-
90
- # Format and align tables
91
- def format_table(data):
92
- table = Table(data, colWidths=[270, 270])
93
- table.setStyle(TableStyle([
94
- ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
95
- ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
96
- ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
97
- ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
98
- ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
99
- ('GRID', (0, 0), (-1, -1), 1, colors.black),
100
- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
101
- ]))
102
- return table
103
-
104
- # Draw tables and images
105
- patient_table = format_table(patient_data)
106
- patient_table.wrapOn(c, 480, 500)
107
- patient_table.drawOn(c, 50, 620)
108
-
109
- c.drawInlineImage(img_path, 50, 320, width=250, height=250)
110
- c.setFont("Helvetica-Bold", 12)
111
- c.drawString(120, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
112
-
113
- treatment_table = format_table(treatment_data)
114
- treatment_table.wrapOn(c, 480, 200)
115
- treatment_table.drawOn(c, 50, 200)
116
-
117
- cost_table = format_table(cost_duration_data)
118
- cost_table.wrapOn(c, 480, 150)
119
- cost_table.drawOn(c, 50, 80)
120
-
121
- c.save()
122
-
123
- return report_path # Return path for auto-download
124
-
125
- # Function to send email with attachment
126
- def send_email(patient_email, report_path):
127
- sender_email = "[email protected]"
128
- sender_password = "1w3r5y7i9pW$"
129
- subject = "Bone Fracture Detection Report"
130
- body = "Attached is your bone fracture detection report."
131
-
132
- msg = MIMEMultipart()
133
- msg["From"] = sender_email
134
- msg["To"] = patient_email
135
- msg["Subject"] = subject
136
- msg.attach(MIMEText(body, "plain"))
137
-
138
- with open(report_path, "rb") as attachment:
139
- part = MIMEBase("application", "octet-stream")
140
- part.set_payload(attachment.read())
141
- encoders.encode_base64(part)
142
- part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(report_path)}")
143
- msg.attach(part)
144
-
145
- try:
146
- server = smtplib.SMTP("smtp.gmail.com", 587)
147
- server.starttls()
148
- server.login(sender_email, sender_password)
149
- server.sendmail(sender_email, patient_email, msg.as_string())
150
- server.quit()
151
- return "Email Sent Successfully!"
152
- except Exception as e:
153
- return f"Error sending email: {str(e)}"
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")
162
- age = gr.Number(label="Age")
163
- gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
164
- patient_email = gr.Textbox(label="Patient Email")
165
-
166
- with gr.Row():
167
- weight = gr.Number(label="Weight (kg)")
168
- height = gr.Number(label="Height (cm)")
169
-
170
- with gr.Row():
171
- allergies = gr.Textbox(label="Allergies")
172
- cause = gr.Textbox(label="Cause of Injury")
173
-
174
- xray = gr.Image(type="filepath", label="Upload X-ray Image")
175
- generate_button = gr.Button("Generate & Download Report")
176
- send_email_button = gr.Button("Send Report via Email")
177
- output_file = gr.File(label="Download Report")
178
- status = gr.Textbox(label="Email Status", interactive=False)
179
-
180
- generate_button.click(generate_report, inputs=[name, age, gender, weight, height, allergies, cause, xray], outputs=[output_file])
181
- send_email_button.click(send_email, inputs=[patient_email, output_file], outputs=[status])
182
-
183
- if __name__ == "__main__":
184
- app.launch()