Spaces:
Sleeping
Sleeping
Upload src/tetris_env/client.py with huggingface_hub
Browse files- src/tetris_env/client.py +43 -0
src/tetris_env/client.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OpenEnv client for Tetris environment.
|
| 3 |
+
Used from Colab/training scripts to interact with the deployed environment.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Dict, Any
|
| 7 |
+
from openenv.core import EnvClient
|
| 8 |
+
from openenv.core.env_client import StepResult
|
| 9 |
+
from .models import TetrisAction, TetrisObservation, TetrisState
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TetrisEnvClient(EnvClient[TetrisAction, TetrisObservation, TetrisState]):
|
| 13 |
+
"""
|
| 14 |
+
Client for connecting to a remote Tetris OpenEnv server.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
with TetrisEnvClient(base_url="https://your-space.hf.space") as env:
|
| 18 |
+
result = env.reset(seed=42)
|
| 19 |
+
while not result.done:
|
| 20 |
+
action = TetrisAction(action="drop")
|
| 21 |
+
result = env.step(action)
|
| 22 |
+
print(f"Reward: {result.reward}, Score: {result.observation.score}")
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def _step_payload(self, action: TetrisAction) -> Dict[str, Any]:
|
| 26 |
+
"""Convert TetrisAction to JSON payload for the server."""
|
| 27 |
+
return action.model_dump()
|
| 28 |
+
|
| 29 |
+
def _parse_result(self, payload: Dict[str, Any]) -> StepResult[TetrisObservation]:
|
| 30 |
+
"""Parse server response into StepResult with TetrisObservation."""
|
| 31 |
+
obs_data = payload.get("observation", payload)
|
| 32 |
+
reward = payload.get("reward")
|
| 33 |
+
done = payload.get("done", False)
|
| 34 |
+
obs = TetrisObservation(**obs_data, reward=reward, done=done)
|
| 35 |
+
return StepResult(
|
| 36 |
+
observation=obs,
|
| 37 |
+
reward=reward,
|
| 38 |
+
done=done,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def _parse_state(self, payload: Dict[str, Any]) -> TetrisState:
|
| 42 |
+
"""Parse server state response into TetrisState."""
|
| 43 |
+
return TetrisState(**payload)
|