| import gradio as gr
|
| import torch
|
| from transformers import AutoImageProcessor, AutoModelForImageClassification
|
| from PIL import Image
|
|
|
|
|
|
|
| model_name = "facebook/dinov2-base-imagenet1k-1-layer"
|
| processor = AutoImageProcessor.from_pretrained(model_name)
|
| model = AutoModelForImageClassification.from_pretrained(model_name)
|
|
|
| def classify_image(img):
|
|
|
| inputs = processor(images=img, return_tensors="pt")
|
|
|
|
|
| with torch.no_grad():
|
| outputs = model(**inputs)
|
|
|
|
|
| logits = outputs.logits
|
| probabilities = torch.nn.functional.softmax(logits, dim=-1)[0]
|
|
|
|
|
| top5_prob, top5_indices = torch.topk(probabilities, 5)
|
|
|
|
|
| confidences = {
|
| model.config.id2label[idx.item()]: float(prob)
|
| for prob, idx in zip(top5_prob, top5_indices)
|
| }
|
|
|
| return confidences
|
|
|
|
|
| demo = gr.Interface(
|
| fn=classify_image,
|
| inputs=gr.Image(type="pil", label="Upload Image"),
|
|
|
| outputs=gr.Label(num_top_classes=5, label="Predictions"),
|
| title="Next-Gen Image Classification",
|
| description="Running on **Meta's DINOv2** foundation model. Upload any image to see the top 5 predicted categories.",
|
| theme="soft"
|
| )
|
|
|
| if __name__ == "__main__":
|
| demo.launch() |