Spaces:
Sleeping
Sleeping
Commit ·
36ee706
1
Parent(s): ad68238
added chess file
Browse files
chess.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
import base64
|
| 4 |
+
|
| 5 |
+
def get_base64(file_path: str) -> str:
|
| 6 |
+
with open(file_path, "rb") as f:
|
| 7 |
+
base64_data = base64.b64encode(f.read()).decode('utf-8')
|
| 8 |
+
return base64_data
|
| 9 |
+
|
| 10 |
+
def fen_notation(image_path:str, current_player:str)->str:
|
| 11 |
+
chessvisionai_url = "http://app.chessvision.ai/predict"
|
| 12 |
+
base64_image = get_base64(image_path)
|
| 13 |
+
base64_image_encoded = f"data:image/png;base64,{base64_image}"
|
| 14 |
+
current_player = 'black'
|
| 15 |
+
if current_player not in ["black", "white"]:
|
| 16 |
+
raise ValueError("current_player must be 'black' or 'white'")
|
| 17 |
+
payload = {
|
| 18 |
+
"board_orientation": "predict",
|
| 19 |
+
"cropped": False,
|
| 20 |
+
"current_player": current_player,
|
| 21 |
+
"image": base64_image_encoded,
|
| 22 |
+
"predict_turn": False
|
| 23 |
+
}
|
| 24 |
+
response = requests.post(chessvisionai_url
|
| 25 |
+
, json=payload)
|
| 26 |
+
if response.status_code == 200:
|
| 27 |
+
fen_notation = response.json()['result'].replace('_', ' ')
|
| 28 |
+
return fen_notation
|
| 29 |
+
else:
|
| 30 |
+
raise Exception('Error retrieving fen' + response.status_code + response.text)
|
| 31 |
+
|
| 32 |
+
def chess_analysis(fen_notation:str)->str:
|
| 33 |
+
chess_api = "https://chess-api.com/v1"
|
| 34 |
+
url = chess_api
|
| 35 |
+
payload = {
|
| 36 |
+
"fen": fen_notation
|
| 37 |
+
}
|
| 38 |
+
chess_response = requests.post(url, json=payload)
|
| 39 |
+
if chess_response.status_code == 200:
|
| 40 |
+
best_move = chess_response.json().get('san')
|
| 41 |
+
return best_move
|
| 42 |
+
else:
|
| 43 |
+
raise Exception(f'Error occurred {chess_response.status_code} {chess_response.text}')
|
| 44 |
+
|