File size: 3,619 Bytes
b1dec00
 
25a7357
4d10011
 
3687a02
b1dec00
25a7357
 
 
847096d
25a7357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1dec00
3687a02
847096d
25a7357
 
 
 
 
 
 
b1dec00
 
 
3687a02
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
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
109
110
111
112
113
114
115
116
117
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

@app.get("/")
async def root():
    return {"status": "online", "environment": "DocumentClassification-v1"}

@app.post("/reset")
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))

@app.post("/step")
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))

@app.get("/state")
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()