ftx7go commited on
Commit
93bb174
·
verified ·
1 Parent(s): 8d5cd6c

Delete app.py

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