ftx7go's picture
Update app.py
8079fc6 verified
raw
history blame
2.71 kB
import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing import image
from PIL import Image
import os
from fpdf import FPDF
import datetime
# Load the trained model
model = tf.keras.models.load_model("my_keras_model.h5")
# Define image size based on the model's input requirement
image_size = (224, 224)
# Function to make predictions
def predict_image(img):
img = img.resize(image_size) # Resize image to model's expected size
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0 # Normalize
prediction = model.predict(img_array)
# Assuming binary classification (fractured or normal)
class_names = ['Fractured', 'Normal']
predicted_class = class_names[int(prediction[0] > 0.5)] # Threshold at 0.5
confidence = prediction[0][0]
return predicted_class, confidence
# Function to generate a PDF report
def generate_report(name, age, weight, height, img):
# Predict result
predicted_class, confidence = predict_image(img)
# Create PDF
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12)
# Add title
pdf.set_font("Arial", style='B', size=16)
pdf.cell(200, 10, "Bone Fracture Detection Report", ln=True, align='C')
pdf.ln(10)
# Add patient details
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, f"Patient Name: {name}", ln=True)
pdf.cell(200, 10, f"Age: {age}", ln=True)
pdf.cell(200, 10, f"Weight: {weight} kg", ln=True)
pdf.cell(200, 10, f"Height: {height} cm", ln=True)
pdf.cell(200, 10, f"Diagnosis Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True)
pdf.ln(10)
# Add prediction result
pdf.set_font("Arial", style='B', size=14)
pdf.cell(200, 10, f"Diagnosis: {predicted_class}", ln=True)
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, f"Confidence: {confidence:.2f}", ln=True)
# Save PDF
pdf_filename = "patient_report.pdf"
pdf.output(pdf_filename)
return pdf_filename
# Define Gradio Interface
interface = gr.Interface(
fn=generate_report,
inputs=[
gr.Textbox(label="Patient Name"),
gr.Number(label="Age"),
gr.Number(label="Weight (kg)"),
gr.Number(label="Height (cm)"),
gr.Image(type="pil", label="X-ray Image")
],
outputs=gr.File(label="Download Report"),
title="Bone Fracture Detection & Diagnosis",
description="Fill in the patient details and upload an X-ray image. The system will analyze the image and generate a PDF report with the diagnosis."
)
# Launch the Gradio app
if __name__ == "__main__":
interface.launch()