ftx7go commited on
Commit
58bb914
·
verified ·
1 Parent(s): 6ff5d91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -81
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Force TensorFlow to use CPU
3
-
 
4
  import gradio as gr
5
  import tensorflow as tf
6
  import numpy as np
@@ -18,7 +19,13 @@ model = tf.keras.models.load_model("my_keras_model.h5")
18
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
19
 
20
  # Function to process X-ray and generate a PDF report
21
- def generate_report(name, age, gender, weight, height, address, parent_name, allergies, cause, xray):
 
 
 
 
 
 
22
  image_size = (224, 224)
23
 
24
  def predict_fracture(xray_path):
@@ -28,53 +35,49 @@ def generate_report(name, age, gender, weight, height, address, parent_name, all
28
  prediction = model.predict(img_array)[0][0]
29
  return prediction
30
 
31
- # Predict fracture
32
  prediction = predict_fracture(xray)
33
  diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
34
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
35
 
36
- # Hospital details
37
- hospital_name = "City Care Hospital"
38
- hospital_address = "123 Health Street, MedCity, India"
39
- doctor_name = "Dr. Anil Sharma (Orthopedic Specialist)"
 
 
 
 
 
 
 
 
40
 
41
- # Save X-ray image for report
42
  img = Image.open(xray).resize((300, 300))
43
  img_path = f"{name}_xray.png"
44
  img.save(img_path)
45
 
46
- # Generate PDF report
47
  report_path = f"{name}_fracture_report.pdf"
48
  c = canvas.Canvas(report_path, pagesize=letter)
49
-
50
- # Set page margins
51
- c.translate(20, 20)
52
-
53
- # Report title
54
  c.setFont("Helvetica-Bold", 16)
55
- c.drawString(180, 750, hospital_name)
56
- c.setFont("Helvetica", 12)
57
- c.drawString(140, 735, hospital_address)
58
- c.drawString(180, 720, f"Attending Doctor: {doctor_name}")
59
 
60
- # Patient details
61
  patient_data = [
62
- ["Patient Name", name[:50]],
63
  ["Age", age],
64
  ["Gender", gender],
65
- ["Parent's Name", parent_name[:50]],
66
- ["Address", address[:70]],
67
  ["Weight", f"{weight} kg"],
68
  ["Height", f"{height} cm"],
69
- ["Allergies", allergies[:50] if allergies else "None"],
70
- ["Cause of Injury", cause[:50] if cause else "Not Provided"],
 
 
71
  ["Diagnosis", diagnosed_class],
72
  ["Injury Severity", severity]
73
  ]
74
 
75
- # Format and align tables
76
  def format_table(data):
77
- table = Table(data, colWidths=[200, 350])
78
  table.setStyle(TableStyle([
79
  ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
80
  ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
@@ -86,83 +89,80 @@ def generate_report(name, age, gender, weight, height, address, parent_name, all
86
  ]))
87
  return table
88
 
89
- # Draw patient details table
90
  patient_table = format_table(patient_data)
91
- patient_table.wrapOn(c, 450, 500)
92
  patient_table.drawOn(c, 50, 620)
93
 
94
- # Load and insert X-ray image
95
- c.drawInlineImage(img_path, 50, 350, width=250, height=250)
96
  c.setFont("Helvetica-Bold", 12)
97
- c.drawString(120, 320, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
 
 
 
 
98
 
99
- # Injury details
100
- c.setFont("Helvetica-Bold", 14)
101
- c.drawString(50, 270, "Injury Details and Treatment Recommendations")
102
- c.setFont("Helvetica", 12)
103
- c.drawString(50, 250, "• Immobilization and pain management")
104
- c.drawString(50, 235, "• Follow-up X-rays required")
105
- c.drawString(50, 220, "• Surgical intervention if needed")
106
- c.drawString(50, 205, "• Physiotherapy for recovery")
107
 
108
  c.save()
109
 
110
- return report_path # Return path for auto-download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  # Function to select a sample image
113
  def use_sample_image(sample_image_path):
114
- return sample_image_path # Returns selected sample image filepath
115
 
116
  # Define Gradio Interface
117
  with gr.Blocks() as app:
118
- gr.Markdown("## **Bone Fracture Detection System**")
119
 
120
- # Informative Blog Section
121
- with gr.Accordion("Bone Fractures - Symptoms, Causes, & Treatment", open=True):
122
- gr.Markdown("""
123
- **A fracture** is a break or crack in a bone caused by excessive force.
124
- **Common Causes:**
125
- - Traumatic injuries (sports, accidents, falls)
126
- - Osteoporosis or cancer (weakened bones)
127
-
128
- **Symptoms:**
129
- - Severe pain, swelling, bruising
130
- - Deformity or inability to use the limb
131
-
132
- **Diagnosis:**
133
- - X-rays, CT scans, MRI scans
134
-
135
- **Treatment:**
136
- - Plaster casts, splints, surgery if needed
137
- - Pain management and physiotherapy
138
-
139
- **First Aid:**
140
- - Immobilize the area
141
- - Apply a cold pack
142
- - Seek medical help immediately
143
- """)
144
-
145
- # Patient Details Form
146
  with gr.Row():
147
- name = gr.Textbox(label="Patient Name", max_length=50)
148
  age = gr.Number(label="Age")
149
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
150
-
151
- with gr.Row():
152
- parent_name = gr.Textbox(label="Parent's Name", max_length=50)
153
- address = gr.Textbox(label="Address", max_length=70)
154
-
155
  with gr.Row():
156
  weight = gr.Number(label="Weight (kg)")
157
  height = gr.Number(label="Height (cm)")
158
-
159
  with gr.Row():
160
- allergies = gr.Textbox(label="Allergies (if any, max 50 chars)", max_length=50)
161
- cause = gr.Textbox(label="Cause of Injury (max 50 chars)", max_length=50)
 
 
 
 
162
 
 
 
 
163
  with gr.Row():
164
  xray = gr.Image(type="filepath", label="Upload X-ray Image")
165
-
166
  with gr.Row():
167
  sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
168
  select_button = gr.Button("Load Sample Image")
@@ -174,10 +174,9 @@ with gr.Blocks() as app:
174
 
175
  submit_button.click(
176
  generate_report,
177
- inputs=[name, age, gender, weight, height, address, parent_name, allergies, cause, xray],
178
  outputs=[output_file],
179
  )
180
 
181
- # Launch the Gradio app
182
  if __name__ == "__main__":
183
  app.launch()
 
1
  import os
2
+ import smtplib
3
+ import mimetypes
4
+ from email.message import EmailMessage
5
  import gradio as gr
6
  import tensorflow as tf
7
  import numpy as np
 
19
  sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
20
 
21
  # Function to process X-ray and generate a PDF report
22
+ def generate_report(name, age, gender, weight, height, address, parents, allergies, cause, email, xray):
23
+ # Input validation
24
+ name = name[:50]
25
+ address = address[:100]
26
+ parents = parents[:50]
27
+ cause = ' '.join(cause.split()[:100])
28
+
29
  image_size = (224, 224)
30
 
31
  def predict_fracture(xray_path):
 
35
  prediction = model.predict(img_array)[0][0]
36
  return prediction
37
 
 
38
  prediction = predict_fracture(xray)
39
  diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
40
  severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
41
 
42
+ treatment_data = [
43
+ ["Severity Level", "Recommended Treatment", "Recovery Duration"],
44
+ ["Mild", "Rest, pain relievers, follow-up X-ray", "4-6 weeks"],
45
+ ["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
46
+ ["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
47
+ ]
48
+
49
+ cost_duration_data = [
50
+ ["Hospital Type", "Estimated Cost", "Recovery Time"],
51
+ ["Government", 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"],
52
+ ["Private", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
53
+ ]
54
 
 
55
  img = Image.open(xray).resize((300, 300))
56
  img_path = f"{name}_xray.png"
57
  img.save(img_path)
58
 
 
59
  report_path = f"{name}_fracture_report.pdf"
60
  c = canvas.Canvas(report_path, pagesize=letter)
61
+
 
 
 
 
62
  c.setFont("Helvetica-Bold", 16)
63
+ c.drawString(200, 770, "Bone Fracture Detection Report")
 
 
 
64
 
 
65
  patient_data = [
66
+ ["Patient Name", name],
67
  ["Age", age],
68
  ["Gender", gender],
 
 
69
  ["Weight", f"{weight} kg"],
70
  ["Height", f"{height} cm"],
71
+ ["Address", address],
72
+ ["Parent's Name", parents],
73
+ ["Allergies", allergies if allergies else "None"],
74
+ ["Cause of Injury", cause],
75
  ["Diagnosis", diagnosed_class],
76
  ["Injury Severity", severity]
77
  ]
78
 
 
79
  def format_table(data):
80
+ table = Table(data, colWidths=[270, 270])
81
  table.setStyle(TableStyle([
82
  ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
83
  ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
 
89
  ]))
90
  return table
91
 
 
92
  patient_table = format_table(patient_data)
93
+ patient_table.wrapOn(c, 480, 500)
94
  patient_table.drawOn(c, 50, 620)
95
 
96
+ c.drawInlineImage(img_path, 170, 320, width=250, height=250)
 
97
  c.setFont("Helvetica-Bold", 12)
98
+ c.drawString(250, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
99
+
100
+ treatment_table = format_table(treatment_data)
101
+ treatment_table.wrapOn(c, 480, 200)
102
+ treatment_table.drawOn(c, 50, 200)
103
 
104
+ cost_table = format_table(cost_duration_data)
105
+ cost_table.wrapOn(c, 480, 150)
106
+ cost_table.drawOn(c, 50, 80)
 
 
 
 
 
107
 
108
  c.save()
109
 
110
+ send_email(email, report_path)
111
+
112
+ return report_path
113
+
114
+ # Function to send email
115
+ def send_email(receiver_email, attachment_path):
116
+ sender_email = "[email protected]"
117
+ sender_password = "yourpassword"
118
+
119
+ msg = EmailMessage()
120
+ msg["Subject"] = "Your Bone Fracture Report"
121
+ msg["From"] = sender_email
122
+ msg["To"] = receiver_email
123
+ msg.set_content("Please find attached your bone fracture diagnosis report.")
124
+
125
+ mime_type, _ = mimetypes.guess_type(attachment_path)
126
+ mime_type = mime_type or "application/octet-stream"
127
+
128
+ with open(attachment_path, "rb") as attachment:
129
+ msg.add_attachment(attachment.read(), maintype=mime_type.split("/")[0], subtype=mime_type.split("/")[1], filename=os.path.basename(attachment_path))
130
+
131
+ with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
132
+ server.login(sender_email, sender_password)
133
+ server.send_message(msg)
134
 
135
  # Function to select a sample image
136
  def use_sample_image(sample_image_path):
137
+ return sample_image_path
138
 
139
  # Define Gradio Interface
140
  with gr.Blocks() as app:
141
+ gr.Markdown("## Bone Fracture Detection System")
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  with gr.Row():
144
+ name = gr.Textbox(label="Patient Name (Max 50 chars)", max_chars=50)
145
  age = gr.Number(label="Age")
146
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
147
+
 
 
 
 
148
  with gr.Row():
149
  weight = gr.Number(label="Weight (kg)")
150
  height = gr.Number(label="Height (cm)")
151
+
152
  with gr.Row():
153
+ address = gr.Textbox(label="Address (Max 100 chars)", max_chars=100)
154
+ parents = gr.Textbox(label="Parent's Name (Max 50 chars)", max_chars=50)
155
+
156
+ with gr.Row():
157
+ allergies = gr.Textbox(label="Allergies (if any)")
158
+ cause = gr.Textbox(label="Cause of Injury (Max 100 words)")
159
 
160
+ with gr.Row():
161
+ email = gr.Textbox(label="Patient's Email (To receive report)", type="email")
162
+
163
  with gr.Row():
164
  xray = gr.Image(type="filepath", label="Upload X-ray Image")
165
+
166
  with gr.Row():
167
  sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
168
  select_button = gr.Button("Load Sample Image")
 
174
 
175
  submit_button.click(
176
  generate_report,
177
+ inputs=[name, age, gender, weight, height, address, parents, allergies, cause, email, xray],
178
  outputs=[output_file],
179
  )
180
 
 
181
  if __name__ == "__main__":
182
  app.launch()