-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_example.py
More file actions
353 lines (295 loc) Β· 12.1 KB
/
Copy pathclient_example.py
File metadata and controls
353 lines (295 loc) Β· 12.1 KB
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
"""
CusVoiceModel API ν΄λΌμ΄μΈνΈ μμ
FastAPI μλ² μ¬μ©λ²μ 보μ¬μ£Όλ μμ ν μμ
"""
import requests
import time
import json
from pathlib import Path
import argparse
class CusVoiceModelClient:
"""CusVoiceModel FastAPI μλ²μ© ν΄λΌμ΄μΈνΈ"""
def __init__(self, base_url: str = "http://localhost:8090"):
self.base_url = base_url.rstrip('/')
def health_check(self):
"""μλ² μν νμΈ"""
try:
response = requests.get(f"{self.base_url}/health")
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"μν νμΈ μ€ν¨: {e}")
return None
def generate_speech(self, text: str, **kwargs):
"""ν
μ€νΈμμ μμ± μμ±"""
payload = {
"text": text,
**kwargs
}
try:
response = requests.post(f"{self.base_url}/generate", json=payload)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"μμ± μμ± μμ² μ€ν¨: {e}")
return None
def generate_with_voice(self, text: str, voice_file_path: str, **kwargs):
"""μμ± ν΄λ‘λμΌλ‘ μμ± μμ±"""
files = {"voice_file": open(voice_file_path, "rb")}
data = {
"text": text,
**kwargs
}
try:
response = requests.post(f"{self.base_url}/generate-with-voice",
files=files, data=data)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"μμ± ν΄λ‘λ μμ² μ€ν¨: {e}")
return None
finally:
files["voice_file"].close()
def get_task_status(self, task_id: str):
"""μμ
μν νμΈ"""
try:
response = requests.get(f"{self.base_url}/status/{task_id}")
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"μν νμΈ μ€ν¨: {e}")
return None
def download_audio(self, task_id: str, output_path: str):
"""μμ±λ μ€λμ€ λ€μ΄λ‘λ"""
try:
response = requests.get(f"{self.base_url}/download/{task_id}")
response.raise_for_status()
with open(output_path, "wb") as f:
f.write(response.content)
return True
except requests.RequestException as e:
print(f"λ€μ΄λ‘λ μ€ν¨: {e}")
return False
def wait_for_completion(self, task_id: str, timeout: int = 300):
"""μμ
μλ£ λκΈ°"""
start_time = time.time()
while time.time() - start_time < timeout:
status = self.get_task_status(task_id)
if not status:
return None
print(f"μν: {status['status']} - {status['message']}")
if status["status"] == "completed":
return status
elif status["status"] == "failed":
print(f"μμ
μ€ν¨: {status['message']}")
return status
time.sleep(2)
print("μλ£ λκΈ° μκ° μ΄κ³Ό")
return None
def main():
parser = argparse.ArgumentParser(description="CusVoiceModel API ν΄λΌμ΄μΈνΈ μμ ")
parser.add_argument("--url", default="http://localhost:8090",
help="API μλ² URL")
parser.add_argument("--text", default="μλ
νμΈμ, CusVoiceModel API ν
μ€νΈμ
λλ€.",
help="μμ±μΌλ‘ λ³νν ν
μ€νΈ")
parser.add_argument("--model", default="CusVoiceModel-1.5B",
choices=["CusVoiceModel-1.5B", "CusVoiceModel-Large", "CusVoiceModel-Large-Quant-4Bit"],
help="μ¬μ©ν λͺ¨λΈ")
parser.add_argument("--voice", help="ν΄λ‘λμ© μ°Έμ‘° μμ± νμΌ κ²½λ‘")
parser.add_argument("--output", default="generated_speech.wav",
help="μΆλ ₯ μ€λμ€ νμΌ κ²½λ‘")
parser.add_argument("--seed", type=int, default=42, help="λλ€ μλ")
parser.add_argument("--steps", type=int, default=20, help="λν¨μ μ€ν
")
parser.add_argument("--cfg-scale", type=float, default=1.3, help="CFG μ€μΌμΌ")
args = parser.parse_args()
# ν΄λΌμ΄μΈνΈ μ΄κΈ°ν
client = CusVoiceModelClient(args.url)
# μλ² μν νμΈ
print("μλ² μν νμΈ μ€...")
health = client.health_check()
if not health:
print("μλ²κ° μλ΅νμ§ μμ΅λλ€!")
return
print(f"μλ² μν: {health['status']}")
print(f"λͺ¨λΈ λ‘λλ¨: {health['model_loaded']}")
print(f"GPU μ¬μ© κ°λ₯: {health['gpu_available']}")
# μμ± μμ±
print(f"\nμμ± μμ± μ€...")
print(f"ν
μ€νΈ: {args.text}")
print(f"λͺ¨λΈ: {args.model}")
if args.voice:
print(f"μμ± ν΄λ‘λ μ¬μ©: {args.voice}")
result = client.generate_with_voice(
text=args.text,
voice_file_path=args.voice,
model=args.model,
seed=args.seed,
diffusion_steps=args.steps,
cfg_scale=args.cfg_scale
)
else:
print("ν©μ± μμ± μ¬μ©")
result = client.generate_speech(
text=args.text,
model=args.model,
seed=args.seed,
diffusion_steps=args.steps,
cfg_scale=args.cfg_scale
)
if not result:
print("μμ± μμ μ€ν¨!")
return
task_id = result["task_id"]
print(f"μμ
ID: {task_id}")
# μλ£ λκΈ°
print("\nμλ£ λκΈ° μ€...")
final_status = client.wait_for_completion(task_id)
if final_status and final_status["status"] == "completed":
print("\nμμ± μλ£!")
# μ€λμ€ λ€μ΄λ‘λ
print(f"{args.output}λ‘ μ€λμ€ λ€μ΄λ‘λ μ€...")
if client.download_audio(task_id, args.output):
print(f"β
μ€λμ€ μ μ₯ μ±κ³΅: {args.output}")
# κ²°κ³Ό μ 보 νμ
if final_status.get("result"):
duration = final_status["result"].get("duration_seconds")
if duration:
print(f"μ€λμ€ κΈΈμ΄: {duration:.2f}μ΄")
else:
print("β μ€λμ€ λ€μ΄λ‘λ μ€ν¨")
else:
print("β μμ± μ€ν¨ λλ μκ° μ΄κ³Ό")
def example_batch_processing():
"""μ¬λ¬ ν
μ€νΈ λ°°μΉ μ²λ¦¬ μμ """
client = CusVoiceModelClient()
texts = [
"첫 λ²μ§Έ μμ ν
μ€νΈμ
λλ€.",
"λ λ²μ§Έ ν
μ€νΈμλ 무μμ΄ μμ΅λλ€. [pause:1000] λ€λ¦¬μ
¨λμ?",
"μΈ λ²μ§Έ ν
μ€νΈλ κΈ΄ λ΄μ© μ²λ¦¬ κΈ°λ₯μ 보μ¬μ€λλ€.",
"λ§μ§λ§μΌλ‘, λ€ λ²μ§Έ ν
μ€νΈλ‘ λ°°μΉ μμ λ₯Ό λ§μΉ©λλ€. [pause] κ°μ¬ν©λλ€!"
]
print("λ°°μΉ μ²λ¦¬ μμ ...")
tasks = []
# λͺ¨λ μμ
μ μΆ
for i, text in enumerate(texts):
print(f"μμ
{i+1}/{len(texts)} μ μΆ μ€...")
result = client.generate_speech(
text=text,
seed=42 + i, # κ°κ° λ€λ₯Έ μλ
model="CusVoiceModel-1.5B"
)
if result:
tasks.append((result["task_id"], f"batch_output_{i+1}.wav"))
else:
print(f"μμ
{i+1} μ μΆ μ€ν¨")
# λͺ¨λ μλ£ λκΈ°
print(f"\n{len(tasks)}κ° μμ
μλ£ λκΈ° μ€...")
for task_id, output_file in tasks:
print(f"μμ
{task_id} λκΈ° μ€...")
status = client.wait_for_completion(task_id)
if status and status["status"] == "completed":
if client.download_audio(task_id, output_file):
print(f"β
λ€μ΄λ‘λ μλ£: {output_file}")
else:
print(f"β λ€μ΄λ‘λ μ€ν¨: {output_file}")
else:
print(f"β μμ
μ€ν¨: {task_id}")
def example_voice_cloning():
"""μμ± ν΄λ‘λ κΈ°λ₯ μμ """
client = CusVoiceModelClient()
# μ°Έμ‘° μμ± νμΌμ μ 곡ν΄μΌ ν©λλ€
reference_voice = "reference_voice.wav"
if not Path(reference_voice).exists():
print(f"μ°Έμ‘° μμ± νμΌμ μ°Ύμ μ μμ: {reference_voice}")
print("ν΄λ‘λ μμ λ₯Ό μν΄ μ°Έμ‘° μμ± νμΌμ μ 곡ν΄μ£ΌμΈμ")
return
text = "μμ± ν΄λ‘λ μμ μ
λλ€. AIκ° μ°Έμ‘° μμ±μ λͺ¨λ°©νλ €κ³ μλν©λλ€."
print("μμ± ν΄λ‘λ μμ ...")
result = client.generate_with_voice(
text=text,
voice_file_path=reference_voice,
model="CusVoiceModel-1.5B",
seed=42
)
if result:
task_id = result["task_id"]
status = client.wait_for_completion(task_id)
if status and status["status"] == "completed":
if client.download_audio(task_id, "cloned_voice_output.wav"):
print("β
μμ± ν΄λ‘λ μλ£: cloned_voice_output.wav")
else:
print("β ν΄λ‘ λ μμ± λ€μ΄λ‘λ μ€ν¨")
else:
print("β μμ± ν΄λ‘λ μ€ν¨")
else:
print("β μμ± ν΄λ‘λ μμ μ€ν¨")
def example_pause_functionality():
"""무μ κΈ°λ₯ μμ° μμ """
client = CusVoiceModelClient()
text_with_pauses = """
무μ κΈ°λ₯ μμ°μ μ€μ κ²μ νμν©λλ€. [pause]
μ΄κ²μ 1μ΄ λ¬΄μμ
λλ€. [pause:1500]
λ°©κΈ κ²μ 1.5μ΄ λ¬΄μμ΄μμ΅λλ€. [pause:500]
μ΄κ²μ 0.5μ΄ λ¬΄μμ΄μμ΅λλ€. [pause:2000]
κ·Έλ¦¬κ³ λ°©κΈ κ²μ 2μ΄ λ¬΄μμ΄μμ΅λλ€. λ€μ΄μ£Όμ
μ κ°μ¬ν©λλ€!
"""
print("무μ κΈ°λ₯ μμ ...")
result = client.generate_speech(
text=text_with_pauses,
model="CusVoiceModel-1.5B",
seed=42
)
if result:
task_id = result["task_id"]
status = client.wait_for_completion(task_id)
if status and status["status"] == "completed":
if client.download_audio(task_id, "pause_example.wav"):
print("β
무μ μμ μλ£: pause_example.wav")
if status.get("result"):
duration = status["result"].get("duration_seconds")
if duration:
print(f"무μ ν¬ν¨ μ΄ κΈΈμ΄: {duration:.2f}μ΄")
else:
print("β 무μ μμ λ€μ΄λ‘λ μ€ν¨")
else:
print("β 무μ μμ μ€ν¨")
else:
print("β 무μ μμ μμ μ€ν¨")
if __name__ == "__main__":
# λͺ
λ Ήμ€ μΈμ νμΈ
import sys
if len(sys.argv) > 1:
# λ©μΈ CLI μΈν°νμ΄μ€ μ€ν
main()
else:
# μμ μ€ν
print("CusVoiceModel API μμ μ€ν μ€...")
print("CLI μ΅μ
μ --help μ¬μ©, λλ μλ μμ λ€μ μ€ν:\n")
# κΈ°λ³Έ μμ
print("=== κΈ°λ³Έ μμ± μμ± ===")
main_args = argparse.Namespace(
url="http://localhost:8090",
text="μλ
νμΈμ, CusVoiceModel API κΈ°λ³Έ μμ μ
λλ€.",
model="CusVoiceModel-1.5B",
voice=None,
output="basic_example.wav",
seed=42,
steps=20,
cfg_scale=1.3
)
# μμ λ₯Ό μν΄ sys.argv μμ κ΅μ²΄
original_argv = sys.argv[:]
sys.argv = ["client_example.py", "--text", main_args.text]
try:
main()
except:
pass
finally:
sys.argv = original_argv
print("\n=== 무μ κΈ°λ₯ ===")
example_pause_functionality()
print("\n=== λ°°μΉ μ²λ¦¬ ===")
example_batch_processing()
print("\n=== μμ± ν΄λ‘λ (μ°Έμ‘° νμΌμ΄ μλ κ²½μ°) ===")
example_voice_cloning()
print("\nμμ μλ£! μμ±λ μ€λμ€ νμΌλ€μ νμΈν΄λ³΄μΈμ.")