Files
pokerfreak/entscheiden/decide.py
T
mmintel 7a8907682e Frische-Wache: geprueft wird nur ein zum Kern passendes Binary
Alle Praegefalle laufen gegen das Release-Binary. Wurde der Kern geaendert und
nicht gebaut, pruefte die Kette stillschweigend die alte Fassung - eine
Spezifikation war deshalb rot, ohne dass der Kern schuld war.
2026-10-29 00:21:57 +01:00

102 lines
3.9 KiB
Python

#!/usr/bin/env python3
"""Schickt Anfragen an den Entscheidungskern (pokerfreak) und liest Antworten.
from decide import entscheide
"""
import os as _os, sys as _sys
_w = _os.path.dirname(_os.path.abspath(__file__))
while _w != "/" and not _os.path.isdir(_os.path.join(_w, "hand")):
_w = _os.path.dirname(_w)
WURZEL = _w
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import json
import os
import sys
import subprocess
BASE = os.path.dirname(os.path.abspath(__file__))
BINARY = os.environ.get("COINPOKER_KERN", os.path.join(BASE, "..", "..", "pokerfreak", "target", "release", "pokerfreak"))
QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, "..", "..", "pokerfreak"))
def bereit():
return os.path.exists(BINARY)
def baue():
"""Baut den Kern, falls nötig."""
r = subprocess.run(["cargo", "build", "--release"], cwd=QUELLE,
capture_output=True, text=True, timeout=600)
return r.returncode == 0, (r.stdout + r.stderr)[-400:]
def frisch():
"""Ist das Release-Binary nicht aelter als der Kern-Quelltext?
Alles hier entscheidet ueber dieses Binary. Wird der Kern geaendert und nicht mit
`cargo build --release` gebaut, prueft die Kette stillschweigend die alte Fassung -
deshalb tests/kern_frisch_spec.py.
"""
if not os.path.exists(BINARY):
return False
quelle = os.path.join(QUELLE, "src")
if not os.path.isdir(quelle):
return True # fremder Kern: nur das Binary da
juengste = max((os.path.getmtime(os.path.join(w, f))
for w, _, fs in os.walk(quelle) for f in fs if f.endswith(".rs")),
default=0.0)
return os.path.getmtime(BINARY) >= juengste
def entscheide(anfragen, timeout=30):
"""Liste von Anfrage-Zeilen -> Liste von Entscheidungen (dict)."""
if not anfragen:
return []
# Was die Übersetzung absichtlich leer lässt (`_unklar`), geht nicht zum Kern: ohne
# eigenen Platz wäre es für ihn eine ungültige Anfrage statt eines Aussetzens.
aussetzen = {}
for i, zeile in enumerate(anfragen):
try:
a = json.loads(zeile)
except ValueError:
continue
if isinstance(a, dict) and a.get("legalActions") == [] and a.get("_unklar"):
aussetzen[i] = {"action": "ABSTAIN", "reason": f"Übersetzung setzt aus: {a['_unklar']}"}
if aussetzen:
rest = iter(entscheide([z for i, z in enumerate(anfragen) if i not in aussetzen], timeout))
return [aussetzen[i] if i in aussetzen else next(rest) for i in range(len(anfragen))]
r = subprocess.run([BINARY], input="\n".join(anfragen) + "\n",
capture_output=True, text=True, timeout=timeout)
if r.returncode != 0:
raise RuntimeError(f"pokerfreak scheiterte: {r.stderr.strip()[:300]}")
antworten = []
for zeile in r.stdout.strip().split("\n"):
if not zeile.strip():
continue
try:
antworten.append(json.loads(zeile))
except Exception:
antworten.append({"action": "ABSTAIN", "reason": "Antwort unlesbar"})
return antworten
if __name__ == "__main__":
import sys
if not bereit():
ok, ausgabe = baue()
print("gebaut:", ok)
if not ok:
print(ausgabe)
sys.exit(1)
probe = json.dumps({
"variant": "NLHE", "bigBlind": 0.1, "seats": 6, "heroSeat": 5,
"heroCards": [{"rank": "ACE", "suit": "SPADES"}, {"rank": "ACE", "suit": "HEARTS"}],
"board": {}, "street": "PREFLOP", "pot": 0.15, "toCall": 0.1,
"heroStack": 10.0, "legalActions": ["FOLD", "CALL", "RAISE"],
"allowedSizes": [0.3, 0.5],
"villains": [{"seat": 2, "stack": 10.0, "folded": False}]})
print(entscheide([probe])[0])