FEN-Extractor / cli.py
Pratyush2502's picture
codebase
6e9ac7a verified
Raw History Blame Contribute Delete
2.16 kB
import click
from PIL import Image
from chess_fen import detect_board, PieceDetector, map_to_grid, grid_to_fen
import os
@click.command()
@click.option('--image', type=click.Path(exists=True), required=True, help="Path to input screenshot")
@click.option('--model', type=click.Path(), default="models/best.pt", help="Path to YOLOv8 weights")
@click.option('--flipped', is_flag=True, help="Is the board flipped (black at bottom)?")
@click.option('--conf', type=float, default=0.5, help="Confidence threshold")
@click.option('--output', type=click.Path(), default=None, help="Save FEN to this file")
def main(image, model, flipped, conf, output):
"""Extract FEN from a chessboard screenshot."""
if not os.path.exists(model):
click.echo(f"Error: Model not found at '{model}'", err=True)
return
try:
img = Image.open(image).convert('RGB')
click.echo("Loaded image...")
detector = PieceDetector(model_path=model, conf=conf)
detections, yolo_board_box = detector.detect(img)
if yolo_board_box:
x, y, w, h = yolo_board_box
click.echo(f"Detected board natively via YOLO at x={int(x)}, y={int(y)}, w={int(w)}, h={int(h)}")
else:
_, (x, y, w, h) = detect_board(img)
click.echo(f"Detected board via OpenCV at x={x}, y={y}, w={w}, h={h}")
shifted_detections = []
for p, cx, cy, cnf in detections:
if x <= cx <= x + w and y <= cy <= y + h:
shifted_detections.append((p, cx - x, cy - y, cnf))
click.echo(f"Mapped {len(shifted_detections)} pieces securely inside the board boundaries.")
grid = map_to_grid(shifted_detections, board_w=w, board_h=h, flipped=flipped)
fen = grid_to_fen(grid, is_black_turn=flipped)
click.secho(f"\nFEN: {fen}\n", fg='green', bold=True)
if output:
with open(output, 'w') as f:
f.write(fen)
click.echo(f"Saved FEN to {output}")
except Exception as e:
click.echo(f"An error occurred: {e}", err=True)
if __name__ == '__main__':
main()