-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1568 lines (1434 loc) · 55.8 KB
/
Copy pathapp.py
File metadata and controls
1568 lines (1434 loc) · 55.8 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
from __future__ import annotations
import logging
from pathlib import Path
from threading import Event, Lock
import gradio as gr
from auto_asr.config import get_config_path, load_config, update_config
from auto_asr.funasr_asr import (
download_funasr_model,
preload_funasr_model,
release_funasr_resources,
)
from auto_asr.model_hub import get_models_dir, set_hf_endpoint
from auto_asr.pipeline import transcribe_to_subtitles
from auto_asr.qwen3_asr import (
Qwen3ASRConfig,
download_qwen3_models,
preload_qwen3_model,
release_qwen3_resources,
)
from auto_asr.subtitle_processing.pipeline import (
process_subtitle_file,
process_subtitle_file_multi,
)
from auto_asr.subtitle_processing.settings import (
save_subtitle_processing_settings,
save_subtitle_provider_settings,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
force=True,
)
logger = logging.getLogger(__name__)
_SAVED_CONFIG = load_config()
_CONFIG_PATH = get_config_path()
def _str(v: object | None) -> str:
return "" if v is None else str(v)
def _int(v: object | None, default: int) -> int:
try:
return int(v) # type: ignore[arg-type]
except Exception:
return default
def _clamp_int(v: int, lo: int, hi: int) -> int:
return max(lo, min(hi, v))
DEFAULT_HF_ENDPOINT = (
_str(_SAVED_CONFIG.get("hf_endpoint", "huggingface.co")).strip() or "huggingface.co"
)
# Apply at import time so subsequent model downloads (including in pipelines) use the same endpoint.
set_hf_endpoint(DEFAULT_HF_ENDPOINT)
DEFAULT_OPENAI_API_KEY = _str(_SAVED_CONFIG.get("openai_api_key")).strip()
DEFAULT_OPENAI_BASE_URL = _str(_SAVED_CONFIG.get("openai_base_url")).strip()
DEFAULT_MODEL = _str(_SAVED_CONFIG.get("model", "whisper-1")).strip() or "whisper-1"
DEFAULT_ASR_BACKEND = _str(_SAVED_CONFIG.get("asr_backend", "qwen3asr")).strip() or "qwen3asr"
if DEFAULT_ASR_BACKEND not in {"openai", "funasr", "qwen3asr"}:
DEFAULT_ASR_BACKEND = "qwen3asr"
DEFAULT_SUBTITLE_PROVIDER = (
_str(_SAVED_CONFIG.get("subtitle_provider", "openai")).strip() or "openai"
)
DEFAULT_SUBTITLE_OPENAI_API_KEY = _str(
_SAVED_CONFIG.get("subtitle_openai_api_key", DEFAULT_OPENAI_API_KEY)
).strip()
DEFAULT_SUBTITLE_OPENAI_BASE_URL = _str(
_SAVED_CONFIG.get("subtitle_openai_base_url", DEFAULT_OPENAI_BASE_URL)
).strip()
DEFAULT_SUBTITLE_LLM_MODEL = _str(
_SAVED_CONFIG.get("subtitle_llm_model", _SAVED_CONFIG.get("llm_model", "gpt-4o-mini"))
).strip() or "gpt-4o-mini"
try:
DEFAULT_SUBTITLE_LLM_TEMPERATURE = float(_SAVED_CONFIG.get("subtitle_llm_temperature", 0.2))
except Exception:
DEFAULT_SUBTITLE_LLM_TEMPERATURE = 0.2
DEFAULT_SUBTITLE_LLM_TEMPERATURE = max(0.0, min(2.0, DEFAULT_SUBTITLE_LLM_TEMPERATURE))
DEFAULT_SUBTITLE_TARGET_LANGUAGE = _str(_SAVED_CONFIG.get("subtitle_target_language", "zh")).strip()
if DEFAULT_SUBTITLE_TARGET_LANGUAGE not in {"zh", "en", "ja", "ko", "fr", "de", "es", "ru"}:
DEFAULT_SUBTITLE_TARGET_LANGUAGE = "zh"
DEFAULT_SUBTITLE_SPLIT_MODE = _str(
_SAVED_CONFIG.get("subtitle_split_mode", "inplace_newlines")
).strip() or "inplace_newlines"
if DEFAULT_SUBTITLE_SPLIT_MODE not in {"inplace_newlines", "split_to_cues"}:
DEFAULT_SUBTITLE_SPLIT_MODE = "inplace_newlines"
DEFAULT_SUBTITLE_CUSTOM_PROMPT = _str(_SAVED_CONFIG.get("subtitle_custom_prompt", ""))
DEFAULT_SUBTITLE_BATCH_SIZE = _clamp_int(_int(_SAVED_CONFIG.get("subtitle_batch_size"), 30), 1, 200)
DEFAULT_SUBTITLE_CONCURRENCY = _clamp_int(_int(_SAVED_CONFIG.get("subtitle_concurrency"), 4), 1, 16)
_saved_subtitle_processors = _SAVED_CONFIG.get("subtitle_processors", ["optimize"])
if isinstance(_saved_subtitle_processors, list):
DEFAULT_SUBTITLE_PROCESSORS = [
str(x)
for x in _saved_subtitle_processors
if str(x) in {"optimize", "translate", "split"}
] or ["optimize"]
else:
DEFAULT_SUBTITLE_PROCESSORS = ["optimize"]
DEFAULT_SUBTITLE_SPLIT_STRATEGY = (
_str(_SAVED_CONFIG.get("subtitle_split_strategy", "semantic")).strip() or "semantic"
)
if DEFAULT_SUBTITLE_SPLIT_STRATEGY not in {"semantic", "sentence"}:
DEFAULT_SUBTITLE_SPLIT_STRATEGY = "semantic"
DEFAULT_SUBTITLE_SPLIT_MAX_WORD_COUNT_CJK = _clamp_int(
_int(_SAVED_CONFIG.get("subtitle_split_max_word_count_cjk"), 18), 1, 200
)
DEFAULT_SUBTITLE_SPLIT_MAX_WORD_COUNT_ENGLISH = _clamp_int(
_int(_SAVED_CONFIG.get("subtitle_split_max_word_count_english"), 12), 1, 200
)
DEFAULT_SUBTITLE_TRANSLATE_REFLECT = bool(_SAVED_CONFIG.get("subtitle_translate_reflect", False))
DEFAULT_FUNASR_MODEL = _str(_SAVED_CONFIG.get("funasr_model", "iic/SenseVoiceSmall")).strip()
DEFAULT_FUNASR_DEVICE = _str(_SAVED_CONFIG.get("funasr_device", "auto")).strip() or "auto"
if DEFAULT_FUNASR_DEVICE not in {"auto", "cpu", "cuda:0"}:
DEFAULT_FUNASR_DEVICE = "auto"
DEFAULT_FUNASR_LANGUAGE = _str(_SAVED_CONFIG.get("funasr_language", "auto")).strip() or "auto"
DEFAULT_FUNASR_USE_ITN = bool(_SAVED_CONFIG.get("funasr_use_itn", True))
DEFAULT_FUNASR_ENABLE_PUNC = bool(_SAVED_CONFIG.get("funasr_enable_punc", True))
DEFAULT_QWEN3_MODEL = _str(_SAVED_CONFIG.get("qwen3_model", "Qwen/Qwen3-ASR-1.7B")).strip()
QWEN3_ASR_HF_URL = "https://huggingface.co/Qwen/Qwen3-ASR-1.7B"
DEFAULT_QWEN3_DEVICE = _str(_SAVED_CONFIG.get("qwen3_device", "auto")).strip() or "auto"
if DEFAULT_QWEN3_DEVICE not in {"auto", "cpu", "cuda:0"}:
DEFAULT_QWEN3_DEVICE = "auto"
DEFAULT_QWEN3_MAX_INFERENCE_BATCH_SIZE = _clamp_int(
_int(_SAVED_CONFIG.get("qwen3_max_inference_batch_size"), 8), 1, 64
)
DEFAULT_OUTPUT_FORMAT = _str(_SAVED_CONFIG.get("output_format", "srt")).strip() or "srt"
if DEFAULT_OUTPUT_FORMAT not in {"srt", "vtt", "txt"}:
DEFAULT_OUTPUT_FORMAT = "srt"
DEFAULT_LANGUAGE = _str(_SAVED_CONFIG.get("language", "auto")).strip() or "auto"
if DEFAULT_LANGUAGE not in {"auto", "zh", "en", "ja", "ko", "fr", "de", "es", "ru"}:
DEFAULT_LANGUAGE = "auto"
DEFAULT_ENABLE_VAD = bool(_SAVED_CONFIG.get("enable_vad", True))
DEFAULT_VAD_SEGMENT_THRESHOLD_S = _clamp_int(
_int(_SAVED_CONFIG.get("vad_segment_threshold_s"), 120), 30, 240
)
DEFAULT_VAD_MAX_SEGMENT_THRESHOLD_S = _clamp_int(
_int(_SAVED_CONFIG.get("vad_max_segment_threshold_s"), 180), 60, 360
)
try:
DEFAULT_VAD_THRESHOLD = float(_SAVED_CONFIG.get("vad_threshold", 0.25))
except Exception:
DEFAULT_VAD_THRESHOLD = 0.25
DEFAULT_VAD_THRESHOLD = max(0.1, min(0.9, DEFAULT_VAD_THRESHOLD))
DEFAULT_VAD_MIN_SPEECH_DURATION_MS = _clamp_int(
_int(_SAVED_CONFIG.get("vad_min_speech_duration_ms"), 100), 50, 2000
)
DEFAULT_VAD_MIN_SILENCE_DURATION_MS = _clamp_int(
_int(_SAVED_CONFIG.get("vad_min_silence_duration_ms"), 300), 50, 2000
)
DEFAULT_VAD_SPEECH_PAD_MS = _clamp_int(_int(_SAVED_CONFIG.get("vad_speech_pad_ms"), 400), 0, 2000)
DEFAULT_TIMELINE_STRATEGY = _str(_SAVED_CONFIG.get("timeline_strategy", "vad_speech")).strip()
if DEFAULT_TIMELINE_STRATEGY not in {"chunk", "vad_speech"}:
DEFAULT_TIMELINE_STRATEGY = "vad_speech"
DEFAULT_UPLOAD_AUDIO_FORMAT = _str(_SAVED_CONFIG.get("upload_audio_format", "wav")).strip()
if DEFAULT_UPLOAD_AUDIO_FORMAT not in {"wav", "mp3"}:
DEFAULT_UPLOAD_AUDIO_FORMAT = "wav"
UPLOAD_MP3_BITRATE_KBPS = 192
DEFAULT_VAD_SPEECH_MAX_UTTERANCE_S = _clamp_int(
_int(_SAVED_CONFIG.get("vad_speech_max_utterance_s"), 8), 5, 60
)
DEFAULT_VAD_SPEECH_MERGE_GAP_MS = _clamp_int(
_int(_SAVED_CONFIG.get("vad_speech_merge_gap_ms"), 100), 0, 2000
)
DEFAULT_API_CONCURRENCY = _clamp_int(_int(_SAVED_CONFIG.get("api_concurrency"), 4), 1, 16)
CONFIG_NOTE = f"配置文件:`{_CONFIG_PATH}`"
def _detect_cuda() -> tuple[bool, str]:
try:
import torch # type: ignore
except Exception as e:
return False, f"torch 未安装:{e}"
try:
torch_version = getattr(torch, "__version__", "unknown")
cuda_version = getattr(getattr(torch, "version", None), "cuda", None) or "n/a"
available = bool(torch.cuda.is_available())
if not available:
return False, f"torch={torch_version}, cuda={cuda_version}, available=False"
count = int(torch.cuda.device_count())
names: list[str] = []
for i in range(min(count, 4)):
try:
names.append(str(torch.cuda.get_device_name(i)))
except Exception:
continue
devices = ", ".join(names) if names else "unknown"
return True, f"torch={torch_version}, cuda={cuda_version}, devices={count}, names={devices}"
except Exception as e:
return False, f"CUDA 检测异常:{e}"
CUDA_AVAILABLE, CUDA_DETAILS = _detect_cuda()
CUDA_NOTE = (
f"CUDA 检测:{'可用' if CUDA_AVAILABLE else '不可用'}({CUDA_DETAILS})"
if CUDA_DETAILS
else "CUDA 检测:未知"
)
def _load_theme():
"""Load the bundled 'miku' Gradio theme if present; fallback to Soft()."""
try:
base = Path(__file__).resolve().parent
candidates = [
base / "theme" / "miku" / "theme_schema@1.2.2.json",
base / "miku" / "themes" / "theme_schema@1.2.2.json",
]
for theme_path in candidates:
if theme_path.exists():
return gr.Theme.load(str(theme_path))
except Exception as e:
logger.info("加载 miku 主题失败,回退默认主题: %s", e)
return gr.themes.Soft()
THEME = _load_theme()
logger.info(
"auto-asr 启动: config=%s, exists=%s, api_key_saved=%s",
_CONFIG_PATH,
_CONFIG_PATH.exists(),
bool(DEFAULT_OPENAI_API_KEY),
)
logger.info("auto-asr CUDA 检测: available=%s, details=%s", CUDA_AVAILABLE, CUDA_DETAILS)
_CANCEL_LOCK = Lock()
_CURRENT_CANCEL_EVENT: Event | None = None
def _set_current_cancel_event(ev: Event | None) -> None:
global _CURRENT_CANCEL_EVENT
with _CANCEL_LOCK:
_CURRENT_CANCEL_EVENT = ev
def stop_transcribe() -> str:
with _CANCEL_LOCK:
ev = _CURRENT_CANCEL_EVENT
if ev is None:
return "当前没有正在进行的转写。"
ev.set()
logger.info("收到停止转写请求。")
return "已发送停止信号(后台会尽快停止)。"
def _resolve_funasr_device_ui(device: str) -> str:
d = (device or "").strip()
if d in {"", "auto"}:
return "cuda:0" if CUDA_AVAILABLE else "cpu"
return d
def _resolve_qwen3_device_ui(device: str) -> str:
d = (device or "").strip()
if d in {"", "auto"}:
return "cuda:0" if CUDA_AVAILABLE else "cpu"
return d
def load_funasr_model_ui(
funasr_model: str,
funasr_device: str,
funasr_enable_punc: bool,
) -> str:
resolved_device = _resolve_funasr_device_ui(funasr_device)
try:
preload_funasr_model(
model=(funasr_model or "").strip(),
device=resolved_device,
enable_punc=bool(funasr_enable_punc),
)
except Exception as e:
logger.exception("加载 FunASR 模型失败: model=%s, device=%s", funasr_model, resolved_device)
return f"加载失败:{e}"
return f"已加载 FunASR 模型:{(funasr_model or '').strip()}(device={resolved_device})"
def download_funasr_model_ui(
funasr_model: str,
funasr_enable_punc: bool,
) -> str:
try:
download_funasr_model(
model=(funasr_model or "").strip(),
enable_punc=bool(funasr_enable_punc),
)
except Exception as e:
logger.exception("下载 FunASR 模型失败: model=%s", funasr_model)
return f"下载失败:{e}"
return f"下载完成:模型文件已下载到项目目录 `{get_models_dir()}`。"
def prepare_funasr_model_ui(
hf_endpoint: str,
funasr_model: str,
funasr_device: str,
funasr_enable_punc: bool,
) -> str:
"""One-click: download (if needed) + load FunASR model into memory."""
set_hf_endpoint((hf_endpoint or "").strip() or DEFAULT_HF_ENDPOINT)
model_name = (funasr_model or "").strip()
resolved_device = _resolve_funasr_device_ui(funasr_device)
try:
# Download first so the UI can show a deterministic "project-local models" message.
download_funasr_model(model=model_name, enable_punc=bool(funasr_enable_punc))
preload_funasr_model(
model=model_name,
device=resolved_device,
enable_punc=bool(funasr_enable_punc),
)
except Exception as e:
logger.exception("准备 FunASR 模型失败: model=%s, device=%s", model_name, resolved_device)
return f"准备失败:{e}"
return (
f"已准备 FunASR 模型:{model_name}(device={resolved_device})\n\n"
f"模型目录:`{get_models_dir()}`"
)
def load_qwen3_model_ui(
qwen3_model: str,
qwen3_device: str,
qwen3_max_inference_batch_size: int,
) -> str:
resolved_device = _resolve_qwen3_device_ui(qwen3_device)
try:
preload_qwen3_model(
cfg=Qwen3ASRConfig(
model=(qwen3_model or "").strip() or "Qwen/Qwen3-ASR-1.7B",
device=resolved_device,
max_inference_batch_size=max(1, int(qwen3_max_inference_batch_size)),
)
)
except Exception as e:
logger.exception(
"加载 Qwen3-ASR 模型失败: model=%s, device=%s",
qwen3_model,
resolved_device,
)
return f"加载失败:{e}"
model_name = (qwen3_model or "").strip()
return f"已加载 Qwen3-ASR 模型:{model_name}(device={resolved_device})"
def download_qwen3_models_ui(
qwen3_model: str,
) -> str:
try:
download_qwen3_models(
model=(qwen3_model or "").strip() or "Qwen/Qwen3-ASR-1.7B",
)
except Exception as e:
logger.exception("下载 Qwen3-ASR 模型失败: model=%s", qwen3_model)
return f"下载失败:{e}"
return f"下载完成:模型文件已下载到项目目录 `{get_models_dir()}`。"
def prepare_qwen3_model_ui(
hf_endpoint: str,
qwen3_model: str,
qwen3_device: str,
qwen3_max_inference_batch_size: int,
) -> str:
"""One-click: download (if needed) + load Qwen3-ASR model into memory."""
set_hf_endpoint((hf_endpoint or "").strip() or DEFAULT_HF_ENDPOINT)
resolved_device = _resolve_qwen3_device_ui(qwen3_device)
model_id = (qwen3_model or "").strip() or "Qwen/Qwen3-ASR-1.7B"
try:
local_dir = download_qwen3_models(model=model_id)
preload_qwen3_model(
cfg=Qwen3ASRConfig(
# Always load from local dir to avoid triggering a second download path.
model=str(local_dir),
device=resolved_device,
max_inference_batch_size=max(1, int(qwen3_max_inference_batch_size)),
)
)
except Exception as e:
logger.exception("准备 Qwen3-ASR 模型失败: model=%s, device=%s", model_id, resolved_device)
return f"准备失败:{e}"
return (
f"已准备 Qwen3-ASR 模型:{model_id}(device={resolved_device})\n\n"
f"本地目录:`{local_dir}`"
)
def release_cuda_ui() -> str:
try:
release_funasr_resources()
release_qwen3_resources()
except Exception as e:
logger.exception("释放显存失败")
return f"释放失败:{e}"
return "已释放 FunASR/Qwen3 模型缓存/显存(如仍显示占用,通常是 PyTorch 缓存行为)。"
def _save_hf_endpoint_ui(hf_endpoint: str):
value = (hf_endpoint or "").strip() or "huggingface.co"
try:
set_hf_endpoint(value)
update_config({"hf_endpoint": value})
except Exception as e:
logger.exception("保存 HuggingFace 下载源失败: %s", e)
return f"保存 HuggingFace 下载源失败:{e}"
return None
def _save_subtitle_provider_settings_ui(
subtitle_provider: str,
subtitle_openai_api_key: str,
subtitle_openai_base_url: str,
subtitle_llm_model: str,
subtitle_llm_temperature: float,
split_strategy: str,
):
try:
save_subtitle_provider_settings(
provider=subtitle_provider,
openai_api_key=subtitle_openai_api_key,
openai_base_url=subtitle_openai_base_url,
llm_model=subtitle_llm_model,
llm_temperature=float(subtitle_llm_temperature),
split_strategy=split_strategy,
)
except Exception as e:
logger.exception("保存字幕处理 LLM 配置失败: %s", e)
return f"保存字幕处理配置失败:{e}"
return None
def _save_subtitle_processing_settings_ui(
subtitle_processors: list[str] | None,
batch_size: int,
concurrency: int,
target_language: str,
translate_reflect: bool,
split_mode: str,
split_max_word_count_cjk: int,
split_max_word_count_english: int,
custom_prompt: str,
):
try:
save_subtitle_processing_settings(
processors=subtitle_processors,
batch_size=int(batch_size),
concurrency=int(concurrency),
target_language=target_language,
translate_reflect=bool(translate_reflect),
split_mode=split_mode,
split_max_word_count_cjk=int(split_max_word_count_cjk),
split_max_word_count_english=int(split_max_word_count_english),
custom_prompt=custom_prompt,
)
except Exception as e:
logger.exception("保存字幕处理参数失败: %s", e)
return f"保存字幕处理参数失败:{e}"
return None
def _auto_save_settings(
*,
asr_backend: str,
openai_api_key: str,
openai_base_url: str,
model: str,
funasr_model: str,
funasr_device: str,
funasr_language: str,
funasr_use_itn: bool,
funasr_enable_punc: bool,
qwen3_model: str,
qwen3_device: str,
qwen3_max_inference_batch_size: int,
output_format: str,
language: str,
enable_vad: bool,
vad_segment_threshold_s: int,
vad_max_segment_threshold_s: int,
vad_threshold: float,
vad_min_speech_duration_ms: int,
vad_min_silence_duration_ms: int,
vad_speech_pad_ms: int,
timeline_strategy: str,
vad_speech_max_utterance_s: int,
vad_speech_merge_gap_ms: int,
upload_audio_format: str,
api_concurrency: int,
hf_endpoint: str,
) -> None:
api_key = (openai_api_key or "").strip()
if not api_key:
# Avoid wiping the saved key due to an accidental empty input.
api_key = DEFAULT_OPENAI_API_KEY
config = {
"asr_backend": (asr_backend or "").strip() or "openai",
"enable_vad": bool(enable_vad),
"funasr_device": (funasr_device or "").strip() or "auto",
"funasr_enable_punc": bool(funasr_enable_punc),
"funasr_language": (funasr_language or "").strip() or "auto",
"funasr_model": (funasr_model or "").strip() or "iic/SenseVoiceSmall",
"funasr_use_itn": bool(funasr_use_itn),
"language": (language or "").strip() or "auto",
"model": (model or "").strip() or "whisper-1",
"openai_api_key": api_key,
"openai_base_url": (openai_base_url or "").strip(),
"output_format": (output_format or "").strip() or "srt",
"qwen3_device": (qwen3_device or "").strip() or "auto",
"qwen3_max_inference_batch_size": int(qwen3_max_inference_batch_size),
"qwen3_model": (qwen3_model or "").strip() or "Qwen/Qwen3-ASR-1.7B",
"timeline_strategy": (timeline_strategy or "").strip() or "vad_speech",
"upload_audio_format": (upload_audio_format or "").strip() or "wav",
"upload_mp3_bitrate_kbps": int(UPLOAD_MP3_BITRATE_KBPS),
"vad_threshold": float(vad_threshold),
"vad_min_speech_duration_ms": int(vad_min_speech_duration_ms),
"vad_min_silence_duration_ms": int(vad_min_silence_duration_ms),
"vad_speech_pad_ms": int(vad_speech_pad_ms),
"vad_speech_max_utterance_s": int(vad_speech_max_utterance_s),
"vad_speech_merge_gap_ms": int(vad_speech_merge_gap_ms),
"vad_max_segment_threshold_s": int(vad_max_segment_threshold_s),
"vad_segment_threshold_s": int(vad_segment_threshold_s),
"api_concurrency": int(api_concurrency),
"hf_endpoint": (hf_endpoint or "").strip() or DEFAULT_HF_ENDPOINT,
}
path = update_config(config)
logger.info("配置已自动保存: path=%s", path)
def run_asr(
audio_path: str | None,
asr_backend: str,
openai_api_key: str,
openai_base_url: str,
model: str,
funasr_model: str,
funasr_device: str,
funasr_language: str,
funasr_use_itn: bool,
funasr_enable_punc: bool,
output_format: str,
language: str,
prompt: str,
enable_vad: bool,
vad_segment_threshold_s: int,
vad_max_segment_threshold_s: int,
vad_threshold: float,
vad_min_speech_duration_ms: int,
vad_min_silence_duration_ms: int,
vad_speech_pad_ms: int,
timeline_strategy: str,
vad_speech_max_utterance_s: int,
vad_speech_merge_gap_ms: int,
upload_audio_format: str,
api_concurrency: int,
qwen3_model: str,
qwen3_device: str,
qwen3_max_inference_batch_size: int,
hf_endpoint: str = DEFAULT_HF_ENDPOINT,
):
if not audio_path:
raise gr.Error("请先上传或录制一段音频。")
asr_backend = (asr_backend or "").strip() or "openai"
if asr_backend == "openai" and not (openai_api_key or "").strip():
raise gr.Error("请先填写 OpenAI API Key。")
hf_endpoint = (hf_endpoint or "").strip() or DEFAULT_HF_ENDPOINT
set_hf_endpoint(hf_endpoint)
lang = None if language == "auto" else language
prompt = (prompt or "").strip() or None
model = (model or "").strip() or "whisper-1"
base_url = (openai_base_url or "").strip() or None
logger.info(
"收到转写请求: backend=%s, file=%s, format=%s, language=%s, model=%s, base_url=%s, "
"enable_vad=%s, target=%ss, max=%ss, timeline_strategy=%s, upload=%s, "
"vad_threshold=%.2f, vad_min_speech_ms=%d, vad_min_silence_ms=%d, vad_pad_ms=%d, "
"api_concurrency=%d",
asr_backend,
audio_path,
output_format,
lang or "auto",
model,
base_url or "(default)",
enable_vad,
vad_segment_threshold_s,
vad_max_segment_threshold_s,
timeline_strategy,
f"{upload_audio_format}/{UPLOAD_MP3_BITRATE_KBPS}k",
float(vad_threshold),
int(vad_min_speech_duration_ms),
int(vad_min_silence_duration_ms),
int(vad_speech_pad_ms),
int(api_concurrency),
)
_auto_save_settings(
asr_backend=asr_backend,
openai_api_key=openai_api_key,
openai_base_url=openai_base_url,
model=model,
funasr_model=funasr_model,
funasr_device=funasr_device,
funasr_language=funasr_language,
funasr_use_itn=funasr_use_itn,
funasr_enable_punc=funasr_enable_punc,
qwen3_model=qwen3_model,
qwen3_device=qwen3_device,
qwen3_max_inference_batch_size=qwen3_max_inference_batch_size,
output_format=output_format,
language=language,
enable_vad=enable_vad,
vad_segment_threshold_s=vad_segment_threshold_s,
vad_max_segment_threshold_s=vad_max_segment_threshold_s,
vad_threshold=vad_threshold,
vad_min_speech_duration_ms=vad_min_speech_duration_ms,
vad_min_silence_duration_ms=vad_min_silence_duration_ms,
vad_speech_pad_ms=vad_speech_pad_ms,
timeline_strategy=timeline_strategy,
vad_speech_max_utterance_s=vad_speech_max_utterance_s,
vad_speech_merge_gap_ms=vad_speech_merge_gap_ms,
upload_audio_format=upload_audio_format,
api_concurrency=api_concurrency,
hf_endpoint=hf_endpoint,
)
cancel_event = Event()
_set_current_cancel_event(cancel_event)
try:
resolved_funasr_model = (funasr_model or "").strip() or DEFAULT_FUNASR_MODEL
resolved_qwen3_model = (qwen3_model or "").strip() or DEFAULT_QWEN3_MODEL
resolved_qwen3_max_batch = _clamp_int(int(qwen3_max_inference_batch_size), 1, 64)
result = transcribe_to_subtitles(
input_audio_path=audio_path,
asr_backend=asr_backend,
openai_api_key=openai_api_key,
openai_base_url=base_url,
output_format=output_format,
model=model,
language=lang,
prompt=prompt,
funasr_model=resolved_funasr_model,
funasr_device=(funasr_device or "").strip() or DEFAULT_FUNASR_DEVICE,
funasr_language=(funasr_language or "").strip() or DEFAULT_FUNASR_LANGUAGE,
funasr_use_itn=bool(funasr_use_itn),
funasr_enable_punc=bool(funasr_enable_punc),
qwen3_model=resolved_qwen3_model,
qwen3_device=(qwen3_device or "").strip() or DEFAULT_QWEN3_DEVICE,
qwen3_max_inference_batch_size=resolved_qwen3_max_batch,
enable_vad=enable_vad,
vad_segment_threshold_s=int(vad_segment_threshold_s),
vad_max_segment_threshold_s=int(vad_max_segment_threshold_s),
vad_threshold=float(vad_threshold),
vad_min_speech_duration_ms=int(vad_min_speech_duration_ms),
vad_min_silence_duration_ms=int(vad_min_silence_duration_ms),
vad_speech_pad_ms=int(vad_speech_pad_ms),
timeline_strategy=(timeline_strategy or "").strip() or "vad_speech",
vad_speech_max_utterance_s=int(vad_speech_max_utterance_s),
vad_speech_merge_gap_ms=int(vad_speech_merge_gap_ms),
upload_audio_format=(upload_audio_format or "").strip() or "wav",
upload_mp3_bitrate_kbps=int(UPLOAD_MP3_BITRATE_KBPS),
api_concurrency=int(api_concurrency),
cancel_event=cancel_event,
)
except Exception as e:
if cancel_event.is_set() or "已停止转写" in str(e):
logger.info("转写已停止: %s", e)
return "", "", None, "已停止转写"
raise gr.Error(f"转写失败:{e}") from e
finally:
_set_current_cancel_event(None)
return result.preview_text, result.full_text, result.subtitle_file_path, result.debug
def run_subtitle_processing(
subtitle_path: str | None,
subtitle_processors: list[str] | None,
subtitle_provider: str,
subtitle_openai_api_key: str,
subtitle_openai_base_url: str,
subtitle_llm_model: str,
subtitle_llm_temperature: float,
target_language: str,
translate_reflect: bool,
split_strategy: str,
split_mode: str,
split_max_word_count_cjk: int,
split_max_word_count_english: int,
custom_prompt: str,
batch_size: int,
concurrency: int,
):
if not subtitle_path:
raise gr.Error("请先上传字幕文件(SRT/VTT)。")
save_subtitle_processing_settings(
processors=subtitle_processors,
batch_size=int(batch_size),
concurrency=int(concurrency),
target_language=target_language,
translate_reflect=bool(translate_reflect),
split_mode=split_mode,
split_max_word_count_cjk=int(split_max_word_count_cjk),
split_max_word_count_english=int(split_max_word_count_english),
custom_prompt=custom_prompt,
)
processor_order = ["optimize", "translate", "split"]
selected = [str(x).strip() for x in (subtitle_processors or []) if str(x).strip()]
selected = [p for p in processor_order if p in set(selected)]
if not selected:
raise gr.Error("请至少选择一个处理类型。")
provider = (subtitle_provider or "").strip() or "openai"
if provider != "openai":
raise gr.Error(f"暂不支持该字幕处理提供商:{provider!r}")
api_key = (subtitle_openai_api_key or "").strip()
if not api_key:
raise gr.Error("请先在「字幕处理」中填写 API Key。")
base_url = (subtitle_openai_base_url or "").strip() or None
llm_model = (subtitle_llm_model or "").strip() or DEFAULT_SUBTITLE_LLM_MODEL
try:
llm_temperature = float(subtitle_llm_temperature)
except Exception:
llm_temperature = DEFAULT_SUBTITLE_LLM_TEMPERATURE
llm_temperature = max(0.0, min(2.0, llm_temperature))
common = {"concurrency": int(concurrency)}
options_by_processor: dict[str, dict] = {}
if "translate" in selected:
options_by_processor["translate"] = {
**common,
"target_language": (target_language or "").strip() or "zh",
"reflect": bool(translate_reflect),
"custom_prompt": (custom_prompt or "").strip(),
"batch_size": int(batch_size),
}
if "optimize" in selected:
options_by_processor["optimize"] = {
**common,
"custom_prompt": (custom_prompt or "").strip(),
"batch_size": int(batch_size),
}
if "split" in selected:
options_by_processor["split"] = {
**common,
"strategy": (split_strategy or "").strip() or "semantic",
"mode": (split_mode or "").strip() or "inplace_newlines",
"max_word_count_cjk": int(split_max_word_count_cjk),
"max_word_count_english": int(split_max_word_count_english),
}
save_subtitle_provider_settings(
provider=provider,
openai_api_key=api_key,
openai_base_url=subtitle_openai_base_url,
llm_model=llm_model,
llm_temperature=llm_temperature,
split_strategy=split_strategy,
)
out_dir = str(Path("outputs") / "processed")
if len(selected) == 1:
name = selected[0]
res = process_subtitle_file(
subtitle_path,
processor=name,
out_dir=out_dir,
options=options_by_processor.get(name, common),
llm_model=llm_model,
llm_temperature=llm_temperature,
openai_api_key=api_key,
openai_base_url=base_url,
chat_json=None,
)
else:
res = process_subtitle_file_multi(
subtitle_path,
processors=selected,
out_dir=out_dir,
options_by_processor=options_by_processor,
llm_model=llm_model,
llm_temperature=llm_temperature,
openai_api_key=api_key,
openai_base_url=base_url,
chat_json=None,
)
return res.preview_text, res.out_path, res.debug
with gr.Blocks(
title="Auto-ASR",
) as demo:
gr.Markdown(
"\n".join(
[
"# Auto-ASR",
"上传/录制音频 -> ASR -> 导出 SRT / VTT / TXT。",
"",
"- 若上游不返回时间戳,可用「VAD 语音段」模式生成更准的字幕轴。",
"- VAD 语音段模式会增加调用次数(按语音段逐段转写)。",
"",
CONFIG_NOTE,
]
)
)
with gr.Tabs():
with gr.Tab("转写", id="tab_transcribe"):
with gr.Row():
audio_in = gr.Audio(
sources=["upload", "microphone"],
type="filepath",
label="音频",
)
with gr.Row():
asr_backend = gr.Dropdown(
choices=[
("Qwen3-ASR(本地推理)", "qwen3asr"),
("FunASR(本地推理)", "funasr"),
("OpenAI API(远程)", "openai"),
],
value=DEFAULT_ASR_BACKEND,
label="ASR 引擎",
)
output_format = gr.Dropdown(
choices=[
("SRT 字幕", "srt"),
("VTT 字幕", "vtt"),
("纯文本", "txt"),
],
value=DEFAULT_OUTPUT_FORMAT,
label="输出格式",
)
language = gr.Dropdown(
choices=[
("自动检测", "auto"),
("中文", "zh"),
("英语", "en"),
("日语", "ja"),
("韩语", "ko"),
("法语", "fr"),
("德语", "de"),
("西语", "es"),
("俄语", "ru"),
],
value=DEFAULT_LANGUAGE,
label="语言",
)
prompt = gr.Textbox(
label="提示词(可选)",
placeholder="可填写术语/人名/地名等上下文,提升识别效果。",
)
run_btn = gr.Button("开始转写", variant="primary")
stop_btn = gr.Button("停止转写", variant="stop")
with gr.Row():
preview = gr.Textbox(label="字幕预览", lines=12)
with gr.Row():
full_text = gr.Textbox(label="完整文本", lines=12)
with gr.Row():
out_file = gr.File(label="下载")
debug = gr.Textbox(label="调试信息", lines=2)
with gr.Tab("字幕处理", id="tab_subtitle"):
gr.Markdown(
"\n".join(
[
"对已有字幕文件(SRT/VTT)进行 **校正 / 翻译 / 分割**。",
"可多选处理类型,按顺序依次执行:**校正 -> 翻译 -> 分割**。",
]
)
)
with gr.Accordion("LLM 提供商(仅字幕处理)", open=True):
subtitle_provider = gr.Dropdown(
choices=[
("OpenAI 兼容", "openai"),
],
value=DEFAULT_SUBTITLE_PROVIDER,
label="提供商",
)
subtitle_openai_api_key = gr.Textbox(
label="API Key",
type="password",
placeholder="sk-...",
value=DEFAULT_SUBTITLE_OPENAI_API_KEY,
)
subtitle_openai_base_url = gr.Textbox(
label="Base URL",
placeholder="例如:https://api.openai.com/v1",
value=DEFAULT_SUBTITLE_OPENAI_BASE_URL,
)
subtitle_llm_model = gr.Textbox(
label="模型名",
value=DEFAULT_SUBTITLE_LLM_MODEL,
)
subtitle_llm_temperature = gr.Slider(
minimum=0.0,
maximum=1.0,
value=DEFAULT_SUBTITLE_LLM_TEMPERATURE,
step=0.05,
label="温度(越低越稳定,越高越发散)",
)
subtitle_llm_settings_state = gr.State(None)
subtitle_in = gr.File(
label="字幕文件(SRT/VTT)",
file_types=[".srt", ".vtt"],
type="filepath",
)
subtitle_processors = gr.CheckboxGroup(
choices=[
("字幕校正(LLM)", "optimize"),
("字幕翻译(LLM)", "translate"),
("智能断句(LLM)", "split"),
],
value=DEFAULT_SUBTITLE_PROCESSORS,
label="处理类型(可多选)",
)
with gr.Row():
target_language = gr.Dropdown(
choices=[
("中文", "zh"),
("英语", "en"),
("日语", "ja"),
("韩语", "ko"),
("法语", "fr"),
("德语", "de"),
("西语", "es"),
("俄语", "ru"),
],
value=DEFAULT_SUBTITLE_TARGET_LANGUAGE,
label="目标语言(仅翻译)",
)
translate_reflect = gr.Checkbox(
value=DEFAULT_SUBTITLE_TRANSLATE_REFLECT,
label="反思翻译(更自然)",
)
split_strategy = gr.Dropdown(
choices=[
("语义断句(更易读,适合长句/无标点)", "semantic"),
("按句子断句(更保守,尽量按标点)", "sentence"),
],
value=DEFAULT_SUBTITLE_SPLIT_STRATEGY,
label="断句方式(仅断句)",
)
split_mode = gr.Dropdown(
choices=[
("只插入换行(不改变时间轴)", "inplace_newlines"),
("拆分为多条字幕(重新分配时间轴)", "split_to_cues"),
],
value=DEFAULT_SUBTITLE_SPLIT_MODE,
label="输出形式(仅断句)",
)
with gr.Row():
split_max_word_count_cjk = gr.Slider(
minimum=1,