dseditor commited on
Commit
186763b
·
verified ·
1 Parent(s): f4d5302

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -142
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
- Breeze2-VITS 繁體中文語音合成 - 英文朗讀問題修復
3
- 增強調試功能和轉換邏輯
4
  """
5
 
6
  import gradio as gr
@@ -24,12 +24,12 @@ except ImportError:
24
 
25
 
26
  class TextConverter:
27
- """文本轉換器,將英文和數字轉換為中文發音 - 增強調試版"""
28
 
29
  def __init__(self, mapping_file="text_mapping.txt"):
30
  self.mapping_file = Path(mapping_file)
31
  self.conversion_map = {}
32
- self.debug_mode = True # 啟用調試模式
33
  self.load_mapping()
34
 
35
  def load_mapping(self):
@@ -243,6 +243,21 @@ class TextConverter:
243
  result += digit
244
  return result
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  def convert_english(self, text):
247
  """轉換英文單詞為中文 - 增強調試版"""
248
  self.debug_print(f"英文轉換前: {repr(text)}")
@@ -328,16 +343,19 @@ class TextConverter:
328
  if text != original_text:
329
  self.debug_print(f"預處理後: {repr(text)}")
330
 
331
- # 1. 轉換英文單詞先處理多字母詞彙
 
 
 
332
  text = self.convert_english(text)
333
 
334
- # 2. 轉換數字
335
  text = self.convert_numbers(text)
336
 
337
- # 3. 轉換剩餘的單個字母
338
  text = self.convert_single_letters(text)
339
 
340
- # 4. 後處理
341
  text = self.postprocess_text(text)
342
 
343
  if text != original_text:
@@ -352,11 +370,13 @@ class TextConverter:
352
  if test_texts is None:
353
  test_texts = [
354
  "Hello world",
355
- "I have 123 apples",
 
356
  "My email is test@gmail.com",
357
  "Apple iPhone 15 is good",
358
- "AI and ML are useful",
359
- "CPU speed is 3.5 GHz"
 
360
  ]
361
 
362
  print("\n🧪 測試文本轉換功能:")
@@ -374,7 +394,7 @@ class TaiwaneseVITSTTS:
374
  self.model_dir = Path("./models")
375
  self.dict_dir = Path("./dict")
376
  self.text_converter = TextConverter()
377
- self.debug_mode = True # 啟用調試模式
378
  self.setup_jieba_dict()
379
  self.setup_model()
380
 
@@ -557,37 +577,9 @@ class TaiwaneseVITSTTS:
557
  return None, error_msg
558
 
559
 
560
- # 初始化時運行測試
561
- def run_initialization_tests():
562
- """運行初始化測試"""
563
- print("\n" + "="*60)
564
- print("🔧 運行系統診斷測試")
565
- print("="*60)
566
-
567
- # 測試文本轉換器
568
- converter = TextConverter()
569
- test_cases = [
570
- "Hello world",
571
- "I love Apple iPhone 15",
572
- "AI technology is amazing",
573
- "My email is user@gmail.com",
574
- "CPU speed is 2.5 GHz"
575
- ]
576
-
577
- print("\n📝 測試文本轉換功能:")
578
- for test_text in test_cases:
579
- result = converter.convert_text(test_text)
580
- print(f" 輸入: {test_text}")
581
- print(f" 輸出: {result}")
582
- print()
583
-
584
-
585
  # 全局 TTS 實例
586
  print("🔧 正在初始化 TTS 模型...")
587
  try:
588
- # 運行診斷測試
589
- run_initialization_tests()
590
-
591
  tts_model = TaiwaneseVITSTTS()
592
  print("✅ TTS 系統就緒!")
593
  model_status = "🟢 模型已載入"
@@ -606,22 +598,20 @@ def generate_speech(text, speed, enable_conversion):
606
 
607
 
608
  def create_interface():
609
- # 預設範例文本 - 增加更多測試用例
610
  examples = [
611
- ["你好,歡迎使用繁體中文語音合成系統!", 1.0, True],
612
- ["Hello world! 這是一個測試。", 1.0, True],
613
- ["I love Apple iPhone 15 and Samsung Galaxy", 1.0, True],
614
- ["AI technology is amazing, CPU speed is 3.5 GHz", 1.0, True],
615
- ["My email is test@gmail.com, please contact me", 1.0, True],
616
- ["今天是2024年1月1日天氣很好。", 1.0, True],
617
- ["Google and Microsoft are big tech companies", 1.0, True],
618
- ["API development with Python is easy", 1.0, True],
619
  ]
620
 
621
  device_info = "🎮 GPU" if torch.cuda.is_available() else "💻 CPU"
622
 
623
  with gr.Blocks(
624
- title="繁體中文語音合成 - Breeze2-VITS Enhanced Debug",
625
  theme=gr.themes.Soft(),
626
  css="""
627
  .gradio-container {
@@ -643,29 +633,16 @@ def create_interface():
643
  margin: 10px 0;
644
  text-align: center;
645
  }
646
- .debug-box {
647
- background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
648
- color: white;
649
- padding: 10px 15px;
650
- border-radius: 8px;
651
- margin: 10px 0;
652
- }
653
  """
654
  ) as demo:
655
 
656
  gr.HTML(f"""
657
  <div class="status-box">
658
- <h1>🎙️ 繁體中文語音合成 - Breeze2-VITS Enhanced Debug</h1>
659
  <p><strong>狀態:</strong> {model_status} | <strong>設備:</strong> {device_info}</p>
660
  </div>
661
  """)
662
 
663
- gr.HTML("""
664
- <div class="debug-box">
665
- <strong>🔍 調試增強版</strong> | 詳細轉換日志 | 問題診斷 | 性能分析
666
- </div>
667
- """)
668
-
669
  gr.HTML("""
670
  <div class="feature-box">
671
  <strong>🇹🇼 專業台灣國語 TTS</strong> | 🔄 自動英數轉換 | 🎯 智慧文本處理
@@ -685,24 +662,20 @@ def create_interface():
685
  placeholder="請輸入要合成的文本,支援中文、英文、數字混合...",
686
  lines=5,
687
  max_lines=8,
688
- value="Hello world! 今天是2024年,歡迎使用AI語音合成系統。"
689
  )
690
 
691
- with gr.Row():
692
- speed = gr.Slider(
693
- label="⚡ 語音速度",
694
- minimum=0.5,
695
- maximum=2.0,
696
- step=0.1,
697
- value=1.0,
698
- info="調節語音播放速度"
699
- )
700
-
701
- enable_conversion = gr.Checkbox(
702
- label="🔄 啟用英數轉換",
703
- value=True,
704
- info="自動將英文和數字轉換為中文發音"
705
- )
706
 
707
  generate_btn = gr.Button(
708
  "🎵 生成台灣國語語音",
@@ -729,65 +702,23 @@ def create_interface():
729
  if tts_model:
730
  gr.Examples(
731
  examples=examples,
732
- inputs=[text_input, speed, enable_conversion],
733
  outputs=[audio_output, status_msg],
734
- fn=generate_speech,
735
  cache_examples=False,
736
- label="📚 範例文本 (包含英文朗讀測試)"
737
  )
738
 
739
- with gr.Accordion("🔍 調試信息與故障排除", open=True):
740
- gr.Markdown(f"""
741
- ### 🚀 調試功能
742
-
743
- #### 🔄 轉換規則狀態
744
- - **載入規則數**: {len(tts_model.text_converter.conversion_map) if tts_model else 0} 個
745
- - **調試模式**: {'✅ 已啟用' if tts_model and tts_model.debug_mode else '❌ 未啟用'}
746
- - **模型狀態**: {model_status}
747
-
748
- #### 🧪 常見問題診斷
749
-
750
- **問題1: 英文不發音**
751
- - ✅ 確保啟用「英數轉換」功能
752
- - ✅ 檢查控制台轉換日志
753
- - ✅ 測試單獨的英文單詞
754
-
755
- **問題2: 轉換後仍有英文**
756
- - 可能是詞典中缺少該詞彙
757
- - 查看調試信息中的轉換過程
758
- - 考慮添加自定義轉換規則
759
-
760
- **問題3: 發音不自然**
761
- - 嘗試調整轉換後的中文用詞
762
- - 使用更常見的中文表達
763
- - 關閉轉換使用純中文測試
764
-
765
- #### 🔧 調試步驟
766
- 1. 打開瀏覽器開發者工具查看控制台
767
- 2. 輸入測試文本並生成語音
768
- 3. 觀察轉換過程的調試信息
769
- 4. 檢查哪些詞彙被成功轉換
770
- 5. 分析未轉換詞彙的原因
771
-
772
- #### 📝 測試建議
773
- - 先測試純英文: "Hello world"
774
- - 再測試中英混合: "Hello 世界"
775
- - 測試數字: "I have 123 apples"
776
- - 測試品牌: "Apple iPhone Samsung"
777
- - 測試技術詞彙: "AI CPU GPU API"
778
- """)
779
-
780
  with gr.Accordion("📋 使用說明與功能特色", open=False):
781
  gr.Markdown(f"""
782
  ### 🚀 主要功能
783
 
784
- #### 🔄 智慧文本轉換 (增強版)
785
- - **基本英文**: hello → 哈囉, good好的, thank謝謝
786
- - **技術詞彙**: AI → 人工智慧, CPU → 中央處理器, API → 程式介面
787
- - **品牌名稱**: Apple → 蘋果, Google → 谷歌, iPhone → 愛瘋
788
  - **數字轉換**: 123 → 一二三, 2024 → 二零二四
789
- - **字母發音**: A, B, C西
790
- - **縮寫詞**: CEO執行長, USA美國, GPS → 全球定位系統
 
791
 
792
  #### 🎯 支援內容
793
  - 繁體中文文本
@@ -795,33 +726,40 @@ def create_interface():
795
  - 阿拉伯數字
796
  - 混合語言文本
797
  - 常見縮寫和品牌
798
- - 網路用語和技術術語
799
 
800
  ### 📝 使用技巧
801
- 1. **測試**: 使用範例中的英文測試案例
802
- 2. **調試轉換**: 查看控制台的詳細轉換過程
803
- 3. **混合文本**: 嘗試「Hello world 這是測試」
804
- 4. **數字處理**: 測試不同長度的數字
805
 
806
  ### 🔧 技術資訊
807
  - **模型**: MediaTek Breeze2-VITS-onnx
808
  - **轉換規則**: {len(tts_model.text_converter.conversion_map) if tts_model else 0} 個內建對照
809
- - **調試模式**: {'啟用' if tts_model and tts_model.debug_mode else '未啟用'}
810
  - **運行設備**: {device_info}
811
- - **模型狀態**: {model_status}
 
 
 
 
 
 
 
812
  """)
813
 
814
- # 事件綁定
815
  generate_btn.click(
816
- fn=generate_speech,
817
- inputs=[text_input, speed, enable_conversion],
818
  outputs=[audio_output, status_msg],
819
  api_name="generate_speech"
820
  )
821
 
822
  text_input.submit(
823
- fn=generate_speech,
824
- inputs=[text_input, speed, enable_conversion],
825
  outputs=[audio_output, status_msg]
826
  )
827
 
 
1
  """
2
+ Breeze2-VITS 繁體中文語音合成 - 優化
3
+ 支援英文數字自動轉換為中文發音,大寫英文逐字母發音
4
  """
5
 
6
  import gradio as gr
 
24
 
25
 
26
  class TextConverter:
27
+ """文本轉換器,將英文和數字轉換為中文發音"""
28
 
29
  def __init__(self, mapping_file="text_mapping.txt"):
30
  self.mapping_file = Path(mapping_file)
31
  self.conversion_map = {}
32
+ self.debug_mode = False # 簡化調試模式
33
  self.load_mapping()
34
 
35
  def load_mapping(self):
 
243
  result += digit
244
  return result
245
 
246
+ def convert_uppercase_words(self, text):
247
+ """轉換全大寫單字為逐字母發音"""
248
+ def uppercase_to_letters(match):
249
+ word = match.group()
250
+ result = ""
251
+ for letter in word:
252
+ chinese_letter = self.conversion_map.get(letter.lower(), letter)
253
+ result += chinese_letter
254
+ self.debug_print(f" 大寫轉換: {word} → {result}")
255
+ return result
256
+
257
+ # 匹配全大寫的單字(2個字母以上)
258
+ result = re.sub(r'\b[A-Z]{2,}\b', uppercase_to_letters, text)
259
+ return result
260
+
261
  def convert_english(self, text):
262
  """轉換英文單詞為中文 - 增強調試版"""
263
  self.debug_print(f"英文轉換前: {repr(text)}")
 
343
  if text != original_text:
344
  self.debug_print(f"預處理後: {repr(text)}")
345
 
346
+ # 1. 轉換大寫英文縮寫在其他轉換之前
347
+ text = self.convert_uppercase_words(text)
348
+
349
+ # 2. 轉換英文單詞(普通詞彙)
350
  text = self.convert_english(text)
351
 
352
+ # 3. 轉換數字
353
  text = self.convert_numbers(text)
354
 
355
+ # 4. 轉換剩餘的單個字母
356
  text = self.convert_single_letters(text)
357
 
358
+ # 5. 後處理
359
  text = self.postprocess_text(text)
360
 
361
  if text != original_text:
 
370
  if test_texts is None:
371
  test_texts = [
372
  "Hello world",
373
+ "I have 123 apples",
374
+ "CPU and GPU are important",
375
  "My email is test@gmail.com",
376
  "Apple iPhone 15 is good",
377
+ "API development with Python",
378
+ "NASA sent rockets to space",
379
+ "USA and UK are allies"
380
  ]
381
 
382
  print("\n🧪 測試文本轉換功能:")
 
394
  self.model_dir = Path("./models")
395
  self.dict_dir = Path("./dict")
396
  self.text_converter = TextConverter()
397
+ self.debug_mode = False # 簡化調試模式
398
  self.setup_jieba_dict()
399
  self.setup_model()
400
 
 
577
  return None, error_msg
578
 
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  # 全局 TTS 實例
581
  print("🔧 正在初始化 TTS 模型...")
582
  try:
 
 
 
583
  tts_model = TaiwaneseVITSTTS()
584
  print("✅ TTS 系統就緒!")
585
  model_status = "🟢 模型已載入"
 
598
 
599
 
600
  def create_interface():
601
+ # 預設範例文本 - 純中文版本
602
  examples = [
603
+ ["你好,歡迎使用繁體中文語音合成系統!", 1.0],
604
+ ["今天天氣晴朗,適合外出踏青。", 1.0],
605
+ ["台灣的夜市文化非常豐富多彩。", 1.0],
606
+ ["人工智慧技術正在快速發展。", 1.1],
607
+ ["這個語音合成系統效果很不錯。", 1.0],
608
+ ["祝您使用愉快謝謝您的支持。", 0.9],
 
 
609
  ]
610
 
611
  device_info = "🎮 GPU" if torch.cuda.is_available() else "💻 CPU"
612
 
613
  with gr.Blocks(
614
+ title="繁體中文語音合成 - Breeze2-VITS Enhanced",
615
  theme=gr.themes.Soft(),
616
  css="""
617
  .gradio-container {
 
633
  margin: 10px 0;
634
  text-align: center;
635
  }
 
 
 
 
 
 
 
636
  """
637
  ) as demo:
638
 
639
  gr.HTML(f"""
640
  <div class="status-box">
641
+ <h1>🎙️ 繁體中文語音合成 - Breeze2-VITS Enhanced</h1>
642
  <p><strong>狀態:</strong> {model_status} | <strong>設備:</strong> {device_info}</p>
643
  </div>
644
  """)
645
 
 
 
 
 
 
 
646
  gr.HTML("""
647
  <div class="feature-box">
648
  <strong>🇹🇼 專業台灣國語 TTS</strong> | 🔄 自動英數轉換 | 🎯 智慧文本處理
 
662
  placeholder="請輸入要合成的文本,支援中文、英文、數字混合...",
663
  lines=5,
664
  max_lines=8,
665
+ value="你好!歡迎使用繁體中文語音合成系統。"
666
  )
667
 
668
+ speed = gr.Slider(
669
+ label="⚡ 語音速度",
670
+ minimum=0.5,
671
+ maximum=2.0,
672
+ step=0.1,
673
+ value=1.0,
674
+ info="調節語音播放速度"
675
+ )
676
+
677
+ # 隱藏的轉換開關,預設啟用
678
+ enable_conversion = gr.State(value=True)
 
 
 
 
679
 
680
  generate_btn = gr.Button(
681
  "🎵 生成台灣國語語音",
 
702
  if tts_model:
703
  gr.Examples(
704
  examples=examples,
705
+ inputs=[text_input, speed],
706
  outputs=[audio_output, status_msg],
707
+ fn=lambda text, speed: generate_speech(text, speed, True),
708
  cache_examples=False,
709
+ label="📚 範例文本"
710
  )
711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712
  with gr.Accordion("📋 使用說明與功能特色", open=False):
713
  gr.Markdown(f"""
714
  ### 🚀 主要功能
715
 
716
+ #### 🔄 智慧文本轉換
717
+ - **英文轉換**: hello → 哈囉, AI人工智慧, iPhone愛瘋
 
 
718
  - **數字轉換**: 123 → 一二三, 2024 → 二零二四
719
+ - **大寫縮寫**: CPU西皮優, API欸皮愛, GPS吉皮艾斯
720
+ - **品牌名稱**: Apple蘋果, Google谷歌
721
+ - **技術詞彙**: computer → 電腦, software → 軟體
722
 
723
  #### 🎯 支援內容
724
  - 繁體中文文本
 
726
  - 阿拉伯數字
727
  - 混合語言文本
728
  - 常見縮寫和品牌
729
+ - 大寫英文縮寫(逐字母發音)
730
 
731
  ### 📝 使用技巧
732
+ 1. **混合**: 支援「今天天氣很好,temperature是25度」
733
+ 2. **大寫縮寫**: CPU、API、GPS等會自動逐字母發音
734
+ 3. **數字處理**: 支援各種數字格式轉換
735
+ 4. **專有名詞**: 內建常見品牌和技術詞彙
736
 
737
  ### 🔧 技術資訊
738
  - **模型**: MediaTek Breeze2-VITS-onnx
739
  - **轉換規則**: {len(tts_model.text_converter.conversion_map) if tts_model else 0} 個內建對照
740
+ - **支援格式**: 中文、英文、數字、符號
741
  - **運行設備**: {device_info}
742
+ - **自動轉換**: 已啟用英文數字自動轉換
743
+
744
+ ### ⚙️ 自定義轉換
745
+ 您可以編輯 `text_mapping.txt` 文件來添加自定義的轉換規則:
746
+ ```
747
+ your_word|您的中文發音
748
+ brand_name|品牌中文名
749
+ ```
750
  """)
751
 
752
+ # 事件綁定 - 修正inputs參數
753
  generate_btn.click(
754
+ fn=lambda text, speed, conv=True: generate_speech(text, speed, conv),
755
+ inputs=[text_input, speed],
756
  outputs=[audio_output, status_msg],
757
  api_name="generate_speech"
758
  )
759
 
760
  text_input.submit(
761
+ fn=lambda text, speed, conv=True: generate_speech(text, speed, conv),
762
+ inputs=[text_input, speed],
763
  outputs=[audio_output, status_msg]
764
  )
765