zhouyik commited on
Commit
99b1fec
ยท
verified ยท
1 Parent(s): 33492cf

Upload ./app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +292 -0
app.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://huggingface.co/spaces/PolyU-ChenLab/UniPixel/blob/main/app.py
2
+
3
+ import random
4
+ import re
5
+ import colorsys
6
+ from PIL import Image
7
+ import matplotlib as mpl
8
+ import numpy as np
9
+ import uuid
10
+ import imageio.v3 as iio
11
+
12
+ import torch
13
+ from torchvision.transforms.functional import to_pil_image
14
+
15
+ import spaces
16
+ import gradio as gr
17
+
18
+ from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
19
+ from .sam2 import VQ_SAM2, VQ_SAM2Config, SAM2Config
20
+ from .visualizer import sample_color, draw_mask
21
+
22
+ class DirectResize:
23
+ def __init__(self, target_length: int) -> None:
24
+ self.target_length = target_length
25
+
26
+ def apply_image(self, image: np.ndarray) -> np.ndarray:
27
+ """
28
+ Expects a numpy array with shape HxWxC in uint8 format.
29
+ """
30
+ img = to_pil_image(image, mode='RGB')
31
+ return np.array(img.resize((self.target_length, self.target_length)))
32
+
33
+ def extract_mt_token_ids_v1(text):
34
+ pattern = r"<\|mt_(\d{4})\|>"
35
+ return [int(x) for x in re.findall(pattern, text)]
36
+
37
+ def extract_mt_token_ids_v2(text):
38
+ pattern = re.compile(r'<\|mt_start\|><\|mt_(\d{4})\|><\|mt_(\d{4})\|><\|mt_end\|>')
39
+ matches = pattern.findall(text)
40
+ ret_list = []
41
+ for num1, num2 in matches:
42
+ ret_list.append(int(num1))
43
+ ret_list.append(int(num2))
44
+ return ret_list
45
+
46
+ def find_first_index(arr, value):
47
+ indices = np.where(arr == value)[0]
48
+
49
+ return indices[0] if len(indices) > 0 else -1
50
+
51
+ def fix_mt_format_comprehensive(text):
52
+ pattern_too_many = r'(<\|mt_start\|>)(<\|mt_\d+\|>)(<\|mt_\d+\|>)(?:<\|mt_\d+\|>)+<\|mt_end\|>'
53
+ replacement_too_many = r'\1\2\3<|mt_end|>'
54
+ text = re.sub(pattern_too_many, replacement_too_many, text)
55
+
56
+ pattern_too_few_with_end = r'(<\|mt_start\|>)(<\|mt_\d+\|>)(<\|mt_end\|>)'
57
+ replacement_too_few = r'\1\2<|mt_9999|><|mt_end|>'
58
+ text = re.sub(pattern_too_few_with_end, replacement_too_few, text)
59
+
60
+ pattern_too_few_no_end = r'(<\|mt_start\|>)(<\|mt_\d+\|>)(?!<\|mt_)'
61
+ replacement_too_few_no_end = r'\1\2<|mt_9999|><|mt_end|>'
62
+ text = re.sub(pattern_too_few_no_end, replacement_too_few_no_end, text)
63
+ return text
64
+
65
+
66
+ MODEL = 'zhouyik/Qwen3-VL-8B-SAMTok'
67
+
68
+ TITLE = 'SAMTok: Representing Any Mask with Two Words'
69
+
70
+ HEADER = """
71
+ <p align="center" style="margin: 1em 0 2em;"><img width="260" src="https://github.com/bytedance/Sa2VA/blob/main/projects/samtok/figs/logo.png"></p>
72
+ <h3 align="center">SAMTok: Representing Any Mask with Two Words</h3>
73
+ <div style="display: flex; justify-content: center; gap: 5px;">
74
+ <a href="https://github.com/bytedance/Sa2VA/tree/main/projects/samtok" target="_blank"><img src="https://img.shields.io/badge/arXiv-2509.18094-red"></a>
75
+ <a href="https://github.com/bytedance/Sa2VA/tree/main/projects/samtok" target="_blank"><img src="https://img.shields.io/badge/Project-Page-brightgreen"></a>
76
+ <a href="https://huggingface.co/collections/zhouyik/samtok" target="_blank"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model-blue"></a>
77
+ <a href="https://github.com/bytedance/Sa2VA" target="_blank"><img src="https://img.shields.io/github/stars/bytedance/Sa2VA"></a>
78
+ </div>
79
+ <p style="margin-top: 1em;">SAMTok provides a unified mask-token interface for MLLMs. (1) SAMTok compresses region masks into two discrete tokens and faithfully reconstructs them across diverse visual domains. (2) Injecting these mask tokens into MLLMs enables a wide range of region-level mask generation and understanding tasks. (3) The text-based representation of region masks allows a purely textual answer-matching reward for the GRPO of the mask generation task.</p>
80
+ """
81
+
82
+ JS = """
83
+ function init() {
84
+ if (window.innerWidth >= 1536) {
85
+ document.querySelector('main').style.maxWidth = '1536px'
86
+ }
87
+ document.getElementById('query_1').addEventListener('keydown', function f1(e) { if (e.key === 'Enter') { document.getElementById('submit_1').click() } })
88
+ document.getElementById('query_2').addEventListener('keydown', function f2(e) { if (e.key === 'Enter') { document.getElementById('submit_2').click() } })
89
+ document.getElementById('query_3').addEventListener('keydown', function f3(e) { if (e.key === 'Enter') { document.getElementById('submit_3').click() } })
90
+ document.getElementById('query_4').addEventListener('keydown', function f4(e) { if (e.key === 'Enter') { document.getElementById('submit_4').click() } })
91
+ }
92
+ """
93
+
94
+ device = torch.device('cuda')
95
+
96
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
97
+ MODEL, torch_dtype="auto"
98
+ ).cuda().eval()
99
+
100
+ processor = AutoProcessor.from_pretrained(MODEL)
101
+
102
+ # build vq-sam2 model
103
+ CODEBOOK_SIZE = 256
104
+ CODEBOOK_DEPTH = 2
105
+ sam2_config = SAM2Config(
106
+ ckpt_path=MODEL+"/sam2.1_hiera_large.pt",
107
+ )
108
+ vq_sam2_config = VQ_SAM2Config(
109
+ sam2_config=sam2_config,
110
+ codebook_size=CODEBOOK_SIZE,
111
+ codebook_depth=CODEBOOK_DEPTH,
112
+ shared_codebook=False,
113
+ latent_dim=256,
114
+ )
115
+ vq_sam2 = VQ_SAM2(vq_sam2_config).cuda().eval()
116
+ state = torch.load(MODEL+"/mask_tokenizer_256x2.pth", map_location="cpu")
117
+ vq_sam2.load_state_dict(state)
118
+ sam2_image_processor = DirectResize(1024)
119
+
120
+
121
+ colors = sample_color()
122
+ color_map = {f'Target {i + 1}': f'#{int(c[0]):02x}{int(c[1]):02x}{int(c[2]):02x}' for i, c in enumerate(colors * 255)}
123
+ color_map_light = {
124
+ f'Target {i + 1}': f'#{int(c[0] * 127.5 + 127.5):02x}{int(c[1] * 127.5 + 127.5):02x}{int(c[2] * 127.5 + 127.5):02x}'
125
+ for i, c in enumerate(colors)
126
+ }
127
+
128
+ def enable_btns():
129
+ return (gr.Button(interactive=True), ) * 4
130
+
131
+
132
+ def disable_btns():
133
+ return (gr.Button(interactive=False), ) * 4
134
+
135
+
136
+ def reset_seg():
137
+ return 16, gr.Button(interactive=False)
138
+
139
+
140
+ def reset_reg():
141
+ return 1, gr.Button(interactive=False)
142
+
143
+ @spaces.GPU
144
+ def infer_seg(media, query):
145
+ global model
146
+
147
+ if not media:
148
+ gr.Warning('Please upload an image')
149
+ return None, None, None
150
+
151
+ if not query:
152
+ gr.Warning('Please provide a text prompt.')
153
+ return None, None, None
154
+
155
+ image = Image.open(path).convert('RGB')
156
+ ori_width, ori_height = image.size
157
+ messages = [
158
+ {
159
+ "role": "user",
160
+ "content": [
161
+ {
162
+ "type": "image",
163
+ "image": media,
164
+ },
165
+ {"type": "text", "text": query},
166
+ ],
167
+ }
168
+ ]
169
+ inputs = processor.apply_chat_template(
170
+ messages,
171
+ tokenize=True,
172
+ add_generation_prompt=True,
173
+ return_dict=True,
174
+ return_tensors="pt"
175
+ )
176
+
177
+ model = model.to(device)
178
+
179
+ inputs = inputs.to(model.device)
180
+
181
+ generated_ids = model.generate(
182
+ **inputs,
183
+ max_new_tokens=1024,
184
+ do_sample=False,
185
+ top_p=1.0,
186
+ )
187
+ generated_ids_trimmed = [
188
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
189
+ ]
190
+ output_text = processor.batch_decode(
191
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
192
+ )[0]
193
+
194
+ quant_ids = extract_mt_token_ids_v1(output_text)
195
+ if len(quant_ids) % CODEBOOK_DEPTH != 0:
196
+ output_text = fix_mt_format_comprehensive(output_text)
197
+ quant_ids = extract_mt_token_ids_v2(output_text)
198
+
199
+ batch_size = len(quant_ids) // CODEBOOK_DEPTH
200
+ remap_quant_ids = []
201
+ tags = []
202
+ for bs_id in range(batch_size):
203
+ chunk_quant_ids = quant_ids[bs_id*CODEBOOK_DEPTH:(bs_id+1)*CODEBOOK_DEPTH]
204
+ tags.append(f'<|mt_start|><|mt_{str(chunk_quant_ids[0]).zfill(4)}|><|mt_{str(chunk_quant_ids[1]).zfill(4)}|><|mt_end|>')
205
+ remap_chunk_quant_ids = [quant_id - book_id*CODEBOOK_SIZE for book_id, quant_id in enumerate(chunk_quant_ids)]
206
+ code1 = remap_chunk_quant_ids[0]
207
+ code2 = remap_chunk_quant_ids[1]
208
+ if not (code2 >= 0 and code2 < CODEBOOK_SIZE):
209
+ code2 = -1
210
+ remap_chunk_quant_ids_error_handle = [code1, code2]
211
+ remap_quant_ids.append(remap_chunk_quant_ids_error_handle)
212
+
213
+ batch_size = len(remap_quant_ids)
214
+ sam2_image = np.array(image)
215
+ sam2_image = sam2_image_processor.apply_image(sam2_image)
216
+ sam2_pixel_values = torch.from_numpy(sam2_image).permute(2, 0, 1).contiguous()
217
+ sam2_pixel_values = sam2_pixel_values.unsqueeze(0).to(vq_sam2.dtype).to(vq_sam2.device)
218
+ sam2_pixel_values = sam2_pixel_values.repeat(batch_size, 1, 1, 1)
219
+
220
+ quant_ids = torch.LongTensor(remap_quant_ids).to(vq_sam2.device)
221
+
222
+ with torch.no_grad():
223
+ _pred_masks = vq_sam2.forward_with_codes(sam2_pixel_values, quant_ids)
224
+ _pred_masks = torch.nn.functional.interpolate(_pred_masks, size=(ori_height, ori_width), mode='bilinear')
225
+ _pred_masks = _pred_masks > 0.5
226
+ # _pred_masks = _pred_masks[:, 0, :, :].cpu().numpy().astype(np.uint8)
227
+ _pred_masks = _pred_masks.long().unsqueeze(2).cpu() # n, 1, 1, h, w
228
+
229
+ entities = []
230
+ unique_tags = list(set(tags))
231
+ entity_names = []
232
+ for i, tag in enumerate(unique_tags):
233
+ for m in re.finditer(re.escape(tag), output_text):
234
+ entities.append(dict(entity=f'Target {i + 1}', start=m.start(), end=m.end()))
235
+ entity_names.append(f'Target {i + 1}')
236
+
237
+ answer = dict(text=output_text, entities=entities)
238
+
239
+ frames = torch.from_numpy(np.array(image)).unsqueeze(0)
240
+ imgs = draw_mask(frames, _pred_masks, colors=colors)
241
+
242
+ path = f"/tmp/{uuid.uuid4().hex}.png"
243
+ iio.imwrite(path, imgs, duration=100, loop=0)
244
+
245
+ masks = media, [(m[0, 0].numpy(), entity_names[i]) for i, m in enumerate(_pred_masks)]
246
+
247
+ return answer, masks, path
248
+
249
+
250
+ def build_demo():
251
+ with gr.Blocks(title=TITLE, js=JS, theme=gr.themes.Soft()) as demo:
252
+ gr.HTML(HEADER)
253
+
254
+ # with gr.Tab('Mask Generation'):
255
+ download_btn_1 = gr.DownloadButton(label='๐Ÿ“ฆ Download', interactive=False, render=False)
256
+ msk_1 = gr.AnnotatedImage(label='De-tokenized 2D masks', color_map=color_map, render=False)
257
+ ans_1 = gr.HighlightedText(
258
+ label='Model Response', color_map=color_map_light, show_inline_category=False, render=False)
259
+ with gr.Row():
260
+ with gr.Column():
261
+ media_1 = gr.Image(type='filepath')
262
+
263
+ sample_frames_1 = gr.Slider(1, 32, value=16, step=1, visible=False)
264
+
265
+ query_1 = gr.Textbox(label='Text Prompt', placeholder='Please segment the...', elem_id='query_1')
266
+
267
+ with gr.Row():
268
+ random_btn_1 = gr.Button(value='๐Ÿ”ฎ Random', visible=False)
269
+
270
+ reset_btn_1 = gr.ClearButton([media_1, query_1, msk_1, ans_1], value='๐Ÿ—‘๏ธ Reset')
271
+ reset_btn_1.click(reset_seg, None, [sample_frames_1, download_btn_1])
272
+
273
+ download_btn_1.render()
274
+
275
+ submit_btn_1 = gr.Button(value='๐Ÿš€ Submit', variant='primary', elem_id='submit_1')
276
+
277
+ with gr.Column():
278
+ msk_1.render()
279
+ ans_1.render()
280
+
281
+ ctx_1 = submit_btn_1.click(disable_btns, None, [random_btn_1, reset_btn_1, download_btn_1, submit_btn_1])
282
+ ctx_1 = ctx_1.then(infer_seg, [media_1, query_1], [ans_1, msk_1, download_btn_1])
283
+ ctx_1.then(enable_btns, None, [random_btn_1, reset_btn_1, download_btn_1, submit_btn_1])
284
+ # with gr.Tab('Mask Understanding'):
285
+ # pass
286
+
287
+
288
+ if __name__ == '__main__':
289
+ demo = build_demo()
290
+
291
+ demo.queue()
292
+ demo.launch(server_name='0.0.0.0')