Alstears commited on
Commit
e0fc798
·
verified ·
1 Parent(s): 866a529

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import requests
4
+ import torch
5
+ import torchaudio as ta
6
+ import gradio as gr
7
+
8
+ from chatterbox.tts import ChatterboxTTS
9
+ from huggingface_hub import hf_hub_download
10
+ from safetensors.torch import load_file
11
+
12
+ MODEL_REPO = "grandhigh/Chatterbox-TTS-Indonesian"
13
+ CHECKPOINT_FILENAME = "t3_cfg.safetensors"
14
+ DEVICE = "cpu"
15
+
16
+ print("Loading model...")
17
+ model = ChatterboxTTS.from_pretrained(device=DEVICE)
18
+
19
+ checkpoint_path = hf_hub_download(repo_id=MODEL_REPO, filename=CHECKPOINT_FILENAME)
20
+ t3_state = load_file(checkpoint_path, device="cpu")
21
+ model.t3.load_state_dict(t3_state)
22
+
23
+ model = model.to(DEVICE)
24
+ model.eval()
25
+ print("Model loaded.")
26
+
27
+ def _download_audio_from_url(url: str) -> str:
28
+ r = requests.get(url, timeout=60)
29
+ r.raise_for_status()
30
+ tmp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
31
+ tmp_wav.write(r.content)
32
+ tmp_wav.close()
33
+ return tmp_wav.name
34
+
35
+ def clone_voice(text: str, audio_file, audio_url: str):
36
+ if not text or not text.strip():
37
+ raise gr.Error("Text prompt tidak boleh kosong.")
38
+
39
+ prompt_path = None
40
+ if audio_file is not None:
41
+ prompt_path = audio_file
42
+ elif audio_url and audio_url.strip():
43
+ prompt_path = _download_audio_from_url(audio_url.strip())
44
+
45
+ if prompt_path is None:
46
+ raise gr.Error("Upload WAV atau isi audio_url.")
47
+
48
+ with torch.no_grad():
49
+ wav = model.generate(text.strip(), audio_prompt_path=prompt_path)
50
+
51
+ if wav.dim() == 1:
52
+ wav = wav.unsqueeze(0)
53
+
54
+ out_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav").name
55
+ ta.save(out_file, wav.cpu(), model.sr)
56
+ return out_file
57
+
58
+ with gr.Blocks(title="Chatterbox Indonesian Voice Cloning API") as demo:
59
+ gr.Markdown("## Chatterbox-TTS Indonesian (Voice Cloning, CPU)")
60
+ text_in = gr.Textbox(label="Text Prompt", lines=4)
61
+ wav_in = gr.Audio(label="Upload WAV Prompt", type="filepath")
62
+ url_in = gr.Textbox(label="Audio URL (opsional)")
63
+ btn = gr.Button("Generate")
64
+ out_audio = gr.Audio(label="Hasil Audio", type="filepath")
65
+
66
+ btn.click(
67
+ fn=clone_voice,
68
+ inputs=[text_in, wav_in, url_in],
69
+ outputs=[out_audio],
70
+ api_name="clone_voice"
71
+ )
72
+
73
+ if __name__ == "__main__":
74
+ port = int(os.getenv("PORT", os.getenv("GRADIO_SERVER_PORT", 7860)))
75
+ demo.launch(server_name="0.0.0.0", server_port=port)