insomnia7 commited on
Commit
0d552d6
·
verified ·
1 Parent(s): 800c8e2

Upload ./app.py with huggingface_hub

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