ftx7go commited on
Commit
aec8e3c
·
verified ·
1 Parent(s): 0c37068

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -0
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Force TensorFlow to use CPU
3
+
4
+ import gradio as gr
5
+ import numpy as np
6
+ from PIL import Image
7
+ from reportlab.lib.pagesizes import letter
8
+ from reportlab.pdfgen import canvas
9
+ from reportlab.lib import colors
10
+ from reportlab.platypus import Table, TableStyle
11
+ import requests
12
+ import smtplib
13
+ from email.mime.multipart import MIMEMultipart
14
+ from email.mime.text import MIMEText
15
+ from email.mime.base import MIMEBase
16
+ from email import encoders
17
+ import io
18
+ import base64
19
+
20
+ # FastAPI server URL
21
+ FASTAPI_URL = "http://localhost:7860/analyze" # Adjust if your FastAPI server is running elsewhere
22
+
23
+ # Email credentials
24
+ SENDER_EMAIL = "[email protected]"
25
+ SENDER_PASSWORD = "1w3r5y7i9pW$"
26
+
27
+ # Read HTML content from `re.html`
28
+ with open("templates/re.html", "r", encoding="utf-8") as file:
29
+ html_content = file.read()
30
+
31
+ # List of sample images
32
+ sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
33
+
34
+ def image_to_base64(image_path):
35
+ with open(image_path, "rb") as image_file:
36
+ return base64.b64encode(image_file.read()).decode('utf-8')
37
+
38
+ # Function to process X-ray and generate a PDF report
39
+ def generate_report(name, age, gender, weight, height, allergies, cause, xray, email):
40
+ image_size = (224, 224)
41
+
42
+ # Send X-ray to FastAPI for analysis
43
+ try:
44
+ with open(xray, 'rb') as f:
45
+ files = {'file': (os.path.basename(xray), f)}
46
+ response = requests.post(FASTAPI_URL, files=files)
47
+ response.raise_for_status() # Raise an exception for bad status codes
48
+ fastapi_results_html = response.text
49
+ except requests.exceptions.RequestException as e:
50
+ return f"Error connecting to FastAPI server: {e}"
51
+
52
+ # Extract prediction from FastAPI response (you might need to adjust this based on the exact HTML structure)
53
+ diagnosed_class = "normal"
54
+ severity = "Not Available"
55
+ try:
56
+ # Simple string matching for now - improve this if the HTML structure is complex
57
+ if "KnochenWächter" in fastapi_results_html:
58
+ if "Kein Knochenbruch" in fastapi_results_html:
59
+ diagnosed_class = "normal"
60
+ elif "Knochenbruch" in fastapi_results_html or "Auffällig" in fastapi_results_html:
61
+ diagnosed_class = "Fractured"
62
+
63
+ if diagnosed_class == "Fractured":
64
+ if "score-high" in fastapi_results_html:
65
+ severity = "Severe"
66
+ elif "score-medium" in fastapi_results_html:
67
+ severity = "Moderate"
68
+ else:
69
+ severity = "Mild"
70
+ else:
71
+ severity = "Mild" # Assuming normal is mild
72
+ except Exception as e:
73
+ print(f"Error parsing FastAPI response: {e}")
74
+
75
+ # Treatment details table
76
+ treatment_data = [
77
+ ["Severity Level", "Recommended Treatment", "Recovery Duration"],
78
+ ["Mild", "Rest, pain relievers, and follow-up X-ray", "4-6 weeks"],
79
+ ["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
80
+ ["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
81
+ ]
82
+
83
+ # Estimated cost & duration table
84
+ cost_duration_data = [
85
+ ["Hospital Type", "Estimated Cost", "Recovery Time"],
86
+ ["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"],
87
+ ["Private Hospital", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
88
+ ]
89
+
90
+ # Save X-ray image for report
91
+ img = Image.open(xray).resize((300, 300))
92
+ img_path = f"{name}_xray.png"
93
+ img.save(img_path)
94
+
95
+ # Generate PDF report
96
+ report_path = f"{name}_fracture_report.pdf"
97
+ c = canvas.Canvas(report_path, pagesize=letter)
98
+
99
+ # Report title
100
+ c.setFont("Helvetica-Bold", 16)
101
+ c.drawString(200, 770, "Bone Fracture Detection Report")
102
+
103
+ # Patient details table
104
+ patient_data = [
105
+ ["Patient Name", name],
106
+ ["Age", age],
107
+ ["Gender", gender],
108
+ ["Weight", f"{weight} kg"],
109
+ ["Height", f"{height} cm"],
110
+ ["Allergies", allergies if allergies else "None"],
111
+ ["Cause of Injury", cause if cause else "Not Provided"],
112
+ ["Diagnosis", diagnosed_class],
113
+ ["Injury Severity", severity]
114
+ ]
115
+
116
+ # Format and align tables
117
+ def format_table(data):
118
+ table = Table(data, colWidths=[270, 270]) # Set 90% width
119
+ table.setStyle(TableStyle([
120
+ ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
121
+ ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
122
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
123
+ ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
124
+ ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
125
+ ('GRID', (0, 0), (-1, -1), 1, colors.black),
126
+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
127
+ ]))
128
+ return table
129
+
130
+ # Draw patient details table
131
+ patient_table = format_table(patient_data)
132
+ patient_table.wrapOn(c, 480, 500)
133
+ patient_table.drawOn(c, 50, 620)
134
+
135
+ # Load and insert X-ray image
136
+ c.drawInlineImage(img_path, 50, 320, width=250, height=250)
137
+ c.setFont("Helvetica-Bold", 12)
138
+ c.drawString(120, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
139
+
140
+ # Draw treatment and cost tables
141
+ treatment_table = format_table(treatment_data)
142
+ treatment_table.wrapOn(c, 480, 200)
143
+ treatment_table.drawOn(c, 50, 200)
144
+
145
+ cost_table = format_table(cost_duration_data)
146
+ cost_table.wrapOn(c, 480, 150)
147
+ cost_table.drawOn(c, 50, 80)
148
+
149
+ c.save()
150
+
151
+ # Send email with the report
152
+ subject = "Bone Fracture Detection Report"
153
+ body = f"Dear {name},\n\nPlease find attached your bone fracture detection report.\n\nSincerely,\nYour Bone Fracture Detection System"
154
+
155
+ msg = MIMEMultipart()
156
+ msg['From'] = SENDER_EMAIL
157
+ msg['To'] = email
158
+ msg['Subject'] = subject
159
+ msg.attach(MIMEText(body))
160
+
161
+ with open(report_path, "rb") as attachment:
162
+ part = MIMEBase('application', "octet-stream")
163
+ part.set_payload(attachment.read())
164
+
165
+ encoders.encode_base64(part)
166
+ part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(report_path)}")
167
+ msg.attach(part)
168
+
169
+ try:
170
+ with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
171
+ server.login(SENDER_EMAIL, SENDER_PASSWORD)
172
+ server.sendmail(SENDER_EMAIL, email, msg.as_string())
173
+ print(f"Report sent successfully to {email}")
174
+ return report_path # Return path for auto-download
175
+ except Exception as e:
176
+ return f"Error sending email: {e}"
177
+
178
+ # Function to select a sample image
179
+ def use_sample_image(sample_image_path):
180
+ return sample_image_path # Returns selected sample image filepath
181
+
182
+ # Define Gradio Interface
183
+ with gr.Blocks() as app:
184
+ gr.HTML(html_content) # Display `re.html` content in Gradio
185
+ gr.Markdown("## Bone Fracture Detection System")
186
+
187
+ with gr.Row():
188
+ name = gr.Textbox(label="Patient Name")
189
+ age = gr.Number(label="Age")
190
+ gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
191
+
192
+ with gr.Row():
193
+ weight = gr.Number(label="Weight (kg)")
194
+ height = gr.Number(label="Height (cm)")
195
+
196
+ with gr.Row():
197
+ allergies = gr.Textbox(label="Allergies (if any)")
198
+ cause = gr.Textbox(label="Cause of Injury")
199
+
200
+ with gr.Row():
201
+ xray = gr.Image(type="filepath", label="Upload X-ray Image")
202
+
203
+ with gr.Row():
204
+ sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
205
+ select_button = gr.Button("Load Sample Image")
206
+
207
+ email = gr.Textbox(label="Patient Email Address")
208
+ submit_button = gr.Button("Generate Report and Send Email")
209
+ output_file = gr.File(label="Download Report")
210
+
211
+ select_button.click(use_sample_image, inputs=[sample_selector], outputs=[xray])
212
+
213
+ submit_button.click(
214
+ generate_report,
215
+ inputs=[name, age, gender, weight, height, allergies, cause, xray, email],
216
+ outputs=[output_file],
217
+ )
218
+
219
+ # Launch the Gradio app
220
+ if __name__ == "__main__":
221
+ app.launch()