| import requests | |
| import json | |
| import base64 | |
| def get_base64(file_path: str) -> str: | |
| with open(file_path, "rb") as f: | |
| base64_data = base64.b64encode(f.read()).decode('utf-8') | |
| return base64_data | |
| def fen_notation(image_path:str, current_player:str)->str: | |
| chessvisionai_url = "http://app.chessvision.ai/predict" | |
| base64_image = get_base64(image_path) | |
| base64_image_encoded = f"data:image/png;base64,{base64_image}" | |
| current_player = 'black' | |
| if current_player not in ["black", "white"]: | |
| raise ValueError("current_player must be 'black' or 'white'") | |
| payload = { | |
| "board_orientation": "predict", | |
| "cropped": False, | |
| "current_player": current_player, | |
| "image": base64_image_encoded, | |
| "predict_turn": False | |
| } | |
| response = requests.post(chessvisionai_url | |
| , json=payload) | |
| if response.status_code == 200: | |
| fen_notation = response.json()['result'].replace('_', ' ') | |
| return fen_notation | |
| else: | |
| raise Exception('Error retrieving fen' + response.status_code + response.text) | |
| def chess_analysis(fen_notation:str)->str: | |
| chess_api = "https://chess-api.com/v1" | |
| url = chess_api | |
| payload = { | |
| "fen": fen_notation | |
| } | |
| chess_response = requests.post(url, json=payload) | |
| if chess_response.status_code == 200: | |
| best_move = chess_response.json().get('san') | |
| return best_move | |
| else: | |
| raise Exception(f'Error occurred {chess_response.status_code} {chess_response.text}') | |