Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,144 +1,138 @@
|
|
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 |
-
# —
|
12 |
-
HF_TOKEN = os.getenv("HF_TOKEN"
|
13 |
if HF_TOKEN:
|
14 |
login(HF_TOKEN)
|
15 |
|
16 |
-
# —
|
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": "
|
26 |
|
27 |
-
# —
|
|
|
|
|
|
|
|
|
|
|
28 |
@app.on_event("startup")
|
29 |
-
async def
|
30 |
-
global
|
31 |
-
# 1) SNAC
|
32 |
-
|
33 |
-
# 2) TTS
|
34 |
-
|
35 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
36 |
model = AutoModelForCausalLM.from_pretrained(
|
37 |
-
|
38 |
-
device_map="auto",
|
39 |
-
torch_dtype=torch.bfloat16 if device
|
40 |
low_cpu_mem_usage=True
|
41 |
-
)
|
42 |
-
# make pad == eos
|
43 |
model.config.pad_token_id = model.config.eos_token_id
|
44 |
|
45 |
-
# —
|
46 |
-
START_TOKEN
|
47 |
-
END_TOKENS
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
ids
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
codes = [
|
68 |
-
torch.tensor(
|
69 |
-
torch.tensor(
|
70 |
-
torch.tensor(
|
71 |
]
|
72 |
-
audio =
|
73 |
-
|
74 |
-
return pcm16
|
75 |
|
76 |
-
# —
|
77 |
@app.websocket("/ws/tts")
|
78 |
async def tts_ws(ws: WebSocket):
|
79 |
await ws.accept()
|
80 |
try:
|
81 |
-
# 1)
|
82 |
msg = await ws.receive_text()
|
83 |
req = json.loads(msg)
|
84 |
text = req.get("text", "")
|
85 |
-
voice = req.get("voice", "
|
86 |
-
|
87 |
-
# 2)
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
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:
|
@@ -146,3 +140,7 @@ async def tts_ws(ws: WebSocket):
|
|
146 |
except Exception as e:
|
147 |
print("Error in /ws/tts:", e)
|
148 |
await ws.close(code=1011)
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import json
|
|
|
|
|
3 |
import torch
|
4 |
+
import numpy as np
|
5 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
6 |
from huggingface_hub import login
|
|
|
7 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
8 |
+
from snac import SNAC
|
9 |
|
10 |
+
# — HF‑Token & Login (wenn gesetzt) —
|
11 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
12 |
if HF_TOKEN:
|
13 |
login(HF_TOKEN)
|
14 |
|
15 |
+
# — Device wählen —
|
16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
17 |
|
|
|
18 |
app = FastAPI()
|
19 |
|
|
|
20 |
@app.get("/")
|
21 |
async def read_root():
|
22 |
+
return {"message": "Hello, world!"}
|
23 |
|
24 |
+
# — Globale Modelle —
|
25 |
+
model = None
|
26 |
+
tokenizer = None
|
27 |
+
snac_model = None
|
28 |
+
|
29 |
+
# — Startup: SNAC & Orpheus laden —
|
30 |
@app.on_event("startup")
|
31 |
+
async def load_models():
|
32 |
+
global model, tokenizer, snac_model
|
33 |
+
# 1) SNAC
|
34 |
+
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device)
|
35 |
+
# 2) Orpheus‑TTS
|
36 |
+
REPO = "SebastianBodza/Kartoffel_Orpheus-3B_german_synthetic-v0.1"
|
37 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO)
|
38 |
model = AutoModelForCausalLM.from_pretrained(
|
39 |
+
REPO,
|
40 |
+
device_map="auto" if device=="cuda" else None,
|
41 |
+
torch_dtype=torch.bfloat16 if device=="cuda" else None,
|
42 |
low_cpu_mem_usage=True
|
43 |
+
).to(device)
|
|
|
44 |
model.config.pad_token_id = model.config.eos_token_id
|
45 |
|
46 |
+
# — Marker und Offsets aus der Vorlage —
|
47 |
+
START_TOKEN = 128259
|
48 |
+
END_TOKENS = [128009, 128260]
|
49 |
+
AUDIO_OFFSET = 128266
|
50 |
+
|
51 |
+
def process_single_prompt(prompt: str, voice: str) -> list[int]:
|
52 |
+
# Prompt zusammenbauen
|
53 |
+
if voice and voice != "in_prompt":
|
54 |
+
text = f"{voice}: {prompt}"
|
55 |
+
else:
|
56 |
+
text = prompt
|
57 |
+
# Tokenize + Marker
|
58 |
+
ids = tokenizer(text, return_tensors="pt").input_ids
|
59 |
+
start = torch.tensor([[START_TOKEN]], dtype=torch.int64)
|
60 |
+
end = torch.tensor([END_TOKENS], dtype=torch.int64)
|
61 |
+
input_ids = torch.cat([start, ids, end], dim=1).to(device)
|
62 |
+
attention_mask = torch.ones_like(input_ids)
|
63 |
+
|
64 |
+
# Generieren
|
65 |
+
gen = model.generate(
|
66 |
+
input_ids=input_ids,
|
67 |
+
attention_mask=attention_mask,
|
68 |
+
max_new_tokens=4000,
|
69 |
+
do_sample=True,
|
70 |
+
temperature=0.6,
|
71 |
+
top_p=0.95,
|
72 |
+
repetition_penalty=1.1,
|
73 |
+
eos_token_id=128258,
|
74 |
+
use_cache=True,
|
75 |
+
)
|
76 |
+
|
77 |
+
# letzten START_TOKEN finden & croppen
|
78 |
+
token_to_find = 128257
|
79 |
+
token_to_remove = 128258
|
80 |
+
idxs = (gen == token_to_find).nonzero(as_tuple=True)[1]
|
81 |
+
if idxs.numel() > 0:
|
82 |
+
cropped = gen[:, idxs[-1] + 1 :]
|
83 |
+
else:
|
84 |
+
cropped = gen
|
85 |
+
|
86 |
+
# Padding entfernen
|
87 |
+
row = cropped[0][cropped[0] != token_to_remove]
|
88 |
+
# Aus Länge ein Vielfaches von 7 machen
|
89 |
+
new_len = (row.size(0) // 7) * 7
|
90 |
+
trimmed = row[:new_len].tolist()
|
91 |
+
# Offset abziehen
|
92 |
+
return [t - AUDIO_OFFSET for t in trimmed]
|
93 |
+
|
94 |
+
def redistribute_codes(code_list: list[int]) -> np.ndarray:
|
95 |
+
# Die 7er‑Blöcke auf 3 Layer verteilen und dekodieren
|
96 |
+
layer1, layer2, layer3 = [], [], []
|
97 |
+
for i in range(len(code_list) // 7):
|
98 |
+
b = code_list[7*i : 7*i+7]
|
99 |
+
layer1.append(b[0])
|
100 |
+
layer2.append(b[1] - 4096)
|
101 |
+
layer3.append(b[2] - 2*4096)
|
102 |
+
layer3.append(b[3] - 3*4096)
|
103 |
+
layer2.append(b[4] - 4*4096)
|
104 |
+
layer3.append(b[5] - 5*4096)
|
105 |
+
layer3.append(b[6] - 6*4096)
|
106 |
+
|
107 |
codes = [
|
108 |
+
torch.tensor(layer1, device=device).unsqueeze(0),
|
109 |
+
torch.tensor(layer2, device=device).unsqueeze(0),
|
110 |
+
torch.tensor(layer3, device=device).unsqueeze(0),
|
111 |
]
|
112 |
+
audio = snac_model.decode(codes).squeeze().cpu().numpy()
|
113 |
+
return audio # float32 @24 kHz
|
|
|
114 |
|
115 |
+
# — WebSocket‑Endpoint für TTS —
|
116 |
@app.websocket("/ws/tts")
|
117 |
async def tts_ws(ws: WebSocket):
|
118 |
await ws.accept()
|
119 |
try:
|
120 |
+
# 1) Text + Voice empfangen
|
121 |
msg = await ws.receive_text()
|
122 |
req = json.loads(msg)
|
123 |
text = req.get("text", "")
|
124 |
+
voice = req.get("voice", "")
|
125 |
+
|
126 |
+
# 2) Prompt → Code‑Liste
|
127 |
+
with torch.no_grad():
|
128 |
+
codes = process_single_prompt(text, voice)
|
129 |
+
audio_np = redistribute_codes(codes)
|
130 |
+
|
131 |
+
# 3) In PCM16 konvertieren und senden
|
132 |
+
pcm16 = (audio_np * 32767).astype(np.int16).tobytes()
|
133 |
+
await ws.send_bytes(pcm16)
|
134 |
+
|
135 |
+
# 4) sauber schließen
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
await ws.close()
|
137 |
|
138 |
except WebSocketDisconnect:
|
|
|
140 |
except Exception as e:
|
141 |
print("Error in /ws/tts:", e)
|
142 |
await ws.close(code=1011)
|
143 |
+
|
144 |
+
if __name__ == "__main__":
|
145 |
+
import uvicorn
|
146 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|