ktvoice commited on
Commit
ff44ae6
·
verified ·
1 Parent(s): 29cef31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -139
app.py CHANGED
@@ -1,140 +1,141 @@
1
- import spaces
2
- import os
3
- import gradio as gr
4
- import soundfile as sf
5
- import tempfile
6
- import torch
7
- import librosa
8
- import time
9
- from tts_engine import VoiceEngine
10
-
11
- # --- 1. KHỞI TẠO (Giữ nguyên logic nạp model đã thành công) ---
12
- os.environ['SPACES_ZERO_GPU'] = '1'
13
- device = "cuda" if torch.cuda.is_available() else "cpu"
14
-
15
- print(f"🔄 Đang khởi động trên: {device}")
16
-
17
- try:
18
- tts = VoiceEngine(
19
- backbone_repo="ktvoice/Backbone",
20
- backbone_device=device,
21
- codec_repo="ktvoice/Codec",
22
- codec_device=device
23
- )
24
- print("✅ Đã nạp thành công Model!")
25
- except Exception as e:
26
- print(f"❌ Lỗi nạp mô hình: {e}")
27
- tts = None
28
-
29
- # Danh sách giọng
30
- VOICE_SAMPLES = {
31
- "Tuyên (nam miền Bắc)": {"audio": "./sample/Tuyên (nam miền Bắc).wav", "text": "./sample/Tuyên (nam miền Bắc).txt"},
32
- "Thiện Tâm": {"audio": "./sample/thientam.mp3", "text": "./sample/thientam.txt"},
33
- "Vĩnh (nam miền Nam)": {"audio": "./sample/Vĩnh (nam miền Nam).wav", "text": "./sample/Vĩnh (nam miền Nam).txt"},
34
- "Bình (nam miền Bắc)": {"audio": "./sample/Bình (nam miền Bắc).wav", "text": "./sample/Bình (nam miền Bắc).txt"},
35
- "Nguyên (nam miền Nam)": {"audio": "./sample/Nguyên (nam miền Nam).wav", "text": "./sample/Nguyên (nam miền Nam).txt"},
36
- "Sơn (nam miền Nam)": {"audio": "./sample/Sơn (nam miền Nam).wav", "text": "./sample/Sơn (nam miền Nam).txt"},
37
- "Đoan (nữ miền Nam)": {"audio": "./sample/Đoan (nữ miền Nam).wav", "text": "./sample/Đoan (nữ miền Nam).txt"},
38
- "Ngọc (nữ miền Bắc)": {"audio": "./sample/Ngọc (nữ miền Bắc).wav", "text": "./sample/Ngọc (nữ miền Bắc).txt"},
39
- "Ly (nữ miền Bắc)": {"audio": "./sample/Ly (nữ miền Bắc).wav", "text": "./sample/Ly (nữ miền Bắc).txt"},
40
- "Dung (nữ miền Nam)": {"audio": "./sample/Dung (nữ miền Nam).wav", "text": "./sample/Dung (nữ miền Nam).txt"}
41
- }
42
-
43
- @spaces.GPU(duration=60)
44
- def tts_process(text, voice_choice, custom_audio, custom_text, mode_tab, pause_level, speed_value):
45
- if tts is None:
46
- return None, "Hệ thống chưa sẵn sàng."
47
-
48
- if not text or not text.strip():
49
- return None, "Vui lòng nhập văn bản."
50
-
51
- try:
52
- # Chọn nguồn giọng
53
- if mode_tab == "custom":
54
- if not custom_audio: return None, "Thiếu Audio mẫu."
55
- if not custom_text: return None, "Thiếu lời thoại mẫu."
56
- ref_path, ref_txt_val = custom_audio, custom_text
57
- else:
58
- sample = VOICE_SAMPLES.get(voice_choice)
59
- ref_path = sample["audio"]
60
- try:
61
- with open(sample["text"], "r", encoding="utf-8") as f:
62
- ref_txt_val = f.read()
63
- except:
64
- return None, "Lỗi đọc file text mẫu."
65
-
66
- # Xử lý ngắt nghỉ
67
- processed_text = text
68
- if pause_level == "Trung bình":
69
- processed_text = processed_text.replace(",", ", , ").replace(".", ". . ")
70
- elif pause_level == "Dài":
71
- processed_text = processed_text.replace(",", ", , , ").replace(".", ". . . . ")
72
-
73
- start_time = time.time()
74
-
75
- # Chạy AI
76
- ref_codes = tts.encode_reference(ref_path)
77
- wav = tts.infer(processed_text[:500], ref_codes, ref_txt_val)
78
-
79
- # Tốc độ
80
- if speed_value != 1.0:
81
- wav = librosa.effects.time_stretch(wav, rate=float(speed_value))
82
-
83
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
84
- sf.write(tmp.name, wav, 24000)
85
- return tmp.name, f"Hoàn tất: {time.time() - start_time:.2f}s"
86
-
87
- except Exception as e:
88
- return None, f"Lỗi: {str(e)}"
89
-
90
- # --- 2. GIAO DIỆN CƠ BẢN (Native Gradio) ---
91
- with gr.Blocks(title="AI Voice") as demo:
92
- gr.Markdown("# 🎙️ AI Voice Studio")
93
-
94
- with gr.Row():
95
- with gr.Column():
96
- input_text = gr.Textbox(
97
- label="Văn bản cần đọc",
98
- lines=5,
99
- placeholder="Nhập tiếng Việt vào đây..."
100
- )
101
-
102
- with gr.Tabs() as tabs:
103
- with gr.Tab("Chọn giọng có sẵn", id="preset"):
104
- voice_dropdown = gr.Dropdown(
105
- choices=list(VOICE_SAMPLES.keys()),
106
- value="Tuyên (nam miền Bắc)",
107
- label="Danh sách Nghệ sĩ"
108
- )
109
- with gr.Tab("Tự nhân bản (Clone)", id="custom"):
110
- c_audio = gr.Audio(label="Audio mẫu", type="filepath")
111
- c_text = gr.Textbox(label="Lời thoại mẫu", lines=2)
112
-
113
- with gr.Row():
114
- pause_radio = gr.Radio(["Mặc định", "Trung bình", "Dài"], value="Mặc định", label="Ngắt nghỉ")
115
- speed_slider = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Tốc độ")
116
-
117
- active_tab = gr.State("preset")
118
- gen_btn = gr.Button("ĐỌC NGAY", variant="primary")
119
-
120
- with gr.Column():
121
- output_audio = gr.Audio(label="Kết quả", interactive=False)
122
- output_status = gr.Textbox(label="Trạng thái", interactive=False)
123
-
124
- tabs.children[0].select(lambda: "preset", None, active_tab)
125
- tabs.children[1].select(lambda: "custom", None, active_tab)
126
-
127
- gen_btn.click(
128
- fn=tts_process,
129
- inputs=[input_text, voice_dropdown, c_audio, c_text, active_tab, pause_radio, speed_slider],
130
- outputs=[output_audio, output_status]
131
- )
132
-
133
- if __name__ == "__main__":
134
- # Cấu hình chuẩn để tránh mọi cảnh báo và lỗi
135
- demo.queue().launch(
136
- server_name="0.0.0.0",
137
- server_port=7860,
138
- ssr_mode=False,
139
- theme=gr.themes.Default()
 
140
  )
 
1
+ import spaces
2
+ import os
3
+ import gradio as gr
4
+ import soundfile as sf
5
+ import tempfile
6
+ import torch
7
+ import librosa
8
+ import time
9
+ from tts_engine import VoiceEngine
10
+
11
+ # --- 1. KHỞI TẠO (Giữ nguyên logic nạp model đã thành công) ---
12
+ os.environ['SPACES_ZERO_GPU'] = '1'
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ print(f"🔄 Đang khởi động trên: {device}")
16
+
17
+ try:
18
+ tts = VoiceEngine(
19
+ backbone_repo="ktvoice/Backbone",
20
+ backbone_device=device,
21
+ codec_repo="ktvoice/Codec",
22
+ codec_device=device
23
+ )
24
+ print("✅ Đã nạp thành công Model!")
25
+ except Exception as e:
26
+ print(f"❌ Lỗi nạp mô hình: {e}")
27
+ tts = None
28
+
29
+ # Danh sách giọng
30
+ VOICE_SAMPLES = {
31
+ "Tuyên (nam miền Bắc)": {"audio": "./sample/Tuyên (nam miền Bắc).wav", "text": "./sample/Tuyên (nam miền Bắc).txt"},
32
+ "Thiện Tâm": {"audio": "./sample/thientam.mp3", "text": "./sample/thientam.txt"},
33
+ "Vĩnh (nam miền Nam)": {"audio": "./sample/Vĩnh (nam miền Nam).wav", "text": "./sample/Vĩnh (nam miền Nam).txt"},
34
+ "Bình (nam miền Bắc)": {"audio": "./sample/Bình (nam miền Bắc).wav", "text": "./sample/Bình (nam miền Bắc).txt"},
35
+ "Nguyên (nam miền Nam)": {"audio": "./sample/Nguyên (nam miền Nam).wav", "text": "./sample/Nguyên (nam miền Nam).txt"},
36
+ "Sơn (nam miền Nam)": {"audio": "./sample/Sơn (nam miền Nam).wav", "text": "./sample/Sơn (nam miền Nam).txt"},
37
+ "Đoan (nữ miền Nam)": {"audio": "./sample/Đoan (nữ miền Nam).wav", "text": "./sample/Đoan (nữ miền Nam).txt"},
38
+ "Ngọc (nữ miền Bắc)": {"audio": "./sample/Ngọc (nữ miền Bắc).wav", "text": "./sample/Ngọc (nữ miền Bắc).txt"},
39
+ "Ly (nữ miền Bắc)": {"audio": "./sample/Ly (nữ miền Bắc).wav", "text": "./sample/Ly (nữ miền Bắc).txt"},
40
+ "Dung (nữ miền Nam)": {"audio": "./sample/Dung (nữ miền Nam).wav", "text": "./sample/Dung (nữ miền Nam).txt"}
41
+ }
42
+
43
+ @spaces.GPU(duration=60)
44
+ def tts_process(text, voice_choice, custom_audio, custom_text, mode_tab, pause_level, speed_value):
45
+ if tts is None:
46
+ return None, "Hệ thống chưa sẵn sàng."
47
+
48
+ if not text or not text.strip():
49
+ return None, "Vui lòng nhập văn bản."
50
+
51
+ try:
52
+ # Chọn nguồn giọng
53
+ if mode_tab == "custom":
54
+ if not custom_audio: return None, "Thiếu Audio mẫu."
55
+ if not custom_text: return None, "Thiếu lời thoại mẫu."
56
+ ref_path, ref_txt_val = custom_audio, custom_text
57
+ else:
58
+ sample = VOICE_SAMPLES.get(voice_choice)
59
+ ref_path = sample["audio"]
60
+ try:
61
+ with open(sample["text"], "r", encoding="utf-8") as f:
62
+ ref_txt_val = f.read()
63
+ except:
64
+ return None, "Lỗi đọc file text mẫu."
65
+
66
+ # Xử lý ngắt nghỉ
67
+ processed_text = text
68
+ if pause_level == "Trung bình":
69
+ processed_text = processed_text.replace(",", ", , ").replace(".", ". . ")
70
+ elif pause_level == "Dài":
71
+ processed_text = processed_text.replace(",", ", , , ").replace(".", ". . . . ")
72
+
73
+ start_time = time.time()
74
+
75
+ # Chạy AI
76
+ ref_codes = tts.encode_reference(ref_path)
77
+ wav = tts.infer(processed_text[:500], ref_codes, ref_txt_val)
78
+
79
+ # Tốc độ
80
+ if speed_value != 1.0:
81
+ wav = librosa.effects.time_stretch(wav, rate=float(speed_value))
82
+
83
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
84
+ sf.write(tmp.name, wav, 24000)
85
+ return tmp.name, f"Hoàn tất: {time.time() - start_time:.2f}s"
86
+
87
+ except Exception as e:
88
+ return None, f"Lỗi: {str(e)}"
89
+
90
+ # --- 2. GIAO DIỆN CƠ BẢN (Native Gradio) ---
91
+ with gr.Blocks(title="AI Voice") as demo:
92
+ gr.Markdown("# 🎙️ AI Voice Studio")
93
+
94
+ with gr.Row():
95
+ with gr.Column():
96
+ input_text = gr.Textbox(
97
+ label="Văn bản cần đọc",
98
+ lines=5,
99
+ placeholder="Nhập tiếng Việt vào đây..."
100
+ )
101
+
102
+ with gr.Tabs() as tabs:
103
+ with gr.Tab("Chọn giọng có sẵn", id="preset"):
104
+ voice_dropdown = gr.Dropdown(
105
+ choices=list(VOICE_SAMPLES.keys()),
106
+ value="Tuyên (nam miền Bắc)",
107
+ label="Danh sách Nghệ sĩ"
108
+ )
109
+ with gr.Tab("Tự nhân bản (Clone)", id="custom"):
110
+ c_audio = gr.Audio(label="Audio mẫu", type="filepath")
111
+ c_text = gr.Textbox(label="Lời thoại mẫu", lines=2)
112
+
113
+ with gr.Row():
114
+ pause_radio = gr.Radio(["Mặc định", "Trung bình", "Dài"], value="Mặc định", label="Ngắt nghỉ")
115
+ speed_slider = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Tốc độ")
116
+
117
+ active_tab = gr.Textbox(value="preset", visible=False, label="Mode")
118
+ gen_btn = gr.Button("ĐỌC NGAY", variant="primary")
119
+
120
+ with gr.Column():
121
+ output_audio = gr.Audio(label="Kết quả", interactive=False)
122
+ output_status = gr.Textbox(label="Trạng thái", interactive=False)
123
+
124
+ tabs.children[0].select(lambda: "preset", None, active_tab)
125
+ tabs.children[1].select(lambda: "custom", None, active_tab)
126
+
127
+ gen_btn.click(
128
+ fn=tts_process,
129
+ inputs=[input_text, voice_dropdown, c_audio, c_text, active_tab, pause_radio, speed_slider],
130
+ outputs=[output_audio, output_status],
131
+ api_name="tts" # <--- QUAN TRỌNG: Định danh API là "tts"
132
+ )
133
+
134
+ if __name__ == "__main__":
135
+ # Cấu hình chuẩn để tránh mọi cảnh báo và lỗi
136
+ demo.queue().launch(
137
+ server_name="0.0.0.0",
138
+ server_port=7860,
139
+ ssr_mode=False,
140
+ theme=gr.themes.Default()
141
  )