Spaces:
Sleeping
Sleeping
File size: 9,823 Bytes
98c059c 9493f84 98c059c e70f4ad 98c059c 9493f84 98c059c 2b1054d 98c059c 9493f84 98c059c 2b1054d 98c059c 2b1054d | 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict, Any
from models import Action, StepResult, Reward
from environment import DataCleaningEnv
# βββββββββββββββββββββββββββββββββββββββββ
# App Setup
# βββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="Data Cleaning OpenEnv (Team Garuda)",
description=(
"An OpenEnv-compliant environment where AI agents "
"learn to clean messy real-world datasets step by step."
),
version="1.0.0"
)
# Serve UI
os.makedirs("static", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# βββββββββββββββββββββββββββββββββββββββββ
# One environment instance per task
# βββββββββββββββββββββββββββββββββββββββββ
VALID_TASKS = [
"easy_dedup_rename",
"medium_missing_dtype",
"hard_full_pipeline",
"expert_sales_pipeline"
]
envs: Dict[str, DataCleaningEnv] = {
task_id: DataCleaningEnv(task_id=task_id)
for task_id in VALID_TASKS
}
def get_env(task_id: str) -> DataCleaningEnv:
if task_id not in envs:
raise HTTPException(
status_code=404,
detail=(
f"Task '{task_id}' not found. "
f"Valid tasks: {VALID_TASKS}"
)
)
return envs[task_id]
# βββββββββββββββββββββββββββββββββββββββββ
# ROUTES
# βββββββββββββββββββββββββββββββββββββββββ
@app.get("/ui")
def ui():
return FileResponse("static/index.html")
@app.get("/")
def root():
return {
"name": "Data Cleaning OpenEnv",
"version": "1.0.0",
"status": "running",
"tasks": VALID_TASKS,
"endpoints": {
"reset": "POST /reset/{task_id}",
"step": "POST /step/{task_id}",
"state": "GET /state/{task_id}",
"tasks": "GET /tasks",
"health": "GET /health",
"docs": "GET /docs"
}
}
@app.get("/health")
def health():
return {
"status": "ok",
"tasks_loaded": len(envs)
}
@app.get("/tasks")
def list_tasks():
return {
"tasks": [
{
"task_id": "easy_dedup_rename",
"difficulty": "easy",
"description": (
"Remove duplicate rows and rename columns "
"to snake_case in an employee dataset."
),
"max_steps": 10,
"operations": ["remove_duplicates", "rename_columns", "finish"]
},
{
"task_id": "medium_missing_dtype",
"difficulty": "medium",
"description": (
"Fill missing values using correct strategies "
"and fix wrong data types in a customer dataset."
),
"max_steps": 15,
"operations": ["fill_missing", "fix_dtype", "finish"]
},
{
"task_id": "hard_full_pipeline",
"difficulty": "hard",
"description": (
"Run a full cleaning pipeline: remove duplicates, "
"fill missing values, fix dtypes, remove outliers, "
"and validate schema on an orders dataset."
),
"max_steps": 20,
"operations": [
"remove_duplicates", "fill_missing", "fix_dtype",
"remove_outliers", "validate_schema", "finish"
]
},
{
"task_id": "expert_sales_pipeline",
"difficulty": "expert",
"description": (
"Expert level: Full sales data cleaning pipeline "
"requiring correct order of operations including "
"case standardization, outlier removal, and schema validation."
),
"max_steps": 25,
"operations": [
"remove_duplicates", "fill_missing", "fix_dtype",
"remove_outliers", "rename_columns",
"validate_schema", "finish"
]
}
]
}
@app.post("/reset/{task_id}")
def reset(task_id: str):
"""Reset environment and start fresh episode."""
env = get_env(task_id)
try:
result = env.reset()
return result.dict()
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Reset failed: {str(e)}"
)
@app.post("/step/{task_id}")
def step(task_id: str, action: Action):
"""Take one action in the environment."""
env = get_env(task_id)
if env.current_df is None:
raise HTTPException(
status_code=400,
detail="Environment not initialized. Call /reset/{task_id} first."
)
try:
result = env.step(action)
return result.dict()
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Step failed: {str(e)}"
)
@app.get("/state/{task_id}")
def state(task_id: str):
"""Get current environment state."""
env = get_env(task_id)
try:
return env.state()
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"State failed: {str(e)}"
)
@app.get("/validate")
def validate():
"""OpenEnv spec validation endpoint."""
results = {}
for task_id in VALID_TASKS:
try:
env = DataCleaningEnv(task_id=task_id)
# Test reset
reset_result = env.reset()
assert reset_result.observation is not None
assert reset_result.reward is not None
assert reset_result.done == False
# Test step
from models import Action
action = Action(
operation="remove_duplicates",
parameters={}
)
step_result = env.step(action)
assert step_result.observation is not None
assert 0.0 <= step_result.reward.total <= 1.0
# Test state
state_result = env.state()
assert "task_id" in state_result
results[task_id] = {
"status": "passed",
"reset": "ok",
"step": "ok",
"state": "ok",
"reward_range": f"{step_result.reward.total}"
}
except Exception as e:
results[task_id] = {
"status": "failed",
"error": str(e)
}
all_passed = all(r["status"] == "passed" for r in results.values())
return {
"openenv_valid": all_passed,
"tasks": results
}
# In memory leaderboard
leaderboard_data = []
@app.post("/leaderboard/submit")
def submit_score(entry: Dict[str, Any]):
"""Submit a score to the leaderboard."""
required = ["model_name", "task_id", "score"]
for field in required:
if field not in entry:
raise HTTPException(
status_code=400,
detail=f"Missing field: {field}"
)
if not 0.0 <= float(entry["score"]) <= 1.0:
raise HTTPException(
status_code=400,
detail="Score must be between 0.0 and 1.0"
)
leaderboard_data.append({
"model_name": entry["model_name"],
"task_id": entry["task_id"],
"score": round(float(entry["score"]), 4),
"steps": entry.get("steps", 0),
"timestamp": __import__("datetime").datetime.utcnow().isoformat()
})
return {"status": "submitted", "entry": leaderboard_data[-1]}
@app.get("/leaderboard")
def get_leaderboard():
"""Get current leaderboard rankings."""
if not leaderboard_data:
# Return baseline scores
return {
"leaderboard": [
{
"rank": 1,
"model_name": "gpt-4o-mini (baseline)",
"easy_score": 1.0000,
"medium_score": 0.6643,
"hard_score": 0.8386,
"avg_score": 0.8343
}
],
"total_submissions": 1
}
# Group by model
from collections import defaultdict
model_scores = defaultdict(dict)
for entry in leaderboard_data:
model_scores[entry["model_name"]][entry["task_id"]] = entry["score"]
ranked = []
for model, scores in model_scores.items():
avg = sum(scores.values()) / len(scores) if scores else 0
ranked.append({
"model_name": model,
"scores": scores,
"avg_score": round(avg, 4)
})
ranked.sort(key=lambda x: x["avg_score"], reverse=True)
for i, r in enumerate(ranked):
r["rank"] = i + 1
return {
"leaderboard": ranked,
"total_submissions": len(leaderboard_data)
}
|