somepago commited on
Commit
9614331
·
verified ·
1 Parent(s): dbaa597

Upload predict.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. predict.py +157 -0
predict.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Aesthetic scoring — simple inference interface.
3
+
4
+ Usage:
5
+ from predict import AestheticScorer
6
+
7
+ scorer = AestheticScorer.from_pretrained("somepago/aes26")
8
+ score = scorer.rate("photo.jpg") # float 1-10
9
+ scores = scorer.rate(["a.jpg", "b.jpg"]) # list of floats
10
+
11
+ Or with a local checkpoint:
12
+ scorer = AestheticScorer.from_local("checkpoints/.../best.pt")
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from PIL import Image
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Allow running from repo root or after `pip install` via HF snapshot
27
+ # ---------------------------------------------------------------------------
28
+ _HERE = Path(__file__).parent
29
+ if str(_HERE) not in sys.path:
30
+ sys.path.insert(0, str(_HERE))
31
+
32
+ from naflex import preprocess_image, naflex_collate
33
+ from model import AestheticModel
34
+
35
+
36
+ class AestheticScorer:
37
+ """Scores images on a 1-10 aesthetic scale."""
38
+
39
+ def __init__(self, model: AestheticModel, device: torch.device):
40
+ self.model = model
41
+ self.device = device
42
+
43
+ # ------------------------------------------------------------------
44
+ # Constructors
45
+ # ------------------------------------------------------------------
46
+
47
+ @classmethod
48
+ def from_pretrained(
49
+ cls,
50
+ repo_id: str = "somepago/aes26",
51
+ filename: str = "best.pt",
52
+ device: str | None = None,
53
+ ) -> "AestheticScorer":
54
+ """Download weights from Hugging Face Hub and load model."""
55
+ from huggingface_hub import hf_hub_download
56
+
57
+ ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
58
+ return cls.from_local(ckpt_path, device=device)
59
+
60
+ @classmethod
61
+ def from_local(
62
+ cls,
63
+ ckpt_path: str,
64
+ device: str | None = None,
65
+ ) -> "AestheticScorer":
66
+ """Load model from a local checkpoint path."""
67
+ if device is None:
68
+ device = "cuda" if torch.cuda.is_available() else "cpu"
69
+ dev = torch.device(device)
70
+
71
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
72
+ config = ckpt["config"]
73
+
74
+ # Support checkpoints that saved EMA weights under ema_state_dict
75
+ state_key = "ema_state_dict" if "ema_state_dict" in ckpt else "model_state_dict"
76
+
77
+ model = AestheticModel(config)
78
+ model.load_state_dict(ckpt[state_key])
79
+ model.eval().to(dev)
80
+
81
+ return cls(model, dev)
82
+
83
+ # ------------------------------------------------------------------
84
+ # Inference
85
+ # ------------------------------------------------------------------
86
+
87
+ @torch.inference_mode()
88
+ def rate(
89
+ self,
90
+ images: Union[str, Path, Image.Image, list],
91
+ batch_size: int = 32,
92
+ ) -> Union[float, list[float]]:
93
+ """Score one or more images.
94
+
95
+ Parameters
96
+ ----------
97
+ images : path, PIL Image, or list of either
98
+ batch_size : how many images to process at once
99
+
100
+ Returns
101
+ -------
102
+ float if a single image was passed, list[float] for a list
103
+ """
104
+ single = not isinstance(images, list)
105
+ if single:
106
+ images = [images]
107
+
108
+ scores: list[float] = []
109
+ for i in range(0, len(images), batch_size):
110
+ batch_imgs = images[i : i + batch_size]
111
+ items = []
112
+ for img in batch_imgs:
113
+ if not isinstance(img, Image.Image):
114
+ img = Image.open(img).convert("RGB")
115
+ else:
116
+ img = img.convert("RGB")
117
+ patches, grid = preprocess_image(img)
118
+ items.append({"patches": patches, "grid": grid, "score": 0.0})
119
+
120
+ collated = naflex_collate(items)
121
+ with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
122
+ logits = self.model(
123
+ collated["patches"].to(self.device),
124
+ collated["spatial_shapes"].to(self.device),
125
+ collated["attention_mask"].to(self.device),
126
+ )
127
+ batch_scores = self.model.logits_to_score(logits).cpu().tolist()
128
+ if isinstance(batch_scores, float):
129
+ batch_scores = [batch_scores]
130
+ scores.extend(batch_scores)
131
+
132
+ return round(scores[0], 2) if single else [round(s, 2) for s in scores]
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # CLI: python predict.py image1.jpg image2.jpg ...
137
+ # ---------------------------------------------------------------------------
138
+ if __name__ == "__main__":
139
+ import argparse
140
+
141
+ parser = argparse.ArgumentParser(description="Score images aesthetically (1-10)")
142
+ parser.add_argument("images", nargs="+", help="Image paths to score")
143
+ parser.add_argument("--repo", default="somepago/aes26", help="HF repo or local checkpoint")
144
+ parser.add_argument("--device", default=None, help="cuda / cpu")
145
+ args = parser.parse_args()
146
+
147
+ if Path(args.repo).exists():
148
+ scorer = AestheticScorer.from_local(args.repo, device=args.device)
149
+ else:
150
+ scorer = AestheticScorer.from_pretrained(args.repo, device=args.device)
151
+
152
+ scores = scorer.rate(args.images)
153
+ if not isinstance(scores, list):
154
+ scores = [scores]
155
+
156
+ for path, score in zip(args.images, scores):
157
+ print(f"{score:.2f} {path}")