TanujInsane commited on
Commit
b1dec00
·
1 Parent(s): 1c58b85

fix: add uv.lock and server/app.py for openenv validate

Browse files
Files changed (2) hide show
  1. server/app.py +97 -0
  2. uv.lock +0 -0
server/app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.responses import JSONResponse
5
+ from environment import DocumentClassificationEnv
6
+
7
+ def sanitize(obj):
8
+ import numpy as np
9
+ if isinstance(obj, dict):
10
+ return {k: sanitize(v) for k, v in obj.items()}
11
+ elif isinstance(obj, (list, tuple)):
12
+ return [sanitize(i) for i in obj]
13
+ elif isinstance(obj, np.integer):
14
+ return int(obj)
15
+ elif isinstance(obj, np.floating):
16
+ return float(obj)
17
+ elif isinstance(obj, np.ndarray):
18
+ return obj.tolist()
19
+ elif isinstance(obj, np.bool_):
20
+ return bool(obj)
21
+ else:
22
+ return obj
23
+
24
+ def ensure_models():
25
+ """Train and persist ML models before starting servers."""
26
+ from baseline_inference import load_or_train
27
+ print("[startup] Pre-training classification models...")
28
+ for difficulty in ["easy", "medium", "hard"]:
29
+ load_or_train(difficulty)
30
+ print(f"[startup] {difficulty} model ready!")
31
+ print("[startup] All models ready!")
32
+
33
+ # Step 1: pre-train models (blocking, needed before server starts)
34
+ ensure_models()
35
+
36
+ app = FastAPI()
37
+ api_envs = {}
38
+
39
+ import traceback
40
+
41
+ @app.api_route("/reset", methods=["GET", "POST"])
42
+ async def reset_route(request: Request):
43
+ try:
44
+ try:
45
+ data = await request.json()
46
+ except Exception:
47
+ data = {}
48
+ data = data or {}
49
+ difficulty = data.get("difficulty", "easy") if data else "easy"
50
+ seed = data.get("seed", 42) if data else 42
51
+
52
+ env = DocumentClassificationEnv(task_difficulty=difficulty, seed=seed)
53
+ obs, _ = env.reset(seed=seed)
54
+ api_envs["current"] = env
55
+
56
+ return JSONResponse(content=sanitize({"observation": dict(obs)}))
57
+
58
+ except Exception as e:
59
+ return JSONResponse({"error": str(e), "traceback": traceback.format_exc()}, status_code=500)
60
+
61
+
62
+ @app.post("/step")
63
+ async def step_route(request: Request):
64
+ try:
65
+ try:
66
+ data = await request.json()
67
+ except Exception:
68
+ data = {}
69
+ data = data or {}
70
+ action_val = data.get("action", 0)
71
+
72
+ if "current" not in api_envs:
73
+ return JSONResponse(status_code=400, content={"error": "Environment not initialized"})
74
+
75
+ env = api_envs["current"]
76
+ obs, reward, done, _, info = env.step(action_val)
77
+
78
+ return JSONResponse(content=sanitize({"observation": dict(obs), "reward": reward, "done": done, "info": info}))
79
+
80
+ except Exception as e:
81
+ return JSONResponse({"error": str(e), "traceback": traceback.format_exc()}, status_code=500)
82
+
83
+ @app.get("/state")
84
+ async def state_route():
85
+ if "current" not in api_envs:
86
+ return JSONResponse(status_code=400, content={"error": "Environment not initialized"})
87
+ env = api_envs["current"]
88
+ state = env.state()
89
+ return JSONResponse(content=sanitize(state))
90
+
91
+ if __name__ == "__main__":
92
+ import uvicorn
93
+ # When run standalone (e.g. local dev or docker), defaults to 7860.
94
+ port = int(os.environ.get("PORT", "7860"))
95
+ print(f"Starting FastAPI (OpenEnv API) on port {port}...")
96
+ uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
97
+
uv.lock ADDED
The diff for this file is too large to render. See raw diff