-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
370 lines (285 loc) · 10.6 KB
/
server.py
File metadata and controls
370 lines (285 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""AIguessr — web dashboard server.
Serves the React dashboard and proxies commands to the geo.py TCP server.
Handles autonomous play via Anthropic/OpenRouter APIs with parallel agents.
Usage:
python server.py — start dashboard on http://127.0.0.1:8080
python server.py --port 9090 — custom port
"""
import asyncio
import json
import os
import socket
import subprocess
import sys
from pathlib import Path
from dotenv import load_dotenv
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from brain import GeoBrain
from browser_detect import detect_browsers, launch_browser, is_cdp_available
from config import load_config, save_config
from match_tracker import MatchTracker
load_dotenv()
APP_DIR = Path(__file__).parent
SCREENSHOTS_DIR = APP_DIR / "screenshots"
DASHBOARD_DIST = APP_DIR / "dashboard" / "dist"
GEO_HOST = "127.0.0.1"
GEO_PORT = 5555
app = FastAPI(title="AIguessr Dashboard")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
ws_clients: list[WebSocket] = []
active_brain: GeoBrain | None = None
play_task: asyncio.Task | None = None
browser_process: subprocess.Popen | None = None
active_match: MatchTracker | None = None
def send_geo_command(cmd: str, timeout: float = 30) -> str:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((GEO_HOST, GEO_PORT))
s.sendall((cmd + "\n").encode())
data = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
s.close()
return data.decode().strip()
except ConnectionRefusedError:
return "ERROR geo.py server not running (start with: python geo.py serve)"
except socket.timeout:
return "ERROR command timed out"
except Exception as e:
return f"ERROR {e}"
async def broadcast(message: dict):
dead = []
for ws in ws_clients:
try:
await ws.send_json(message)
except Exception:
dead.append(ws)
for ws in dead:
ws_clients.remove(ws)
async def brain_event_handler(event_type: str, data: dict):
await broadcast({"type": "brain_event", "event": event_type, "data": data})
if event_type == "overlay_recommendation":
guess = data.get("guess", {})
overlay_data = json.dumps({
"country": guess.get("country", ""),
"country_navigation": guess.get("country_navigation", ""),
"region": guess.get("region", ""),
"region_position": guess.get("region_position", ""),
"pin_placement": guess.get("pin_placement", ""),
"confidence": guess.get("confidence", "low"),
})
await asyncio.to_thread(send_geo_command, "overlay_inject")
await asyncio.to_thread(send_geo_command, f"overlay_update {overlay_data}")
class CommandRequest(BaseModel):
command: str
class SettingsRequest(BaseModel):
provider: str
apiKey: str = ""
model: str = ""
class PlayRequest(BaseModel):
mode: str = "classic"
play_style: str = "aggressive"
@app.post("/api/command")
async def run_command(req: CommandRequest):
result = await asyncio.to_thread(send_geo_command, req.command)
await broadcast({"type": "log", "message": result, "level": "error" if result.startswith("ERROR") else "success"})
return {"result": result}
@app.get("/api/state")
async def get_state():
result = await asyncio.to_thread(send_geo_command, "state")
try:
return json.loads(result)
except json.JSONDecodeError:
return {"error": result}
@app.get("/api/screenshots/{filename}")
async def get_screenshot(filename: str):
path = SCREENSHOTS_DIR / filename
if not path.exists() or not path.is_file():
return JSONResponse({"error": "not found"}, status_code=404)
if not str(path.resolve()).startswith(str(SCREENSHOTS_DIR.resolve())):
return JSONResponse({"error": "forbidden"}, status_code=403)
return FileResponse(path, media_type="image/png")
@app.get("/api/health")
async def health():
geo_ok = await asyncio.to_thread(send_geo_command, "state")
return {
"server": "ok",
"geo_server": "ok" if not geo_ok.startswith("ERROR") else "disconnected",
"brain_active": active_brain is not None and active_brain.playing,
}
@app.post("/api/settings")
async def save_settings(req: SettingsRequest):
env_path = APP_DIR / ".env"
lines = []
if env_path.exists():
lines = env_path.read_text().splitlines()
env_vars = {
"GEOGUESSR_PROVIDER": req.provider,
"GEOGUESSR_MODEL": req.model,
}
if req.apiKey:
if req.provider == "anthropic":
env_vars["ANTHROPIC_API_KEY"] = req.apiKey
elif req.provider == "openrouter":
env_vars["OPENROUTER_API_KEY"] = req.apiKey
updated_keys = set()
new_lines = []
for line in lines:
key = line.split("=", 1)[0].strip() if "=" in line else ""
if key in env_vars:
new_lines.append(f"{key}={env_vars[key]}")
updated_keys.add(key)
else:
new_lines.append(line)
for key, val in env_vars.items():
if key not in updated_keys:
new_lines.append(f"{key}={val}")
env_path.write_text("\n".join(new_lines) + "\n")
for key, val in env_vars.items():
os.environ[key] = val
return {"status": "saved"}
@app.post("/api/play/start")
async def start_play(req: PlayRequest):
global active_brain, play_task
if active_brain and active_brain.playing:
return {"status": "already_playing"}
provider = os.environ.get("GEOGUESSR_PROVIDER", "anthropic")
model = os.environ.get("GEOGUESSR_MODEL", "claude-sonnet-4-6")
if provider == "anthropic":
api_key = os.environ.get("ANTHROPIC_API_KEY", "")
elif provider == "openrouter":
api_key = os.environ.get("OPENROUTER_API_KEY", "")
else:
return {"status": "error", "message": "Claude Code mode doesn't support autonomous play. Use Anthropic API or OpenRouter."}
if not api_key:
return {"status": "error", "message": f"No API key configured for {provider}. Go to Settings."}
active_brain = GeoBrain(provider, api_key, model)
active_brain.on_event(brain_event_handler)
duels = req.mode == "duels"
play_task = asyncio.create_task(active_brain.auto_play(duels=duels, play_style=req.play_style))
return {"status": "started", "mode": req.mode, "play_style": req.play_style}
@app.post("/api/play/stop")
async def stop_play():
global active_brain, play_task
if active_brain:
active_brain.stop()
if play_task and not play_task.done():
play_task.cancel()
try:
await play_task
except asyncio.CancelledError:
pass
active_brain = None
play_task = None
return {"status": "stopped"}
@app.get("/api/play/status")
async def play_status():
if active_brain and active_brain.playing:
return {"status": "playing", "mode": "duels" if active_brain.duels_mode else "classic"}
return {"status": "idle"}
@app.post("/api/duels/start")
async def duels_start():
return await start_play(PlayRequest(mode="duels"))
@app.post("/api/duels/stop")
async def duels_stop():
return await stop_play()
@app.get("/api/browsers")
async def list_browsers():
browsers = detect_browsers()
cdp_ok = is_cdp_available()
return {"browsers": browsers, "cdp_connected": cdp_ok}
@app.post("/api/browser/launch")
async def launch_browser_endpoint(req: dict):
global browser_process
path = req.get("path", "")
if not path:
return JSONResponse({"error": "No browser path provided"}, status_code=400)
browser_process = launch_browser(path)
return {"status": "launched", "pid": browser_process.pid}
@app.get("/api/browser/status")
async def browser_status():
cdp_ok = is_cdp_available()
running = browser_process is not None and browser_process.poll() is None
return {"cdp_connected": cdp_ok, "browser_running": running}
@app.get("/api/config")
async def get_config():
return load_config()
@app.put("/api/config")
async def update_config(req: dict):
config = load_config()
config.update(req)
config["first_run"] = False
save_config(config)
return {"status": "saved"}
@app.get("/api/match/stats")
async def match_stats():
return MatchTracker.get_stats()
@app.get("/api/match/history")
async def match_history():
return {"matches": MatchTracker.get_history()}
@app.get("/api/match/state")
async def match_state():
if active_match and active_match.active:
return active_match.get_state()
return {"active": False}
@app.get("/api/match/{match_id}")
async def match_detail(match_id: int):
match = MatchTracker.get_match(match_id)
if not match:
return JSONResponse({"error": "not found"}, status_code=404)
return match
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await ws.accept()
ws_clients.append(ws)
geo_result = await asyncio.to_thread(send_geo_command, "state")
geo_ok = not geo_result.startswith("ERROR")
await ws.send_json({
"type": "connection",
"status": "connected" if geo_ok else "disconnected",
})
try:
while True:
data = await ws.receive_text()
try:
msg = json.loads(data)
if msg.get("type") == "command":
result = await asyncio.to_thread(send_geo_command, msg["command"])
await ws.send_json({"type": "log", "message": result})
except json.JSONDecodeError:
pass
except WebSocketDisconnect:
pass
finally:
if ws in ws_clients:
ws_clients.remove(ws)
if DASHBOARD_DIST.exists():
app.mount("/assets", StaticFiles(directory=str(DASHBOARD_DIST / "assets")), name="assets")
@app.get("/{path:path}")
async def serve_spa(path: str):
file_path = DASHBOARD_DIST / path
if file_path.exists() and file_path.is_file():
return FileResponse(file_path)
return FileResponse(DASHBOARD_DIST / "index.html")
if __name__ == "__main__":
import uvicorn
port = 8080
if "--port" in sys.argv:
idx = sys.argv.index("--port")
port = int(sys.argv[idx + 1])
print(f"Dashboard: http://127.0.0.1:{port}")
print(f"Proxying commands to geo.py on {GEO_HOST}:{GEO_PORT}")
uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")