M ShreeRaj commited on
Refactor main.py for OpenEnv integration
Browse filesRefactor main.py to integrate OpenEnv compatibility and enhance API structure.
- backend/main.py +164 -101
backend/main.py
CHANGED
|
@@ -1,108 +1,171 @@
|
|
| 1 |
-
import uuid
|
| 2 |
-
from typing import Dict, Any, Optional
|
| 3 |
-
|
| 4 |
-
from fastapi import FastAPI, HTTPException
|
| 5 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
-
from pydantic import BaseModel
|
| 7 |
-
|
| 8 |
-
import sys
|
| 9 |
import os
|
|
|
|
|
|
|
|
|
|
| 10 |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 11 |
|
| 12 |
-
from
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
class
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
class
|
| 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 |
-
def
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
+
from typing import Any, Dict, List, Optional
|
| 4 |
+
|
| 5 |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 6 |
|
| 7 |
+
from fastapi import FastAPI
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from pydantic import Field
|
| 10 |
|
| 11 |
+
from openenv.core.env_server.interfaces import Environment
|
| 12 |
+
from openenv.core.env_server.types import (
|
| 13 |
+
Action as OEAction,
|
| 14 |
+
Observation as OEObservation,
|
| 15 |
+
State as OEState,
|
| 16 |
+
EnvironmentMetadata,
|
| 17 |
+
)
|
| 18 |
+
from openenv.core.env_server.http_server import HTTPEnvServer
|
| 19 |
|
| 20 |
+
from models import (
|
| 21 |
+
Action as ModelAction,
|
| 22 |
+
Observation as ModelObservation,
|
| 23 |
+
generate_tasks,
|
| 24 |
+
deterministic_grader,
|
| 25 |
+
CLMEnvironment,
|
| 26 |
)
|
| 27 |
|
| 28 |
+
|
| 29 |
+
# ββ OpenEnv-compatible Action / Observation / State models ββββββββββββββββββ
|
| 30 |
+
|
| 31 |
+
class CLMAction(OEAction):
|
| 32 |
+
"""Action for the Cognitive Load Manager environment."""
|
| 33 |
+
type: str = Field(description="Action type: work, break, switch, or delay")
|
| 34 |
+
task_id: Optional[str] = Field(default=None, description="Task ID to act on")
|
| 35 |
+
|
| 36 |
+
model_config = {"extra": "allow"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CLMObservation(OEObservation):
|
| 40 |
+
"""Observation from the Cognitive Load Manager environment."""
|
| 41 |
+
tasks: List[Dict[str, Any]] = Field(default_factory=list)
|
| 42 |
+
visible_state: Dict[str, Any] = Field(default_factory=dict)
|
| 43 |
+
time_step: int = Field(default=0)
|
| 44 |
+
|
| 45 |
+
model_config = {"extra": "allow"}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class CLMState(OEState):
|
| 49 |
+
"""State for the Cognitive Load Manager environment."""
|
| 50 |
+
energy: float = Field(default=1.0)
|
| 51 |
+
stress: float = Field(default=0.0)
|
| 52 |
+
fatigue: float = Field(default=0.0)
|
| 53 |
+
current_task_id: Optional[str] = Field(default=None)
|
| 54 |
+
tasks: List[Dict[str, Any]] = Field(default_factory=list)
|
| 55 |
+
|
| 56 |
+
model_config = {"extra": "allow"}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ββ OpenEnv Environment wrapper βββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββ
|
| 60 |
+
|
| 61 |
+
class CLMEnvWrapper(Environment):
|
| 62 |
+
"""
|
| 63 |
+
Cognitive Load Manager wrapped as an OpenEnv-compliant environment.
|
| 64 |
+
|
| 65 |
+
Three difficulty levels via the task_id reset parameter:
|
| 66 |
+
- easy: 2 tasks, no deadlines
|
| 67 |
+
- medium: 5 tasks with deadlines
|
| 68 |
+
- hard: 8 tasks with tight deadlines
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
SUPPORTS_CONCURRENT_SESSIONS = True
|
| 72 |
+
|
| 73 |
+
def __init__(self):
|
| 74 |
+
super().__init__()
|
| 75 |
+
level = os.getenv("CLM_LEVEL", "easy")
|
| 76 |
+
tasks = generate_tasks(level)
|
| 77 |
+
self._env = CLMEnvironment(tasks=tasks, max_steps=50)
|
| 78 |
+
self._final_score: float = 0.0
|
| 79 |
+
|
| 80 |
+
def _to_oe_obs(self, obs: ModelObservation, done: bool = False, reward: Optional[float] = None, info: Optional[dict] = None) -> CLMObservation:
|
| 81 |
+
return CLMObservation(
|
| 82 |
+
tasks=[t.model_dump() for t in obs.tasks],
|
| 83 |
+
visible_state=obs.visible_state.model_dump(),
|
| 84 |
+
time_step=obs.time_step,
|
| 85 |
+
done=done,
|
| 86 |
+
reward=reward,
|
| 87 |
+
metadata=info or {},
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def reset(self, seed: Optional[int] = None, episode_id: Optional[str] = None, task_id: str = "easy", **kwargs) -> CLMObservation:
|
| 91 |
+
if task_id not in ("easy", "medium", "hard"):
|
| 92 |
+
task_id = "easy"
|
| 93 |
+
tasks = generate_tasks(task_id)
|
| 94 |
+
self._env = CLMEnvironment(tasks=tasks, max_steps=50)
|
| 95 |
+
self._final_score = 0.0
|
| 96 |
+
obs = self._env.reset()
|
| 97 |
+
return self._to_oe_obs(obs)
|
| 98 |
+
|
| 99 |
+
def step(self, action: CLMAction, timeout_s: Optional[float] = None, **kwargs) -> CLMObservation:
|
| 100 |
+
model_action = ModelAction(type=action.type, task_id=action.task_id)
|
| 101 |
+
obs, reward, done, info = self._env.step(model_action)
|
| 102 |
+
if done:
|
| 103 |
+
self._final_score = deterministic_grader(
|
| 104 |
+
self._env.state.tasks,
|
| 105 |
+
self._env.state.time_step,
|
| 106 |
+
self._env.state.energy,
|
| 107 |
+
)
|
| 108 |
+
info["final_score"] = self._final_score
|
| 109 |
+
return self._to_oe_obs(obs, done=done, reward=float(reward), info=info)
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def state(self) -> CLMState:
|
| 113 |
+
raw = self._env.state_dict()
|
| 114 |
+
return CLMState(
|
| 115 |
+
energy=raw.get("energy", 1.0),
|
| 116 |
+
stress=raw.get("stress", 0.0),
|
| 117 |
+
fatigue=raw.get("fatigue", 0.0),
|
| 118 |
+
current_task_id=raw.get("current_task_id"),
|
| 119 |
+
tasks=raw.get("tasks", []),
|
| 120 |
+
step_count=raw.get("time_step", 0),
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def get_metadata(self) -> EnvironmentMetadata:
|
| 124 |
+
return EnvironmentMetadata(
|
| 125 |
+
name="cognitive-load-manager",
|
| 126 |
+
description=(
|
| 127 |
+
"Cognitive Load Manager (CLM) simulates human cognitive load "
|
| 128 |
+
"(energy, stress, fatigue) while managing tasks with deadlines. "
|
| 129 |
+
"Three difficulty levels: easy (2 tasks, no deadlines), "
|
| 130 |
+
"medium (5 tasks with deadlines), hard (8 tasks with tight deadlines)."
|
| 131 |
+
),
|
| 132 |
+
version="1.0.0",
|
| 133 |
+
author="Team Innovators",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def close(self) -> None:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ββ Build FastAPI app via OpenEnv HTTPEnvServer ββββββββββββββββββββββββββββββ
|
| 141 |
+
|
| 142 |
+
def build_app() -> FastAPI:
|
| 143 |
+
server = HTTPEnvServer(
|
| 144 |
+
env=CLMEnvWrapper,
|
| 145 |
+
action_cls=CLMAction,
|
| 146 |
+
observation_cls=CLMObservation,
|
| 147 |
+
max_concurrent_envs=10,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
_app = FastAPI(
|
| 151 |
+
title="Cognitive Load Manager (CLM) Environment API",
|
| 152 |
+
version="1.0.0",
|
| 153 |
+
description=(
|
| 154 |
+
"OpenEnv-compliant environment for the Meta PyTorch Hackathon. "
|
| 155 |
+
"Simulates cognitive load management with three difficulty levels."
|
| 156 |
+
),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
_app.add_middleware(
|
| 160 |
+
CORSMiddleware,
|
| 161 |
+
allow_origins=["*"],
|
| 162 |
+
allow_credentials=True,
|
| 163 |
+
allow_methods=["*"],
|
| 164 |
+
allow_headers=["*"],
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
server.register_routes(_app)
|
| 168 |
+
return _app
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
app = build_app()
|