from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware import chess.engine import chess.pgn import io import os app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) # Sử dụng đường dẫn chính xác của Stockfish engine_path = "/usr/local/bin/stockfish" engine = chess.engine.SimpleEngine.popen_uci(engine_path) @app.post("/analyze") async def analyze(pgn: str): try: pgn_io = io.StringIO(pgn) game = chess.pgn.read_game(pgn_io) board = game.board() results = [] for move in game.mainline_moves(): board.push(move) info = engine.analyse(board, chess.engine.Limit(depth=18)) results.append({ "move": board.san(move), "score": str(info["score"].relative), "pv": str(info.get("pv", "")) }) return {"status": "ok", "analysis": results} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/") def root(): return {"status": "ok", "engine": "Stockfish 16"}