Spaces:
Sleeping
Sleeping
Download server/app.py from ayushrwt/OpenEnv_Hackathon: direct link, hf CLI and curl.
- Browser
- Download file 6.02 kB
-
https://huggingface.co/spaces/ayushrwt/OpenEnv_Hackathon/resolve/main/server/app.py
- Command line
-
hf download hf://spaces/ayushrwt/OpenEnv_Hackathon/server/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ayushrwt/OpenEnv_Hackathon/resolve/main/server/app.py
6.02 kB
| # Copyright (c) Meta Platforms, Inc. and affiliates. | |
| # All rights reserved. | |
| # | |
| # This source code is licensed under the BSD-style license found in the | |
| # LICENSE file in the root directory of this source tree. | |
| """ | |
| FastAPI application for the Wildfire Environment. | |
| """ | |
| import os | |
| from typing import List | |
| from fastapi import Request | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| try: | |
| from openenv.core.env_server.http_server import create_app | |
| except Exception as e: # pragma: no cover | |
| raise ImportError( | |
| "openenv is required. Install dependencies with '\n uv sync\n'" | |
| ) from e | |
| try: | |
| from ..models import ( | |
| WildfireAction, WildfireObservation, | |
| TaskResponse, GraderResponse, BaselineResponse, | |
| ResetRequest, StepResponse, ResetResponse, StateResponse, | |
| ) | |
| # FIX: correct filename and class name | |
| from .Wildfire_env import Wildfire_env | |
| from .tasks import TASKS, TaskGrader | |
| from .agent import BaselineAgent | |
| except (ModuleNotFoundError, ImportError): | |
| from models import ( | |
| WildfireAction, WildfireObservation, | |
| TaskResponse, GraderResponse, BaselineResponse, | |
| ResetRequest, StepResponse, ResetResponse, StateResponse, | |
| ) | |
| # FIX: correct filename and class name | |
| from server.Wildfire_env import Wildfire_env | |
| from server.tasks import TASKS, TaskGrader | |
| from server.agent import BaselineAgent | |
| # Create the app with web interface and README integration | |
| app = create_app( | |
| Wildfire_env, | |
| WildfireAction, | |
| WildfireObservation, | |
| env_name="wildfireEnvironment", | |
| max_concurrent_envs=1, | |
| ) | |
| # ----------------------------------------------------------------------------- | |
| # Remove auto-generated /step, /reset, /state so we can define bare endpoints | |
| # ----------------------------------------------------------------------------- | |
| app.router.routes = [ | |
| r for r in app.router.routes | |
| if getattr(r, "path", None) not in ["/reset", "/step", "/state"] | |
| ] | |
| GLOBAL_ENV = Wildfire_env() | |
| def get_active_env(): | |
| """Return the currently active OpenEnv session instance.""" | |
| if hasattr(app.state, "env_manager"): | |
| envs = getattr(app.state.env_manager, "_envs", {}) | |
| if envs: | |
| return list(envs.values())[-1] | |
| return GLOBAL_ENV | |
| def reset_env(body: ResetRequest = None): | |
| active_env = get_active_env() | |
| task = (body.task if body else None) or 1 | |
| obs = active_env.reset(task=task) | |
| obs_dict = obs.model_dump() if hasattr(obs, "model_dump") else obs.dict() | |
| return {"observation": obs_dict, "info": {"task": task}} | |
| def step_env(action: WildfireAction): | |
| active_env = get_active_env() | |
| obs = active_env.step(action) | |
| obs_dict = obs.model_dump() if hasattr(obs, "model_dump") else obs.dict() | |
| info = obs_dict.get("metadata", {}) | |
| return {"observation": obs_dict, "reward": obs.reward, "done": obs.done, "info": info} | |
| def get_state(): | |
| active_env = get_active_env() | |
| return {"state": active_env.get_internal_state()} | |
| # ----------------------------------------------------------------------------- | |
| # Additional routes | |
| # ----------------------------------------------------------------------------- | |
| STATIC_DIR = os.path.join( | |
| os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static" | |
| ) | |
| if os.path.isdir(STATIC_DIR): | |
| app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") | |
| def serve_frontend(): | |
| index = os.path.join(STATIC_DIR, "index.html") | |
| if os.path.exists(index): | |
| return FileResponse(index) | |
| return {"message": "Wildfire ICS OpenEnv API is running. Visit /docs for the API."} | |
| def list_tasks(): | |
| return [ | |
| { | |
| "id": t.id, | |
| "name": t.name, | |
| "difficulty": t.difficulty, | |
| "description": t.description, | |
| "grader": t.grader, | |
| } | |
| for t in TASKS | |
| ] | |
| def get_grader_scores(): | |
| active_env = get_active_env() | |
| grader = TaskGrader(active_env) | |
| return { | |
| "task_scores": { | |
| "task_1": grader.grade_task_1(), | |
| "task_2": grader.grade_task_2(), | |
| "task_3": grader.grade_task_3(), | |
| } | |
| } | |
| def run_baseline(): | |
| """Run the rule-based baseline agent on a fresh env instance.""" | |
| fresh_env = Wildfire_env() | |
| current_task = 1 | |
| try: | |
| active_env = get_active_env() | |
| if hasattr(active_env, "task"): | |
| current_task = active_env.task | |
| except Exception: | |
| pass | |
| fresh_env.reset(task=current_task) | |
| agent = BaselineAgent(fresh_env) | |
| total_reward = 0.0 | |
| steps = 0 | |
| while not fresh_env.done: | |
| obs_obj = fresh_env._get_obs() | |
| obs_dict = obs_obj.model_dump() if hasattr(obs_obj, "model_dump") else obs_obj.dict() | |
| # Use multi-action dispatch so baseline commands all burning divisions | |
| actions = agent.select_all_actions(obs_dict) | |
| for action_dict in actions: | |
| action_obj = WildfireAction(**action_dict) | |
| obs_res = fresh_env.step(action_obj) | |
| total_reward += obs_res.reward | |
| if fresh_env.done: | |
| break | |
| steps += 1 | |
| grader = TaskGrader(fresh_env) | |
| return { | |
| "task_scores": { | |
| "task_1": grader.grade_task_1(), | |
| "task_2": grader.grade_task_2(), | |
| "task_3": grader.grade_task_3(), | |
| }, | |
| "total_reward": round(total_reward, 4), | |
| "steps_taken": steps, | |
| } | |
| def main(host: str = "0.0.0.0", port: int = 8000): | |
| import uvicorn | |
| uvicorn.run(app, host=host, port=port) | |
| if __name__ == "__main__": | |
| main() | |