MamaPearl commited on
Commit
095c1e2
·
verified ·
1 Parent(s): c4047a9

Create infer.py

Browse files
Files changed (1) hide show
  1. infer.py +49 -0
infer.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms as T
3
+ from PIL import Image
4
+ from transformers import AutoModelForImageClassification
5
+ import requests
6
+ from io import BytesIO
7
+
8
+ MEAN = [0.5, 0.5, 0.5]
9
+ STD = [0.5, 0.5, 0.5]
10
+
11
+ transform = T.Compose([
12
+ T.Resize((32, 32), interpolation=T.InterpolationMode.BICUBIC),
13
+ T.ToTensor(),
14
+ T.Normalize(mean=MEAN, std=STD)
15
+ ])
16
+
17
+ def load_image(source: str) -> Image.Image:
18
+ if source.startswith("http://") or source.startswith("https://"):
19
+ response = requests.get(source)
20
+ return Image.open(BytesIO(response.content)).convert("RGB")
21
+ return Image.open(source).convert("RGB")
22
+
23
+ def predict(model, image_source: str, device: str = "cpu") -> dict:
24
+ image = load_image(image_source)
25
+ x = transform(image).unsqueeze(0).to(device)
26
+ with torch.no_grad():
27
+ logits = model(pixel_values=x).logits
28
+ probs = torch.softmax(logits, dim=-1)[0]
29
+ top5 = probs.topk(5)
30
+ return {
31
+ model.config.id2label[i.item()]: f"{p.item()*100:.2f}%"
32
+ for i, p in zip(top5.indices, top5.values)
33
+ }
34
+
35
+ if __name__ == "__main__":
36
+ import sys
37
+ source = sys.argv[1] if len(sys.argv) > 1 else "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg" # an ant for fallback!
38
+
39
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
40
+
41
+ model = AutoModelForImageClassification.from_pretrained(
42
+ "MamaPearl/nula-cifar10-robust-v0",
43
+ trust_remote_code=True
44
+ ).to(DEVICE)
45
+ model.eval()
46
+
47
+ results = predict(model, source, device=DEVICE)
48
+ for label, prob in results.items():
49
+ print(f"{label:15} {prob}")