File size: 29,636 Bytes
3d934fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f857c2
3d934fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f857c2
3d934fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import os

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import spaces  # noqa: E402  (must precede torch)

import asyncio
import base64
import contextvars
import hashlib
import io
import json
import math
import queue
import shutil
import tempfile
import threading
import time
from concurrent.futures import Future
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

import gradio as gr
import numpy as np
import torch
from PIL import Image
from transformers import (
    AutoModelForImageTextToText,
    AutoModelForSpeechSeq2Seq,
    AutoProcessor,
    AutoTokenizer,
)

import pmm.sandbox as pmm_sandbox
from pmm.agent import Agent, Question, Settings
from pmm.frames import FrameStore
from pmm.memory.asr import TextRecord, normalize_segment
from pmm.memory.build import LAYERS, windows
from pmm.memory.prompts import caption_prompt, summary_prompt
from pmm.memory.writer import CAPTION_MAX_TOKENS, SUMMARY_MAX_TOKENS
from pmm.memory_store import Clip, MemoryStore
from pmm.tools import Submodel

# ---------------------------------------------------------------------------
# Models
# ---------------------------------------------------------------------------
ROOT_ID = "Shadow-Weave/PMM-9B"
SUB_ID = "Qwen/Qwen3-VL-8B-Instruct"
SUB_REVISION = "0c351dd01ed87e9c1b53cbc748cba10e6187ff3b"  # revision used in the paper
ASR_ID = "distil-whisper/distil-large-v3.5"

MAX_SECONDS = 300  # memory covers the first 5 minutes of a video
SUB_MAX_LEN = 32768  # vLLM --max-model-len used for the submodel in the paper

root_tokenizer = AutoTokenizer.from_pretrained(ROOT_ID)
root_model = AutoModelForImageTextToText.from_pretrained(
    ROOT_ID, dtype=torch.bfloat16, attn_implementation="sdpa"
).to("cuda").eval()
ROOT_STOP = [root_tokenizer.convert_tokens_to_ids("<|im_end|>"), root_tokenizer.convert_tokens_to_ids("<|endoftext|>")]

sub_processor = AutoProcessor.from_pretrained(SUB_ID, revision=SUB_REVISION)
sub_model = AutoModelForImageTextToText.from_pretrained(
    SUB_ID, revision=SUB_REVISION, dtype=torch.bfloat16, attn_implementation="sdpa"
).to("cuda").eval()
SUB_PAD = sub_processor.tokenizer.pad_token_id
if SUB_PAD is None:
    SUB_PAD = sub_processor.tokenizer.eos_token_id

asr_processor = AutoProcessor.from_pretrained(ASR_ID)
asr_model = AutoModelForSpeechSeq2Seq.from_pretrained(ASR_ID, dtype=torch.float16).to("cuda").eval()

MEMORY_ROOT = Path(tempfile.gettempdir()) / "pmm_memory"
MEMORY_ROOT.mkdir(parents=True, exist_ok=True)

# Per-request event queue (routes trace events from the agent thread to the UI).
EVENTS: contextvars.ContextVar = contextvars.ContextVar("pmm_events", default=None)


# ---------------------------------------------------------------------------
# Submodel engine: micro-batched Qwen3-VL-8B generation (replaces the vLLM server)
# ---------------------------------------------------------------------------
def _to_hf_messages(messages):
    out = []
    for message in messages:
        content = message.get("content")
        if isinstance(content, str):
            parts = [{"type": "text", "text": content}]
        else:
            parts = []
            for item in content or []:
                if item.get("type") == "text":
                    parts.append({"type": "text", "text": item["text"]})
                elif item.get("type") == "image_url":
                    url = item["image_url"]["url"]
                    data = base64.b64decode(url.split(",", 1)[1])
                    parts.append({"type": "image", "image": Image.open(io.BytesIO(data)).convert("RGB")})
        out.append({"role": message["role"], "content": parts})
    return out


class SubmodelEngine:
    """Single GPU thread that batches concurrent chat requests (see / llm_query / writer)."""

    MAX_BATCH = 8
    MAX_BATCH_TOKENS = 32000

    def __init__(self):
        self.requests: queue.Queue = queue.Queue()
        self.stop = threading.Event()
        self.thread = threading.Thread(target=self._loop, daemon=True)
        self.thread.start()

    def submit(self, messages, max_tokens) -> Future:
        future: Future = Future()
        self.requests.put((messages, max_tokens, future))
        return future

    def chat(self, messages, max_tokens):
        return self.submit(messages, max_tokens).result()

    def close(self):
        self.stop.set()
        self.thread.join(timeout=10)

    def _prepare(self, messages):
        inputs = sub_processor.apply_chat_template(
            _to_hf_messages(messages), tokenize=True, add_generation_prompt=True,
            return_dict=True, return_tensors="pt",
        )
        return dict(inputs)

    def _loop(self):
        pending = []
        while not self.stop.is_set():
            try:
                pending.append(self.requests.get(timeout=0.05))
            except queue.Empty:
                if not pending:
                    continue
            # give concurrent callers a moment to join the batch
            time.sleep(0.02)
            while True:
                try:
                    pending.append(self.requests.get_nowait())
                except queue.Empty:
                    break
            prepared = []
            for messages, max_tokens, future in pending:
                if future.done():
                    continue
                try:
                    inputs = self._prepare(messages)
                except Exception as exc:  # noqa: BLE001
                    future.set_exception(exc)
                    continue
                length = inputs["input_ids"].shape[1]
                if length >= SUB_MAX_LEN:
                    future.set_exception(ValueError(
                        f"This model's maximum context length is {SUB_MAX_LEN} tokens. "
                        f"However, your request has {length} input tokens."
                    ))
                    continue
                prepared.append((inputs, min(max_tokens, SUB_MAX_LEN - length), future))
            pending = []
            while prepared:
                batch, total = [], 0
                while prepared and len(batch) < self.MAX_BATCH:
                    length = prepared[0][0]["input_ids"].shape[1]
                    if batch and total + length > self.MAX_BATCH_TOKENS:
                        break
                    batch.append(prepared.pop(0))
                    total += length
                try:
                    texts = self._generate(batch)
                    for (_, _, future), text in zip(batch, texts):
                        future.set_result(text)
                except Exception as exc:  # noqa: BLE001
                    for _, _, future in batch:
                        if not future.done():
                            future.set_exception(exc)
                    torch.cuda.empty_cache()

    @torch.inference_mode()
    def _generate(self, batch):
        lengths = [item[0]["input_ids"].shape[1] for item in batch]
        width = max(lengths)
        collated = {}
        keys = set().union(*(item[0].keys() for item in batch))
        for key in keys:
            values = [item[0].get(key) for item in batch]
            first = next(v for v in values if v is not None)
            seq_aligned = first.dim() == 2 and first.shape[0] == 1 and key in (
                "input_ids", "attention_mask", "mm_token_type_ids", "token_type_ids"
            )
            if seq_aligned:
                pad_value = SUB_PAD if key == "input_ids" else 0
                rows = []
                for v, n in zip(values, lengths):
                    pad = torch.full((1, width - n), pad_value, dtype=v.dtype)
                    rows.append(torch.cat([pad, v], dim=1))
                collated[key] = torch.cat(rows, dim=0)
            else:
                collated[key] = torch.cat([v for v in values if v is not None], dim=0)
        collated = {k: v.to("cuda") for k, v in collated.items()}
        if "pixel_values" in collated:
            collated["pixel_values"] = collated["pixel_values"].to(torch.bfloat16)
        max_new = max(item[1] for item in batch)
        output = sub_model.generate(
            **collated, max_new_tokens=max_new, do_sample=False, repetition_penalty=1.0,
        )
        texts = []
        for row, (_, limit, _) in zip(output[:, width:], batch):
            texts.append(sub_processor.tokenizer.decode(row[:limit], skip_special_tokens=True).strip())
        return texts


class _OpenAIHandler(BaseHTTPRequestHandler):
    """Minimal OpenAI-compatible /v1/chat/completions endpoint used by the PMM REPL worker."""

    engine: SubmodelEngine = None

    def log_message(self, *args):
        pass

    def do_POST(self):  # noqa: N802
        length = int(self.headers.get("Content-Length", 0))
        body = json.loads(self.rfile.read(length) or b"{}")
        try:
            text = self.engine.chat(body["messages"], int(body.get("max_tokens") or 2048))
            payload = {
                "id": "chatcmpl-local", "object": "chat.completion", "created": int(time.time()),
                "model": body.get("model", SUB_ID),
                "choices": [{"index": 0, "finish_reason": "stop",
                             "message": {"role": "assistant", "content": text}}],
                "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
            }
            status = 200
        except Exception as exc:  # noqa: BLE001
            payload = {"error": {"message": str(exc), "type": "BadRequestError", "code": 400}}
            status = 400
        data = json.dumps(payload).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


def start_server(engine):
    handler = type("Handler", (_OpenAIHandler,), {"engine": engine})
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    server.daemon_threads = True
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server, f"http://127.0.0.1:{server.server_address[1]}"


# ---------------------------------------------------------------------------
# Root: PMM-9B with transformers greedy decoding (replaces SGLang /generate)
# ---------------------------------------------------------------------------
class LocalRoot:
    def __init__(self):
        self.tokenizer = root_tokenizer
        self.turn = 0

    async def generate(self, input_ids, max_new_tokens, deadline):
        return await asyncio.to_thread(self._generate, list(input_ids), max_new_tokens)

    @torch.inference_mode()
    def _generate(self, input_ids, max_new_tokens):
        ids = torch.tensor([input_ids], device="cuda")
        output = root_model.generate(
            input_ids=ids, attention_mask=torch.ones_like(ids), max_new_tokens=max_new_tokens,
            do_sample=False, temperature=None, top_p=None, top_k=None,
            eos_token_id=ROOT_STOP, pad_token_id=ROOT_STOP[1],
        )
        new = output[0, len(input_ids):].tolist()
        # keep everything up to and including the first stop token
        for i, token in enumerate(new):
            if token in ROOT_STOP:
                new = new[: i + 1]
                break
        self.turn += 1
        events = EVENTS.get()
        if events is not None:
            text = self.tokenizer.decode(new, skip_special_tokens=True)
            events.put(("root", self.turn, text))
        return new


# Report each REPL execution to the UI without touching the agent loop itself.
_original_execute = pmm_sandbox.ProcessSession.execute


async def _execute_with_events(self, code, *, deadline):
    result = await _original_execute(self, code, deadline=deadline)
    events = EVENTS.get()
    if events is not None:
        events.put(("repl", code, result.formatted_output, result.final_answer))
    return result


pmm_sandbox.ProcessSession.execute = _execute_with_events


# ---------------------------------------------------------------------------
# Memory writer (PMM write-time pipeline: ASR + 10 s captions + 30s/3min/10min/1h layers)
# ---------------------------------------------------------------------------
def video_duration(path):
    from decord import VideoReader, cpu

    reader = VideoReader(str(path), ctx=cpu(0), num_threads=1)
    return len(reader) / reader.get_avg_fps()


def decode_audio(path, limit_s, sampling_rate=16000):
    import av

    with av.open(str(path)) as container:
        if not container.streams.audio:
            return None
        resampler = av.audio.resampler.AudioResampler(format="s16", layout="mono", rate=sampling_rate)
        chunks = []
        for frame in container.decode(audio=0):
            for out in resampler.resample(frame):
                chunks.append(out.to_ndarray().reshape(-1))
            if sum(len(c) for c in chunks) > limit_s * sampling_rate:
                break
        for out in resampler.resample(None):
            chunks.append(out.to_ndarray().reshape(-1))
    if not chunks:
        return None
    audio = np.concatenate(chunks).astype(np.float32) / 32768.0
    return audio[: int(limit_s * sampling_rate)]


@torch.inference_mode()
def transcribe(path, duration):
    audio = decode_audio(path, duration)
    if audio is None or len(audio) < 16000 or float(np.abs(audio).max()) < 1e-3:
        return []
    from transformers import pipeline

    asr = pipeline(
        "automatic-speech-recognition", model=asr_model, tokenizer=asr_processor.tokenizer,
        feature_extractor=asr_processor.feature_extractor, dtype=torch.float16, device="cuda",
    )
    result = asr(
        {"raw": audio, "sampling_rate": 16000}, chunk_length_s=25, batch_size=8,
        return_timestamps=True, generate_kwargs={"language": "en", "task": "transcribe"},
    )
    rows = []
    for chunk in result.get("chunks", []):
        start, end = chunk["timestamp"]
        if start is None:
            continue
        end = end if end is not None else min(duration, start + 5)
        try:
            row = normalize_segment(float(start), float(end), chunk["text"], duration)
        except ValueError:
            continue
        if row is not None:
            rows.append(row)
    rows.sort(key=lambda r: (r.t0, r.t1))
    return rows


def build_context(engine, video_path, video_id, duration, use_asr, profile):
    """Same layering as pmm.memory.build._context, with concurrent (batched) writer calls."""
    clip = Clip(Path(video_path), 0.0, duration)
    rows = transcribe(video_path, duration) if use_asr else []
    context = {
        "video": {
            "video_id": video_id, "duration_s": round(duration, 3),
            "duration_source": "logical", "asr_source": "whisper" if rows else "none",
        },
        "asr": [r.__dict__ for r in rows],
    }
    frames = FrameStore()
    system = caption_prompt(profile)
    jobs = []
    for t0, t1 in windows(clip.t0, clip.t1, 10):
        batch = frames.frames([clip], t0, math.nextafter(t1, -math.inf))
        selected = [(s, p) for s, p in zip(batch.timestamps, batch.pngs) if t0 <= s < t1]
        lines = [r for r in rows if r.t0 < t1 and r.t1 > t0]
        if not selected and not lines:
            continue
        bounds = [(s, min(clip.t1, math.nextafter(s, math.inf))) for s, _ in selected] + [
            (r.t0, r.t1) for r in lines
        ]
        content = [
            {"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(p).decode()}}
            for _, p in selected
        ]
        if lines:
            content.append({"type": "text", "text": "Transcript:\n" + "\n".join(
                f"[{r.t0:g}-{r.t1:g}] {r.text}" for r in lines)})
        messages = [{"role": "system", "content": system}, {"role": "user", "content": content}]
        jobs.append((min(a for a, _ in bounds), max(b for _, b in bounds),
                     engine.submit(messages, CAPTION_MAX_TOKENS)))
    current = [TextRecord(a, b, f.result().strip() or "(no caption)") for a, b, f in jobs]
    context["caption_10s"] = [r.__dict__ for r in current]
    for layer, seconds in LAYERS.items():
        prompt = summary_prompt(profile, layer, seconds)
        groups = {}
        for row in current:
            groups.setdefault(int(row.t0 // seconds), []).append(row)
        futures = []
        for children in groups.values():
            text = "\n".join(f"[{r.t0:g}-{r.t1:g}] {r.text}" for r in children)
            messages = [{"role": "system", "content": prompt}, {"role": "user", "content": text}]
            futures.append((children, engine.submit(messages, SUMMARY_MAX_TOKENS)))
        current = [
            TextRecord(min(r.t0 for r in ch), max(r.t1 for r in ch), f.result().strip() or "(empty)")
            for ch, f in futures
        ]
        context[layer] = [r.__dict__ for r in current]
    return context


def _build_duration(video_path, memory_dir, video_id, duration, use_asr=True, profile="general"):
    return int(min(200, 25 + 0.55 * duration))


@spaces.GPU(duration=_build_duration)
def build_memory_gpu(video_path, memory_dir, video_id, duration, use_asr=True, profile="general"):
    engine = SubmodelEngine()
    try:
        context = build_context(engine, video_path, video_id, duration, use_asr, profile)
    finally:
        engine.close()
    memory_dir = Path(memory_dir)
    (memory_dir / "contexts").mkdir(parents=True, exist_ok=True)
    (memory_dir / "contexts" / f"{video_id}.clips.json").write_text(json.dumps(
        [{"path": f"{video_id}.mp4", "t0": 0.0, "t1": duration}]))
    (memory_dir / "contexts" / f"{video_id}.json").write_text(json.dumps(context, ensure_ascii=False))
    return context


# ---------------------------------------------------------------------------
# Answering: the original PMM agent loop (pmm.agent.Agent) + sandboxed REPL worker
# ---------------------------------------------------------------------------
def _answer_duration(memory_dir, video_id, question, options, max_turns=10):
    return int(min(200, 30 + 8 * int(max_turns)))


@spaces.GPU(duration=_answer_duration)
def answer_gpu(memory_dir, video_id, question, options, max_turns=10):
    budget = _answer_duration(memory_dir, video_id, question, options, max_turns) - 12
    engine = SubmodelEngine()
    server, url = start_server(engine)
    events: queue.Queue = queue.Queue()
    done = object()
    holder = {}

    def run():
        EVENTS.set(events)
        try:
            agent = Agent(
                LocalRoot(), memory=MemoryStore(memory_dir), submodel=Submodel(url=url),
                settings=Settings(max_turns=int(max_turns), question_s=budget, execute_s=budget),
            )
            question_obj = Question("demo", video_id, question, options)
            with tempfile.TemporaryDirectory() as trace_dir:
                holder["answer"] = asyncio.run(agent.answer(question_obj, trace_dir=Path(trace_dir)))
        except Exception as exc:  # noqa: BLE001
            holder["error"] = f"{type(exc).__name__}: {exc}"
        finally:
            events.put(done)

    thread = threading.Thread(target=run, daemon=True)
    thread.start()
    try:
        while True:
            event = events.get()
            if event is done:
                break
            yield event
    finally:
        thread.join(timeout=5)
        server.shutdown()
        engine.close()
    answer = holder.get("answer")
    if answer is None:
        yield ("final", None, "error", 0, holder.get("error", "unknown error"))
    else:
        yield ("final", answer.letter, answer.terminal, answer.turns, answer.error)


# ---------------------------------------------------------------------------
# UI glue
# ---------------------------------------------------------------------------
def _fmt(t):
    t = int(t)
    return f"{t // 60:d}:{t % 60:02d}"


def memory_markdown(context):
    if not context:
        return ""
    parts = []
    video = context["video"]
    parts.append(
        f"**Video:** {video['duration_s']:.0f} s · **ASR:** {len(context.get('asr', []))} segments · "
        f"**10 s captions:** {len(context.get('caption_10s', []))}"
    )
    for key, title in [("caption_3min", "3-min summary"), ("caption_30s", "30 s layer"),
                       ("caption_10s", "10 s captions"), ("asr", "Transcript")]:
        rows = context.get(key) or []
        if not rows:
            continue
        parts.append(f"\n#### {title}")
        for r in rows:
            parts.append(f"- **[{_fmt(r['t0'])}–{_fmt(r['t1'])}]** {r['text']}")
    return "\n".join(parts)


def _sha(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def ask(
    video: str,
    question: str,
    option_a: str,
    option_b: str,
    option_c: str = "",
    option_d: str = "",
    max_turns: int = 10,
    use_asr: bool = True,
    profile: str = "general",
):
    """Answer a multiple-choice question about a video with Programmatic Multimodal Memory.

    PMM first writes a temporal memory of the video (10 s captions + ASR, summarised into
    30 s / 3 min / 10 min / 1 h layers), then the PMM-9B Root writes Python in a REPL to search
    that memory, calling `see` (Qwen3-VL-8B on raw frames) and `llm_query` when needed.

    Args:
        video: path to a video file (only the first 5 minutes are used).
        question: the question about the video.
        option_a: answer option A.
        option_b: answer option B.
        option_c: answer option C (optional).
        option_d: answer option D (optional; needs C).
        max_turns: maximum number of Root REPL turns.
        use_asr: transcribe speech with distil-whisper and add it to the memory.
        profile: caption prompt profile, "general" or "egocentric".

    Returns:
        (answer markdown, reasoning trace messages, memory markdown)
    """
    if not video:
        raise gr.Error("Please upload a video.")
    if not question or not question.strip():
        raise gr.Error("Please enter a question.")
    raw = [option_a, option_b, option_c, option_d]
    options = {}
    for letter, text in zip("ABCD", raw):
        text = (text or "").strip()
        if not text:
            break
        options[letter] = text
    if len(options) < 2:
        raise gr.Error("Please give at least options A and B (options are filled in order A, B, C, D).")

    trace = []
    duration = min(video_duration(video), MAX_SECONDS)
    key = hashlib.sha256(f"{_sha(video)}|{use_asr}|{profile}".encode()).hexdigest()[:16]
    video_id = f"video_{key}"
    memory_dir = MEMORY_ROOT / key
    context_path = memory_dir / "contexts" / f"{video_id}.json"
    videos_dir = memory_dir / "videos"
    videos_dir.mkdir(parents=True, exist_ok=True)
    if not (videos_dir / f"{video_id}.mp4").exists():
        shutil.copy(video, videos_dir / f"{video_id}.mp4")

    t_start = time.perf_counter()
    if context_path.exists():
        context = json.loads(context_path.read_text())
    else:
        yield "⏳ **Step 1/2 — writing the temporal memory** (captions every 10 s + summaries)…", trace, ""
        context = build_memory_gpu(str(videos_dir / f"{video_id}.mp4"), str(memory_dir), video_id,
                                   duration, bool(use_asr), profile)
    t_mem = time.perf_counter() - t_start
    mem_md = memory_markdown(context)
    yield f"⏳ **Step 2/2 — the Root is reading the memory with code…** (memory ready in {t_mem:.0f} s)", trace, mem_md

    t_answer = time.perf_counter()
    status = "⏳ Root is thinking…"
    for event in answer_gpu(str(memory_dir), video_id, question.strip(), options, int(max_turns)):
        kind = event[0]
        if kind == "root":
            _, turn, text = event
            trace.append({"role": "assistant", "content": text.strip() or "(empty)",
                          "metadata": {"title": f"🧠 Root · turn {turn}"}})
            status = f"⏳ Root turn {turn}: executing code in the REPL…"
        elif kind == "repl":
            _, code, output, final = event
            shown = output if len(output) < 6000 else output[:6000] + f"\n… [{len(output) - 6000} more chars]"
            trace.append({"role": "user", "content": f"```text\n{shown.strip() or '(no output)'}\n```",
                          "metadata": {"title": "🖥️ REPL output"}})
            status = "⏳ Root is reading the REPL output…"
        elif kind == "final":
            _, letter, terminal, turns, error = event
            elapsed = time.perf_counter() - t_answer
            if letter:
                status = (f"### Answer: **{letter}. {options[letter]}**\n\n"
                          f"<sub>{terminal} after {turns} Root turn(s) · reasoning {elapsed:.0f} s · "
                          f"memory {t_mem:.0f} s</sub>")
            else:
                status = f"### No answer\n\nTerminal state: `{terminal}`" + (f" — {error}" if error else "")
        yield status, trace, mem_md


# ---------------------------------------------------------------------------
# Layout
# ---------------------------------------------------------------------------
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
#memory-box { max-height: 520px; overflow-y: auto; }
"""

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# Programmatic Multimodal Memory (PMM)\n"
            "Ask a multiple-choice question about a video. PMM writes a **timestamped caption memory** of the "
            "video, then the trained **PMM-9B Root** writes Python in a REPL to search it, looking at raw frames "
            "with `see` (Qwen3-VL-8B) only when the captions are not enough.\n\n"
            "[Paper](https://huggingface.co/papers/2611.41408) · [Code](https://github.com/Shadow-Weave/PMM) · "
            "[PMM-9B](https://huggingface.co/Shadow-Weave/PMM-9B) · "
            "[Project page](https://shadow-weave.github.io/PMM/)"
        )
        with gr.Row():
            with gr.Column(scale=5):
                video = gr.Video(label="Video (first 5 minutes are used)", height=300)
                question = gr.Textbox(label="Question", placeholder="What happens right after …?")
                with gr.Row():
                    option_a = gr.Textbox(label="A")
                    option_b = gr.Textbox(label="B")
                with gr.Row():
                    option_c = gr.Textbox(label="C (optional)")
                    option_d = gr.Textbox(label="D (optional)")
                run = gr.Button("Ask PMM", variant="primary")
                with gr.Accordion("Advanced settings", open=False):
                    max_turns = gr.Slider(2, 20, value=10, step=1, label="Max Root turns (paper: 20)")
                    use_asr = gr.Checkbox(value=True, label="Transcribe speech (distil-whisper) into the memory")
                    profile = gr.Radio(["general", "egocentric"], value="general", label="Caption profile")
            with gr.Column(scale=6):
                answer = gr.Markdown("The answer will appear here.")
                with gr.Tabs():
                    with gr.Tab("Reasoning with code"):
                        trace = gr.Chatbot(label="Root ↔ REPL trace", height=520, show_label=False)
                    with gr.Tab("Temporal memory"):
                        memory = gr.Markdown(elem_id="memory-box")

        inputs = [video, question, option_a, option_b, option_c, option_d, max_turns, use_asr, profile]
        outputs = [answer, trace, memory]
        run.click(ask, inputs=inputs, outputs=outputs, api_name="ask")

        gr.Examples(
            examples=[
                ["examples/kitchen_day.mp4", "What does the person do right after frothing milk with the steam wand?",
                 "Pours honey on a spoon", "Pours coffee over a glass of ice", "Kneads bread dough", "Slices a zucchini"],
                ["examples/kitchen_day.mp4", "Which food is poured into a red silicone mold?",
                 "Melted chocolate", "Honey", "Milk", "Pancake batter"],
                ["examples/nature_walk.mp4", "Which animal appears in black-and-white footage?",
                 "A border collie", "A squirrel", "A pelican", "A horse"],
                ["examples/nature_walk.mp4", "What is the squirrel doing when it appears?",
                 "Burying a nut in the snow", "Nibbling food while sitting on a branch",
                 "Jumping between trees", "Running across a lawn"],
            ],
            inputs=[video, question, option_a, option_b, option_c, option_d],
            outputs=outputs,
            fn=ask,
            cache_examples=True,
            cache_mode="lazy",
        )
        gr.Markdown(
            "<sub>Demo port: the Root runs with 🤗 transformers greedy decoding instead of SGLang, the "
            "submodel/memory writer is Qwen3-VL-8B-Instruct (the paper's frozen submodel) instead of the default "
            "27B writer, and ASR uses distil-whisper-large-v3.5 via transformers. The Root's code runs in the "
            "original PMM REPL worker subprocess. Example clips: CC0 videos from "
            "[linoyts/repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).</sub>"
        )

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=2).launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)