smartwang commited on
Commit
a9d9345
·
1 Parent(s): 4c93f05

加whisper

Browse files
Files changed (2) hide show
  1. app.py +67 -0
  2. requirements.txt +2 -2
app.py CHANGED
@@ -15,6 +15,7 @@ from qwen_tts import Qwen3TTSModel
15
  import functools
16
  import uuid
17
  import random
 
18
  # 配置日志
19
  logging.basicConfig(
20
  level=logging.INFO,
@@ -93,6 +94,14 @@ def load_model(model_type, model_size):
93
  attn_implementation="kernels-community/flash-attn3"
94
  )
95
 
 
 
 
 
 
 
 
 
96
  # logger.info("正在加载 Base 1.7B 模型...")
97
  # base_model_1_7b = Qwen3TTSModel.from_pretrained(
98
  # get_model_path("Base", "1.7B"),
@@ -408,6 +417,28 @@ def generate_voice_clone_from_prompt_file(prompt_file_path, target_text, languag
408
  return None, f"错误: {type(e).__name__}: {e}"
409
 
410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  # def generate_custom_voice(text, language, speaker, instruct, model_size, progress=gr.Progress(track_tqdm=True)):
412
  # """Generate speech using CustomVoice model with segment-based GPU allocation."""
413
  # if not text or not text.strip():
@@ -454,12 +485,48 @@ def build_ui():
454
  A unified Text-to-Speech demo featuring three powerful modes:
455
  - **Voice Design**: Create custom voices using natural language descriptions
456
  - **Voice Clone (Base)**: Clone any voice from a reference audio
 
457
  - **TTS (CustomVoice)**: Generate speech with predefined speakers and optional style instructions
458
  Built with [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) by Alibaba Qwen Team.
459
  """
460
  )
461
 
462
  with gr.Tabs():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  # Tab 1: Voice Design (Default, 1.7B only)
464
  with gr.Tab("Voice Design"):
465
  gr.Markdown("### Create Custom Voice with Natural Language")
 
15
  import functools
16
  import uuid
17
  import random
18
+ import whisper
19
  # 配置日志
20
  logging.basicConfig(
21
  level=logging.INFO,
 
94
  attn_implementation="kernels-community/flash-attn3"
95
  )
96
 
97
+ @functools.lru_cache(maxsize=1)
98
+ def load_whisper_model(model_name="large-v3"):
99
+ logger.info(f"正在加载 Whisper 模型: {model_name}...")
100
+ # whisper.load_model 会自动处理下载和缓存
101
+ model = whisper.load_model(model_name, device="cuda" if torch.cuda.is_available() else "cpu")
102
+ logger.info("Whisper 模型加载成功!")
103
+ return model
104
+
105
  # logger.info("正在加载 Base 1.7B 模型...")
106
  # base_model_1_7b = Qwen3TTSModel.from_pretrained(
107
  # get_model_path("Base", "1.7B"),
 
417
  return None, f"错误: {type(e).__name__}: {e}"
418
 
419
 
420
+ @spaces.GPU
421
+ def infer_whisper_audio(audio_path, model_size="large-v3"):
422
+ """Transcribe audio using Whisper model."""
423
+ if not audio_path:
424
+ return "错误:请上传音频文件或进行录音。"
425
+
426
+ logger.info(f"开始 Whisper 语音识别任务。模型: {model_size}, 音频路径: {audio_path}")
427
+ try:
428
+ model = load_whisper_model(model_size)
429
+
430
+ # 使用 transcribe 方法进行转录
431
+ # whisper 会自动处理音频加载和重采样
432
+ result = model.transcribe(audio_path)
433
+
434
+ text = result["text"]
435
+ logger.info(f"Whisper 识别完成。文本长度: {len(text)}")
436
+ return text.strip()
437
+ except Exception as e:
438
+ logger.error(f"Whisper 识别失败: {str(e)}", exc_info=True)
439
+ return f"识别出错: {type(e).__name__}: {e}"
440
+
441
+
442
  # def generate_custom_voice(text, language, speaker, instruct, model_size, progress=gr.Progress(track_tqdm=True)):
443
  # """Generate speech using CustomVoice model with segment-based GPU allocation."""
444
  # if not text or not text.strip():
 
485
  A unified Text-to-Speech demo featuring three powerful modes:
486
  - **Voice Design**: Create custom voices using natural language descriptions
487
  - **Voice Clone (Base)**: Clone any voice from a reference audio
488
+ - **ASR (Whisper)**: Accurate speech-to-text using OpenAI's Whisper model
489
  - **TTS (CustomVoice)**: Generate speech with predefined speakers and optional style instructions
490
  Built with [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) by Alibaba Qwen Team.
491
  """
492
  )
493
 
494
  with gr.Tabs():
495
+ # Tab 3: ASR (Whisper)
496
+ with gr.Tab("ASR (Whisper)"):
497
+ gr.Markdown("### 语音识别 (Speech Recognition)")
498
+ gr.Markdown("使用 OpenAI Whisper 模型将语音转换为文本。")
499
+
500
+ with gr.Row():
501
+ with gr.Column(scale=1):
502
+ asr_audio_input = gr.Audio(
503
+ label="输入音频 (录音或上传)",
504
+ type="filepath", # Whisper 需要文件路径
505
+ sources=["microphone", "upload"]
506
+ )
507
+ asr_model_size = gr.Dropdown(
508
+ label="Whisper 模型大小",
509
+ choices=["base", "small", "medium", "large-v3"],
510
+ value="large-v3",
511
+ interactive=True,
512
+ info="越大越准,但速度越慢"
513
+ )
514
+ asr_btn = gr.Button("开始识别 (Transcribe)", variant="primary")
515
+
516
+ with gr.Column(scale=1):
517
+ asr_text_output = gr.Textbox(
518
+ label="识别结果",
519
+ lines=10,
520
+ show_copy_button=True
521
+ )
522
+
523
+ asr_btn.click(
524
+ infer_whisper_audio,
525
+ inputs=[asr_audio_input, asr_model_size],
526
+ outputs=[asr_text_output],
527
+ api_name="infer_whisper"
528
+ )
529
+
530
  # Tab 1: Voice Design (Default, 1.7B only)
531
  with gr.Tab("Voice Design"):
532
  gr.Markdown("### Create Custom Voice with Natural Language")
requirements.txt CHANGED
@@ -10,6 +10,6 @@ soundfile
10
  sox
11
  onnxruntime
12
  spaces
13
- torch
14
  numpy
15
- kernels
 
 
10
  sox
11
  onnxruntime
12
  spaces
 
13
  numpy
14
+ kernels
15
+ openai-whisper