poker-table-perception-eval / render_tables.py
ThreeSixNine's picture
Upload render_tables.py with huggingface_hub
e51f92e verified
Raw History Blame Contribute Delete
8.54 kB
"""Generate perfectly-labeled synthetic poker table screenshots for perception evals.
Outputs:
dataset/images/test_XXX.png (1600x900)
dataset/labels/test_XXX.json (ground truth: cards, stacks, pot, bboxes)
Everything is deterministic given --seed. Labels use "A♠"-style card strings
and pixel-space bounding boxes. No redistribution concerns: all pixels are ours.
"""
import argparse
import json
import math
import os
import random
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
W, H = 1600, 900
RANKS = ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"]
SUITS = ["♠", "♥", "♦", "♣"]
RED_SUITS = {"♥", "♦"}
POSITIONS = {2: ["BTN", "SB", ], # completed later: BB
3: ["BTN", "SB", "BB"],
4: ["BTN", "SB", "BB", "UTG"],
5: ["BTN", "SB", "BB", "MP", "UTG"],
6: ["BTN", "SB", "BB", "MP", "MP2", "UTG"]}
def _font(size, bold=True):
for name in ("DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf",
"LiberationSans-Bold.ttf" if bold else "LiberationSans-Regular.ttf"):
for d in ("/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/truetype/liberation"):
p = os.path.join(d, name)
if os.path.exists(p):
return ImageFont.truetype(p, size)
try:
return ImageFont.load_default(size=size)
except TypeError:
return ImageFont.load_default()
FONT_CARD = _font(34)
FONT_SUIT = _font(58)
FONT_UI = _font(22)
FONT_UI_BIG = _font(30)
def _rand_deck(rng):
deck = [(r, s) for r in RANKS for s in SUITS]
rng.shuffle(deck)
return deck
def _card_str(card):
r, s = card
return r + s
def render_card(canvas, x, y, card, w=84, h=118, cid=None, labels=None):
"""Draw one face-up card at (x, y) top-left. Records pixel bbox."""
r, s = card
draw = ImageDraw.Draw(canvas)
draw.rounded_rectangle([x, y, x + w, y + h], radius=8, fill=(248, 248, 245),
outline=(40, 40, 40), width=2)
color = (200, 30, 30) if s in RED_SUITS else (20, 20, 20)
draw.text((x + 6, y + 4), r, font=FONT_CARD, fill=color)
draw.text((x + 6, y + 34), s, font=FONT_CARD, fill=color)
draw.text((x + w - 40, y + h - 66), s, font=FONT_SUIT, fill=color)
if labels is not None:
labels["card_bboxes"].append({"card": _card_str(card), "bbox": [x, y, x + w, y + h],
"where": cid})
def generate_one(idx, rng, race=0):
n_players = rng.choice([2, 3, 4, 5, 6])
deck = _rand_deck(rng)
stage = rng.choice(["preflop", "flop", "turn", "river"])
n_board = {"preflop": 0, "flop": 3, "turn": 4, "river": 5}[stage]
pos_order = POSITIONS[n_players][:] if n_players > 2 else ["BTN", "SB/BB"]
pos_order = (pos_order + ["BB"])[:n_players]
pos_order = ["UTG"] + pos_order[:-1] if n_players >= 4 else pos_order
pot = rng.choice([40, 80, 120, 240, 500, 1250, 3400])
labels = {
"image": f"test_{idx:03d}.png", "width": W, "height": H,
"stage": stage, "pot": pot, "seats": [],
"community": [], "card_bboxes": [],
}
canvas = Image.new("RGB", (W, H), (18, 92, 46))
draw = ImageDraw.Draw(canvas)
# felt shading rings for a bit of texture
cx, cy = W // 2, H // 2 + 30
draw.ellipse([cx - 560, cy - 300, cx + 560, cy + 300], fill=(24, 104, 52))
draw.ellipse([cx - 460, cy - 240, cx + 460, cy + 240], fill=(30, 116, 60))
# board cards (center upper area); unrevealed slots left blank
board = [deck.pop() for _ in range(n_board)]
bw, bh = 92, 130
total_w = 5 * (bw + 12)
bx0 = cx - total_w // 2
for i, card in enumerate(board):
bx = bx0 + i * (bw + 12)
render_card(canvas, bx, 250, card, bw, bh, cid=f"board_{i}", labels=labels)
labels["community"].append({"card": _card_str(card), "bbox": [bx, 250, bx + bw, 250 + bh]})
# hero cards, center bottom, slightly larger
hero = [deck.pop(), deck.pop()]
for i, card in enumerate(hero):
hx = cx - bw - 10 + i * (bw + 20)
render_card(canvas, hx, 640, card, bw + 10, bh + 14, cid="hero",
labels=labels)
labels["hero"] = [_card_str(hero[0]), _card_str(hero[1])]
# pot text
pot_y = 430
draw = ImageDraw.Draw(canvas)
draw.text((cx - 70, pot_y), f"POT: {pot}", font=FONT_UI_BIG, fill=(245, 235, 200))
labels["pot_bbox"] = [cx - 90, pot_y - 6, cx + 120, pot_y + 40]
# seats around the ellipse, alternating left/right/top/bottom
seat_angles = [(90 + 360 * i / n_players) for i in range(n_players)]
names = ["Alice", "Bob", "Clara", "Dan", "Eve", "Flo"]
for i, ang in enumerate(seat_angles):
sx = cx + int(500 * math.cos(math.radians(ang))) - 90
sy = cy + int(265 * math.sin(math.radians(ang))) - 40
sy = min(max(sy, 40), H - 130)
sx = min(max(sx, 20), W - 220)
stack = rng.choice([500, 900, 1800, 4200, 12000])
seat_label = pos_order[i % len(pos_order)]
seat_cards = [deck.pop(), deck.pop()]
slot = {"seat": i, "name": names[i], "stack": stack, "position": seat_label,
"hole": [_card_str(seat_cards[0]), _card_str(seat_cards[1])],
"card_bboxes": []}
# two cards per seat
for j, card in enumerate(seat_cards):
jx = sx + j * 92
if sy > cy: # bottom seats: cards above the name plate
card_y = sy - 10
else:
card_y = sy + 34
render_card(canvas, jx, card_y, seat_cards[j] if False else card,
cid=f"seat{i}", labels={"card_bboxes": labels["card_bboxes"]})
labels["card_bboxes"][-1]["where"] = f"seat{i}"
slot["card_bboxes"].append(labels["card_bboxes"][-1])
# name plate with stack
draw = ImageDraw.Draw(canvas)
plate_y = sy if sy > cy else sy
draw.rounded_rectangle([sx - 6, plate_y, sx + 200, plate_y + 30], radius=6,
fill=(40, 40, 60), outline=(10, 10, 10), width=1)
draw.text((sx + 2, plate_y + 3), f"{names[i]} [{seat_label}]", font=FONT_UI,
fill=(235, 235, 235))
draw.text((sx + 118, plate_y + 3), f"STACK {stack}", font=FONT_UI,
fill=(255, 215, 120))
slot["bbox"] = [sx - 6, plate_y, sx + 200, plate_y + 30]
# optional bet circle
if rng.random() < 0.5:
bet = rng.choice([20, 40, 60, 120, 300, 720])
draw.ellipse([sx - 70, plate_y + 34, sx + 40, plate_y + 74],
fill=(220, 180, 40), outline=(120, 90, 10), width=2)
draw.text((sx - 62, plate_y + 44), f"{bet}", font=FONT_UI, fill=(40, 30, 5))
slot["bet"] = bet
labels["seats"].append(slot)
# dealer button
bi = rng.randrange(n_players)
ang = seat_angles[bi]
dx = cx + int(430 * math.cos(math.radians(ang)))
dy = cy + int(225 * math.sin(math.radians(ang)))
draw.ellipse([dx - 16, dy - 16, dx + 16, dy + 16], fill=(235, 235, 235),
outline=(60, 60, 60), width=2)
draw.text((dx - 7, dy - 12), "D", font=FONT_UI, fill=(20, 20, 20))
labels["dealer_seat"] = bi
# mild noise so OCR isn't trivially easy
for _ in range(900):
npx = (rng.randrange(0, W), rng.randrange(0, H))
g = rng.randrange(140, 220)
draw.point(npx, fill=(g, g, g))
return canvas, labels
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="dataset")
ap.add_argument("--n", type=int, default=60)
ap.add_argument("--seed", type=int, default=17)
args = ap.parse_args()
rng = random.Random(args.seed)
img_dir = Path(args.out) / "images"
lbl_dir = Path(args.out) / "labels"
img_dir.mkdir(parents=True, exist_ok=True)
lbl_dir.mkdir(parents=True, exist_ok=True)
deck_check = []
for i in range(args.n):
img, labels = generate_one(i, rng)
img.save(img_dir / labels["image"], quality=92)
(lbl_dir / (labels["image"].replace(".png", ".json"))).write_text(
json.dumps(labels, indent=1))
ncards = len(labels["card_bboxes"])
deck_check.append(ncards)
if i < 3:
print(f"test_{i:03d}: {ncards} cards, {len(labels['seats'])} seats, "
f"stage={labels['stage']}, pot={labels['pot']}")
print(f"done: {args.n} images; cards/image avg={sum(deck_check)/len(deck_check):.1f}")
if __name__ == "__main__":
main()