File size: 2,157 Bytes
6e9ac7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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()