Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +29 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
transformers
|
| 3 |
+
torch
|
| 4 |
+
|