Spaces:
Running on Zero

File size: 11,687 Bytes
5c58a52
5a19b4e
 
e605e7b
5c58a52
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e605e7b
5a19b4e
915206b
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
915206b
 
5a19b4e
 
 
76088f5
5a19b4e
 
5c58a52
 
 
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76088f5
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c58a52
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""Tempora-1 demo Space (ZeroGPU).

The page (static/page.html, app.css, app.js) is plain HTML rendered inside Gradio; it calls the queued Gradio endpoint
`/segment` through the Gradio JS client. The model is the private checkpoint ambient-intelligence-labs/tempora-1 (Tempora-1), loaded
with transformers. Video goes through qwen-vl-utils with the settings the model was trained and evaluated with
(3 fps, at most 540 frames, 64 to 112 visual tokens per frame), and decoding is greedy, as in the release repo's
offline inference.

  HF_TOKEN          Space secret with read access to the model repo
  TEMPORA_MOCK=1    local UI work without a GPU: replays the saved example outputs
"""
import json
import os
import threading
import time

import gradio as gr

HERE = os.path.dirname(os.path.abspath(__file__))
STATIC = os.path.join(HERE, "static")
MODEL_ID = os.environ.get("TEMPORA_MODEL", "ambient-intelligence-labs/tempora-1")
MOCK = os.environ.get("TEMPORA_MOCK") == "1"
MAX_NEW_TOKENS = {True: 6144, False: 3072}     # thinking on / off (offline eval: 32768 / 3072; WGO median ~400)
RETURN_LINE = 'Return JSON: {"chunks":[{"start":sec,"end":sec,"label":...}]}'
CORE = {"start", "end", "label", "metadata"}
EXAMPLES = {e["id"]: e for e in json.load(open(os.path.join(STATIC, "examples.json")))}

# ---------------------------------------------------------------- video sampling (release VideoConfig)
os.environ.setdefault("FORCE_QWENVL_VIDEO_READER", "torchcodec")
if not MOCK:
    import spaces
    import torch
    from qwen_vl_utils import process_vision_info, vision_process
    from transformers import AutoModelForImageTextToText, AutoProcessor, TextIteratorStreamer

    vision_process.FORCE_QWENVL_VIDEO_READER = "torchcodec"
    vision_process.get_video_reader_backend.cache_clear()
    vision_process.FPS, vision_process.FPS_MAX_FRAMES = 3.0, 540
    vision_process.VIDEO_MAX_TOKEN_NUM, vision_process.VIDEO_MIN_TOKEN_NUM = 112, 64

    TOKEN = os.environ.get("HF_TOKEN")
    processor = AutoProcessor.from_pretrained(MODEL_ID, token=TOKEN)
    model = AutoModelForImageTextToText.from_pretrained(MODEL_ID, token=TOKEN, dtype=torch.bfloat16).to("cuda")
    model.eval()


def build_prompt(instruction="", task="", fields=(), field_descriptions=None):
    """The trained prompt format (release repo: video_chunker.prompt.build_prompt)."""
    instruction, task, fields = instruction.strip(), task.strip(), list(fields)
    lines = []
    if instruction:
        lines.append(f"Instruction:\n{instruction}" if "\n" in instruction else f"Instruction: {instruction}")
    if task:
        lines.append(f"Task: {task}")
    if instruction or fields:
        lines.append("metadata_fields: " + json.dumps(fields))
        if field_descriptions:
            lines.append("metadata_fields_description: " + json.dumps(list(field_descriptions)))
    lines.append(RETURN_LINE)
    return "\n".join(lines)


def extract_chunks(text):
    """The outermost {"chunks": [...]} object (or a bare list) in the answer; None if there is none."""
    s = (text or "").strip()
    if s.startswith("```"):
        s = s.split("\n", 1)[-1].rsplit("```", 1)[0]
    dec = json.JSONDecoder()
    for i, ch in enumerate(s):
        if ch not in "{[":
            continue
        try:
            obj, _ = dec.raw_decode(s[i:])
        except json.JSONDecodeError:
            continue
        chunks = obj.get("chunks") if isinstance(obj, dict) else obj
        if isinstance(chunks, list) and all(isinstance(c, dict) and "start" in c and "end" in c for c in chunks):
            rows = []
            for c in chunks:
                meta = dict(c.get("metadata") or {}) if isinstance(c.get("metadata"), dict) else {}
                meta.update({k: v for k, v in c.items() if k not in CORE})
                try:
                    rows.append({"start": float(c["start"]), "end": float(c["end"]), "label": str(c.get("label", "")),
                                 "metadata": meta})
                except (TypeError, ValueError):
                    continue
            return rows
    return None


def msg(**kw):
    return json.dumps(kw, ensure_ascii=False)


# ---------------------------------------------------------------- model call
def _gpu_seconds(inputs, thinking, n_frames):
    """ZeroGPU time to reserve. transformers generates ~15 tokens/s here (reference GDN/conv kernels), plus prefill."""
    return 420 if thinking else 150


if not MOCK:
    @spaces.GPU(duration=_gpu_seconds, size="xlarge")   # 54.7 GB of bf16 weights: a "large" slice has ~51 GB
    def generate(inputs, thinking, n_frames):
        """Greedy generation on the GPU, streaming text as it is produced."""
        n_gpu = torch.cuda.device_count()
        print(f"[gpu] {n_gpu} device(s): " + "; ".join(
            f"{i} {torch.cuda.get_device_name(i)} {torch.cuda.mem_get_info(i)[1] / 2**30:.1f} GiB" for i in range(n_gpu)),
            flush=True)
        batch = {k: (v.to("cuda") if hasattr(v, "to") else v) for k, v in inputs.items()}
        streamer = TextIteratorStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
        out = {}

        def run():
            with torch.inference_mode():
                ids = model.generate(**batch, max_new_tokens=MAX_NEW_TOKENS[thinking], do_sample=False,
                                     temperature=None, top_p=None, top_k=None, streamer=streamer)
            out["n"] = int(ids.shape[1] - batch["input_ids"].shape[1])

        t = threading.Thread(target=run)
        t.start()
        for piece in streamer:
            yield piece, None
        t.join()
        yield "", out.get("n")


def segment(video, example, instruction, task, fields, thinking):
    """Gradio endpoint /segment. Streams JSON messages: stage updates, partial text, then the result."""
    t0 = time.time()
    thinking = bool(thinking)
    try:
        rows = [f for f in json.loads(fields or "[]") if str(f.get("name", "")).strip()]
    except (json.JSONDecodeError, AttributeError):
        raise gr.Error("Metadata fields must be a list of {name, description}.")
    names = [str(f["name"]).strip() for f in rows]
    descs = [str(f.get("description", "")).strip() for f in rows]
    if not (instruction or "").strip() and not names:
        raise gr.Error("Write an instruction (and optionally a task or fields).")
    prompt = build_prompt(instruction or "", task or "", names, descs if any(descs) else None)
    if example:
        if example not in EXAMPLES:
            raise gr.Error("Unknown example.")
        path = os.path.join(STATIC, EXAMPLES[example]["src"])
    elif video:
        path = video if isinstance(video, str) else getattr(video, "name", None) or video.get("path")
    else:
        raise gr.Error("Choose an example or upload a video.")
    yield msg(stage="decoding", prompt=prompt, thinking=thinking)

    if MOCK:   # replay a saved output so the page can be built without a GPU
        ex = EXAMPLES.get(example) or next(iter(EXAMPLES.values()))
        res = ex["result"]
        text = (("<think>\n" + res["reasoning"] + "\n</think>\n\n") if thinking and res.get("reasoning") else "") \
            + (res.get("raw") or "")
        yield msg(stage="generating", frames=120, duration=ex["duration"], input_tokens=0)
        acc = ""
        for i in range(0, len(text), 40):
            acc += text[i:i + 40]
            time.sleep(0.01)
            yield msg(stage="generating", partial=acc)
        answer = res.get("raw") or ""
        yield msg(stage="done", prompt=prompt, thinking=thinking, raw=answer, reasoning=res.get("reasoning"),
                  chunks=extract_chunks(answer), stats={"mock": True, "seconds": round(time.time() - t0, 1)})
        return

    msgs = [{"role": "user", "content": [{"type": "video", "video": path}, {"type": "text", "text": prompt}]}]
    try:
        text = processor.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=thinking)
        _, videos, _ = process_vision_info(msgs, image_patch_size=16, return_video_kwargs=True,
                                           return_video_metadata=True)
    except Exception as e:  # noqa: BLE001
        raise gr.Error(f"Could not read this video ({type(e).__name__}). Try an H.264 .mp4.")
    frames, meta = videos[0]
    inputs = processor(text=[text], videos=[frames], video_metadata=[meta], do_sample_frames=False, do_resize=False,
                       return_tensors="pt")
    n_frames = int(frames.shape[0])
    dur = float(meta.get("total_num_frames", 0)) / float(meta.get("fps", 1) or 1)
    n_in = int(inputs["input_ids"].shape[1])
    yield msg(stage="queued", frames=n_frames, duration=round(dur, 1), input_tokens=n_in,
              frame_hw=[int(frames.shape[2]), int(frames.shape[3])], decode_s=round(time.time() - t0, 1))

    acc, n_out, t1, last = "", None, None, 0.0
    for piece, n in generate(dict(inputs), thinking, n_frames):
        if t1 is None:
            t1 = time.time()
            yield msg(stage="generating")
        if n is not None:
            n_out = n
        acc += piece
        if time.time() - last > 0.25:
            last = time.time()
            yield msg(stage="generating", partial=acc)
    if t1 is None:
        raise gr.Error("The GPU run failed before generating. Try again in a minute.")
    reasoning, answer = None, acc.strip()
    if thinking:   # no closing tag = the reasoning used the whole budget = no answer
        head, sep, tail = acc.partition("</think>")
        reasoning, answer = head.replace("<think>", "").strip(), (tail.strip() if sep else "")
    chunks = extract_chunks(answer)
    yield msg(stage="done", prompt=prompt, thinking=thinking, raw=answer, reasoning=reasoning, chunks=chunks,
              truncated=thinking and "</think>" not in acc,
              stats={"frames": n_frames, "duration": round(dur, 1), "input_tokens": n_in, "output_tokens": n_out,
                     "generate_s": round(time.time() - (t1 or time.time()), 1),
                     "seconds": round(time.time() - t0, 1)})


# ---------------------------------------------------------------- page
gr.set_static_paths(paths=[STATIC])
PAGE = open(os.path.join(STATIC, "page.html")).read()
BASE = "/gradio_api/file=" + STATIC + "/"
VER = int(max(os.path.getmtime(os.path.join(STATIC, f)) for f in ("app.css", "app.js", "page.html")))
HEAD = f"""
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,600;0,700;0,800;1,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="{BASE}app.css?v={VER}" />
<script>window.TEMPORA = {{ base: {json.dumps(BASE)}, mock: {json.dumps(MOCK)} }};</script>
<script type="module" src="{BASE}app.js?v={VER}"></script>
"""

with gr.Blocks(title="Tempora-1", fill_width=True) as demo:
    gr.HTML(PAGE, elem_id="tempora-host", container=False, padding=False, apply_default_css=False)
    with gr.Column(visible=False):
        video_in = gr.File(file_types=["video"])
        example_in = gr.Textbox()
        instruction_in = gr.Textbox()
        task_in = gr.Textbox()
        fields_in = gr.Textbox()
        thinking_in = gr.Checkbox(value=True)
        out = gr.Textbox()
        btn = gr.Button()
    btn.click(segment, [video_in, example_in, instruction_in, task_in, fields_in, thinking_in], out,
              api_name="segment", concurrency_limit=1)

if __name__ == "__main__":
    demo.queue(max_size=20).launch(head=HEAD, allowed_paths=[STATIC], show_error=True)