Spaces:
Sleeping

File size: 3,899 Bytes
1be0df2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import asyncio
from typing import Any, Dict, Optional

try:
    import websockets
    HAS_WS = True
except ImportError:
    HAS_WS = False

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False


class DataCleaningEnv:
    """
    Sync client for the Data Cleaning OpenEnv environment.

    Usage:
        env = DataCleaningEnv(base_url="http://localhost:8000")
        obs = env.reset(task_id="easy")
        result = env.step({"operation": "fill_nulls", "column": "age",
                           "params": {"strategy": "median"}, "reasoning": "age has nulls"})
        print(result["observation"]["data_quality_score"])
    """

    def __init__(self, base_url: str = "http://localhost:8000"):
        self.base_url = base_url.rstrip("/")
        if not HAS_REQUESTS:
            raise ImportError("pip install requests")

    def reset(self, task_id: str = "easy") -> Dict[str, Any]:
        resp = requests.post(f"{self.base_url}/reset", json={"task_id": task_id}, timeout=30)
        resp.raise_for_status()
        return resp.json()

    def step(self, action: Dict[str, Any]) -> Dict[str, Any]:
        resp = requests.post(f"{self.base_url}/step", json=action, timeout=30)
        resp.raise_for_status()
        return resp.json()

    def state(self) -> Dict[str, Any]:
        resp = requests.get(f"{self.base_url}/state", timeout=10)
        resp.raise_for_status()
        return resp.json()

    def health(self) -> bool:
        try:
            resp = requests.get(f"{self.base_url}/health", timeout=5)
            return resp.status_code == 200
        except Exception:
            return False

    # Convenience: run a full episode with a simple policy function
    def run_episode(self, policy_fn, task_id: str = "easy") -> Dict[str, Any]:
        """
        policy_fn(observation: dict) -> action: dict
        Returns episode summary dict.
        """
        result = self.reset(task_id=task_id)
        obs    = result["observation"]
        total_reward = 0.0
        steps = 0

        while not obs["done"]:
            action = policy_fn(obs)
            result = self.step(action)
            obs    = result["observation"]
            if obs["reward"] is not None:
                total_reward += obs["reward"]
            steps += 1

        return {
            "task_id":       task_id,
            "steps":         steps,
            "total_reward":  round(total_reward, 4),
            "final_quality": obs["data_quality_score"],
            "done":          obs["done"],
        }


class AsyncDataCleaningEnv:
    """Async WebSocket client — preferred for high-throughput training."""

    def __init__(self, base_url: str = "ws://localhost:8000"):
        if not HAS_WS:
            raise ImportError("pip install websockets")
        self.ws_url = base_url.rstrip("/").replace("http://", "ws://").replace("https://", "wss://") + "/ws"
        self._ws = None

    async def connect(self):
        self._ws = await websockets.connect(self.ws_url)
        return self

    async def close(self):
        if self._ws:
            await self._ws.close()

    async def reset(self, task_id: str = "easy") -> Dict[str, Any]:
        await self._ws.send(json.dumps({"method": "reset", "payload": {"task_id": task_id}}))
        return json.loads(await self._ws.recv())

    async def step(self, action: Dict[str, Any]) -> Dict[str, Any]:
        await self._ws.send(json.dumps({"method": "step", "payload": action}))
        return json.loads(await self._ws.recv())

    async def state(self) -> Dict[str, Any]:
        await self._ws.send(json.dumps({"method": "state", "payload": {}}))
        return json.loads(await self._ws.recv())

    async def __aenter__(self):
        return await self.connect()

    async def __aexit__(self, *args):
        await self.close()