Taperx commited on
Commit
96f9c6a
·
verified ·
1 Parent(s): 9ccd1bc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -0
app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import threading
4
+ import json
5
+ import requests
6
+ import gradio as gr
7
+
8
+ LICHESS_TOKEN = os.environ.get("LICHESS_TOKEN")
9
+ ENGINE_PATH = "./veloct"
10
+
11
+ def compile_engine():
12
+ print("Compiling engine locally inside Hugging Face runtime...")
13
+ try:
14
+ if os.path.exists(ENGINE_PATH):
15
+ return
16
+
17
+ compile_cmd = [
18
+ "g++", "-O3", "-std=c++17", "-DNDEBUG", "-DUSE_PTHREADS",
19
+ "-pthread", "veloct.cpp", "-o", "veloct", "-latomic"
20
+ ]
21
+ result = subprocess.run(compile_cmd, capture_output=True, text=True)
22
+ if result.returncode == 0:
23
+ print("Engine compiled successfully!")
24
+ os.chmod(ENGINE_PATH, 0o755)
25
+ else:
26
+ print(f"Compilation failed:\n{result.stderr}")
27
+ except Exception as e:
28
+ print(f"Compilation error: {e}")
29
+
30
+ def send_move(game_id, move):
31
+ url = f"https://lichess.org/api/bot/game/{game_id}/move/{move}"
32
+ headers = {"Authorization": f"Bearer {LICHESS_TOKEN}"}
33
+ requests.post(url, headers=headers)
34
+
35
+ def engine_think(game_id, fen, moves_string):
36
+ try:
37
+ proc = subprocess.Popen(
38
+ [ENGINE_PATH], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1
39
+ )
40
+ proc.stdin.write("uci\n")
41
+ proc.stdin.write("isready\n")
42
+
43
+ pos_cmd = f"position fen {fen}" if fen else "position startpos"
44
+ if moves_string:
45
+ pos_cmd += f" moves {moves_string}"
46
+
47
+ proc.stdin.write(f"{pos_cmd}\n")
48
+ proc.stdin.write("go movetime 1500\n")
49
+ proc.stdin.flush()
50
+
51
+ while True:
52
+ line = proc.stdout.readline()
53
+ if not line:
54
+ break
55
+ if line.startswith("bestmove"):
56
+ best_move = line.split()[1]
57
+ if best_move != "(none)":
58
+ send_move(game_id, best_move)
59
+ break
60
+ proc.terminate()
61
+ except Exception as e:
62
+ print(f"Engine execution error: {e}")
63
+
64
+ def stream_game(game_id):
65
+ url = f"https://lichess.org/api/bot/game/stream/{game_id}"
66
+ headers = {"Authorization": f"Bearer {LICHESS_TOKEN}"}
67
+ response = requests.get(url, headers=headers, stream=True)
68
+
69
+ fen = None
70
+ for line in response.iter_lines():
71
+ if line:
72
+ event = json.loads(line.decode('utf-8'))
73
+ if event.get("type") == "gameFull":
74
+ fen = event.get("initialFen")
75
+ state = event.get("state")
76
+ else:
77
+ state = event
78
+
79
+ moves = state.get("moves", "")
80
+ moves_list = moves.split() if moves else []
81
+
82
+ if len(moves_list) % 2 == 0:
83
+ threading.Thread(target=engine_think, args=(game_id, fen, moves)).start()
84
+
85
+ def listen_events():
86
+ url = "https://lichess.org/api/stream/event"
87
+ headers = {"Authorization": f"Bearer {LICHESS_TOKEN}"}
88
+ print("Connecting to Lichess Bot Stream API...")
89
+
90
+ try:
91
+ response = requests.get(url, headers=headers, stream=True)
92
+ for line in response.iter_lines():
93
+ if line:
94
+ event = json.loads(line.decode('utf-8'))
95
+ if event.get("type") == "challenge":
96
+ challenge_id = event["challenge"]["id"]
97
+ requests.post(f"https://lichess.org/api/challenge/{challenge_id}/accept", headers=headers)
98
+ elif event.get("type") == "gameStart":
99
+ game_id = event["game"]["id"]
100
+ threading.Thread(target=stream_game, args=(game_id,)).start()
101
+ except Exception as e:
102
+ print(f"Stream error: {e}")
103
+
104
+ if LICHESS_TOKEN:
105
+ compile_engine()
106
+ threading.Thread(target=listen_events, daemon=True).start()
107
+ else:
108
+ print("Warning: LICHESS_TOKEN missing.")
109
+
110
+ with gr.Blocks() as demo:
111
+ gr.Markdown("# 🤖 VeloCT Engine Lichess Bot")
112
+ gr.Markdown("Status: Running execution loop in background runtime container.")
113
+
114
+ demo.launch()