File size: 37,239 Bytes
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e32d01d
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e32d01d
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560345f
 
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
560345f
64f1078
 
 
 
 
 
 
 
560345f
 
 
 
 
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560345f
 
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560345f
 
 
64f1078
e32d01d
 
 
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728e2fc
64f1078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728e2fc
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
"""Sage-Interaction on ZeroGPU.

A turn-based port of the official full-duplex demo (github.com/InternLM/Sage-Interaction/demo).
The user's speech (or typed message) is streamed into the native MiniCPM-o duplex session in
1-second units, exactly like the browser client does, followed by silent units so the model can
decide when to speak, delegate a task to a backend, or wait for a timed reminder.
"""

import os

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

import importlib.util
import json
import math
import random
import re
import shutil
import sys
import tempfile
import time
import uuid

import spaces  # noqa: E402  (must precede torch)
import gradio as gr
import numpy as np
import torch
from huggingface_hub import hf_hub_download, snapshot_download

HERE = os.path.dirname(os.path.abspath(__file__))
MODEL_ID = "internlm/Sage-Interaction"
SEED = 20261028
CHUNK = 16000  # one second of 16 kHz input per unit (config.example.json: chunk_samples)
OUT_SR = 24000
MAX_INPUT_SECONDS = 45
MAX_REMINDER_SECONDS = 60
MAX_UNITS = 150
BACKEND_MAX_CHARS = 180
FRONTEND_PROMPT = open(os.path.join(HERE, "frontend.txt")).read()
BACKEND_PROMPT = open(os.path.join(HERE, "backend.txt")).read().replace("{{MAX_CHARS}}", str(BACKEND_MAX_CHARS))


# --------------------------------------------------------------------------------------
# StepAudio2 Token2wav: apply the demo's two patches (scripts/prepare_environment.py) to a
# private copy of the installed package, so we never edit site-packages in place.
# --------------------------------------------------------------------------------------
def _prepare_stepaudio2():
    spec = importlib.util.find_spec("stepaudio2")
    src = os.path.dirname(spec.origin)
    root = os.path.join(tempfile.gettempdir(), "sage_vendor")
    dst = os.path.join(root, "stepaudio2")
    if os.path.exists(dst):
        shutil.rmtree(dst)
    shutil.copytree(src, dst)
    with open(os.path.join(dst, "__init__.py"), "w") as f:
        f.write('"""Minimal Token2wav entry point used by the demo."""\nfrom .token2wav import Token2wav\n\n__all__ = ["Token2wav"]\n')
    path = os.path.join(dst, "token2wav.py")
    code = open(path).read()
    a = "        # update vocoder cache\n"
    b = "        if not last_chunk:\n            speech = speech[:, :-self.source_cache_len]\n"
    assert code.count(a) == 1 and code.count(b) == 1, "unexpected stepaudio2 version"
    code = code.replace(a, "        is_first_chunk = hift_cache_speech.shape[-1] == 0\n\n" + a)
    code = code.replace(
        b,
        b
        + "            if is_first_chunk:\n"
        + "                silence = speech.new_zeros(1, self.source_cache_len)\n"
        + "                speech = torch.cat([silence, speech], dim=1)\n",
    )
    open(path, "w").write(code)
    sys.path.insert(0, root)


_prepare_stepaudio2()


def _patch_whisper_attention():
    """Bridge the transformers 4.51 Whisper signature used by MiniCPM-o (sage_demo/model.py)."""
    import inspect
    from transformers.models.whisper.modeling_whisper import WhisperAttention

    if "past_key_values" in inspect.signature(WhisperAttention.forward).parameters:
        return
    original = WhisperAttention.forward

    def patched(self, *args, past_key_values=None, **kwargs):
        kwargs.setdefault("past_key_value", past_key_values)
        result = original(self, *args, **kwargs)
        return result[:2] if isinstance(result, tuple) and len(result) > 2 else result

    WhisperAttention.forward = patched


# --------------------------------------------------------------------------------------
# Model (module scope, eager .to("cuda") — ZeroGPU packs it at startup)
# --------------------------------------------------------------------------------------
from transformers import AutoModel  # noqa: E402

CKPT = snapshot_download(MODEL_ID, ignore_patterns=["*.png", "*.DS_Store", "*.md"])
DEFAULT_VOICE = hf_hub_download("openbmb/MiniCPM-o-4_5", "assets/system_ref_audio.wav")

_patch_whisper_attention()
base = (
    AutoModel.from_pretrained(
        CKPT,
        trust_remote_code=True,
        attn_implementation="sdpa",
        torch_dtype=torch.bfloat16,
        init_tts=True,
    )
    .eval()
    .to("cuda")
)
base.prepare_processor()  # CPU-only: tokenizer + audio/image processors
base.init_tts(model_dir=os.path.join(CKPT, "assets", "token2wav"))  # Token2wav (flow + HiFT) on GPU
TOKEN2WAV = base.tts.audio_tokenizer
TOKENIZER = base.processor.tokenizer
IM_END = TOKENIZER.convert_tokens_to_ids("<|im_end|>")
print("Sage-Interaction loaded", flush=True)


# --------------------------------------------------------------------------------------
# Ported from sage_demo/streaming_actions.py (native duplex action decoding)
# --------------------------------------------------------------------------------------
def configure_speech_completion(duplex, final_max_tokens):
    native_generate = duplex.model.tts.generate_chunk

    def _generate_chunk(*args, **kwargs):
        if duplex.current_turn_ended:
            kwargs["max_new_token"] = max(kwargs["max_new_token"], final_max_tokens)
        return native_generate(*args, **kwargs)

    duplex.model.tts.generate_chunk = _generate_chunk


def observe_tts_termination(tts, generate, *args, **kwargs):
    termination = {"speech_eos_reached": False}
    previous = sys.getprofile()

    def _observe(frame, event, result):
        if previous is not None:
            previous(frame, event, result)
        if event != "return" or frame.f_code.co_name != "generate_chunk":
            return
        values = frame.f_locals
        if values.get("self") is tts and "finish" in values and "t" in values:
            termination["speech_eos_reached"] = bool(values["finish"].all().item())

    sys.setprofile(_observe)
    try:
        tokens, cache = generate(*args, **kwargs)
    finally:
        sys.setprofile(previous)
    return tokens, cache, termination


def reset_speech_turn(duplex, *, close_language_turn=False):
    if close_language_turn and not duplex.current_turn_ended:
        ids = [
            duplex.unit_token_id,
            duplex.speak_token_id,
            duplex.turn_eos_token_id,
            duplex.chunk_eos_token_id,
            int(duplex.tokenizer.convert_tokens_to_ids("</unit>")),
        ]
        duplex.decoder.feed(duplex.decoder.embed_tokens(ids))
        duplex.total_ids.extend(ids)
        duplex.total_hidden.append([])
        duplex.decoder.register_unit_end(input_type="audio", generated_tokens=ids[1:-1], is_listen=False, generated_text="")
    duplex.current_turn_ended = True
    duplex.tts_text_start_pos = 0
    duplex.tts_past_key_values = None
    duplex.tts_current_turn_start_time = None
    duplex._reset_token2wav_for_new_turn()


def generate_control_action(duplex, native_generate, generation_kwargs, max_query_tokens=256):
    """allow_interruption=True, native_action_policy=True (config.example.json)."""
    tokenizer = duplex.tokenizer
    action_ids = {n: int(tokenizer.convert_tokens_to_ids(f"<|{n}|>")) for n in ("listen", "speak", "delegate")}
    if duplex.pending_logits is None:
        return {"action": "listen", "is_listen": True, "text": "", "end_of_turn": False}
    if duplex.is_session_stop_set() or duplex.is_break_set() or duplex._streaming_generate_count < duplex.force_listen_count:
        return native_generate(**generation_kwargs)
    native_decode = duplex.decoder.decode
    first_token = native_decode(
        logits=duplex.pending_logits,
        mode=generation_kwargs.get("decode_mode", "sampling"),
        temperature=generation_kwargs.get("temperature", 0.7),
        top_k=generation_kwargs.get("top_k", 100),
        top_p=generation_kwargs.get("top_p", 0.8),
        listen_top_k=generation_kwargs.get("listen_top_k"),
        listen_prob_scale=generation_kwargs.get("listen_prob_scale", 1.0),
        text_repetition_penalty=generation_kwargs.get("text_repetition_penalty", 1.05),
        text_repetition_window_size=generation_kwargs.get("text_repetition_window_size", 512),
    )
    selected = {t: n for n, t in action_ids.items()}.get(int(first_token.item()), "speak")
    interrupted = not bool(duplex.current_turn_ended) and selected != "speak"
    if interrupted:
        reset_speech_turn(duplex)
    if selected != "delegate":
        first_pending = True

        def _decode(*args, **kwargs):
            nonlocal first_pending
            if first_pending:
                first_pending = False
                return first_token
            return native_decode(*args, **kwargs)

        duplex.decoder.decode = _decode
        try:
            result = native_generate(**generation_kwargs)
        finally:
            duplex.decoder.decode = native_decode
        result["action"] = selected
        result["speech_interrupted"] = interrupted
        return result

    duplex.pending_logits = None
    delegate_id = action_ids["delegate"]
    duplex.total_ids.append(delegate_id)
    logits, _ = duplex.decoder.feed(duplex.decoder.embed_token(delegate_id), return_logits=True)
    payload_ids = []
    for token_id in tokenizer.encode('{"query":"', add_special_tokens=False):
        payload_ids.append(int(token_id))
        logits, _ = duplex.decoder.feed(duplex.decoder.embed_token(int(token_id)), return_logits=True)
    query_ids = []
    forbidden = {
        *action_ids.values(),
        int(duplex.chunk_eos_token_id),
        int(duplex.turn_eos_token_id),
        int(tokenizer.convert_tokens_to_ids("</unit>")),
        int(duplex.tts_bos_token_id),
    }
    for _ in range(max_query_tokens):
        next_id = int(
            duplex.decoder.decode(
                logits=logits, mode="greedy", temperature=0.7, top_k=100, top_p=0.8,
                listen_prob_scale=1.0, text_repetition_penalty=1.05, text_repetition_window_size=512,
            ).item()
        )
        piece = tokenizer.decode([next_id], skip_special_tokens=False)
        if next_id in forbidden or any(c in piece for c in ('"', "\\", "\n", "\r", "{", "}")):
            break
        query_ids.append(next_id)
        payload_ids.append(next_id)
        logits, _ = duplex.decoder.feed(duplex.decoder.embed_token(next_id), return_logits=True)
    query_text = tokenizer.decode(query_ids, skip_special_tokens=True).strip()
    for token_id in tokenizer.encode('"}', add_special_tokens=False):
        payload_ids.append(int(token_id))
        logits, _ = duplex.decoder.feed(duplex.decoder.embed_token(int(token_id)), return_logits=True)
    chunk_eos, unit_end = int(duplex.chunk_eos_token_id), int(tokenizer.convert_tokens_to_ids("</unit>"))
    duplex.decoder.feed(duplex.decoder.embed_token(chunk_eos))
    duplex.decoder.feed(duplex.decoder.embed_token(unit_end))
    duplex.total_ids.extend(payload_ids + [chunk_eos, unit_end])
    duplex.current_turn_ended = True
    duplex.total_hidden.append([])
    text = json.dumps({"query": query_text}, ensure_ascii=False, separators=(",", ":"))
    duplex.decoder.register_unit_end(
        input_type=duplex.current_mode.lower() if duplex.current_mode else "audio",
        generated_tokens=payload_ids, is_listen=False, generated_text=text,
    )
    return {"action": "delegate", "is_listen": False, "text": text, "audio_waveform": None,
            "end_of_turn": True, "speech_interrupted": interrupted}


def inject_tool_result(duplex, event):
    ids = duplex.tokenizer.encode(event, add_special_tokens=False)
    duplex.decoder.feed(duplex.decoder.embed_tokens(ids))
    duplex.total_ids.extend(int(t) for t in ids)


def align_voice_prefill(duplex, tokenizer):
    """Match the voice collator's <unit><|audio_start|>[audio]<|audio_end|> layout (no timestamps)."""
    original_prefill = duplex.streaming_prefill
    original_feed = duplex.decoder.feed
    audio_start = int(tokenizer.convert_tokens_to_ids("<|audio_start|>"))
    audio_end = int(tokenizer.convert_tokens_to_ids("<|audio_end|>"))
    state = {"inside": False, "feeds": 0}

    def _feed(embeddings, *args, **kwargs):
        if not state["inside"]:
            return original_feed(embeddings, *args, **kwargs)
        state["feeds"] += 1
        if state["feeds"] == 1:
            return original_feed(embeddings, *args, **kwargs)
        original_feed(duplex.decoder.embed_token(audio_start))
        original_feed(embeddings, *args, **kwargs)
        return original_feed(duplex.decoder.embed_token(audio_end), return_logits=kwargs.get("return_logits", False))

    def _prefill(audio_waveform, **kwargs):
        state["inside"], state["feeds"] = True, 0
        try:
            result = original_prefill(audio_waveform=audio_waveform, **kwargs)
        finally:
            state["inside"] = False
        if result["success"]:
            marker = duplex._current_unit_prefill_tokens[-1]
            duplex._current_unit_prefill_tokens = [duplex.unit_token_id, audio_start, marker, audio_end]
        return result

    duplex.decoder.feed = _feed
    duplex.streaming_prefill = _prefill


# --------------------------------------------------------------------------------------
# Ported from sage_demo/protocol.py + query_routing.py
# --------------------------------------------------------------------------------------
def delegate_query(text):
    payload = json.loads(text)
    if not isinstance(payload, dict) or set(payload) != {"query"}:
        raise ValueError("bad delegate payload")
    query = payload["query"]
    if not isinstance(query, str) or not query.strip() or len(query) > 6000:
        raise ValueError("bad delegate query")
    return query.strip()


def tool_event(task_id, query, content, status="ok", event_name="", event_id=""):
    payload = dict(type="delegate_result", task_id=task_id, status=status, query=query, content=content)
    if event_name:
        payload["event"] = event_name
    if event_id:
        payload["event_id"] = event_id
    return payload, "<|im_start|>tool\n" + json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "<|im_end|>"


_NUMBERS = dict(one=1, two=2, three=3, four=4, five=5, six=6, seven=7, eight=8, nine=9, ten=10, eleven=11,
                twelve=12, fifteen=15, twenty=20, thirty=30, forty=40, fifty=50, sixty=60)


def parse_timer_request(query):
    text = re.sub(r"^\s*TimeSpeak task:\s*", "", query.strip(), flags=re.IGNORECASE)
    text = re.sub(r"\bhalf an? minute\b", "30 seconds", text, flags=re.IGNORECASE)
    text = re.sub(r"\ban? (minute|second)\b", r"1 \1", text, flags=re.IGNORECASE)
    text = re.sub(r"\b(" + "|".join(_NUMBERS) + r")\b", lambda m: str(_NUMBERS[m.group(1).lower()]), text, flags=re.IGNORECASE)
    for pattern, scale in (
        (r"(?:in|after)\s+(\d+(?:\.\d+)?)\s*(?:seconds?|secs?)\b", 1.0),
        (r"(?:in|after)\s+(\d+(?:\.\d+)?)\s*(?:minutes?|mins?)\b", 60.0),
        (r"(\d+(?:\.\d+)?)\s*(?:seconds?|secs?)\s+(?:later|from now)\b", 1.0),
        (r"(\d+(?:\.\d+)?)\s*(?:minutes?|mins?)\s+(?:later|from now)\b", 60.0),
    ):
        match = re.search(pattern, text, flags=re.IGNORECASE)
        if match:
            delay = float(match.group(1)) * scale
            return delay if 0 < delay <= 86400 else None
    return None


class SpokenQueryRouter:
    """Buffer a possible spoken tool envelope at the start of a speech turn."""

    def __init__(self):
        self.reset()

    def reset(self):
        self.mode, self.text, self.audio = "prefix", "", []

    def route(self, result, audio):
        original = result["text"]
        if result.get("speech_interrupted", False):
            self.reset()
        if result["action"] != "speak":
            self.reset()
            return result, audio
        if self.mode == "speech":
            if result["end_of_turn"]:
                self.reset()
            return result, audio
        self.text += original
        if audio is not None and audio.size:
            self.audio.append(audio)
        body = self.text.lstrip()
        compact = re.sub(r"\s+", "", body)
        if body.startswith("```"):
            body = body[3:]
            if body.startswith("json"):
                body = body[4:]
            body = body.lstrip()
        header = re.match(r'^\{\s*"query"\s*:', body)
        possible = '{"query":'.startswith(compact) or "```json".startswith(compact) or "```".startswith(compact)
        if compact.startswith("```json"):
            possible = '{"query":'.startswith(compact[7:])
        elif compact.startswith("```") and not "```json".startswith(compact):
            possible = '{"query":'.startswith(compact[3:])
        if header is not None:
            self.mode = "query"
        if self.mode != "query" and (not possible or result["end_of_turn"]):
            released = dict(result, text=self.text)
            waveform = np.concatenate(self.audio) if self.audio else None
            self.reset()
            self.mode = "prefix" if result["end_of_turn"] else "speech"
            return released, waveform
        state, payload = "buffering", None
        if self.mode == "query":
            try:
                value, _ = json.JSONDecoder().raw_decode(body)
            except json.JSONDecodeError:
                value = None
            if value is not None:
                try:
                    payload = json.dumps({"query": delegate_query(json.dumps(value))}, ensure_ascii=False)
                    state = "rerouted"
                except ValueError:
                    state = "rejected"
            elif result["end_of_turn"] or len(self.text) > 6000:
                state = "rejected"
        elif len(self.text) > 6000:
            state = "rejected"
        routed = dict(result, action="delegate" if payload else "listen", text=payload or "", routing=state)
        if state != "buffering":
            routed.update(end_of_turn=True, speech_complete=True)
            self.reset()
        else:
            routed.update(speech_complete=False)
        return routed, None


# --------------------------------------------------------------------------------------
# Backend for delegated tasks
# --------------------------------------------------------------------------------------
def _parse_content(raw):
    raw = (raw or "").strip()
    raw = re.sub(r"^```(?:json)?|```$", "", raw).strip()
    try:
        value = json.loads(raw)
        if isinstance(value, dict) and isinstance(value.get("content"), str):
            return value["content"].strip()
    except Exception:
        pass
    m = re.search(r'"content"\s*:\s*"((?:[^"\\]|\\.)*)', raw)
    return (m.group(1) if m else raw).strip()


def _remote_backend(task_id, query):
    """The authors' backend is DeepSeek-V4.1-Flash; used when the Space has an HF_TOKEN secret."""
    import httpx

    r = httpx.post(
        "https://router.huggingface.co/v1/chat/completions",
        headers={"Authorization": "Bearer " + os.environ["HF_TOKEN"]},
        json=dict(
            model="deepseek-ai/DeepSeek-V4.1-Flash",
            messages=[
                dict(role="system", content=BACKEND_PROMPT),
                dict(role="user", content=json.dumps(dict(type="delegate", task_id=task_id, query=query), ensure_ascii=False)),
            ],
            max_tokens=2048,
            temperature=0.3,
        ),
        timeout=60,
    )
    r.raise_for_status()
    return _parse_content(r.json()["choices"][0]["message"]["content"]), "DeepSeek-V4.1-Flash"


@torch.inference_mode()
def _local_backend(task_id, query, max_new_tokens=160):
    """Fallback: answer with the Sage LLM tower itself, in plain text-chat mode."""
    from transformers.cache_utils import DynamicCache

    prompt = (
        f"<|im_start|>system\n{BACKEND_PROMPT}<|im_end|>\n<|im_start|>user\n"
        + json.dumps(dict(type="delegate", task_id=task_id, query=query), ensure_ascii=False)
        + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
    )
    ids = torch.tensor([TOKENIZER.encode(prompt, add_special_tokens=False)], device="cuda")
    cache = DynamicCache()
    out = []
    for _ in range(max_new_tokens):
        logits = base.llm(input_ids=ids, past_key_values=cache, use_cache=True).logits[:, -1]
        nxt = int(logits.argmax(-1).item())
        if nxt == IM_END or nxt == TOKENIZER.eos_token_id:
            break
        out.append(nxt)
        ids = torch.tensor([[nxt]], device="cuda")
    return _parse_content(TOKENIZER.decode(out, skip_special_tokens=True)), "Sage LLM (local)"


def run_backend(task_id, query):
    if os.environ.get("HF_TOKEN"):
        try:
            content, who = _remote_backend(task_id, query)
            if content:
                return content[:BACKEND_MAX_CHARS], who
        except Exception as e:  # fall back to the local tower
            print("remote backend failed:", repr(e), flush=True)
    content, who = _local_backend(task_id, query)
    return (content or "Sorry, I could not work that out.")[:BACKEND_MAX_CHARS], who


# --------------------------------------------------------------------------------------
# Session
# --------------------------------------------------------------------------------------
def _new_session(voice_path):
    for attr in ("generate_chunk",):  # undo wrappers left by a previous call in a warm worker
        base.tts.__dict__.pop(attr, None)
    base.init_tts = lambda **kwargs: TOKEN2WAV  # reuse the loaded Token2wav (sage_demo/model.py)
    try:
        duplex = base.as_duplex(device="cuda", generate_audio=True)
    finally:
        base.__dict__.pop("init_tts", None)

    random.seed(SEED)
    np.random.seed(SEED)
    torch.manual_seed(SEED)
    torch.cuda.manual_seed_all(SEED)
    calls = {"n": 0, "step": []}
    native_tts = base.tts.generate_chunk

    def _tts(*args, **kwargs):
        with torch.random.fork_rng(devices=[torch.cuda.current_device()]):
            torch.cuda.manual_seed(SEED + calls["n"])
            tokens, cache, term = observe_tts_termination(base.tts, native_tts, *args, **kwargs)
        calls["step"].append(term)
        calls["n"] += 1
        return tokens, cache

    base.tts.generate_chunk = _tts
    configure_speech_completion(duplex, 128)

    base.audio_past_key_values = None
    TOKEN2WAV.cache, TOKEN2WAV.stream_cache, TOKEN2WAV.hift_cache_dict = None, None, {}
    duplex.prepare(prefix_system_prompt=FRONTEND_PROMPT, prompt_wav_path=voice_path)
    base.audio_past_key_values = None
    native_prefill = duplex.streaming_prefill
    align_voice_prefill(duplex, duplex.tokenizer)
    return duplex, native_prefill, calls


def _step(duplex, native_prefill, calls, voice_path, waveform, text, deliveries, interrupt):
    calls["step"] = []
    if interrupt:
        reset_speech_turn(duplex, close_language_turn=True)
    for event in deliveries:
        inject_tool_result(duplex, event)
    if text:
        r = native_prefill(text_list=[text], max_slice_nums=1)
        if not r.get("success"):
            raise RuntimeError(f"text prefill failed: {r}")
    r = duplex.streaming_prefill(audio_waveform=waveform)
    if not r.get("success"):
        raise RuntimeError(f"audio prefill failed: {r}")
    out = generate_control_action(
        duplex,
        duplex.streaming_generate,
        dict(prompt_wav_path=voice_path, max_new_speak_tokens_per_chunk=20, decode_mode="greedy",
             temperature=0.0, top_k=100, top_p=1.0),
        256,
    )
    audio = out.pop("audio_waveform", None)
    if audio is not None:
        audio = audio.detach().float().cpu().numpy() if isinstance(audio, torch.Tensor) else np.asarray(audio)
        audio = np.asarray(audio, dtype=np.float32).reshape(-1)
    action = out.get("action", "listen" if out.get("is_listen") else "speak")
    end = bool(out.get("end_of_turn"))
    return dict(
        action=action,
        text=out.get("text", "") or "",
        end_of_turn=end,
        speech_interrupted=bool(out.get("speech_interrupted", False)),
        speech_complete=end and bool(calls["step"]) and all(c["speech_eos_reached"] for c in calls["step"]),
    ), audio


def _load_audio(path):
    import librosa

    wav, _ = librosa.load(path, sr=16000, mono=True, duration=MAX_INPUT_SECONDS)
    wav = np.clip(np.asarray(wav, dtype=np.float32), -1, 1)
    peak = float(np.max(np.abs(wav))) if wav.size else 0.0
    if 0 < peak < 0.3:  # gentle normalisation for quiet mic recordings
        wav = wav * (0.5 / peak)
    return wav


def _duration(text="", audio=None, voice=None, tail_seconds=20, *args, **kwargs):
    secs = 0.0
    if audio:
        try:
            import soundfile as sf

            secs = min(MAX_INPUT_SECONDS, sf.info(audio).duration)
        except Exception:
            secs = MAX_INPUT_SECONDS
    reminder = MAX_REMINDER_SECONDS if text and parse_timer_request(text) else 0
    return int(min(180, 20 + 1.0 * (secs + int(tail_seconds)) + 0.4 * reminder))


def _fmt(t):
    return f"{int(t) // 60:02d}:{int(t) % 60:02d}"


@spaces.GPU(duration=_duration)
def converse(text: str = "", audio: str | None = None, voice: str | None = None, tail_seconds: int = 20):
    """Talk to Sage-Interaction for one turn.

    The input (typed message and/or recorded speech) is streamed into the model's native
    full-duplex session one second at a time, followed by silent seconds. In each second the
    model chooses to listen, speak, or delegate a task to a backend; delegated results and timed
    reminders are injected back into the live session.

    Args:
        text: Typed message to the assistant (optional if audio is given).
        audio: Path to a recording of your speech (16 kHz or any rate; first 45 s used).
        voice: Optional voice-reference WAV for the assistant's voice.
        tail_seconds: How many silent seconds to keep listening after the input ends.

    Returns:
        (reply speech as (sr, waveform), conversation mix as (sr, waveform), transcript markdown)
    """
    text = (text or "").strip()[:3000]
    if not text and not audio:
        raise gr.Error("Type a message or record/upload some speech first.")
    voice_path = voice or DEFAULT_VOICE
    started = time.perf_counter()
    budget = _duration(text, audio, voice, tail_seconds)

    units = []
    if text:
        units.append(("text", text, np.zeros(CHUNK, dtype=np.float32)))
    user_wav = None
    if audio:
        user_wav = _load_audio(audio)
        n = max(1, math.ceil(len(user_wav) / CHUNK))
        padded = np.zeros(n * CHUNK, dtype=np.float32)
        padded[: len(user_wav)] = user_wav
        for i in range(n):
            units.append(("audio", "", padded[i * CHUNK : (i + 1) * CHUNK]))
    first_audio_unit = 1 if text else 0
    tail = int(tail_seconds)

    log, speech = [], []  # speech: (unit_index, waveform)
    reply_text, current_line = [], ""
    with torch.inference_mode():
        duplex, native_prefill, calls = _new_session(voice_path)
        router = SpokenQueryRouter()
        native_speaking = awaiting_ack = False
        speech_complete = True
        query_reset = False
        pending = []  # dicts: ready_unit, event, label
        deadline = len(units) + tail
        spoke = False
        quiet = 0
        turn_done = False  # a reply finished and no new input/tool result arrived since
        u = 0
        while u < min(deadline, MAX_UNITS):
            if u < len(units):
                kind, utext, wav = units[u]
            else:
                kind, utext, wav = "silence", "", np.zeros(CHUNK, dtype=np.float32)
            if kind == "text":
                log.append(f"`{_fmt(u)}` 🧑 **You (typed):** {utext}")

            delivered = []
            if not awaiting_ack and not native_speaking and speech_complete:
                for item in [p for p in pending if p["ready_unit"] <= u]:
                    pending.remove(item)
                    delivered.append(item["event"])
                    turn_done = False
                    log.append(f"`{_fmt(u)}` 📥 {item['label']}")

            interrupt = query_reset
            if query_reset:
                router.reset()
                query_reset = False
            result, wave = _step(duplex, native_prefill, calls, voice_path, wav, utext, delivered, interrupt)
            result, wave = router.route(result, wave)
            if (result["action"] == "speak" and u >= len(units) and turn_done
                    and not native_speaking and not pending and not delivered):
                # Nothing new was heard since the last finished reply; in this turn-based port that
                # only happens when the model starts repeating itself, so end the session here.
                break
            routing = result.get("routing")
            if routing in ("rerouted", "rejected"):
                query_reset = True
            action = result["action"]
            native_speaking = routing == "buffering" or (not result["end_of_turn"] and action == "speak")
            if result["speech_interrupted"]:
                awaiting_ack, speech_complete = False, True
            if action == "delegate":
                awaiting_ack = True
            elif action == "speak":
                awaiting_ack = False
                speech_complete = result.get("speech_complete", result["end_of_turn"])
            elif awaiting_ack:
                awaiting_ack = False

            if action == "speak":
                spoke = True
                if result["text"]:
                    current_line += result["text"]
                if wave is not None and wave.size:
                    speech.append((u, wave))
                if result["end_of_turn"]:
                    turn_done = True
                if result["end_of_turn"] and current_line.strip():
                    log.append(f"`{_fmt(u)}` 🤖 **Sage:** {current_line.strip()}")
                    reply_text.append(current_line.strip())
                    current_line = ""
            elif current_line.strip():
                log.append(f"`{_fmt(u)}` 🤖 **Sage:** {current_line.strip()} *(cut)*")
                reply_text.append(current_line.strip())
                current_line = ""

            if action == "delegate":
                try:
                    query = delegate_query(result["text"])
                except ValueError:
                    query = None
                if query:
                    task_id = "task_" + uuid.uuid4().hex[:12]
                    log.append(f"`{_fmt(u)}` 🔀 **Delegated to backend:** {query}")
                    delay = parse_timer_request(query)
                    if delay is not None:
                        if delay > MAX_REMINDER_SECONDS:
                            _, ev = tool_event(task_id, query, f"Reminders can be scheduled at most {MAX_REMINDER_SECONDS} seconds ahead in this demo.", "error")
                            pending.append(dict(ready_unit=u + 1, event=ev, label="Backend: reminder too far ahead"))
                        else:
                            reminder = query if query.lower().startswith("timespeak task:") else "TimeSpeak task: " + query
                            _, ev = tool_event(task_id, query, reminder, "ok", "time_up", "timer_" + task_id)
                            ready = u + 1 + int(math.ceil(delay))
                            pending.append(dict(ready_unit=ready, event=ev, label=f"⏰ Timer fired after {delay:g}s (`time_up`)"))
                            log.append(f"`{_fmt(u)}` ⏳ Timer scheduled for {_fmt(ready)}")
                    else:
                        content, who = run_backend(task_id, query)
                        _, ev = tool_event(task_id, query, content)
                        pending.append(dict(ready_unit=u + 1, event=ev, label=f"**Backend result** ({who}): {content}"))

            # stopping rule: keep listening `tail` seconds after the last input / last delivery
            busy = bool(pending) or native_speaking or awaiting_ack or not speech_complete
            if pending:
                deadline = max(deadline, max(p["ready_unit"] for p in pending) + tail)
            if u >= len(units) - 1:
                quiet = 0 if (busy or action != "listen") else quiet + 1
                if spoke and quiet >= 4 and not pending:
                    break
            if time.perf_counter() - started > budget - 8:  # stay inside the ZeroGPU reservation
                log.append("*(stopped early to stay within the GPU time budget)*")
                break
            u += 1

    if current_line.strip():
        log.append(f"`{_fmt(u)}` 🤖 **Sage:** {current_line.strip()}")
        reply_text.append(current_line.strip())

    # reply speech (concatenated) and a time-aligned mix of user audio + assistant speech
    reply = np.concatenate([w for _, w in speech]) if speech else np.zeros(OUT_SR // 2, dtype=np.float32)
    total = (u + 2) * OUT_SR + sum(len(w) for _, w in speech)
    mix = np.zeros(total, dtype=np.float32)
    if user_wav is not None:
        import librosa

        up = librosa.resample(user_wav, orig_sr=16000, target_sr=OUT_SR)
        start = first_audio_unit * OUT_SR
        mix[start : start + len(up)] += 0.8 * up[: max(0, total - start)]
    cursor = 0
    for unit, w in speech:
        s = max(cursor, (unit + 1) * OUT_SR)  # output of unit i plays once unit i has been heard
        mix[s : s + len(w)] += w[: max(0, total - s)]
        cursor = s + len(w)
    mix = mix[: max(cursor, (u + 1) * OUT_SR)]
    mix = np.clip(mix, -1, 1)

    elapsed = time.perf_counter() - started
    print(f"converse: {u + 1} units, {len(speech)} speech chunks, {elapsed:.1f}s", flush=True)
    if not reply_text and not speech:
        log.append("*(Sage kept listening and did not reply — try a clearer or longer question.)*")
    transcript = "\n\n".join(log) + f"\n\n<sub>{u + 1} one-second units processed in {elapsed:.1f}s</sub>"
    return (OUT_SR, (np.clip(reply, -1, 1) * 32767).astype(np.int16)), (OUT_SR, (mix * 32767).astype(np.int16)), transcript


# --------------------------------------------------------------------------------------
# UI
# --------------------------------------------------------------------------------------
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

with gr.Blocks(title="Sage-Interaction", theme=gr.themes.Citrus(), css=CSS) as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# Sage-Interaction\n"
            "A 9B omni interaction model (built on MiniCPM-o 4.5) that listens to a live stream, decides every second "
            "whether to **listen**, **speak**, or **delegate** a longer task to a backend, and answers in speech. "
            "This Space runs one turn at a time: your message is streamed into the model's native duplex session "
            "second by second, and it keeps listening afterwards so you can hear delegated answers and timed reminders arrive.\n\n"
            "[Model](https://huggingface.co/internlm/Sage-Interaction) · "
            "[GitHub](https://github.com/InternLM/Sage-Interaction) · "
            "[Project page](https://internlm.github.io/Sage-Interaction/)"
        )
        with gr.Row():
            with gr.Column():
                audio_in = gr.Audio(sources=["microphone", "upload"], type="filepath", label="Speak to Sage (up to 45 s)")
                text_in = gr.Textbox(label="…or type a message", placeholder="e.g. Remind me to stretch in 20 seconds.", lines=2)
                run_btn = gr.Button("Send", variant="primary")
            with gr.Column():
                reply_out = gr.Audio(label="Sage's spoken reply", type="numpy", autoplay=True)
                transcript_out = gr.Markdown(label="Conversation timeline")
                mix_out = gr.Audio(label="Full timeline (your input + Sage, time-aligned)", type="numpy")
        with gr.Accordion("Advanced settings", open=False):
            voice_in = gr.Audio(sources=["upload", "microphone"], type="filepath",
                                label="Assistant voice reference (optional, a few seconds of clean speech)")
            tail_in = gr.Slider(5, 40, value=20, step=1, label="Seconds to keep listening after your input")
            gr.Markdown(
                "Delegated tasks are answered by DeepSeek-V4.1-Flash (the authors' backend) when the Space has an "
                "`HF_TOKEN` secret, otherwise by Sage's own language tower. Reminders are capped at 60 s here."
            )

        gr.Examples(
            examples=[
                ["Remind me to stretch in 20 seconds."],
                ["Why is topology so approachable?"],
                ["My blender won't start. It's only 11 months old. Check the warranty, but don't file a claim yet."],
                ["Find a hotel in London for my dog and me. Rated 4.5 or higher, please."],
            ],
            inputs=[text_in],
            outputs=[reply_out, mix_out, transcript_out],
            fn=converse,
            cache_examples=True,
            cache_mode="lazy",
        )

    run_btn.click(converse, inputs=[text_in, audio_in, voice_in, tail_in],
                  outputs=[reply_out, mix_out, transcript_out], api_name="converse")

if __name__ == "__main__":
    demo.launch(mcp_server=True)