Image Classification
timm
drhead commited on
Commit
0e7389a
·
verified ·
1 Parent(s): 7dcbd8e

create per-model inference scripts

Browse files
Files changed (1) hide show
  1. JTP_PILOT/inference_gradio.py +194 -0
JTP_PILOT/inference_gradio.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import safetensors.torch
6
+ import timm
7
+ from timm.models import VisionTransformer
8
+ import torch
9
+ from torchvision.transforms import transforms
10
+ from torchvision.transforms import InterpolationMode
11
+ import torchvision.transforms.functional as TF
12
+
13
+ torch.set_grad_enabled(False)
14
+
15
+ class Fit(torch.nn.Module):
16
+ def __init__(
17
+ self,
18
+ bounds: tuple[int, int] | int,
19
+ interpolation = InterpolationMode.LANCZOS,
20
+ grow: bool = True,
21
+ pad: float | None = None
22
+ ):
23
+ super().__init__()
24
+
25
+ self.bounds = (bounds, bounds) if isinstance(bounds, int) else bounds
26
+ self.interpolation = interpolation
27
+ self.grow = grow
28
+ self.pad = pad
29
+
30
+ def forward(self, img: Image) -> Image:
31
+ wimg, himg = img.size
32
+ hbound, wbound = self.bounds
33
+
34
+ hscale = hbound / himg
35
+ wscale = wbound / wimg
36
+
37
+ if not self.grow:
38
+ hscale = min(hscale, 1.0)
39
+ wscale = min(wscale, 1.0)
40
+
41
+ scale = min(hscale, wscale)
42
+ if scale == 1.0:
43
+ return img
44
+
45
+ hnew = min(round(himg * scale), hbound)
46
+ wnew = min(round(wimg * scale), wbound)
47
+
48
+ img = TF.resize(img, (hnew, wnew), self.interpolation)
49
+
50
+ if self.pad is None:
51
+ return img
52
+
53
+ hpad = hbound - hnew
54
+ wpad = wbound - wnew
55
+
56
+ tpad = hpad // 2
57
+ bpad = hpad - tpad
58
+
59
+ lpad = wpad // 2
60
+ rpad = wpad - lpad
61
+
62
+ return TF.pad(img, (lpad, tpad, rpad, bpad), self.pad)
63
+
64
+ def __repr__(self) -> str:
65
+ return (
66
+ f"{self.__class__.__name__}(" +
67
+ f"bounds={self.bounds}, " +
68
+ f"interpolation={self.interpolation.value}, " +
69
+ f"grow={self.grow}, " +
70
+ f"pad={self.pad})"
71
+ )
72
+
73
+ class CompositeAlpha(torch.nn.Module):
74
+ def __init__(
75
+ self,
76
+ background: tuple[float, float, float] | float,
77
+ ):
78
+ super().__init__()
79
+
80
+ self.background = (background, background, background) if isinstance(background, float) else background
81
+ self.background = torch.tensor(self.background).unsqueeze(1).unsqueeze(2)
82
+
83
+ def forward(self, img: torch.Tensor) -> torch.Tensor:
84
+ if img.shape[-3] == 3:
85
+ return img
86
+
87
+ alpha = img[..., 3, None, :, :]
88
+
89
+ img[..., :3, :, :] *= alpha
90
+
91
+ background = self.background.expand(-1, img.shape[-2], img.shape[-1])
92
+ if background.ndim == 1:
93
+ background = background[:, None, None]
94
+ elif background.ndim == 2:
95
+ background = background[None, :, :]
96
+
97
+ img[..., :3, :, :] += (1.0 - alpha) * background
98
+ return img[..., :3, :, :]
99
+
100
+ def __repr__(self) -> str:
101
+ return (
102
+ f"{self.__class__.__name__}(" +
103
+ f"background={self.background})"
104
+ )
105
+
106
+ transform = transforms.Compose([
107
+ Fit((384, 384)),
108
+ transforms.ToTensor(),
109
+ CompositeAlpha(0.5),
110
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
111
+ transforms.CenterCrop((384, 384)),
112
+ ])
113
+
114
+ model = timm.create_model(
115
+ "vit_so400m_patch14_siglip_384.webli",
116
+ pretrained=False,
117
+ num_classes=9083,
118
+ ) # type: VisionTransformer
119
+
120
+ safetensors.torch.load_model(model, "JTP_PILOT-e4-vit_so400m_patch14_siglip_384.safetensors")
121
+
122
+ if torch.cuda.is_available():
123
+ model.cuda()
124
+ if torch.cuda.get_device_capability()[0] >= 7: # tensor cores
125
+ model.to(dtype=torch.float16, memory_format=torch.channels_last)
126
+
127
+ model.eval()
128
+
129
+ with open("tagger_tags.json", "r") as file:
130
+ tags = json.load(file) # type: dict
131
+ allowed_tags = list(tags.keys())
132
+
133
+ for idx, tag in enumerate(allowed_tags):
134
+ allowed_tags[idx] = tag.replace("_", " ")
135
+
136
+ sorted_tag_score = {}
137
+
138
+ def run_classifier(image, threshold):
139
+ global sorted_tag_score
140
+ img = image.convert('RGB')
141
+ tensor = transform(img).unsqueeze(0)
142
+
143
+ if torch.cuda.is_available():
144
+ tensor = tensor.cuda()
145
+ if torch.cuda.get_device_capability()[0] >= 7: # tensor cores
146
+ tensor = tensor.to(dtype=torch.float16, memory_format=torch.channels_last)
147
+
148
+ with torch.no_grad():
149
+ logits = model(tensor)
150
+ probits = torch.nn.functional.sigmoid(logits[0]).cpu()
151
+ values, indices = probits.topk(250)
152
+
153
+ tag_score = dict()
154
+ for i in range(indices.size(0)):
155
+ tag_score[allowed_tags[indices[i]]] = values[i].item()
156
+ sorted_tag_score = dict(sorted(tag_score.items(), key=lambda item: item[1], reverse=True))
157
+
158
+ return create_tags(threshold)
159
+
160
+ def create_tags(threshold):
161
+ global sorted_tag_score
162
+ filtered_tag_score = {key: value for key, value in sorted_tag_score.items() if value > threshold}
163
+ text_no_impl = ", ".join(filtered_tag_score.keys())
164
+ return text_no_impl, filtered_tag_score
165
+
166
+
167
+ with gr.Blocks(css=".output-class { display: none; }") as demo:
168
+ gr.Markdown("""
169
+ ## Joint Tagger Project: PILOT Demo
170
+ This tagger is designed for use on furry images (though may very well work on out-of-distribution images, potentially with funny results). A threshold of 0.2 is recommended. Lower thresholds often turn up more valid tags, but can also result in some amount of hallucinated tags.
171
+ This tagger is the result of joint efforts between members of the RedRocket team. Special thanks to Minotoro at frosting.ai for providing the compute power for this project.
172
+ """)
173
+ with gr.Row():
174
+ with gr.Column():
175
+ image_input = gr.Image(label="Source", sources=['upload'], type='pil', height=512, show_label=False)
176
+ threshold_slider = gr.Slider(minimum=0.00, maximum=1.00, step=0.01, value=0.20, label="Threshold")
177
+ with gr.Column():
178
+ tag_string = gr.Textbox(label="Tag String")
179
+ label_box = gr.Label(label="Tag Predictions", num_top_classes=250, show_label=False)
180
+
181
+ image_input.upload(
182
+ fn=run_classifier,
183
+ inputs=[image_input, threshold_slider],
184
+ outputs=[tag_string, label_box]
185
+ )
186
+
187
+ threshold_slider.input(
188
+ fn=create_tags,
189
+ inputs=[threshold_slider],
190
+ outputs=[tag_string, label_box]
191
+ )
192
+
193
+ if __name__ == "__main__":
194
+ demo.launch()