Spaces:
Sleeping
Sleeping
File size: 15,066 Bytes
14100c7 |
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 |
import os
import sys
import subprocess
from huggingface_hub import hf_hub_download
from pydub import AudioSegment
import gradio as gr
import time
# Thêm thư mục src vào sys.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src')))
def run_f5_tts(ref_audio_path, ref_text, gen_text, model="F5TTS_Base", speed=1.2, vocoder_name="vocos"):
current_dir = os.path.dirname(os.path.abspath(__file__))
infer_cli_path = os.path.join(current_dir, "src", "f5_tts", "infer", "infer_cli.py")
tests_dir = os.path.join(current_dir, "tests")
print(f"Infer CLI path: {infer_cli_path}")
print(f"Does infer_cli.py exist? {os.path.exists(infer_cli_path)}")
if not os.path.exists(infer_cli_path):
return None, "File infer_cli.py không tồn tại!"
try:
vocab_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="vocab.txt")
ckpt_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="model_last.pt")
except Exception as e:
return None, f"Lỗi khi tải model/vocab: {str(e)}"
os.environ['PYTHONIOENCODING'] = 'utf-8'
env = os.environ.copy()
env['PYTHONPATH'] = os.path.abspath(os.path.join(current_dir, 'src'))
command = [
sys.executable,
infer_cli_path,
"--model", model,
"--ref_audio", ref_audio_path,
"--ref_text", ref_text,
"--gen_text", gen_text,
"--speed", str(speed),
"--vocoder_name", vocoder_name,
"--vocab_file", vocab_file,
"--ckpt_file", ckpt_file
]
print(f"Running command: {' '.join(command)}")
try:
result = subprocess.run(
command,
check=True,
capture_output=True,
text=True,
env=env
)
print("Subprocess stdout:", result.stdout)
if os.path.exists(tests_dir):
wav_files = [f for f in os.listdir(tests_dir) if f.endswith('.wav')]
if wav_files:
latest_wav = max(wav_files, key=lambda x: os.path.getmtime(os.path.join(tests_dir, x)))
output_wav = os.path.join(tests_dir, latest_wav)
audio = AudioSegment.from_wav(output_wav)
output_mp3 = os.path.join(tests_dir, "output.mp3")
audio.export(output_mp3, format="mp3")
return output_mp3, "Suy luận thành công!"
return None, "Không tìm thấy file âm thanh trong thư mục tests"
except subprocess.CalledProcessError as e:
return None, f"Lỗi khi chạy infer_cli.py: {e.stderr}"
except Exception as e:
return None, str(e)
def generate_speech(ref_audio, ref_text, gen_text, speed, model):
if ref_audio is None:
return None, "Vui lòng tải lên file audio tham chiếu!"
# ref_audio là đường dẫn file, tải bằng AudioSegment
audio_segment = AudioSegment.from_file(ref_audio)
audio_segment = audio_segment.set_channels(1) # Chuyển sang mono
ref_audio_path = f"temp_ref_{int(time.time())}.wav"
audio_segment.export(ref_audio_path, format="wav")
output_mp3, message = run_f5_tts(ref_audio_path, ref_text, gen_text, model, float(speed))
os.remove(ref_audio_path)
if output_mp3 and os.path.exists(output_mp3):
return output_mp3, message
return None, message
interface = gr.Interface(
fn=generate_speech,
inputs=[
gr.Audio(type="filepath", label="Tải lên file audio tham chiếu (.wav hoặc .mp3)"),
gr.Textbox(label="Text tham chiếu", placeholder="Nhập text của audio tham chiếu"),
gr.Textbox(label="Text cần sinh", placeholder="Nhập text bạn muốn sinh"),
gr.Slider(minimum=0.5, maximum=2.0, value=1.0, label="Tốc độ"),
gr.Dropdown(choices=["F5TTS_Base"], value="F5TTS_Base", label="Mô hình")
],
outputs=[
gr.Audio(type="filepath", label="Kết quả audio (.mp3)"),
gr.Textbox(label="Trạng thái")
],
title="F5-TTS Suy luận",
description="Tải lên audio tham chiếu, nhập text, và sinh audio mới với F5-TTS."
)
if __name__ == "__main__":
interface.launch(server_name="0.0.0.0", server_port=7860)
# import os
# import sys
# import subprocess
# from huggingface_hub import hf_hub_download
# from pydub import AudioSegment
# import gradio as gr
# import time
# # Thêm thư mục src vào sys.path
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src')))
# def run_f5_tts(ref_audio_path, ref_text, gen_text, model="F5TTS_Base", speed=1.2, vocoder_name="vocos"):
# current_dir = os.path.dirname(os.path.abspath(__file__))
# infer_cli_path = os.path.join(current_dir, "src", "f5_tts", "infer", "infer_cli.py")
# tests_dir = os.path.join(current_dir, "tests")
# # Debug: In đường dẫn để kiểm tra
# print(f"Infer CLI path: {infer_cli_path}")
# print(f"Tests dir: {tests_dir}")
# # Tải file từ Hugging Face Hub
# try:
# vocab_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="vocab.txt")
# ckpt_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="model_last.pt")
# except Exception as e:
# return None, f"Lỗi khi tải model/vocab từ Hugging Face: {str(e)}"
# os.environ['PYTHONIOENCODING'] = 'utf-8'
# env = os.environ.copy()
# env['PYTHONPATH'] = os.path.abspath(os.path.join(current_dir, 'src'))
# command = [
# sys.executable,
# infer_cli_path,
# "--model", model,
# "--ref_audio", ref_audio_path,
# "--ref_text", ref_text,
# "--gen_text", gen_text,
# "--speed", str(speed),
# "--vocoder_name", vocoder_name,
# "--vocab_file", vocab_file,
# "--ckpt_file", ckpt_file
# ]
# print(f"Running command: {' '.join(command)}")
# try:
# result = subprocess.run(
# command,
# check=True,
# capture_output=True,
# text=True,
# env=env
# )
# print("Subprocess stdout:", result.stdout)
# if os.path.exists(tests_dir):
# wav_files = [f for f in os.listdir(tests_dir) if f.endswith('.wav')]
# if wav_files:
# latest_wav = max(wav_files, key=lambda x: os.path.getmtime(os.path.join(tests_dir, x)))
# output_wav = os.path.join(tests_dir, latest_wav)
# audio = AudioSegment.from_wav(output_wav)
# output_mp3 = os.path.join(tests_dir, "output.mp3")
# audio.export(output_mp3, format="mp3")
# return output_mp3, "Suy luận thành công!"
# return None, "Không tìm thấy file âm thanh trong thư mục tests"
# except subprocess.CalledProcessError as e:
# return None, f"Lỗi khi chạy infer_cli.py: {e.stderr}"
# except Exception as e:
# return None, str(e)
# def generate_speech(ref_audio, ref_text, gen_text, speed, model):
# if ref_audio is None:
# return None, "Vui lòng tải lên file audio tham chiếu!"
# ref_audio_path = f"temp_ref_{int(time.time())}.wav"
# ref_audio.convert_audio_channels(1) # Chuyển sang mono
# ref_audio.export(ref_audio_path, format="wav")
# output_mp3, message = run_f5_tts(ref_audio_path, ref_text, gen_text, model, float(speed))
# os.remove(ref_audio_path)
# if output_mp3 and os.path.exists(output_mp3):
# return output_mp3, message
# return None, message
# interface = gr.Interface(
# fn=generate_speech,
# inputs=[
# gr.Audio(type="filepath", label="Tải lên file audio tham chiếu (.wav hoặc .mp3)"),
# gr.Textbox(label="Text tham chiếu", placeholder="Nhập text của audio tham chiếu"),
# gr.Textbox(label="Text cần sinh", placeholder="Nhập text bạn muốn sinh"),
# gr.Slider(minimum=0.5, maximum=2.0, value=1.0, label="Tốc độ"),
# gr.Dropdown(choices=["F5TTS_Base"], value="F5TTS_Base", label="Mô hình")
# ],
# outputs=[
# gr.Audio(type="filepath", label="Kết quả audio (.mp3)"),
# gr.Textbox(label="Trạng thái")
# ],
# title="F5-TTS Suy luận",
# description="Tải lên audio tham chiếu, nhập text, và sinh audio mới với F5-TTS."
# )
# if __name__ == "__main__":
# interface.launch(server_name="0.0.0.0", server_port=7860)
# from flask import Flask, request, send_file
# import subprocess
# import os
# import sys
# from huggingface_hub import hf_hub_download
# from pydub import AudioSegment
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src')))
# app = Flask(__name__)
# def run_f5_tts(ref_audio_path, ref_text, gen_text, model="F5TTS_Base", speed=1.2, vocoder_name="vocos"):
# current_dir = os.path.dirname(os.path.abspath(__file__))
# infer_cli_path = os.path.join(current_dir, "src", "f5_tts", "infer", "infer_cli.py")
# tests_dir = os.path.join(current_dir, "tests")
# vocab_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="vocab.txt")
# ckpt_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="model_last.pt")
# os.environ['PYTHONIOENCODING'] = 'utf-8'
# env = os.environ.copy()
# env['PYTHONPATH'] = os.path.abspath(os.path.join(current_dir, 'src'))
# command = [
# sys.executable,
# infer_cli_path,
# "--model", model,
# "--ref_audio", ref_audio_path,
# "--ref_text", ref_text,
# "--gen_text", gen_text,
# "--speed", str(speed),
# "--vocoder_name", vocoder_name,
# "--vocab_file", vocab_file,
# "--ckpt_file", ckpt_file
# ]
# try:
# result = subprocess.run(
# command,
# check=True,
# capture_output=True,
# text=True,
# encoding='utf-8',
# env=env
# )
# if os.path.exists(tests_dir):
# wav_files = [f for f in os.listdir(tests_dir) if f.endswith('.wav')]
# if wav_files:
# latest_wav = max(wav_files, key=lambda x: os.path.getmtime(os.path.join(tests_dir, x)))
# output_wav = os.path.join(tests_dir, latest_wav)
# audio = AudioSegment.from_wav(output_wav)
# output_mp3 = os.path.join(tests_dir, "output.mp3")
# audio.export(output_mp3, format="mp3")
# return True, output_mp3
# return False, "Không tìm thấy file âm thanh trong thư mục tests"
# except subprocess.CalledProcessError as e:
# return False, f"Lỗi khi chạy infer_cli.py: {e.stderr}"
# except Exception as e:
# return False, str(e)
# @app.route('/')
# def home():
# return "F5-TTS API is running. Use POST /api/generate to generate audio."
# @app.route('/api/generate', methods=['POST'])
# def generate_speech():
# if 'ref_audio' not in request.files:
# return {"error": "Missing ref_audio"}, 400
# ref_audio = request.files['ref_audio']
# ref_text = request.form.get('ref_text', '')
# gen_text = request.form.get('gen_text', '')
# model = request.form.get('model', 'F5TTS_Base')
# speed = float(request.form.get('speed', 1.2))
# import time
# ref_audio_path = f"temp_ref_{int(time.time())}.wav"
# ref_audio.save(ref_audio_path)
# success, result = run_f5_tts(ref_audio_path, ref_text, gen_text, model, speed)
# os.remove(ref_audio_path)
# if success:
# return send_file(result, mimetype='audio/mpeg')
# else:
# return {"error": result}, 500
# if __name__ == "__main__":
# port = int(os.environ.get("PORT", 7860))
# app.run(host="0.0.0.0", port=port, debug=False)
# from flask import Flask, request, send_file
# import subprocess
# import os
# import sys
# from huggingface_hub import hf_hub_download
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src')))
# app = Flask(__name__)
# # =========================
# # Hàm chạy F5-TTS
# # =========================
# def run_f5_tts(ref_audio_path, ref_text, gen_text, model="F5TTS_Base", speed=1.2, vocoder_name="vocos"):
# current_dir = os.path.dirname(os.path.abspath(__file__))
# infer_cli_path = os.path.join(current_dir, "src", "f5_tts", "infer", "infer_cli.py")
# tests_dir = os.path.join(current_dir, "tests")
# # Dùng huggingface_hub để tải file model và vocab từ repo 'nguyensu27/TTS'
# vocab_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="vocab.txt")
# ckpt_file = hf_hub_download(repo_id="nguyensu27/TTS", filename="model_last.pt")
# os.environ['PYTHONIOENCODING'] = 'utf-8'
# command = [
# sys.executable,
# infer_cli_path,
# "--model", model,
# "--ref_audio", ref_audio_path,
# "--ref_text", ref_text,
# "--gen_text", gen_text,
# "--speed", str(speed),
# "--vocoder_name", vocoder_name,
# "--vocab_file", vocab_file,
# "--ckpt_file", ckpt_file
# ]
# try:
# result = subprocess.run(
# command,
# check=True,
# capture_output=True,
# text=True,
# encoding='utf-8'
# )
# if os.path.exists(tests_dir):
# wav_files = [f for f in os.listdir(tests_dir) if f.endswith('.wav')]
# if wav_files:
# latest_wav = max(
# wav_files, key=lambda x: os.path.getmtime(os.path.join(tests_dir, x))
# )
# output_file = os.path.join(tests_dir, latest_wav)
# return True, output_file
# return False, "Không tìm thấy file âm thanh trong thư mục tests"
# except subprocess.CalledProcessError as e:
# return False, e.stderr
# except Exception as e:
# return False, str(e)
# # =========================
# # Routes
# # =========================
# @app.route('/')
# def home():
# return "F5-TTS API is running. Use POST /api/generate to generate audio."
# @app.route('/api/generate', methods=['POST'])
# def generate_speech():
# if 'ref_audio' not in request.files:
# return {"error": "Missing ref_audio"}, 400
# ref_audio = request.files['ref_audio']
# ref_text = request.form.get('ref_text', '')
# gen_text = request.form.get('gen_text', '')
# model = request.form.get('model', 'F5TTS_Base')
# speed = float(request.form.get('speed', 1.2))
# ref_audio_path = 'temp_ref.wav'
# ref_audio.save(ref_audio_path)
# success, result = run_f5_tts(ref_audio_path, ref_text, gen_text, model, speed)
# os.remove(ref_audio_path)
# if success:
# return send_file(result, mimetype='audio/wav')
# else:
# return {"error": result}, 500
# # =========================
# # Main
# # =========================
# if __name__ == "__main__":
# port = int(os.environ.get("PORT", 7860))
# app.run(host="0.0.0.0", port=port, debug=False)
|