Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
|
6 |
+
# Load model and processor from the Hugging Face Hub
|
7 |
+
model_name = "prithivMLmods/Bone-Fracture-Detection"
|
8 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
9 |
+
processor = AutoImageProcessor.from_pretrained(model_name)
|
10 |
+
|
11 |
+
def detect_fracture(image):
|
12 |
+
"""
|
13 |
+
Takes a NumPy image array, processes it, and returns the model's prediction.
|
14 |
+
"""
|
15 |
+
# Convert NumPy array to a PIL Image
|
16 |
+
image = Image.fromarray(image).convert("RGB")
|
17 |
+
|
18 |
+
# Process the image and prepare it as input for the model
|
19 |
+
inputs = processor(images=image, return_tensors="pt")
|
20 |
+
|
21 |
+
# Perform inference without calculating gradients
|
22 |
+
with torch.no_grad():
|
23 |
+
outputs = model(**inputs)
|
24 |
+
logits = outputs.logits
|
25 |
+
|
26 |
+
# Apply softmax to get probabilities and convert to a list
|
27 |
+
probs = torch.nn.functional.softmax(logits, dim=1).squeeze().tolist()
|
28 |
+
|
29 |
+
# Create a dictionary of labels and their corresponding probabilities
|
30 |
+
# This now correctly uses the labels from the model's configuration
|
31 |
+
prediction = {model.config.id2label[i]: round(probs[i], 3) for i in range(len(probs))}
|
32 |
+
|
33 |
+
return prediction
|
34 |
+
|
35 |
+
# Create the Gradio Interface
|
36 |
+
iface = gr.Interface(
|
37 |
+
fn=detect_fracture,
|
38 |
+
inputs=gr.Image(type="numpy", label="Upload Bone X-ray"),
|
39 |
+
outputs=gr.Label(num_top_classes=2, label="Detection Result"),
|
40 |
+
title="🔬 Bone Fracture Detection",
|
41 |
+
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'.",
|
42 |
+
examples=[
|
43 |
+
["fractured_example.png"],
|
44 |
+
["not_fractured_example.png"]
|
45 |
+
] # Note: You would need to have these image files in the same directory for the examples to work.
|
46 |
+
)
|
47 |
+
|
48 |
+
# Launch the app
|
49 |
+
if __name__ == "__main__":
|
50 |
+
iface.launch()
|