freddyaboulton HF staff commited on
Commit
87ec49a
1 Parent(s): 859d7b7

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +24 -0
app.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import ViTFeatureExtractor, ViTForImageClassification
2
+ from PIL import Image
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import time
6
+
7
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
8
+
9
+ feature_extractor = ViTFeatureExtractor.from_pretrained('google/vit-base-patch16-224')
10
+ model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224').to(device)
11
+
12
+ def predict(image):
13
+ inputs = feature_extractor(images=image, return_tensors="pt").to(device)
14
+ outputs = model(**inputs)
15
+ logits = outputs.logits
16
+ predicted_class_prob = F.softmax(logits, dim=-1).detach().cpu().numpy().max()
17
+ predicted_class_idx = logits.argmax(-1).item()
18
+ label = model.config.id2label[predicted_class_idx].split(",")[0]
19
+ time.sleep(2)
20
+ return {label: float(predicted_class_prob)}
21
+
22
+ import gradio as gr
23
+
24
+ gr.Interface(predict, gr.Image(type="pil"), "label").queue(concurrency_count=1).launch()