Topgun3232 commited on
Commit
094f3b2
·
verified ·
1 Parent(s): d8c07bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -29
app.py CHANGED
@@ -1,29 +1,47 @@
1
- import gradio as gr
2
- from transformers import ViTFeatureExtractor, ViTForImageClassification
3
- from PIL import Image
4
- import torch
5
-
6
- # Load pre-trained model and feature extractor
7
- model_name = "google/vit-base-patch16-224"
8
- feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
9
- model = ViTForImageClassification.from_pretrained(model_name)
10
-
11
- # Define the prediction function
12
- def classify_image(img):
13
- inputs = feature_extractor(images=img, return_tensors="pt")
14
- with torch.no_grad():
15
- outputs = model(**inputs)
16
- logits = outputs.logits
17
- predicted_class_idx = logits.argmax(-1).item()
18
- predicted_label = model.config.id2label[predicted_class_idx]
19
- return predicted_label
20
-
21
- # Build the Gradio interface
22
- interface = gr.Interface(fn=classify_image,
23
- inputs=gr.Image(type="pil"),
24
- outputs="text",
25
- title="Image Classification with ViT",
26
- description="Upload an image and classify it using Vision Transformer (ViT)")
27
-
28
- # Launch the app
29
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()