Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import AutoImageProcessor, AutoModelForImageClassification | |
from PIL import Image | |
import torch | |
# Load model and processor from the Hugging Face Hub | |
model_name = "prithivMLmods/Bone-Fracture-Detection" | |
model = AutoModelForImageClassification.from_pretrained(model_name) | |
processor = AutoImageProcessor.from_pretrained(model_name) | |
def detect_fracture(image): | |
""" | |
Takes a NumPy image array, processes it, and returns the model's prediction. | |
""" | |
# Convert NumPy array to a PIL Image | |
image = Image.fromarray(image).convert("RGB") | |
# Process the image and prepare it as input for the model | |
inputs = processor(images=image, return_tensors="pt") | |
# Perform inference without calculating gradients | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
logits = outputs.logits | |
# Apply softmax to get probabilities and convert to a list | |
probs = torch.nn.functional.softmax(logits, dim=1).squeeze().tolist() | |
# Create a dictionary of labels and their corresponding probabilities | |
# This now correctly uses the labels from the model's configuration | |
prediction = {model.config.id2label[i]: round(probs[i], 3) for i in range(len(probs))} | |
return prediction | |
# Create the Gradio Interface | |
iface = gr.Interface( | |
fn=detect_fracture, | |
inputs=gr.Image(type="numpy", label="Upload Bone X-ray"), | |
outputs=gr.Label(num_top_classes=2, label="Detection Result"), | |
title="π¬ Bone Fracture Detection", | |
description="Upload a bone X-ray image to detect if there is a fracture. The model will return the probability for 'Fractured' and 'Not Fractured'.", | |
examples=[ | |
["fractured_example.png"], | |
["not_fractured_example.png"] | |
] # Note: You would need to have these image files in the same directory for the examples to work. | |
) | |
# Launch the app | |
if __name__ == "__main__": | |
iface.launch() | |