ftx7go's picture
Update app.py
58bb914 verified
raw
history blame
6.61 kB
import os
import smtplib
import mimetypes
from email.message import EmailMessage
import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing import image
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.platypus import Table, TableStyle
# Load the trained model
model = tf.keras.models.load_model("my_keras_model.h5")
# List of sample images
sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))]
# Function to process X-ray and generate a PDF report
def generate_report(name, age, gender, weight, height, address, parents, allergies, cause, email, xray):
# Input validation
name = name[:50]
address = address[:100]
parents = parents[:50]
cause = ' '.join(cause.split()[:100])
image_size = (224, 224)
def predict_fracture(xray_path):
img = Image.open(xray_path).resize(image_size)
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
prediction = model.predict(img_array)[0][0]
return prediction
prediction = predict_fracture(xray)
diagnosed_class = "Normal" if prediction > 0.5 else "Fractured"
severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
treatment_data = [
["Severity Level", "Recommended Treatment", "Recovery Duration"],
["Mild", "Rest, pain relievers, follow-up X-ray", "4-6 weeks"],
["Moderate", "Plaster cast, minor surgery if needed", "6-10 weeks"],
["Severe", "Major surgery, metal implants, physiotherapy", "Several months"]
]
cost_duration_data = [
["Hospital Type", "Estimated Cost", "Recovery Time"],
["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"],
["Private", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"]
]
img = Image.open(xray).resize((300, 300))
img_path = f"{name}_xray.png"
img.save(img_path)
report_path = f"{name}_fracture_report.pdf"
c = canvas.Canvas(report_path, pagesize=letter)
c.setFont("Helvetica-Bold", 16)
c.drawString(200, 770, "Bone Fracture Detection Report")
patient_data = [
["Patient Name", name],
["Age", age],
["Gender", gender],
["Weight", f"{weight} kg"],
["Height", f"{height} cm"],
["Address", address],
["Parent's Name", parents],
["Allergies", allergies if allergies else "None"],
["Cause of Injury", cause],
["Diagnosis", diagnosed_class],
["Injury Severity", severity]
]
def format_table(data):
table = Table(data, colWidths=[270, 270])
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
]))
return table
patient_table = format_table(patient_data)
patient_table.wrapOn(c, 480, 500)
patient_table.drawOn(c, 50, 620)
c.drawInlineImage(img_path, 170, 320, width=250, height=250)
c.setFont("Helvetica-Bold", 12)
c.drawString(250, 290, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
treatment_table = format_table(treatment_data)
treatment_table.wrapOn(c, 480, 200)
treatment_table.drawOn(c, 50, 200)
cost_table = format_table(cost_duration_data)
cost_table.wrapOn(c, 480, 150)
cost_table.drawOn(c, 50, 80)
c.save()
send_email(email, report_path)
return report_path
# Function to send email
def send_email(receiver_email, attachment_path):
sender_email = "[email protected]"
sender_password = "yourpassword"
msg = EmailMessage()
msg["Subject"] = "Your Bone Fracture Report"
msg["From"] = sender_email
msg["To"] = receiver_email
msg.set_content("Please find attached your bone fracture diagnosis report.")
mime_type, _ = mimetypes.guess_type(attachment_path)
mime_type = mime_type or "application/octet-stream"
with open(attachment_path, "rb") as attachment:
msg.add_attachment(attachment.read(), maintype=mime_type.split("/")[0], subtype=mime_type.split("/")[1], filename=os.path.basename(attachment_path))
with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
server.login(sender_email, sender_password)
server.send_message(msg)
# Function to select a sample image
def use_sample_image(sample_image_path):
return sample_image_path
# Define Gradio Interface
with gr.Blocks() as app:
gr.Markdown("## Bone Fracture Detection System")
with gr.Row():
name = gr.Textbox(label="Patient Name (Max 50 chars)", max_chars=50)
age = gr.Number(label="Age")
gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
with gr.Row():
weight = gr.Number(label="Weight (kg)")
height = gr.Number(label="Height (cm)")
with gr.Row():
address = gr.Textbox(label="Address (Max 100 chars)", max_chars=100)
parents = gr.Textbox(label="Parent's Name (Max 50 chars)", max_chars=50)
with gr.Row():
allergies = gr.Textbox(label="Allergies (if any)")
cause = gr.Textbox(label="Cause of Injury (Max 100 words)")
with gr.Row():
email = gr.Textbox(label="Patient's Email (To receive report)", type="email")
with gr.Row():
xray = gr.Image(type="filepath", label="Upload X-ray Image")
with gr.Row():
sample_selector = gr.Dropdown(choices=sample_images, label="Use Sample Image")
select_button = gr.Button("Load Sample Image")
submit_button = gr.Button("Generate Report")
output_file = gr.File(label="Download Report")
select_button.click(use_sample_image, inputs=[sample_selector], outputs=[xray])
submit_button.click(
generate_report,
inputs=[name, age, gender, weight, height, address, parents, allergies, cause, email, xray],
outputs=[output_file],
)
if __name__ == "__main__":
app.launch()