Spaces:
Sleeping
Sleeping
Download server/app.py from itsjovy/fraudlens: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/itsjovy/fraudlens/resolve/main/server/app.py
- Command line
-
hf download hf://spaces/itsjovy/fraudlens/server/app.py
-
curl -L -o app.py https://huggingface.co/spaces/itsjovy/fraudlens/resolve/main/server/app.py
2.24 kB
| import os | |
| import sys | |
| from fastapi import FastAPI | |
| from fastapi.responses import JSONResponse | |
| import uvicorn | |
| # Add parent directory to path so we can import env | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from env import FraudEnv | |
| from models import Action, Observation, Reward | |
| from typing import Optional | |
| app = FastAPI() | |
| # Global environment instance | |
| _env: Optional[FraudEnv] = None | |
| _task_level: str = "medium" | |
| _num_users: int = 5 | |
| async def root(): | |
| return { | |
| "message": "Ecommerce Fraud RL Agent API", | |
| "endpoints": { | |
| "POST /reset": "Initialize the environment", | |
| "POST /step": "Execute one step in the environment", | |
| "GET /state": "Get current environment state", | |
| "GET /health": "Health check" | |
| } | |
| } | |
| async def reset(): | |
| global _env, _task_level, _num_users | |
| _env = FraudEnv(task_level=_task_level, num_users=_num_users) | |
| obs = _env.reset() | |
| return { | |
| "observation": obs.model_dump(), | |
| "done": False, | |
| "info": {} | |
| } | |
| async def step(action: dict): | |
| global _env | |
| if _env is None: | |
| return JSONResponse( | |
| status_code=400, | |
| content={"error": "Environment not initialized. Call /reset first."} | |
| ) | |
| try: | |
| action_obj = Action(**action) | |
| next_obs, reward, done, info = _env.step(action_obj) | |
| return { | |
| "observation": next_obs.model_dump(), | |
| "reward": reward.value, | |
| "done": done, | |
| "info": info | |
| } | |
| except Exception as e: | |
| return JSONResponse( | |
| status_code=400, | |
| content={"error": str(e)} | |
| ) | |
| async def state(): | |
| global _env | |
| if _env is None: | |
| return JSONResponse( | |
| status_code=400, | |
| content={"error": "Environment not initialized. Call /reset first."} | |
| ) | |
| state_dict = _env.state() | |
| return state_dict | |
| async def health(): | |
| return {"status": "ok"} | |
| def main(): | |
| port = int(os.getenv("PORT", 7860)) | |
| uvicorn.run(app, host="0.0.0.0", port=port) | |
| if __name__ == "__main__": | |
| main() | |