import os import smtplib import gradio as gr import tensorflow as tf import numpy as np from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders 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 # Ensure the "reports" directory exists if not os.path.exists("reports"): os.makedirs("reports") # Load the trained model model = tf.keras.models.load_model("my_keras_model.h5") # Read HTML content from `re.html` with open("templates/re.html", "r", encoding="utf-8") as file: html_content = file.read() # List of sample images sample_images = [f"samples/{img}" for img in os.listdir("samples") if img.endswith((".png", ".jpg", ".jpeg"))] # Function to generate and save the report def generate_report(name, age, gender, weight, height, allergies, cause, xray): 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 # Predict fracture prediction = predict_fracture(xray) diagnosed_class = "normal" if prediction > 0.5 else "Fractured" # Injury severity classification severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe" # Treatment details table treatment_data = [ ["Severity Level", "Recommended Treatment", "Recovery Duration"], ["Mild", "Rest, pain relievers, and 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"] ] # Estimated cost & duration table cost_duration_data = [ ["Hospital Type", "Estimated Cost", "Recovery Time"], ["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"], ["Private Hospital", f"₹{10000 if severity == 'Mild' else 30000 if severity == 'Moderate' else 100000}+", "6 weeks - Several months"] ] # Save X-ray image for report img = Image.open(xray).resize((300, 300)) img_path = f"reports/{name}_xray.png" img.save(img_path) # Generate PDF report report_path = f"reports/{name}_fracture_report.pdf" c = canvas.Canvas(report_path, pagesize=letter) # Report title c.setFont("Helvetica-Bold", 16) c.drawString(200, 770, "Bone Fracture Detection Report") # Patient details table patient_data = [ ["Patient Name", name], ["Age", age], ["Gender", gender], ["Weight", f"{weight} kg"], ["Height", f"{height} cm"], ["Allergies", allergies if allergies else "None"], ["Cause of Injury", cause if cause else "Not Provided"], ["Diagnosis", diagnosed_class], ["Injury Severity", severity] ] # Format and align tables 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 # Draw tables and images patient_table = format_table(patient_data) patient_table.wrapOn(c, 480, 500) patient_table.drawOn(c, 50, 620) c.drawInlineImage(img_path, 50, 320, width=250, height=250) c.setFont("Helvetica-Bold", 12) c.drawString(120, 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() return report_path # Return path for auto-download # Function to send email with attachment def send_email(patient_email, report_path): sender_email = "your_email@example.com" sender_password = "your_email_password" subject = "Bone Fracture Detection Report" body = "Attached is your bone fracture detection report." msg = MIMEMultipart() msg["From"] = sender_email msg["To"] = patient_email msg["Subject"] = subject msg.attach(MIMEText(body, "plain")) with open(report_path, "rb") as attachment: part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(report_path)}") msg.attach(part) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(sender_email, sender_password) server.sendmail(sender_email, patient_email, msg.as_string()) server.quit() return "Email Sent Successfully!" except Exception as e: return f"Error sending email: {str(e)}" # Define Gradio Interface with gr.Blocks() as app: gr.HTML(html_content) gr.Markdown("## Bone Fracture Detection System") with gr.Row(): name = gr.Textbox(label="Patient Name") age = gr.Number(label="Age") gender = gr.Radio(["Male", "Female", "Other"], label="Gender") patient_email = gr.Textbox(label="Patient Email") with gr.Row(): weight = gr.Number(label="Weight (kg)") height = gr.Number(label="Height (cm)") with gr.Row(): allergies = gr.Textbox(label="Allergies") cause = gr.Textbox(label="Cause of Injury") xray = gr.Image(type="filepath", label="Upload X-ray Image") generate_button = gr.Button("Generate & Download Report") send_email_button = gr.Button("Send Report via Email") output_file = gr.File(label="Download Report") status = gr.Textbox(label="Email Status", interactive=False) generate_button.click(generate_report, inputs=[name, age, gender, weight, height, allergies, cause, xray], outputs=[output_file]) send_email_button.click(send_email, inputs=[patient_email, output_file], outputs=[status]) if __name__ == "__main__": app.launch()