SkyNait commited on
Commit
5a418bf
·
verified ·
1 Parent(s): 56a78b6

allow file uplaod

Browse files
Files changed (1) hide show
  1. app.py +176 -9
app.py CHANGED
@@ -14,6 +14,8 @@ import os
14
  from transformers import AutoProcessor, AutoModelForImageTextToText
15
  import torch
16
  from PIL import Image
 
 
17
 
18
  # Cache for loaded model and processor
19
  default_cache = {'model_id': None, 'processor': None, 'model': None, 'device': None}
@@ -46,8 +48,34 @@ def update_model(model_id, device):
46
  model.eval()
47
  model_cache.update({'model_id': model_id, 'processor': processor, 'model': model, 'device': device})
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  @spaces.GPU
50
  def caption_frame(frame, model_id, interval_ms, sys_prompt, usr_prompt, device):
 
51
  debug_msgs = []
52
  update_model(model_id, device)
53
  processor = model_cache['processor']
@@ -115,6 +143,97 @@ def caption_frame(frame, model_id, interval_ms, sys_prompt, usr_prompt, device):
115
 
116
  return caption, '\n'.join(debug_msgs)
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  def main():
120
  logging.basicConfig(level=logging.INFO)
@@ -123,6 +242,7 @@ def main():
123
  'HuggingFaceTB/SmolVLM2-500M-Video-Instruct',
124
  'HuggingFaceTB/SmolVLM2-2.2B-Instruct'
125
  ]
 
126
  # Determine available devices
127
  device_options = ['cpu']
128
  if torch.cuda.is_available():
@@ -133,28 +253,75 @@ def main():
133
  default_device = 'cuda' if torch.cuda.is_available() else ('xpu' if has_xpu else 'cpu')
134
 
135
  with gr.Blocks() as demo:
136
- gr.Markdown('## 🎥 Real-Time Webcam Captioning with SmolVLM2 (Transformers)')
 
 
 
 
 
 
 
137
 
138
  with gr.Row():
139
- model_dd = gr.Dropdown(model_choices, value=model_choices[0], label='Model ID')
140
  device_dd = gr.Dropdown(device_options, value=default_device, label='Device')
141
 
142
- interval = gr.Slider(100, 20000, step=100, value=3000, label='Interval (ms)')
143
- sys_p = gr.Textbox(lines=2, value='Describe the key action', label='System Prompt')
144
- usr_p = gr.Textbox(lines=1, value='What is happening in this image?', label='User Prompt')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- cam = gr.Image(sources=['webcam'], streaming=True, label='Webcam Feed')
147
  caption_tb = gr.Textbox(interactive=False, label='Caption')
148
- log_tb = gr.Textbox(lines=4, interactive=False, label='Debug Log')
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  cam.stream(
151
  fn=caption_frame,
152
  inputs=[cam, model_dd, interval, sys_p, usr_p, device_dd],
153
  outputs=[caption_tb, log_tb],
154
  time_limit=600
155
  )
 
 
 
 
 
 
 
156
 
157
- # Enable Gradio's async event queue to register callback IDs and prevent KeyErrors
158
  demo.queue()
159
 
160
  # Launch the app
@@ -162,4 +329,4 @@ def main():
162
 
163
 
164
  if __name__ == '__main__':
165
- main()
 
14
  from transformers import AutoProcessor, AutoModelForImageTextToText
15
  import torch
16
  from PIL import Image
17
+ import numpy as np
18
+ from pathlib import Path
19
 
20
  # Cache for loaded model and processor
21
  default_cache = {'model_id': None, 'processor': None, 'model': None, 'device': None}
 
48
  model.eval()
49
  model_cache.update({'model_id': model_id, 'processor': processor, 'model': model, 'device': device})
50
 
51
+ def extract_frames_from_video(video_path, max_frames=10):
52
+ """Extract frames from video file for processing"""
53
+ cap = cv2.VideoCapture(video_path)
54
+ frames = []
55
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
56
+
57
+ # Calculate step size to extract evenly distributed frames
58
+ step = max(1, frame_count // max_frames)
59
+
60
+ frame_idx = 0
61
+ while cap.isOpened():
62
+ ret, frame = cap.read()
63
+ if not ret:
64
+ break
65
+
66
+ if frame_idx % step == 0:
67
+ frames.append(frame)
68
+ if len(frames) >= max_frames:
69
+ break
70
+
71
+ frame_idx += 1
72
+
73
+ cap.release()
74
+ return frames
75
+
76
  @spaces.GPU
77
  def caption_frame(frame, model_id, interval_ms, sys_prompt, usr_prompt, device):
78
+ """Caption a single frame (used for webcam streaming)"""
79
  debug_msgs = []
80
  update_model(model_id, device)
81
  processor = model_cache['processor']
 
143
 
144
  return caption, '\n'.join(debug_msgs)
145
 
146
+ @spaces.GPU
147
+ def process_video_file(video_file, model_id, sys_prompt, usr_prompt, device, max_frames):
148
+ """Process uploaded video file and return captions for multiple frames"""
149
+ if video_file is None:
150
+ return "No video file uploaded", ""
151
+
152
+ debug_msgs = []
153
+ update_model(model_id, device)
154
+ processor = model_cache['processor']
155
+ model = model_cache['model']
156
+
157
+ try:
158
+ # Extract frames from video
159
+ t0 = time.time()
160
+ frames = extract_frames_from_video(video_file, max_frames)
161
+ debug_msgs.append(f'Extracted {len(frames)} frames in {int((time.time()-t0)*1000)} ms')
162
+
163
+ if not frames:
164
+ return "No frames could be extracted from the video", '\n'.join(debug_msgs)
165
+
166
+ captions = []
167
+
168
+ for i, frame in enumerate(frames):
169
+ # Preprocess frame
170
+ t1 = time.time()
171
+ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
172
+ pil_img = Image.fromarray(rgb)
173
+ temp_path = f'frame_{i}.jpg'
174
+ pil_img.save(temp_path, format='JPEG', quality=50)
175
+
176
+ # Prepare multimodal chat messages
177
+ messages = [
178
+ {'role': 'system', 'content': [{'type': 'text', 'text': sys_prompt}]},
179
+ {'role': 'user', 'content': [
180
+ {'type': 'image', 'url': temp_path},
181
+ {'type': 'text', 'text': usr_prompt}
182
+ ]}
183
+ ]
184
+
185
+ # Tokenize and encode
186
+ inputs = processor.apply_chat_template(
187
+ messages,
188
+ add_generation_prompt=True,
189
+ tokenize=True,
190
+ return_dict=True,
191
+ return_tensors='pt'
192
+ )
193
+
194
+ # Move inputs to correct device and dtype
195
+ param_dtype = next(model.parameters()).dtype
196
+ cast_inputs = {}
197
+ for k, v in inputs.items():
198
+ if isinstance(v, torch.Tensor):
199
+ if v.dtype.is_floating_point:
200
+ cast_inputs[k] = v.to(device=model.device, dtype=param_dtype)
201
+ else:
202
+ cast_inputs[k] = v.to(device=model.device)
203
+ else:
204
+ cast_inputs[k] = v
205
+ inputs = cast_inputs
206
+
207
+ # Inference
208
+ outputs = model.generate(**inputs, do_sample=False, max_new_tokens=128)
209
+
210
+ # Decode and strip history
211
+ raw = processor.batch_decode(outputs, skip_special_tokens=True)[0]
212
+ if "Assistant:" in raw:
213
+ caption = raw.split("Assistant:")[-1].strip()
214
+ else:
215
+ lines = raw.splitlines()
216
+ caption = lines[-1].strip() if len(lines) > 1 else raw.strip()
217
+
218
+ captions.append(f"Frame {i+1}: {caption}")
219
+
220
+ # Clean up temp file
221
+ if os.path.exists(temp_path):
222
+ os.remove(temp_path)
223
+
224
+ debug_msgs.append(f'Frame {i+1} processed in {int((time.time()-t1)*1000)} ms')
225
+
226
+ return '\n\n'.join(captions), '\n'.join(debug_msgs)
227
+
228
+ except Exception as e:
229
+ return f"Error processing video: {str(e)}", '\n'.join(debug_msgs)
230
+
231
+ def toggle_input_mode(input_mode):
232
+ """Toggle between webcam and video file input"""
233
+ if input_mode == "Webcam":
234
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
235
+ else: # Video File
236
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
237
 
238
  def main():
239
  logging.basicConfig(level=logging.INFO)
 
242
  'HuggingFaceTB/SmolVLM2-500M-Video-Instruct',
243
  'HuggingFaceTB/SmolVLM2-2.2B-Instruct'
244
  ]
245
+
246
  # Determine available devices
247
  device_options = ['cpu']
248
  if torch.cuda.is_available():
 
253
  default_device = 'cuda' if torch.cuda.is_available() else ('xpu' if has_xpu else 'cpu')
254
 
255
  with gr.Blocks() as demo:
256
+ gr.Markdown('## 🎥 Real-Time Webcam & Video File Captioning with SmolVLM2 (Transformers)')
257
+
258
+ with gr.Row():
259
+ input_mode = gr.Radio(
260
+ choices=["Webcam", "Video File"],
261
+ value="Webcam",
262
+ label="Input Mode"
263
+ )
264
 
265
  with gr.Row():
266
+ model_dd = gr.Dropdown(model_choices, value=model_choices[0], label='Model ID')
267
  device_dd = gr.Dropdown(device_options, value=default_device, label='Device')
268
 
269
+ # Webcam-specific controls
270
+ with gr.Row() as webcam_controls:
271
+ interval = gr.Slider(100, 20000, step=100, value=3000, label='Interval (ms)')
272
+
273
+ # Video file-specific controls
274
+ with gr.Row(visible=False) as video_controls:
275
+ max_frames = gr.Slider(1, 20, step=1, value=5, label='Max Frames to Process')
276
+
277
+ sys_p = gr.Textbox(lines=2, value='Describe the key action', label='System Prompt')
278
+ usr_p = gr.Textbox(lines=1, value='What is happening in this image?', label='User Prompt')
279
+
280
+ # Input components
281
+ cam = gr.Image(sources=['webcam'], streaming=True, label='Webcam Feed')
282
+ video_file = gr.File(
283
+ label="Upload Video File",
284
+ file_types=[".mp4", ".avi", ".mov", ".mkv", ".webm"],
285
+ visible=False
286
+ )
287
+
288
+ # Process button for video files
289
+ process_btn = gr.Button("Process Video", visible=False)
290
 
291
+ # Output components
292
  caption_tb = gr.Textbox(interactive=False, label='Caption')
293
+ log_tb = gr.Textbox(lines=4, interactive=False, label='Debug Log')
294
 
295
+ # Toggle input mode
296
+ input_mode.change(
297
+ fn=toggle_input_mode,
298
+ inputs=[input_mode],
299
+ outputs=[cam, video_file, process_btn]
300
+ )
301
+
302
+ # Also toggle the control panels
303
+ input_mode.change(
304
+ fn=lambda mode: (gr.update(visible=mode=="Webcam"), gr.update(visible=mode=="Video File")),
305
+ inputs=[input_mode],
306
+ outputs=[webcam_controls, video_controls]
307
+ )
308
+
309
+ # Webcam streaming
310
  cam.stream(
311
  fn=caption_frame,
312
  inputs=[cam, model_dd, interval, sys_p, usr_p, device_dd],
313
  outputs=[caption_tb, log_tb],
314
  time_limit=600
315
  )
316
+
317
+ # Video file processing
318
+ process_btn.click(
319
+ fn=process_video_file,
320
+ inputs=[video_file, model_dd, sys_p, usr_p, device_dd, max_frames],
321
+ outputs=[caption_tb, log_tb]
322
+ )
323
 
324
+ # Enable Gradio's async event queue
325
  demo.queue()
326
 
327
  # Launch the app
 
329
 
330
 
331
  if __name__ == '__main__':
332
+ main()