- engine::audit_turn: Turn-Entscheidungen im Turn+River-Spiel (E3-Löser) nachgerechnet, EV je Aktion fuer die echte Hand (TrSolver::hand_action_values), Gegner-Range entlang der Linie - engine::audit_allin: Preflop gegen All-in (Equity gegen Nash-Push-Range vs Preis), Push/Fold first-in <= 25 bb (Nash-Spiel der Charts), Flop gegen All-in (exakte Equity vs Preis) - bin/audit: Feld method/note, --turn-iters/--turn-combos/--turn-cards - lesen/audit_lauf.py: exakte Spots aus dem Schatten-Log, Cache je Lauf, Bericht je Lauf (Street, Messlatte, Engine-Teil, Top 10), Wochensumme, Fixture-Vorschlaege - sicht/audit_seite.py + Route: /audit, /api/audit, /api/audit/laeufe, /api/audit/woche - betrieb/audit_haken.py + docs/notizen/D4-audit-haken.patch (runner.py, 3 Zeilen) - tests/audit_lauf_spec.py 12/12; cargo test engine::audit 14/14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
181 lines
9.3 KiB
Python
181 lines
9.3 KiB
Python
"""Entscheidungs-Audit (Plan D4) im Cockpit-Server (lesen/audit_lauf.py): eine Seite und JSON-Endpunkte.
|
||
|
||
/audit Seite: Lauf oder Woche wählen, Bericht (Summen, die 10 teuersten Spots)
|
||
/api/audit?pid=.. {"status": "fertig"|"rechnet"|"fehler"|"fehlt", "bericht", "text", "stand"}
|
||
ohne pid: der jüngste Laufbericht
|
||
/api/audit?pid=..&neu=1 rechnet den Lauf (neu) im Hintergrund; der Cache macht es billig
|
||
/api/audit/laeufe [{pid, von, bis, entscheidungen, bericht: bool}]
|
||
/api/audit/woche?woche=JJJJ-Www Wochensumme (aus den Laufberichten; ohne woche: die jüngste)
|
||
|
||
Gelesen wird, was der Haken nach jedem Lauf schreibt (archiv/audit/lauf-<pid>.json). Ein Lauf ohne
|
||
Bericht wird nur auf Anforderung (`neu=1`) gerechnet, in EINEM Hintergrundfaden (die Bin läuft in
|
||
Priorität Idle), nie im Anfrage-Faden. Datenquelle: AUDIT_WURZEL, sonst dieser Baum.
|
||
"""
|
||
import json
|
||
import os
|
||
import sys
|
||
import threading
|
||
import time
|
||
from urllib.parse import parse_qs
|
||
|
||
_w = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
_l = os.path.join(_w, "lesen")
|
||
if _l not in sys.path:
|
||
sys.path.append(_l)
|
||
|
||
_sperre = threading.Lock()
|
||
_rechnet = {} # pid -> {"status", "fehler", "stand"}
|
||
_faden = None
|
||
|
||
|
||
def _wurzel():
|
||
return os.environ.get("AUDIT_WURZEL") or _w
|
||
|
||
|
||
def _bericht_laden(pid=None):
|
||
import audit_lauf
|
||
if pid is None:
|
||
alle = audit_lauf.laufberichte(_wurzel())
|
||
return max(alle, key=lambda b: b["lauf"].get("von") or "") if alle else None
|
||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), f"lauf-{pid}.json"))
|
||
return b or None
|
||
|
||
|
||
def _rechnen(pid):
|
||
import audit_lauf
|
||
try:
|
||
b = audit_lauf.lauf_bericht(_wurzel(), pid=pid, still=True)
|
||
if "fehler" in b:
|
||
raise RuntimeError(b["fehler"])
|
||
audit_lauf.woche_schreiben(_wurzel(), audit_lauf.iso_woche(b["lauf"]["von"]))
|
||
with _sperre:
|
||
_rechnet[str(pid)] = {"status": "fertig", "stand": time.time()}
|
||
except Exception as e: # noqa: BLE001 - die Seite zeigt den Fehler, der Server bleibt stehen
|
||
with _sperre:
|
||
_rechnet[str(pid)] = {"status": "fehler", "fehler": f"{type(e).__name__}: {e}", "stand": time.time()}
|
||
|
||
|
||
def anfordern(pid=None, neu=False):
|
||
"""Stand für einen Lauf; `neu` stößt das Rechnen an (ein Faden für alles)."""
|
||
global _faden
|
||
import audit_lauf
|
||
with _sperre:
|
||
laeuft = _faden is not None and _faden.is_alive()
|
||
st = dict(_rechnet.get(str(pid)) or {})
|
||
if neu and pid and not laeuft:
|
||
_rechnet[str(pid)] = {"status": "rechnet", "stand": time.time()}
|
||
_faden = threading.Thread(target=_rechnen, args=(pid,), daemon=True, name="audit")
|
||
_faden.start()
|
||
st = dict(_rechnet[str(pid)])
|
||
elif neu and laeuft and st.get("status") != "rechnet":
|
||
st = {"status": "wartet", "text": "ein anderer Lauf wird gerade gerechnet ..."}
|
||
b = _bericht_laden(pid)
|
||
if st.get("status") in ("rechnet", "wartet", "fehler"):
|
||
st.update({"bericht": b, "text": audit_lauf.markdown(b) if b else st.get("text", "rechnet ...")})
|
||
return st
|
||
if not b:
|
||
return {"status": "fehlt", "text": "noch kein Bericht für diesen Lauf (neu rechnen stößt ihn an)", "bericht": None}
|
||
return {"status": "fertig", "bericht": b, "text": audit_lauf.markdown(b), "stand": b.get("erstellt")}
|
||
|
||
|
||
def laeufe():
|
||
import audit_lauf
|
||
import roentgen
|
||
da = {str(b["lauf"].get("pid")) for b in audit_lauf.laufberichte(_wurzel())}
|
||
liste = roentgen.laeufe(roentgen.daten(_wurzel())["schatten"])
|
||
return [dict(r, bericht=str(r["pid"]) in da) for r in liste if r["entscheidungen"] > 0]
|
||
|
||
|
||
def woche(w=None):
|
||
import audit_lauf
|
||
if w:
|
||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), f"woche-{w}.json"))
|
||
else:
|
||
alle = sorted(p for p in os.listdir(audit_lauf.ordner(_wurzel())) if p.startswith("woche-") and p.endswith(".json")) \
|
||
if os.path.isdir(audit_lauf.ordner(_wurzel())) else []
|
||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), alle[-1])) if alle else {}
|
||
if not b:
|
||
return {"status": "fehlt", "text": "noch keine Wochensumme", "bericht": None}
|
||
return {"status": "fertig", "bericht": b, "text": audit_lauf.markdown(b)}
|
||
|
||
|
||
SEITE = """<!doctype html>
|
||
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>Entscheidungs-Audit</title>
|
||
<style>
|
||
:root{--bg:#fff;--fg:#1d1d1f;--mut:#6e6e73;--rand:#d2d2d7;--akzent:#0a62c9;--rot:#c9341f}
|
||
@media (prefers-color-scheme:dark){:root{--bg:#1c1c1e;--fg:#f2f2f7;--mut:#98989d;--rand:#3a3a3c;--akzent:#64a8ff;--rot:#ff6b5a}}
|
||
body{margin:0;padding:16px;background:var(--bg);color:var(--fg);font:14px/1.4 -apple-system,Segoe UI,sans-serif}
|
||
h1{font-size:18px;margin:0 0 12px}h2{font-size:15px;margin:18px 0 6px}
|
||
select,button{font:inherit;padding:4px 8px;background:var(--bg);color:var(--fg);border:1px solid var(--rand);border-radius:6px}
|
||
#status{color:var(--mut);margin:8px 0}
|
||
.kacheln{display:flex;flex-wrap:wrap;gap:8px;margin:8px 0}
|
||
.k{border:1px solid var(--rand);border-radius:8px;padding:6px 10px;min-width:110px}
|
||
.k b{display:block;font-size:18px;font-variant-numeric:tabular-nums}.k span{color:var(--mut);font-size:12px}
|
||
.tab{overflow-x:auto}
|
||
table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums}
|
||
td,th{border-bottom:1px solid var(--rand);padding:3px 8px;text-align:left;vertical-align:top}
|
||
td.z{text-align:right}.v{color:var(--rot);font-weight:600}
|
||
pre{font:12px/1.45 ui-monospace,Consolas,monospace;overflow-x:auto;white-space:pre-wrap;border-top:1px solid var(--rand);padding-top:12px}
|
||
</style></head><body>
|
||
<h1>Entscheidungs-Audit (D4)</h1>
|
||
<label>Bericht <select id="wahl"></select></label> <button id="neu">Lauf neu rechnen</button>
|
||
<div id="status"></div>
|
||
<div class="kacheln" id="kacheln"></div>
|
||
<h2>Die 10 teuersten Entscheidungen</h2><div class="tab"><table id="top"></table></div>
|
||
<h2>Je Street, Messlatte, Engine-Teil</h2><pre id="text">lädt ...</pre>
|
||
<script>
|
||
const $=id=>document.getElementById(id);let uhr=null;
|
||
const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||
async function liste(){
|
||
const l=await (await fetch('/api/audit/laeufe')).json();
|
||
$('wahl').innerHTML='<option value="woche">Woche (Summe)</option>'+l.slice().reverse().map(r=>
|
||
`<option value="${r.pid}">pid ${r.pid} · ${r.von} – ${r.bis.slice(11)} · ${r.entscheidungen} Anfr.${r.bericht?'':' · ohne Bericht'}</option>`).join('');
|
||
}
|
||
function zeigen(r){
|
||
const b=r.bericht;$('text').textContent=r.text||'';
|
||
if(!b){$('kacheln').innerHTML='';$('top').innerHTML='';return;}
|
||
const g=b.streets.GESAMT,h=b.haende||0;
|
||
const k=[[g.verlust_bb.toFixed(1)+' bb','Verlust gesamt'],[h?(100*g.verlust_bb/h).toFixed(2):'-','bb/100 Hände'],
|
||
[g.bewertet+' / '+g.n,'bewertet / Entscheidungen'],[h,'Hände']];
|
||
for(const s of ['PREFLOP','FLOP','TURN','RIVER']){const x=b.streets[s];k.push([x.verlust_bb.toFixed(1)+' bb',s+' ('+x.bewertet+')']);}
|
||
$('kacheln').innerHTML=k.map(([w,t])=>`<div class="k"><b>${esc(w)}</b><span>${esc(t)}</span></div>`).join('');
|
||
$('top').innerHTML='<tr><th>#</th><th>Hand</th><th>Street</th><th>Karten / Brett</th><th>gespielt</th><th>besser</th><th>Verlust bb</th><th>Hand bb</th><th>Engine-Teil</th><th>Grund</th></tr>'+
|
||
b.top.slice(0,10).map((t,i)=>`<tr><td class="z">${i+1}</td><td>${esc(t.hand)}<br><span style="color:var(--mut)">${esc(t.zeit)}</span></td><td>${esc(t.street)}</td>`+
|
||
`<td>${esc(t.karten)} / ${esc(t.brett||'-')}</td><td>${esc(t.gespielt_als)}</td><td>${esc(t.beste)}</td><td class="z v">${t.verlust_bb.toFixed(2)}</td>`+
|
||
`<td class="z">${t.ergebnis_bb==null?'-':t.ergebnis_bb.toFixed(1)}</td><td>${esc(t.wer_name||t.wer)}</td><td>${esc((t.grund||'').slice(0,90))}</td></tr>`).join('');
|
||
}
|
||
async function holen(neu){
|
||
clearTimeout(uhr);const w=$('wahl').value;
|
||
try{
|
||
const url=w==='woche'?'/api/audit/woche':'/api/audit?pid='+encodeURIComponent(w)+(neu?'&neu=1':'');
|
||
const r=await (await fetch(url)).json();zeigen(r);
|
||
$('status').textContent=r.status==='fertig'?'fertig'+(r.stand?' ('+r.stand+')':''):r.status==='fehler'?'Fehler: '+r.fehler:
|
||
r.status==='rechnet'?'wird gerechnet (Bin, Priorität Idle) ...':r.text||r.status;
|
||
if(r.status==='rechnet'||r.status==='wartet') uhr=setTimeout(()=>holen(false),4000);
|
||
}catch(e){$('status').textContent='Server nicht erreichbar';uhr=setTimeout(()=>holen(false),5000);}
|
||
}
|
||
$('wahl').onchange=()=>holen(false);$('neu').onclick=()=>holen(true);
|
||
liste().then(()=>holen(false));
|
||
</script></body></html>"""
|
||
|
||
|
||
def _js(x):
|
||
return 200, json.dumps(x, ensure_ascii=False, default=str).encode("utf-8"), "application/json; charset=utf-8"
|
||
|
||
|
||
def antwort(pfad, query=""):
|
||
"""(code, daten, art) für unsere Pfade, sonst None."""
|
||
q = parse_qs(query or "")
|
||
if pfad == "/audit":
|
||
return 200, SEITE.encode("utf-8"), "text/html; charset=utf-8"
|
||
if pfad == "/api/audit/laeufe":
|
||
return _js(laeufe())
|
||
if pfad == "/api/audit/woche":
|
||
return _js(woche((q.get("woche") or [None])[0]))
|
||
if pfad == "/api/audit":
|
||
pid = (q.get("pid") or [None])[0]
|
||
neu = (q.get("neu") or ["0"])[0] == "1"
|
||
return _js(anfordern(pid, neu))
|
||
return None
|