File size: 4,812 Bytes
75ae599
f494b68
12a86ab
 
236bf74
 
 
 
12a86ab
 
 
236bf74
f494b68
236bf74
 
 
58bb914
236bf74
58a8df2
c6b4946
236bf74
 
 
c6b4946
236bf74
 
 
 
 
 
 
12a86ab
236bf74
 
 
 
58bb914
236bf74
 
 
 
 
58bb914
236bf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58bb914
236bf74
 
58bb914
236bf74
 
 
58bb914
236bf74
 
 
 
 
 
 
58bb914
236bf74
 
12a86ab
236bf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12a86ab
 
236bf74
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import os
import gradio as gr
import tensorflow as tf
import numpy as np
import cv2
import smtplib
import ssl
from email.message import EmailMessage
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader

# Disable GPU to avoid CUDA errors
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

# Load the trained model
model = tf.keras.models.load_model("my_keras_model.h5")

# Email sender credentials (Set your own credentials here)
SENDER_EMAIL = "[email protected]"
SENDER_PASSWORD = "your_email_password"

def send_email(receiver_email, file_path):
    """Function to send an email with the generated PDF attached"""
    msg = EmailMessage()
    msg["Subject"] = "Bone Fracture Patient Report"
    msg["From"] = SENDER_EMAIL
    msg["To"] = receiver_email
    msg.set_content("Please find the attached bone fracture report.")

    # Attach PDF file
    with open(file_path, "rb") as f:
        file_data = f.read()
        msg.add_attachment(file_data, maintype="application", subtype="pdf", filename="Fracture_Report.pdf")

    # Send email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.send_message(msg)

def preprocess_image(image):
    """Preprocess the image for model prediction"""
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)
    image = cv2.resize(image, (224, 224))
    image = np.expand_dims(image, axis=-1)
    image = np.expand_dims(image, axis=0) / 255.0
    return image

def generate_pdf(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email):
    """Generate a PDF report"""
    file_path = "Fracture_Report.pdf"
    c = canvas.Canvas(file_path, pagesize=letter)
    width, height = letter

    # Title
    c.setFont("Helvetica-Bold", 16)
    c.drawCentredString(width / 2, height - 50, "Bone Fracture Patient Report")

    # Patient Info Table
    c.setFont("Helvetica", 12)
    data = [
        ["Patient Name:", name[:50]],
        ["Age:", age],
        ["Gender:", gender],
        ["Weight (kg):", weight],
        ["Height (cm):", height],
        ["Allergies:", allergies[:100]],
        ["Injury Cause:", " ".join(injury_cause.split()[:100])],  # Limit to 100 words
        ["Address:", address[:100]],
        ["Parent/Guardian Name:", parent_name[:50]],
    ]

    x_start, y_start = 50, height - 100
    line_spacing = 20

    for row in data:
        c.drawString(x_start, y_start, f"{row[0]} {row[1]}")
        y_start -= line_spacing

    # Add X-ray image
    if image:
        img = Image.open(image)
        img.thumbnail((250, 250))
        img_path = "temp_image.jpg"
        img.save(img_path)
        c.drawImage(ImageReader(img_path), width / 2 - 125, y_start - 250, 250, 250)

    # Close and save the PDF
    c.save()

    # Send email
    if email:
        send_email(email, file_path)

    return file_path

def predict_and_generate_report(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email):
    """Make a prediction and generate a report"""
    if image is None:
        return "Please upload an X-ray image."

    # Preprocess and make a prediction
    processed_image = preprocess_image(image)
    prediction = model.predict(processed_image)
    confidence = float(prediction[0][0]) * 100
    fracture_status = "Yes" if confidence > 50 else "No"

    # Generate PDF report
    pdf_path = generate_pdf(name, age, gender, weight, height, allergies, injury_cause, address, parent_name, image, email)

    return f"Fractured: {fracture_status} (Confidence: {confidence:.2f}%)", pdf_path

# Define the Gradio Interface
iface = gr.Interface(
    fn=predict_and_generate_report,
    inputs=[
        gr.Textbox(label="Patient Name (Max 50 chars)"),
        gr.Number(label="Age", precision=0),
        gr.Radio(label="Gender", choices=["Male", "Female", "Other"]),
        gr.Number(label="Weight (kg)"),
        gr.Number(label="Height (cm)"),
        gr.Textbox(label="Allergies (Max 100 chars)"),
        gr.Textbox(label="Cause of Injury (Max 100 words)"),
        gr.Textbox(label="Address (Max 100 chars)"),
        gr.Textbox(label="Parent/Guardian Name (Max 50 chars)"),
        gr.Image(type="pil", label="Upload X-ray Image"),
        gr.Textbox(label="Email Address (for Report)"),
    ],
    outputs=[
        gr.Textbox(label="Fracture Prediction"),
        gr.File(label="Download Report"),
    ],
    title="Bone Fracture Detection System",
    description="Upload an X-ray image, enter patient details, and generate a fracture report."
)

if __name__ == "__main__":
    iface.launch()