import os import smtplib import gradio as gr import tensorflow as tf import numpy as np from email.message import EmailMessage 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") # Ensure the reports directory exists REPORTS_DIR = "reports" os.makedirs(REPORTS_DIR, exist_ok=True) # 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 process X-ray and generate a PDF report def generate_report(name, age, gender, weight, height, allergies, cause, xray, email): 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" severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe" # File paths report_filename = f"{name}_fracture_report.pdf" report_path = os.path.join(REPORTS_DIR, report_filename) # Generate PDF report c = canvas.Canvas(report_path, pagesize=letter) c.setFont("Helvetica-Bold", 16) c.drawString(200, 770, "Bone Fracture Detection Report") # Patient details 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 table function 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 patient details table patient_table = format_table(patient_data) patient_table.wrapOn(c, 480, 500) patient_table.drawOn(c, 50, 620) # Save and return report path c.save() # Send email with report send_email_with_attachment(email, report_path, name) return report_path # For download # Function to send email with PDF attachment def send_email_with_attachment(to_email, file_path, patient_name): sender_email = "your-email@gmail.com" # Replace with your email sender_password = "your-email-password" # Use App Passwords if using Gmail msg = EmailMessage() msg["Subject"] = f"Bone Fracture Report for {patient_name}" msg["From"] = sender_email msg["To"] = to_email msg.set_content(f"Dear {patient_name},\n\nAttached is your bone fracture detection report.\n\nThank you!") # Attach PDF file with open(file_path, "rb") as f: file_data = f.read() file_name = os.path.basename(file_path) msg.add_attachment(file_data, maintype="application", subtype="pdf", filename=file_name) # Send email try: with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server: server.login(sender_email, sender_password) server.send_message(msg) print(f"Email sent to {to_email}") except Exception as e: print(f"Failed to send email: {e}") # 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.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") with gr.Row(): weight = gr.Number(label="Weight (kg)") height = gr.Number(label="Height (cm)") with gr.Row(): allergies = gr.Textbox(label="Allergies (if any)") cause = gr.Textbox(label="Cause of Injury") with gr.Row(): email = gr.Textbox(label="Patient 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 & Send Email") 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, allergies, cause, xray, email], outputs=[output_file], ) # Launch the Gradio app if __name__ == "__main__": app.launch()