File size: 1,933 Bytes
76b753e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()