ktvoice commited on
Commit
de9af94
·
verified ·
1 Parent(s): 12df545

Upload app.py

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