Update app.py
Browse files
app.py
CHANGED
|
@@ -1,155 +1,148 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import asyncio
|
|
|
|
| 4 |
import torch
|
| 5 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 6 |
from huggingface_hub import login
|
| 7 |
from snac import SNAC
|
| 8 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
|
| 10 |
-
# —
|
| 11 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 12 |
if HF_TOKEN:
|
| 13 |
login(HF_TOKEN)
|
| 14 |
|
| 15 |
-
# —
|
| 16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
|
| 18 |
-
# —
|
| 19 |
app = FastAPI()
|
| 20 |
|
| 21 |
-
# —
|
| 22 |
@app.get("/")
|
| 23 |
async def read_root():
|
| 24 |
-
return {"message": "
|
| 25 |
|
| 26 |
-
# —
|
| 27 |
@app.on_event("startup")
|
| 28 |
-
async def
|
| 29 |
global tokenizer, model, snac
|
| 30 |
-
# SNAC
|
| 31 |
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device)
|
| 32 |
-
# TTS
|
| 33 |
model_name = "SebastianBodza/Kartoffel_Orpheus-3B_german_natural-v0.1"
|
| 34 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 35 |
model = AutoModelForCausalLM.from_pretrained(
|
| 36 |
model_name,
|
| 37 |
-
device_map="auto"
|
| 38 |
-
torch_dtype=torch.bfloat16 if device=="cuda" else None,
|
| 39 |
low_cpu_mem_usage=True
|
| 40 |
-
)
|
|
|
|
| 41 |
model.config.pad_token_id = model.config.eos_token_id
|
| 42 |
|
| 43 |
-
# —
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
def prepare_inputs(text: str, voice: str):
|
| 45 |
prompt = f"{voice}: {text}"
|
| 46 |
-
|
| 47 |
-
start = torch.tensor([[
|
| 48 |
-
end = torch.tensor([
|
| 49 |
-
ids = torch.cat([start,
|
| 50 |
-
mask = torch.ones_like(ids
|
| 51 |
return ids, mask
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
l1, l2, l3 = [], [], []
|
| 56 |
b = tokens
|
| 57 |
-
l1
|
| 58 |
-
l2
|
| 59 |
-
l3
|
| 60 |
-
l3.append(b[3]-3*4096)
|
| 61 |
-
l2.append(b[4]-4*4096)
|
| 62 |
-
l3.append(b[5]-5*4096)
|
| 63 |
-
l3.append(b[6]-6*4096)
|
| 64 |
codes = [
|
| 65 |
torch.tensor(l1, device=device).unsqueeze(0),
|
| 66 |
torch.tensor(l2, device=device).unsqueeze(0),
|
| 67 |
torch.tensor(l3, device=device).unsqueeze(0),
|
| 68 |
]
|
| 69 |
audio = snac.decode(codes).squeeze().cpu().numpy()
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
-
# —
|
| 73 |
@app.websocket("/ws/tts")
|
| 74 |
async def tts_ws(ws: WebSocket):
|
| 75 |
await ws.accept()
|
| 76 |
try:
|
| 77 |
-
# 1)
|
| 78 |
msg = await ws.receive_text()
|
| 79 |
req = json.loads(msg)
|
| 80 |
text = req.get("text", "")
|
| 81 |
voice = req.get("voice", "Jakob")
|
| 82 |
|
| 83 |
-
# 2)
|
| 84 |
input_ids, attention_mask = prepare_inputs(text, voice)
|
| 85 |
-
|
| 86 |
-
buffer_codes: list[int] = []
|
| 87 |
-
|
| 88 |
-
# 3) Chunk‑Generate‑Loop
|
| 89 |
-
chunk_size = 50
|
| 90 |
-
eos_id = model.config.eos_token_id
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
while True:
|
|
|
|
| 96 |
out = model.generate(
|
| 97 |
-
input_ids
|
| 98 |
attention_mask=attention_mask if past_kvs is None else None,
|
| 99 |
-
max_new_tokens=
|
| 100 |
do_sample=True,
|
| 101 |
temperature=0.7,
|
| 102 |
top_p=0.95,
|
| 103 |
repetition_penalty=1.1,
|
| 104 |
-
eos_token_id=
|
|
|
|
| 105 |
use_cache=True,
|
| 106 |
-
return_dict_in_generate=
|
| 107 |
-
|
| 108 |
-
past_key_values=past_kvs
|
| 109 |
)
|
| 110 |
-
#
|
| 111 |
-
past_kvs = out
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
for
|
| 121 |
-
if
|
| 122 |
-
|
| 123 |
-
new_tokens = [] # clean up
|
| 124 |
break
|
| 125 |
-
if
|
| 126 |
-
|
| 127 |
continue
|
| 128 |
-
#
|
| 129 |
-
|
| 130 |
-
#
|
| 131 |
-
if len(
|
| 132 |
-
block =
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
await ws.send_bytes(
|
| 136 |
-
|
| 137 |
-
# 6) Abbruch, wenn EOS im Chunk war
|
| 138 |
-
if eos_id in new_tokens:
|
| 139 |
break
|
| 140 |
|
| 141 |
-
|
| 142 |
-
input_ids = attention_mask = None
|
| 143 |
-
|
| 144 |
-
# 7) Zum Schluss sauber schließen
|
| 145 |
await ws.close()
|
|
|
|
| 146 |
except WebSocketDisconnect:
|
| 147 |
-
|
| 148 |
except Exception as e:
|
| 149 |
print("Error in /ws/tts:", e)
|
| 150 |
await ws.close(code=1011)
|
| 151 |
-
|
| 152 |
-
# — Main für lokalen Test —
|
| 153 |
-
if __name__ == "__main__":
|
| 154 |
-
import uvicorn
|
| 155 |
-
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import asyncio
|
| 4 |
+
|
| 5 |
import torch
|
| 6 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 7 |
from huggingface_hub import login
|
| 8 |
from snac import SNAC
|
| 9 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
|
| 11 |
+
# — ENV & AUTH —
|
| 12 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 13 |
if HF_TOKEN:
|
| 14 |
login(HF_TOKEN)
|
| 15 |
|
| 16 |
+
# — DEVICE SETUP —
|
| 17 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
|
| 19 |
+
# — FASTAPI INSTANCE —
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
+
# — HEALTHCHECK / ROOT —
|
| 23 |
@app.get("/")
|
| 24 |
async def read_root():
|
| 25 |
+
return {"message": "TTS WebSocket up and running!"}
|
| 26 |
|
| 27 |
+
# — LOAD MODELS ON STARTUP —
|
| 28 |
@app.on_event("startup")
|
| 29 |
+
async def startup_event():
|
| 30 |
global tokenizer, model, snac
|
| 31 |
+
# 1) SNAC vocoder
|
| 32 |
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device)
|
| 33 |
+
# 2) TTS model & tokenizer
|
| 34 |
model_name = "SebastianBodza/Kartoffel_Orpheus-3B_german_natural-v0.1"
|
| 35 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 36 |
model = AutoModelForCausalLM.from_pretrained(
|
| 37 |
model_name,
|
| 38 |
+
device_map="auto",
|
| 39 |
+
torch_dtype=torch.bfloat16 if device == "cuda" else None,
|
| 40 |
low_cpu_mem_usage=True
|
| 41 |
+
)
|
| 42 |
+
# make pad == eos
|
| 43 |
model.config.pad_token_id = model.config.eos_token_id
|
| 44 |
|
| 45 |
+
# — HELPERS —
|
| 46 |
+
START_TOKEN = 128259
|
| 47 |
+
END_TOKENS = [128009, 128260]
|
| 48 |
+
RESET_MARKER = 128257
|
| 49 |
+
EOS_TOKEN = 128258
|
| 50 |
+
AUDIO_TOKEN_OFFSET = 128266 # to subtract from token→audio code
|
| 51 |
+
|
| 52 |
def prepare_inputs(text: str, voice: str):
|
| 53 |
prompt = f"{voice}: {text}"
|
| 54 |
+
in_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
| 55 |
+
start = torch.tensor([[START_TOKEN]], dtype=torch.int64, device=device)
|
| 56 |
+
end = torch.tensor([END_TOKENS], dtype=torch.int64, device=device)
|
| 57 |
+
ids = torch.cat([start, in_ids, end], dim=1)
|
| 58 |
+
mask = torch.ones_like(ids)
|
| 59 |
return ids, mask
|
| 60 |
|
| 61 |
+
def decode_seven(tokens: list[int]) -> bytes:
|
| 62 |
+
"""Take exactly 7 audio‑codes, build SNAC input and decode to PCM16 bytes."""
|
|
|
|
| 63 |
b = tokens
|
| 64 |
+
l1 = [ b[0] ]
|
| 65 |
+
l2 = [ b[1] - 1*4096, b[4] - 4*4096 ]
|
| 66 |
+
l3 = [ b[2] - 2*4096, b[3] - 3*4096, b[5] - 5*4096, b[6] - 6*4096 ]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
codes = [
|
| 68 |
torch.tensor(l1, device=device).unsqueeze(0),
|
| 69 |
torch.tensor(l2, device=device).unsqueeze(0),
|
| 70 |
torch.tensor(l3, device=device).unsqueeze(0),
|
| 71 |
]
|
| 72 |
audio = snac.decode(codes).squeeze().cpu().numpy()
|
| 73 |
+
pcm16 = (audio * 32767).astype("int16").tobytes()
|
| 74 |
+
return pcm16
|
| 75 |
|
| 76 |
+
# — WEBSOCKET ENDPOINT —
|
| 77 |
@app.websocket("/ws/tts")
|
| 78 |
async def tts_ws(ws: WebSocket):
|
| 79 |
await ws.accept()
|
| 80 |
try:
|
| 81 |
+
# 1) receive JSON request
|
| 82 |
msg = await ws.receive_text()
|
| 83 |
req = json.loads(msg)
|
| 84 |
text = req.get("text", "")
|
| 85 |
voice = req.get("voice", "Jakob")
|
| 86 |
|
| 87 |
+
# 2) prepare prompt
|
| 88 |
input_ids, attention_mask = prepare_inputs(text, voice)
|
| 89 |
+
prompt_len = input_ids.size(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# 3) chunked generation setup
|
| 92 |
+
past_kvs = None
|
| 93 |
+
buffer: list[int] = []
|
| 94 |
+
generated_offset = 0
|
| 95 |
|
| 96 |
while True:
|
| 97 |
+
# 4) generate up to 50 new tokens at a time
|
| 98 |
out = model.generate(
|
| 99 |
+
input_ids= input_ids if past_kvs is None else None,
|
| 100 |
attention_mask=attention_mask if past_kvs is None else None,
|
| 101 |
+
max_new_tokens=50,
|
| 102 |
do_sample=True,
|
| 103 |
temperature=0.7,
|
| 104 |
top_p=0.95,
|
| 105 |
repetition_penalty=1.1,
|
| 106 |
+
eos_token_id=EOS_TOKEN,
|
| 107 |
+
pad_token_id=EOS_TOKEN,
|
| 108 |
use_cache=True,
|
| 109 |
+
return_dict_in_generate=False,
|
| 110 |
+
return_legacy_cache=True,
|
| 111 |
+
past_key_values=past_kvs,
|
| 112 |
)
|
| 113 |
+
# out is a tuple: (generated_ids, new_past_kvs)
|
| 114 |
+
gen_ids, past_kvs = out
|
| 115 |
+
|
| 116 |
+
# 5) extract only newly generated tokens
|
| 117 |
+
seq = gen_ids[0]
|
| 118 |
+
new_seq = seq[prompt_len + generated_offset :]
|
| 119 |
+
generated_offset += new_seq.size(0)
|
| 120 |
+
|
| 121 |
+
# 6) process each new token
|
| 122 |
+
stop = False
|
| 123 |
+
for t in new_seq.tolist():
|
| 124 |
+
if t == EOS_TOKEN:
|
| 125 |
+
stop = True
|
|
|
|
| 126 |
break
|
| 127 |
+
if t == RESET_MARKER:
|
| 128 |
+
buffer.clear()
|
| 129 |
continue
|
| 130 |
+
# convert to audio-code
|
| 131 |
+
buffer.append(t - AUDIO_TOKEN_OFFSET)
|
| 132 |
+
# once we have 7 codes, decode & stream
|
| 133 |
+
if len(buffer) >= 7:
|
| 134 |
+
block = buffer[:7]
|
| 135 |
+
buffer = buffer[7:]
|
| 136 |
+
pcm_bytes = decode_seven(block)
|
| 137 |
+
await ws.send_bytes(pcm_bytes)
|
| 138 |
+
if stop:
|
|
|
|
|
|
|
| 139 |
break
|
| 140 |
|
| 141 |
+
# 7) clean close
|
|
|
|
|
|
|
|
|
|
| 142 |
await ws.close()
|
| 143 |
+
|
| 144 |
except WebSocketDisconnect:
|
| 145 |
+
pass
|
| 146 |
except Exception as e:
|
| 147 |
print("Error in /ws/tts:", e)
|
| 148 |
await ws.close(code=1011)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|