FEN-Extractor / app.py
Pratyush2502's picture
codebase
6e9ac7a verified
Raw History Blame Contribute Delete
3.65 kB
import streamlit as st
from PIL import Image
import os
import cv2
import numpy as np
from chess_fen import detect_board, PieceDetector, map_to_grid, grid_to_fen
# Emphasizing standard centered layout which is mobile-friendly
st.set_page_config(page_title="Chess FEN Extractor", layout="centered", page_icon="♟️")
st.title("♟️ Chess FEN Extractor")
st.markdown("Upload a screenshot of a chessboard to extract its Forsyth-Edwards Notation (FEN).")
# Ensure models directory exists
os.makedirs("models", exist_ok=True)
model_path = os.path.join("models", "best.pt")
if not os.path.exists(model_path):
st.error(f"⚠️ YOLOv8 model weights not found at `{model_path}`!")
st.info("Please download or place your trained `best.pt` file into the `models` directory to proceed.")
st.stop()
@st.cache_resource
def load_model_v2(conf):
return PieceDetector(model_path=model_path, conf=conf)
confidence = st.sidebar.slider("Detection Confidence", 0.1, 1.0, 0.5)
try:
detector = load_model_v2(confidence)
detector.conf = confidence
st.sidebar.success("🤖 YOLOv8 Model loaded successfully.")
except Exception as e:
st.error(f"Error loading model: {e}")
st.stop()
flipped = st.sidebar.checkbox("Black to play (Flipped Board)?", value=False)
uploaded_file = st.file_uploader("Upload Chessboard Image", type=["png", "jpg", "jpeg", "webp"])
if uploaded_file is not None:
image = Image.open(uploaded_file).convert('RGB')
# We remove side-by-side columns to make the UI vertically stacked and perfectly responsive on mobile phones.
st.subheader("Original Image")
st.image(image, width="stretch")
with st.spinner("Processing image..."):
try:
# Run YOLO on the full image first to see all pieces + board ROI
detections, yolo_board_box = detector.detect(image)
# Determine crop parameters
if yolo_board_box:
x, y, w, h = yolo_board_box
else:
_, (x, y, w, h) = detect_board(image)
# Shift pieces relative to the board top-left boundary
shifted_detections = []
for piece, cx, cy, conf in detections:
if x <= cx <= x + w and y <= cy <= y + h:
shifted_detections.append((piece, cx - x, cy - y, conf))
# 3. Map to grid
grid = map_to_grid(shifted_detections, board_w=w, board_h=h, flipped=flipped)
# 4. Assemble FEN
fen = grid_to_fen(grid, is_black_turn=flipped)
st.divider()
st.subheader("Detected Board & Pieces")
# Annotate the cropped board
img_cv = np.array(image)
# Crop purely for visual display
board_img_display = img_cv[int(y):int(y+h), int(x):int(x+w)]
for piece, cx, cy, conf in shifted_detections:
cv2.circle(board_img_display, (int(cx), int(cy)), 4, (0, 255, 0), -1)
cv2.putText(board_img_display, piece, (int(cx) - 10, int(cy) - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
st.image(board_img_display, channels="RGB", width="stretch")
st.subheader("Extracted FEN")
st.code(fen, language="text")
st.write(f"Detected **{len(shifted_detections)}** pieces on the board.")
st.success("Analysis complete!")
except Exception as e:
st.error(f"An error occurred during processing: {e}")