Spaces:
Sleeping
Sleeping
File size: 6,586 Bytes
b92d20c ea373a2 b92d20c 2d2c6e4 b92d20c ea373a2 b92d20c ea373a2 62d767e b92d20c 2d2c6e4 b92d20c ea373a2 2d2c6e4 ea373a2 2d2c6e4 ea373a2 2d2c6e4 ea373a2 2d2c6e4 ea373a2 b92d20c 2d2c6e4 b92d20c | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | from __future__ import annotations
from pathlib import Path
from threading import Lock
from uuid import uuid4
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import os
from typing import Any
import uvicorn
from codereview_env.models import (
CodeReviewAction,
CodeReviewObservation,
CodeReviewState,
)
from server.environment import CodeReviewEnvironment
from server.tasks import TASKS, TASKS_BY_ID, grade_submission
def make_env() -> CodeReviewEnvironment:
return CodeReviewEnvironment()
app = FastAPI(title="CodeReview-Env", version="2.0.0")
_sessions: dict[str, CodeReviewEnvironment] = {}
_latest_session_id: str | None = None
_session_lock = Lock()
_current_dir = Path(__file__).resolve().parent
_root_dir = _current_dir.parent
# Robust path resolution for frontend
_frontend_dir = (_root_dir / "frontend").resolve()
if not _frontend_dir.exists():
# Attempt to find it relative to current working directory
_frontend_dir = (Path.cwd() / "frontend").resolve()
if not _frontend_dir.exists():
# Fallback for container structured where source might be in /app
_frontend_dir = Path("/app/frontend").resolve()
app.mount("/static", StaticFiles(directory=str(_frontend_dir)), name="static") if _frontend_dir.exists() else None
def _serialize_step(observation: CodeReviewObservation, session_id: str) -> dict:
return {
"session_id": session_id,
"observation": observation.model_dump(),
"reward": observation.reward,
"done": observation.done,
}
def _resolve_session(session_id: str | None) -> tuple[str, CodeReviewEnvironment]:
selected_session_id = session_id or _latest_session_id
if not selected_session_id or selected_session_id not in _sessions:
raise HTTPException(
status_code=404, detail="No active session. Call /reset first."
)
return selected_session_id, _sessions[selected_session_id]
@app.get("/", include_in_schema=False, response_model=None)
@app.get("/index.html", include_in_schema=False, response_model=None)
@app.get("/ui", include_in_schema=False, response_model=None)
def root(request: Request) -> Any:
index_path = _frontend_dir / "index.html"
# Debug info for logs
print(f"DEBUG: Root request for {request.url.path}")
print(f"DEBUG: Looking for index.html at {index_path}")
if not index_path.exists():
return JSONResponse(
status_code=404,
content={
"error": "Dashboard files missing",
"searched_at": str(index_path),
"cwd": os.getcwd(),
"frontend_dir_exists": _frontend_dir.exists(),
"frontend_dir": str(_frontend_dir),
"files_in_frontend": (
os.listdir(str(_frontend_dir)) if _frontend_dir.exists() else []
),
},
)
return FileResponse(index_path)
@app.get("/health", tags=["Health"])
def health() -> dict:
return {
"status": "ok",
"benchmark": "codereview-env",
"task_count": len(TASKS),
"tasks": [task.task_id for task in TASKS],
}
@app.get("/tasks", tags=["Environment Info"])
def tasks() -> list[dict]:
return [
{
"task_id": task.task_id,
"title": task.title,
"difficulty": task.difficulty,
"objective": task.objective,
"step_limit": task.step_limit,
}
for task in TASKS
]
@app.get("/tasks/{task_id}", tags=["Environment Info"])
def task_detail(task_id: str) -> dict:
if task_id not in TASKS_BY_ID:
raise HTTPException(status_code=404, detail=f"Unknown task_id: {task_id}")
task = TASKS_BY_ID[task_id]
return {
"task_id": task.task_id,
"title": task.title,
"difficulty": task.difficulty,
"objective": task.objective,
"summary": task.summary,
"step_limit": task.step_limit,
"artifacts": [artifact.artifact_id for artifact in task.artifacts.values()],
}
@app.get("/metadata", tags=["Environment Info"])
def metadata() -> dict:
env = make_env()
try:
return env.get_metadata()
finally:
env.close()
@app.post("/reset", tags=["Episode"])
def reset(payload: dict | None = None) -> dict:
global _latest_session_id
body = payload or {}
env = make_env()
task_id = body.get("task_id") or body.get("task_name")
observation = env.reset(
seed=body.get("seed"),
episode_id=body.get("episode_id"),
task_id=task_id,
)
session_id = body.get("session_id") or str(uuid4())
with _session_lock:
_sessions[session_id] = env
_latest_session_id = session_id
return _serialize_step(observation, session_id)
@app.post("/step", tags=["Episode"])
def step(payload: dict) -> dict:
session_id, env = _resolve_session(payload.get("session_id"))
action = CodeReviewAction.model_validate(payload.get("action", {}))
observation = env.step(action)
return _serialize_step(observation, session_id)
@app.get("/state", tags=["Episode"])
def state() -> CodeReviewState:
_, env = _resolve_session(None)
return env.state
@app.get("/state/{session_id}", tags=["Episode"])
def state_by_id(session_id: str) -> CodeReviewState:
_, env = _resolve_session(session_id)
return env.state
@app.post("/grade", tags=["Evaluation"])
def grade(payload: dict) -> dict:
task_id = payload.get("task_id") or payload.get("task_name")
if not task_id:
raise HTTPException(status_code=400, detail="task_id is required")
return grade_submission(
task_id=task_id,
review_text=payload.get("review_comment", ""),
findings=payload.get("findings") or [],
)
@app.get("/demo", tags=["Evaluation"])
def demo() -> dict:
return {
"task_id": "tenant-export-auth",
"bad_review": "Looks fine to me.",
"good_review": (
"This route is missing both require_admin and require_account_scope, "
"so another tenant's invoices can be exported by passing an arbitrary account_id."
),
}
@app.exception_handler(KeyError)
async def handle_key_error(request: Request, exc: KeyError) -> JSONResponse:
return JSONResponse(
status_code=400, content={"error": f"Unknown key: {exc.args[0]}"}
)
def main() -> None:
uvicorn.run("server.app:app", host="0.0.0.0", port=7860)
if __name__ == "__main__":
main()
|