|
import os |
|
import json |
|
import asyncio |
|
import torch |
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
|
from huggingface_hub import login |
|
from snac import SNAC |
|
from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
|
|
|
HF_TOKEN = os.getenv("HF_TOKEN") |
|
if HF_TOKEN: |
|
login(HF_TOKEN) |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
@app.get("/") |
|
async def read_root(): |
|
return {"message": "Hello, world!"} |
|
|
|
|
|
@app.on_event("startup") |
|
async def load_models(): |
|
global tokenizer, model, snac |
|
|
|
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device) |
|
|
|
model_name = "SebastianBodza/Kartoffel_Orpheus-3B_german_natural-v0.1" |
|
tokenizer = AutoTokenizer.from_pretrained(model_name) |
|
model = AutoModelForCausalLM.from_pretrained( |
|
model_name, |
|
device_map="auto" if device=="cuda" else None, |
|
torch_dtype=torch.bfloat16 if device=="cuda" else None, |
|
low_cpu_mem_usage=True |
|
).to(device) |
|
model.config.pad_token_id = model.config.eos_token_id |
|
|
|
|
|
def prepare_inputs(text: str, voice: str): |
|
prompt = f"{voice}: {text}" |
|
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device) |
|
start = torch.tensor([[128259]], dtype=torch.int64, device=device) |
|
end = torch.tensor([[128009, 128260]], dtype=torch.int64, device=device) |
|
ids = torch.cat([start, input_ids, end], dim=1) |
|
mask = torch.ones_like(ids, device=device) |
|
return ids, mask |
|
|
|
|
|
def decode_block(tokens: list[int]) -> bytes: |
|
l1, l2, l3 = [], [], [] |
|
b = tokens |
|
l1.append(b[0]) |
|
l2.append(b[1]-4096) |
|
l3.append(b[2]-2*4096) |
|
l3.append(b[3]-3*4096) |
|
l2.append(b[4]-4*4096) |
|
l3.append(b[5]-5*4096) |
|
l3.append(b[6]-6*4096) |
|
codes = [ |
|
torch.tensor(l1, device=device).unsqueeze(0), |
|
torch.tensor(l2, device=device).unsqueeze(0), |
|
torch.tensor(l3, device=device).unsqueeze(0), |
|
] |
|
audio = snac.decode(codes).squeeze().cpu().numpy() |
|
return (audio * 32767).astype("int16").tobytes() |
|
|
|
|
|
@app.websocket("/ws/tts") |
|
async def tts_ws(ws: WebSocket): |
|
await ws.accept() |
|
try: |
|
|
|
msg = await ws.receive_text() |
|
req = json.loads(msg) |
|
text = req.get("text", "") |
|
voice = req.get("voice", "Jakob") |
|
|
|
|
|
input_ids, attention_mask = prepare_inputs(text, voice) |
|
past_kvs = None |
|
buffer_codes: list[int] = [] |
|
|
|
|
|
chunk_size = 50 |
|
eos_id = model.config.eos_token_id |
|
|
|
|
|
prev_len = 0 |
|
|
|
while True: |
|
out = model.generate( |
|
input_ids = input_ids if past_kvs is None else None, |
|
attention_mask=attention_mask if past_kvs is None else None, |
|
max_new_tokens=chunk_size, |
|
do_sample=True, |
|
temperature=0.7, |
|
top_p=0.95, |
|
repetition_penalty=1.1, |
|
eos_token_id=eos_id, |
|
use_cache=True, |
|
return_dict_in_generate=True, |
|
output_scores=False, |
|
past_key_values=past_kvs |
|
) |
|
|
|
past_kvs = out.past_key_values |
|
seqs = out.sequences |
|
total_len = seqs.shape[1] |
|
|
|
|
|
new_tokens = seqs[0, prev_len:total_len].tolist() |
|
prev_len = total_len |
|
|
|
|
|
for tok in new_tokens: |
|
if tok == eos_id: |
|
|
|
new_tokens = [] |
|
break |
|
if tok == 128257: |
|
buffer_codes.clear() |
|
continue |
|
|
|
buffer_codes.append(tok - 128266) |
|
|
|
if len(buffer_codes) >= 7: |
|
block = buffer_codes[:7] |
|
buffer_codes = buffer_codes[7:] |
|
pcm = decode_block(block) |
|
await ws.send_bytes(pcm) |
|
|
|
|
|
if eos_id in new_tokens: |
|
break |
|
|
|
|
|
input_ids = attention_mask = None |
|
|
|
|
|
await ws.close() |
|
except WebSocketDisconnect: |
|
return |
|
except Exception as e: |
|
print("Error in /ws/tts:", e) |
|
await ws.close(code=1011) |
|
|
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run("app:app", host="0.0.0.0", port=7860) |
|
|