ftx7go's picture
Update app.py
6ff5d91 verified
raw
history blame
6.41 kB
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Force TensorFlow to use CPU
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, parent_name, 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"
severity = "Mild" if prediction < 0.3 else "Moderate" if prediction < 0.7 else "Severe"
# Hospital details
hospital_name = "City Care Hospital"
hospital_address = "123 Health Street, MedCity, India"
doctor_name = "Dr. Anil Sharma (Orthopedic Specialist)"
# Save X-ray image for report
img = Image.open(xray).resize((300, 300))
img_path = f"{name}_xray.png"
img.save(img_path)
# Generate PDF report
report_path = f"{name}_fracture_report.pdf"
c = canvas.Canvas(report_path, pagesize=letter)
# Set page margins
c.translate(20, 20)
# Report title
c.setFont("Helvetica-Bold", 16)
c.drawString(180, 750, hospital_name)
c.setFont("Helvetica", 12)
c.drawString(140, 735, hospital_address)
c.drawString(180, 720, f"Attending Doctor: {doctor_name}")
# Patient details
patient_data = [
["Patient Name", name[:50]],
["Age", age],
["Gender", gender],
["Parent's Name", parent_name[:50]],
["Address", address[:70]],
["Weight", f"{weight} kg"],
["Height", f"{height} cm"],
["Allergies", allergies[:50] if allergies else "None"],
["Cause of Injury", cause[:50] if cause else "Not Provided"],
["Diagnosis", diagnosed_class],
["Injury Severity", severity]
]
# Format and align tables
def format_table(data):
table = Table(data, colWidths=[200, 350])
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, 450, 500)
patient_table.drawOn(c, 50, 620)
# Load and insert X-ray image
c.drawInlineImage(img_path, 50, 350, width=250, height=250)
c.setFont("Helvetica-Bold", 12)
c.drawString(120, 320, f"Fractured: {'Yes' if diagnosed_class == 'Fractured' else 'No'}")
# Injury details
c.setFont("Helvetica-Bold", 14)
c.drawString(50, 270, "Injury Details and Treatment Recommendations")
c.setFont("Helvetica", 12)
c.drawString(50, 250, "• Immobilization and pain management")
c.drawString(50, 235, "• Follow-up X-rays required")
c.drawString(50, 220, "• Surgical intervention if needed")
c.drawString(50, 205, "• Physiotherapy for recovery")
c.save()
return report_path # Return path for auto-download
# Function to select a sample image
def use_sample_image(sample_image_path):
return sample_image_path # Returns selected sample image filepath
# Define Gradio Interface
with gr.Blocks() as app:
gr.Markdown("## **Bone Fracture Detection System**")
# Informative Blog Section
with gr.Accordion("Bone Fractures - Symptoms, Causes, & Treatment", open=True):
gr.Markdown("""
**A fracture** is a break or crack in a bone caused by excessive force.
**Common Causes:**
- Traumatic injuries (sports, accidents, falls)
- Osteoporosis or cancer (weakened bones)
**Symptoms:**
- Severe pain, swelling, bruising
- Deformity or inability to use the limb
**Diagnosis:**
- X-rays, CT scans, MRI scans
**Treatment:**
- Plaster casts, splints, surgery if needed
- Pain management and physiotherapy
**First Aid:**
- Immobilize the area
- Apply a cold pack
- Seek medical help immediately
""")
# Patient Details Form
with gr.Row():
name = gr.Textbox(label="Patient Name", max_length=50)
age = gr.Number(label="Age")
gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
with gr.Row():
parent_name = gr.Textbox(label="Parent's Name", max_length=50)
address = gr.Textbox(label="Address", max_length=70)
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, max 50 chars)", max_length=50)
cause = gr.Textbox(label="Cause of Injury (max 50 chars)", max_length=50)
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, parent_name, allergies, cause, xray],
outputs=[output_file],
)
# Launch the Gradio app
if __name__ == "__main__":
app.launch()