Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,51 +12,55 @@ 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 |
# — FastAPI instanziieren —
|
| 19 |
app = FastAPI()
|
| 20 |
|
| 21 |
-
# —
|
| 22 |
@app.get("/")
|
| 23 |
async def read_root():
|
| 24 |
-
return {"message": "
|
| 25 |
|
| 26 |
# — Modelle bei Startup laden —
|
| 27 |
@app.on_event("startup")
|
| 28 |
async def load_models():
|
| 29 |
global tokenizer, model, snac
|
|
|
|
| 30 |
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device)
|
| 31 |
-
|
| 32 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
|
|
|
| 33 |
model = AutoModelForCausalLM.from_pretrained(
|
| 34 |
-
|
| 35 |
device_map="auto",
|
| 36 |
-
torch_dtype=torch.bfloat16 if device
|
| 37 |
low_cpu_mem_usage=True
|
| 38 |
)
|
| 39 |
-
|
| 40 |
-
model.config.pad_token_id = model.config.eos_token_id
|
| 41 |
-
|
| 42 |
-
# — Hilfsfunktionen —
|
| 43 |
-
START_TOKEN = 128259
|
| 44 |
-
END_TOKENS = [128009, 128260]
|
| 45 |
-
RESET_TOKEN = 128257
|
| 46 |
-
AUDIO_OFFSET = 128266
|
| 47 |
-
EOS_TOKEN = model.config.eos_token_id if 'model' in globals() else 128258
|
| 48 |
|
|
|
|
| 49 |
def prepare_inputs(text: str, voice: str):
|
| 50 |
-
prompt
|
| 51 |
-
|
| 52 |
-
start
|
| 53 |
-
end
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
return
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
l1, l2, l3 = [], [], []
|
| 61 |
b = block
|
| 62 |
l1.append(b[0])
|
|
@@ -72,68 +76,76 @@ def decode_block(block: list[int]):
|
|
| 72 |
torch.tensor(l3, device=device).unsqueeze(0),
|
| 73 |
]
|
| 74 |
audio = snac.decode(codes).squeeze().cpu().numpy()
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
# — WebSocket‑Endpoint für TTS Streaming —
|
| 78 |
@app.websocket("/ws/tts")
|
| 79 |
async def tts_ws(ws: WebSocket):
|
| 80 |
await ws.accept()
|
| 81 |
try:
|
| 82 |
-
|
| 83 |
-
req
|
| 84 |
text = req.get("text", "")
|
| 85 |
voice = req.get("voice", "Jakob")
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
collected = []
|
| 90 |
-
|
| 91 |
-
# Token‑für‑Token mit eigener Sampling‑Schleife
|
| 92 |
-
while True:
|
| 93 |
-
out = model(
|
| 94 |
-
input_ids=input_ids if past_kvs is None else None,
|
| 95 |
-
attention_mask=attention_mask if past_kvs is None else None,
|
| 96 |
-
past_key_values=past_kvs,
|
| 97 |
-
use_cache=True,
|
| 98 |
-
)
|
| 99 |
-
logits = out.logits[:, -1, :]
|
| 100 |
-
past_kvs = out.past_key_values
|
| 101 |
-
|
| 102 |
-
# Sampling
|
| 103 |
-
probs = torch.softmax(logits, dim=-1)
|
| 104 |
-
nxt = torch.multinomial(probs, num_samples=1).item()
|
| 105 |
-
|
| 106 |
-
# EOS → fertig
|
| 107 |
-
if nxt == EOS_TOKEN:
|
| 108 |
-
break
|
| 109 |
-
# RESET → alte Sammlung verwerfen
|
| 110 |
-
if nxt == RESET_TOKEN:
|
| 111 |
-
collected = []
|
| 112 |
-
# und input_ids für nächsten Durchlauf auf None setzen
|
| 113 |
-
input_ids = None
|
| 114 |
-
attention_mask = None
|
| 115 |
-
continue
|
| 116 |
|
| 117 |
-
# Audio‑Code abziehen & sammeln
|
| 118 |
-
collected.append(nxt - AUDIO_OFFSET)
|
| 119 |
-
# jede 7 Codes → dekodieren & streamen
|
| 120 |
-
if len(collected) == 7:
|
| 121 |
-
pcm = decode_block(collected)
|
| 122 |
-
collected = []
|
| 123 |
-
await ws.send_bytes(pcm)
|
| 124 |
-
|
| 125 |
-
# nur beim allerersten Schritt mit IDs arbeiten
|
| 126 |
-
input_ids = None
|
| 127 |
-
attention_mask = None
|
| 128 |
-
|
| 129 |
-
# Stream sauber beenden
|
| 130 |
await ws.close()
|
| 131 |
-
|
| 132 |
except WebSocketDisconnect:
|
| 133 |
-
# Client hat Disconnect gemacht → nichts tun
|
| 134 |
pass
|
| 135 |
-
|
| 136 |
except Exception as e:
|
| 137 |
-
# auf Fehler 1011 senden
|
| 138 |
print("Error in /ws/tts:", e)
|
| 139 |
await ws.close(code=1011)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
if HF_TOKEN:
|
| 13 |
login(HF_TOKEN)
|
| 14 |
|
| 15 |
+
# — Gerät wählen —
|
| 16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
|
| 18 |
+
# — Modell‑Parameter —
|
| 19 |
+
MODEL_NAME = "SebastianBodza/Kartoffel_Orpheus-3B_german_natural-v0.1"
|
| 20 |
+
START_MARKER = 128259 # <|startoftranscript|>
|
| 21 |
+
RESTART_MARKER = 128257 # <|startoftranscript_again|>
|
| 22 |
+
EOS_TOKEN = 128258 # <|endoftranscript|>
|
| 23 |
+
AUDIO_TOKEN_OFFSET = 128266 # Offset zum Zurückrechnen
|
| 24 |
+
BLOCK_TOKENS = 7 # SNAC erwartet 7 Audio‑Tokens pro Block
|
| 25 |
+
CHUNK_TOKENS = 50 # Anzahl neuer Tokens pro Generate‑Runde
|
| 26 |
+
|
| 27 |
# — FastAPI instanziieren —
|
| 28 |
app = FastAPI()
|
| 29 |
|
| 30 |
+
# — Damit GET / nicht 404 wirft —
|
| 31 |
@app.get("/")
|
| 32 |
async def read_root():
|
| 33 |
+
return {"message": "Orpheus TTS Server ist live 🎙️"}
|
| 34 |
|
| 35 |
# — Modelle bei Startup laden —
|
| 36 |
@app.on_event("startup")
|
| 37 |
async def load_models():
|
| 38 |
global tokenizer, model, snac
|
| 39 |
+
# SNAC laden
|
| 40 |
snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").to(device)
|
| 41 |
+
# Tokenizer
|
| 42 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 43 |
+
# TTS‑LM
|
| 44 |
model = AutoModelForCausalLM.from_pretrained(
|
| 45 |
+
MODEL_NAME,
|
| 46 |
device_map="auto",
|
| 47 |
+
torch_dtype=torch.bfloat16 if device=="cuda" else None,
|
| 48 |
low_cpu_mem_usage=True
|
| 49 |
)
|
| 50 |
+
model.config.pad_token_id = EOS_TOKEN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
# — Eingabe aufbereiten —
|
| 53 |
def prepare_inputs(text: str, voice: str):
|
| 54 |
+
prompt = f"{voice}: {text}"
|
| 55 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
| 56 |
+
start = torch.tensor([[START_MARKER]], device=device)
|
| 57 |
+
end = torch.tensor([[128009, EOS_TOKEN]], device=device)
|
| 58 |
+
ids = torch.cat([start, input_ids, end], dim=1)
|
| 59 |
+
attn_mask = torch.ones_like(ids)
|
| 60 |
+
return ids, attn_mask
|
| 61 |
+
|
| 62 |
+
# — Aus 7 Audio‑Tokens ein PCM‑Block erzeugen —
|
| 63 |
+
def decode_block(block: list[int]) -> bytes:
|
| 64 |
l1, l2, l3 = [], [], []
|
| 65 |
b = block
|
| 66 |
l1.append(b[0])
|
|
|
|
| 76 |
torch.tensor(l3, device=device).unsqueeze(0),
|
| 77 |
]
|
| 78 |
audio = snac.decode(codes).squeeze().cpu().numpy()
|
| 79 |
+
pcm16 = (audio * 32767).astype("int16").tobytes()
|
| 80 |
+
return pcm16
|
| 81 |
+
|
| 82 |
+
# — Generator: kleine Chunks token‑weise erzeugen und block‑weise dekodieren —
|
| 83 |
+
async def generate_and_stream(ws: WebSocket, ids, attn_mask):
|
| 84 |
+
buffer: list[int] = []
|
| 85 |
+
past_kvs = None
|
| 86 |
+
|
| 87 |
+
while True:
|
| 88 |
+
# wir rufen model.generate in Häppchen auf
|
| 89 |
+
outputs = model.generate(
|
| 90 |
+
input_ids = ids if past_kvs is None else None,
|
| 91 |
+
attention_mask = attn_mask if past_kvs is None else None,
|
| 92 |
+
past_key_values= past_kvs,
|
| 93 |
+
use_cache = True,
|
| 94 |
+
max_new_tokens = CHUNK_TOKENS,
|
| 95 |
+
do_sample = True,
|
| 96 |
+
temperature = 0.7,
|
| 97 |
+
top_p = 0.95,
|
| 98 |
+
repetition_penalty = 1.1,
|
| 99 |
+
eos_token_id = EOS_TOKEN,
|
| 100 |
+
pad_token_id = EOS_TOKEN,
|
| 101 |
+
return_dict_in_generate = True,
|
| 102 |
+
output_scores = False,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# update past_kvs
|
| 106 |
+
past_kvs = outputs.past_key_values
|
| 107 |
+
|
| 108 |
+
# erhalte nur die gerade neu generierten Token
|
| 109 |
+
seq = outputs.sequences[0]
|
| 110 |
+
new_tokens = seq[-CHUNK_TOKENS:].tolist() if past_kvs is not None else seq[ids.shape[-1]:].tolist()
|
| 111 |
+
|
| 112 |
+
for tok in new_tokens:
|
| 113 |
+
# Neustart bei erneutem START‑Marker
|
| 114 |
+
if tok == RESTART_MARKER:
|
| 115 |
+
buffer = []
|
| 116 |
+
continue
|
| 117 |
+
# Ende
|
| 118 |
+
if tok == EOS_TOKEN:
|
| 119 |
+
return
|
| 120 |
+
# Audio‑Code berechnen
|
| 121 |
+
buffer.append(tok - AUDIO_TOKEN_OFFSET)
|
| 122 |
+
# sobald 7 Audio‑Tokens, dekodieren und streamen
|
| 123 |
+
if len(buffer) >= BLOCK_TOKENS:
|
| 124 |
+
block = buffer[:BLOCK_TOKENS]
|
| 125 |
+
buffer = buffer[BLOCK_TOKENS:]
|
| 126 |
+
pcm = decode_block(block)
|
| 127 |
+
await ws.send_bytes(pcm)
|
| 128 |
|
| 129 |
# — WebSocket‑Endpoint für TTS Streaming —
|
| 130 |
@app.websocket("/ws/tts")
|
| 131 |
async def tts_ws(ws: WebSocket):
|
| 132 |
await ws.accept()
|
| 133 |
try:
|
| 134 |
+
data = await ws.receive_text()
|
| 135 |
+
req = json.loads(data)
|
| 136 |
text = req.get("text", "")
|
| 137 |
voice = req.get("voice", "Jakob")
|
| 138 |
|
| 139 |
+
ids, attn_mask = prepare_inputs(text, voice)
|
| 140 |
+
await generate_and_stream(ws, ids, attn_mask)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
await ws.close()
|
|
|
|
| 143 |
except WebSocketDisconnect:
|
|
|
|
| 144 |
pass
|
|
|
|
| 145 |
except Exception as e:
|
|
|
|
| 146 |
print("Error in /ws/tts:", e)
|
| 147 |
await ws.close(code=1011)
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
import uvicorn
|
| 151 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|