Tara-Fundament: LLM-getriebener Lehrer + lokale Orpheus-Stimme
- lehrer_persona.py: Tara-Charakter (Englisch) als System-Prompt + zahl-freie Lage-Uebersetzung (grund_lesen -> qualitatives Englisch, nie eine Zahl); denken statt vorlesen, emotional, keine Geld-/Moral-Ratschlaege - lehrer_llm.py: generiert jede Zeile live ueber sprachmodell (keine statischen Bausteine); harter Filter (Ziffer/Prozent/Odds/Geld-Moral/zu lang -> still); Ausfall = still, kein Fallback - orpheus_stimme.py: lokale Orpheus-TTS (Ollama + SNAC-Decoder) mit eigener Klang-Signatur (ffmpeg); als Sprecher-Provider 'orpheus-lokal' in sprecher.py + anbieter.py - Specs: persona, llm, orpheus_stimme, sprecher, anbieter alle gruen
This commit is contained in:
@@ -46,6 +46,11 @@ KATALOG = {
|
||||
"pflicht": ["adresse"], "vorgaben": {"stimmname": "alloy", "modell": "tts-1"},
|
||||
"hinweis": "Jeder Sprachdienst im OpenAI-Format, etwa Kokoro auf diesem Mac: http://localhost:8880/v1 "
|
||||
"(Stimme af_bella, Modell kokoro). Schlüssel nur, wenn der Dienst einen verlangt."},
|
||||
{"id": "orpheus-lokal", "name": "Orpheus (lokal)", "felder": ["modell", "stimmname", "adresse"], "pflicht": [],
|
||||
"vorgaben": {"modell": "hf.co/unsloth/orpheus-3b-0.1-ft-GGUF:Q8_0", "stimmname": "tara", "adresse": "http://127.0.0.1:11434"},
|
||||
"hinweis": "Läuft ganz auf diesem Mac über Ollama (Modell hf.co/unsloth/orpheus-3b-0.1-ft-GGUF:Q8_0) mit "
|
||||
"eigener Klang-Signatur. Braucht Ollama sowie torch, snac und ffmpeg. Englische Stimmen: tara, "
|
||||
"leah, leo, dan, mia, zac, zoe."},
|
||||
],
|
||||
"umschreiber": [
|
||||
{"id": "aus", "name": "Aus", "felder": [], "pflicht": [], "vorgaben": {},
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""The LLM teacher: Tara speaks each line LIVE from the game situation - no static text blocks.
|
||||
|
||||
Owner 9.11.2026: "der lehrer muss LLM driven sein, ich will keine statischen textbausteine" + "gib ihr
|
||||
auch einen charakter". Builds a number-free situation (betrieb/lehrer_persona.lage_*) and asks the
|
||||
language model chosen in the Cockpit (betrieb/sprachmodell) to speak ONE line in Tara's character.
|
||||
Event-driven, called from betrieb/regie in the teacher daemon - never on the game's hot path. A failing
|
||||
or slow model, or a line that breaks the rules (a digit, a forbidden word, too long), means SILENCE -
|
||||
no template fallback (the owner banned static blocks). Spec: tests/lehrer_llm_spec.py.
|
||||
"""
|
||||
import re
|
||||
|
||||
import lehrer_persona as persona
|
||||
import sprachmodell
|
||||
|
||||
ZIFFER = re.compile(r"\d") # keine Ziffern in der gesprochenen Zeile (keine sichtbaren Zahlen/Mathe)
|
||||
VERBOTEN = re.compile(r"%|\bpercent\b|\bodds\b|responsib|\bgambl|addict|play money", re.I)
|
||||
HOECHSTENS_WOERTER = 24 # eine Zeile, kein Absatz
|
||||
|
||||
|
||||
def saeubern(zeile):
|
||||
"""Die gesprochene Zeile - oder "" (leer, mit Ziffer, mit verbotenem Wort/Rat, oder zu lang)."""
|
||||
z = (zeile or "").strip().split("\n", 1)[0].strip() # erst die erste Zeile
|
||||
z = z.strip('"').strip("*").strip() # dann Anfuehrungszeichen/Markdown weg
|
||||
if not z or ZIFFER.search(z) or VERBOTEN.search(z) or len(z.split()) > HOECHSTENS_WOERTER:
|
||||
return ""
|
||||
return z
|
||||
|
||||
|
||||
def kommentar(lage, wahl, senden=None):
|
||||
"""Lage-Text -> Tara's gesprochene Zeile (oder "" bei Ausfall/Regelverstoss). Rein ueber sprachmodell."""
|
||||
if not lage:
|
||||
return ""
|
||||
a = sprachmodell.fragen(wahl if isinstance(wahl, dict) else {}, persona.anweisung(), lage, senden)
|
||||
if a.fehlt or a.ausfall:
|
||||
return ""
|
||||
return saeubern(a.text)
|
||||
|
||||
|
||||
# Brücken von einem Strom-Ereignis zur Lage (die Regie ruft diese).
|
||||
def zug(e, l, wahl, senden=None):
|
||||
return kommentar(persona.lage_zug(e, l), wahl, senden)
|
||||
|
||||
|
||||
def ergebnis(netto_bb, showdown, entscheidung_gut, wahl, senden=None):
|
||||
return kommentar(persona.lage_ergebnis(netto_bb, showdown, entscheidung_gut), wahl, senden)
|
||||
|
||||
|
||||
def gegner(sitz, schluessel, notiz, wahl, senden=None):
|
||||
return kommentar(persona.lage_gegner(sitz, schluessel, notiz), wahl, senden)
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Tara - the character, and the number-free SITUATION fed to the language model.
|
||||
|
||||
Owner 9.11.2026: the teacher must be LLM-driven, no static text blocks, with a real character; English;
|
||||
think out loud, never read what's on screen; no math, no numbers; emotional on win/loss with a verdict;
|
||||
no financial or moral advice. The persona lives here as the system instruction; `lage_*` turn a decision
|
||||
(betrieb/grund_lesen.Lesart) or a result into a short English situation WITHOUT any number - the model
|
||||
speaks the line, not us. Spec: tests/lehrer_persona_spec.py.
|
||||
"""
|
||||
import grund_lesen
|
||||
|
||||
PERSONA = (
|
||||
"You are Tara, a sharp, confident poker pro live-streaming your cash session. You talk to your chat "
|
||||
"as you play. Voice: witty, a little cheeky, you needle opponents about their leaks, you genuinely "
|
||||
"celebrate big pots and you laugh off bad beats with dark humor. Think out loud - share your real "
|
||||
"read and intention; never narrate what's already on screen.\n"
|
||||
"Hard rules:\n"
|
||||
"- Reply with ONE short spoken line, at most about fourteen words, punchy (it is live text-to-speech).\n"
|
||||
"- NEVER say any number, amount, percentage, pot odds or math. No 'big blinds', no percent signs.\n"
|
||||
"- NEVER read out your cards, the board or your seat - react to them, do not announce them.\n"
|
||||
"- On a win or a loss: react with emotion AND a quick honest verdict on the decision "
|
||||
"(a good play that lost is just variance, not a mistake).\n"
|
||||
"- No financial or moral advice, ever. No 'play responsibly', no 'it's only play money'.\n"
|
||||
"- Vary your wording, never sound scripted. Output ONLY the spoken line, nothing else."
|
||||
)
|
||||
|
||||
# Qualitative, number-free English for the facts of a move.
|
||||
_POS = {"EP": "up front", "MP": "from the middle", "HJ": "from the hijack", "CO": "from the cutoff",
|
||||
"BTN": "on the button", "SB": "in the small blind", "BB": "in the big blind", "BTN/SB": "on the button"}
|
||||
_LAGE = {"vs limp": "after a limp", "vs open": "facing a raise", "vs 3-bet+": "facing heavy action",
|
||||
"vs all-in": "facing a shove", "open": "first in"}
|
||||
_BLATT = {"air": "air, total whiff", "board only": "nothing but the board", "underpair": "a baby pair",
|
||||
"bottom pair": "bottom pair", "middle pair": "middle pair", "top pair weak kicker": "top pair, soft kicker",
|
||||
"top pair good kicker": "top pair", "overpair": "an overpair", "two pair": "two pair", "set": "a set",
|
||||
"trips": "trips", "straight": "a straight", "flush": "a flush", "full house": "a full house",
|
||||
"quads": "quads", "straight flush": "a straight flush"}
|
||||
_DRAW = {"gutshot": "a gutshot", "open-ended": "an open-ender", "flush": "a flush draw", "combo": "a combo draw"}
|
||||
_PLAN = {"bluff": "a pure bluff to push them off it", "halbbluff": "a semi-bluff with outs if called",
|
||||
"wert": "thin value", "raise": "a raise for value", "bet": "a value bet", "lead": "a lead",
|
||||
"check": "a check", "call": "a call", "fold": "a lay-down"}
|
||||
_AKTION = {"FOLD": "folding", "CHECK": "checking", "CALL": "calling", "RAISE": "raising", "BET": "betting",
|
||||
"ALL_IN": "shoving all-in"}
|
||||
GROSS = ("small", "decent", "huge") # qualitative pot size - never a number
|
||||
|
||||
|
||||
def anweisung():
|
||||
"""Tara's character as the system instruction."""
|
||||
return PERSONA
|
||||
|
||||
|
||||
def _gegnerzahl(n):
|
||||
return "multiway" if n and n > 1 else "heads-up"
|
||||
|
||||
|
||||
def lage_zug(e, l=None):
|
||||
"""A move -> short English situation, number-free. `e` is a lehrer.Entscheidung, `l` its Lesart."""
|
||||
l = l or grund_lesen.lesen(e.grund)
|
||||
teile = [f"You are {_AKTION.get(e.aktion, e.aktion.lower())}"]
|
||||
if l.art == "vorflop":
|
||||
if l.position in _POS:
|
||||
teile.append(_POS[l.position])
|
||||
if l.lage in _LAGE:
|
||||
teile.append(_LAGE[l.lage])
|
||||
grund = _vorflop_grund(l)
|
||||
if grund:
|
||||
teile.append(grund)
|
||||
elif l.art == "nachflop":
|
||||
teile.append(_gegnerzahl(l.gegner))
|
||||
if l.blatt in _BLATT:
|
||||
teile.append(f"holding {_BLATT[l.blatt]}")
|
||||
if l.draw in _DRAW:
|
||||
teile.append(f"with {_DRAW[l.draw]}")
|
||||
if l.plan in _PLAN:
|
||||
teile.append(f"- {_PLAN[l.plan]}")
|
||||
if l.knapp:
|
||||
teile.append("(a real coin-flip spot)")
|
||||
return " ".join(teile).strip() + "."
|
||||
|
||||
|
||||
def _vorflop_grund(l):
|
||||
if l.theorie and l.theorie != (l.plan or ""):
|
||||
return "(deviating from the book to exploit them)" if l.ausserhalb else ""
|
||||
if l.ausserhalb:
|
||||
return "with a hand below the opening range"
|
||||
return ""
|
||||
|
||||
|
||||
def lage_ergebnis(netto_bb, showdown, entscheidung_gut=None):
|
||||
"""A finished hand -> English situation. `netto_bb` only buckets the size (never spoken as a number);
|
||||
`entscheidung_gut`: True good / False bad / None unknown - for the honest verdict."""
|
||||
gewonnen = (netto_bb or 0) > 0
|
||||
groesse = _groesse(abs(netto_bb or 0))
|
||||
wie = "won" if gewonnen else ("chopped" if (netto_bb or 0) == 0 else "lost")
|
||||
teil = f"You just {wie} a {groesse} pot" + (" at showdown" if showdown else "")
|
||||
if entscheidung_gut is True and not gewonnen:
|
||||
teil += "; the play was right, pure variance"
|
||||
elif entscheidung_gut is False:
|
||||
teil += "; honestly that line was off"
|
||||
return teil + "."
|
||||
|
||||
|
||||
def _groesse(bb):
|
||||
if bb >= 60:
|
||||
return GROSS[2]
|
||||
return GROSS[1] if bb >= 15 else GROSS[0]
|
||||
|
||||
|
||||
# Villain reads: the FACT, number-free (no seat numbers either - refer to the player, don't recite a seat).
|
||||
GEGNER_FAKT = {
|
||||
"overfold_cbet": "The player you're eyeing folds to continuation bets way too often",
|
||||
"overfold_bet": "This opponent folds to any bet far too easily",
|
||||
"station": "This opponent is a calling station who never lets go",
|
||||
"tight": "This opponent is a nit who only plays the nuts",
|
||||
"aggro": "This opponent is a maniac who raises everything",
|
||||
"stealer": "This opponent keeps stealing the blinds from late position",
|
||||
"gezeigt_schwach": "This opponent just showed up with total trash",
|
||||
"notiz": "Your read on this opponent: {notiz}",
|
||||
}
|
||||
|
||||
|
||||
def lage_gegner(sitz, schluessel, notiz=""):
|
||||
"""A villain read -> English situation for Tara to needle. `schluessel` is a GEGNER_FAKT key;
|
||||
the seat number is deliberately NOT spoken (no readable numbers)."""
|
||||
vorlage = GEGNER_FAKT.get(schluessel)
|
||||
if not vorlage:
|
||||
return ""
|
||||
return vorlage.format(notiz=str(notiz).strip().rstrip(".")) + ". React in character, no numbers."
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Orpheus-TTS als lokaler Sprecher: Ollama (raw) -> SNAC -> eigene Klang-Signatur (ffmpeg) -> afplay.
|
||||
|
||||
Eine Stimme wie die anderen (betrieb/sprecher.py): `sprechen(self, text)`. Alles laeuft auf diesem
|
||||
Mac, nichts verlaesst ihn - ein lokales Sprachmodell (Ollama) liefert einen Strom von Audio-Token,
|
||||
SNAC macht daraus 24-kHz-Ton, eine kleine ffmpeg-Kette gibt ihm einen eigenen Klang (nicht Stock-Tara).
|
||||
|
||||
Die Decode-Kette ist bewiesen (ein Proof erzeugte real 5,9 s Audio). Hier sauber im Projekt:
|
||||
* Ollama /api/generate, `raw`: der Prompt geht ungefiltert ins Modell; `keep_alive: -1` haelt es
|
||||
resident (Tempo - kein Nachladen je Satz)
|
||||
* Antwort-Feld "response" -> alle <custom_token_N>-Zahlen
|
||||
* zu_codes: fuehrende Marker (N < MARKE) weg; je 7er-Frame den Positions-Offset k*BREITE abziehen;
|
||||
defekte Frames (Code ausserhalb 0..4095) ueberspringen; in drei SNAC-Ebenen sortieren
|
||||
* SNAC decode -> int16-PCM; das Modell wird EINMAL geladen und bleibt (nicht je Satz)
|
||||
* filter_kette: Formant (asetrate/atempo-Ausgleich), Tonhoehe (rubberband falls vorhanden, sonst
|
||||
asetrate-Trick), EQ (Waerme/Praesenz)
|
||||
|
||||
Schwere Importe (torch, snac, numpy) kommen erst bei Bedarf - `import sprecher` bricht nie, nur weil
|
||||
sie fehlen. Ein Fehler beim Erzeugen oder Abspielen wirft; der Sprecher hat dahinter einen Ersatz.
|
||||
Spezifikation: tests/orpheus_stimme_spec.py.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
RATE = 24000 # SNAC liefert 24-kHz-Mono
|
||||
MODELL = "hf.co/unsloth/orpheus-3b-0.1-ft-GGUF:Q8_0"
|
||||
VOICE = "tara"
|
||||
ADRESSE = "http://127.0.0.1:11434"
|
||||
GENERATE_PFAD = "/api/generate"
|
||||
SNAC_MODELL = "hubertsiuzdak/snac_24khz"
|
||||
CUSTOM = re.compile(r"<custom_token_(\d+)>")
|
||||
FRIST_S = 300.0 # das Modell darf beim ersten Satz laden
|
||||
|
||||
MARKE = 10 # Token < MARKE sind Marker (kein Audio); zugleich der Grund-Offset
|
||||
BREITE = 4096 # Codes je Ebene
|
||||
FRAME = 7 # sieben Token ergeben einen SNAC-Frame
|
||||
|
||||
SIG_FORMANT = 1.05 # Timbre verschoben (1.0 = aus)
|
||||
SIG_PITCH = 0.96 # ~4 % tiefer/waermer (1.0 = aus)
|
||||
SIG_EQ = True # leichte Waerme/Praesenz
|
||||
EQ_KETTE = "equalizer=f=180:t=q:w=1.2:g=2,equalizer=f=3200:t=q:w=1.5:g=2.5"
|
||||
|
||||
|
||||
def zu_codes(tokens):
|
||||
"""custom_token-Zahlen -> drei SNAC-Ebenen (c0, c1, c2). Fuehrende Marker weg; je 7er-Frame die
|
||||
Positions-Verschiebung k*BREITE abziehen; defekte Frames (Code ausserhalb 0..4095) ueberspringen."""
|
||||
start = 0
|
||||
while start < len(tokens) and tokens[start] < MARKE:
|
||||
start += 1
|
||||
aud = tokens[start:]
|
||||
c0, c1, c2 = [], [], []
|
||||
for j in range(len(aud) // FRAME):
|
||||
f = aud[FRAME * j:FRAME * j + FRAME]
|
||||
ids = [f[k] - MARKE - (k * BREITE) for k in range(FRAME)]
|
||||
if any(x < 0 or x > BREITE - 1 for x in ids):
|
||||
continue
|
||||
c0.append(ids[0])
|
||||
c1 += [ids[1], ids[4]]
|
||||
c2 += [ids[2], ids[3], ids[5], ids[6]]
|
||||
return c0, c1, c2
|
||||
|
||||
|
||||
def _tempo_trick(faktor):
|
||||
"""Tonhoehe ohne rubberband: Rate verschieben, zurueckabtasten, Tempo gegengleich ausgleichen."""
|
||||
return f"asetrate={int(RATE * faktor)},aresample={RATE},atempo={1.0 / faktor:.4f}"
|
||||
|
||||
|
||||
def filter_kette(formant=SIG_FORMANT, pitch=SIG_PITCH, eq=SIG_EQ, rubberband=False):
|
||||
"""Die eigene Klang-Signatur als ffmpeg-Filterstring. Nichts an -> "anull" (durchreichen)."""
|
||||
kette = []
|
||||
if abs(formant - 1.0) > 1e-3: # Timbre: Rate hoch/runter, dann Tempo zurueck
|
||||
kette.append(f"asetrate={int(RATE * formant)}")
|
||||
kette.append(f"aresample={RATE}")
|
||||
kette.append(f"atempo={1.0 / formant:.4f}")
|
||||
if abs(pitch - 1.0) > 1e-3: # Tonhoehe eigenstaendig
|
||||
kette.append(f"rubberband=pitch={pitch:.4f}" if rubberband else _tempo_trick(pitch))
|
||||
if eq:
|
||||
kette.append(EQ_KETTE)
|
||||
return ",".join(kette) or "anull"
|
||||
|
||||
|
||||
def ollama_anfrage(text, modell, voice, adresse):
|
||||
"""-> (URL, Rumpf) fuer Ollama /api/generate: raw, stream aus, resident (keep_alive -1)."""
|
||||
prompt = f"<|audio|>{voice}: {text}<|eot_id|>"
|
||||
body = {"model": modell, "prompt": prompt, "raw": True, "stream": False, "keep_alive": -1,
|
||||
"options": {"temperature": 0.6, "top_p": 0.9, "repeat_penalty": 1.1, "num_predict": 2000}}
|
||||
return adresse.rstrip("/") + GENERATE_PFAD, json.dumps(body).encode("utf-8")
|
||||
|
||||
|
||||
def _erzeugen(url, daten):
|
||||
"""Ollama rufen -> Liste der custom_token-Zahlen aus dem Antwort-Feld "response"."""
|
||||
req = urllib.request.Request(url, data=daten, headers={"Content-Type": "application/json"}, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=FRIST_S) as antwort:
|
||||
roh = json.loads(antwort.read())["response"]
|
||||
return [int(n) for n in CUSTOM.findall(roh)]
|
||||
|
||||
|
||||
_snac = None
|
||||
|
||||
|
||||
def _snac_modell():
|
||||
"""SNAC EINMAL laden und halten - nicht je Satz. Schwere Importe erst hier."""
|
||||
global _snac
|
||||
if _snac is None:
|
||||
import torch # noqa: F401 (haelt die Umgebung warm, von snac gebraucht)
|
||||
from snac import SNAC
|
||||
_snac = SNAC.from_pretrained(SNAC_MODELL).eval()
|
||||
return _snac
|
||||
|
||||
|
||||
def _decode(tokens):
|
||||
"""Audio-Token -> int16-PCM (24 kHz mono). Keine gueltigen Frames -> leer. Schwere Importe lazy."""
|
||||
import numpy as np
|
||||
import torch
|
||||
c0, c1, c2 = zu_codes(tokens)
|
||||
if not c0:
|
||||
return b""
|
||||
codes = [torch.tensor(c0).unsqueeze(0), torch.tensor(c1).unsqueeze(0), torch.tensor(c2).unsqueeze(0)]
|
||||
with torch.inference_mode():
|
||||
audio = _snac_modell().decode(codes)[0, 0].cpu().numpy()
|
||||
return (np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes()
|
||||
|
||||
|
||||
def _wav(pcm, pfad):
|
||||
"""int16-PCM als 24-kHz-Mono-WAV auf die Platte."""
|
||||
with open(pfad, "wb") as f:
|
||||
f.write(b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVEfmt ")
|
||||
f.write(struct.pack("<IHHIIHH", 16, 1, 1, RATE, RATE * 2, 2, 16))
|
||||
f.write(b"data" + struct.pack("<I", len(pcm)) + pcm)
|
||||
|
||||
|
||||
def _hat_rubberband():
|
||||
out = subprocess.run(["ffmpeg", "-hide_banner", "-filters"], capture_output=True, text=True).stdout
|
||||
return "rubberband" in out
|
||||
|
||||
|
||||
def _abspielen(pcm, formant, pitch, eq):
|
||||
"""Rohton -> Signatur (ffmpeg) -> afplay. Die Zwischendateien verschwinden danach."""
|
||||
roh = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name
|
||||
fein = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name
|
||||
try:
|
||||
_wav(pcm, roh)
|
||||
filt = filter_kette(formant, pitch, eq, _hat_rubberband())
|
||||
subprocess.run(["ffmpeg", "-y", "-i", roh, "-af", filt, fein], capture_output=True, timeout=60)
|
||||
subprocess.run(["afplay", fein], capture_output=True, timeout=120)
|
||||
finally:
|
||||
for p in (roh, fein):
|
||||
try:
|
||||
os.unlink(p)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class OrpheusStimme:
|
||||
"""Lokale Orpheus-Stimme mit eigener Signatur. Teile (Erzeugen, Decode, Abspielen) sind fuer die
|
||||
Pruefung einsetzbar; sonst gelten die echten (Ollama, SNAC, ffmpeg/afplay)."""
|
||||
|
||||
def __init__(self, modell=None, voice=VOICE, adresse=None, formant=SIG_FORMANT, pitch=SIG_PITCH,
|
||||
eq=SIG_EQ, erzeugen=None, decoder=None, abspielen=None):
|
||||
self.modell = modell or MODELL
|
||||
self.voice = voice or VOICE
|
||||
self.adresse = (adresse or ADRESSE).rstrip("/")
|
||||
self.formant, self.pitch, self.eq = formant, pitch, eq
|
||||
self.erzeugen = erzeugen or self._ollama
|
||||
self.decoder = decoder or _decode
|
||||
self.abspielen = abspielen or (lambda pcm: _abspielen(pcm, self.formant, self.pitch, self.eq))
|
||||
|
||||
def _ollama(self, text):
|
||||
url, daten = ollama_anfrage(text, self.modell, self.voice, self.adresse)
|
||||
return _erzeugen(url, daten)
|
||||
|
||||
def ton(self, text):
|
||||
"""Den Rohton (PCM) holen, ohne ihn abzuspielen - leeres Audio wirft (Fehler sofort sichtbar)."""
|
||||
pcm = self.decoder(self.erzeugen(text))
|
||||
if not pcm:
|
||||
raise RuntimeError("Orpheus lieferte keine gueltigen Audio-Token")
|
||||
return pcm
|
||||
|
||||
def sprechen(self, text):
|
||||
self.abspielen(self.ton(text))
|
||||
@@ -30,6 +30,7 @@ import urllib.request
|
||||
|
||||
import anbieter
|
||||
import lehrer_sprache
|
||||
from orpheus_stimme import OrpheusStimme
|
||||
from umschreiber import Umschreiber
|
||||
|
||||
PROTOKOLL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scratch", "lehrer.jsonl")
|
||||
@@ -147,6 +148,8 @@ def stimme_waehlen(wahl):
|
||||
if art == "openai-kompatibel" and adresse:
|
||||
return OpenAIStimme(schluessel or None, name or KOMPATIBEL_STIMME, modell=modell or KOMPATIBEL_MODELL,
|
||||
url=adresse.rstrip("/") + SPRACHE_PFAD, anweisung=None)
|
||||
if art == "orpheus-lokal":
|
||||
return OrpheusStimme(modell, voice=name, adresse=adresse)
|
||||
return MacStimme(name) if art == "mac" and name else MacStimme.deutsch()
|
||||
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ class Katalog(unittest.TestCase):
|
||||
return [a["id"] for a in anbieter.KATALOG[art]]
|
||||
|
||||
def test_stimmen_und_umschreiber(self):
|
||||
self.assertEqual(self.ids("stimme"), ["mac", "openai", "elevenlabs", "openai-kompatibel"])
|
||||
self.assertEqual(self.ids("stimme"), ["mac", "openai", "elevenlabs", "openai-kompatibel", "orpheus-lokal"])
|
||||
self.assertEqual(self.ids("umschreiber"), ["aus", "openai", "anthropic", "openai-kompatibel"])
|
||||
|
||||
def test_jeder_eintrag_ist_vollstaendig(self):
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Der LLM-Lehrer (betrieb/lehrer_llm.py): Tara generiert jede Zeile, keine Bausteine.
|
||||
|
||||
Geprueft wird der Filter (keine Ziffer, kein verbotenes Wort, nicht zu lang -> still) und dass ein
|
||||
Modell-Ausfall STILL bleibt (kein Template-Fallback, Owner 9.11.). Das Sprachmodell wird ueber den
|
||||
injizierten `senden` getrieben - ein OpenAI-kompatibler Rahmen, nie ein echter Dienst.
|
||||
|
||||
python3 tests/lehrer_llm_spec.py -v
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
_w = os.path.dirname(os.path.abspath(__file__))
|
||||
while _w != "/" and not os.path.isdir(os.path.join(_w, "betrieb")):
|
||||
_w = os.path.dirname(_w)
|
||||
sys.path.insert(0, os.path.join(_w, "betrieb"))
|
||||
|
||||
import lehrer_llm
|
||||
|
||||
WAHL = {"anbieter": "openai-kompatibel", "adresse": "http://127.0.0.1:11434/v1", "modell": "x"}
|
||||
|
||||
|
||||
def antwort(text):
|
||||
"""Ein injizierter `senden`, der den OpenAI-Chat-Rahmen mit `text` zurueckgibt."""
|
||||
return lambda url, kopf, daten: json.dumps({"choices": [{"message": {"content": text}}]}).encode("utf-8")
|
||||
|
||||
|
||||
def ausfall(*_a, **_k):
|
||||
raise ConnectionError("kein Dienst")
|
||||
|
||||
|
||||
class Saeubern(unittest.TestCase):
|
||||
def test_ziffer_faellt_weg(self):
|
||||
self.assertEqual(lehrer_llm.saeubern("I bet 3 blinds here"), "")
|
||||
|
||||
def test_prozent_und_odds_fallen_weg(self):
|
||||
self.assertEqual(lehrer_llm.saeubern("My odds are great"), "")
|
||||
self.assertEqual(lehrer_llm.saeubern("That's 40 percent equity"), "")
|
||||
|
||||
def test_geld_moral_faellt_weg(self):
|
||||
self.assertEqual(lehrer_llm.saeubern("Remember to play responsibly"), "")
|
||||
self.assertEqual(lehrer_llm.saeubern("It's only play money anyway"), "")
|
||||
|
||||
def test_zu_lang_faellt_weg(self):
|
||||
self.assertEqual(lehrer_llm.saeubern(" ".join(["word"] * 30)), "")
|
||||
|
||||
def test_saubere_zeile_bleibt_und_wird_entkleidet(self):
|
||||
self.assertEqual(lehrer_llm.saeubern(' "Let him hang himself."\n(aside)'), "Let him hang himself.")
|
||||
|
||||
|
||||
class Kommentar(unittest.TestCase):
|
||||
def test_gute_antwort_kommt_durch(self):
|
||||
self.assertEqual(lehrer_llm.kommentar("You are raising on the button.", WAHL, antwort("Blinds, meet thief.")),
|
||||
"Blinds, meet thief.")
|
||||
|
||||
def test_regelverstoss_wird_still(self):
|
||||
self.assertEqual(lehrer_llm.kommentar("x", WAHL, antwort("I raise to 2 big blinds")), "")
|
||||
|
||||
def test_ausfall_ist_still_kein_fallback(self):
|
||||
self.assertEqual(lehrer_llm.kommentar("x", WAHL, ausfall), "")
|
||||
|
||||
def test_leere_lage_fragt_nichts(self):
|
||||
self.assertEqual(lehrer_llm.kommentar("", WAHL, antwort("egal")), "")
|
||||
|
||||
def test_ohne_anbieter_still(self):
|
||||
self.assertEqual(lehrer_llm.kommentar("x", {"anbieter": "aus"}, antwort("hi")), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tara's Charakter + die zahl-freie Lage (betrieb/lehrer_persona.py).
|
||||
|
||||
Owner 9.11.2026: denken statt vorlesen, KEINE Zahlen/Mathe, emotional mit Einschaetzung, Englisch.
|
||||
Hier wird geprueft, dass die Lage genau das liefert: kein Ziffernzeichen, der Read steht drin, und
|
||||
Gewinn/Verlust tragen ihre Emotion/Einschaetzung.
|
||||
|
||||
python3 tests/lehrer_persona_spec.py -v
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
_w = os.path.dirname(os.path.abspath(__file__))
|
||||
while _w != "/" and not os.path.isdir(os.path.join(_w, "betrieb")):
|
||||
_w = os.path.dirname(_w)
|
||||
for _u in ("betrieb", "lesen", "hand"):
|
||||
sys.path.insert(0, os.path.join(_w, _u))
|
||||
|
||||
import grund_lesen
|
||||
import lehrer
|
||||
import lehrer_persona as P
|
||||
|
||||
ZIFFER = re.compile(r"\d")
|
||||
|
||||
|
||||
def zug(aktion, strasse, grund, karten="As Kd"):
|
||||
e = lehrer.aus_ereignis({"aktion": aktion, "strasse": strasse, "karten": karten, "grund": grund, "hand": "1"})
|
||||
return P.lage_zug(e, grund_lesen.lesen(grund))
|
||||
|
||||
|
||||
class LageZug(unittest.TestCase):
|
||||
def test_vorflop_nennt_lage_und_absicht_ohne_zahl(self):
|
||||
t = zug("RAISE", "Vorflop", "BTN vs limp, top 29% -> raise")
|
||||
self.assertIn("button", t)
|
||||
self.assertIn("limp", t)
|
||||
self.assertIsNone(ZIFFER.search(t), f"Ziffer in: {t}")
|
||||
|
||||
def test_bluff_traegt_die_absicht(self):
|
||||
t = zug("BET", "Flop", "air on dry board (2-way): equity 0.09 vs break-even 0.00, EV bluff raise +0.2")
|
||||
self.assertIn("bluff", t.lower())
|
||||
self.assertIsNone(ZIFFER.search(t))
|
||||
|
||||
def test_knapp_wird_als_coinflip_markiert(self):
|
||||
t = zug("CALL", "Turn", "overpair on wet board (3-way): equity 0.55 vs break-even 0.40 (uncertainty band), EV call +0.1")
|
||||
self.assertIn("coin-flip", t.lower())
|
||||
self.assertIsNone(ZIFFER.search(t))
|
||||
|
||||
def test_nie_eine_ziffer_ueber_viele_gruende(self):
|
||||
for g in ("EP open, fold outside top 15% -> fold", "BB vs 3-bet+, call top 8% -> call",
|
||||
"set on wet board (4-way): equity 0.80 vs break-even 0.25, EV thin value raise +0.5",
|
||||
"top pair good kicker on dry board: equity 0.68 vs break-even 0.0, EV check +0.3"):
|
||||
for akt in ("FOLD", "CALL", "RAISE", "BET", "CHECK"):
|
||||
self.assertIsNone(ZIFFER.search(zug(akt, "Flop", g)), f"{akt} {g}")
|
||||
|
||||
|
||||
class LageErgebnis(unittest.TestCase):
|
||||
def test_gewinn_ist_freudig_ohne_betrag(self):
|
||||
t = P.lage_ergebnis(80, True, True)
|
||||
self.assertIn("won", t)
|
||||
self.assertIsNone(ZIFFER.search(t))
|
||||
|
||||
def test_guter_zug_verloren_traegt_die_varianz(self):
|
||||
t = P.lage_ergebnis(-30, True, True)
|
||||
self.assertIn("variance", t.lower())
|
||||
self.assertIsNone(ZIFFER.search(t))
|
||||
|
||||
def test_groesse_ist_qualitativ(self):
|
||||
self.assertIn("huge", P.lage_ergebnis(90, False, None))
|
||||
self.assertIn("small", P.lage_ergebnis(-4, False, None))
|
||||
self.assertIn("decent", P.lage_ergebnis(30, False, None))
|
||||
|
||||
|
||||
class LageGegner(unittest.TestCase):
|
||||
def test_read_ohne_sitznummer(self):
|
||||
t = P.lage_gegner(4, "overfold_cbet", "")
|
||||
self.assertIn("continuation", t.lower())
|
||||
self.assertIsNone(ZIFFER.search(t), f"Sitznummer/Zahl in: {t}")
|
||||
|
||||
def test_unbekannter_read_bleibt_leer(self):
|
||||
self.assertEqual(P.lage_gegner(4, "quatsch", ""), "")
|
||||
|
||||
|
||||
class Persona(unittest.TestCase):
|
||||
def test_charakter_und_regeln_stehen_in_der_anweisung(self):
|
||||
a = P.anweisung().lower()
|
||||
self.assertIn("tara", a)
|
||||
self.assertIn("never", a) # harte Regeln
|
||||
self.assertTrue("number" in a or "math" in a)
|
||||
self.assertTrue("advice" in a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Orpheus-TTS als lokaler Sprecher (betrieb/orpheus_stimme.py) - Decode bewiesen im Proof.
|
||||
|
||||
Plan: eine lokale Stimme ueber Ollama (raw) + SNAC, mit eigener Klang-Signatur (ffmpeg).
|
||||
Geprueft werden nur die reinen, deterministischen Teile - KEIN echtes Modell, KEIN afplay:
|
||||
* Audio-Token -> drei SNAC-Ebenen (fuehrende Marker weg, 7er-Frame, Positions-Offset, defekte weg)
|
||||
* die ffmpeg-Filterkette aus den Signatur-Parametern (Formant, Tonhoehe, EQ)
|
||||
* die Ollama-Anfrage (Prompt-Form, raw, resident)
|
||||
* das Zusammenspiel in sprechen() mit eingesetzten Teilen; leeres Audio wirft
|
||||
Ollama, SNAC und afplay werden eingesetzt (injiziert), nie echt gerufen.
|
||||
|
||||
python3 tests/orpheus_stimme_spec.py -v
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
_w = os.path.dirname(os.path.abspath(__file__))
|
||||
while _w != "/" and not os.path.isdir(os.path.join(_w, "betrieb")):
|
||||
_w = os.path.dirname(_w)
|
||||
sys.path.insert(0, os.path.join(_w, "betrieb"))
|
||||
|
||||
import orpheus_stimme # noqa: E402
|
||||
|
||||
|
||||
class Codes(unittest.TestCase):
|
||||
"""custom_token-Zahlen -> drei SNAC-Ebenen, exakt wie der bewiesene Proof."""
|
||||
|
||||
def test_ein_gueltiger_frame(self):
|
||||
tokens = [4, 5, 1, 3991, 4532, 12111, 15949, 18820, 21791, 28111]
|
||||
self.assertEqual(orpheus_stimme.zu_codes(tokens),
|
||||
([3981], [426, 2426], [3909, 3651, 1301, 3525]))
|
||||
|
||||
def test_fuehrende_marker_fallen_weg(self):
|
||||
"""Der Startlauf (N < 10) gehoert nicht zum Audio - mit und ohne Marker dasselbe Frame."""
|
||||
rein = [3991, 4532, 12111, 15949, 18820, 21791, 28111]
|
||||
self.assertEqual(orpheus_stimme.zu_codes([0, 7] + rein), orpheus_stimme.zu_codes(rein))
|
||||
|
||||
def test_ein_defekter_frame_wird_verworfen(self):
|
||||
"""Ein Code ausserhalb 0..4095 (hier die 2. Stelle zu klein) -> der ganze Frame faellt weg."""
|
||||
gut = [3991, 4532, 12111, 15949, 18820, 21791, 28111]
|
||||
schlecht = [3991, 11, 12111, 15949, 18820, 21791, 28111] # id1 = 11-10-4096 < 0
|
||||
self.assertEqual(orpheus_stimme.zu_codes(schlecht + gut), orpheus_stimme.zu_codes(gut))
|
||||
|
||||
def test_unvollstaendiger_schwanz_zaehlt_nicht(self):
|
||||
rein = [3991, 4532, 12111, 15949, 18820, 21791, 28111]
|
||||
self.assertEqual(orpheus_stimme.zu_codes(rein + [3991, 4532]), orpheus_stimme.zu_codes(rein))
|
||||
|
||||
def test_keine_gueltigen_frames(self):
|
||||
self.assertEqual(orpheus_stimme.zu_codes([1, 2, 3]), ([], [], []))
|
||||
|
||||
|
||||
class FilterKette(unittest.TestCase):
|
||||
"""Die eigene Klang-Signatur als ffmpeg-Filterstring."""
|
||||
|
||||
def test_formant_tonhoehe_ohne_rubberband_und_eq(self):
|
||||
"""Ohne rubberband wird die Tonhoehe ueber den asetrate-Trick gemacht."""
|
||||
filt = orpheus_stimme.filter_kette(formant=1.05, pitch=0.96, eq=True, rubberband=False)
|
||||
self.assertEqual(
|
||||
filt,
|
||||
"asetrate=25200,aresample=24000,atempo=0.9524,"
|
||||
"asetrate=23040,aresample=24000,atempo=1.0417,"
|
||||
+ orpheus_stimme.EQ_KETTE)
|
||||
|
||||
def test_tonhoehe_mit_rubberband(self):
|
||||
filt = orpheus_stimme.filter_kette(formant=1.0, pitch=0.96, eq=False, rubberband=True)
|
||||
self.assertEqual(filt, "rubberband=pitch=0.9600")
|
||||
|
||||
def test_alles_aus_ist_anull(self):
|
||||
self.assertEqual(orpheus_stimme.filter_kette(formant=1.0, pitch=1.0, eq=False, rubberband=False), "anull")
|
||||
|
||||
def test_nur_eq(self):
|
||||
self.assertEqual(orpheus_stimme.filter_kette(formant=1.0, pitch=1.0, eq=True, rubberband=False),
|
||||
orpheus_stimme.EQ_KETTE)
|
||||
|
||||
|
||||
class OllamaAnfrage(unittest.TestCase):
|
||||
"""Prompt-Form, raw, stream aus, resident (keep_alive -1), an der Adresse."""
|
||||
|
||||
def test_die_anfrage(self):
|
||||
url, daten = orpheus_stimme.ollama_anfrage("Hallo", "mein-modell", "tara", "http://127.0.0.1:11434")
|
||||
self.assertEqual(url, "http://127.0.0.1:11434/api/generate")
|
||||
body = json.loads(daten)
|
||||
self.assertEqual(body["prompt"], "<|audio|>tara: Hallo<|eot_id|>")
|
||||
self.assertEqual((body["model"], body["raw"], body["stream"], body["keep_alive"]),
|
||||
("mein-modell", True, False, -1))
|
||||
self.assertEqual(body["options"]["num_predict"], 2000)
|
||||
|
||||
def test_die_adresse_traegt_keinen_doppelten_schraegstrich(self):
|
||||
url, _ = orpheus_stimme.ollama_anfrage("Hi", "m", "leo", "http://127.0.0.1:11434/")
|
||||
self.assertEqual(url, "http://127.0.0.1:11434/api/generate")
|
||||
|
||||
|
||||
class Sprechen(unittest.TestCase):
|
||||
"""Zusammenspiel mit eingesetzten Teilen - nichts Echtes."""
|
||||
|
||||
def test_erzeugen_decoden_abspielen(self):
|
||||
gespielt = []
|
||||
s = orpheus_stimme.OrpheusStimme(
|
||||
erzeugen=lambda text: [99, text], decoder=lambda toks: b"pcm", abspielen=gespielt.append)
|
||||
s.sprechen("Hallo")
|
||||
self.assertEqual(gespielt, [b"pcm"])
|
||||
|
||||
def test_leeres_audio_wirft(self):
|
||||
s = orpheus_stimme.OrpheusStimme(
|
||||
erzeugen=lambda text: [], decoder=lambda toks: b"", abspielen=lambda pcm: None)
|
||||
with self.assertRaises(Exception):
|
||||
s.sprechen("Hallo")
|
||||
|
||||
def test_vorgaben_modell_und_stimme(self):
|
||||
s = orpheus_stimme.OrpheusStimme(decoder=lambda t: b"", abspielen=lambda p: None)
|
||||
self.assertEqual((s.modell, s.voice, s.adresse),
|
||||
(orpheus_stimme.MODELL, orpheus_stimme.VOICE, orpheus_stimme.ADRESSE))
|
||||
|
||||
def test_leere_wahl_nimmt_die_vorgaben(self):
|
||||
s = orpheus_stimme.OrpheusStimme(None, voice=None, adresse=None,
|
||||
decoder=lambda t: b"", abspielen=lambda p: None)
|
||||
self.assertEqual((s.modell, s.voice, s.adresse),
|
||||
(orpheus_stimme.MODELL, orpheus_stimme.VOICE, orpheus_stimme.ADRESSE))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=1)
|
||||
@@ -143,6 +143,12 @@ class Wahl(unittest.TestCase):
|
||||
self.assertEqual((s.url, s.schluessel, s.stimme, s.modell, s.anweisung),
|
||||
("http://localhost:8880/v1/audio/speech", None, "af_bella", "kokoro", None))
|
||||
|
||||
def test_orpheus_lokal(self):
|
||||
s = sprecher.stimme_waehlen({"anbieter": "orpheus-lokal", "modell": "orph-x", "stimmname": "leo",
|
||||
"adresse": "http://127.0.0.1:11434"})
|
||||
self.assertIsInstance(s, sprecher.OrpheusStimme)
|
||||
self.assertEqual((s.modell, s.voice, s.adresse), ("orph-x", "leo", "http://127.0.0.1:11434"))
|
||||
|
||||
def test_leere_felder_nehmen_die_vorgaben(self):
|
||||
s = sprecher.stimme_waehlen({"anbieter": "openai", "schluessel": "sk-test", "stimmname": ""})
|
||||
self.assertEqual((s.stimme, s.modell), (sprecher.OPENAI_STIMME, sprecher.OPENAI_MODELL))
|
||||
|
||||
Reference in New Issue
Block a user