VaiVas commited on
Commit
4e2d608
·
verified ·
1 Parent(s): d19f083

Update server/app.py

Browse files
Files changed (1) hide show
  1. server/app.py +74 -31
server/app.py CHANGED
@@ -1,14 +1,13 @@
1
  from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel, Field
3
  from typing import Dict, List, Optional, Any
4
  import ast
5
  import uuid
6
- import time
7
  import threading
8
- import os
9
- from tasks import TASKS # Import the tasks we just defined
10
  import uvicorn
11
- import jsonify
 
12
 
13
  class CodeMigrationAction(BaseModel):
14
  func_id: str
@@ -23,6 +22,8 @@ class CodeMigrationObservation(BaseModel):
23
  class Reward(BaseModel):
24
  value: float
25
 
 
 
26
  class CodeMigrationEnv:
27
  def __init__(self, task_config: Dict):
28
  self.config = task_config
@@ -40,30 +41,63 @@ class CodeMigrationEnv:
40
  names = [n.name for n in node.names]
41
  if any(name.startswith(source_prefix) for name in names): return True
42
  if isinstance(node, ast.ImportFrom) and node.module and node.module.startswith(source_prefix): return True
43
- return source_prefix in code_str # String fallback for safety
44
  except: return True
45
 
46
- def step(self, action: CodeMigrationAction):
47
- if action.func_id not in self.pending:
48
- return self.state(), Reward(value=-0.1), False, {"error": "Invalid ID"}
49
-
 
 
 
 
 
 
 
 
50
  try:
51
- ast.parse(action.rewritten_code)
52
- if self._uses_old_library(action.rewritten_code):
53
- reward = -0.2
54
- self.last_error = f"Still uses {self.config['source_lib']}"
 
55
  else:
56
- reward = 1.0
57
- self.completed.append(action.func_id)
58
- del self.pending[action.func_id]
59
- self.last_error = None
 
 
 
 
 
 
 
 
 
 
 
 
60
  except SyntaxError as e:
61
- reward = -0.5
62
  self.last_error = f"Syntax Error: {e}"
 
63
 
64
- self.cumulative_reward += reward
 
 
 
 
 
 
 
 
 
 
 
 
65
  done = len(self.pending) == 0
66
- return self.state(), Reward(value=reward), done, {}
67
 
68
  def state(self) -> CodeMigrationObservation:
69
  return CodeMigrationObservation(
@@ -73,16 +107,14 @@ class CodeMigrationEnv:
73
  last_error=self.last_error
74
  )
75
 
 
 
76
  app = FastAPI()
77
  sessions: Dict[str, Dict] = {}
78
  _lock = threading.Lock()
79
 
80
  @app.get("/")
81
  def ping():
82
- """
83
- Automated ping to the Space URL.
84
- Must return 200 OK.
85
- """
86
  return {"status": "ok", "message": "space is running"}
87
 
88
  @app.post("/reset")
@@ -91,30 +123,41 @@ def reset(task_id: str = "task_easy"):
91
  env = CodeMigrationEnv(TASKS[task_id])
92
  sid = str(uuid.uuid4())
93
  with _lock: sessions[sid] = {"env": env, "rewards": []}
94
- return {"session_id": sid, "observation": env.state().dict()}
95
 
96
  @app.post("/step")
97
  def step(session_id: str, action: CodeMigrationAction):
98
  with _lock:
99
  if session_id not in sessions: raise HTTPException(404)
100
  env = sessions[session_id]["env"]
 
101
  obs, reward, done, info = env.step(action)
 
102
  with _lock: sessions[session_id]["rewards"].append(reward.value)
103
- return {"observation": obs.dict(), "reward": reward.dict(), "done": done, "info": info}
104
 
105
  @app.get("/grader")
106
  def grader(session_id: str):
107
  with _lock:
108
  session = sessions.get(session_id)
109
  if not session: raise HTTPException(404)
 
110
  total = sum(session["rewards"])
111
  n_funcs = len(TASKS[session["env"].config["id"]]["functions"])
112
- return {"score": max(0.02, min(0.98, total/n_funcs)), "success": len(session["env"].pending) == 0}
 
 
 
 
 
 
 
 
113
 
114
  def main():
115
- """Entry point for openenv server mode."""
116
- uvicorn.run(app, host="0.0.0.0", port=7860)
117
-
118
 
119
  if __name__ == "__main__":
120
  main()
 
1
  from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
  from typing import Dict, List, Optional, Any
4
  import ast
5
  import uuid
 
6
  import threading
7
+ from tasks import TASKS
 
8
  import uvicorn
9
+
10
+ # --- Models ---
11
 
12
  class CodeMigrationAction(BaseModel):
13
  func_id: str
 
22
  class Reward(BaseModel):
23
  value: float
24
 
25
+ # --- Environment ---
26
+
27
  class CodeMigrationEnv:
28
  def __init__(self, task_config: Dict):
29
  self.config = task_config
 
41
  names = [n.name for n in node.names]
42
  if any(name.startswith(source_prefix) for name in names): return True
43
  if isinstance(node, ast.ImportFrom) and node.module and node.module.startswith(source_prefix): return True
44
+ return source_prefix in code_str
45
  except: return True
46
 
47
+ def calculate_complex_reward(self, old_code: str, new_code: str) -> float:
48
+ """
49
+ Evaluates migration quality:
50
+ - Base success: +1.0
51
+ - Async alignment: +/- 0.5
52
+ - Context manager usage: +0.3
53
+ - Syntax/Library Errors: Penalties
54
+ Max possible per function: 1.8
55
+ """
56
+ target_lib = self.config["target_lib"]
57
+ reward = 0.0
58
+
59
  try:
60
+ new_tree = ast.parse(new_code)
61
+
62
+ # 1. Base Success: Check if old library is gone
63
+ if not self._uses_old_library(new_code):
64
+ reward += 1.0
65
  else:
66
+ self.last_error = f"Still uses {self.config['source_lib']}"
67
+ return -0.2
68
+
69
+ # 2. Paradigm Check: Async usage for Async targets
70
+ is_async_target = "async" in target_lib.lower()
71
+ has_await = any(isinstance(node, ast.Await) for node in ast.walk(new_tree))
72
+ if is_async_target:
73
+ reward += 0.5 if has_await else -0.5
74
+
75
+ # 3. Best Practice: Using 'with' blocks (context managers)
76
+ if any(isinstance(node, (ast.With, ast.AsyncWith)) for node in ast.walk(new_tree)):
77
+ reward += 0.3
78
+
79
+ self.last_error = None
80
+ return round(reward, 2)
81
+
82
  except SyntaxError as e:
 
83
  self.last_error = f"Syntax Error: {e}"
84
+ return -0.8
85
 
86
+ def step(self, action: CodeMigrationAction):
87
+ if action.func_id not in self.pending:
88
+ return self.state(), Reward(value=-0.1), False, {"error": "Invalid ID"}
89
+
90
+ old_code = self.pending[action.func_id]["code"]
91
+ reward_value = self.calculate_complex_reward(old_code, action.rewritten_code)
92
+
93
+ # Move to completed only if functional success was achieved (reward > 0)
94
+ if reward_value > 0:
95
+ self.completed.append(action.func_id)
96
+ del self.pending[action.func_id]
97
+
98
+ self.cumulative_reward += reward_value
99
  done = len(self.pending) == 0
100
+ return self.state(), Reward(value=reward_value), done, {}
101
 
102
  def state(self) -> CodeMigrationObservation:
103
  return CodeMigrationObservation(
 
107
  last_error=self.last_error
108
  )
109
 
110
+ # --- FastAPI App ---
111
+
112
  app = FastAPI()
113
  sessions: Dict[str, Dict] = {}
114
  _lock = threading.Lock()
115
 
116
  @app.get("/")
117
  def ping():
 
 
 
 
118
  return {"status": "ok", "message": "space is running"}
119
 
120
  @app.post("/reset")
 
123
  env = CodeMigrationEnv(TASKS[task_id])
124
  sid = str(uuid.uuid4())
125
  with _lock: sessions[sid] = {"env": env, "rewards": []}
126
+ return {"session_id": sid, "observation": env.state().model_dump()}
127
 
128
  @app.post("/step")
129
  def step(session_id: str, action: CodeMigrationAction):
130
  with _lock:
131
  if session_id not in sessions: raise HTTPException(404)
132
  env = sessions[session_id]["env"]
133
+
134
  obs, reward, done, info = env.step(action)
135
+
136
  with _lock: sessions[session_id]["rewards"].append(reward.value)
137
+ return {"observation": obs.model_dump(), "reward": reward.model_dump(), "done": done, "info": info}
138
 
139
  @app.get("/grader")
140
  def grader(session_id: str):
141
  with _lock:
142
  session = sessions.get(session_id)
143
  if not session: raise HTTPException(404)
144
+
145
  total = sum(session["rewards"])
146
  n_funcs = len(TASKS[session["env"].config["id"]]["functions"])
147
+
148
+ # Ceiling: 1.0 (base) + 0.5 (async) + 0.3 (best practice) = 1.8 max per function
149
+ max_possible = n_funcs * 1.8
150
+ score = total / max_possible if max_possible > 0 else 0
151
+
152
+ return {
153
+ "score": max(0.02, min(0.98, score)),
154
+ "success": len(session["env"].pending) == 0
155
+ }
156
 
157
  def main():
158
+ import os
159
+ port = int(os.environ.get("PORT", 7860))
160
+ uvicorn.run(app, host="0.0.0.0", port=port)
161
 
162
  if __name__ == "__main__":
163
  main()