multimodalart HF Staff commited on
Commit
2bc6213
·
verified ·
1 Parent(s): ecea815

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. .gitattributes +2 -0
  2. README.md +45 -7
  3. app.py +582 -0
  4. man_jumping_rope.mp4 +3 -0
  5. rec-1596.mp4 +3 -0
  6. requirements.txt +8 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ man_jumping_rope.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ rec-1596.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,51 @@
1
  ---
2
- title: Onestreamer
3
- emoji: 📉
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.29.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OneStreamer-4B
3
+ emoji: 🎬
4
+ colorFrom: pink
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 6.29.0
 
8
  app_file: app.py
9
+ python_version: "3.12"
10
+ short_description: Streaming video LLM that answers at the right time
11
+ startup_duration_timeout: 30m
12
  ---
13
 
14
+ # OneStreamer-4B · Streaming Video Interaction
15
+
16
+ **Perceive the present. Remember the past. Respond at the right time.**
17
+
18
+ [OneStreamer](https://arxiv.org/abs/2610.01762) is a streaming video LLM that watches video
19
+ incrementally and jointly learns to record evidence and respond proactively. This Space runs
20
+ **OneStreamer-4B** ([MCG-NJU/OneStreamer-4B](https://huggingface.co/MCG-NJU/OneStreamer-4B),
21
+ initialized from Qwen3-VL-4B-Instruct) exactly like the official
22
+ [`Inference/inference.py`](https://github.com/MCG-NJU/OneStreamer/tree/main/Inference) reference:
23
+
24
+ - the video is sampled at **4 frames per second** and fed **one second at a time**;
25
+ - a **rolling window of 64 frames** (the recent visual window) is kept in context;
26
+ - at every update the model picks one of three proactive states —
27
+ `</Silence>` (keep watching), `</Standby>` (evidence is building),
28
+ `</Response>` (answer now) — using the paper's conservative three-protocol prompt;
29
+ - responses are timestamped to the moment the model decides to speak.
30
+
31
+ Upload a clip (or record one with your webcam), ask what to watch for, and press
32
+ **Watch video**. The timeline shows the model's state for every second of the stream; the
33
+ transcript lists each proactive answer with the time it was emitted.
34
+
35
+ ## Example video provenance
36
+
37
+ - `rec-1596.mp4` — OVOBench REC sample 1596 (Perception Test `video_2669.mp4`), the clip used by
38
+ the paper's own inference example; included unchanged under the Perception Test dataset's
39
+ CC BY 4.0 license.
40
+ - `man_jumping_rope.mp4` — CC0-style sample from
41
+ [linoyts/repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).
42
+
43
+ ## Citation
44
+
45
+ ```bibtex
46
+ @misc{zeng2026onestreamerunifyingperceptionmemory,
47
+ title={OneStreamer: Unifying Perception, Memory, and Proactive Response in Streaming Video Interaction},
48
+ author={Zeng, Xiangyu and Yang, Yuandong and Zhang, Zhiqiu and Zhu, Yuhan and Li, Xinhao and Si, Qingyi and others},
49
+ year={2026}
50
+ }
51
+ ```
app.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
2
+ import math
3
+ import os
4
+ import random
5
+ from typing import List, Optional, Sequence, Tuple
6
+
7
+ import spaces # MUST be imported before torch / transformers
8
+ import cv2
9
+ import gradio as gr
10
+ import torch
11
+ from PIL import Image
12
+ from transformers import AutoModelForImageTextToText, AutoProcessor, set_seed
13
+
14
+ MODEL_ID = "MCG-NJU/OneStreamer-4B"
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Reference: MCG-NJU/OneStreamer -> Inference/inference.py + Eval/VLMEvalKit
18
+ # vlmeval/vlm/qwen3_ovotiming (inference_fast.py / utils.py) + ovo_timing.py
19
+ # ---------------------------------------------------------------------------
20
+
21
+ # Streaming system prompt from Eval/VLMEvalKit/vlmeval/dataset/ovo_timing.py
22
+ # (STREAMING_SYS_CONSERVATIVE_THREE_PROTOCOL)
23
+ STREAMING_SYSTEM = """You are a conservative assistant for real-time streaming video event detection.
24
+ You receive the video incrementally, with every update labeled by an absolute time interval such as <0s-1s>. Base each decision only on evidence observed so far.
25
+
26
+ Every </Response> is a final detection of one distinct event boundary. An unmatched, premature, or duplicate response is an error, so prioritize precision over frequent responses.
27
+
28
+ At every update, use exactly one of these three protocols:
29
+
30
+ 1. Use </Silence> when:
31
+ - No relevant event is currently supported by clear visual evidence.
32
+ - The requested event has not started, or a suspected event is no longer supported.
33
+ - The same event was already reported and no unmistakably new occurrence or step has completed.
34
+ - The scene is unchanged, shows only aftermath, or merely repeats evidence already used for a response.
35
+ Output exactly </Silence> and nothing else.
36
+
37
+ 2. Use </Standby> only when:
38
+ - A specific relevant event is visibly developing, but its completion or identity still needs confirmation.
39
+ - There is concrete new evidence, not just generic activity or uncertainty.
40
+ </Standby> is reversible. Return to </Silence> if later frames do not confirm a new event.
41
+ Output exactly </Standby> and nothing else.
42
+
43
+ 3. Use </Response> only when:
44
+ - The visual evidence clearly establishes that a new, distinct requested event or step has just completed.
45
+ - All essential entities, actions, attributes, and relationships required by the question are confirmed.
46
+ - This event has not already been reported.
47
+ Output </Response> followed by a concise answer.
48
+
49
+ Task-specific rules:
50
+ - For a single-event question, respond at most once in the entire stream. After responding, always use </Silence>.
51
+ - For "How many times" questions, respond exactly once when each genuinely new occurrence completes. Do not repeat the same count while no new occurrence has happened.
52
+ - For step-description questions, respond exactly once when each genuinely new requested step completes. Do not repeatedly report an ongoing or already completed step."""
53
+
54
+
55
+ # ---- video sampling (Inference/inference.py: video_windows, fps=4) ---------
56
+
57
+ def iter_video_windows(path: str, max_seconds: Optional[float], fps: int = 4):
58
+ """Sample the video at `fps` frames per second and yield one-second
59
+ windows: (frames, per-frame (lo, hi) interval list)."""
60
+ cap = cv2.VideoCapture(path)
61
+ try:
62
+ if not cap.isOpened():
63
+ raise RuntimeError("Cannot open the uploaded video. Please try another file.")
64
+ source_fps = float(cap.get(cv2.CAP_PROP_FPS))
65
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
66
+ if source_fps <= 0 or frame_count <= 0:
67
+ raise RuntimeError("The video must report a positive frame rate and frame count.")
68
+ duration = frame_count / source_fps
69
+ end = min(duration, max_seconds) if max_seconds is not None else duration
70
+ frames: List[Image.Image] = []
71
+ times: List[Tuple[float, float]] = []
72
+ for step in range(math.ceil(end * fps)):
73
+ timestamp = step / fps
74
+ frame_index = min(int(timestamp * source_fps), frame_count - 1)
75
+ cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
76
+ ok, frame = cap.read()
77
+ if not ok:
78
+ raise RuntimeError(f"Cannot decode a frame at {timestamp:.3f}s.")
79
+ frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
80
+ times.append((timestamp, timestamp + 1 / fps))
81
+ if len(frames) == fps:
82
+ yield frames, times
83
+ frames, times = [], []
84
+ if frames:
85
+ yield frames, times
86
+ finally:
87
+ cap.release()
88
+
89
+
90
+ # ---- frame resize (qwen3_ovotiming/utils.py: smart_resize family) ---------
91
+
92
+ def smart_resize(height, width, factor=28, min_pixels=56 * 56,
93
+ max_pixels=14 * 14 * 4 * 1280, force_resize=False):
94
+ if max(height, width) / min(height, width) > 200:
95
+ raise ValueError(
96
+ f"absolute aspect ratio must be smaller than 200, got "
97
+ f"{max(height, width) / min(height, width)}"
98
+ )
99
+ if force_resize:
100
+ beta = math.sqrt((height * width) / max_pixels)
101
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
102
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
103
+ return h_bar, w_bar
104
+ h_bar = round(height / factor) * factor
105
+ w_bar = round(width / factor) * factor
106
+ if h_bar * w_bar > max_pixels:
107
+ beta = math.sqrt((height * width) / max_pixels)
108
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
109
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
110
+ elif h_bar * w_bar < min_pixels:
111
+ beta = math.sqrt(min_pixels / (height * width))
112
+ h_bar = math.ceil(height * beta / factor) * factor
113
+ w_bar = math.ceil(width * beta / factor) * factor
114
+ return h_bar, w_bar
115
+
116
+
117
+ def stream_frame_size(height: int, width: int, factor: int):
118
+ """Resize target used by Inference/inference.py: every streamed frame is
119
+ normalised to at most 224*224 pixels on a `factor` grid."""
120
+ if height < factor or width < factor:
121
+ raise ValueError(
122
+ f"height:{height} or width:{width} must be larger than factor:{factor}"
123
+ )
124
+ h_bar, w_bar = smart_resize(
125
+ height, width, factor=factor, min_pixels=factor ** 2,
126
+ max_pixels=224 * 224, force_resize=True,
127
+ )
128
+ return h_bar, w_bar
129
+
130
+
131
+ # ---- streaming chat state (qwen3_ovotiming/inference_fast.py) --------------
132
+
133
+ class StreamingSession:
134
+ """Rolling conversation for incremental video, ported 1:1 from
135
+ vlmeval.vlm.qwen3_ovotiming.inference_fast.StreamingSession."""
136
+
137
+ def __init__(self, engine, system: str, question: str,
138
+ max_num_frames: int = 64, max_tokens: int = 128,
139
+ temperature: float = 0.7):
140
+ self.engine = engine
141
+ self.system = system
142
+ self.question = question
143
+ self.max_num_frames = max_num_frames
144
+ self.max_tokens = max_tokens
145
+ self.temperature = temperature
146
+ self._data: Optional[dict] = None
147
+ self._last_answer: Optional[str] = None
148
+ self._turn_image_counts: List[int] = []
149
+ self._turn_meta: List[dict] = []
150
+
151
+ @staticmethod
152
+ def _user_content_multi(time_secs: Sequence[Tuple[float, float]]) -> str:
153
+ return "\n".join(f"<{lo:.3f}s-{hi:.3f}s>\n<image>" for lo, hi in time_secs)
154
+
155
+ def _first_frame_user_message_index(self) -> int:
156
+ for i, msg in enumerate(self._data["messages"]):
157
+ if msg.get("role") == "user" and "<image>" in str(msg.get("content", "")):
158
+ return i
159
+ return len(self._data["messages"])
160
+
161
+ def _append_turn(self, frames: Sequence[Image.Image],
162
+ time_secs: Sequence[Tuple[float, float]], round_idx: int) -> None:
163
+ if len(frames) != len(time_secs) or not frames:
164
+ raise ValueError("frames and time_secs must be non-empty and equal length")
165
+
166
+ if self._data is None:
167
+ messages: List[dict] = []
168
+ if self.system:
169
+ messages.append({"role": "system", "content": self.system})
170
+ if self.question:
171
+ messages.append({"role": "user", "content": self.question})
172
+ messages.append({
173
+ "role": "user",
174
+ "content": self._user_content_multi(time_secs),
175
+ })
176
+ self._data = {"images": list(frames), "messages": messages}
177
+ self._turn_image_counts = [len(frames)]
178
+ self._turn_meta = [{"time_secs": [tuple(t) for t in time_secs]}]
179
+ else:
180
+ messages = self._data["messages"]
181
+ if self._last_answer is not None:
182
+ messages.append({"role": "assistant", "content": self._last_answer})
183
+ messages.append({
184
+ "role": "user",
185
+ "content": self._user_content_multi(time_secs),
186
+ })
187
+ self._data["images"].extend(frames)
188
+ self._turn_image_counts.append(len(frames))
189
+ self._turn_meta.append({"time_secs": [tuple(t) for t in time_secs]})
190
+
191
+ self._trim_sliding_window()
192
+
193
+ def _trim_sliding_window(self) -> None:
194
+ if self._data is None:
195
+ return
196
+ images = self._data["images"]
197
+ messages = self._data["messages"]
198
+ while len(images) > self.max_num_frames:
199
+ first_u = self._first_frame_user_message_index()
200
+ if first_u + 1 >= len(messages):
201
+ break
202
+ n0 = self._turn_image_counts[0]
203
+ del messages[first_u: first_u + 2]
204
+ self._data["images"] = images[n0:]
205
+ images = self._data["images"]
206
+ self._turn_image_counts.pop(0)
207
+ self._turn_meta.pop(0)
208
+ first_u = self._first_frame_user_message_index()
209
+ if first_u < len(messages) and messages[first_u].get("role") == "user":
210
+ ts = self._turn_meta[0]["time_secs"]
211
+ messages[first_u]["content"] = self._user_content_multi(ts)
212
+
213
+ def step_frames(self, frames: Sequence[Image.Image],
214
+ time_secs: Sequence[Tuple[float, float]],
215
+ round_idx: int) -> Optional[str]:
216
+ self._append_turn(list(frames), time_secs, round_idx)
217
+ answer = self.engine.infer(
218
+ self._data, max_tokens=self.max_tokens, temperature=self.temperature,
219
+ )
220
+ self._last_answer = answer
221
+ return answer
222
+
223
+
224
+ # ---- engine (qwen3_ovotiming/utils.py: _Qwen3VLInferenceFastEngine) --------
225
+
226
+ class InferenceEngine:
227
+ def __init__(self, processor, model, top_p=0.8, top_k=20,
228
+ repetition_penalty=1.0):
229
+ self.processor = processor
230
+ self.model = model
231
+ self.generation_options = dict(
232
+ top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty,
233
+ )
234
+ self.device = next(self.model.parameters()).device
235
+
236
+ @staticmethod
237
+ def _to_chat_messages(messages: List[dict],
238
+ images: List[Image.Image]) -> List[dict]:
239
+ image_iter = iter(images)
240
+ converted = []
241
+ for m in messages:
242
+ role, content = m["role"], m["content"]
243
+ if "<image>" not in content:
244
+ converted.append({"role": role,
245
+ "content": [{"type": "text", "text": content}]})
246
+ continue
247
+ segments = content.split("<image>")
248
+ parts: List[dict] = []
249
+ for idx, seg in enumerate(segments):
250
+ seg = seg.strip()
251
+ if seg:
252
+ parts.append({"type": "text", "text": seg})
253
+ if idx < len(segments) - 1:
254
+ parts.append({"type": "image", "image": next(image_iter)})
255
+ converted.append({"role": role, "content": parts})
256
+ return converted
257
+
258
+ @staticmethod
259
+ def _strip_end_tokens(text: str) -> str:
260
+ # The reference strips the (empty-content) end tokens; the shipped
261
+ # tokenizer decodes them to zero-width strings.
262
+ return text.strip()
263
+
264
+ def infer(self, data: dict, max_tokens: int = 128,
265
+ temperature: float = 0.0) -> str:
266
+ chat = self._to_chat_messages(data["messages"], data["images"])
267
+ inputs = self.processor.apply_chat_template(
268
+ chat, add_generation_prompt=True, tokenize=True,
269
+ return_dict=True, return_tensors="pt",
270
+ ).to(self.device)
271
+ gen_kwargs = dict(
272
+ max_new_tokens=max_tokens,
273
+ do_sample=(temperature > 0.0),
274
+ use_cache=True,
275
+ pad_token_id=self.processor.tokenizer.pad_token_id
276
+ or self.processor.tokenizer.eos_token_id,
277
+ )
278
+ if temperature > 0.0:
279
+ gen_kwargs["temperature"] = temperature
280
+ gen_kwargs.update(self.generation_options)
281
+ with torch.inference_mode():
282
+ out = self.model.generate(**inputs, **gen_kwargs)
283
+ prompt_len = inputs["input_ids"].shape[-1]
284
+ new_tokens = out[:, prompt_len:]
285
+ text = self.processor.batch_decode(new_tokens, skip_special_tokens=False)[0]
286
+ return self._strip_end_tokens(text)
287
+
288
+
289
+ # ---- model load (module scope, eager .to("cuda")) --------------------------
290
+
291
+ set_seed(42)
292
+ _processor = AutoProcessor.from_pretrained(MODEL_ID)
293
+ _model = AutoModelForImageTextToText.from_pretrained(
294
+ MODEL_ID,
295
+ dtype=torch.bfloat16,
296
+ attn_implementation="flash_attention_2",
297
+ ).eval().to("cuda")
298
+ ENGINE = InferenceEngine(_processor, _model)
299
+
300
+ # visual geometry of the processor: patch_size * merge_size (16 * 2 = 32)
301
+ _ip = getattr(_processor, "image_processor", None)
302
+ _patch = getattr(_ip, "patch_size", 16) or 16
303
+ _merge = getattr(_ip, "merge_size", getattr(_ip, "spatial_merge_size", 2)) or 2
304
+ RESIZE_FACTOR = int(_patch) * int(_merge)
305
+ MAX_WINDOW_FRAMES = 64 # reference: rolling Recent-16 (16 rounds x 4 frames)
306
+ MAX_NEW_TOKENS = 128
307
+
308
+
309
+ # ---- result classification -------------------------------------------------
310
+
311
+ def classify(raw: Optional[str]) -> str:
312
+ if raw is None:
313
+ return "silence"
314
+ if "</Response>" in raw:
315
+ return "response"
316
+ if "</Standby>" in raw:
317
+ return "standby"
318
+ if "</Silence>" in raw:
319
+ return "silence"
320
+ return "plain"
321
+
322
+
323
+ # ---- timeline visualization (dataviz: status strip, one row per second) ---
324
+
325
+ TL_CSS = """
326
+ <style>
327
+ .tl-root { --tl-blue:#2a78d6; --tl-aqua:#1baf7a; --tl-warn:#fab219;
328
+ --tl-ink:#0b0b0b; --tl-ink2:#52514e; --tl-muted:#898781;
329
+ --tl-grid:#e1e0d9; --tl-border:rgba(11,11,11,0.10); --tl-surface:#fcfcfb; }
330
+ .dark .tl-root { --tl-blue:#3987e5; --tl-aqua:#199e70; --tl-warn:#fab219;
331
+ --tl-ink:#ffffff; --tl-ink2:#c3c2b7; --tl-muted:#898781;
332
+ --tl-grid:#2c2c2a; --tl-border:rgba(255,255,255,0.10); --tl-surface:#1a1a19; }
333
+ .tl-root { font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
334
+ background: var(--tl-surface); border: 1px solid var(--tl-border);
335
+ border-radius: 10px; padding: 12px 14px; color: var(--tl-ink); }
336
+ .tl-title { font-size: 13px; font-weight: 600; margin: 0 0 8px 0; color: var(--tl-ink); }
337
+ .tl-track { display: flex; gap: 2px; align-items: stretch; }
338
+ .tl-cell { flex: 1 1 0; min-width: 0; height: 34px; border-radius: 4px;
339
+ position: relative; cursor: default; }
340
+ .tl-cell span { position: absolute; inset: 0; display: flex; align-items: center;
341
+ justify-content: center; font-size: 11px; font-variant-numeric: tabular-nums;
342
+ overflow: hidden; }
343
+ .tl-sil { background: var(--tl-grid); }
344
+ .tl-stb { background: var(--tl-warn); }
345
+ .tl-res { background: var(--tl-blue); }
346
+ .tl-pln { background: var(--tl-aqua); }
347
+ .tl-sil span { color: var(--tl-ink2); }
348
+ .tl-stb span { color: #0b0b0b; }
349
+ .tl-res span { color: #ffffff; }
350
+ .tl-pln span { color: #0b0b0b; }
351
+ .tl-legend { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 8px;
352
+ font-size: 12px; color: var(--tl-ink2); align-items: center; }
353
+ .tl-key { display: inline-flex; align-items: center; gap: 5px; }
354
+ .tl-sw { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
355
+ </style>
356
+ """
357
+
358
+
359
+ def render_timeline(states: List[str], ends: List[float],
360
+ response_texts: List[str]) -> str:
361
+ n = len(states)
362
+ cells = []
363
+ for i, st in enumerate(states):
364
+ cls = {"silence": "tl-sil", "standby": "tl-stb",
365
+ "response": "tl-res", "plain": "tl-pln"}[st]
366
+ tip = (
367
+ f"t = {ends[i]:.2f}s · " + st
368
+ + (f" · {response_texts[i]}" if st == "response" and response_texts[i] else "")
369
+ )
370
+ label = "✓" if st == "response" else ("…" if st == "standby" else "·")
371
+ cells.append(
372
+ f'<div class="tl-cell {cls}" title="{html.escape(tip)}"><span>{label}</span></div>'
373
+ )
374
+ legend = """
375
+ <div class="tl-legend">
376
+ <span class="tl-key"><span class="tl-sw" style="background:var(--tl-grid)"></span>silence — nothing new</span>
377
+ <span class="tl-key"><span class="tl-sw" style="background:var(--tl-warn)"></span>standby — evidence building</span>
378
+ <span class="tl-key"><span class="tl-sw" style="background:var(--tl-blue)"></span>response — answer emitted</span>
379
+ <span class="tl-key"><span class="tl-sw" style="background:var(--tl-aqua)"></span>plain text (no state tag)</span>
380
+ </div>"""
381
+ if n == 0:
382
+ return TL_CSS + '<div class="tl-root"><p class="tl-title">Streaming states over time</p><div style="color:var(--tl-muted);font-size:12px;">The state timeline appears once the video starts being processed.</div></div>'
383
+ return (
384
+ TL_CSS
385
+ + '<div class="tl-root"><p class="tl-title">Streaming states · one cell per second of video</p>'
386
+ + '<div class="tl-track">' + "".join(cells) + "</div>"
387
+ + legend + "</div>"
388
+ )
389
+
390
+
391
+ # ---- main handler -----------------------------------------------------------
392
+
393
+ DEFAULT_QUESTION = "How many times does the event: showing something to the camera happen?"
394
+
395
+
396
+ def _duration_estimate(video, question, max_seconds, show_all):
397
+ # warm worker: ~0.4-0.7 s per one-second window; cold start adds ~25 s
398
+ try:
399
+ secs = float(max_seconds or 30)
400
+ except (TypeError, ValueError):
401
+ secs = 30.0
402
+ return min(240, int(28 + 2.2 * secs))
403
+
404
+
405
+ @spaces.GPU(duration=_duration_estimate)
406
+ def watch_video(video, question: str, max_seconds: float = 30.0,
407
+ show_all: bool = False):
408
+ """Watch a video as a stream and answer the question at the right moments.
409
+
410
+ OneStreamer-4B receives the clip one second at a time (4 frames/second),
411
+ keeps a rolling visual window of 64 frames, and at every update decides
412
+ whether to stay silent, hold standby, or emit a response.
413
+
414
+ Args:
415
+ video: uploaded video file (mp4/webm/mkv).
416
+ question: what the model should watch for, e.g.
417
+ "How many times does the event: showing something to the camera happen?"
418
+ max_seconds: process only this prefix of the video.
419
+ show_all: also show silence/standby turns in the transcript.
420
+
421
+ Returns:
422
+ A live status line, the per-second state timeline, and a transcript
423
+ of the model's proactive responses with their timestamps.
424
+ """
425
+ if not video:
426
+ raise gr.Error("Please upload a video first.")
427
+ question = (question or "").strip()
428
+ if not question:
429
+ raise gr.Error("Please enter a question for the model to watch for.")
430
+
431
+ session = StreamingSession(
432
+ ENGINE, system=STREAMING_SYSTEM, question=question,
433
+ max_num_frames=MAX_WINDOW_FRAMES, max_tokens=MAX_NEW_TOKENS,
434
+ temperature=0.7,
435
+ )
436
+
437
+ states: List[str] = []
438
+ ends: List[float] = []
439
+ response_texts: List[str] = []
440
+ chat: List[dict] = [{"role": "user", "content": question}]
441
+ n_responses = 0
442
+
443
+ total_rounds = 0
444
+ for round_idx, (frames, times) in enumerate(
445
+ iter_video_windows(video, max_seconds or None, fps=4)
446
+ ):
447
+ total_rounds += 1
448
+ resized = []
449
+ for frame in frames:
450
+ h, w = stream_frame_size(frame.height, frame.width, RESIZE_FACTOR)
451
+ resized.append(frame.resize((w, h)))
452
+ try:
453
+ answer = session.step_frames(resized, times, round_idx) or ""
454
+ except ValueError as e:
455
+ raise gr.Error(f"Frame {times[-1][1]:.1f}s: {e}")
456
+ state = classify(answer)
457
+ resp_text = ""
458
+ if state == "response":
459
+ resp_text = answer.split("</Response>", 1)[-1].strip()
460
+ n_responses += 1
461
+
462
+ states.append(state)
463
+ ends.append(times[-1][1])
464
+ response_texts.append(resp_text)
465
+
466
+ if state == "response":
467
+ chat.append({"role": "assistant",
468
+ "content": f"[{times[-1][1]:.1f}s] {resp_text}"})
469
+ elif show_all and state in ("standby", "plain", "silence"):
470
+ label = {"standby": "standby", "silence": "silence",
471
+ "plain": "plain"}[state]
472
+ chat.append({"role": "assistant",
473
+ "content": f"[{times[-1][1]:.1f}s] ({label})"})
474
+
475
+ status = (f"⏳ Watching second **{round_idx + 1}** · "
476
+ f"{n_responses} response{'s' if n_responses != 1 else ''} so far")
477
+ yield (
478
+ status,
479
+ render_timeline(states, ends, response_texts),
480
+ chat,
481
+ )
482
+
483
+ if total_rounds == 0:
484
+ raise gr.Error("The video could not be sampled. Please try another file.")
485
+
486
+ final = (f"✅ Done · {total_rounds} seconds processed · "
487
+ f"**{n_responses}** proactive response{'s' if n_responses != 1 else ''}")
488
+ if not n_responses:
489
+ final += " — the model never found enough evidence to answer. Try a more specific question."
490
+ yield (
491
+ final,
492
+ render_timeline(states, ends, response_texts),
493
+ chat,
494
+ )
495
+
496
+
497
+ # ---- UI ---------------------------------------------------------------------
498
+
499
+ CSS = """
500
+ #col-container { max-width: 1280px; margin: 0 auto; }
501
+ .dark .gradio-container { color: var(--body-text-color); }
502
+ """
503
+
504
+ with gr.Blocks(title="OneStreamer-4B · streaming video interaction") as demo:
505
+ gr.Markdown(
506
+ """
507
+ # 🎬 OneStreamer-4B · Streaming Video Interaction
508
+ **Perceive the present. Remember the past. Respond at the right time.**
509
+
510
+ OneStreamer-4B watches your video *one second at a time* (4 frames/s, rolling 64-frame window)
511
+ and decides on its own when it has enough evidence to answer your question — through the
512
+ proactive states `</Silence>`, `</Standby>`, `</Response>`.
513
+
514
+ [Paper](https://arxiv.org/abs/2610.01762) · [Code](https://github.com/MCG-NJU/OneStreamer) · [Model](https://huggingface.co/MCG-NJU/OneStreamer-4B)
515
+ """
516
+ )
517
+ with gr.Row():
518
+ with gr.Column(scale=5):
519
+ video_in = gr.Video(label="Video to stream", sources=["upload", "webcam"])
520
+ question_in = gr.Textbox(
521
+ label="Question / instruction", value=DEFAULT_QUESTION, lines=2,
522
+ placeholder="e.g. How many times does the event: X happen?",
523
+ )
524
+ with gr.Accordion("Advanced", open=False):
525
+ max_seconds_in = gr.Slider(
526
+ minimum=5, maximum=60, value=30, step=1,
527
+ label="Max seconds of video to process",
528
+ )
529
+ show_all_in = gr.Checkbox(
530
+ value=False,
531
+ label="Show silence/standby turns in the transcript",
532
+ )
533
+ run_btn = gr.Button("▶ Watch video", variant="primary")
534
+ with gr.Column(scale=7):
535
+ status_out = gr.Markdown("Upload a video, ask a question, then press **Watch video**.")
536
+ timeline_out = gr.HTML(render_timeline([], [], []))
537
+ chat_out = gr.Chatbot(
538
+ label="Proactive responses", height=420,
539
+ placeholder="Responses appear here, timestamped, as soon as OneStreamer decides to speak.",
540
+ )
541
+
542
+ run_btn.click(
543
+ watch_video,
544
+ inputs=[video_in, question_in, max_seconds_in, show_all_in],
545
+ outputs=[status_out, timeline_out, chat_out],
546
+ api_name="watch",
547
+ concurrency_limit=1,
548
+ )
549
+
550
+ gr.Examples(
551
+ examples=[
552
+ ["rec-1596.mp4", DEFAULT_QUESTION],
553
+ ["rec-1596.mp4",
554
+ "Tell me each time the person shows a new object to the camera."],
555
+ ["man_jumping_rope.mp4",
556
+ "How many times does the event: the man completing a full jump-rope jump happen?"],
557
+ ],
558
+ inputs=[video_in, question_in],
559
+ outputs=[status_out, timeline_out, chat_out],
560
+ fn=watch_video,
561
+ cache_examples=True,
562
+ cache_mode="lazy",
563
+ label="Examples",
564
+ )
565
+
566
+ gr.Markdown(
567
+ """
568
+ ---
569
+ *OneStreamer-4B is initialized from Qwen3-VL-4B-Instruct and fine-tuned for streaming
570
+ interaction ([OneStreamer-1M](https://huggingface.co/datasets/MCG-NJU/OneStreamer-1M)).
571
+ This Space follows the official `Inference/inference.py` reference: 4 fps sampling,
572
+ one-second updates, a rolling 64-frame window, and the conservative three-protocol prompt.
573
+
574
+ **Example video provenance:** `rec-1596.mp4` — OVOBench REC sample 1596 (Perception Test
575
+ `video_2669.mp4`), used in the paper's inference example; included unchanged under the
576
+ Perception Test dataset's CC BY 4.0 license. `man_jumping_rope.mp4` — CC0-style sample from
577
+ [repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).*
578
+ """
579
+ )
580
+
581
+ if __name__ == "__main__":
582
+ demo.launch(mcp_server=True, theme=gr.themes.Citrus(), css=CSS)
man_jumping_rope.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53ea745d319bc6268699319e4ca3c680cfe2160f5f002483c4b3fbbe1b9b40b8
3
+ size 1135863
rec-1596.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34648062978e51b2a6375f4bb1ab9f0aa4d3e279535396d9579bcb1e6411bfc0
3
+ size 13379856
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ transformers==5.18.0
2
+ accelerate
3
+ torchvision
4
+ opencv-python-headless
5
+ Pillow
6
+ numpy
7
+ einops
8
+ https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt212-cu130-cp312/flash_attn-2.7.4.post1-cp312-cp312-linux_x86_64.whl