poker / server.py
Alisson990's picture
Web front-end
fe1a02a verified
Raw History Blame Contribute Delete
12 kB
"""
Local web front-end for the poker AI.
python server.py # abre http://localhost:8765
python server.py --model ckpts/checkpoints/model_it00261.pt --port 8765
"""
import argparse
import json
import os
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import torch
from play import PokerAI, card_str
from poker_core import ACTION_NAMES, N_ACTIONS, NREV, HandEvaluator, PokerEnv
torch.set_grad_enabled(False)
HERE = os.path.dirname(os.path.abspath(__file__))
CAT_NAMES = ["Carta alta", "Par", "Dois pares", "Trinca", "Sequência", "Flush", "Full house", "Quadra",
"Straight flush"]
STREETS = ["Pré-flop", "Flop", "Turn", "River"]
def fmt(x):
x = round(float(x), 2)
return f"{x:g}"
class Game:
def __init__(self, ai, ev):
self.ai, self.ev = ai, ev
self.lock = threading.Lock()
self.env = None
# ---------------------------------------------------------------- setup
def new_game(self, players=6, stack=100.0, mode="play", reveal=False):
players = max(2, min(23, int(players)))
self.n = players
self.stack0 = float(stack)
self.hero = 0 if mode == "play" else -1
self.reveal = bool(reveal) or self.hero < 0
self.env = PokerEnv(1, players, [0] * (players - 2) + [1], "cpu", self.ev, eq_samples=64, ante_prob=0.0)
self.profit = [0.0] * players
self.hands = 0
self.button = -1
self.new_hand()
def new_hand(self):
env, n = self.env, self.n
self.button = (self.button + 1) % n
env.reset(n_override=n, stacks_override=torch.full((1, n), self.stack0))
# place the dealer button deterministically (rotate each hand) and re-post blinds
env.button[0] = self.button
env.stack[0, :n] = self.stack0
env.bet.zero_(); env.contrib.zero_(); env.st_contrib.zero_()
sb = self.button if n == 2 else (self.button + 1) % n
bb = (sb + 1) % n
for s, a in ((sb, 0.5), (bb, 1.0)):
env.stack[0, s] -= a; env.bet[0, s] += a; env.contrib[0, s] += a; env.st_contrib[0, s, 0] += a
env.max_bet[0] = 1.0
env.cur[0] = env._next_need(torch.tensor([bb]), env._need())[0][0]
self.sb, self.bb = sb, bb
self.last = [""] * n
self.last[sb], self.last[bb] = "SB 0.5", "BB 1"
self.log = [f"— Mão #{self.hands + 1} — botão: {self.name(self.button)}"]
self.think = None
self.result = None
self.street_seen = 0
def name(self, s):
return "Você" if s == self.hero else f"IA {s + 1}"
# ---------------------------------------------------------------- actions
def probs_for_current(self):
o = self.env.obs()
pr = self.ai.probs(o)[0]
return pr, o
def describe(self, a, custom=None):
env = self.env
p = int(env.cur[0])
bet_p = env.bet[0, p].item()
stk = env.stack[0, p].item()
to_call = max(env.max_bet[0].item() - bet_p, 0.0)
if a == 0:
return "fold"
if a == 1:
if to_call <= 1e-9:
return "check"
return f"call {fmt(min(to_call, stk))}" + (" (all-in)" if stk <= to_call + 1e-9 else "")
if a == 9:
return f"ALL-IN {fmt(bet_p + stk)}"
if a == N_ACTIONS:
to = max(custom, env.max_bet[0].item() + env.min_raise[0].item())
else:
to = env._raise_targets(env.cur)[0, a].item()
to = min(to, bet_p + stk)
verb = "bet" if env.max_bet[0].item() <= 1e-9 else "raise para"
return f"{verb} {fmt(to)}" + (" (all-in)" if to >= bet_p + stk - 1e-9 else "")
def apply(self, a, custom=None):
env = self.env
p = int(env.cur[0])
street = int(env.street[0])
txt = self.describe(a, custom)
self.last[p] = txt
self.log.append(f"{self.name(p)}: {txt}")
fin, delta = env.step(torch.tensor([a]), custom_to=None if custom is None else torch.tensor([float(custom)]))
if not fin[0] and int(env.street[0]) != street:
st = int(env.street[0])
self.last = [""] * self.n
cards = " ".join(card_str(c) for c in env.board[0, :NREV[st]].tolist())
self.log.append(f"— {STREETS[st]}: {cards}")
if fin[0]:
self.finish(delta[0])
def finish(self, delta):
env, n = self.env, self.n
self.hands += 1
live = [s for s in range(n) if not env.folded[0, s]]
board = env.board[0].tolist()
showdown = len(live) > 1
hands = {}
if showdown:
for s in live:
sc = self.ev.eval_k(torch.tensor([env.hole[0, s].tolist() + board]))
hands[s] = CAT_NAMES[int(self.ev.category(sc)[0])]
self.log.append(f"— Showdown: {' '.join(card_str(c) for c in board)}")
winners = []
for s in range(n):
d = delta[s].item()
self.profit[s] += d
if d > 1e-9:
winners.append(s)
self.log.append(f"{self.name(s)} ganha {fmt(d + env.contrib[0, s].item())}"
+ (f" com {hands[s]}" if s in hands else ""))
self.result = dict(winners=winners, hands={str(k): v for k, v in hands.items()}, showdown=showdown,
delta=[round(delta[s].item(), 2) for s in range(n)])
def ai_step(self):
env = self.env
if env.done[0] or int(env.cur[0]) == self.hero:
return
p = int(env.cur[0])
pr, o = self.probs_for_current()
a = int(torch.distributions.Categorical(probs=pr).sample())
self.think = self.think_info(p, pr, a)
self.apply(a)
def hero_act(self, kind, amount=None):
env = self.env
if env.done[0] or int(env.cur[0]) != self.hero:
return
L = env.legal()[0]
if kind == "fold":
a, c = (0 if L[0] else 1), None
elif kind == "call":
a, c = 1, None
elif kind == "allin":
a, c = (9 if L[9] else 1), None
else:
if not L[9]:
a, c = 1, None
else:
a, c = N_ACTIONS, float(amount)
if c >= env.bet[0, self.hero].item() + env.stack[0, self.hero].item() - 1e-9:
a, c = 9, None
self.apply(a, c)
def think_info(self, p, pr, chosen=None):
env = self.env
merged = {}
for i in range(N_ACTIONS):
if pr[i] < 1e-4:
continue
lab = self.describe(i) # different abstract sizes can map to the same real amount
m = merged.setdefault(lab, dict(label=lab, p=0.0, chosen=False))
m["p"] += pr[i].item()
m["chosen"] |= (i == chosen)
opts = [dict(m, p=round(m["p"], 3)) for m in merged.values() if m["p"] >= 0.005 or m["chosen"]]
opts.sort(key=lambda d: -d["p"])
o = env.obs()
return dict(seat=p, name=self.name(p), options=opts, equity=round(o["glob"][0, 4 + 18].item(), 3),
street=STREETS[int(env.street[0])])
# ---------------------------------------------------------------- state
def state(self, hint=False):
env, n = self.env, self.n
st = int(env.street[0])
done = bool(env.done[0])
cur = -1 if done else int(env.cur[0])
seats = []
for s in range(n):
show = (s == self.hero) or self.reveal or (done and self.result and self.result["showdown"]
and not env.folded[0, s])
seats.append(dict(
seat=s, name=self.name(s), stack=round(env.stack[0, s].item(), 2), bet=round(env.bet[0, s].item(), 2),
folded=bool(env.folded[0, s]), allin=bool(env.allin[0, s]),
cards=[card_str(c) for c in env.hole[0, s].tolist()] if show else None,
last=self.last[s], button=s == self.button, sb=s == self.sb, bb=s == self.bb,
profit=round(self.profit[s], 2), hero=s == self.hero))
d = dict(n=n, hero=self.hero, street=STREETS[st], board=[card_str(c) for c in env.board[0, :NREV[st]].tolist()]
if not done else [card_str(c) for c in env.board[0, :NREV[st] if not (self.result and self.result["showdown"]) else 5].tolist()],
pot=round(env.contrib[0].sum().item(), 2), cur=cur, done=done, seats=seats, log=self.log[-60:],
think=self.think, result=self.result, hands=self.hands, stack0=self.stack0)
if not done and cur == self.hero:
bet_p = env.bet[0, cur].item()
stk = env.stack[0, cur].item()
L = env.legal()[0]
to_call = max(env.max_bet[0].item() - bet_p, 0.0)
pot = env.contrib[0].sum().item()
d["hero_opts"] = dict(
to_call=round(min(to_call, stk), 2), can_fold=bool(L[0]), can_raise=bool(L[9]),
min_to=round(min(env.max_bet[0].item() + env.min_raise[0].item(), bet_p + stk), 2),
max_to=round(bet_p + stk, 2), pot=round(pot, 2), max_bet=round(env.max_bet[0].item(), 2),
bet_word="Bet" if env.max_bet[0].item() <= 1e-9 else "Raise")
if hint:
pr, _ = self.probs_for_current()
d["hint"] = self.think_info(cur, pr)
return d
class Handler(BaseHTTPRequestHandler):
game = None
def log_message(self, *a):
pass
def _send(self, code, body, ctype="application/json"):
b = body.encode() if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
if self.path.split("?")[0] in ("/", "/index.html"):
with open(os.path.join(HERE, "web", "index.html"), "rb") as f:
self._send(200, f.read(), "text/html; charset=utf-8")
else:
self._send(404, "not found", "text/plain")
def do_POST(self):
n = int(self.headers.get("Content-Length", 0) or 0)
req = json.loads(self.rfile.read(n) or b"{}")
g = self.game
try:
with g.lock:
if self.path == "/api/new_game":
g.new_game(req.get("players", 6), req.get("stack", 100), req.get("mode", "play"), req.get("reveal", False))
elif g.env is None:
g.new_game()
elif self.path == "/api/next_hand":
g.new_hand()
elif self.path == "/api/ai_step":
g.ai_step()
elif self.path == "/api/act":
g.hero_act(req.get("kind"), req.get("amount"))
elif self.path != "/api/state":
return self._send(404, "{}")
self._send(200, json.dumps(g.state(hint=bool(req.get("hint")))))
except Exception as e: # report errors to the page instead of crashing
import traceback
traceback.print_exc()
self._send(500, json.dumps(dict(error=str(e))))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default=None, help="caminho do .pt (padrão: model.pt do Hugging Face)")
ap.add_argument("--port", type=int, default=8765)
ap.add_argument("--no-browser", action="store_true")
a = ap.parse_args()
print("carregando modelo e avaliador de mãos...")
ai = PokerAI.load(a.model)
Handler.game = Game(ai, HandEvaluator("cpu"))
url = f"http://localhost:{a.port}"
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
print(f"pronto: {url} (Ctrl+C para sair)")
if not a.no_browser:
webbrowser.open(url)
srv.serve_forever()
if __name__ == "__main__":
main()