Repository navigation
Expand file tree
/
Copy pathwebui.html
More file actions
1488 lines (1464 loc) · 74.9 KB
/
Copy pathwebui.html
File metadata and controls
1488 lines (1464 loc) · 74.9 KB
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RapidSpeech 服务控制台</title>
<style>
:root { --bg:#0f1115; --card:#171a21; --card2:#10131a; --line:#262b36; --fg:#e6e9ef; --mut:#9aa4b2;
--acc:#4f8cff; --ok:#3ecf8e; --warn:#e0a33e; --err:#ff6b6b; --violet:#b59cff; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,
BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; }
header { padding:14px 20px; border-bottom:1px solid var(--line); display:flex;
gap:16px; align-items:center; flex-wrap:wrap; background:var(--card); }
header h1 { font-size:16px; margin:0; font-weight:600; }
header .st { font-size:12px; color:var(--mut); }
header .dot { display:inline-block; width:8px; height:8px; border-radius:50%;
background:var(--err); margin-right:5px; vertical-align:middle; }
header .dot.up { background:var(--ok); }
main { max-width:1440px; margin:0 auto; padding:18px; display:grid;
grid-template-columns:1fr 1fr; gap:16px; }
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px 16px; }
.card h2 { font-size:13px; margin:0 0 10px; color:var(--acc); font-weight:600;
text-transform:uppercase; letter-spacing:.04em; }
.card h2 .tag { float:right; font-size:10px; color:var(--mut); text-transform:none; letter-spacing:0; }
label { display:block; font-size:12px; color:var(--mut); margin:8px 0 3px; }
input[type=text], input[type=number], textarea, select {
width:100%; background:#0d1017; border:1px solid var(--line); color:var(--fg);
border-radius:7px; padding:7px 9px; font:inherit; }
textarea { resize:vertical; min-height:52px; }
input[type=file] { font-size:12px; color:var(--mut); }
button { background:var(--acc); color:#fff; border:0; border-radius:7px;
padding:7px 13px; font:inherit; font-weight:600; cursor:pointer; margin:8px 6px 0 0; }
button.sec { background:#2a3140; }
button.danger { background:#7b3539; }
button:disabled { opacity:.45; cursor:not-allowed; }
.row { display:flex; gap:8px; flex-wrap:wrap; align-items:end; }
.row > * { flex:1; min-width:0; }
.grid2 { display:grid; grid-template-columns:1fr 1fr; gap:8px; }
.grid3 { display:grid; grid-template-columns:repeat(3,1fr); gap:8px; }
.split { display:grid; grid-template-columns:360px minmax(0,1fr); gap:14px; }
.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
.toolbar .push { flex:1; }
.out { margin-top:10px; background:#0b0e14; border:1px solid var(--line);
border-radius:7px; padding:9px 11px; min-height:38px; font-size:13px;
white-space:pre-wrap; word-break:break-word; }
.partial { color:var(--warn); }
.final { color:var(--ok); }
.seg { border-left:2px solid var(--line); padding-left:8px; margin:3px 0; }
.muted { color:var(--mut); font-size:12px; }
.pill { display:inline-flex; align-items:center; height:24px; padding:0 8px;
color:var(--mut); background:var(--card2); border:1px solid var(--line);
border-radius:6px; font-size:11px; font-variant-numeric:tabular-nums; }
.metrics { display:grid; grid-template-columns:repeat(6,minmax(110px,1fr)); gap:8px; margin-top:10px; }
.metric { background:var(--card2); border:1px solid var(--line); border-radius:7px; padding:8px 10px; min-height:56px; }
.metric .k { color:var(--mut); font-size:10px; text-transform:uppercase; letter-spacing:.05em; }
.metric .v { margin-top:3px; color:var(--ok); font-weight:700; font-size:17px; font-variant-numeric:tabular-nums; overflow:hidden; text-overflow:ellipsis; }
.metric .s { color:var(--mut); font-size:11px; font-variant-numeric:tabular-nums; }
.trace { margin-top:10px; min-height:190px; max-height:360px; overflow:auto; background:#0b0e14;
border:1px solid var(--line); border-radius:7px; padding:8px; }
.line { border-left:2px solid var(--line); padding:7px 9px; margin:0 0 7px;
background:#10141c; border-radius:0 6px 6px 0; }
.line.partial { border-left-color:var(--warn); color:#f3d18a; }
.line.final { border-left-color:var(--ok); color:var(--fg); }
.line.error { border-left-color:var(--err); color:#ffb1b1; }
.line .meta { color:var(--mut); font-size:11px; margin-bottom:3px; font-variant-numeric:tabular-nums; }
.checklist { display:grid; grid-template-columns:repeat(4,minmax(180px,1fr)); gap:8px; }
.check { background:var(--card2); border:1px solid var(--line); border-radius:7px; padding:9px 10px; }
.check b { display:block; color:var(--fg); margin-bottom:3px; }
canvas { display:block; width:100%; height:150px; background:#0b0e14; border:1px solid var(--line); border-radius:7px; margin-top:10px; }
.chunkbar { height:28px; background:#0b0e14; border:1px solid var(--line); border-radius:7px;
margin-top:10px; position:relative; overflow:hidden; display:flex; align-items:stretch; }
.chunkbar .chunk { border-right:1px solid #0b0e14; background:var(--acc); opacity:.85; animation:pop .22s ease; }
.chunkbar .playhead { position:absolute; top:0; bottom:0; width:2px; background:#fff; left:0; }
@keyframes pop { from { transform:scaleY(0); } to { transform:scaleY(1); } }
.video-box { position:relative; overflow:hidden; min-height:210px; background:#07090d;
border:1px solid var(--line); border-radius:7px; display:grid; place-items:center; margin-top:10px; }
.video-box img { display:block; width:100%; max-height:360px; object-fit:contain; background:#07090d; }
.alerts { display:grid; gap:7px; margin-top:10px; }
.alert { padding:8px 9px; background:#271f14; color:#f0c36a; border:1px solid #5e4920; border-radius:6px; }
.alert.error { background:#2b1719; color:#ffb4b4; border-color:#6f3137; }
audio { width:100%; margin-top:10px; }
.full { grid-column:1 / -1; }
#log { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:11px;
color:var(--mut); max-height:150px; overflow:auto; }
code { color:var(--acc); }
@media (max-width:1040px) {
main { grid-template-columns:1fr; }
.split { grid-template-columns:1fr; }
.metrics { grid-template-columns:repeat(3,minmax(110px,1fr)); }
.checklist { grid-template-columns:1fr 1fr; }
}
@media (max-width:640px) {
.grid2, .grid3, .metrics, .checklist { grid-template-columns:1fr; }
header input[type=text] { width:100% !important; }
}
</style>
</head>
<body>
<header>
<h1>RapidSpeech Server — Test Console</h1>
<div><span id="dot" class="dot"></span><span id="status" class="st">not connected</span></div>
<div style="flex:1"></div>
<div style="display:flex; gap:8px; align-items:center;">
<label style="margin:0">Language</label>
<select id="langSelect" style="width:96px"><option value="zh">中文</option><option value="en">English</option></select>
<label style="margin:0">HTTP</label>
<input id="httpBase" type="text" style="width:190px" placeholder="http://127.0.0.1:8080">
<label style="margin:0">WS</label>
<input id="wsBase" type="text" style="width:190px" placeholder="ws://127.0.0.1:8081">
<button class="sec" onclick="ping()">Connect</button>
</div>
</header>
<main>
<section class="card full">
<h2>Capability coverage <span class="tag">one console · local first</span></h2>
<div class="checklist">
<div class="check"><b>HTTP ASR / TTS</b><span class="muted">OpenAI-compatible transcription and speech endpoints.</span></div>
<div class="check"><b>Streaming ASR</b><span class="muted">Microphone or file input, pure stream and VAD segmentation.</span></div>
<div class="check"><b>Streaming TTS</b><span class="muted">True chunk streaming, sentence segmentation, latency and RTF.</span></div>
<div class="check"><b>Observer bridge</b><span class="muted">Optional ffmpeg source, video, RSS/CPU and soak-test alerts.</span></div>
</div>
</section>
<section class="card full">
<h2>Model selection <span class="tag">registry · download · hot load</span></h2>
<div class="grid3">
<div>
<label>ASR model</label>
<select id="modelAsr"></select>
<button id="modelAsrLoad" onclick="loadSelectedModel('asr','modelAsr')">Load ASR</button>
</div>
<div>
<label>TTS model</label>
<select id="modelTts"></select>
<button id="modelTtsLoad" onclick="loadSelectedModel('tts','modelTts')">Load TTS</button>
</div>
<div>
<label>VAD model</label>
<select id="modelVad"></select>
<button id="modelVadLoad" class="sec" onclick="loadSelectedModel('vad','modelVad')">Load VAD</button>
</div>
</div>
<div id="modelStatus" class="out muted">Connect to load the model registry.</div>
</section>
<!-- HTTP: transcription -->
<section class="card">
<h2>HTTP transcription <span class="tag">POST /v1/audio/transcriptions</span></h2>
<label>Audio file (WAV)</label>
<input id="trFile" type="file" accept="audio/*">
<div><button onclick="httpTranscribe()">Transcribe</button></div>
<div id="trOut" class="out"></div>
</section>
<!-- HTTP: speech -->
<section class="card">
<h2>HTTP speech <span class="tag">POST /v1/audio/speech</span></h2>
<label>Text</label>
<textarea id="spText">你好,欢迎使用 RapidSpeech。</textarea>
<div class="row">
<div><label>voice</label><input id="spVoice" type="text" value="female"></div>
<div><label>language</label><input id="spLang" type="text" value="Chinese"></div>
</div>
<div><button onclick="httpSpeech()">Synthesize</button></div>
<div id="spOut" class="out muted"></div>
<audio id="spAudio" controls></audio>
</section>
<!-- WS: streaming ASR -->
<section class="card">
<h2>WS streaming ASR <span class="tag">/asr/stream</span></h2>
<div class="row">
<div><label>chunk_len</label>
<select id="asChunk"><option>16</option><option selected>32</option><option>48</option><option>96</option></select></div>
<div><label>PCM chunk ms</label><input id="asPcmMs" type="number" value="200" min="40" max="1000"></div>
</div>
<div>
<button id="asMic" onclick="runAsrMic()">🎙 Mic</button>
<button class="sec" id="asStop" onclick="stopAsr()" disabled>Stop</button>
<label style="display:inline">or file:</label>
<input id="asFile" type="file" accept="audio/*" style="display:inline; width:auto">
<button class="sec" onclick="runAsrFile('/asr/stream','asOut',false)">Send file</button>
<button class="sec" onclick="clearAsrOutput('asOut')">Clear</button>
<button class="sec" onclick="downloadAsrText('asOut')">Download transcript</button>
</div>
<div class="metrics">
<div class="metric"><div class="k">Audio</div><div id="asAudio" class="v">0.0s</div><div class="s">16 kHz mono</div></div>
<div class="metric"><div class="k">Level</div><div id="asRms" class="v">-120 dB</div><div id="asPeak" class="s">peak -120 dB</div></div>
<div class="metric"><div class="k">Messages</div><div id="asMessages" class="v">0</div><div id="asFinals" class="s">0 finals</div></div>
<div class="metric"><div class="k">ASR idle</div><div id="asIdle" class="v">0s</div><div class="s">since last event</div></div>
</div>
<canvas id="asWave" width="1000" height="180"></canvas>
<div id="asOut" class="trace"></div>
</section>
<!-- WS: VAD + ASR -->
<section class="card">
<h2>WS VAD + ASR <span class="tag">/asr/vad</span></h2>
<div class="grid3">
<div><label>threshold</label><input id="vaThreshold" type="number" value="0.5" min="0" max="1" step="0.05"></div>
<div><label>end silence ms</label><input id="vaSilence" type="number" value="600" min="0"></div>
<div><label>partial ms</label><input id="vaPartial" type="number" value="600" min="0"></div>
</div>
<div class="grid3">
<div><label>min segment ms</label><input id="vaMinSeg" type="number" value="500" min="0"></div>
<div><label>max segment ms</label><input id="vaMaxSeg" type="number" value="0" min="0"></div>
<label class="muted" style="display:flex;align-items:center;gap:6px;margin:22px 0 0"><input id="vaTwoPass" type="checkbox" style="width:auto"> two pass</label>
<label class="muted" style="display:flex;align-items:center;gap:6px;margin:22px 0 0"><input id="vaCtcPrecheck" type="checkbox" style="width:auto"> CTC precheck</label>
</div>
<div>
<button id="vaMic" onclick="runVadMic()">🎙 Mic</button>
<button class="sec" id="vaStop" onclick="stopAsr()" disabled>Stop</button>
<label style="display:inline">or file:</label>
<input id="vaFile" type="file" accept="audio/*" style="display:inline; width:auto">
<button class="sec" onclick="runAsrFile('/asr/vad','vaOut',true)">Send file</button>
<button class="sec" onclick="clearAsrOutput('vaOut')">Clear</button>
<button class="sec" onclick="downloadAsrText('vaOut')">Download transcript</button>
</div>
<div id="vaOut" class="trace"></div>
</section>
<!-- WS: TTS streaming -->
<section class="card">
<h2>WS TTS <span class="tag">/tts/stream · /tts/segmented</span></h2>
<label>Text</label>
<textarea id="ttText">第一句话。第二句话,稍微长一点。</textarea>
<div class="row">
<div><label>voice</label><input id="ttVoice" type="text" value="female"></div>
<div><label>language</label><input id="ttLang" type="text" value="Chinese"></div>
<div><label>seed</label><input id="ttSeed" type="number" value="42"></div>
<div><label>steps</label><input id="ttSteps" type="number" value="8" min="1"></div>
</div>
<div class="row">
<div><label>stream mode</label>
<select id="ttStreamMode">
<option value="true">true · full-text streaming</option>
<option value="hybrid" selected>hybrid · first sentence + batched tail</option>
<option value="auto">auto · hybrid for multi-sentence text</option>
</select></div>
<div><label>segment max chars</label><input id="ttSegmentMaxChars" type="number" value="80" min="16" max="512"></div>
</div>
<div>
<select id="ttEndpoint" style="width:auto"><option value="/tts/stream">/tts/stream · selectable stream mode</option><option value="/tts/segmented">/tts/segmented · sentence chunks</option></select>
<button id="ttStart" onclick="runTts()">Synthesize and play</button>
<button class="sec" id="ttStop" onclick="stopTts()" disabled>Stop</button>
<button class="sec" id="ttDownload" onclick="downloadTts()" disabled>Download WAV</button>
</div>
<div id="ttOut" class="out muted"></div>
<div class="metrics">
<div class="metric"><div class="k">First audio</div><div id="ttFirst" class="v">-</div><div class="s">request to first chunk</div></div>
<div class="metric"><div class="k">Chunks</div><div id="ttChunks" class="v">0</div><div id="ttSegments" class="s">0 segments</div></div>
<div class="metric"><div class="k">Audio</div><div id="ttAudioSec" class="v">0.00s</div><div class="s">received PCM</div></div>
<div class="metric"><div class="k">Wall / RTF</div><div id="ttWall" class="v">-</div><div id="ttRtf" class="s">RTF -</div></div>
<div class="metric"><div class="k">Buffer ahead</div><div id="ttAhead" class="v">-</div><div class="s">positive is healthy</div></div>
</div>
<div id="ttBar" class="chunkbar"><div class="playhead"></div></div>
<audio id="ttAudio" controls></audio>
</section>
<!-- Optional asr-observer bridge -->
<section class="card full">
<div class="toolbar">
<h2 style="margin:0">ASR Observer bridge <span class="tag">optional observer.py on :8090</span></h2>
<span class="push"></span><span id="obEventState" class="pill">events disconnected</span>
</div>
<div class="split">
<div>
<label>observer HTTP base</label><input id="obBase" type="text" value="http://127.0.0.1:8090">
<label>source URL or file path</label><input id="obSource" type="text" value="http://38.75.136.137:98/gslb/dsdqbv/cctv1hd.m3u8?auth=test20251009" placeholder="/path/audio.wav or https://...">
<div class="row">
<div><label>rs-server WS</label><input id="obRsWs" type="text"></div>
<div><label>ASR endpoint</label><select id="obMode"><option value="stream">/asr/stream</option><option value="vad">/asr/vad</option></select></div>
</div>
<div class="row">
<div><label>chunk ms</label><input id="obChunkMs" type="number" value="200" min="40"></div>
<div><label>chunk_len</label><select id="obChunkLen"><option>16</option><option selected>32</option><option>48</option><option>96</option></select></div>
</div>
<div class="grid3">
<div><label>source idle s</label><input id="obSourceIdleWarn" type="number" value="30" min="5"></div>
<div><label>ASR idle s</label><input id="obAsrIdle" type="number" value="180" min="15"></div>
<div><label>RSS warn MB/h</label><input id="obLeakWarn" type="number" value="200" min="0"></div>
</div>
<div class="toolbar" style="margin-top:8px">
<label class="muted" style="display:flex;align-items:center;gap:6px"><input id="obRealtime" type="checkbox" checked style="width:auto"> pace source</label>
<label class="muted" style="display:flex;align-items:center;gap:6px"><input id="obVideo" type="checkbox" checked style="width:auto"> video preview</label>
<label class="muted" style="display:flex;align-items:center;gap:6px"><input id="obPlay" type="checkbox" style="width:auto"> monitor audio</label>
<input id="obVolume" type="range" min="0" max="1" step="0.05" value="0.35" style="width:110px">
</div>
<div class="grid3">
<div><label>video FPS</label><input id="obVideoFps" type="number" value="2" min="1" max="10"></div>
<div><label>video width</label><input id="obVideoWidth" type="number" value="640" min="240" max="1920"></div>
<div><label>ffmpeg extra args</label><input id="obFfmpegExtra" type="text" placeholder="-headers ..."></div>
</div>
<button id="obConnect" class="sec" onclick="connectObserver()">Connect events</button>
<button id="obStart" onclick="startObserver()">Start observer</button>
<button id="obStop" class="danger" onclick="stopObserver()" disabled>Stop</button>
<div class="muted" style="margin-top:8px">This bridge keeps ffmpeg, video preview, process RSS/CPU, idle and RSS-slope checks in the existing observer backend. Start it separately with <code>python3 examples/server/asr-observer/observer.py</code>.</div>
</div>
<div>
<div class="metrics">
<div class="metric"><div class="k">Source audio</div><div id="obAudio" class="v">0.0s</div><div id="obAudioMb" class="s">0.00 MB</div></div>
<div class="metric"><div class="k">Level</div><div id="obRms" class="v">-120 dB</div><div id="obPeak" class="s">peak -120 dB</div></div>
<div class="metric"><div class="k">rs-server</div><div id="obRs" class="v">n/a</div><div id="obRsCpu" class="s">cpu n/a</div></div>
<div class="metric"><div class="k">ffmpeg</div><div id="obFfmpeg" class="v">n/a</div><div id="obFfmpegCpu" class="s">cpu n/a</div></div>
<div class="metric"><div class="k">Idle</div><div id="obIdle" class="v">0s</div><div id="obSourceIdleMetric" class="s">source 0s</div></div>
<div class="metric"><div class="k">RSS slope</div><div id="obSlope" class="v">n/a</div><div id="obFfSlope" class="s">ffmpeg n/a</div></div>
</div>
<canvas id="obWave" width="1000" height="180"></canvas>
<div class="video-box"><img id="obVideoFrame" alt="observer video preview" style="display:none"><div id="obVideoEmpty" class="muted">No video frames</div></div>
<div class="toolbar" style="margin-top:10px"><span class="muted">Observer transcript</span><span class="push"></span><button class="sec" onclick="clearObserverTranscript()">Clear</button></div>
<div id="obTranscript" class="trace"></div>
<div id="obAlerts" class="alerts"><div class="muted">No observer alerts</div></div>
</div>
</div>
</section>
<!-- log -->
<section class="card full">
<h2>Log</h2>
<div id="log" class="out"></div>
</section>
</main>
<script>
const UI_I18N = {
"RapidSpeech Server — Test Console": { zh: "RapidSpeech 服务控制台", en: "RapidSpeech Server — Test Console" },
"not connected": { zh: "未连接", en: "not connected" },
"unreachable": { zh: "无法连接", en: "unreachable" },
"Language": { zh: "语言", en: "Language" },
"Connect": { zh: "连接", en: "Connect" },
"Capability coverage": { zh: "能力覆盖", en: "Capability coverage" },
"one console · local first": { zh: "一个控制台 · 本地优先", en: "one console · local first" },
"HTTP ASR / TTS": { zh: "HTTP ASR / TTS", en: "HTTP ASR / TTS" },
"OpenAI-compatible transcription and speech endpoints.": { zh: "OpenAI 兼容的转写和语音合成端点。", en: "OpenAI-compatible transcription and speech endpoints." },
"Streaming ASR": { zh: "流式 ASR", en: "Streaming ASR" },
"Microphone or file input, pure stream and VAD segmentation.": { zh: "支持麦克风或文件输入、纯流式和 VAD 分段。", en: "Microphone or file input, pure stream and VAD segmentation." },
"Streaming TTS": { zh: "流式 TTS", en: "Streaming TTS" },
"True chunk streaming, sentence segmentation, latency and RTF.": { zh: "支持真实分块流、按句分段、延迟和 RTF 指标。", en: "True chunk streaming, sentence segmentation, latency and RTF." },
"Observer bridge": { zh: "Observer 桥接", en: "Observer bridge" },
"Optional ffmpeg source, video, RSS/CPU and soak-test alerts.": { zh: "可选 ffmpeg 源、视频预览、RSS/CPU 和长跑告警。", en: "Optional ffmpeg source, video, RSS/CPU and soak-test alerts." },
"Model selection": { zh: "模型选择", en: "Model selection" },
"registry · download · hot load": { zh: "模型表 · 下载 · 热加载", en: "registry · download · hot load" },
"ASR model": { zh: "ASR 模型", en: "ASR model" },
"TTS model": { zh: "TTS 模型", en: "TTS model" },
"VAD model": { zh: "VAD 模型", en: "VAD model" },
"Load ASR": { zh: "加载 ASR", en: "Load ASR" },
"Load TTS": { zh: "加载 TTS", en: "Load TTS" },
"Load VAD": { zh: "加载 VAD", en: "Load VAD" },
"Connect to load the model registry.": { zh: "连接后加载模型列表。", en: "Connect to load the model registry." },
"HTTP transcription": { zh: "HTTP 转写", en: "HTTP transcription" },
"Audio file (WAV)": { zh: "音频文件(WAV)", en: "Audio file (WAV)" },
"Transcribe": { zh: "开始转写", en: "Transcribe" },
"HTTP speech": { zh: "HTTP 语音合成", en: "HTTP speech" },
"Text": { zh: "文本", en: "Text" },
"voice": { zh: "音色", en: "voice" },
"language": { zh: "语言", en: "language" },
"Synthesize": { zh: "合成", en: "Synthesize" },
"WS streaming ASR": { zh: "WS 流式 ASR", en: "WS streaming ASR" },
"PCM chunk ms": { zh: "PCM 分块 ms", en: "PCM chunk ms" },
"Mic": { zh: "麦克风", en: "Mic" },
"Stop": { zh: "停止", en: "Stop" },
"or file:": { zh: "或文件:", en: "or file:" },
"Send file": { zh: "发送文件", en: "Send file" },
"Clear": { zh: "清空", en: "Clear" },
"Download transcript": { zh: "下载转写文本", en: "Download transcript" },
"Audio": { zh: "音频", en: "Audio" },
"16 kHz mono": { zh: "16 kHz 单声道", en: "16 kHz mono" },
"Level": { zh: "电平", en: "Level" },
"peak -120 dB": { zh: "峰值 -120 dB", en: "peak -120 dB" },
"Messages": { zh: "消息数", en: "Messages" },
"0 finals": { zh: "0 个 final", en: "0 finals" },
"ASR idle": { zh: "ASR 空闲", en: "ASR idle" },
"since last event": { zh: "距上次事件", en: "since last event" },
"WS VAD + ASR": { zh: "WS VAD + ASR", en: "WS VAD + ASR" },
"threshold": { zh: "阈值", en: "threshold" },
"end silence ms": { zh: "结束静音 ms", en: "end silence ms" },
"partial ms": { zh: "partial 间隔 ms", en: "partial ms" },
"min segment ms": { zh: "最短分段 ms", en: "min segment ms" },
"max segment ms": { zh: "最长分段 ms", en: "max segment ms" },
"two pass": { zh: "二次解码", en: "two pass" },
"CTC precheck": { zh: "CTC 预检", en: "CTC precheck" },
"WS TTS": { zh: "WS TTS", en: "WS TTS" },
"seed": { zh: "随机种子", en: "seed" },
"steps": { zh: "步数", en: "steps" },
"stream mode": { zh: "流式模式", en: "stream mode" },
"segment max chars": { zh: "分段最大字符数", en: "segment max chars" },
"true · full-text streaming": { zh: "true · 整段真流式", en: "true · full-text streaming" },
"hybrid · first sentence + batched tail": { zh: "hybrid · 首句真流式 + 后续批处理", en: "hybrid · first sentence + batched tail" },
"auto · hybrid for multi-sentence text": { zh: "auto · 多句自动 hybrid", en: "auto · hybrid for multi-sentence text" },
"/tts/stream · selectable stream mode": { zh: "/tts/stream · 可选流式模式", en: "/tts/stream · selectable stream mode" },
"/tts/segmented · sentence chunks": { zh: "/tts/segmented · 按句分块", en: "/tts/segmented · sentence chunks" },
"Synthesize and play": { zh: "合成并播放", en: "Synthesize and play" },
"Download WAV": { zh: "下载 WAV", en: "Download WAV" },
"First audio": { zh: "首个音频", en: "First audio" },
"request to first chunk": { zh: "请求到首包", en: "request to first chunk" },
"Chunks": { zh: "分块数", en: "Chunks" },
"0 segments": { zh: "0 个分段", en: "0 segments" },
"received PCM": { zh: "已接收 PCM", en: "received PCM" },
"Wall / RTF": { zh: "耗时 / RTF", en: "Wall / RTF" },
"Buffer ahead": { zh: "缓冲领先", en: "Buffer ahead" },
"positive is healthy": { zh: "正数表示播放稳定", en: "positive is healthy" },
"ASR Observer bridge": { zh: "ASR Observer 桥接", en: "ASR Observer bridge" },
"optional observer.py on :8090": { zh: "可选 observer.py,默认 :8090", en: "optional observer.py on :8090" },
"events disconnected": { zh: "事件未连接", en: "events disconnected" },
"events connecting": { zh: "事件连接中", en: "events connecting" },
"events connected": { zh: "事件已连接", en: "events connected" },
"events reconnecting": { zh: "事件重连中", en: "events reconnecting" },
"observer unavailable": { zh: "Observer 不可用", en: "observer unavailable" },
"observer HTTP base": { zh: "observer API 地址", en: "observer HTTP base" },
"source URL or file path": { zh: "媒体源 URL 或文件路径", en: "source URL or file path" },
"rs-server WS": { zh: "rs-server WS 地址", en: "rs-server WS" },
"ASR endpoint": { zh: "ASR 端点", en: "ASR endpoint" },
"chunk ms": { zh: "分块 ms", en: "chunk ms" },
"source idle s": { zh: "源空闲告警 s", en: "source idle s" },
"RSS warn MB/h": { zh: "RSS 增长告警 MB/h", en: "RSS warn MB/h" },
"pace source": { zh: "按实时速率推流", en: "pace source" },
"video preview": { zh: "视频预览", en: "video preview" },
"monitor audio": { zh: "监听音频", en: "monitor audio" },
"video FPS": { zh: "视频 FPS", en: "video FPS" },
"video width": { zh: "视频宽度", en: "video width" },
"ffmpeg extra args": { zh: "ffmpeg 额外参数", en: "ffmpeg extra args" },
"Connect events": { zh: "连接事件", en: "Connect events" },
"Start observer": { zh: "启动 Observer", en: "Start observer" },
"This bridge keeps ffmpeg, video preview, process RSS/CPU, idle and RSS-slope checks in the existing observer backend. Start it separately with": { zh: "此桥接保留现有 observer 后端的 ffmpeg、视频预览、进程 RSS/CPU、空闲和 RSS 斜率检查。请先单独启动:", en: "This bridge keeps ffmpeg, video preview, process RSS/CPU, idle and RSS-slope checks in the existing observer backend. Start it separately with" },
"Source audio": { zh: "源音频", en: "Source audio" },
"rs-server": { zh: "rs-server", en: "rs-server" },
"ffmpeg": { zh: "ffmpeg", en: "ffmpeg" },
"Idle": { zh: "空闲", en: "Idle" },
"source 0s": { zh: "源 0s", en: "source 0s" },
"RSS slope": { zh: "RSS 斜率", en: "RSS slope" },
"ffmpeg n/a": { zh: "ffmpeg 无数据", en: "ffmpeg n/a" },
"No video frames": { zh: "暂无视频帧", en: "No video frames" },
"Observer transcript": { zh: "Observer 转写", en: "Observer transcript" },
"No observer alerts": { zh: "暂无 observer 告警", en: "No observer alerts" },
"Log": { zh: "日志", en: "Log" }
};
const UI_ATTR_I18N = {
"/path/audio.wav or https://...": { zh: "本地音频路径或媒体 URL", en: "/path/audio.wav or https://..." },
"-headers ...": { zh: "-headers ...", en: "-headers ..." }
};
function currentLang() {
return document.getElementById("langSelect")?.value || "zh";
}
function uiText(key) {
const lang = currentLang();
return UI_I18N[key]?.[lang] || key;
}
function applyI18n(lang) {
const active = lang || "zh";
document.documentElement.lang = active === "zh" ? "zh-CN" : "en";
document.title = UI_I18N["RapidSpeech Server — Test Console"][active];
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
const parent = node.parentElement;
if (!parent || ["SCRIPT", "STYLE", "CODE"].includes(parent.tagName)) return NodeFilter.FILTER_REJECT;
const key = node.__i18nKey || node.nodeValue.trim();
return UI_I18N[key] ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
});
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
nodes.forEach(node => {
const key = node.__i18nKey || node.nodeValue.trim();
node.__i18nKey = key;
const leading = node.nodeValue.match(/^\s*/)[0];
const trailing = node.nodeValue.match(/\s*$/)[0];
node.nodeValue = leading + UI_I18N[key][active] + trailing;
});
document.querySelectorAll("[placeholder]").forEach(node => {
const key = node.dataset.i18nPlaceholder || node.getAttribute("placeholder");
if (!UI_ATTR_I18N[key]) return;
node.dataset.i18nPlaceholder = key;
node.setAttribute("placeholder", UI_ATTR_I18N[key][active]);
});
}
function initI18n() {
const select = document.getElementById("langSelect");
const lang = localStorage.getItem("rs_webui_lang") || "zh";
select.value = lang;
applyI18n(lang);
select.addEventListener("change", () => {
localStorage.setItem("rs_webui_lang", select.value);
applyI18n(select.value);
});
}
// ── config ──────────────────────────────────────────────────────────────
(function init() {
const loc = location;
const served = loc.protocol.startsWith("http");
httpBase.value = served ? loc.origin : "http://127.0.0.1:8080";
const wsPort = served ? (Number(loc.port || 80) + 1) : 8081;
const wsHost = served ? loc.hostname : "127.0.0.1";
wsBase.value = `ws://${wsHost}:${wsPort}`;
initI18n();
})();
const HTTP = () => httpBase.value.replace(/\/$/, "");
const WS = () => wsBase.value.replace(/\/$/, "");
function log(m) { const t = new Date().toLocaleTimeString();
document.getElementById("log").textContent += `[${t}] ${m}\n`;
document.getElementById("log").scrollTop = 1e9; }
let modelRegistry = null;
function fmtModelSize(bytes) {
const n = Number(bytes || 0);
if (!n) return "";
if (n >= 1e9) return (n / 1e9).toFixed(1) + " GB";
return Math.round(n / 1e6) + " MB";
}
function modelLabel(model, variant) {
const cached = variant.cached ? "cached" : "download";
const marker = variant.default ? " · default" : "";
const deps = model.dependencies || [];
const depStatus = deps.length
? ` · deps ${deps.every((dep) => dep.cached) ? "cached" : "download"}`
: "";
return `${model.id}:${variant.id} · ${fmtModelSize(variant.size_bytes)} · ${cached}${depStatus}${marker}`;
}
function setModelStatus(message) {
const box = document.getElementById("modelStatus");
if (box) box.textContent = message;
}
function fillModelSelect(task, id) {
const select = document.getElementById(id);
if (!select || !modelRegistry) return;
select.innerHTML = "";
const loaded = modelRegistry.loaded?.[task] || "";
const models = (modelRegistry.models || []).filter((model) => model.task === task);
for (const model of models) {
for (const variant of model.variants || []) {
const option = document.createElement("option");
option.value = variant.spec;
option.textContent = modelLabel(model, variant);
option.title = model.description || "";
if (loaded === variant.spec || (!loaded && variant.default)) option.selected = true;
select.appendChild(option);
}
}
if (!select.children.length) {
const option = document.createElement("option");
option.value = "";
option.textContent = "no " + task + " models";
select.appendChild(option);
}
}
function renderModelRegistry() {
if (!modelRegistry) return;
fillModelSelect("asr", "modelAsr");
fillModelSelect("tts", "modelTts");
fillModelSelect("vad", "modelVad");
const loaded = modelRegistry.loaded || {};
const cacheDir = modelRegistry.cache_dir || "";
setModelStatus(
`loaded ASR=${loaded.asr || "none"} · TTS=${loaded.tts || "none"} · VAD=${loaded.vad || "none"}\n` +
`cache: ${cacheDir}`
);
}
async function refreshModelRegistry() {
try {
modelRegistry = await fetch(HTTP() + "/v1/models/registry").then((r) => {
if (!r.ok) throw new Error("HTTP " + r.status);
return r.json();
});
renderModelRegistry();
} catch (error) {
setModelStatus("model registry unavailable: " + error);
}
}
window.loadSelectedModel = async (task, selectId) => {
const select = document.getElementById(selectId);
const spec = select?.value || "";
if (!spec) return;
const button = document.getElementById("model" + task[0].toUpperCase() + task.slice(1) + "Load");
if (button) button.disabled = true;
setModelStatus(`loading ${task} model ${spec} ...\nIf it is not cached, the server will download and verify it first.`);
log("POST /v1/models/load " + task + " " + spec);
try {
const response = await fetch(HTTP() + "/v1/models/load", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ task, model: spec })
});
const data = await response.json().catch(async () => ({ error: { message: await response.text() } }));
if (!response.ok || data.ok === false) {
throw new Error(data.error?.message || JSON.stringify(data));
}
setModelStatus(`loaded ${data.task} ${data.model} · arch=${data.arch || "n/a"} · downloaded=${data.downloaded ? "yes" : "no"}`);
await refreshModelRegistry();
await ping();
} catch (error) {
setModelStatus("load failed: " + error.message);
log("model load failed: " + error.message);
} finally {
if (button) button.disabled = false;
}
};
async function ping() {
const dotEl = document.getElementById("dot");
const statusEl = document.getElementById("status");
try {
const h = await fetch(HTTP() + "/health").then(r => r.json());
const m = await fetch(HTTP() + "/v1/models").then(r => r.json());
const ids = m.data.map(d => `${d.id}(${d.arch})`).join(", ") || "none";
dotEl.classList.add("up");
statusEl.textContent = currentLang() === "zh"
? `${h.status === "ok" ? "正常" : h.status} · 模型:${ids}`
: `${h.status} · models: ${ids}`;
log("connected · models: " + ids);
refreshModelRegistry();
} catch (e) { dotEl.classList.remove("up"); statusEl.textContent = uiText("unreachable");
log("health failed: " + e); }
}
// ── HTTP transcription ──────────────────────────────────────────────────
async function httpTranscribe() {
const f = trFile.files[0];
if (!f) { trOut.textContent = "pick a WAV file"; return; }
trOut.textContent = "…"; log("POST /v1/audio/transcriptions " + f.name);
const fd = new FormData(); fd.append("file", f); fd.append("model", "rapidspeech-asr");
try {
const r = await fetch(HTTP() + "/v1/audio/transcriptions", { method:"POST", body:fd });
const j = await r.json();
trOut.textContent = j.text ?? JSON.stringify(j);
} catch (e) { trOut.textContent = "error: " + e; }
}
// ── HTTP speech ─────────────────────────────────────────────────────────
async function httpSpeech() {
spOut.textContent = "synthesizing…"; log("POST /v1/audio/speech");
const body = { model:"rapidspeech-tts", input:spText.value,
voice:spVoice.value, language:spLang.value };
try {
const t0 = performance.now();
const r = await fetch(HTTP() + "/v1/audio/speech",
{ method:"POST", headers:{ "content-type":"application/json" }, body:JSON.stringify(body) });
if (!r.ok) { spOut.textContent = "error: " + (await r.text()); return; }
const blob = await r.blob();
spAudio.src = URL.createObjectURL(blob);
spOut.textContent = `${(blob.size/1024).toFixed(0)} KB WAV · ${(performance.now()-t0|0)} ms`;
spAudio.play().catch(()=>{});
} catch (e) { spOut.textContent = "error: " + e; }
}
// ── audio helpers ───────────────────────────────────────────────────────
function floatToI16(f32) {
const i16 = new Int16Array(f32.length);
for (let i = 0; i < f32.length; i++) {
let s = Math.max(-1, Math.min(1, f32[i]));
i16[i] = s < 0 ? s * 32768 : s * 32767;
}
return i16;
}
function resample(f32, from, to) {
if (from === to) return f32;
const n = Math.round(f32.length * to / from), out = new Float32Array(n);
for (let i = 0; i < n; i++) {
const x = i * from / to, i0 = Math.floor(x), i1 = Math.min(i0 + 1, f32.length - 1);
out[i] = f32[i0] + (f32[i1] - f32[i0]) * (x - i0);
}
return out;
}
// ── microphone streaming (shared by both ASR endpoints) ─────────────────
let micCtx = null, micNode = null, micStream = null, micWs = null;
async function startMic(path, out, isVad) {
const ws = new WebSocket(WS() + path);
ws.binaryType = "arraybuffer";
micWs = ws;
const view = document.getElementById(out);
view.innerHTML = ""; const segs = {};
ws.onmessage = (e) => onAsrMsg(e, view, segs, isVad);
ws.onclose = () => log(path + " closed");
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
log(path + " connected (mic)");
micCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000 });
micStream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount:1 } });
const src = micCtx.createMediaStreamSource(micStream);
micNode = micCtx.createScriptProcessor(4096, 1, 1);
const rate = micCtx.sampleRate;
src.connect(micNode); micNode.connect(micCtx.destination);
micNode.onaudioprocess = (ev) => {
if (!micWs || micWs.readyState !== 1) return;
let ch = ev.inputBuffer.getChannelData(0);
if (rate !== 16000) ch = resample(ch, rate, 16000);
micWs.send(floatToI16(ch).buffer);
};
document.querySelectorAll("#asStop,#vaStop").forEach(b => b.disabled = false);
document.querySelectorAll("#asMic,#vaMic").forEach(b => b.disabled = true);
}
function stopMic() {
if (micNode) micNode.disconnect();
if (micStream) micStream.getTracks().forEach(t => t.stop());
if (micCtx) micCtx.close();
if (micWs && micWs.readyState === 1) micWs.send(JSON.stringify({ type:"eos" }));
micCtx = micNode = micStream = null;
document.querySelectorAll("#asStop,#vaStop").forEach(b => b.disabled = true);
document.querySelectorAll("#asMic,#vaMic").forEach(b => b.disabled = false);
}
const asrStreamMic = () => startMic("/asr/stream", "asOut", false).catch(e => log("mic err: " + e));
const asrVadMic = () => startMic("/asr/vad", "vaOut", true).catch(e => log("mic err: " + e));
function onAsrMsg(e, view, segs, isVad) {
if (typeof e.data !== "string") return;
const d = JSON.parse(e.data);
if (d.type === "ready") { log("asr ready"); return; }
if (d.type === "error") { view.innerHTML = `<span style="color:var(--err)">${d.error}</span>`; return; }
if (!isVad) {
if (d.type === "partial") view.innerHTML = `<span class="partial">${d.text}</span>`;
if (d.type === "final") view.innerHTML = `<span class="final">${d.text}</span>`;
return;
}
// VAD: one line per segment, partial (amber) → final (green)
const s = d.segment;
if (d.type === "partial" || d.type === "final") {
if (!segs[s]) { segs[s] = document.createElement("div"); segs[s].className = "seg"; view.appendChild(segs[s]); }
const text = d.text || (d.type === "partial" ? "(listening)" : "");
segs[s].innerHTML = `<span class="muted">#${s}</span> <span class="${d.type}">${text}</span>`;
}
if (d.type === "done") log("vad done");
}
// ── ASR from a file over WS ─────────────────────────────────────────────
async function asrStreamFile(path, out, isVad) {
const inp = isVad ? vaFile : asFile;
const f = inp.files[0];
if (!f) { log("pick a file"); return; }
const buf = await f.arrayBuffer();
const actx = new (window.AudioContext || window.webkitAudioContext)();
const ab = await actx.decodeAudioData(buf);
let pcm = ab.getChannelData(0);
pcm = resample(pcm, ab.sampleRate, 16000);
actx.close();
const ws = new WebSocket(WS() + path + (isVad ? "" : "?chunk_len=" + asChunk.value));
ws.binaryType = "arraybuffer";
const view = document.getElementById(out); view.innerHTML = ""; const segs = {};
ws.onmessage = (e) => onAsrMsg(e, view, segs, isVad);
ws.onopen = async () => {
log(path + " sending " + (pcm.length/16000).toFixed(1) + "s");
const step = 3200; // 200 ms
for (let i = 0; i < pcm.length; i += step) {
ws.send(floatToI16(pcm.subarray(i, i + step)).buffer);
await new Promise(r => setTimeout(r, 30));
}
ws.send(JSON.stringify({ type:"eos" }));
};
ws.onclose = () => log(path + " closed");
}
// ── TTS over WS (streaming playback) ────────────────────────────────────
function ttsWs(path) {
const ws = new WebSocket(WS() + path);
ws.binaryType = "arraybuffer";
ttOut.textContent = "connecting…";
let sr = 24000, actx = null, playAt = 0, chunks = [], nSeg = 0, t0 = 0, firstAt = 0;
ws.onopen = () => {
t0 = performance.now();
const req = { type:"text", text:ttText.value,
voice:ttVoice.value, language:ttLang.value };
if (path === "/tts/stream") {
req.stream_mode = ttStreamMode.value;
req.segment_max_chars = Number(ttSegmentMaxChars.value || 80);
}
ws.send(JSON.stringify(req));
log(path + " sent text" + (req.stream_mode ? " mode=" + req.stream_mode
+ " max_chars=" + req.segment_max_chars : ""));
};
ws.onmessage = (e) => {
if (typeof e.data === "string") {
const d = JSON.parse(e.data);
if (d.type === "audio_info") {
sr = d.sample_rate;
actx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: sr });
playAt = actx.currentTime + 0.1;
log(path + " audio " + sr + " Hz"
+ (d.stream_mode ? " mode=" + d.stream_mode : "")
+ (d.segment_max_chars ? " max_chars=" + d.segment_max_chars : ""));
} else if (d.type === "segment") { nSeg++; }
else if (d.type === "error") { ttOut.textContent = "error: " + d.error; }
else if (d.type === "final") {
const total = chunks.reduce((a, c) => a + c.length, 0);
ttOut.textContent = `done · ${(total/sr).toFixed(2)}s · ${nSeg} segment(s) · ` +
`first audio ${(firstAt - t0)|0} ms`;
// build a WAV blob for the <audio> element too
ttAudio.src = URL.createObjectURL(wavBlob(chunks, sr));
ws.close();
}
} else {
// binary int16 PCM chunk → schedule for gapless streaming playback
const i16 = new Int16Array(e.data);
chunks.push(i16);
if (!firstAt) firstAt = performance.now();
if (actx) {
const f = new Float32Array(i16.length);
for (let i = 0; i < i16.length; i++) f[i] = i16[i] / 32768;
const b = actx.createBuffer(1, f.length, sr); b.copyToChannel(f, 0);
const s = actx.createBufferSource(); s.buffer = b; s.connect(actx.destination);
playAt = Math.max(playAt, actx.currentTime);
s.start(playAt); playAt += b.duration;
}
}
};
ws.onerror = () => { ttOut.textContent = "ws error"; };
}
function wavBlob(chunks, sr) {
let n = chunks.reduce((a, c) => a + c.length, 0);
const buf = new ArrayBuffer(44 + n * 2), v = new DataView(buf);
const s = (o, str) => { for (let i = 0; i < str.length; i++) v.setUint8(o + i, str.charCodeAt(i)); };
s(0, "RIFF"); v.setUint32(4, 36 + n * 2, true); s(8, "WAVE"); s(12, "fmt ");
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, sr, true); v.setUint32(28, sr * 2, true); v.setUint16(32, 2, true);
v.setUint16(34, 16, true); s(36, "data"); v.setUint32(40, n * 2, true);
let o = 44; for (const c of chunks) for (let i = 0; i < c.length; i++) { v.setInt16(o, c[i], true); o += 2; }
return new Blob([buf], { type:"audio/wav" });
}
ping();
</script>
<script>
// Enhanced workbench: keeps the original smoke-test functions intact while
// adding the asr-observer and tts-stream capabilities to this page.
(function () {
const el = (id) => document.getElementById(id);
const is_zh = () => currentLang() === "zh";
const final_label = (n) => is_zh() ? `${n} 个 final` : `${n} finals`;
const segment_label = (n) => is_zh() ? `${n} 个分段` : `${n} segments`;
const peak_label = (v) => is_zh() ? `峰值 ${v}` : `peak ${v}`;
const source_idle_label = (v) => is_zh() ? `源 ${v}` : `source ${v}`;
const cpu_label = (v) => is_zh() ? `CPU ${v}` : `cpu ${v}`;
const asr = {
ws: null, ctx: null, node: null, stream: null, mode: "", output: "",
is_vad: false, segments: {}, cancel: false, audio_samples: 0,
messages: 0, finals: 0, last_event: 0, started_at: 0
};
const tts = {
ws: null, ctx: null, sample_rate: 24000, play_at: 0, chunks: [],
total_samples: 0, segments: 0, started_at: 0, first_at: 0,
running: false, timer: null, finished: false
};
const observer = {
events: null, audio_ctx: null, play_at: 0, metrics: [],
last_pcm: new Int16Array(0), event_error_reported: false
};
function http_root() {
return el("httpBase").value.trim().replace(/\/+$/, "");
}
function ws_root() {
return el("wsBase").value.trim().replace(/\/+$/, "");
}
function escape_text(value) {
return String(value == null ? "" : value);
}
function set_text(id, value) {
el(id).textContent = String(value);
}
function log_enhanced(message) {
const t = new Date().toLocaleTimeString();
const target = el("log");
target.textContent += "[" + t + "] " + message + "\n";
target.scrollTop = target.scrollHeight;
}
function wait_open(ws) {
return new Promise((resolve, reject) => {
ws.addEventListener("open", resolve, { once: true });
ws.addEventListener("error", () => reject(new Error("WebSocket connection failed")), { once: true });
});
}
function wait_ms(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function float_to_i16(f32) {
const out = new Int16Array(f32.length);
for (let i = 0; i < f32.length; i++) {
const sample = Math.max(-1, Math.min(1, f32[i]));
out[i] = sample < 0 ? sample * 32768 : sample * 32767;
}
return out;
}
function resample_audio(f32, from, to) {
if (from === to) return f32;
const n = Math.max(1, Math.round(f32.length * to / from));
const out = new Float32Array(n);
for (let i = 0; i < n; i++) {
const x = i * from / to;
const i0 = Math.min(f32.length - 1, Math.floor(x));
const i1 = Math.min(f32.length - 1, i0 + 1);
out[i] = f32[i0] + (f32[i1] - f32[i0]) * (x - i0);
}
return out;
}
function pcm_stats(i16) {
if (!i16.length) return { rms: -120, peak: -120 };
let sum = 0, peak = 0;
for (let i = 0; i < i16.length; i++) {
const n = i16[i] / 32768;
sum += n * n;
peak = Math.max(peak, Math.abs(i16[i]) / 32768);
}
return {
rms: 20 * Math.log10(Math.max(Math.sqrt(sum / i16.length), 1e-6)),
peak: 20 * Math.log10(Math.max(peak, 1e-6))
};
}
function draw_wave(canvas_id, i16, rms, peak) {
const canvas = el(canvas_id);
if (!canvas) return;
const dpr = window.devicePixelRatio || 1;
const width = Math.max(1, canvas.clientWidth);
const height = Math.max(1, canvas.clientHeight);
if (canvas.width !== Math.floor(width * dpr) || canvas.height !== Math.floor(height * dpr)) {
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = "#0b0e14";
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "#27303b";
ctx.lineWidth = 1;
for (let y = 0; y <= height; y += height / 4) {
ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke();
}
ctx.strokeStyle = "#3ecf8e";
ctx.lineWidth = 1.5;
ctx.beginPath();
const mid = height / 2;
const step = Math.max(1, Math.floor(i16.length / width));
for (let x = 0; x < width; x++) {
const start = x * step;
let min = 0, max = 0;
for (let j = 0; j < step && start + j < i16.length; j++) {
const value = i16[start + j] / 32768;
min = Math.min(min, value); max = Math.max(max, value);
}
ctx.moveTo(x, mid - max * mid * 0.9);
ctx.lineTo(x, mid - min * mid * 0.9);
}
ctx.stroke();
ctx.fillStyle = "#9aa4b2";
ctx.font = "11px ui-monospace,SFMono-Regular,Menlo,monospace";
ctx.fillText("rms " + Number(rms || -120).toFixed(1) + " dB " +
peak_label(Number(peak || -120).toFixed(1) + " dB"), 10, 18);
}
function base64_i16(value) {
const raw = atob(value || "");
const bytes = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
return new Int16Array(bytes.buffer);
}
function wav_blob(chunks, sample_rate) {
const samples = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
const buffer = new ArrayBuffer(44 + samples * 2);
const view = new DataView(buffer);
const write = (offset, text) => {
for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));
};
write(0, "RIFF"); view.setUint32(4, 36 + samples * 2, true);
write(8, "WAVE"); write(12, "fmt "); view.setUint32(16, 16, true);
view.setUint16(20, 1, true); view.setUint16(22, 1, true);
view.setUint32(24, sample_rate, true); view.setUint32(28, sample_rate * 2, true);
view.setUint16(32, 2, true); view.setUint16(34, 16, true);
write(36, "data"); view.setUint32(40, samples * 2, true);
let offset = 44;
for (const chunk of chunks) {
for (let i = 0; i < chunk.length; i++, offset += 2) view.setInt16(offset, chunk[i], true);
}
return new Blob([buffer], { type: "audio/wav" });
}
function download_blob(blob, name) {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
}
// ── ASR workbench ─────────────────────────────────────────────────────
function asr_query(path) {
const query = new URLSearchParams();
if (path === "/asr/stream") {
query.set("chunk_len", el("asChunk").value);
} else {
query.set("vad_threshold", el("vaThreshold").value);
query.set("vad_end_silence_ms", el("vaSilence").value);
query.set("vad_partial_ms", el("vaPartial").value);
query.set("vad_min_segment_ms", el("vaMinSeg").value);
query.set("vad_max_segment_ms", el("vaMaxSeg").value);
query.set("two_pass", el("vaTwoPass").checked ? "1" : "0");
query.set("ctc_precheck", el("vaCtcPrecheck").checked ? "1" : "0");
}
return path + "?" + query.toString();
}
function reset_asr_stats() {
asr.audio_samples = 0; asr.messages = 0; asr.finals = 0;
asr.last_event = performance.now(); asr.started_at = performance.now();
set_text("asAudio", "0.0s"); set_text("asRms", "-120 dB");
set_text("asPeak", "peak -120 dB"); set_text("asMessages", "0");
set_text("asFinals", final_label(0)); set_text("asIdle", "0s");