TanujInsane
Fix 500 error on /reset and manually implement FastAPI endpoints for grader compatibility
25a7357 Download server/app.py from TanujInsane/document-classification-env: direct link, hf CLI and curl.
- Browser
- Download file 3.62 kB
-
https://huggingface.co/spaces/TanujInsane/document-classification-env/resolve/main/server/app.py
- Command line
-
hf download hf://spaces/TanujInsane/document-classification-env/server/app.py
-
curl -L -o app.py https://huggingface.co/spaces/TanujInsane/document-classification-env/resolve/main/server/app.py
3.62 kB
| import os | |
| import sys | |
| from typing import Optional | |
| # Allow importing from root directory | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from server.document_classification_environment import DocumentClassificationEnvironment | |
| app = FastAPI(title="OpenEnv Document Classification API") | |
| # Store the active environment instance | |
| # In a real OpenEnv session, this might be handled per-session, | |
| # but for a simple hackathon grader, a singleton is often used. | |
| env_container = {"instance": None} | |
| def get_env(difficulty: str = "easy", seed: int = 42): | |
| if env_container["instance"] is None: | |
| env_container["instance"] = DocumentClassificationEnvironment(difficulty=difficulty, seed=seed) | |
| return env_container["instance"] | |
| class ResetRequest(BaseModel): | |
| difficulty: str = "easy" | |
| seed: Optional[int] = 42 | |
| class StepRequest(BaseModel): | |
| action: int | |
| async def root(): | |
| return {"status": "online", "environment": "DocumentClassification-v1"} | |
| async def reset(req: Optional[ResetRequest] = None): | |
| try: | |
| difficulty = req.difficulty if req else "easy" | |
| seed = req.seed if req else 42 | |
| # Fresh instance for every reset | |
| env_container["instance"] = DocumentClassificationEnvironment(difficulty=difficulty, seed=seed) | |
| env = env_container["instance"] | |
| # reset() returns DocObservation which has all fields | |
| obs = env.reset(seed=seed) | |
| # Return exactly what the user/grader expects: {"observation": {...}} | |
| # We exclude reward/done/metadata from the inner observation if they are handled at top level | |
| obs_dict = obs.model_dump() | |
| return { | |
| "observation": obs_dict, | |
| "reward": 0.0, | |
| "done": False, | |
| "metadata": {} | |
| } | |
| except Exception as e: | |
| import traceback | |
| print(f"[ERROR] Reset failed: {e}") | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def step(req: StepRequest): | |
| try: | |
| env = env_container.get("instance") | |
| if env is None: | |
| # Fallback for graders that don't call /reset first or expect a default | |
| env = get_env() | |
| from models import DocAction | |
| action = DocAction(action_id=req.action) | |
| obs = env.step(action) | |
| obs_dict = obs.model_dump() | |
| reward = obs_dict.pop("reward", 0.0) | |
| done = obs_dict.pop("done", False) | |
| metadata = obs_dict.pop("metadata", {}) | |
| return { | |
| "observation": obs_dict, | |
| "reward": reward, | |
| "done": done, | |
| "metadata": metadata | |
| } | |
| except Exception as e: | |
| import traceback | |
| print(f"[ERROR] Step failed: {e}") | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def state(): | |
| try: | |
| env = env_container.get("instance") | |
| if env is None: | |
| env = get_env() | |
| return env.state | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def main(): | |
| import uvicorn | |
| # Pre-train models if needed | |
| try: | |
| from startup import ensure_models | |
| ensure_models() | |
| except ImportError: | |
| pass | |
| port = int(os.environ.get("PORT", "7860")) | |
| uvicorn.run(app, host="0.0.0.0", port=port, log_level="info") | |
| if __name__ == "__main__": | |
| main() | |