File size: 2,668 Bytes
377e8b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
"""Classify images with NoTokenLM-ImageGen-Class-2.5.

  python inference.py cat.jpg dog.png https://example.com/x.jpg
  python inference.py photo.jpg --res 64 --topk 10
  python inference.py photo.jpg --model ./local_dir_with_weights --device cpu --json

Images are prepared exactly like the training data (centre square crop -> Lanczos 256 -> 128 -> --res).
"""
import argparse, io, json, os, sys, urllib.request

import torch
from PIL import Image
from transformers import AutoModelForImageClassification

DEFAULT_REPO = "VeroLM/NoTokenLM-ImageGen-Class-2.5"


def load_image(src):
    if src.startswith(("http://", "https://")):
        req = urllib.request.Request(src, headers={"User-Agent": "ntlm-class25/1.0"})
        with urllib.request.urlopen(req, timeout=30) as r:
            return Image.open(io.BytesIO(r.read())).convert("RGB")
    return Image.open(src).convert("RGB")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("images", nargs="+", help="image file paths or http(s) URLs")
    ap.add_argument("--model", default=DEFAULT_REPO, help="Hub repo id or local folder (default: %(default)s)")
    ap.add_argument("--res", type=int, default=128, help="input resolution, multiple of 16 (trained at 64 and 128)")
    ap.add_argument("--topk", type=int, default=5)
    ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    ap.add_argument("--dtype", choices=["float32", "bfloat16"], default="float32",
                    help="float32 matches the reference exactly; bfloat16 matches the training numerics")
    ap.add_argument("--token", default=os.environ.get("HF_TOKEN"), help="HF token (needed only for private repos)")
    ap.add_argument("--json", action="store_true", help="print machine-readable JSON")
    a = ap.parse_args()

    model = AutoModelForImageClassification.from_pretrained(
        a.model, trust_remote_code=True, token=a.token, dtype=getattr(torch, a.dtype)).to(a.device).eval()
    imgs = []
    for s in a.images:
        try:
            imgs.append(load_image(s))
        except Exception as e:
            sys.exit(f"cannot read '{s}': {e}")
    results = model.predict(imgs, top_k=a.topk, resolution=a.res)

    if a.json:
        print(json.dumps({s: r for s, r in zip(a.images, results)}, indent=2, ensure_ascii=False))
        return
    for s, r in zip(a.images, results):
        print(f"\n{s}")
        for rank, p in enumerate(r, 1):
            print(f"  {rank}. {p['label']:<35} {p['score'] * 100:6.2f}%   (class {p['id']})")


if __name__ == "__main__":
    main()