AGAZO_Final_Assignment / chess_image_to_fen_tool.py
Alexandre Gazola
fix
abffb61
raw
history blame
2.35 kB
from langchain_core.tools import tool
from image_to_text_tool import image_to_text
from utils import get_base64
from typing import Literal, Dict
from utils import get_base64
import requests
import json
@tool
def chess_image_to_fen(image_path_in_base64:str, current_player: Literal["black", "white"]) -> Dict[str,str]:
"""
Convert chess image to FEN (Forsyth-Edwards Notation) notation.
Args:
image_path_in_base64: Path to the image file in base64 format.
current_player: Whose turn it is to play. Must be either 'black' or 'white'.
Returns:
JSON with FEN (Forsyth-Edwards Notation) string representing the current board position.
"""
print(f"Image to Fen invocada com os seguintes parametros:")
print(f"image_path: {image_path_in_base64}")
print(f"current_player: {current_player}")
CHESSVISION_TO_FEN_URL = "http://app.chessvision.ai/predict"
if current_player not in ["black", "white"]:
raise ValueError("current_player must be 'black' or 'white'")
print('Reading chess image in base 64: ' + image_path_in_base64)
base64_image = get_base64(image_path_in_base64)
print("content in base64:\n\n" + base64_image)
if not base64_image:
raise ValueError("Failed to encode image to base64.")
base64_image_encoded = f"data:image/png;base64,{base64_image}"
url = CHESSVISION_TO_FEN_URL
payload = {
"board_orientation": "predict",
"cropped": False,
"current_player": current_player,
"image": base64_image_encoded,
"predict_turn": False
}
response = requests.post(url, json=payload)
if response.status_code == 200:
dados = response.json()
if dados.get("success"):
print(f"Retorno Chessvision {dados}")
fen = dados.get("result")
fen = fen.replace("_", " ") #retorna _ no lugar de espaço em branco
return json.dumps({"fen": fen})
else:
raise Exception("Requisição feita, mas falhou na predição.")
else:
print("Deu erro na chamada a API para obtencao do FEN: " + response.text)
return {
"fen": "3r2k1/pp3pp1/4b2p/7Q/3n4/PqBBR2P/5PP1/6K1 b - - 0 1",
"current_player": "black",
"status": "ongoing"
}