Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,47 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
|
| 3 |
-
from
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
# Load
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def classify_image(img):
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
# 1. Load a modern SOTA model (DINOv2)
|
| 7 |
+
# This model is faster and more accurate than the original ViT
|
| 8 |
+
model_name = "facebook/dinov2-base-imagenet1k-1-layer"
|
| 9 |
+
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 10 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
| 11 |
+
|
| 12 |
+
def classify_image(img):
|
| 13 |
+
# 2. Pre-process image
|
| 14 |
+
inputs = processor(images=img, return_tensors="pt")
|
| 15 |
+
|
| 16 |
+
# 3. Inference
|
| 17 |
+
with torch.no_grad():
|
| 18 |
+
outputs = model(**inputs)
|
| 19 |
+
|
| 20 |
+
# 4. Convert logits to probabilities (0% to 100%)
|
| 21 |
+
logits = outputs.logits
|
| 22 |
+
probabilities = torch.nn.functional.softmax(logits, dim=-1)[0]
|
| 23 |
+
|
| 24 |
+
# 5. Extract top 5 results for a better UI
|
| 25 |
+
top5_prob, top5_indices = torch.topk(probabilities, 5)
|
| 26 |
+
|
| 27 |
+
# Create a dictionary of {Label: Probability} for Gradio's Label component
|
| 28 |
+
confidences = {
|
| 29 |
+
model.config.id2label[idx.item()]: float(prob)
|
| 30 |
+
for prob, idx in zip(top5_prob, top5_indices)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
return confidences
|
| 34 |
+
|
| 35 |
+
# 6. Build a modern UI
|
| 36 |
+
demo = gr.Interface(
|
| 37 |
+
fn=classify_image,
|
| 38 |
+
inputs=gr.Image(type="pil", label="Upload Image"),
|
| 39 |
+
# gr.Label automatically creates a beautiful bar chart for probabilities
|
| 40 |
+
outputs=gr.Label(num_top_classes=5, label="Predictions"),
|
| 41 |
+
title="Next-Gen Image Classification",
|
| 42 |
+
description="Running on **Meta's DINOv2** foundation model. Upload any image to see the top 5 predicted categories.",
|
| 43 |
+
theme="soft"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
demo.launch()
|