liangtm commited on
Commit
5a13ec5
·
verified ·
1 Parent(s): a67632f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -101
app.py CHANGED
@@ -1,39 +1,35 @@
1
  import gradio as gr
 
 
 
 
 
 
 
2
  import torchvision.transforms as T
3
  from models import build_model
4
- import os
5
  import torch
6
  import misc as utils
7
  import numpy as np
8
  import torch.nn.functional as F
9
- import matplotlib.colors
10
  from torchvision.io import read_video
11
  import torchvision.transforms.functional as Func
12
  from ruamel.yaml import YAML
13
  from easydict import EasyDict
14
  from misc import nested_tensor_from_videos_list
15
  from torch.cuda.amp import autocast
16
- from PIL import Image, ImageDraw, ImageFont
17
- from rich.progress import track
18
  import imageio.v3 as iio
19
- import imageio
20
  import cv2
21
- import warnings
22
  import tempfile
23
  import argparse
24
  import time
25
  from huggingface_hub import hf_hub_download
26
 
27
- warnings.filterwarnings("ignore")
28
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
29
 
30
- # TARGET_FPS = 10
31
-
32
- so_path = "models/GroundingDINO/ops/MultiScaleDeformableAttention.cpython-39-x86_64-linux-gnu.so"
33
- if not os.path.exists(so_path):
34
- # print("Building MultiScaleDeformableAttention module...")
35
- # subprocess.run(["python", "setup.py", "build_ext", "--inplace"], cwd="models/GroundingDINO/ops", check=True)
36
- os.system("python models/GroundingDINO/ops/setup.py build_ext develop --user")
37
 
38
  # Transform for video frames
39
  transform = T.Compose([
@@ -50,7 +46,7 @@ color_list = color_list.astype('uint8').tolist()
50
  model = None
51
 
52
 
53
- def load_model_once(config_path, checkpoint_path, device='cpu'):
54
  """Load model once at startup"""
55
  global model
56
  if model is None:
@@ -62,19 +58,12 @@ def load_model_once(config_path, checkpoint_path, device='cpu'):
62
 
63
  args = EasyDict(config)
64
  args.device = device
65
- args.checkpoint_path = checkpoint_path
66
 
67
  model = build_model(args)
68
  model.to(device)
69
-
70
- ckpt_path = hf_hub_download(
71
- repo_id="Birdy80/888",
72
- filename="ckpt/ryb_mevis_swinb.pth",
73
- token=os.environ.get("HUGGINGFACE_HUB_TOKEN"),
74
- repo_type="model"
75
- )
76
-
77
- checkpoint = torch.load(ckpt_path, map_location='cpu')
78
  state_dict = checkpoint["model_state_dict"]
79
  model.load_state_dict(state_dict, strict=False)
80
  model.eval()
@@ -118,13 +107,12 @@ def vis_add_mask(img, mask, color, edge_width=3):
118
  return origin_img
119
 
120
 
121
- def run_video_inference(input_video, text_prompt, tracking_alpha=0.1, target_fps=10):
122
  """Main inference function for Gradio"""
123
  global model
124
  model.tracking_alpha = tracking_alpha
125
 
126
  # Set default values for other parameters
127
- frame_step = 1
128
  show_box = True
129
  mask_edge_width = 6
130
 
@@ -137,17 +125,16 @@ def run_video_inference(input_video, text_prompt, tracking_alpha=0.1, target_fps
137
  # Process text prompt
138
  exp = " ".join(text_prompt.lower().split())
139
 
140
- # Read video (≤8s on CPU)
141
- video_frames, _, info = read_video(input_video, end_pts=8, pts_unit='sec') # (T, H, W, C)
142
- original_fps = info['video_fps']
143
- frame_interval = max(round(original_fps / target_fps), 1)
144
 
145
  frames = []
146
- for i in range(0, len(video_frames), frame_interval):
147
  source_frame = Func.to_pil_image(video_frames[i].permute(2, 0, 1))
148
  frames.append(source_frame)
149
 
150
- info['video_fps'] = target_fps
151
  video_len = len(frames)
152
  if video_len == 0:
153
  return None, "No frames found in the video."
@@ -161,92 +148,60 @@ def run_video_inference(input_video, text_prompt, tracking_alpha=0.1, target_fps
161
 
162
  device = next(model.parameters()).device
163
  imgs = torch.stack(imgs, dim=0).to(device)
164
- samples = nested_tensor_from_videos_list(imgs[None], size_divisibility=1)
165
  img_h, img_w = imgs.shape[-2:]
166
  size = torch.as_tensor([int(img_h), int(img_w)]).to(device)
167
  target = {"size": size}
168
 
169
  start_infer = time.time()
 
170
  with torch.no_grad():
171
  with autocast(True):
172
  outputs = model(samples, [exp], [target])
173
  end_infer = time.time()
174
 
175
  pred_logits = outputs["pred_logits"][0] # [t, q, k]
176
- pred_masks = outputs["pred_masks"][0] # [t, q, h, w]
177
- pred_boxes = outputs["pred_boxes"][0] # [t, q, 4]
178
 
179
  # Select the query index according to pred_logits
180
- pred_scores = pred_logits.sigmoid() # [t, q, k]
181
- pred_scores = pred_scores.mean(0) # [q, K]
182
- max_scores, _ = pred_scores.max(-1) # [q,]
183
- _, max_ind = max_scores.max(-1) # [1,]
184
  max_inds = max_ind.repeat(video_len)
185
  pred_masks = pred_masks[range(video_len), max_inds, ...] # [t, h, w]
186
  pred_masks = pred_masks.unsqueeze(0)
187
  pred_boxes = pred_boxes[range(video_len), max_inds].cpu().numpy() # [t, 4]
188
 
189
- # Unpad and resize masks to original frame size
190
  pred_masks = pred_masks[:, :, :img_h, :img_w].cpu()
191
  pred_masks = F.interpolate(pred_masks, size=(origin_h, origin_w), mode='bilinear', align_corners=False)
192
  pred_masks = (pred_masks.sigmoid() > 0.5).squeeze(0).cpu().numpy()
193
 
194
- # Visualization color
195
- color = "#DC143C"
196
- color = (np.array(matplotlib.colors.hex2color(color)) * 255).astype('uint8')
197
 
198
- # ---- Save result video (with per-frame sanitization) ----
199
  start_save = time.time()
200
  save_imgs = []
201
- for t, pil_img in enumerate(frames):
202
- # draw mask
203
- pil_img = vis_add_mask(pil_img, pred_masks[t], color, mask_edge_width)
204
 
205
- # draw bbox
206
- draw = ImageDraw.Draw(pil_img)
207
  draw_boxes = pred_boxes[t][None]
208
  draw_boxes = rescale_bboxes(draw_boxes, (origin_w, origin_h)).tolist()
 
 
209
  if show_box:
210
  xmin, ymin, xmax, ymax = draw_boxes[0]
211
  draw.rectangle(((xmin, ymin), (xmax, ymax)), outline=tuple(color), width=5)
212
 
213
- # --- Force sanitize to (H, W, 3) uint8 contiguous & even size ---
214
- arr = np.asarray(pil_img)
215
- if arr.ndim == 2: # gray -> 3ch
216
- arr = np.stack([arr] * 3, axis=-1)
217
- elif arr.ndim == 3 and arr.shape[2] == 4: # RGBA -> RGB
218
- arr = arr[..., :3]
219
- elif arr.ndim != 3:
220
- arr = np.asarray(Image.fromarray(arr).convert("RGB"))
221
-
222
- if arr.dtype != np.uint8:
223
- arr = arr.astype(np.uint8)
224
 
225
- h, w = arr.shape[:2]
226
- if (h % 2) or (w % 2): # x264 prefers even dims
227
- arr = arr[: h - (h % 2), : w - (w % 2), :]
228
-
229
- arr = np.ascontiguousarray(arr)
230
- assert arr.ndim == 3 and arr.shape[2] == 3, f"Bad frame at t={t}, shape={arr.shape}, dtype={arr.dtype}"
231
-
232
- save_imgs.append(arr)
233
-
234
- # Write once (more robust than append_data)
235
  with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp_file:
236
- fps = int(info['video_fps'] / frame_step)
237
-
238
- writer = imageio.get_writer(
239
- tmp_file.name,
240
- format='FFMPEG',
241
- mode='I',
242
- fps=fps,
243
- codec='libx264',
244
- output_params=['-pix_fmt', 'yuv420p'],
245
- macro_block_size=None,
246
- )
247
- for arr in save_imgs:
248
- writer.append_data(arr)
249
- writer.close()
250
  result_video_path = tmp_file.name
251
 
252
  end_save = time.time()
@@ -257,24 +212,19 @@ def run_video_inference(input_video, text_prompt, tracking_alpha=0.1, target_fps
257
  )
258
  return result_video_path, status
259
 
260
- # except Exception as e:
261
- # return None, f"❌ Error during inference: {str(e)}"
262
-
263
 
264
  def main():
265
  # Configuration
266
  config_path = "configs/ytvos_swinb.yaml" # Update this path
267
- checkpoint_path = "ckpt/ryb_mevis_swinb.pth" # Update this path
268
- # device = "cuda" if torch.cuda.is_available() else "cpu"
269
- device = "cpu"
270
 
271
  # Load model at startup
272
  print("Loading model...")
273
- load_model_once(config_path, checkpoint_path, device)
274
  print(f"Model loaded on device: {device}")
275
 
276
  # Create Gradio interface
277
- # with gr.Blocks(title="ReferDINO") as demo:
278
  with gr.Blocks(
279
  title="ReferDINO",
280
  css="""
@@ -291,7 +241,7 @@ def main():
291
  <h3>Referring Video Object Segmentation with
292
  <a href="https://github.com/iSEE-Laboratory/ReferDINO">ReferDINO</a>
293
  </h3>
294
- <h3>This is a CPU-only demo, so the video will be trimmed to ≤8 seconds.</h3>
295
  """,
296
  elem_id="hero",
297
  )
@@ -323,15 +273,16 @@ def main():
323
  maximum=1.0,
324
  value=0.1,
325
  step=0.05,
326
- info="Controls the memory updating (lower = longer memory)"
327
  )
 
328
  target_fps = gr.Slider(
329
- label="Target FPS",
330
  minimum=1,
331
- maximum=20,
332
  value=10,
333
  step=1,
334
- info="Downsample input video to this FPS for inference & output (Higher FPS will slow down processing)"
335
  )
336
 
337
  with gr.Column(scale=1):
@@ -349,14 +300,14 @@ def main():
349
  # Examples
350
  gr.Examples(
351
  examples=[
352
- ["example_video.mp4", "person walking", 0.1, 10],
353
- ["example_video2.mp4", "red car", 0.1, 10],
354
  ],
355
  inputs=[input_video, text_prompt, tracking_alpha, target_fps],
356
  outputs=[output_video],
357
  fn=run_video_inference,
358
  cache_examples=False,
359
- label="Try these examples:"
360
  )
361
 
362
  # Event handlers
 
1
  import gradio as gr
2
+ import os
3
+ import warnings
4
+
5
+ so_path = "models/GroundingDINO/ops/MultiScaleDeformableAttention.cpython-39-x86_64-linux-gnu.so"
6
+ if not os.path.exists(so_path):
7
+ os.system("python models/GroundingDINO/ops/setup.py build_ext develop --user")
8
+
9
  import torchvision.transforms as T
10
  from models import build_model
 
11
  import torch
12
  import misc as utils
13
  import numpy as np
14
  import torch.nn.functional as F
 
15
  from torchvision.io import read_video
16
  import torchvision.transforms.functional as Func
17
  from ruamel.yaml import YAML
18
  from easydict import EasyDict
19
  from misc import nested_tensor_from_videos_list
20
  from torch.cuda.amp import autocast
21
+ from PIL import Image, ImageDraw
 
22
  import imageio.v3 as iio
 
23
  import cv2
 
24
  import tempfile
25
  import argparse
26
  import time
27
  from huggingface_hub import hf_hub_download
28
 
 
29
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
30
 
31
+ DURATION = 6
32
+ CHECKPOINT = "ryb_mevis_swinb.pth"
 
 
 
 
 
33
 
34
  # Transform for video frames
35
  transform = T.Compose([
 
46
  model = None
47
 
48
 
49
+ def load_model_once(config_path, device='cpu'):
50
  """Load model once at startup"""
51
  global model
52
  if model is None:
 
58
 
59
  args = EasyDict(config)
60
  args.device = device
 
61
 
62
  model = build_model(args)
63
  model.to(device)
64
+ cache_file = hf_hub_download(repo_id="liangtm/referdino", filename=CHECKPOINT)
65
+ # cache_file = 'ckpt/' + CHECKPOINT
66
+ checkpoint = torch.load(cache_file, map_location='cpu')
 
 
 
 
 
 
67
  state_dict = checkpoint["model_state_dict"]
68
  model.load_state_dict(state_dict, strict=False)
69
  model.eval()
 
107
  return origin_img
108
 
109
 
110
+ def run_video_inference(input_video, text_prompt, tracking_alpha=0.1, fps=15):
111
  """Main inference function for Gradio"""
112
  global model
113
  model.tracking_alpha = tracking_alpha
114
 
115
  # Set default values for other parameters
 
116
  show_box = True
117
  mask_edge_width = 6
118
 
 
125
  # Process text prompt
126
  exp = " ".join(text_prompt.lower().split())
127
 
128
+ # Read video
129
+ video_frames, _, info = read_video(input_video, end_pts=DURATION, pts_unit='sec') # (T, H, W, C)
130
+
131
+ frame_step = max(round(info['video_fps'] / fps), 1)
132
 
133
  frames = []
134
+ for i in range(0, len(video_frames), frame_step):
135
  source_frame = Func.to_pil_image(video_frames[i].permute(2, 0, 1))
136
  frames.append(source_frame)
137
 
 
138
  video_len = len(frames)
139
  if video_len == 0:
140
  return None, "No frames found in the video."
 
148
 
149
  device = next(model.parameters()).device
150
  imgs = torch.stack(imgs, dim=0).to(device)
151
+ samples = nested_tensor_from_videos_list(imgs[None], size_divisibility=16)
152
  img_h, img_w = imgs.shape[-2:]
153
  size = torch.as_tensor([int(img_h), int(img_w)]).to(device)
154
  target = {"size": size}
155
 
156
  start_infer = time.time()
157
+ # Run inference
158
  with torch.no_grad():
159
  with autocast(True):
160
  outputs = model(samples, [exp], [target])
161
  end_infer = time.time()
162
 
163
  pred_logits = outputs["pred_logits"][0] # [t, q, k]
164
+ pred_masks = outputs["pred_masks"][0] # [t, q, h, w]
165
+ pred_boxes = outputs["pred_boxes"][0] # [t, q, 4]
166
 
167
  # Select the query index according to pred_logits
168
+ pred_scores = pred_logits.sigmoid() # [t, q, k]
169
+ pred_scores = pred_scores.mean(0) # [q, K]
170
+ max_scores, _ = pred_scores.max(-1) # [q,]
171
+ _, max_ind = max_scores.max(-1) # [1,]
172
  max_inds = max_ind.repeat(video_len)
173
  pred_masks = pred_masks[range(video_len), max_inds, ...] # [t, h, w]
174
  pred_masks = pred_masks.unsqueeze(0)
175
  pred_boxes = pred_boxes[range(video_len), max_inds].cpu().numpy() # [t, 4]
176
 
177
+ # Unpad and resize
178
  pred_masks = pred_masks[:, :, :img_h, :img_w].cpu()
179
  pred_masks = F.interpolate(pred_masks, size=(origin_h, origin_w), mode='bilinear', align_corners=False)
180
  pred_masks = (pred_masks.sigmoid() > 0.5).squeeze(0).cpu().numpy()
181
 
182
+ # Visualization
183
+ color = np.array([220, 20, 60], dtype=np.uint8)
 
184
 
 
185
  start_save = time.time()
186
  save_imgs = []
187
+ for t, img in enumerate(frames):
188
+ # Draw mask
189
+ img = vis_add_mask(img, pred_masks[t], color, mask_edge_width)
190
 
191
+ draw = ImageDraw.Draw(img)
 
192
  draw_boxes = pred_boxes[t][None]
193
  draw_boxes = rescale_bboxes(draw_boxes, (origin_w, origin_h)).tolist()
194
+
195
+ # Draw box if enabled
196
  if show_box:
197
  xmin, ymin, xmax, ymax = draw_boxes[0]
198
  draw.rectangle(((xmin, ymin), (xmax, ymax)), outline=tuple(color), width=5)
199
 
200
+ save_imgs.append(np.asarray(img).copy())
 
 
 
 
 
 
 
 
 
 
201
 
202
+ # Save result video
 
 
 
 
 
 
 
 
 
203
  with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp_file:
204
+ iio.imwrite(tmp_file.name, save_imgs, fps=fps)
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  result_video_path = tmp_file.name
206
 
207
  end_save = time.time()
 
212
  )
213
  return result_video_path, status
214
 
 
 
 
215
 
216
  def main():
217
  # Configuration
218
  config_path = "configs/ytvos_swinb.yaml" # Update this path
219
+ device = "cuda" if torch.cuda.is_available() else "cpu"
220
+ # device = "cpu"
 
221
 
222
  # Load model at startup
223
  print("Loading model...")
224
+ load_model_once(config_path, device)
225
  print(f"Model loaded on device: {device}")
226
 
227
  # Create Gradio interface
 
228
  with gr.Blocks(
229
  title="ReferDINO",
230
  css="""
 
241
  <h3>Referring Video Object Segmentation with
242
  <a href="https://github.com/iSEE-Laboratory/ReferDINO">ReferDINO</a>
243
  </h3>
244
+ <h3>Note that this demo runs on CPU, so the video will be trimmed to ≤6 seconds.</h3>
245
  """,
246
  elem_id="hero",
247
  )
 
273
  maximum=1.0,
274
  value=0.1,
275
  step=0.05,
276
+ info="controls the memory updating (lower = longer memory)"
277
  )
278
+
279
  target_fps = gr.Slider(
280
+ label="FPS",
281
  minimum=1,
282
+ maximum=30,
283
  value=10,
284
  step=1,
285
+ info="controls the FPS (lower = faster processing)"
286
  )
287
 
288
  with gr.Column(scale=1):
 
300
  # Examples
301
  gr.Examples(
302
  examples=[
303
+ ["dogs.mp4", "the dog drinking Sprite", 0.1, 10],
304
+ ["dogs.mp4", "the dog sleeping", 0.1, 10],
305
  ],
306
  inputs=[input_video, text_prompt, tracking_alpha, target_fps],
307
  outputs=[output_video],
308
  fn=run_video_inference,
309
  cache_examples=False,
310
+ label="📋 Try these examples:"
311
  )
312
 
313
  # Event handlers