|
|
|
import os |
|
import json |
|
import torch |
|
import asyncio |
|
import traceback |
|
|
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
|
from huggingface_hub import login |
|
from transformers import AutoTokenizer, AutoModelForCausalLM, LogitsProcessor, StoppingCriteria, StoppingCriteriaList |
|
|
|
from transformers.generation.streamers import BaseStreamer |
|
from snac import SNAC |
|
|
|
|
|
tok = None |
|
model = None |
|
snac = None |
|
masker = None |
|
stopping_criteria = None |
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
HF_TOKEN = os.getenv("HF_TOKEN") |
|
if HF_TOKEN: |
|
print("🔑 Logging in to Hugging Face Hub...") |
|
login(HF_TOKEN) |
|
|
|
|
|
|
|
|
|
REPO = "SebastianBodza/Kartoffel_Orpheus-3B_german_natural-v0.1" |
|
|
|
START_TOKEN = 128259 |
|
NEW_BLOCK = 128257 |
|
EOS_TOKEN = 128258 |
|
AUDIO_BASE = 128266 |
|
AUDIO_SPAN = 4096 * 7 |
|
|
|
AUDIO_IDS_CPU = torch.arange(AUDIO_BASE, AUDIO_BASE + AUDIO_SPAN) |
|
|
|
|
|
class AudioMask(LogitsProcessor): |
|
def __init__(self, audio_ids: torch.Tensor, new_block_token_id: int, eos_token_id: int): |
|
super().__init__() |
|
|
|
self.allow = torch.cat([ |
|
torch.tensor([new_block_token_id], device=audio_ids.device), |
|
audio_ids |
|
], dim=0) |
|
self.eos = torch.tensor([eos_token_id], device=audio_ids.device) |
|
self.allow_with_eos = torch.cat([self.allow, self.eos], dim=0) |
|
self.sent_blocks = 0 |
|
|
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: |
|
|
|
current_allow = self.allow_with_eos if self.sent_blocks > 0 else self.allow |
|
|
|
|
|
mask = torch.full_like(scores, float("-inf")) |
|
|
|
mask[:, current_allow] = 0 |
|
|
|
return scores + mask |
|
|
|
def reset(self): |
|
"""Resets the state for a new generation request.""" |
|
self.sent_blocks = 0 |
|
|
|
|
|
|
|
class EosStoppingCriteria(StoppingCriteria): |
|
def __init__(self, eos_token_id: int): |
|
self.eos_token_id = eos_token_id |
|
|
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: |
|
|
|
if input_ids.shape[1] > 0 and input_ids[:, -1] == self.eos_token_id: |
|
|
|
return True |
|
return False |
|
|
|
|
|
class AudioStreamer(BaseStreamer): |
|
def __init__(self, ws: WebSocket, snac_decoder: SNAC, audio_mask: AudioMask, loop: asyncio.AbstractEventLoop): |
|
self.ws = ws |
|
self.snac = snac_decoder |
|
self.masker = audio_mask |
|
self.loop = loop |
|
self.device = snac_decoder.device |
|
self.buf: list[int] = [] |
|
self.tasks = set() |
|
|
|
def _decode_block(self, block7: list[int]) -> bytes: |
|
""" |
|
Decodes a block of 7 audio token values (AUDIO_BASE subtracted) into audio bytes. |
|
NOTE: The mapping from the 7 tokens to the 3 SNAC codebooks (l1, l2, l3) |
|
is based on a common interleaving hypothesis. Verify if model docs specify otherwise. |
|
""" |
|
if len(block7) != 7: |
|
print(f"Streamer Warning: _decode_block received {len(block7)} tokens, expected 7. Skipping.") |
|
return b"" |
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
l1 = [block7[0], block7[3], block7[6]] |
|
l2 = [block7[1], block7[4]] |
|
l3 = [block7[2], block7[5]] |
|
except IndexError: |
|
print(f"Streamer Error: Index out of bounds during token mapping. Block: {block7}") |
|
return b"" |
|
|
|
|
|
codes_l1 = torch.tensor(l1, dtype=torch.long, device=self.device).unsqueeze(0) |
|
codes_l2 = torch.tensor(l2, dtype=torch.long, device=self.device).unsqueeze(0) |
|
codes_l3 = torch.tensor(l3, dtype=torch.long, device=self.device).unsqueeze(0) |
|
codes = [codes_l1, codes_l2, codes_l3] |
|
|
|
|
|
with torch.no_grad(): |
|
audio = self.snac.decode(codes)[0] |
|
|
|
|
|
audio_np = audio.squeeze().detach().cpu().numpy() |
|
|
|
|
|
audio_bytes = (audio_np * 32767).astype("int16").tobytes() |
|
return audio_bytes |
|
|
|
async def _send_audio_bytes(self, data: bytes): |
|
"""Coroutine to send bytes over WebSocket.""" |
|
if not data: |
|
return |
|
try: |
|
await self.ws.send_bytes(data) |
|
|
|
except WebSocketDisconnect: |
|
print("Streamer: WebSocket disconnected during send.") |
|
except Exception as e: |
|
print(f"Streamer: Error sending bytes: {e}") |
|
|
|
def put(self, value: torch.LongTensor): |
|
""" |
|
Receives new token IDs (Tensor) from generate() (runs in worker thread). |
|
Processes tokens, decodes full blocks, and schedules sending via run_coroutine_threadsafe. |
|
""" |
|
|
|
if value.numel() == 0: |
|
return |
|
new_token_ids = value.squeeze().tolist() |
|
if isinstance(new_token_ids, int): |
|
new_token_ids = [new_token_ids] |
|
|
|
for t in new_token_ids: |
|
if t == EOS_TOKEN: |
|
|
|
|
|
break |
|
|
|
if t == NEW_BLOCK: |
|
|
|
|
|
self.buf.clear() |
|
continue |
|
|
|
|
|
if AUDIO_BASE <= t < AUDIO_BASE + AUDIO_SPAN: |
|
self.buf.append(t - AUDIO_BASE) |
|
else: |
|
|
|
|
|
pass |
|
|
|
|
|
if len(self.buf) == 7: |
|
audio_bytes = self._decode_block(self.buf) |
|
self.buf.clear() |
|
|
|
if audio_bytes: |
|
|
|
future = asyncio.run_coroutine_threadsafe(self._send_audio_bytes(audio_bytes), self.loop) |
|
self.tasks.add(future) |
|
|
|
future.add_done_callback(self.tasks.discard) |
|
|
|
|
|
|
|
if self.masker.sent_blocks == 0: |
|
|
|
self.masker.sent_blocks = 1 |
|
|
|
|
|
|
|
def end(self): |
|
"""Called by generate() when generation finishes.""" |
|
|
|
if len(self.buf) > 0: |
|
print(f"Streamer: End of generation with incomplete block ({len(self.buf)} tokens). Discarding.") |
|
self.buf.clear() |
|
|
|
|
|
|
|
|
|
|
|
|
|
pass |
|
|
|
|
|
app = FastAPI() |
|
|
|
@app.on_event("startup") |
|
async def load_models_startup(): |
|
global tok, model, snac, masker, stopping_criteria, device, AUDIO_IDS_CPU |
|
|
|
print(f"🚀 Starting up on device: {device}") |
|
print("⏳ Lade Modelle …", flush=True) |
|
|
|
tok = AutoTokenizer.from_pretrained(REPO) |
|
print("Tokenizer loaded.") |
|
|
|
|
|
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device) |
|
print(f"SNAC loaded to {snac.device}.") |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
REPO, |
|
device_map={"": 0} if device == "cuda" else None, |
|
torch_dtype=torch.bfloat16 if device == "cuda" and torch.cuda.is_bf16_supported() else torch.float32, |
|
low_cpu_mem_usage=True, |
|
) |
|
model.config.pad_token_id = model.config.eos_token_id |
|
print(f"Model loaded to {model.device}.") |
|
|
|
|
|
model.eval() |
|
|
|
|
|
audio_ids_device = AUDIO_IDS_CPU.to(device) |
|
masker = AudioMask(audio_ids_device, NEW_BLOCK, EOS_TOKEN) |
|
print("AudioMask initialized.") |
|
|
|
|
|
|
|
stopping_criteria = StoppingCriteriaList([EosStoppingCriteria(EOS_TOKEN)]) |
|
print("StoppingCriteria initialized.") |
|
|
|
print("✅ Modelle geladen und bereit!", flush=True) |
|
|
|
@app.get("/") |
|
def hello(): |
|
return {"status": "ok", "message": "TTS Service is running"} |
|
|
|
|
|
def build_prompt(text: str, voice: str) -> tuple[torch.Tensor, torch.Tensor]: |
|
"""Builds the input_ids and attention_mask for the model.""" |
|
|
|
prompt_text = f"{voice}: {text}" |
|
prompt_ids = tok(prompt_text, return_tensors="pt").input_ids.to(device) |
|
|
|
|
|
input_ids = torch.cat([ |
|
torch.tensor([[START_TOKEN]], device=device), |
|
prompt_ids, |
|
torch.tensor([[NEW_BLOCK]], device=device) |
|
], dim=1) |
|
|
|
|
|
attention_mask = torch.ones_like(input_ids) |
|
return input_ids, attention_mask |
|
|
|
|
|
@app.websocket("/ws/tts") |
|
async def tts(ws: WebSocket): |
|
await ws.accept() |
|
print(" клиент подключился") |
|
streamer = None |
|
main_loop = asyncio.get_running_loop() |
|
|
|
try: |
|
|
|
req_text = await ws.receive_text() |
|
print(f"Received request: {req_text}") |
|
req = json.loads(req_text) |
|
text = req.get("text", "Hallo Welt, wie geht es dir heute?") |
|
voice = req.get("voice", "Jakob") |
|
|
|
if not text: |
|
await ws.close(code=1003, reason="Text cannot be empty") |
|
return |
|
|
|
print(f"Generating audio for: '{text}' with voice '{voice}'") |
|
|
|
|
|
ids, attn = build_prompt(text, voice) |
|
|
|
|
|
masker.reset() |
|
|
|
|
|
streamer = AudioStreamer(ws, snac, masker, main_loop) |
|
|
|
|
|
|
|
print("Starting generation...") |
|
await asyncio.to_thread( |
|
model.generate, |
|
input_ids=ids, |
|
attention_mask=attn, |
|
max_new_tokens=1500, |
|
logits_processor=[masker], |
|
stopping_criteria=stopping_criteria, |
|
do_sample=False, |
|
|
|
use_cache=True, |
|
streamer=streamer |
|
|
|
) |
|
print("Generation finished.") |
|
|
|
except WebSocketDisconnect: |
|
print("Client disconnected.") |
|
except json.JSONDecodeError: |
|
print("❌ Invalid JSON received.") |
|
await ws.close(code=1003, reason="Invalid JSON format") |
|
except Exception as e: |
|
error_details = traceback.format_exc() |
|
print(f"❌ WS‑Error: {e}\n{error_details}", flush=True) |
|
|
|
error_payload = json.dumps({"error": str(e)}) |
|
try: |
|
if ws.client_state.name == "CONNECTED": |
|
await ws.send_text(error_payload) |
|
except Exception: |
|
pass |
|
|
|
if ws.client_state.name == "CONNECTED": |
|
await ws.close(code=1011) |
|
finally: |
|
|
|
if streamer: |
|
try: |
|
streamer.end() |
|
except Exception as e_end: |
|
print(f"Error during streamer.end(): {e_end}") |
|
|
|
|
|
print("Closing connection.") |
|
if ws.client_state.name != "DISCONNECTED": |
|
try: |
|
await ws.close(code=1000) |
|
except RuntimeError as e_close: |
|
|
|
print(f"Runtime error closing websocket: {e_close}") |
|
except Exception as e_close_final: |
|
print(f"Error closing websocket: {e_close_final}") |
|
print("Connection closed.") |
|
|
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
print("Starting Uvicorn server...") |
|
|
|
uvicorn.run("app:app", host="0.0.0.0", port=7860, log_level="info") |