Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
3385 lines (2979 loc) · 150 KB
/
Copy pathapp.py
File metadata and controls
3385 lines (2979 loc) · 150 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
"""
Qwen3 ASR 字幕生成器 - CustomTkinter 前端
功能:
1. 音檔上傳 → SRT 字幕(支援 OpenVINO CPU / GPU)
2. 錄製轉換:偵測音訊輸入裝置,錄音後於說話停頓時轉換成字幕
"""
from __future__ import annotations
# ── UTF-8 模式:在所有其他 import 之前設定 ────────────────────────────
# 解決 Traditional Chinese Windows(cp950)上第三方套件用系統預設編碼
# 讀取 UTF-8 檔案時出現 "utf-8 codec can't decode byte 0xa6" 的問題。
# PYTHONUTF8=1 等效於 `python -X utf8`,讓所有 open() 預設使用 UTF-8。
import os as _os, sys as _sys, io as _io
_os.environ.setdefault("PYTHONUTF8", "1")
# 同步修正 stdout/stderr(避免 print 中文在 cp950 console 出錯)
for _stream_name in ("stdout", "stderr"):
_s = getattr(_sys, _stream_name)
if hasattr(_s, "buffer") and _s.encoding.lower() not in ("utf-8", "utf8"):
setattr(_sys, _stream_name,
_io.TextIOWrapper(_s.buffer, encoding="utf-8", errors="replace"))
del _os, _sys, _io, _stream_name, _s
import json
import os
import re
import sys
import tempfile
import time
import threading
import queue
from datetime import datetime
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox
import numpy as np
import customtkinter as ctk
# ── chatllm 後端(可選,import 延遲到 load 時進行)────────────────────
try:
from chatllm_engine import (
ChatLLMASREngine, detect_vulkan_devices, probe_vulkan_devices,
format_vad_diag, detect_degenerate_asr,
)
_CHATLLM_AVAILABLE = True
except Exception:
_CHATLLM_AVAILABLE = False
ChatLLMASREngine = None
def detect_vulkan_devices(_): return []
def probe_vulkan_devices(_):
return {"devices": [], "all_devices": [], "raw": "",
"error": "chatllm 未載入", "exit_code": None, "exe_found": False}
def format_vad_diag(_stats): return "⚠ 未偵測到人聲,未產生字幕"
def detect_degenerate_asr(_text): return None
# ── CrispASR 後端(可選,Whisper/Breeze 走 Vulkan)─────────────────────
try:
from crisp_engine import CrispWhisperEngine
_CRISPASR_AVAILABLE = True
except Exception:
_CRISPASR_AVAILABLE = False
CrispWhisperEngine = None
# ── 字幕分行(全引擎共用,與 CrispASR/Whisper 統一)────────────────────
from subtitle_lines import (
MAX_CHARS, _ZH_CLAUSE_END, _EN_SENT_END,
_srt_ts, _merge_orphan_lines, _ts_chatllm_to_subtitle_lines,
write_transcript, spaced_lines_from_text,
)
import subtitle_lines as _subs
def _resolve_backend(core: str, model_label: str):
"""(核心, 模型標籤) → (backend, 量化/尺寸)。三層選擇的中央映射。
回傳:
("crispasr", "q4"|"q5"|"q8") — Whisper / Breeze
("chatllm", None) — Qwen 1.7B Q8 (Vulkan)
("openvino", "1.7B"|"0.6B") — Qwen OpenVINO
"""
if "Whisper" in core or "Breeze" in model_label:
q = "q4" if "Q4" in model_label else "q8" if "Q8" in model_label else "q5"
return "crispasr", q
if "Q8 (Vulkan)" in model_label:
return "chatllm", None
if "1.7B INT8" in model_label:
return "openvino", "1.7B"
return "openvino", "0.6B"
def _core_for_backend(backend: str) -> str:
"""backend → 核心標籤(載入完成後同步 UI 用)。"""
return "Whisper (Breeze)" if backend == "crispasr" else "Qwen"
def _ui_core_model(settings: dict):
"""settings → (核心標籤, 模型標籤),供載入後同步 UI 下拉。"""
backend = settings.get("backend", "openvino")
if backend == "crispasr":
q = settings.get("crisp_quant", "q5")
label = {"q4": "Breeze Q4 (輕量)", "q5": "Breeze Q5 (標準)",
"q8": "Breeze Q8 (精確)"}.get(q, "Breeze Q5 (標準)")
return "Whisper (Breeze)", label
if backend == "chatllm":
return "Qwen", "Qwen3-ASR-1.7B Q8 (Vulkan)"
sz = settings.get("cpu_model_size", "0.6B")
return "Qwen", ("Qwen3-ASR-1.7B INT8" if "1.7B" in sz else "Qwen3-ASR-0.6B")
# ── 路徑 ──────────────────────────────────────────────
# PyInstaller 凍結時,模型應放在 EXE 旁邊(非 _internal/)
if getattr(sys, "frozen", False):
BASE_DIR = Path(sys.executable).parent
else:
BASE_DIR = Path(__file__).parent
# PyInstaller onefile 解壓的暫存資源根(_MEIPASS):--add-data 進來的檔案在這裡,
# 不在 EXE 旁。隨包附帶的小檔(如 silero_vad_v4.onnx)要從這裡找得到,否則凍結後
# 在 BASE_DIR(EXE 旁)找不到 → VAD 載入失敗、模型永遠停在「載入 VAD…」。
_MEIPASS_DIR = Path(getattr(sys, "_MEIPASS", "")) if getattr(sys, "frozen", False) else None
_DEFAULT_MODEL_DIR = BASE_DIR / "ov_models"
SETTINGS_FILE = BASE_DIR / "settings.json"
SRT_DIR = BASE_DIR / "subtitles"
_CHATLLM_DIR = BASE_DIR / "chatllm"
# .bin 優先找 ov_models/(開發期),再找 GPUModel/(打包後下載位置)
_BIN_PATH = next(
(p for p in [
BASE_DIR / "ov_models" / "qwen3-asr-1.7b.bin",
BASE_DIR / "GPUModel" / "qwen3-asr-1.7b.bin",
] if p.exists()),
BASE_DIR / "GPUModel" / "qwen3-asr-1.7b.bin", # 預設(未下載時)
)
SRT_DIR.mkdir(exist_ok=True)
# ── 常數 ────────# 常數
SAMPLE_RATE = 16000
VAD_CHUNK = 512
VAD_THRESHOLD = 0.5 # 可由設定頁調整(降低可減少掴字)
MAX_GROUP_SEC = 20
MIN_SUB_SEC = 0.6
GAP_SEC = 0.08
RT_SILENCE_CHUNKS = 25 # ~0.8s 靜音後觸發轉錄
RT_MAX_BUFFER_CHUNKS = 600 # ~19s 上限強制轉錄
# ── ForcedAligner 相關常數 ─────────────────────────────────────────
GPU_MODEL_DIR = BASE_DIR / "GPUModel"
ALIGNER_MODEL_NAME = "Qwen3-ForcedAligner-0.6B"
# 斷句標點集合 _ZH_CLAUSE_END / _EN_SENT_END 已移至 subtitle_lines(共用)
# ══════════════════════════════════════════════════════
# 共用工具函式
# ══════════════════════════════════════════════════════
def _detect_speech_groups(audio: np.ndarray, vad_sess, max_group_sec: int = MAX_GROUP_SEC,
stats: dict | None = None) -> list[tuple[float, float, np.ndarray]]:
"""Silero VAD 分段,回傳 [(start_s, end_s, chunk), ...]
可傳入 stats dict,函式會填入 n_chunks / max_prob / mean_prob / threshold /
n_segments,供上層在「未偵測到人聲」時產生明確診斷(見 format_vad_diag)。
"""
h = np.zeros((2, 1, 64), dtype=np.float32)
c = np.zeros((2, 1, 64), dtype=np.float32)
sr = np.array(SAMPLE_RATE, dtype=np.int64)
n = len(audio) // VAD_CHUNK
probs = []
for i in range(n):
chunk = audio[i*VAD_CHUNK:(i+1)*VAD_CHUNK].astype(np.float32)[np.newaxis, :]
out, h, c = vad_sess.run(None, {"input": chunk, "h": h, "c": c, "sr": sr})
probs.append(float(out[0, 0]))
if stats is not None:
stats["n_chunks"] = len(probs)
stats["max_prob"] = max(probs) if probs else 0.0
stats["mean_prob"] = (sum(probs) / len(probs)) if probs else 0.0
stats["threshold"] = VAD_THRESHOLD
if not probs:
return [(0.0, len(audio) / SAMPLE_RATE, audio)]
MIN_CH = 16; PAD = 5; MERGE = 16
raw: list[tuple[int, int]] = []
in_sp = False; s0 = 0
for i, p in enumerate(probs):
if p >= VAD_THRESHOLD and not in_sp:
s0 = i; in_sp = True
elif p < VAD_THRESHOLD and in_sp:
if i - s0 >= MIN_CH:
raw.append((max(0, s0-PAD), min(n, i+PAD)))
in_sp = False
if in_sp and n - s0 >= MIN_CH:
raw.append((max(0, s0-PAD), n))
if stats is not None:
stats["n_segments"] = len(raw)
if not raw:
return []
merged = [list(raw[0])]
for s, e in raw[1:]:
if s - merged[-1][1] <= MERGE:
merged[-1][1] = e
else:
merged.append([s, e])
mx_samp = max_group_sec * SAMPLE_RATE
groups: list[tuple[int, int]] = []
gs = merged[0][0] * VAD_CHUNK
ge = merged[0][1] * VAD_CHUNK
for seg in merged[1:]:
s = seg[0] * VAD_CHUNK; e = seg[1] * VAD_CHUNK
if e - gs > mx_samp:
groups.append((gs, ge)); gs = s
ge = e
groups.append((gs, ge))
result = []
_tail = int(0.35 * SAMPLE_RATE) # 多含尾段 0.35s:補捉 Silero 漏掉的句尾輕聲字(的/了/嗎)
for gs, ge in groups:
# 取完整語音段並多含一點尾巴;mel 會在 processor 補零到固定長度,整秒對齊
# 非必要。舊版 floor 會丟尾段近 1 秒;句尾輕聲字也常被 Silero 的 ge 排除。
ch = audio[gs: min(len(audio), ge + _tail)].astype(np.float32)
if len(ch) < SAMPLE_RATE // 2: # 最小 0.5 秒
continue
result.append((gs / SAMPLE_RATE, ge / SAMPLE_RATE, ch))
return result
def _split_to_lines(text: str) -> list[str]:
"""以標點符號切分短句,移除標點,每句獨立成行。
斷句規則(英文/中文統一):
1. 所有標點(,.!?;: 及中文,。?!;:…—)→ 立即切行,標點不輸出
2. 英文整字為最小單位,詞前補空格(詞界)
3. MAX_CHARS 保護:超限才強制換行
"""
if "<asr_text>" in text:
text = text.split("<asr_text>", 1)[1]
text = text.strip()
if not text:
return []
# 中文、英文標點統一觸發切行(含英文逗號)
PUNCT = frozenset(',。?!;:…—、.,!?;:')
lines: list[str] = []
buf = ""
i = 0
while i < len(text):
ch = text[i]
# ── 標點符號:切行,標點不加入輸出(隱藏)────────────────────
if ch in PUNCT:
if buf.strip():
lines.append(buf.strip())
buf = ""
i += 1
continue
# ── 英文單字:整字收集,詞前補空格(詞界)────────────────────
if ch.isalpha() and ord(ch) < 128:
j = i
while j < len(text) and text[j].isalpha() and ord(text[j]) < 128:
j += 1
word = text[i:j]
prefix = " " if buf and not buf.endswith(" ") else ""
if len(buf) + len(prefix) + len(word) > MAX_CHARS and buf.strip():
lines.append(buf.strip())
buf = word
else:
buf += prefix + word
i = j
continue
# ── 空格:保留分詞間距 ────────────────────────────────────────
if ch == " ":
if buf and not buf.endswith(" "):
buf += " "
i += 1
if len(buf.rstrip()) >= MAX_CHARS:
lines.append(buf.strip())
buf = ""
continue
# ── 中文/日文/數字等:逐字累積 ────────────────────────────────
buf += ch
i += 1
if len(buf) >= MAX_CHARS:
lines.append(buf.strip())
buf = ""
if buf.strip():
lines.append(buf.strip())
return [l for l in lines if l.strip()]
# _srt_ts 已移至 subtitle_lines(共用)
def _assign_ts(lines: list[str], g0: float, g1: float) -> list[tuple[float, float, str]]:
if not lines:
return []
total = sum(len(l) for l in lines)
if total == 0:
return []
dur = g1 - g0; res = []; cur = g0
for i, line in enumerate(lines):
end = cur + max(MIN_SUB_SEC, dur * len(line) / total)
if i == len(lines) - 1:
end = max(end, g1)
res.append((cur, end, line))
cur = end + GAP_SEC
return res
def _find_vad_model(model_dir: Path | None = None) -> Path | None:
"""尋找 Silero VAD ONNX:指定 model_dir → ov_models/ → GPUModel/ → _MEIPASS(打包)。
凍結後隨包附帶的 silero_vad_v4.onnx 位於 _MEIPASS/ov_models(--add-data),
故必須把它納入搜尋,否則在 EXE 旁的 ov_models/ 找不到 → VAD 載入卡死。
"""
candidates: list[Path] = []
if model_dir is not None:
candidates += [Path(model_dir) / "silero_vad_v4.onnx",
Path(model_dir) / "silero_vad.onnx"]
candidates += [
_DEFAULT_MODEL_DIR / "silero_vad_v4.onnx",
GPU_MODEL_DIR / "silero_vad_v4.onnx",
_DEFAULT_MODEL_DIR / "silero_vad.onnx",
GPU_MODEL_DIR / "silero_vad.onnx",
]
if _MEIPASS_DIR is not None:
candidates += [_MEIPASS_DIR / "ov_models" / "silero_vad_v4.onnx",
_MEIPASS_DIR / "silero_vad_v4.onnx"]
for p in candidates:
if p.exists():
return p
return None
# _merge_orphan_lines 已移至 subtitle_lines(共用)
def _ts_to_subtitle_lines(
ts_list,
raw_text: str,
chunk_offset: float,
spk: str | None,
cc,
simplified: bool,
aligner_processor=None,
language: str | None = None,
) -> list[tuple[float, float, str, str | None]]:
"""ForcedAligner token(詞級別)+ ASR 原文(含標點)→ 字幕行。
使用 FA 的 aligner_processor.tokenize_space_lang() 產出 word_list,
保證與 ts_list 完全 1:1 對應。再將每個 word 映射回 raw_text 的
原始位置,以標點觸發切行。
"""
_all_punct = _ZH_CLAUSE_END | _EN_SENT_END
MAX_WORDS = 8
MAX_ZH_CHARS = MAX_CHARS
result: list[tuple[float, float, str, str | None]] = []
if not ts_list or not raw_text.strip():
return result
# ── 1. 用 FA 的 tokenizer 產出 word_list(與 ts_list 1:1)────────
lang_lower = (language or "chinese").lower()
if aligner_processor is not None:
if lang_lower == "japanese":
word_list = aligner_processor.tokenize_japanese(raw_text)
elif lang_lower == "korean":
if aligner_processor.ko_tokenizer is None:
try:
from soynlp.tokenizer import LTokenizer
aligner_processor.ko_tokenizer = LTokenizer(
scores=aligner_processor.ko_score)
except ImportError:
pass
if aligner_processor.ko_tokenizer is not None:
word_list = aligner_processor.tokenize_korean(
aligner_processor.ko_tokenizer, raw_text)
else:
word_list = aligner_processor.tokenize_space_lang(raw_text)
else:
word_list = aligner_processor.tokenize_space_lang(raw_text)
else:
# Fallback: 模擬 tokenize_space_lang(相容舊路徑)
word_list = []
for seg in raw_text.split():
cleaned = "".join(c for c in seg
if c.isalpha() or c.isdigit() or c == "'")
if not cleaned:
continue
buf = ""
for c in cleaned:
if '\u4e00' <= c <= '\u9fff':
if buf:
word_list.append(buf); buf = ""
word_list.append(c)
else:
buf += c
if buf:
word_list.append(buf)
# 取 min 以防長度不一致(防禦性)
n = min(len(word_list), len(ts_list))
# ── 2. 為每個 word 在 raw_text 中找到對應位置 ────────────────────
# 並記錄「在這個 word 之前有哪些標點」→ 用於切行
seg_tokens: list = [] # 當前行的 FA token
seg_words: list[str] = [] # 當前行的原始 word
ri = 0 # raw_text 掃描位置
def _is_latin_word(w: str) -> bool:
return any(c.isascii() and c.isalpha() for c in w)
def _emit():
nonlocal seg_tokens, seg_words
if not seg_tokens:
seg_tokens = []
seg_words = []
return
start = chunk_offset + seg_tokens[0].start_time
end = chunk_offset + seg_tokens[-1].end_time
# 重建文字:有拉丁詞用空格 join,純中文直接 join
if any(_is_latin_word(w) for w in seg_words):
text = " ".join(seg_words)
else:
text = "".join(seg_words)
if not simplified and cc is not None:
text = cc.convert(text)
if end > start and text.strip():
result.append((start, end, text.strip(), spk))
seg_tokens = []
seg_words = []
def _over_limit() -> bool:
if any(_is_latin_word(w) for w in seg_words):
return len(seg_words) > MAX_WORDS
return sum(len(w) for w in seg_words) > MAX_ZH_CHARS
for wi in range(n):
word = word_list[wi]
tok = ts_list[wi] # ForcedAlignItem: .text, .start_time, .end_time
# 在 raw_text 中前進到 word 的位置(跳過標點和空格)
# 遇到標點 → 切行
hit_punct = False
while ri < len(raw_text):
c = raw_text[ri]
if c in _all_punct:
hit_punct = True
ri += 1
continue
if c == " ":
ri += 1
continue
break # 到達下一個有效字元
if hit_punct:
_emit() # 標點前的內容先輸出
seg_tokens.append(tok)
seg_words.append(word)
# 在 raw_text 中跳過 word 佔用的字元
consumed = 0
word_len = len(word)
while ri < len(raw_text) and consumed < word_len:
c = raw_text[ri]
if c in _all_punct or c == " ":
ri += 1
continue
ri += 1
consumed += 1
# MAX_CHARS / MAX_WORDS 保護
if _over_limit():
_emit()
# ── 3. 清空剩餘 ──────────────────────────────────────────────────
_emit()
return _merge_orphan_lines(result)
# _ts_chatllm_to_subtitle_lines 已移至 subtitle_lines(共用,全引擎統一)
def _rebuild_text_with_spaces(raw_chars: list[str]) -> str:
"""以 raw_text 的字元序列(含空格)重建可讀字幕文字(輔助函式,保留相容)。"""
result: list[str] = []
for ch in raw_chars:
if ch == " ":
if result and result[-1] != " ":
result.append(" ")
else:
result.append(ch)
return "".join(result).strip()
# 全域:是否輸出簡體中文(True = 跳過 OpenCC 繁化)
_g_output_simplified: bool = False
# 全域:繁體輸出時是否啟用「簡繁詞彙轉換」
# True → OpenCC "s2twp":除字形外,連詞彙也在地化(軟件→軟體、質量→品質)
# False → OpenCC "s2t" :僅字形轉換,保留原始用詞(軟件、質量)
# 僅在繁體模式(_g_output_simplified=False)下有意義。
_g_vocab_convert: bool = True
def _opencc_config() -> str:
"""依目前詞彙轉換旗標回傳對應的 OpenCC 設定名稱。"""
return "s2twp" if _g_vocab_convert else "s2t"
# ══════════════════════════════════════════════════════
# ASR 引擎
# ══════════════════════════════════════════════════════
class ASREngine:
"""封裝所有模型。transcribe() 加互斥鎖,多執行緒安全。"""
max_chunk_secs: int = 30 # 每段最長音訊(秒),子類別可覆寫
_OV_SUBDIR: str = "qwen3_asr_int8" # model_dir 下的 OV 模型子目錄,子類別可覆寫
# 時間軸對齊改用 chatllm 原生 FA(無需 torch);與 ChatLLMASREngine 共用
# 同一檔名與下載流程,讓「時間軸對齊」UI 在 CPU/GPU 後端行為一致。
FA_BIN_NAME = "qwen3-focedaligner-0.6b.bin"
def __init__(self):
self.ready = False
self._lock = threading.Lock()
self.vad_sess = None
self.audio_enc = None
self.embedder = None
self.dec_req = None
self.processor = None # LightProcessor(不含 torch)
self.pad_id = None
self.cc = None
self.diar_engine = None # DiarizationEngine(可選)
self.aligner = None # 相容旗標(chatllm FA 就緒時為 True)
self.use_aligner = False # 是否啟用時間軸對齊
self._fa = None # ChatLLMAligner(chatllm 原生 FA)
self._fa_bin = None # FA .bin 路徑(就緒時非 None)
self._model_dir = None # 模型資料夾(FA .bin 與下載位置)
def load(self, device: str = "CPU", model_dir: Path = None, cb=None, cpu_threads: int = 0):
"""從背景執行緒呼叫。cb(msg) 用於更新 UI 狀態。
cpu_threads: 0=OpenVINO 自動,>0=指定邏輯核心數(LATENCY hint)
"""
import onnxruntime as ort
import openvino as ov
import opencc
from processor_numpy import LightProcessor
if model_dir is None:
model_dir = _DEFAULT_MODEL_DIR
self._model_dir = model_dir # FA .bin 與按需下載位置
ov_dir = model_dir / self._OV_SUBDIR # 0.6B / 1.7B 由類屬性決定
# ── CPU 執行緒設定 ─────────────────────────────────────────────
# LATENCY hint:單一請求最低延遲(不同於 THROUGHPUT 批次模式)
# ENABLE_HYPER_THREADING YES:確保 P-core HT 與 E-core 均被使用
cpu_cfg: dict = {}
if device == "CPU":
cpu_cfg["PERFORMANCE_HINT"] = "LATENCY"
cpu_cfg["ENABLE_HYPER_THREADING"] = "YES"
if cpu_threads > 0:
cpu_cfg["INFERENCE_NUM_THREADS"] = str(cpu_threads)
# VAD 路徑:含 _MEIPASS(打包)等多處搜尋,凍結後才找得到隨包附帶的 onnx。
vad_path = _find_vad_model(model_dir)
def _s(msg):
if cb: cb(msg)
if vad_path is None:
raise FileNotFoundError(
"找不到 silero_vad_v4.onnx(VAD 模型)。請確認已隨安裝包附帶或放入 ov_models/。")
_s("載入 VAD 模型…")
self.vad_sess = ort.InferenceSession(
str(vad_path), providers=["CPUExecutionProvider"]
)
_s("載入說話者分離模型…")
try:
from diarize import DiarizationEngine
diar_dir = model_dir / "diarization"
eng = DiarizationEngine(diar_dir)
self.diar_engine = eng if eng.ready else None
except Exception:
self.diar_engine = None
_s(f"編譯 ASR 模型({device})…")
core = ov.Core()
self.audio_enc = core.compile_model(str(ov_dir / "audio_encoder_model.xml"), device, cpu_cfg)
self.embedder = core.compile_model(str(ov_dir / "thinker_embeddings_model.xml"), device, cpu_cfg)
self._compile_decoder(core, ov_dir, device, cpu_cfg) # 0.6B stateful / 1.7B KV-cache
_s("載入 Processor(純 numpy)…")
self.processor = LightProcessor(ov_dir)
self.pad_id = self.processor.pad_id
self.cc = opencc.OpenCC(_opencc_config())
# ── ForcedAligner(chatllm 原生,CPU -ngl 0,無需 torch)──────────
# 與 ChatLLMASREngine 共用 chatllm main.exe 子程序對齊邏輯。
# 缺 .bin 時靜默退回比例估算;UI 會引導使用者按需下載。
self._load_aligner(cb=_s)
# 抑制 "Setting pad_token_id to eos_token_id" 重複警告
try:
import transformers.utils.logging as _tf_logging
import logging as _logging
_tf_logging.get_logger("transformers.generation.utils").setLevel(_logging.ERROR)
except Exception:
pass
self.ready = True
aligner_info = " + ForcedAligner" if self.use_aligner else ""
_s(f"編譯完成({device}{aligner_info})")
def rebuild_cc(self):
"""依目前的詞彙轉換旗標重建 OpenCC 轉換器(免重新載入模型)。"""
try:
import opencc
self.cc = opencc.OpenCC(_opencc_config())
except Exception:
pass
# ── 時間軸對齊(chatllm 原生 FA,CPU -ngl 0)──────────────────────────
def _load_aligner(self, cb=None):
"""偵測 chatllm 版 ForcedAligner .bin(與 ASR .bin 同層 model_dir)。
OpenVINO 後端沿用 chatllm main.exe 子程序做字級對齊(CPU -ngl 0),
完全不需 PyTorch。缺 .bin 或驗證失敗時靜默退回比例估算,UI 會引導
使用者按需下載。
"""
from fa_aligner import ChatLLMAligner
self.aligner = None
self.use_aligner = False
self._fa_bin = None
# FA 一律以 CPU 子程序執行(n_gpu_layers=0),與 OpenVINO 裝置選擇無關,
# 避免 Vulkan/Intel 裝置 id 不一致;CPU 對齊已足夠快。
self._fa = ChatLLMAligner(fa_dir=self._model_dir, n_gpu_layers=0)
if self._fa.load(cb=cb):
self._fa_bin = self._fa._fa_bin
self.aligner = True # 相容旗標(沿用 use_aligner 判斷流程)
self.use_aligner = True
def _align_chunk(
self,
wav_path: str,
ref_text: str,
language: str = "Chinese",
) -> list[tuple[str, float, float]]:
"""委派 chatllm FA 對齊「參考文字 + 音訊」,回傳字級時間軸。"""
if self._fa is None or not self._fa_bin:
return []
return self._fa.align_chunk(wav_path, ref_text, language)
# ── Decoder 掛勾(0.6B stateful;ASREngine1p7B 覆寫為 KV-cache)───────
# 2026-08 修正:舊版 ASREngine1p7B 的 load/推理覆寫在 ce1f8b0 重構時被
# 誤刪,導致「1.7B INT8」實際上載入 0.6B 目錄(只裝 1.7B 的機器直接
# 報 Could not open qwen3_asr_int8/...xml)。改以掛勾點分離差異。
def _compile_decoder(self, core, ov_dir: Path, device: str, cpu_cfg: dict):
"""編譯 decoder。0.6B:單一 stateful decoder_model.xml。"""
dec_comp = core.compile_model(str(ov_dir / "decoder_model.xml"), device, cpu_cfg)
self.dec_req = dec_comp.create_infer_request()
def _encode_audio(self, mel) -> np.ndarray:
"""mel → audio embeds。1.7B 匯出的輸入不含 batch 維度,由子類覆寫。"""
return list(self.audio_enc({"mel": mel}).values())[0]
def _generate_tokens(self, combined: np.ndarray, max_tokens: int) -> list[int]:
"""自回歸貪婪解碼(0.6B stateful decoder)。回傳生成的 token id 列表。
transcribe() 與 process_file() 共用此迴圈(原本兩處內聯重複)。
"""
L = combined.shape[1]
pos = np.arange(L, dtype=np.int64)[np.newaxis, :]
self.dec_req.reset_state()
out = self.dec_req.infer({0: combined, "position_ids": pos})
logits = list(out.values())[0]
eos = self.processor.eos_id
eot = self.processor.eot_id
gen: list[int] = []
nxt = int(np.argmax(logits[0, -1, :])); cur = L
while nxt not in (eos, eot) and len(gen) < max_tokens:
gen.append(nxt)
emb = list(self.embedder(
{"input_ids": np.array([[nxt]], dtype=np.int64)}
).values())[0]
out = self.dec_req.infer(
{0: emb, "position_ids": np.array([[cur]], dtype=np.int64)}
)
logits = list(out.values())[0]
nxt = int(np.argmax(logits[0, -1, :])); cur += 1
return gen
def transcribe(
self,
audio: np.ndarray,
max_tokens: int = 300,
language: str | None = None,
context: str | None = None,
) -> str:
"""將 16kHz float32 音訊轉錄為繁體中文。
language : 強制語系(如 "Chinese"),None 表示自動偵測
context : 辨識提示(歌詞/關鍵字),放入 system message
"""
with self._lock:
# ── 前處理(純 numpy,不需 torch)────────────────────────
mel, ids = self.processor.prepare(audio, language=language, context=context)
# ── 音頻編碼 + 文字 Embedding ────────────────────────────
ae = self._encode_audio(mel)
te = list(self.embedder({"input_ids": ids}).values())[0]
# ── 音頻特徵填入音頻 pad 位置 ─────────────────────────────
combined = te.copy()
mask = ids[0] == self.pad_id
np_ = int(mask.sum()); na = ae.shape[1]
if np_ != na:
mn = min(np_, na)
combined[0, np.where(mask)[0][:mn]] = ae[0, :mn]
else:
combined[0, mask] = ae[0]
# ── Decoder 自回歸生成(0.6B stateful / 1.7B KV-cache 掛勾)──
gen = self._generate_tokens(combined, max_tokens)
# ── 解碼(純 Python BPE decode)──────────────────────────
raw = self.processor.decode(gen)
if "<asr_text>" in raw:
raw = raw.split("<asr_text>", 1)[1]
text = raw.strip()
return _subs.to_traditional(self.cc, text, _g_output_simplified)
def _enforce_chunk_limit(
self,
groups: list[tuple[float, float, np.ndarray, "str | None"]],
) -> list[tuple[float, float, np.ndarray, "str | None"]]:
"""將超過 max_chunk_secs 的音訊段落切分為等長子片段。
不論是說話者分離路徑或 VAD 單段路徑,都可能產生比模型
輸入長度(max_chunk_secs)更長的 chunk。若不切分,
_extract_mel() 會靜默截斷尾段,造成掉字。
"""
max_samples = self.max_chunk_secs * SAMPLE_RATE
result = []
for t0, t1, chunk, spk in groups:
if len(chunk) <= max_samples:
result.append((t0, t1, chunk, spk))
else:
pos = 0
while pos < len(chunk):
piece = chunk[pos: pos + max_samples]
if len(piece) < SAMPLE_RATE: # 不足 1 秒的殘餘片段跳過
break
piece_t0 = t0 + pos / SAMPLE_RATE
piece_t1 = min(t1, piece_t0 + len(piece) / SAMPLE_RATE)
result.append((piece_t0, piece_t1, piece, spk))
pos += max_samples
return result
def process_file(
self,
audio_path: Path,
progress_cb=None,
language: str | None = None,
context: str | None = None,
diarize: bool = False,
n_speakers: int | None = None,
original_path: Path | None = None,
out_format: str | None = None,
) -> Path | None:
"""音檔 → 字幕檔,回傳輸出路徑(.srt 或 .txt)。
language : 強制語系(如 "Chinese"),None 表示自動偵測
context : 辨識提示(歌詞/關鍵字),放入 system message
diarize : True 時用說話者分離取代 VAD,SRT 加說話者前綴
n_speakers : 指定說話者人數(None=自動偵測)
out_format : "srt" | "txt";None 採全域設定(端點固定傳 "srt")
"""
from audio_io import load_audio_16k_mono
audio, _ = load_audio_16k_mono(audio_path, SAMPLE_RATE)
self._deg_count = 0 # 本次退化(異常)輸出段數
self._last_vad_diag = None # 本次「未產生字幕」的明確原因
self._last_segments_rich = None # 本次字級結果(卡拉OK用,側通道;無對齊則 words=[])
# ── 分段策略:說話者分離 vs 傳統 VAD ─────────────────────────
# groups_spk: [(g0_sec, g1_sec, audio_chunk, speaker_label | None), ...]
use_diar = diarize and self.diar_engine is not None and self.diar_engine.ready
if use_diar:
diar_segs = self.diar_engine.diarize(audio, n_speakers=n_speakers)
if not diar_segs:
return None
groups_spk = [
(t0, t1,
audio[int(t0 * SAMPLE_RATE): int(t1 * SAMPLE_RATE)],
spk)
for t0, t1, spk in diar_segs
]
else:
if self.vad_sess is None:
self._last_vad_diag = "⚠ VAD 模型(silero_vad)未載入,無法分段"
if progress_cb:
progress_cb(0, 1, self._last_vad_diag)
return None
_vad_stats: dict = {}
vad_groups = _detect_speech_groups(
audio, self.vad_sess, self.max_chunk_secs, stats=_vad_stats)
if not vad_groups:
self._last_vad_diag = format_vad_diag(_vad_stats)
if progress_cb:
progress_cb(0, 1, self._last_vad_diag)
return None
groups_spk = [(g0, g1, chunk, None) for g0, g1, chunk in vad_groups]
# 強制切分超過 max_chunk_secs 的片段(兩條路徑都需要)
groups_spk = self._enforce_chunk_limit(groups_spk)
# ── ASR 逐段轉錄 ─────────────────────────────────────────────
all_subs: list[tuple[float, float, str, str | None]] = []
all_rich: list[dict] = [] # 與 all_subs 平行的字級結構(卡拉OK用)
total = len(groups_spk)
for i, (g0, g1, chunk, spk) in enumerate(groups_spk):
if progress_cb:
spk_info = f" [{spk}]" if spk else ""
progress_cb(i, total,
f"[{i+1}/{total}] {g0:.1f}s~{g1:.1f}s{spk_info}")
# ── ASR 轉錄(取簡體原始輸出,對齊後再繁化)─────────────────
max_tok = 400 if language == "Japanese" else 300
with self._lock:
mel, ids = self.processor.prepare(
chunk, language=language, context=context)
ae = self._encode_audio(mel)
te = list(self.embedder({"input_ids": ids}).values())[0]
combined = te.copy()
mask = ids[0] == self.pad_id
np_ = int(mask.sum()); na = ae.shape[1]
if np_ != na:
mn = min(np_, na)
combined[0, np.where(mask)[0][:mn]] = ae[0, :mn]
else:
combined[0, mask] = ae[0]
# 生成(0.6B stateful / 1.7B KV-cache 掛勾)
gen = self._generate_tokens(combined, max_tok)
raw_decoded = self.processor.decode(gen)
if "<asr_text>" in raw_decoded:
raw_decoded = raw_decoded.split("<asr_text>", 1)[1]
raw_text = raw_decoded.strip()
if not raw_text:
continue
# 退化輸出(複誦提示範本 / 高度重複)→ 不寫入垃圾字幕,跳過並記錄
deg = detect_degenerate_asr(raw_text)
if deg:
self._deg_count = getattr(self, "_deg_count", 0) + 1
self._deg_reason = deg
if progress_cb:
progress_cb(i, total, f"[{i+1}/{total}] 略過異常輸出:{deg}")
continue
# ── ForcedAligner 精確時間軸對齊(chatllm .bin,CPU -ngl 0)──
# 把 chunk 寫成暫存 wav,交給 chatllm main.exe 做字級對齊,
# 再用 _ts_chatllm_to_subtitle_lines 依字級時間軸+標點切行。
aligned = False
if self.use_aligner and self._fa_bin is not None:
import tempfile as _tempfile
import soundfile as _sf
with _tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as _tf:
_tmp_wav = _tf.name
try:
_sf.write(_tmp_wav, chunk, SAMPLE_RATE, subtype="PCM_16")
align_lang = language if (language and language != "自動偵測") else "Chinese"
ts_items = self._align_chunk(_tmp_wav, raw_text, align_lang)
if ts_items:
subs = _ts_chatllm_to_subtitle_lines(
ts_items, raw_text, g0, spk,
self.cc, _g_output_simplified, with_words=True,
)
if subs:
for (s, e, t, sp, words) in subs:
all_subs.append((s, e, t, sp))
all_rich.append({"start": s, "end": e, "text": t,
"speaker": sp, "words": words})
aligned = True
except Exception:
aligned = False # 靜默 fallback 到比例估算
finally:
try:
os.remove(_tmp_wav)
except OSError:
pass
if not aligned:
# ── 比例估算 Fallback ──────────────────────────────────────
# 英文/韓文走共用的空白分詞分行(保留標點、不拆撇號);其餘照舊。
spaced = spaced_lines_from_text(raw_text, g0, g1, spk)
if spaced is not None:
est = [(s, e, line) for (s, e, line, _sp, _w) in spaced]
else:
text = _subs.to_traditional(self.cc, raw_text, _g_output_simplified)
est = _assign_ts(_split_to_lines(text), g0, g1)
for s, e, line in est:
all_subs.append((s, e, line, spk))
all_rich.append({"start": s, "end": e, "text": line,
"speaker": spk, "words": []}) # 無對齊 → 前端內插
if not all_subs:
# 全部段落都退化(垃圾輸出)→ 給明確原因,而非「未偵測到人聲」
if getattr(self, "_deg_count", 0) > 0:
self._last_vad_diag = (
f"⚠ 模型輸出異常({getattr(self, '_deg_reason', '推理退化')}),"
f"共 {self._deg_count} 段被略過,未產生有效字幕。"
f"此核心/裝置可能不相容,建議改用 CPU(OpenVINO) 核心。"
)
return None
if progress_cb:
progress_cb(total, total, "寫入字幕…")
# 字級結果掛上實例(webview_backend 讀取以驅動卡拉OK逐字高亮)
self._last_segments_rich = all_rich
# 以原始檔案的目錄與檔名輸出(影片抽音軌時 audio_path 是暫存路徑)
# 共用寫出層:依全域設定(或 out_format 覆寫)產出 .srt 或 .txt。
ref = original_path if original_path is not None else audio_path
return write_transcript(ref, all_subs, out_format)
# ══════════════════════════════════════════════════════
# ASR 引擎 — 1.7B INT8 KV-cache 版本
# ══════════════════════════════════════════════════════
class ASREngine1p7B(ASREngine):
"""
Qwen3-ASR-1.7B OpenVINO KV-cache 引擎(INT8 版本)。
模型目錄:ov_models/qwen3_asr_1p7b_kv_int8/
audio_encoder_model.xml — mel(128,1000) → audio_embeds(1,130,2048)
thinker_embeddings_model.xml — input_ids → token_embeds
decoder_prefill_kv_model.xml — prefill pass → logit + past_keys + past_vals
decoder_kv_model.xml — decode step → logit + new_keys + new_vals
"""
_OV_SUBDIR = "qwen3_asr_1p7b_kv_int8"
max_chunk_secs = 10 # audio_encoder 匯出固定 T=1000(10s)
def __init__(self):
super().__init__()
self.pf_model = None # compiled prefill model
self.dc_model = None # compiled decode-step model
# ── 掛勾覆寫(load/transcribe/process_file 全部沿用基底類)────────────
# 2026-08 修正:KV-cache 推理實作曾於 ce1f8b0 重構時被誤刪,導致本類
# 退化成空殼、繼承 0.6B 的 load 而讀錯目錄。自 2343122 版本復原並改寫
# 為掛勾覆寫,讓 1.7B 同步取得 cpu_threads/FA 對齊等後續新功能。
def _compile_decoder(self, core, ov_dir: Path, device: str, cpu_cfg: dict):
"""1.7B:prefill + decode-step 兩個 KV-cache 模型,不用 stateful decoder。"""
self.pf_model = core.compile_model(
str(ov_dir / "decoder_prefill_kv_model.xml"), device, cpu_cfg)
self.dc_model = core.compile_model(
str(ov_dir / "decoder_kv_model.xml"), device, cpu_cfg)
self.dec_req = None
def _encode_audio(self, mel) -> np.ndarray:
"""1.7B audio_encoder 匯出的輸入不含 batch 維度:mel (128, 1000)。"""
return list(self.audio_enc({"mel": mel[0]}).values())[0]
def _generate_tokens(self, combined: np.ndarray, max_tokens: int) -> list[int]:
"""KV-cache 貪婪解碼:O(L²) prefill 一次 + O(n) 逐 token decode。"""
seq_len = combined.shape[1]
pos_ids = np.arange(seq_len, dtype=np.int64)[np.newaxis, :]
pf_out = self.pf_model({"input_embeds": combined, "position_ids": pos_ids})
pf_vals = list(pf_out.values())
logits = pf_vals[0] # (1, 1, vocab)
past_k = pf_vals[1] # (28, 1, 8, L, 128)
past_v = pf_vals[2]
eos = self.processor.eos_id
eot = self.processor.eot_id
nxt = int(np.argmax(logits[0, -1, :]))
if nxt in (eos, eot):
return []
gen = [nxt]
cur = seq_len
for _ in range(max_tokens - 1):
new_emb = list(self.embedder(
{"input_ids": np.array([[nxt]], dtype=np.int64)}
).values())[0]
dc_out = self.dc_model({
"new_embed": new_emb,
"new_pos": np.array([[cur]], dtype=np.int64),
"past_keys": past_k,
"past_values": past_v,
})
dc_vals = list(dc_out.values())