Download app.py from Speshal89/ViT: direct link, hf CLI and curl.
- Browser
- Download file 979 Bytes
-
https://huggingface.co/spaces/Speshal89/ViT/resolve/main/app.py
- Command line
-
hf download hf://spaces/Speshal89/ViT/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Speshal89/ViT/resolve/main/app.py
979 Bytes
| import gradio as gr | |
| from transformers import AutoFeatureExtractor, AutoModelForImageClassification | |
| from PIL import Image | |
| import torch | |
| import json | |
| # Load model and extractor | |
| model = AutoModelForImageClassification.from_pretrained("google/vit-base-patch16-224") | |
| extractor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224") | |
| # Load id2label from local file | |
| with open("labels.json", "r") as f: | |
| id2label = json.load(f) | |
| # Predict | |
| def predict(image): | |
| inputs = extractor(images=image, return_tensors="pt") | |
| outputs = model(**inputs) | |
| logits = outputs.logits | |
| probs = torch.nn.functional.softmax(logits, dim=1)[0] | |
| top = torch.topk(probs, 3) | |
| return [ | |
| { | |
| "label": id2label.get(str(idx.item()), f"label_{idx.item()}"), | |
| "score": round(score.item(), 4) | |
| } | |
| for idx, score in zip(top.indices, top.values) | |
| ] | |
| # Launch app | |
| demo = gr.Interface(fn=predict, inputs="image", outputs="json") | |
| demo.launch() | |