File size: 4,439 Bytes
7d819f5
9b58b51
8dd64b1
9b58b51
ba8cf88
16653b0
ba8cf88
8dd64b1
9b58b51
e645a52
ba8cf88
9b58b51
ba8cf88
 
 
54dcb68
 
ba8cf88
7d819f5
ba8cf88
9b58b51
 
7d819f5
 
 
 
 
 
9b58b51
8dd64b1
ba8cf88
8dd64b1
 
 
9b58b51
59687c1
7d819f5
59687c1
7d819f5
 
 
ba8cf88
1149d1a
ba8cf88
7d819f5
ba8cf88
7d819f5
 
 
ba8cf88
 
 
 
1149d1a
7d819f5
 
 
 
 
 
 
 
1149d1a
7d819f5
 
01cecc3
7d819f5
 
 
 
 
 
 
 
 
 
 
 
ba8cf88
cbfb557
569eee3
cbfb557
569eee3
 
9b58b51
ba8cf88
 
7d819f5
ba8cf88
 
8dd64b1
 
 
 
 
 
cbfb557
ba8cf88
cbfb557
 
ba8cf88
cbfb557
8dd64b1
ba8cf88
 
9b58b51
ba8cf88
9b58b51
ba8cf88
9b58b51
ba8cf88
 
 
 
cbfb557
 
 
16653b0
ba8cf88
8dd64b1
ba8cf88
8dd64b1
569eee3
8dd64b1
 
16653b0
ba8cf88
 
e645a52
9fd1484
8dd64b1
ba8cf88
 
ed1b718
ba8cf88
7d819f5
ba8cf88
8dd64b1
ba8cf88
 
 
 
e645a52
ba8cf88
7d819f5
 
ba8cf88
 
 
 
e645a52
569eee3
8dd64b1
ba8cf88
 
 
 
 
 
 
 
 
7d819f5
ba8cf88
16653b0
ba8cf88
 
 
e645a52
 
ba8cf88
 
 
e645a52
 
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
 
import os
import uuid
import torch
import asyncio
import gradio as gr
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import FileResponse
from TTS.api import TTS
import uvicorn
from collections import deque

# =========================
# βœ… ACCEPT LICENSE
# =========================
os.environ["COQUI_TOS_AGREED"] = "1"

# =========================
# πŸ”₯ LOAD MODEL ONCE
# =========================
device = "cuda" if torch.cuda.is_available() else "cpu"

print("πŸš€ Loading XTTS model...")
tts = TTS(
    model_name="tts_models/multilingual/multi-dataset/xtts_v2",
    progress_bar=False
).to(device)
print("βœ… Model loaded!")

# =========================
# πŸ“ OUTPUT DIR
# =========================
OUTPUT_DIR = "outputs"
os.makedirs(OUTPUT_DIR, exist_ok=True)

# =========================
# ⚑ BATCH CONFIG
# =========================
BATCH_SIZE = 3
BATCH_WAIT_TIME = 1  # seconds

request_queue = deque()

# =========================
# πŸ”₯ BATCH WORKER
# =========================
async def batch_worker():
    print("πŸ”₯ Batch worker started...")

    while True:
        if len(request_queue) == 0:
            await asyncio.sleep(0.1)
            continue

        # Wait to collect batch
        await asyncio.sleep(BATCH_WAIT_TIME)

        batch = []
        while len(request_queue) > 0 and len(batch) < BATCH_SIZE:
            batch.append(request_queue.popleft())

        print(f"⚑ Processing batch of {len(batch)}")

        for item in batch:
            text, lang, audio_path, output_path, future = item

            try:
                tts.tts_to_file(
                    text=text,
                    speaker_wav=audio_path,
                    language=lang,
                    file_path=output_path,
                    split_sentences=True
                )
                future.set_result(output_path)

            except Exception as e:
                future.set_result(str(e))


# =========================
# FASTAPI
# =========================
api = FastAPI()

@api.on_event("startup")
async def startup_event():
    asyncio.create_task(batch_worker())


@api.post("/clone-voice/")
async def clone_voice_api(
    text: str = Form(...),
    language: str = Form(...),
    audio: UploadFile = File(...)
):
    try:
        input_path = f"{OUTPUT_DIR}/{uuid.uuid4()}_in.wav"
        output_path = f"{OUTPUT_DIR}/{uuid.uuid4()}_out.wav"

        with open(input_path, "wb") as f:
            f.write(await audio.read())

        loop = asyncio.get_event_loop()
        future = loop.create_future()

        request_queue.append((text, language, input_path, output_path, future))

        result = await future

        if isinstance(result, str) and result.endswith(".wav"):
            return FileResponse(result, media_type="audio/wav")
        else:
            return {"error": result}

    except Exception as e:
        return {"error": str(e)}


# =========================
# GRADIO UI
# =========================
async def clone_voice_ui(audio_path, text, language):
    if audio_path is None:
        return "❌ Upload audio", None

    if text.strip() == "":
        return "❌ Enter text", None

    output_path = f"{OUTPUT_DIR}/{uuid.uuid4()}.wav"

    loop = asyncio.get_event_loop()
    future = loop.create_future()

    request_queue.append((text, language, audio_path, output_path, future))

    result = await future

    if isinstance(result, str) and result.endswith(".wav"):
        return "βœ… Done", result
    else:
        return f"❌ {result}", None


with gr.Blocks(title="XTTS Voice Cloning (Batching)") as demo:
    gr.Markdown("# 🎀 XTTS Voice Cloning (Batch Mode)")

    audio_input = gr.Audio(type="filepath", label="Speaker Audio")
    text_input = gr.Textbox(label="Text")
    lang_input = gr.Textbox(value="en", label="Language")

    btn = gr.Button("Generate")

    status = gr.Textbox(label="Status")
    output_audio = gr.Audio(label="Generated Audio")

    btn.click(
        fn=clone_voice_ui,
        inputs=[audio_input, text_input, lang_input],
        outputs=[status, output_audio]
    )

# βœ… FIXED QUEUE (no concurrency_count)
demo.queue(max_size=20)

# =========================
# COMBINE APP
# =========================
app = gr.mount_gradio_app(api, demo, path="/")

# =========================
# RUN SERVER
# =========================
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)