File size: 6,526 Bytes
a4d9876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py

import asyncio
import base64
import io
import json
import time
from typing import AsyncGenerator

import numpy as np
import soundfile as sf
import torch
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from omnivoice import OmniVoice

# =========================================================
# App
# =========================================================

app = FastAPI(title="OmniVoice OpenAI-Compatible TTS")

# =========================================================
# Constants
# =========================================================

SAMPLE_RATE = 24000
NUM_CHANNELS = 1
BYTES_PER_SAMPLE = 2

FRAME_MS = 20

CHUNK_SIZE = int(
    SAMPLE_RATE * (FRAME_MS / 1000) * BYTES_PER_SAMPLE * NUM_CHANNELS
)

# =========================================================
# Fixed Voice Config
# =========================================================

FIXED_REF_AUDIO = "ref_audio/women_ref_1.mp3"

FIXED_REF_TEXT = (
    "شوفي يا حلوة هالكريم الجديد للبشرة، يخلي وجهك مثل القمر!"
)

FIXED_INSTRUCT = "female, young adult, high pitch"

# =========================================================
# Load Model
# =========================================================

model = OmniVoice.from_pretrained(
    "/home/riftuser/OmniVoice/exp_v1/omnivoice_finetune/checkpoint-5000",
    device_map="cuda:0",
    dtype=torch.float16,
)

# Prevent concurrent GPU inference crashes
generation_lock = asyncio.Lock()

# =========================================================
# Request Schema
# =========================================================

class SpeechRequest(BaseModel):

    model: str = "omnivoice"

    input: str

    speed: float = 1.1

    response_format: str = "pcm"

    # audio | sse
    stream_format: str = "audio"


# =========================================================
# Audio Helpers
# =========================================================

def float32_to_pcm16(audio: np.ndarray) -> bytes:

    audio = np.clip(audio, -1, 1)

    pcm16 = (audio * 32767).astype(np.int16)

    return pcm16.tobytes()


# =========================================================
# Generate Audio
# =========================================================

async def generate_audio(req: SpeechRequest) -> np.ndarray:

    async with generation_lock:

        def _generate():

            with torch.inference_mode():
                
                print("*" * 50)
                print("user text : " , req.input)
                print("*" * 50)

                audio = model.generate(
                    text=req.input,
                    ref_audio=FIXED_REF_AUDIO,
                    ref_text=FIXED_REF_TEXT,
                    instruct=FIXED_INSTRUCT,
                    speed=req.speed,
                    num_step = 30,
                    guidance_scale=2.0,
                    t_shift=0.1,
                    position_temperature=3,
                    layer_penalty_factor=5.0,
                )

            return audio[0]

        return await asyncio.to_thread(_generate)


# =========================================================
# Raw Audio Stream
# =========================================================

async def audio_stream_generator(
    req: SpeechRequest,
) -> AsyncGenerator[bytes, None]:

    audio = await generate_audio(req)

    if req.response_format == "pcm":

        pcm_bytes = float32_to_pcm16(audio)

        for i in range(0, len(pcm_bytes), CHUNK_SIZE):

            yield pcm_bytes[i:i + CHUNK_SIZE]

            await asyncio.sleep(0)

    elif req.response_format == "wav":

        buffer = io.BytesIO()

        sf.write(
            buffer,
            audio,
            SAMPLE_RATE,
            format="WAV",
        )

        buffer.seek(0)

        while True:

            chunk = buffer.read(4096)

            if not chunk:
                break

            yield chunk

            await asyncio.sleep(0)

    else:

        raise HTTPException(
            status_code=400,
            detail=f"Unsupported response_format: {req.response_format}"
        )


# =========================================================
# SSE Stream
# =========================================================

async def sse_stream_generator(
    req: SpeechRequest,
) -> AsyncGenerator[str, None]:

    start_time = time.time()

    audio = await generate_audio(req)

    generation_time = time.time() - start_time

    pcm_bytes = float32_to_pcm16(audio)

    for i in range(0, len(pcm_bytes), CHUNK_SIZE):

        chunk = pcm_bytes[i:i + CHUNK_SIZE]

        b64_chunk = base64.b64encode(chunk).decode("utf-8")

        event = {
            "type": "speech.audio.delta",
            "delta": b64_chunk,
        }

        yield f"data: {json.dumps(event)}\n\n"

        await asyncio.sleep(0)

    audio_duration = len(audio) / SAMPLE_RATE

    usage = {
        "input_tokens": len(req.input.split()),
        "output_tokens": int(audio_duration * 50),
    }

    done_event = {
        "type": "speech.audio.done",
        "usage": usage,
        "metrics": {
            "generation_time_sec": generation_time,
            "audio_duration_sec": audio_duration,
            "rtf": round(generation_time / audio_duration, 4),
        }
    }

    yield f"data: {json.dumps(done_event)}\n\n"

    yield "data: [DONE]\n\n"


# =========================================================
# OpenAI-Compatible Endpoint
# =========================================================

@app.post("/v1/audio/speech")
async def create_speech(req: SpeechRequest):

    if req.stream_format == "sse":

        return StreamingResponse(
            sse_stream_generator(req),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
            },
        )

    media_type = (
        "audio/pcm"
        if req.response_format == "pcm"
        else "audio/wav"
    )

    return StreamingResponse(
        audio_stream_generator(req),
        media_type=media_type,
    )


# =========================================================
# Health
# =========================================================

@app.get("/health")
async def health():

    return {
        "status": "ok",
        "sample_rate": SAMPLE_RATE,
        "voice": {
            "ref_audio": FIXED_REF_AUDIO,
            "instruct": FIXED_INSTRUCT,
        }
    }