completion batch: arcprize__ARC-AGI
Browse files- arcprize__ARC-AGI/arc_agi/__init__.py +31 -0
- arcprize__ARC-AGI/arc_agi/api.py +501 -0
- arcprize__ARC-AGI/arc_agi/base.py +1126 -0
- arcprize__ARC-AGI/arc_agi/local_wrapper.py +251 -0
- arcprize__ARC-AGI/arc_agi/models.py +84 -0
- arcprize__ARC-AGI/arc_agi/remote_wrapper.py +261 -0
- arcprize__ARC-AGI/arc_agi/rendering.py +294 -0
- arcprize__ARC-AGI/arc_agi/scorecard.py +1012 -0
- arcprize__ARC-AGI/arc_agi/server.py +130 -0
- arcprize__ARC-AGI/arc_agi/wrapper.py +236 -0
- arcprize__ARC-AGI/test_environment_files/game1/bt11.py +111 -0
- arcprize__ARC-AGI/test_environment_files/game1/metadata.json +9 -0
- arcprize__ARC-AGI/test_environment_files/game2/subdir/bt33.py +166 -0
- arcprize__ARC-AGI/test_environment_files/game2/subdir/metadata.json +10 -0
- arcprize__ARC-AGI/tests/__init__.py +29 -0
- arcprize__ARC-AGI/tests/test_base.py +639 -0
- arcprize__ARC-AGI/tests/test_listen_and_serve.py +652 -0
- arcprize__ARC-AGI/tests/test_local_wrapper.py +288 -0
- arcprize__ARC-AGI/tests/test_models.py +483 -0
- arcprize__ARC-AGI/tests/test_scorecard.py +1058 -0
arcprize__ARC-AGI/arc_agi/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ARC-AGI package."""
|
| 2 |
+
|
| 3 |
+
from .api import RestAPI
|
| 4 |
+
from .base import Arcade, OperationMode
|
| 5 |
+
from .local_wrapper import LocalEnvironmentWrapper
|
| 6 |
+
from .models import APIError, EnvironmentInfo
|
| 7 |
+
from .remote_wrapper import RemoteEnvironmentWrapper
|
| 8 |
+
from .scorecard import (
|
| 9 |
+
EnvironmentScore,
|
| 10 |
+
EnvironmentScoreCalculator,
|
| 11 |
+
EnvironmentScorecard,
|
| 12 |
+
EnvironmentScoreList,
|
| 13 |
+
ScorecardManager,
|
| 14 |
+
)
|
| 15 |
+
from .wrapper import EnvironmentWrapper
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"Arcade",
|
| 19 |
+
"EnvironmentInfo",
|
| 20 |
+
"EnvironmentWrapper",
|
| 21 |
+
"EnvironmentScore",
|
| 22 |
+
"EnvironmentScoreList",
|
| 23 |
+
"EnvironmentScoreCalculator",
|
| 24 |
+
"EnvironmentScorecard",
|
| 25 |
+
"LocalEnvironmentWrapper",
|
| 26 |
+
"OperationMode",
|
| 27 |
+
"RemoteEnvironmentWrapper",
|
| 28 |
+
"ScorecardManager",
|
| 29 |
+
"RestAPI",
|
| 30 |
+
"APIError",
|
| 31 |
+
]
|
arcprize__ARC-AGI/arc_agi/api.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
+
from typing import Any, Callable, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
from arcengine import ActionInput, FrameData, FrameDataRaw, GameAction
|
| 9 |
+
from flask import Response, jsonify, request
|
| 10 |
+
from pydantic import ValidationError
|
| 11 |
+
|
| 12 |
+
from .base import Arcade
|
| 13 |
+
from .local_wrapper import LocalEnvironmentWrapper
|
| 14 |
+
from .models import APIError
|
| 15 |
+
from .scorecard import EnvironmentScorecard
|
| 16 |
+
from .wrapper import EnvironmentWrapper
|
| 17 |
+
|
| 18 |
+
MAX_OPAQUE_BYTES = 16 * 1024 # 16KiB (16384 bytes)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RestAPI:
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
arcade: Arcade,
|
| 25 |
+
competition_mode: bool = False,
|
| 26 |
+
save_all_recordings: bool = False,
|
| 27 |
+
include_frame_data: bool = True,
|
| 28 |
+
add_cookie: Optional[Callable[[Response, str], Response]] = None,
|
| 29 |
+
on_scorecard_close: Optional[Callable[[EnvironmentScorecard], None]] = None,
|
| 30 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 31 |
+
) -> None:
|
| 32 |
+
self.arcade = arcade
|
| 33 |
+
self.competition_mode = competition_mode
|
| 34 |
+
self.save_all_recordings = save_all_recordings
|
| 35 |
+
self.include_frame_data = include_frame_data
|
| 36 |
+
self.add_cookie = add_cookie
|
| 37 |
+
self.on_scorecard_close = on_scorecard_close
|
| 38 |
+
self._environmentCache: dict[str, EnvironmentWrapper] = {}
|
| 39 |
+
self._cache_lock = threading.Lock()
|
| 40 |
+
self.renderer = renderer
|
| 41 |
+
self.scorecard_openned = False
|
| 42 |
+
self.level_reset_only = os.getenv("ONLY_RESET_LEVELS") == "true"
|
| 43 |
+
|
| 44 |
+
def _json_with_cookie(
|
| 45 |
+
self,
|
| 46 |
+
data: Any,
|
| 47 |
+
*,
|
| 48 |
+
api_key: Optional[str] = None,
|
| 49 |
+
) -> Response:
|
| 50 |
+
"""Return JSON response with 200; optionally wrap response with add_cookie(response, api_key)."""
|
| 51 |
+
resp = jsonify(data)
|
| 52 |
+
if self.add_cookie is not None and api_key is not None:
|
| 53 |
+
resp = self.add_cookie(resp, api_key)
|
| 54 |
+
return resp
|
| 55 |
+
|
| 56 |
+
def get_games(self) -> Tuple[Response, int]:
|
| 57 |
+
out = [
|
| 58 |
+
e.model_dump(
|
| 59 |
+
mode="json",
|
| 60 |
+
exclude={"private_tags", "level_tags", "baseline_actions"},
|
| 61 |
+
)
|
| 62 |
+
for e in self.arcade.available_environments
|
| 63 |
+
]
|
| 64 |
+
return jsonify(out), 200
|
| 65 |
+
|
| 66 |
+
def get_game_info(self, game_id: str) -> Tuple[Response, int]:
|
| 67 |
+
for env in self.arcade.available_environments:
|
| 68 |
+
if env.game_id == game_id or env.game_id.startswith(f"{game_id}-"):
|
| 69 |
+
return jsonify(
|
| 70 |
+
env.model_dump(
|
| 71 |
+
mode="json",
|
| 72 |
+
exclude={
|
| 73 |
+
"private_tags",
|
| 74 |
+
"level_tags",
|
| 75 |
+
"baseline_actions",
|
| 76 |
+
},
|
| 77 |
+
)
|
| 78 |
+
), 200
|
| 79 |
+
return jsonify(
|
| 80 |
+
{
|
| 81 |
+
"error": APIError.SERVER_ERROR,
|
| 82 |
+
"message": f"game {game_id} not found",
|
| 83 |
+
}
|
| 84 |
+
), 404
|
| 85 |
+
|
| 86 |
+
def get_scorecard(
|
| 87 |
+
self, card_id: Optional[str] = None, game_id: Optional[str] = None
|
| 88 |
+
) -> Tuple[Response, int]:
|
| 89 |
+
api_key = request.headers.get("X-API-Key", "1234")
|
| 90 |
+
scorecard = (
|
| 91 |
+
self.arcade.scorecard_manager.get_scorecard(card_id, api_key)
|
| 92 |
+
if card_id
|
| 93 |
+
else None
|
| 94 |
+
)
|
| 95 |
+
if scorecard is None:
|
| 96 |
+
return jsonify(
|
| 97 |
+
{
|
| 98 |
+
"error": APIError.SERVER_ERROR,
|
| 99 |
+
"message": f"card_id `{card_id}` not found",
|
| 100 |
+
}
|
| 101 |
+
), 404
|
| 102 |
+
|
| 103 |
+
if scorecard.competition_mode:
|
| 104 |
+
return jsonify(
|
| 105 |
+
{
|
| 106 |
+
"error": APIError.SERVER_ERROR,
|
| 107 |
+
"message": "cannot get scorecard that is in competition mode",
|
| 108 |
+
}
|
| 109 |
+
), 403
|
| 110 |
+
|
| 111 |
+
if game_id is not None:
|
| 112 |
+
return self._json_with_cookie(
|
| 113 |
+
scorecard.get_json_for(game_id),
|
| 114 |
+
api_key=api_key,
|
| 115 |
+
), 200
|
| 116 |
+
else:
|
| 117 |
+
envs = self.arcade.available_environments
|
| 118 |
+
if envs is None:
|
| 119 |
+
return jsonify(
|
| 120 |
+
{
|
| 121 |
+
"error": APIError.SERVER_ERROR,
|
| 122 |
+
"message": "no environments available",
|
| 123 |
+
}
|
| 124 |
+
), 500
|
| 125 |
+
out = EnvironmentScorecard.from_scorecard(scorecard, envs)
|
| 126 |
+
out.api_key = None # do not expose api_key
|
| 127 |
+
return self._json_with_cookie(
|
| 128 |
+
out.model_dump(exclude_none=True),
|
| 129 |
+
api_key=api_key,
|
| 130 |
+
), 200
|
| 131 |
+
|
| 132 |
+
def new_scorecard(self) -> Tuple[Response, int]:
|
| 133 |
+
with self._cache_lock:
|
| 134 |
+
if self.competition_mode and self.scorecard_openned:
|
| 135 |
+
return jsonify(
|
| 136 |
+
{
|
| 137 |
+
"error": APIError.SERVER_ERROR,
|
| 138 |
+
"message": "cannot open multiple scorecards in competition mode",
|
| 139 |
+
}
|
| 140 |
+
), 409
|
| 141 |
+
self.scorecard_openned = True
|
| 142 |
+
|
| 143 |
+
data = request.get_json()
|
| 144 |
+
if not isinstance(data, dict):
|
| 145 |
+
return jsonify({"error": "request body must be a JSON object"}), 400
|
| 146 |
+
|
| 147 |
+
# ----- opaque guard-rail -----------------------------------------
|
| 148 |
+
opaque = data.get("opaque")
|
| 149 |
+
try:
|
| 150 |
+
# stringify exactly the bytes we’ll send to Postgres
|
| 151 |
+
opaque_bytes = json.dumps(opaque, separators=(",", ":")).encode("utf-8")
|
| 152 |
+
except (TypeError, ValueError):
|
| 153 |
+
return jsonify({"error": "opaque must be JSON-serialisable"}), 400
|
| 154 |
+
|
| 155 |
+
if len(opaque_bytes) > MAX_OPAQUE_BYTES:
|
| 156 |
+
return jsonify({"error": "opaque exceeds 8 KB limit"}), 400
|
| 157 |
+
# -----------------------------------------------------------------
|
| 158 |
+
|
| 159 |
+
tags = data.get("tags", [])
|
| 160 |
+
if "human" not in tags and "agent" not in tags:
|
| 161 |
+
tags.append("agent")
|
| 162 |
+
|
| 163 |
+
source_url = data.get("source_url")
|
| 164 |
+
api_key = request.headers.get("X-API-Key", "1234")
|
| 165 |
+
competition_mode_raw = data.get("competition_mode")
|
| 166 |
+
|
| 167 |
+
competition_mode: bool | None = None
|
| 168 |
+
|
| 169 |
+
# if the server is in competition mode or the client is in competition mode, set competition_mode to True
|
| 170 |
+
if self.competition_mode or competition_mode_raw is not None:
|
| 171 |
+
competition_mode = True
|
| 172 |
+
|
| 173 |
+
card_id = self.arcade.scorecard_manager.new_scorecard(
|
| 174 |
+
source_url=source_url,
|
| 175 |
+
tags=tags,
|
| 176 |
+
api_key=api_key,
|
| 177 |
+
opaque=opaque, # original Python value
|
| 178 |
+
competition_mode=competition_mode,
|
| 179 |
+
)
|
| 180 |
+
return self._json_with_cookie(
|
| 181 |
+
{"card_id": card_id},
|
| 182 |
+
api_key=api_key,
|
| 183 |
+
), 200
|
| 184 |
+
|
| 185 |
+
def close_scorecard(self) -> Tuple[Response, int]:
|
| 186 |
+
data = request.get_json()
|
| 187 |
+
if not isinstance(data, dict) or "card_id" not in data:
|
| 188 |
+
return jsonify(
|
| 189 |
+
{
|
| 190 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 191 |
+
"message": "missing `card_id` in action data",
|
| 192 |
+
}
|
| 193 |
+
), 400
|
| 194 |
+
|
| 195 |
+
api_key = request.headers.get("X-API-Key", "1234")
|
| 196 |
+
|
| 197 |
+
envs = self.arcade.available_environments
|
| 198 |
+
|
| 199 |
+
scorecard = self.arcade.scorecard_manager.get_scorecard(
|
| 200 |
+
data["card_id"], api_key
|
| 201 |
+
)
|
| 202 |
+
# IF this is a competition scorecard, we need to create all the environments for it
|
| 203 |
+
if (
|
| 204 |
+
scorecard is not None
|
| 205 |
+
and scorecard.competition_mode is not None
|
| 206 |
+
and scorecard.competition_mode
|
| 207 |
+
):
|
| 208 |
+
for env in envs:
|
| 209 |
+
if not scorecard.has_environment(env.game_id):
|
| 210 |
+
self.arcade.make(
|
| 211 |
+
env.game_id,
|
| 212 |
+
scorecard_id=scorecard.card_id,
|
| 213 |
+
save_recording=self.save_all_recordings,
|
| 214 |
+
include_frame_data=self.include_frame_data,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
api_key = request.headers.get("X-API-Key", "1234")
|
| 218 |
+
scorecard, guids, _ = self.arcade.scorecard_manager.close_scorecard(
|
| 219 |
+
data["card_id"], api_key
|
| 220 |
+
)
|
| 221 |
+
if scorecard is None:
|
| 222 |
+
return jsonify(
|
| 223 |
+
{
|
| 224 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 225 |
+
"message": f"scorecard {data['card_id']} not found",
|
| 226 |
+
}
|
| 227 |
+
), 404
|
| 228 |
+
|
| 229 |
+
if envs is None:
|
| 230 |
+
return jsonify(
|
| 231 |
+
{
|
| 232 |
+
"error": APIError.SERVER_ERROR,
|
| 233 |
+
"message": "no environments available",
|
| 234 |
+
}
|
| 235 |
+
), 500
|
| 236 |
+
|
| 237 |
+
out_internal = EnvironmentScorecard.from_scorecard(
|
| 238 |
+
scorecard, envs, do_private_tags=True
|
| 239 |
+
)
|
| 240 |
+
out = EnvironmentScorecard.from_scorecard(scorecard, envs)
|
| 241 |
+
if self.on_scorecard_close is not None:
|
| 242 |
+
self.on_scorecard_close(out_internal)
|
| 243 |
+
if guids is not None:
|
| 244 |
+
for guid in guids:
|
| 245 |
+
self.cleanup_environment(guid)
|
| 246 |
+
out.api_key = None # do not expose api_key
|
| 247 |
+
return self._json_with_cookie(
|
| 248 |
+
out.model_dump(exclude_none=True),
|
| 249 |
+
api_key=api_key,
|
| 250 |
+
), 200
|
| 251 |
+
|
| 252 |
+
def cmd(self, action: GameAction) -> Tuple[Response, int]:
|
| 253 |
+
data = request.get_json()
|
| 254 |
+
|
| 255 |
+
if not isinstance(data, dict) or "game_id" not in data:
|
| 256 |
+
return jsonify(
|
| 257 |
+
{
|
| 258 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 259 |
+
"message": "missing `game_id` in action data",
|
| 260 |
+
}
|
| 261 |
+
), 400
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
action.validate_data(data)
|
| 265 |
+
except ValidationError:
|
| 266 |
+
return jsonify(
|
| 267 |
+
{"error": APIError.VALIDATION_ERROR.name, "message": "{e}}"}
|
| 268 |
+
), 400
|
| 269 |
+
|
| 270 |
+
out = {}
|
| 271 |
+
for field, model in action.action_type.model_fields.items():
|
| 272 |
+
out[field] = data[field]
|
| 273 |
+
|
| 274 |
+
api_key = request.headers.get("X-API-Key", "1234")
|
| 275 |
+
game_id = data["game_id"]
|
| 276 |
+
|
| 277 |
+
game, full_reset = self._get_or_create_environment(
|
| 278 |
+
game_id=game_id,
|
| 279 |
+
scorecard_id=data.get("card_id", None),
|
| 280 |
+
guid=data.get("guid", None),
|
| 281 |
+
api_key=api_key,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
if game:
|
| 285 |
+
if game.api_key != api_key: # type: ignore[attr-defined]
|
| 286 |
+
return jsonify(
|
| 287 |
+
{
|
| 288 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 289 |
+
"message": f"game {game_id} with guid {data.get('guid', '')} does not match API key {api_key}",
|
| 290 |
+
}
|
| 291 |
+
), 400
|
| 292 |
+
|
| 293 |
+
guid = data.get("guid")
|
| 294 |
+
if action == GameAction.RESET:
|
| 295 |
+
if not guid:
|
| 296 |
+
guid = game._guid
|
| 297 |
+
|
| 298 |
+
if not guid:
|
| 299 |
+
return jsonify(
|
| 300 |
+
{
|
| 301 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 302 |
+
"message": "missing `guid` for any action other than RESET",
|
| 303 |
+
}
|
| 304 |
+
), 400
|
| 305 |
+
|
| 306 |
+
g = game
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
input_action = ActionInput(
|
| 310 |
+
id=action,
|
| 311 |
+
data=out,
|
| 312 |
+
reasoning=data.get("reasoning"),
|
| 313 |
+
)
|
| 314 |
+
# Only send the action if not a full reset (brand new game)
|
| 315 |
+
|
| 316 |
+
if not full_reset:
|
| 317 |
+
if (
|
| 318 |
+
action == GameAction.RESET
|
| 319 |
+
and isinstance(g, LocalEnvironmentWrapper)
|
| 320 |
+
and g._game is not None
|
| 321 |
+
):
|
| 322 |
+
scorecard = self.arcade.scorecard_manager.get_scorecard(
|
| 323 |
+
data.get("card_id", self.arcade.scorecard_manager.get_scorecard_from_guid(guid).card_id), api_key
|
| 324 |
+
)
|
| 325 |
+
# This is quite hacky as we have to look inside the underlying ARCBaseGame
|
| 326 |
+
# to check if this is the first action of the level and would cause a full reset,
|
| 327 |
+
if (
|
| 328 |
+
scorecard is not None
|
| 329 |
+
and scorecard.competition_mode
|
| 330 |
+
and g._game._action_count == 0
|
| 331 |
+
):
|
| 332 |
+
response = g.observation_space
|
| 333 |
+
if response is not None:
|
| 334 |
+
scorecard.update_scorecard(guid, response, full_reset)
|
| 335 |
+
else:
|
| 336 |
+
response = g.step(
|
| 337 |
+
action=input_action.id,
|
| 338 |
+
data=input_action.data,
|
| 339 |
+
reasoning=input_action.reasoning,
|
| 340 |
+
)
|
| 341 |
+
else:
|
| 342 |
+
response = g.step(
|
| 343 |
+
action=input_action.id,
|
| 344 |
+
data=input_action.data,
|
| 345 |
+
reasoning=input_action.reasoning,
|
| 346 |
+
)
|
| 347 |
+
else:
|
| 348 |
+
response = g.observation_space
|
| 349 |
+
if self.level_reset_only:
|
| 350 |
+
scorecard = self.arcade.scorecard_manager.get_scorecard(
|
| 351 |
+
data.get("card_id", None), api_key
|
| 352 |
+
)
|
| 353 |
+
if scorecard is not None and response is not None:
|
| 354 |
+
scorecard.update_scorecard(guid, response, True)
|
| 355 |
+
|
| 356 |
+
if response is None:
|
| 357 |
+
return jsonify(
|
| 358 |
+
{
|
| 359 |
+
"error": APIError.GAME_NOT_STARTED_ERROR.name,
|
| 360 |
+
"message": f"game {game_id} is available but has not been started, send {GameAction.RESET.name} to begin playing",
|
| 361 |
+
}
|
| 362 |
+
), 400
|
| 363 |
+
update = {
|
| 364 |
+
"game_id": game_id,
|
| 365 |
+
"levels_completed": response.levels_completed,
|
| 366 |
+
"win_levels": response.win_levels,
|
| 367 |
+
"frame": response.frame,
|
| 368 |
+
"state": response.state,
|
| 369 |
+
"guid": guid,
|
| 370 |
+
"action_input": response.action_input,
|
| 371 |
+
"available_actions": response.available_actions,
|
| 372 |
+
}
|
| 373 |
+
update["action_input"] = response.action_input
|
| 374 |
+
python_frame = FrameData(**update)
|
| 375 |
+
|
| 376 |
+
self._save_to_environment_cache(g, guid)
|
| 377 |
+
|
| 378 |
+
if python_frame.is_empty():
|
| 379 |
+
return jsonify(
|
| 380 |
+
{
|
| 381 |
+
"error": APIError.GAME_NOT_STARTED_ERROR.name,
|
| 382 |
+
"message": f"game {data['game_id']} is available but has not been started, send {GameAction.RESET.name} to begin playing",
|
| 383 |
+
}
|
| 384 |
+
), 400
|
| 385 |
+
|
| 386 |
+
out = python_frame.model_dump()
|
| 387 |
+
out["state"] = out["state"].name
|
| 388 |
+
out["action_input"]["id"] = out["action_input"]["id"].value
|
| 389 |
+
return self._json_with_cookie(out, api_key=api_key), 200
|
| 390 |
+
except ValidationError as exc:
|
| 391 |
+
return jsonify(
|
| 392 |
+
{
|
| 393 |
+
"error": APIError.VALIDATION_ERROR.name,
|
| 394 |
+
"message": f"error creating ActionInput: {exc}",
|
| 395 |
+
}
|
| 396 |
+
), 400
|
| 397 |
+
|
| 398 |
+
return jsonify(
|
| 399 |
+
{
|
| 400 |
+
"error": APIError.SERVER_ERROR.name,
|
| 401 |
+
"message": f"game {game_id} not found",
|
| 402 |
+
}
|
| 403 |
+
), 400
|
| 404 |
+
|
| 405 |
+
def _get_or_create_environment(
|
| 406 |
+
self, game_id: str, scorecard_id: str | None, guid: str | None, api_key: str
|
| 407 |
+
) -> tuple[EnvironmentWrapper | None, bool]:
|
| 408 |
+
with self._cache_lock:
|
| 409 |
+
game: Optional[EnvironmentWrapper] = None
|
| 410 |
+
# if there is a guid, try and find it from our cache
|
| 411 |
+
if guid and guid in self._environmentCache:
|
| 412 |
+
game = self._environmentCache.get(guid)
|
| 413 |
+
if game and game.environment_info.game_id == game_id:
|
| 414 |
+
return game, False
|
| 415 |
+
|
| 416 |
+
if not scorecard_id:
|
| 417 |
+
return None, False
|
| 418 |
+
|
| 419 |
+
scorecard = self.arcade.scorecard_manager.get_scorecard(
|
| 420 |
+
scorecard_id, api_key
|
| 421 |
+
)
|
| 422 |
+
if scorecard is None:
|
| 423 |
+
return None, False
|
| 424 |
+
if scorecard.competition_mode and scorecard.has_environment(game_id):
|
| 425 |
+
return None, False
|
| 426 |
+
|
| 427 |
+
game = self.arcade.make(
|
| 428 |
+
game_id,
|
| 429 |
+
scorecard_id=scorecard_id,
|
| 430 |
+
save_recording=self.save_all_recordings,
|
| 431 |
+
include_frame_data=self.include_frame_data,
|
| 432 |
+
renderer=self.renderer,
|
| 433 |
+
)
|
| 434 |
+
if game is None:
|
| 435 |
+
return None, False
|
| 436 |
+
setattr(game, "api_key", api_key)
|
| 437 |
+
return game, True
|
| 438 |
+
|
| 439 |
+
def _save_to_environment_cache(
|
| 440 |
+
self, environment: EnvironmentWrapper, guid: str
|
| 441 |
+
) -> None:
|
| 442 |
+
with self._cache_lock:
|
| 443 |
+
self._environmentCache[guid] = environment
|
| 444 |
+
|
| 445 |
+
def scorecard_cleanup_loop(self) -> None:
|
| 446 |
+
"""Wake up every minute and close stale scorecards."""
|
| 447 |
+
while True:
|
| 448 |
+
time.sleep(60)
|
| 449 |
+
stale_ids = self.arcade.scorecard_manager.get_stale_cards()
|
| 450 |
+
mgr = self.arcade.scorecard_manager
|
| 451 |
+
for cid in stale_ids:
|
| 452 |
+
if not mgr.should_auto_close_scorecard(cid):
|
| 453 |
+
self.arcade.logger.info(
|
| 454 |
+
"[auto-close] scorecard %s no longer eligible for auto-close, skipping",
|
| 455 |
+
cid,
|
| 456 |
+
)
|
| 457 |
+
continue
|
| 458 |
+
idle = mgr.idle_duration_for(cid)
|
| 459 |
+
idle_sec = idle.total_seconds() if idle is not None else -1.0
|
| 460 |
+
self.arcade.logger.info(
|
| 461 |
+
"[auto-close] closing scorecard card_id=%s idle_seconds=%.1f "
|
| 462 |
+
"threshold_seconds=%.1f",
|
| 463 |
+
cid,
|
| 464 |
+
idle_sec,
|
| 465 |
+
mgr.idle_for.total_seconds(),
|
| 466 |
+
)
|
| 467 |
+
scorecard, guids, _ = self.arcade.scorecard_manager.close_scorecard(
|
| 468 |
+
cid, None
|
| 469 |
+
)
|
| 470 |
+
if scorecard is not None:
|
| 471 |
+
if self.arcade._on_scorecard_close is not None:
|
| 472 |
+
env_scorecard = EnvironmentScorecard.from_scorecard(
|
| 473 |
+
scorecard,
|
| 474 |
+
self.arcade.available_environments,
|
| 475 |
+
do_private_tags=True,
|
| 476 |
+
)
|
| 477 |
+
cb = self.arcade._on_scorecard_close
|
| 478 |
+
log = self.arcade.logger
|
| 479 |
+
|
| 480 |
+
def _run_close_hook() -> None:
|
| 481 |
+
try:
|
| 482 |
+
cb(env_scorecard)
|
| 483 |
+
except Exception:
|
| 484 |
+
log.exception(
|
| 485 |
+
"[auto-close] on_scorecard_close failed for card_id=%s",
|
| 486 |
+
env_scorecard.card_id,
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
threading.Thread(
|
| 490 |
+
target=_run_close_hook,
|
| 491 |
+
daemon=True,
|
| 492 |
+
name=f"scorecard-close-{cid[:8]}",
|
| 493 |
+
).start()
|
| 494 |
+
if guids is not None:
|
| 495 |
+
for guid in guids:
|
| 496 |
+
self.cleanup_environment(guid)
|
| 497 |
+
|
| 498 |
+
def cleanup_environment(self, guid: str) -> None:
|
| 499 |
+
with self._cache_lock:
|
| 500 |
+
if guid in self._environmentCache:
|
| 501 |
+
del self._environmentCache[guid]
|
arcprize__ARC-AGI/arc_agi/base.py
ADDED
|
@@ -0,0 +1,1126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base class for ARC-AGI-3 environments."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import threading
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from enum import Enum
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Callable, Optional
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
from arcengine import FrameDataRaw
|
| 14 |
+
from dotenv import load_dotenv
|
| 15 |
+
from flask import Flask, Response
|
| 16 |
+
from pydantic import ValidationError
|
| 17 |
+
|
| 18 |
+
from .local_wrapper import LocalEnvironmentWrapper
|
| 19 |
+
from .models import EnvironmentInfo
|
| 20 |
+
from .remote_wrapper import RemoteEnvironmentWrapper
|
| 21 |
+
from .rendering import render_frames, render_frames_terminal
|
| 22 |
+
from .scorecard import EnvironmentScorecard, ScorecardManager
|
| 23 |
+
from .wrapper import EnvironmentWrapper
|
| 24 |
+
|
| 25 |
+
# Load environment variables from .env and then .env.example
|
| 26 |
+
# Handle missing files and permission errors gracefully
|
| 27 |
+
try:
|
| 28 |
+
load_dotenv(dotenv_path=".env")
|
| 29 |
+
except (OSError, PermissionError, FileNotFoundError):
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
load_dotenv(dotenv_path=".env.example")
|
| 35 |
+
except (OSError, PermissionError, FileNotFoundError):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class OperationMode(str, Enum):
|
| 40 |
+
"""Mode for environment discovery and usage.
|
| 41 |
+
|
| 42 |
+
- NORMAL: Use both local environments and API (default).
|
| 43 |
+
- ONLINE: Use only remote environments via API.
|
| 44 |
+
- OFFLINE: Use only locally available environments.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
NORMAL = "normal"
|
| 48 |
+
ONLINE = "online"
|
| 49 |
+
OFFLINE = "offline"
|
| 50 |
+
COMPETITION = "competition"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Arcade:
|
| 54 |
+
"""Base class for ARC-AGI-3 environments.
|
| 55 |
+
|
| 56 |
+
This class handles configuration loading from environment variables and
|
| 57 |
+
constructor parameters. Environment variables are loaded from .env.example
|
| 58 |
+
and .env files using python-dotenv.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
arc_api_key: str = "",
|
| 64 |
+
arc_base_url: str = "https://three.arcprize.org",
|
| 65 |
+
operation_mode: OperationMode = OperationMode.NORMAL,
|
| 66 |
+
environments_dir: str = "environment_files",
|
| 67 |
+
recordings_dir: str = "recordings",
|
| 68 |
+
logger: Optional[logging.Logger] = None,
|
| 69 |
+
) -> None:
|
| 70 |
+
"""Initialize ARCAGI3 instance.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
arc_api_key: API key for ARC API. Defaults to empty string.
|
| 74 |
+
Can be overridden by ARC_API_KEY environment variable.
|
| 75 |
+
arc_base_url: Base URL for ARC API. Defaults to "https://three.arcprize.org".
|
| 76 |
+
Can be overridden by ARC_BASE_URL environment variable.
|
| 77 |
+
operation_mode: NORMAL (local + API), ONLINE (API only), or OFFLINE (local only).
|
| 78 |
+
Defaults to NORMAL. Can be overridden by OPERATION_MODE env var
|
| 79 |
+
("normal", "online", "offline", "competition").
|
| 80 |
+
environments_dir: Directory to scan for metadata.json files. Defaults to "environment_files".
|
| 81 |
+
Can be overridden by ENVIRONMENTS_DIR environment variable.
|
| 82 |
+
recordings_dir: Directory to save recordings. Defaults to "recordings".
|
| 83 |
+
Can be overridden by RECORDINGS_DIR environment variable.
|
| 84 |
+
logger: Optional logger instance. Defaults to a logger that logs to STDOUT.
|
| 85 |
+
"""
|
| 86 |
+
# Priority order: constructor args > env vars > defaults
|
| 87 |
+
|
| 88 |
+
# arc_api_key: constructor arg > env var > default ""
|
| 89 |
+
if arc_api_key != "":
|
| 90 |
+
self.arc_api_key = arc_api_key
|
| 91 |
+
else:
|
| 92 |
+
self.arc_api_key = os.getenv("ARC_API_KEY", "")
|
| 93 |
+
|
| 94 |
+
# arc_base_url: constructor arg > env var > default URL
|
| 95 |
+
default_base_url = "https://three.arcprize.org"
|
| 96 |
+
if arc_base_url != default_base_url:
|
| 97 |
+
self.arc_base_url = arc_base_url
|
| 98 |
+
else:
|
| 99 |
+
self.arc_base_url = os.getenv("ARC_BASE_URL", default_base_url)
|
| 100 |
+
|
| 101 |
+
# Priority order for competition mode is different, the env var takes precedence over the constructor arg
|
| 102 |
+
env_operation_mode = self._parse_operation_mode_from_env()
|
| 103 |
+
|
| 104 |
+
self.operation_mode: OperationMode = operation_mode
|
| 105 |
+
|
| 106 |
+
# operation_mode: constructor arg > env var > default NORMAL
|
| 107 |
+
if (
|
| 108 |
+
env_operation_mode == OperationMode.COMPETITION
|
| 109 |
+
or self.operation_mode == OperationMode.NORMAL
|
| 110 |
+
):
|
| 111 |
+
self.operation_mode = env_operation_mode
|
| 112 |
+
|
| 113 |
+
# environments_dir: constructor arg > env var > default
|
| 114 |
+
default_environments_dir = "environment_files"
|
| 115 |
+
if environments_dir != default_environments_dir:
|
| 116 |
+
self.environments_dir = environments_dir
|
| 117 |
+
else:
|
| 118 |
+
self.environments_dir = os.getenv(
|
| 119 |
+
"ENVIRONMENTS_DIR", default_environments_dir
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# recordings_dir: constructor arg > env var > default
|
| 123 |
+
default_recordings_dir = "recordings"
|
| 124 |
+
if recordings_dir != default_recordings_dir:
|
| 125 |
+
self.recordings_dir = recordings_dir
|
| 126 |
+
else:
|
| 127 |
+
self.recordings_dir = os.getenv("RECORDINGS_DIR", default_recordings_dir)
|
| 128 |
+
|
| 129 |
+
# Set up logger - default to STDOUT if not provided
|
| 130 |
+
if logger is not None:
|
| 131 |
+
self.logger = logger
|
| 132 |
+
else:
|
| 133 |
+
self.logger = logging.getLogger(__name__)
|
| 134 |
+
self.logger.setLevel(logging.INFO)
|
| 135 |
+
# Remove existing handlers to avoid duplicates
|
| 136 |
+
self.logger.handlers.clear()
|
| 137 |
+
# Create STDOUT handler
|
| 138 |
+
stdout_handler = logging.StreamHandler(sys.stdout)
|
| 139 |
+
stdout_handler.setLevel(logging.INFO)
|
| 140 |
+
formatter = logging.Formatter(
|
| 141 |
+
"%(asctime)s | %(levelname)s | %(message)s",
|
| 142 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 143 |
+
)
|
| 144 |
+
stdout_handler.setFormatter(formatter)
|
| 145 |
+
self.logger.addHandler(stdout_handler)
|
| 146 |
+
|
| 147 |
+
# Create scorecard manager
|
| 148 |
+
self.scorecard_manager = ScorecardManager(recordings_dir=self.recordings_dir)
|
| 149 |
+
|
| 150 |
+
# Store default scorecard_id (will be created on first make() call if needed)
|
| 151 |
+
self._default_scorecard_id: Optional[str] = None
|
| 152 |
+
|
| 153 |
+
# Scan for available environments
|
| 154 |
+
self.available_environments: list[EnvironmentInfo] = []
|
| 155 |
+
self._scan_for_environments()
|
| 156 |
+
|
| 157 |
+
if (
|
| 158 |
+
self.operation_mode == OperationMode.ONLINE
|
| 159 |
+
or self.operation_mode == OperationMode.COMPETITION
|
| 160 |
+
):
|
| 161 |
+
self.headers = {
|
| 162 |
+
"X-API-Key": self.arc_api_key,
|
| 163 |
+
"Accept": "application/json",
|
| 164 |
+
}
|
| 165 |
+
self._session = requests.Session()
|
| 166 |
+
self._session.headers.update(self.headers)
|
| 167 |
+
self._master_cookie_jar = requests.cookies.RequestsCookieJar()
|
| 168 |
+
|
| 169 |
+
self._lock = threading.Lock()
|
| 170 |
+
self._cookie_lock = threading.Lock()
|
| 171 |
+
|
| 172 |
+
if self.arc_api_key == "" or self.arc_api_key is None:
|
| 173 |
+
if self.operation_mode != OperationMode.OFFLINE:
|
| 174 |
+
self.arc_api_key = self._get_anonymous_api_key()
|
| 175 |
+
|
| 176 |
+
# Fetch from API if not in offline mode
|
| 177 |
+
if self.operation_mode != OperationMode.OFFLINE:
|
| 178 |
+
self._fetch_from_api()
|
| 179 |
+
|
| 180 |
+
# Callback for when a scorecard is closed, defaults to None
|
| 181 |
+
# Set by listen_and_serve()
|
| 182 |
+
self.on_scorecard_close: Optional[Callable[[EnvironmentScorecard], None]] = None
|
| 183 |
+
|
| 184 |
+
def _parse_operation_mode_from_env(self) -> OperationMode:
|
| 185 |
+
"""Resolve operation mode from env: OPERATION_MODE"""
|
| 186 |
+
env_op = os.getenv("OPERATION_MODE", "").strip().lower()
|
| 187 |
+
if env_op in ("normal", "online", "offline", "competition"):
|
| 188 |
+
return OperationMode(env_op)
|
| 189 |
+
return OperationMode.NORMAL
|
| 190 |
+
|
| 191 |
+
def _get_anonymous_api_key(self) -> str:
|
| 192 |
+
"""Get an anonymous API key."""
|
| 193 |
+
url = f"{self.arc_base_url}/api/games/anonkey"
|
| 194 |
+
headers = {
|
| 195 |
+
"Accept": "application/json",
|
| 196 |
+
}
|
| 197 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 198 |
+
response.raise_for_status()
|
| 199 |
+
json_data = response.json()
|
| 200 |
+
if "api_key" in json_data:
|
| 201 |
+
key = json_data["api_key"]
|
| 202 |
+
self.logger.info(f"Got anonymous API key: {key}")
|
| 203 |
+
self.logger.info(f"You can register for an API key at {self.arc_base_url}")
|
| 204 |
+
return str(key)
|
| 205 |
+
return ""
|
| 206 |
+
|
| 207 |
+
def _scan_for_environments(self) -> None:
|
| 208 |
+
"""Scan environments_dir for metadata.json files and load them as EnvironmentInfo."""
|
| 209 |
+
if self.environments_dir is None:
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
environments_path = Path(self.environments_dir)
|
| 213 |
+
if not environments_path.exists() or not environments_path.is_dir():
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
# Recursively find all metadata.json files
|
| 217 |
+
for metadata_file in environments_path.rglob("metadata.json"):
|
| 218 |
+
try:
|
| 219 |
+
# Read and parse the JSON file
|
| 220 |
+
json_data = metadata_file.read_text(encoding="utf-8")
|
| 221 |
+
env_info = EnvironmentInfo.model_validate_json(json_data)
|
| 222 |
+
# Set local_dir to the parent directory of metadata.json
|
| 223 |
+
env_info.local_dir = str(metadata_file.parent)
|
| 224 |
+
self.available_environments.append(env_info)
|
| 225 |
+
except Exception as e:
|
| 226 |
+
# Skip files that fail to load (invalid JSON, missing fields, etc.)
|
| 227 |
+
self.logger.warning(
|
| 228 |
+
f"Failed to load metadata.json from {metadata_file}: {e}",
|
| 229 |
+
exc_info=True,
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
|
| 233 |
+
def _fetch_from_api(self) -> None:
|
| 234 |
+
"""Fetch available environments from the API and merge with local environments."""
|
| 235 |
+
if not self.arc_api_key:
|
| 236 |
+
# Skip API call if no API key is provided
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
try:
|
| 240 |
+
url = f"{self.arc_base_url}/api/games"
|
| 241 |
+
headers = {
|
| 242 |
+
"X-Api-Key": self.arc_api_key,
|
| 243 |
+
"Accept": "application/json",
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 247 |
+
response.raise_for_status()
|
| 248 |
+
|
| 249 |
+
# Parse response
|
| 250 |
+
games_data = response.json()
|
| 251 |
+
|
| 252 |
+
# Convert API response to EnvironmentInfo objects
|
| 253 |
+
api_environments: list[EnvironmentInfo] = []
|
| 254 |
+
for game_data in games_data:
|
| 255 |
+
try:
|
| 256 |
+
# API may return different structure, adapt as needed
|
| 257 |
+
# Assuming API returns list of dicts with at least game_id and title
|
| 258 |
+
env_info = EnvironmentInfo(
|
| 259 |
+
game_id=game_data.get("game_id", ""),
|
| 260 |
+
title=game_data.get("title", ""),
|
| 261 |
+
tags=game_data.get("tags", []),
|
| 262 |
+
baseline_actions=game_data.get("baseline_actions", []),
|
| 263 |
+
date_downloaded=game_data.get("date_downloaded"),
|
| 264 |
+
class_name=game_data.get("class_name"),
|
| 265 |
+
)
|
| 266 |
+
api_environments.append(env_info)
|
| 267 |
+
except Exception as e:
|
| 268 |
+
# Skip invalid entries
|
| 269 |
+
game_id = game_data.get("game_id", "unknown")
|
| 270 |
+
self.logger.warning(
|
| 271 |
+
f"Failed to parse API environment entry (game_id: {game_id}): {e}",
|
| 272 |
+
exc_info=True,
|
| 273 |
+
)
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
# Merge with existing environments, removing duplicates by game_id
|
| 277 |
+
existing_game_ids = {env.game_id for env in self.available_environments}
|
| 278 |
+
for api_env in api_environments:
|
| 279 |
+
if api_env.game_id not in existing_game_ids:
|
| 280 |
+
self.available_environments.append(api_env)
|
| 281 |
+
existing_game_ids.add(api_env.game_id)
|
| 282 |
+
|
| 283 |
+
if api_environments:
|
| 284 |
+
self.logger.info(
|
| 285 |
+
f"Successfully fetched {len(api_environments)} environment(s) from API"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
except requests.exceptions.RequestException as e:
|
| 289 |
+
# Network or HTTP errors
|
| 290 |
+
self.logger.error(
|
| 291 |
+
f"Failed to fetch environments from API ({self.arc_base_url}/api/games): {e}",
|
| 292 |
+
exc_info=True,
|
| 293 |
+
)
|
| 294 |
+
except Exception as e:
|
| 295 |
+
# Other errors (invalid JSON, unexpected response format, etc.)
|
| 296 |
+
self.logger.error(
|
| 297 |
+
f"Unexpected error while fetching environments from API: {e}",
|
| 298 |
+
exc_info=True,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
def get_environments(self) -> list[EnvironmentInfo]:
|
| 302 |
+
"""Get the list of available environments.
|
| 303 |
+
|
| 304 |
+
Returns:
|
| 305 |
+
List of EnvironmentInfo objects representing available environments.
|
| 306 |
+
"""
|
| 307 |
+
return self.available_environments
|
| 308 |
+
|
| 309 |
+
def _create_renderer_from_mode(
|
| 310 |
+
self,
|
| 311 |
+
render_mode: Optional[str],
|
| 312 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]],
|
| 313 |
+
environment_info: EnvironmentInfo,
|
| 314 |
+
) -> Optional[Callable[[int, FrameDataRaw], None]]:
|
| 315 |
+
"""Create a renderer callable from render_mode if needed.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
render_mode: Optional render mode string ("human", "terminal", "terminal-fast").
|
| 319 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 320 |
+
environment_info: EnvironmentInfo to get default_fps from.
|
| 321 |
+
|
| 322 |
+
Returns:
|
| 323 |
+
Renderer callable if render_mode or renderer is provided, None otherwise.
|
| 324 |
+
"""
|
| 325 |
+
# If renderer is provided, use it directly
|
| 326 |
+
if renderer is not None:
|
| 327 |
+
return renderer
|
| 328 |
+
|
| 329 |
+
# If render_mode is provided, create a callable from it
|
| 330 |
+
if render_mode is not None:
|
| 331 |
+
default_fps = environment_info.default_fps
|
| 332 |
+
if render_mode == "terminal":
|
| 333 |
+
return lambda steps, frame_data: render_frames_terminal(
|
| 334 |
+
steps=steps,
|
| 335 |
+
frame_data=frame_data,
|
| 336 |
+
default_fps=default_fps,
|
| 337 |
+
scale=1,
|
| 338 |
+
)
|
| 339 |
+
if render_mode == "terminal-fast":
|
| 340 |
+
return lambda steps, frame_data: render_frames_terminal(
|
| 341 |
+
steps=steps,
|
| 342 |
+
frame_data=frame_data,
|
| 343 |
+
default_fps=default_fps,
|
| 344 |
+
scale=1,
|
| 345 |
+
skip_deplay=True,
|
| 346 |
+
)
|
| 347 |
+
elif render_mode == "human":
|
| 348 |
+
return lambda steps, frame_data: render_frames(
|
| 349 |
+
steps=steps,
|
| 350 |
+
frame_data=frame_data,
|
| 351 |
+
default_fps=default_fps,
|
| 352 |
+
scale=4,
|
| 353 |
+
)
|
| 354 |
+
else:
|
| 355 |
+
self.logger.warning(
|
| 356 |
+
f"Unknown render_mode: {render_mode}. No renderer will be used."
|
| 357 |
+
)
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
return None
|
| 361 |
+
|
| 362 |
+
def open_scorecard(
|
| 363 |
+
self,
|
| 364 |
+
source_url: Optional[str] = None,
|
| 365 |
+
tags: Optional[list[str]] = None,
|
| 366 |
+
opaque: Optional[Any] = None,
|
| 367 |
+
) -> str:
|
| 368 |
+
"""Open a scorecard by ID.
|
| 369 |
+
|
| 370 |
+
Args:
|
| 371 |
+
scorecard_id: The ID of the scorecard to open.
|
| 372 |
+
|
| 373 |
+
Returns:
|
| 374 |
+
The EnvironmentScorecard object.
|
| 375 |
+
"""
|
| 376 |
+
return self.create_scorecard(source_url, tags, opaque)
|
| 377 |
+
|
| 378 |
+
def create_scorecard(
|
| 379 |
+
self,
|
| 380 |
+
source_url: Optional[str] = None,
|
| 381 |
+
tags: Optional[list[str]] = None,
|
| 382 |
+
opaque: Optional[Any] = None,
|
| 383 |
+
) -> str:
|
| 384 |
+
"""Create a new scorecard.
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
source_url: Optional source URL for the scorecard.
|
| 388 |
+
tags: Optional list of tags for the scorecard.
|
| 389 |
+
opaque: Optional opaque data for the scorecard.
|
| 390 |
+
|
| 391 |
+
Returns:
|
| 392 |
+
The ID of the newly created scorecard.
|
| 393 |
+
"""
|
| 394 |
+
with self._lock:
|
| 395 |
+
return self._create_scorecard_no_lock(source_url, tags, opaque)
|
| 396 |
+
|
| 397 |
+
def _create_scorecard_no_lock(
|
| 398 |
+
self,
|
| 399 |
+
source_url: Optional[str] = None,
|
| 400 |
+
tags: Optional[list[str]] = None,
|
| 401 |
+
opaque: Optional[Any] = None,
|
| 402 |
+
) -> str:
|
| 403 |
+
"""Create a new scorecard.
|
| 404 |
+
|
| 405 |
+
Args:
|
| 406 |
+
source_url: Optional source URL for the scorecard.
|
| 407 |
+
tags: Optional list of tags for the scorecard.
|
| 408 |
+
opaque: Optional opaque data for the scorecard.
|
| 409 |
+
|
| 410 |
+
Returns:
|
| 411 |
+
The ID of the newly created scorecard.
|
| 412 |
+
"""
|
| 413 |
+
if (
|
| 414 |
+
self.operation_mode == OperationMode.ONLINE
|
| 415 |
+
or self.operation_mode == OperationMode.COMPETITION
|
| 416 |
+
):
|
| 417 |
+
url = f"{self.arc_base_url}/api/scorecard/open"
|
| 418 |
+
headers = {
|
| 419 |
+
"X-API-Key": self.arc_api_key,
|
| 420 |
+
"Accept": "application/json",
|
| 421 |
+
}
|
| 422 |
+
payload: dict[str, Any] = {}
|
| 423 |
+
if tags is not None:
|
| 424 |
+
payload["tags"] = tags
|
| 425 |
+
else:
|
| 426 |
+
payload["tags"] = ["wrapper"]
|
| 427 |
+
if source_url is not None:
|
| 428 |
+
payload["source_url"] = source_url
|
| 429 |
+
if opaque is not None:
|
| 430 |
+
payload["opaque"] = opaque
|
| 431 |
+
if self.operation_mode == OperationMode.COMPETITION:
|
| 432 |
+
payload["competition_mode"] = True
|
| 433 |
+
|
| 434 |
+
with self._cookie_lock:
|
| 435 |
+
self._session.cookies.update(self._master_cookie_jar) # type: ignore[no-untyped-call]
|
| 436 |
+
|
| 437 |
+
response = self._session.post(
|
| 438 |
+
url, headers=headers, json=payload, timeout=10
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
with self._cookie_lock:
|
| 442 |
+
self._master_cookie_jar.update(self._session.cookies) # type: ignore[no-untyped-call]
|
| 443 |
+
|
| 444 |
+
response.raise_for_status()
|
| 445 |
+
card_id = response.json()["card_id"]
|
| 446 |
+
self.logger.info(f"Created new scorecard: {card_id}")
|
| 447 |
+
return str(card_id)
|
| 448 |
+
|
| 449 |
+
# Local scorecard (NORMAL or OFFLINE)
|
| 450 |
+
card_id = self.scorecard_manager.new_scorecard(
|
| 451 |
+
source_url=source_url,
|
| 452 |
+
tags=tags,
|
| 453 |
+
api_key=self.arc_api_key,
|
| 454 |
+
opaque=opaque,
|
| 455 |
+
)
|
| 456 |
+
self.logger.info(f"Created new scorecard: {card_id}")
|
| 457 |
+
return str(card_id)
|
| 458 |
+
|
| 459 |
+
def close_scorecard(
|
| 460 |
+
self, scorecard_id: Optional[str] = None
|
| 461 |
+
) -> Optional[EnvironmentScorecard]:
|
| 462 |
+
with self._lock:
|
| 463 |
+
if scorecard_id is None:
|
| 464 |
+
scorecard_id = self._default_scorecard_id
|
| 465 |
+
|
| 466 |
+
if scorecard_id is None:
|
| 467 |
+
return None
|
| 468 |
+
|
| 469 |
+
if (
|
| 470 |
+
self.operation_mode == OperationMode.ONLINE
|
| 471 |
+
or self.operation_mode == OperationMode.COMPETITION
|
| 472 |
+
):
|
| 473 |
+
url = f"{self.arc_base_url}/api/scorecard/close"
|
| 474 |
+
headers = {
|
| 475 |
+
"X-API-Key": self.arc_api_key,
|
| 476 |
+
"Accept": "application/json",
|
| 477 |
+
}
|
| 478 |
+
data = {
|
| 479 |
+
"card_id": scorecard_id,
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
with self._cookie_lock:
|
| 483 |
+
self._session.cookies.update(self._master_cookie_jar) # type: ignore[no-untyped-call]
|
| 484 |
+
|
| 485 |
+
response = self._session.post(
|
| 486 |
+
url, headers=headers, json=data, timeout=10
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
with self._cookie_lock:
|
| 490 |
+
self._master_cookie_jar.update(self._session.cookies) # type: ignore[no-untyped-call]
|
| 491 |
+
|
| 492 |
+
response.raise_for_status()
|
| 493 |
+
if scorecard_id == self._default_scorecard_id:
|
| 494 |
+
self._default_scorecard_id = None
|
| 495 |
+
self.logger.info(f"Closed scorecard: {scorecard_id}")
|
| 496 |
+
return self._convert_scorecard_to_environment_scorecard(response.json())
|
| 497 |
+
|
| 498 |
+
scorecard, _, _ = self.scorecard_manager.close_scorecard(
|
| 499 |
+
scorecard_id, self.arc_api_key
|
| 500 |
+
)
|
| 501 |
+
if scorecard is None:
|
| 502 |
+
return None
|
| 503 |
+
|
| 504 |
+
# Convert to EnvironmentScorecard using available environments
|
| 505 |
+
out = EnvironmentScorecard.from_scorecard(
|
| 506 |
+
scorecard, self.available_environments
|
| 507 |
+
)
|
| 508 |
+
out.api_key = None
|
| 509 |
+
if scorecard_id == self._default_scorecard_id:
|
| 510 |
+
self._default_scorecard_id = None
|
| 511 |
+
|
| 512 |
+
self.logger.info(f"Closed scorecard: {scorecard_id}")
|
| 513 |
+
return out
|
| 514 |
+
|
| 515 |
+
def get_scorecard(
|
| 516 |
+
self, scorecard_id: Optional[str] = None
|
| 517 |
+
) -> Optional[EnvironmentScorecard]:
|
| 518 |
+
"""Get a scorecard by ID, converted to EnvironmentScorecard.
|
| 519 |
+
|
| 520 |
+
Args:
|
| 521 |
+
scorecard_id: Optional scorecard ID. If not provided, returns the default scorecard.
|
| 522 |
+
|
| 523 |
+
Returns:
|
| 524 |
+
EnvironmentScorecard object if found, None otherwise.
|
| 525 |
+
"""
|
| 526 |
+
with self._lock:
|
| 527 |
+
if scorecard_id is None:
|
| 528 |
+
if self._default_scorecard_id is None:
|
| 529 |
+
# Create default scorecard if it doesn't exist
|
| 530 |
+
self._default_scorecard_id = self._create_scorecard_no_lock()
|
| 531 |
+
scorecard_id = self._default_scorecard_id
|
| 532 |
+
|
| 533 |
+
if (
|
| 534 |
+
self.operation_mode == OperationMode.ONLINE
|
| 535 |
+
or self.operation_mode == OperationMode.COMPETITION
|
| 536 |
+
):
|
| 537 |
+
url = f"{self.arc_base_url}/api/scorecard/{scorecard_id}"
|
| 538 |
+
headers = {
|
| 539 |
+
"X-API-Key": self.arc_api_key,
|
| 540 |
+
"Accept": "application/json",
|
| 541 |
+
}
|
| 542 |
+
with self._cookie_lock:
|
| 543 |
+
self._session.cookies.update(self._master_cookie_jar) # type: ignore[no-untyped-call]
|
| 544 |
+
|
| 545 |
+
response = self._session.get(url, headers=headers, timeout=10)
|
| 546 |
+
|
| 547 |
+
with self._cookie_lock:
|
| 548 |
+
self._master_cookie_jar.update(self._session.cookies) # type: ignore[no-untyped-call]
|
| 549 |
+
|
| 550 |
+
response.raise_for_status()
|
| 551 |
+
return self._convert_scorecard_to_environment_scorecard(response.json())
|
| 552 |
+
|
| 553 |
+
# Get scorecard from manager
|
| 554 |
+
scorecard = self.scorecard_manager.get_scorecard(
|
| 555 |
+
scorecard_id, self.arc_api_key
|
| 556 |
+
)
|
| 557 |
+
if scorecard is None:
|
| 558 |
+
return None
|
| 559 |
+
|
| 560 |
+
# Convert to EnvironmentScorecard using available environments
|
| 561 |
+
out = EnvironmentScorecard.from_scorecard(
|
| 562 |
+
scorecard, self.available_environments
|
| 563 |
+
)
|
| 564 |
+
out.api_key = None
|
| 565 |
+
return out
|
| 566 |
+
|
| 567 |
+
def _convert_scorecard_to_environment_scorecard(
|
| 568 |
+
self, data: dict[str, Any]
|
| 569 |
+
) -> EnvironmentScorecard:
|
| 570 |
+
"""Convert a scorecard from the API to an EnvironmentScorecard."""
|
| 571 |
+
try:
|
| 572 |
+
if "open_at" in data:
|
| 573 |
+
del data["open_at"]
|
| 574 |
+
if "last_update" in data:
|
| 575 |
+
del data["last_update"]
|
| 576 |
+
out = EnvironmentScorecard.model_validate(data)
|
| 577 |
+
except ValidationError as e:
|
| 578 |
+
raise ValueError(f"Invalid EnvironmentScorecard from {data}: {e}") from e
|
| 579 |
+
|
| 580 |
+
out.api_key = None
|
| 581 |
+
return out
|
| 582 |
+
|
| 583 |
+
def make(
|
| 584 |
+
self,
|
| 585 |
+
game_id: str,
|
| 586 |
+
seed: int = 0,
|
| 587 |
+
scorecard_id: Optional[str] = None,
|
| 588 |
+
save_recording: bool = False,
|
| 589 |
+
include_frame_data: bool = True,
|
| 590 |
+
render_mode: Optional[str] = None,
|
| 591 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 592 |
+
) -> Optional[EnvironmentWrapper]:
|
| 593 |
+
"""Make (download and prepare) an environment.
|
| 594 |
+
|
| 595 |
+
Args:
|
| 596 |
+
game_id: Game identifier in format 'ls20' or 'ls20-1234abcd'.
|
| 597 |
+
The first 4 characters are the game_id, everything after '-' is the version.
|
| 598 |
+
scorecard_id: Optional scorecard ID for tracking runs. If not provided,
|
| 599 |
+
a new scorecard will be created and stored for subsequent calls.
|
| 600 |
+
save_recording: Whether to save recordings to JSONL file.
|
| 601 |
+
render_mode: Optional render mode string ("human", "terminal"). If provided,
|
| 602 |
+
creates a renderer callable automatically.
|
| 603 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 604 |
+
If both render_mode and renderer are provided, renderer takes precedence.
|
| 605 |
+
|
| 606 |
+
Returns:
|
| 607 |
+
LocalEnvironmentWrapper object if successful, None otherwise.
|
| 608 |
+
"""
|
| 609 |
+
with self._lock:
|
| 610 |
+
# If scorecard_id not provided, use or create default
|
| 611 |
+
if scorecard_id is None:
|
| 612 |
+
if self._default_scorecard_id is None:
|
| 613 |
+
scorecard_id = self._create_scorecard_no_lock()
|
| 614 |
+
self._default_scorecard_id = scorecard_id
|
| 615 |
+
scorecard_id = self._default_scorecard_id
|
| 616 |
+
|
| 617 |
+
# Split game_id into base_id and version
|
| 618 |
+
if "-" in game_id:
|
| 619 |
+
base_id, version = game_id.split("-", 1)
|
| 620 |
+
else:
|
| 621 |
+
base_id = game_id
|
| 622 |
+
version = None
|
| 623 |
+
|
| 624 |
+
# OFFLINE mode: search in scanned environments only
|
| 625 |
+
if self.operation_mode == OperationMode.OFFLINE:
|
| 626 |
+
return self._find_local_game(
|
| 627 |
+
base_id,
|
| 628 |
+
version,
|
| 629 |
+
scorecard_id,
|
| 630 |
+
save_recording,
|
| 631 |
+
include_frame_data,
|
| 632 |
+
seed,
|
| 633 |
+
render_mode,
|
| 634 |
+
renderer,
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# NORMAL mode: download game and run locally
|
| 638 |
+
if self.operation_mode == OperationMode.NORMAL:
|
| 639 |
+
return self._download_game(
|
| 640 |
+
base_id,
|
| 641 |
+
version,
|
| 642 |
+
scorecard_id,
|
| 643 |
+
save_recording,
|
| 644 |
+
include_frame_data,
|
| 645 |
+
seed,
|
| 646 |
+
render_mode,
|
| 647 |
+
renderer,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
# ONLINE mode: create remote wrapper
|
| 651 |
+
return self._create_remote_wrapper(
|
| 652 |
+
base_id,
|
| 653 |
+
version,
|
| 654 |
+
scorecard_id,
|
| 655 |
+
save_recording,
|
| 656 |
+
include_frame_data,
|
| 657 |
+
render_mode,
|
| 658 |
+
renderer,
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
def _find_local_game(
|
| 662 |
+
self,
|
| 663 |
+
game_id: str,
|
| 664 |
+
version: Optional[str],
|
| 665 |
+
scorecard_id: str,
|
| 666 |
+
save_recording: bool,
|
| 667 |
+
include_frame_data: bool,
|
| 668 |
+
seed: int = 0,
|
| 669 |
+
render_mode: Optional[str] = None,
|
| 670 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 671 |
+
) -> Optional[LocalEnvironmentWrapper]:
|
| 672 |
+
"""Find a local game from scanned environments.
|
| 673 |
+
|
| 674 |
+
Args:
|
| 675 |
+
game_id: 4-character game identifier.
|
| 676 |
+
version: Optional version string. If None, returns the latest downloaded version.
|
| 677 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 678 |
+
|
| 679 |
+
Returns:
|
| 680 |
+
LocalEnvironmentWrapper if found, None otherwise.
|
| 681 |
+
"""
|
| 682 |
+
# Filter environments by base game_id (first 4 characters)
|
| 683 |
+
matching_envs = []
|
| 684 |
+
for env in self.available_environments:
|
| 685 |
+
# Extract base_id from env.game_id (e.g. "ls20" or "ls20-1234abcd")
|
| 686 |
+
env_base_id = env.game_id.split("-", 1)[0]
|
| 687 |
+
if env_base_id == game_id:
|
| 688 |
+
matching_envs.append(env)
|
| 689 |
+
|
| 690 |
+
if not matching_envs:
|
| 691 |
+
self.logger.error(
|
| 692 |
+
f"Game {game_id} not found in scanned environments. "
|
| 693 |
+
f"Available games: {sorted(set(e.game_id.split('-', 1)[0] for e in self.available_environments))}"
|
| 694 |
+
)
|
| 695 |
+
return None
|
| 696 |
+
|
| 697 |
+
# If version is specified, find exact match
|
| 698 |
+
if version:
|
| 699 |
+
for env in matching_envs:
|
| 700 |
+
# Extract version from env.game_id (everything after '-')
|
| 701 |
+
env_version = (
|
| 702 |
+
env.game_id.split("-", 1)[1] if "-" in env.game_id else None
|
| 703 |
+
)
|
| 704 |
+
if env_version == version:
|
| 705 |
+
if env.local_dir is None:
|
| 706 |
+
self.logger.error(
|
| 707 |
+
f"Found game {game_id}-{version} but local_dir is None"
|
| 708 |
+
)
|
| 709 |
+
return None
|
| 710 |
+
return self._create_wrapper(
|
| 711 |
+
env,
|
| 712 |
+
scorecard_id,
|
| 713 |
+
save_recording,
|
| 714 |
+
include_frame_data,
|
| 715 |
+
seed,
|
| 716 |
+
render_mode,
|
| 717 |
+
renderer,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
self.logger.error(
|
| 721 |
+
f"Game {game_id} with version {version} not found. "
|
| 722 |
+
f"Available versions: {[e.game_id.split('-')[1] if '-' in e.game_id else 'default' for e in matching_envs]}"
|
| 723 |
+
)
|
| 724 |
+
return None
|
| 725 |
+
|
| 726 |
+
# No version specified - return the latest downloaded one
|
| 727 |
+
# Sort by date_downloaded (most recent first)
|
| 728 |
+
matching_envs.sort(
|
| 729 |
+
key=lambda e: e.date_downloaded
|
| 730 |
+
or datetime.min.replace(tzinfo=timezone.utc),
|
| 731 |
+
reverse=True,
|
| 732 |
+
)
|
| 733 |
+
latest_env = matching_envs[0]
|
| 734 |
+
|
| 735 |
+
if latest_env.local_dir is None:
|
| 736 |
+
self.logger.error(f"Found game {game_id} but local_dir is None")
|
| 737 |
+
return None
|
| 738 |
+
|
| 739 |
+
self.logger.info(
|
| 740 |
+
f"Found latest version of {game_id}: {latest_env.game_id} "
|
| 741 |
+
f"(downloaded: {latest_env.date_downloaded})"
|
| 742 |
+
)
|
| 743 |
+
return self._create_wrapper(
|
| 744 |
+
latest_env,
|
| 745 |
+
scorecard_id,
|
| 746 |
+
save_recording,
|
| 747 |
+
include_frame_data,
|
| 748 |
+
seed,
|
| 749 |
+
render_mode,
|
| 750 |
+
renderer,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
def _create_wrapper(
|
| 754 |
+
self,
|
| 755 |
+
env_info: EnvironmentInfo,
|
| 756 |
+
scorecard_id: str,
|
| 757 |
+
save_recording: bool,
|
| 758 |
+
include_frame_data: bool,
|
| 759 |
+
seed: int = 0,
|
| 760 |
+
render_mode: Optional[str] = None,
|
| 761 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 762 |
+
) -> Optional[LocalEnvironmentWrapper]:
|
| 763 |
+
"""Create a LocalEnvironmentWrapper from EnvironmentInfo.
|
| 764 |
+
|
| 765 |
+
Args:
|
| 766 |
+
env_info: EnvironmentInfo to wrap.
|
| 767 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 768 |
+
save_recording: Whether to save recordings.
|
| 769 |
+
render_mode: Optional render mode string ("human", "terminal").
|
| 770 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 771 |
+
|
| 772 |
+
Returns:
|
| 773 |
+
LocalEnvironmentWrapper if successful, None otherwise.
|
| 774 |
+
"""
|
| 775 |
+
# Create renderer callable from render_mode if needed
|
| 776 |
+
final_renderer = self._create_renderer_from_mode(
|
| 777 |
+
render_mode, renderer, env_info
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
try:
|
| 781 |
+
wrapper = LocalEnvironmentWrapper(
|
| 782 |
+
environment_info=env_info,
|
| 783 |
+
seed=seed,
|
| 784 |
+
logger=self.logger,
|
| 785 |
+
scorecard_id=scorecard_id,
|
| 786 |
+
save_recording=save_recording,
|
| 787 |
+
include_frame_data=include_frame_data,
|
| 788 |
+
recordings_dir=self.recordings_dir,
|
| 789 |
+
scorecard_manager=self.scorecard_manager,
|
| 790 |
+
renderer=final_renderer,
|
| 791 |
+
)
|
| 792 |
+
return wrapper
|
| 793 |
+
except Exception as e:
|
| 794 |
+
self.logger.error(
|
| 795 |
+
f"Failed to create LocalEnvironmentWrapper for {env_info.game_id}: {e}",
|
| 796 |
+
exc_info=True,
|
| 797 |
+
)
|
| 798 |
+
return None
|
| 799 |
+
|
| 800 |
+
def _fetch_metadata(
|
| 801 |
+
self,
|
| 802 |
+
game_id: str,
|
| 803 |
+
) -> Optional[dict[str, Any]]:
|
| 804 |
+
"""Fetch game metadata from the API.
|
| 805 |
+
|
| 806 |
+
Returns:
|
| 807 |
+
Metadata dictionary if successful, None otherwise.
|
| 808 |
+
"""
|
| 809 |
+
if not self.arc_api_key:
|
| 810 |
+
self.logger.error("Cannot fetch metadata: no API key provided")
|
| 811 |
+
return None
|
| 812 |
+
|
| 813 |
+
metadata_url = f"{self.arc_base_url}/api/games/{game_id}"
|
| 814 |
+
headers = {
|
| 815 |
+
"X-Api-Key": self.arc_api_key,
|
| 816 |
+
"Accept": "application/json",
|
| 817 |
+
}
|
| 818 |
+
|
| 819 |
+
try:
|
| 820 |
+
response = requests.get(metadata_url, headers=headers, timeout=10)
|
| 821 |
+
|
| 822 |
+
if not response.ok:
|
| 823 |
+
self.logger.warning(
|
| 824 |
+
"Failed to fetch metadata for game %s (status=%s): %s",
|
| 825 |
+
game_id,
|
| 826 |
+
response.status_code,
|
| 827 |
+
response.text,
|
| 828 |
+
)
|
| 829 |
+
return None
|
| 830 |
+
|
| 831 |
+
metadata: dict[str, Any] = response.json()
|
| 832 |
+
self.logger.info("Successfully fetched metadata for game %s", game_id)
|
| 833 |
+
return metadata
|
| 834 |
+
|
| 835 |
+
except requests.exceptions.RequestException as e:
|
| 836 |
+
# Network errors, timeouts, DNS, connection refused, etc.
|
| 837 |
+
self.logger.error(
|
| 838 |
+
"Request error while fetching metadata for game %s: %s",
|
| 839 |
+
game_id,
|
| 840 |
+
e,
|
| 841 |
+
exc_info=True,
|
| 842 |
+
)
|
| 843 |
+
return None
|
| 844 |
+
|
| 845 |
+
except ValueError as e:
|
| 846 |
+
# JSON decode errors
|
| 847 |
+
self.logger.error(
|
| 848 |
+
"Invalid JSON returned for game %s: %s",
|
| 849 |
+
game_id,
|
| 850 |
+
e,
|
| 851 |
+
exc_info=True,
|
| 852 |
+
)
|
| 853 |
+
return None
|
| 854 |
+
|
| 855 |
+
def _create_remote_wrapper(
|
| 856 |
+
self,
|
| 857 |
+
game_id: str,
|
| 858 |
+
version: Optional[str],
|
| 859 |
+
scorecard_id: str,
|
| 860 |
+
save_recording: bool,
|
| 861 |
+
include_frame_data: bool,
|
| 862 |
+
render_mode: Optional[str] = None,
|
| 863 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 864 |
+
) -> Optional[RemoteEnvironmentWrapper]:
|
| 865 |
+
"""Create a RemoteEnvironmentWrapper for online-only mode.
|
| 866 |
+
|
| 867 |
+
Args:
|
| 868 |
+
game_id: 4-character game identifier.
|
| 869 |
+
version: Optional version string. If None, fetches from API.
|
| 870 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 871 |
+
|
| 872 |
+
Returns:
|
| 873 |
+
RemoteEnvironmentWrapper if successful, None otherwise.
|
| 874 |
+
"""
|
| 875 |
+
if not self.arc_api_key:
|
| 876 |
+
self.logger.error("Cannot create remote wrapper: no API key provided")
|
| 877 |
+
return None
|
| 878 |
+
|
| 879 |
+
try:
|
| 880 |
+
# Fetch metadata to get exact game_id with version
|
| 881 |
+
metadata = self._fetch_metadata(game_id)
|
| 882 |
+
if metadata is None:
|
| 883 |
+
return None
|
| 884 |
+
|
| 885 |
+
# Get full game_id with version from metadata
|
| 886 |
+
full_game_id = metadata.get("game_id", game_id)
|
| 887 |
+
if version and full_game_id != f"{game_id}-{version}":
|
| 888 |
+
# If version was provided, construct full_game_id
|
| 889 |
+
full_game_id = f"{game_id}-{version}"
|
| 890 |
+
elif not version and "-" not in full_game_id:
|
| 891 |
+
# If no version in metadata, we need to get it from the API response
|
| 892 |
+
# For now, use the game_id from metadata
|
| 893 |
+
self.logger.warning(
|
| 894 |
+
f"Could not determine version for {game_id}, using {full_game_id}"
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
# Create EnvironmentInfo from metadata
|
| 898 |
+
env_info = EnvironmentInfo(
|
| 899 |
+
game_id=metadata.get("game_id", full_game_id),
|
| 900 |
+
title=metadata.get("title", game_id),
|
| 901 |
+
tags=metadata.get("tags", []),
|
| 902 |
+
baseline_actions=metadata.get("baseline_actions", []),
|
| 903 |
+
date_downloaded=metadata.get("date_downloaded"),
|
| 904 |
+
class_name=metadata.get("class_name"),
|
| 905 |
+
)
|
| 906 |
+
# local_dir is None for remote environments
|
| 907 |
+
env_info.local_dir = None
|
| 908 |
+
|
| 909 |
+
# Create renderer callable from render_mode if needed
|
| 910 |
+
final_renderer = self._create_renderer_from_mode(
|
| 911 |
+
render_mode, renderer, env_info
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
# Create RemoteEnvironmentWrapper
|
| 915 |
+
wrapper = RemoteEnvironmentWrapper(
|
| 916 |
+
base_url=self.arc_base_url,
|
| 917 |
+
environment_info=env_info,
|
| 918 |
+
arc_api_key=self.arc_api_key,
|
| 919 |
+
logger=self.logger,
|
| 920 |
+
scorecard_id=scorecard_id,
|
| 921 |
+
save_recording=save_recording,
|
| 922 |
+
include_frame_data=include_frame_data,
|
| 923 |
+
recordings_dir=self.recordings_dir,
|
| 924 |
+
scorecard_manager=self.scorecard_manager,
|
| 925 |
+
renderer=final_renderer,
|
| 926 |
+
master_cookie_jar=self._session.cookies,
|
| 927 |
+
cookie_lock=self._cookie_lock,
|
| 928 |
+
)
|
| 929 |
+
return wrapper
|
| 930 |
+
|
| 931 |
+
except Exception as e:
|
| 932 |
+
self.logger.error(
|
| 933 |
+
f"Unexpected error while creating remote wrapper for {game_id}: {e}",
|
| 934 |
+
exc_info=True,
|
| 935 |
+
)
|
| 936 |
+
return None
|
| 937 |
+
|
| 938 |
+
def _download_game(
|
| 939 |
+
self,
|
| 940 |
+
game_id: str,
|
| 941 |
+
version: Optional[str],
|
| 942 |
+
scorecard_id: str,
|
| 943 |
+
save_recording: bool,
|
| 944 |
+
include_frame_data: bool,
|
| 945 |
+
seed: int = 0,
|
| 946 |
+
render_mode: Optional[str] = None,
|
| 947 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 948 |
+
) -> Optional[LocalEnvironmentWrapper]:
|
| 949 |
+
"""Download game metadata and source from API.
|
| 950 |
+
|
| 951 |
+
Args:
|
| 952 |
+
game_id: 4-character game identifier.
|
| 953 |
+
version: Optional version string.
|
| 954 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 955 |
+
|
| 956 |
+
Returns:
|
| 957 |
+
LocalEnvironmentWrapper if successful, None otherwise.
|
| 958 |
+
"""
|
| 959 |
+
if not self.arc_api_key:
|
| 960 |
+
self.logger.error("Cannot download game: no API key provided")
|
| 961 |
+
return None
|
| 962 |
+
|
| 963 |
+
try:
|
| 964 |
+
# Fetch metadata
|
| 965 |
+
metadata = self._fetch_metadata(game_id)
|
| 966 |
+
if metadata is None:
|
| 967 |
+
return self._find_local_game(
|
| 968 |
+
game_id,
|
| 969 |
+
version,
|
| 970 |
+
scorecard_id,
|
| 971 |
+
save_recording,
|
| 972 |
+
include_frame_data,
|
| 973 |
+
seed,
|
| 974 |
+
render_mode,
|
| 975 |
+
renderer,
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
# Get version from metadata if not provided
|
| 979 |
+
if version is None:
|
| 980 |
+
version = (
|
| 981 |
+
metadata.get("version")
|
| 982 |
+
or metadata.get("game_id", "").split("-")[-1]
|
| 983 |
+
if "-" in metadata.get("game_id", "")
|
| 984 |
+
else None
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
# Create directory structure: {environment_files}/{game_id}/{version}
|
| 988 |
+
env_dir = Path(self.environments_dir) / game_id
|
| 989 |
+
if version:
|
| 990 |
+
env_dir = env_dir / version
|
| 991 |
+
env_dir.mkdir(parents=True, exist_ok=True)
|
| 992 |
+
|
| 993 |
+
# Add date_downloaded to metadata before saving
|
| 994 |
+
date_downloaded = datetime.now(timezone.utc)
|
| 995 |
+
metadata["tags"] = metadata.get("tags", [])
|
| 996 |
+
metadata["baseline_actions"] = metadata.get("baseline_actions", [])
|
| 997 |
+
metadata["local_dir"] = str(env_dir)
|
| 998 |
+
metadata["date_downloaded"] = date_downloaded.isoformat()
|
| 999 |
+
|
| 1000 |
+
# Save metadata.json
|
| 1001 |
+
metadata_file = env_dir / "metadata.json"
|
| 1002 |
+
import json
|
| 1003 |
+
|
| 1004 |
+
# Get class_name from metadata or default to game_id
|
| 1005 |
+
class_name = metadata.get("class_name")
|
| 1006 |
+
if not class_name:
|
| 1007 |
+
# Generate from game_id (first 4 chars, capitalize first letter)
|
| 1008 |
+
class_name = game_id[0].upper() + game_id[1:] if game_id else "Game"
|
| 1009 |
+
|
| 1010 |
+
# Create EnvironmentInfo
|
| 1011 |
+
env_info = EnvironmentInfo(
|
| 1012 |
+
game_id=metadata.get(
|
| 1013 |
+
"game_id", f"{game_id}-{version}" if version else game_id
|
| 1014 |
+
),
|
| 1015 |
+
title=metadata.get("title", game_id),
|
| 1016 |
+
tags=metadata.get("tags", []),
|
| 1017 |
+
baseline_actions=metadata.get("baseline_actions", []),
|
| 1018 |
+
date_downloaded=date_downloaded,
|
| 1019 |
+
class_name=class_name,
|
| 1020 |
+
)
|
| 1021 |
+
env_info.local_dir = str(env_dir)
|
| 1022 |
+
|
| 1023 |
+
metadata_file.write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
| 1024 |
+
|
| 1025 |
+
# Check if game_class is already in the directory
|
| 1026 |
+
game_class_file = env_dir / f"{class_name.lower()}.py"
|
| 1027 |
+
if game_class_file.exists():
|
| 1028 |
+
return self._create_wrapper(
|
| 1029 |
+
env_info,
|
| 1030 |
+
scorecard_id,
|
| 1031 |
+
save_recording,
|
| 1032 |
+
include_frame_data,
|
| 1033 |
+
seed,
|
| 1034 |
+
render_mode,
|
| 1035 |
+
renderer,
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
# Download source code
|
| 1039 |
+
source_url = f"{self.arc_base_url}/api/games/{game_id}-{version}/source"
|
| 1040 |
+
headers = {
|
| 1041 |
+
"X-Api-Key": self.arc_api_key,
|
| 1042 |
+
"Accept": "application/json",
|
| 1043 |
+
}
|
| 1044 |
+
source_response = requests.get(source_url, headers=headers, timeout=10)
|
| 1045 |
+
source_response.raise_for_status()
|
| 1046 |
+
source_code = source_response.text
|
| 1047 |
+
|
| 1048 |
+
# Determine Python filename from class_name in metadata
|
| 1049 |
+
class_name = metadata.get("class_name")
|
| 1050 |
+
if not class_name:
|
| 1051 |
+
# Generate from game_id (first 4 chars, capitalize first letter)
|
| 1052 |
+
class_name = game_id[0].upper() + game_id[1:] if game_id else "Game"
|
| 1053 |
+
|
| 1054 |
+
# Save source code
|
| 1055 |
+
source_file = env_dir / f"{class_name.lower()}.py"
|
| 1056 |
+
source_file.write_text(source_code, encoding="utf-8")
|
| 1057 |
+
|
| 1058 |
+
self.logger.info(
|
| 1059 |
+
f"Successfully downloaded game {game_id} (version: {version}) to {env_dir}"
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
# Create and return LocalEnvironmentWrapper
|
| 1063 |
+
return self._create_wrapper(
|
| 1064 |
+
env_info,
|
| 1065 |
+
scorecard_id,
|
| 1066 |
+
save_recording,
|
| 1067 |
+
include_frame_data,
|
| 1068 |
+
seed,
|
| 1069 |
+
render_mode,
|
| 1070 |
+
renderer,
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
except requests.exceptions.RequestException as e:
|
| 1074 |
+
self.logger.error(
|
| 1075 |
+
f"Failed to download game {game_id} from API: {e}",
|
| 1076 |
+
exc_info=True,
|
| 1077 |
+
)
|
| 1078 |
+
return None
|
| 1079 |
+
except Exception as e:
|
| 1080 |
+
self.logger.error(
|
| 1081 |
+
f"Unexpected error while downloading game {game_id}: {e}",
|
| 1082 |
+
exc_info=True,
|
| 1083 |
+
)
|
| 1084 |
+
return None
|
| 1085 |
+
|
| 1086 |
+
def listen_and_serve(
|
| 1087 |
+
self,
|
| 1088 |
+
host: str = "0.0.0.0",
|
| 1089 |
+
port: int = 8001,
|
| 1090 |
+
competition_mode: bool = False,
|
| 1091 |
+
save_all_recordings: bool = False,
|
| 1092 |
+
include_frame_data: bool = True,
|
| 1093 |
+
add_cookie: Optional[Callable[[Response, str], Response]] = None,
|
| 1094 |
+
scorecard_timeout: Optional[int] = None,
|
| 1095 |
+
on_scorecard_close: Optional[Callable[[EnvironmentScorecard], None]] = None,
|
| 1096 |
+
extra_api_routes: Optional[Callable[["Arcade", Flask], None]] = None,
|
| 1097 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 1098 |
+
**kwargs: Any,
|
| 1099 |
+
) -> None:
|
| 1100 |
+
"""Spin up a Flask server (blocking). Uses arc_agi.server.create_app()."""
|
| 1101 |
+
from .server import create_app
|
| 1102 |
+
|
| 1103 |
+
app, api = create_app(
|
| 1104 |
+
self,
|
| 1105 |
+
competition_mode=competition_mode,
|
| 1106 |
+
save_all_recordings=save_all_recordings,
|
| 1107 |
+
include_frame_data=include_frame_data,
|
| 1108 |
+
add_cookie=add_cookie,
|
| 1109 |
+
on_scorecard_close=on_scorecard_close,
|
| 1110 |
+
renderer=renderer,
|
| 1111 |
+
)
|
| 1112 |
+
app.debug = False
|
| 1113 |
+
app.threaded = True # False increases stability
|
| 1114 |
+
|
| 1115 |
+
if on_scorecard_close is not None:
|
| 1116 |
+
self._on_scorecard_close = on_scorecard_close
|
| 1117 |
+
cleaner = threading.Thread(target=api.scorecard_cleanup_loop, daemon=True)
|
| 1118 |
+
cleaner.start()
|
| 1119 |
+
|
| 1120 |
+
if extra_api_routes is not None:
|
| 1121 |
+
extra_api_routes(self, app)
|
| 1122 |
+
|
| 1123 |
+
if scorecard_timeout is not None:
|
| 1124 |
+
self.scorecard_manager.set_idle_for(scorecard_timeout)
|
| 1125 |
+
|
| 1126 |
+
app.run(host=host, port=port, **kwargs)
|
arcprize__ARC-AGI/arc_agi/local_wrapper.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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athlib import Path
|
| 9 |
+
from typing import Any, Callable, Optional, Type, cast
|
| 10 |
+
|
| 11 |
+
from arcengine import ARCBaseGame, FrameDataRaw, GameAction
|
| 12 |
+
|
| 13 |
+
from .models import EnvironmentInfo
|
| 14 |
+
from .wrapper import EnvironmentWrapper
|
| 15 |
+
|
| 16 |
+
# Resolved game file + class name -> ARCBaseGame subclass (avoid repeated exec per process)
|
| 17 |
+
_game_class_cache: dict[str, Type[ARCBaseGame]] = {}
|
| 18 |
+
_game_class_cache_lock = threading.Lock()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class LocalEnvironmentWrapper(EnvironmentWrapper):
|
| 22 |
+
"""Wrapper for running ARC-AGI-3 environments locally.
|
| 23 |
+
|
| 24 |
+
This wrapper dynamically loads and instantiates game classes from local files.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
environment_info: EnvironmentInfo,
|
| 30 |
+
logger: logging.Logger,
|
| 31 |
+
scorecard_id: str,
|
| 32 |
+
seed: int = 0,
|
| 33 |
+
save_recording: bool = False,
|
| 34 |
+
include_frame_data: bool = True,
|
| 35 |
+
recordings_dir: str = "recordings",
|
| 36 |
+
scorecard_manager: Optional[Any] = None,
|
| 37 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 38 |
+
) -> None:
|
| 39 |
+
"""Initialize the local environment wrapper.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
environment_info: Information about the environment.
|
| 43 |
+
logger: Logger instance for logging.
|
| 44 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 45 |
+
save_recording: Whether to save recordings to JSONL file.
|
| 46 |
+
include_frame_data: Whether to include frame data in the recording file.
|
| 47 |
+
recordings_dir: Directory to save recordings.
|
| 48 |
+
scorecard_manager: Optional scorecard manager for tracking.
|
| 49 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 50 |
+
"""
|
| 51 |
+
super().__init__(
|
| 52 |
+
environment_info,
|
| 53 |
+
logger,
|
| 54 |
+
scorecard_id,
|
| 55 |
+
save_recording,
|
| 56 |
+
include_frame_data,
|
| 57 |
+
recordings_dir,
|
| 58 |
+
scorecard_manager,
|
| 59 |
+
renderer,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Generate UUID for guid (local environments don't get guid from API)
|
| 63 |
+
self._guid = str(uuid.uuid4())
|
| 64 |
+
|
| 65 |
+
# Setup recording file now that guid is set
|
| 66 |
+
if self.save_recording:
|
| 67 |
+
self._setup_recording_file()
|
| 68 |
+
|
| 69 |
+
self._game: Optional[ARCBaseGame] = None
|
| 70 |
+
self._game_class: Optional[Type[ARCBaseGame]] = None
|
| 71 |
+
|
| 72 |
+
# Load the game class
|
| 73 |
+
if self.environment_info.local_dir is None:
|
| 74 |
+
self.logger.error(
|
| 75 |
+
f"Cannot load local environment {self.environment_info.game_id}: "
|
| 76 |
+
"local_dir is None"
|
| 77 |
+
)
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
self._load_game_class(seed)
|
| 81 |
+
self.reset()
|
| 82 |
+
|
| 83 |
+
def _load_game_class(self, seed: int = 0) -> None:
|
| 84 |
+
"""Dynamically load the game class from the local directory."""
|
| 85 |
+
if self.environment_info.local_dir is None:
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
local_dir = Path(self.environment_info.local_dir)
|
| 89 |
+
class_name = self.environment_info.class_name
|
| 90 |
+
|
| 91 |
+
if not class_name:
|
| 92 |
+
self.logger.error(
|
| 93 |
+
f"Cannot load game class: class_name is not set for {self.environment_info.game_id}"
|
| 94 |
+
)
|
| 95 |
+
return
|
| 96 |
+
|
| 97 |
+
# Find the Python file (try both class_name and lowercase version)
|
| 98 |
+
candidates = [
|
| 99 |
+
local_dir / f"{class_name.lower()}.py",
|
| 100 |
+
local_dir / f"{class_name}.py",
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
game_file = next((p for p in candidates if p.exists()), None)
|
| 104 |
+
if game_file is None:
|
| 105 |
+
self.logger.error(
|
| 106 |
+
f"Game source file not found. Looked in: {', '.join(str(p) for p in candidates)}"
|
| 107 |
+
)
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
cache_key = f"{game_file.resolve()}::{class_name}"
|
| 111 |
+
|
| 112 |
+
with _game_class_cache_lock:
|
| 113 |
+
cls = _game_class_cache.get(cache_key)
|
| 114 |
+
|
| 115 |
+
loaded_from_cache = cls is not None
|
| 116 |
+
|
| 117 |
+
if cls is None:
|
| 118 |
+
try:
|
| 119 |
+
source_code = game_file.read_text(encoding="utf-8")
|
| 120 |
+
except Exception as e:
|
| 121 |
+
self.logger.exception(
|
| 122 |
+
f"Failed to read game source from {game_file}: {e}"
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
module_name = f"arc_agi_3.{self.environment_info.game_id}"
|
| 127 |
+
spec = importlib.util.spec_from_loader(module_name, loader=None)
|
| 128 |
+
if spec is None:
|
| 129 |
+
self.logger.error(f"Could not create module spec for {module_name}")
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
module = importlib.util.module_from_spec(spec)
|
| 133 |
+
try:
|
| 134 |
+
exec(source_code, module.__dict__)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
self.logger.exception(
|
| 137 |
+
f"Error executing game source for {self.environment_info.game_id}: {e}"
|
| 138 |
+
)
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
loaded: Any | None = getattr(module, class_name, None)
|
| 142 |
+
if loaded is None or not isinstance(loaded, type):
|
| 143 |
+
self.logger.error(
|
| 144 |
+
f"Expected class `{class_name}` not found in {game_file}"
|
| 145 |
+
)
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
+
if not issubclass(loaded, ARCBaseGame):
|
| 149 |
+
self.logger.error(
|
| 150 |
+
f"Class `{class_name}` exists but is not a subclass of ARCBaseGame"
|
| 151 |
+
)
|
| 152 |
+
return
|
| 153 |
+
|
| 154 |
+
with _game_class_cache_lock:
|
| 155 |
+
cls = _game_class_cache.get(cache_key)
|
| 156 |
+
if cls is None:
|
| 157 |
+
_game_class_cache[cache_key] = loaded
|
| 158 |
+
cls = loaded
|
| 159 |
+
# else: another thread populated the cache first; use cached class
|
| 160 |
+
|
| 161 |
+
self._game_class = cls
|
| 162 |
+
|
| 163 |
+
sig = inspect.signature(cls)
|
| 164 |
+
if seed is not None and "seed" in sig.parameters:
|
| 165 |
+
kwargs = {"seed": seed}
|
| 166 |
+
else:
|
| 167 |
+
kwargs = {}
|
| 168 |
+
|
| 169 |
+
self._game = cls(**kwargs) # type: ignore[arg-type]
|
| 170 |
+
if loaded_from_cache:
|
| 171 |
+
self.logger.debug(
|
| 172 |
+
"Instantiated %s from game class cache (%s)",
|
| 173 |
+
class_name,
|
| 174 |
+
cache_key,
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
self.logger.info(
|
| 178 |
+
f"Successfully loaded game class {class_name} from {game_file}"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def reset(self) -> Optional[FrameDataRaw]:
|
| 182 |
+
"""Reset the environment and return the initial frame data.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
FrameDataRaw object with initial game state, or None if reset failed.
|
| 186 |
+
"""
|
| 187 |
+
if self._game is None:
|
| 188 |
+
self.logger.error("Cannot reset: game not loaded")
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
from arcengine import ActionInput
|
| 193 |
+
|
| 194 |
+
# Perform reset action and get frame data
|
| 195 |
+
reset_action = ActionInput(id=GameAction.RESET)
|
| 196 |
+
frame_data = cast(
|
| 197 |
+
FrameDataRaw, self._game.perform_action(reset_action, raw=True)
|
| 198 |
+
)
|
| 199 |
+
# Set guid in frame_data for local environments
|
| 200 |
+
frame_data.guid = self._guid
|
| 201 |
+
frame_data.game_id = self.environment_info.game_id
|
| 202 |
+
self._set_last_response(frame_data)
|
| 203 |
+
return frame_data
|
| 204 |
+
|
| 205 |
+
except Exception as e:
|
| 206 |
+
self.logger.exception(
|
| 207 |
+
f"Error resetting game {self.environment_info.game_id}: {e}"
|
| 208 |
+
)
|
| 209 |
+
return None
|
| 210 |
+
|
| 211 |
+
def step(
|
| 212 |
+
self,
|
| 213 |
+
action: GameAction,
|
| 214 |
+
data: Optional[dict[str, Any]] = None,
|
| 215 |
+
reasoning: Optional[dict[str, Any]] = None,
|
| 216 |
+
) -> Optional[FrameDataRaw]:
|
| 217 |
+
"""Perform a step in the environment.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
action: The game action to perform.
|
| 221 |
+
data: Optional action data dictionary.
|
| 222 |
+
reasoning: Optional reasoning dictionary.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
FrameDataRaw object with updated game state, or None if step failed.
|
| 226 |
+
"""
|
| 227 |
+
if self._game is None:
|
| 228 |
+
self.logger.error("Cannot step: game not initialized. Call reset() first.")
|
| 229 |
+
return None
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
from arcengine import ActionInput
|
| 233 |
+
|
| 234 |
+
# Create ActionInput from GameAction with data
|
| 235 |
+
action_input = ActionInput(id=action, data=data or {}, reasoning=reasoning)
|
| 236 |
+
|
| 237 |
+
# Perform the action
|
| 238 |
+
frame_data = cast(
|
| 239 |
+
FrameDataRaw, self._game.perform_action(action_input, raw=True)
|
| 240 |
+
)
|
| 241 |
+
# Set guid in frame_data for local environments
|
| 242 |
+
frame_data.guid = self._guid
|
| 243 |
+
frame_data.game_id = self.environment_info.game_id
|
| 244 |
+
self._set_last_response(frame_data, reasoning=reasoning)
|
| 245 |
+
return frame_data
|
| 246 |
+
|
| 247 |
+
except Exception as e:
|
| 248 |
+
self.logger.exception(
|
| 249 |
+
f"Error performing step with action {action.name}: {e}"
|
| 250 |
+
)
|
| 251 |
+
return None
|
arcprize__ARC-AGI/arc_agi/models.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pydantic models for ARC-AGI-3 environments."""
|
| 2 |
+
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
from pydantic import BaseModel, Field, model_validator
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class APIError(str, Enum):
|
| 11 |
+
VALIDATION_ERROR = "VALIDATION_ERROR"
|
| 12 |
+
GAME_NOT_AVAILABLE_ERROR = "GAME_NOT_AVAILABLE_ERROR"
|
| 13 |
+
SERVER_ERROR = "SERVER_ERROR"
|
| 14 |
+
GAME_NOT_STARTED_ERROR = "GAME_NOT_STARTED_ERROR"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class EnvironmentInfo(BaseModel):
|
| 18 |
+
"""Information about an ARC-AGI-3 environment.
|
| 19 |
+
|
| 20 |
+
This class can be serialized to and deserialized from JSON.
|
| 21 |
+
Note: local_dir is excluded from JSON serialization as it's runtime-only.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
game_id: str
|
| 25 |
+
title: Optional[str] = None
|
| 26 |
+
default_fps: Optional[int] = None
|
| 27 |
+
tags: Optional[list[str]] = None
|
| 28 |
+
private_tags: Optional[list[str]] = None
|
| 29 |
+
level_tags: Optional[list[list[str]]] = None
|
| 30 |
+
baseline_actions: Optional[list[int]] = None
|
| 31 |
+
date_downloaded: Optional[datetime] = None
|
| 32 |
+
class_name: Optional[str] = None
|
| 33 |
+
local_dir: Optional[str] = Field(default=None, exclude=True)
|
| 34 |
+
|
| 35 |
+
@model_validator(mode="after")
|
| 36 |
+
def set_defaults(self) -> "EnvironmentInfo":
|
| 37 |
+
"""Set default values for date_downloaded and class_name if not provided."""
|
| 38 |
+
# Set date_downloaded to now if not provided
|
| 39 |
+
if self.date_downloaded is None:
|
| 40 |
+
self.date_downloaded = datetime.now(timezone.utc)
|
| 41 |
+
|
| 42 |
+
if self.default_fps is None:
|
| 43 |
+
self.default_fps = 5
|
| 44 |
+
|
| 45 |
+
# Set class_name from game_id if not provided
|
| 46 |
+
if self.class_name is None:
|
| 47 |
+
# Take first 4 characters and capitalize first letter only
|
| 48 |
+
if len(self.game_id) >= 4:
|
| 49 |
+
first_four = self.game_id[:4]
|
| 50 |
+
self.class_name = first_four[0].upper() + first_four[1:]
|
| 51 |
+
else:
|
| 52 |
+
# If game_id is shorter than 4 characters, capitalize first letter only
|
| 53 |
+
if self.game_id:
|
| 54 |
+
self.class_name = self.game_id[0].upper() + self.game_id[1:]
|
| 55 |
+
else:
|
| 56 |
+
self.class_name = ""
|
| 57 |
+
|
| 58 |
+
return self
|
| 59 |
+
|
| 60 |
+
def model_dump_json(self, **kwargs: Any) -> str:
|
| 61 |
+
"""Serialize to JSON string.
|
| 62 |
+
|
| 63 |
+
Note: local_dir is automatically excluded from serialization.
|
| 64 |
+
"""
|
| 65 |
+
return super().model_dump_json(**kwargs)
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
def model_validate_json(
|
| 69 |
+
cls,
|
| 70 |
+
json_data: str | bytes | bytearray,
|
| 71 |
+
*,
|
| 72 |
+
strict: bool | None = None,
|
| 73 |
+
context: Any | None = None,
|
| 74 |
+
by_alias: bool | None = None,
|
| 75 |
+
by_name: bool | None = None,
|
| 76 |
+
) -> "EnvironmentInfo":
|
| 77 |
+
"""Deserialize from JSON string."""
|
| 78 |
+
return super().model_validate_json(
|
| 79 |
+
json_data,
|
| 80 |
+
strict=strict,
|
| 81 |
+
context=context,
|
| 82 |
+
by_alias=by_alias,
|
| 83 |
+
by_name=by_name,
|
| 84 |
+
)
|
arcprize__ARC-AGI/arc_agi/remote_wrapper.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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numpy as np
|
| 9 |
+
import requests
|
| 10 |
+
from arcengine import FrameData, FrameDataRaw, GameAction
|
| 11 |
+
from requests.cookies import RequestsCookieJar
|
| 12 |
+
|
| 13 |
+
from .models import EnvironmentInfo
|
| 14 |
+
from .wrapper import EnvironmentWrapper
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class RemoteEnvironmentWrapper(EnvironmentWrapper):
|
| 18 |
+
"""Wrapper for running ARC-AGI-3 environments remotely via API.
|
| 19 |
+
|
| 20 |
+
This wrapper makes HTTP requests to the ARC-AGI-3 API to interact with
|
| 21 |
+
environments that are hosted remotely.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
base_url: str,
|
| 27 |
+
environment_info: EnvironmentInfo,
|
| 28 |
+
arc_api_key: str,
|
| 29 |
+
logger: logging.Logger,
|
| 30 |
+
scorecard_id: str,
|
| 31 |
+
save_recording: bool = False,
|
| 32 |
+
include_frame_data: bool = True,
|
| 33 |
+
recordings_dir: str = "recordings",
|
| 34 |
+
scorecard_manager: Optional[Any] = None,
|
| 35 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 36 |
+
master_cookie_jar: Optional[RequestsCookieJar] = None,
|
| 37 |
+
cookie_lock: Optional[threading.Lock] = None,
|
| 38 |
+
) -> None:
|
| 39 |
+
"""Initialize the remote environment wrapper.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
base_url: Base URL for the ARC-AGI-3 API (e.g., "https://three.arcprize.org").
|
| 43 |
+
environment_info: EnvironmentInfo object with game metadata.
|
| 44 |
+
arc_api_key: API key for authentication.
|
| 45 |
+
logger: Logger instance for logging.
|
| 46 |
+
scorecard_id: Scorecard ID for tracking runs.
|
| 47 |
+
save_recording: Whether to save recordings to JSONL file.
|
| 48 |
+
include_frame_data: Whether to include frame data in the recording file.
|
| 49 |
+
recordings_dir: Directory to save recordings.
|
| 50 |
+
scorecard_manager: Optional scorecard manager for tracking.
|
| 51 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 52 |
+
"""
|
| 53 |
+
super().__init__(
|
| 54 |
+
environment_info,
|
| 55 |
+
logger,
|
| 56 |
+
scorecard_id,
|
| 57 |
+
save_recording,
|
| 58 |
+
include_frame_data,
|
| 59 |
+
recordings_dir,
|
| 60 |
+
scorecard_manager,
|
| 61 |
+
renderer,
|
| 62 |
+
)
|
| 63 |
+
self.base_url = base_url
|
| 64 |
+
self.arc_api_key = arc_api_key
|
| 65 |
+
self.headers = {
|
| 66 |
+
"X-API-Key": arc_api_key,
|
| 67 |
+
"Accept": "application/json",
|
| 68 |
+
}
|
| 69 |
+
self._session = requests.Session()
|
| 70 |
+
self._session.headers.update(self.headers)
|
| 71 |
+
|
| 72 |
+
self._master_cookie_jar = (
|
| 73 |
+
master_cookie_jar if master_cookie_jar is not None else RequestsCookieJar()
|
| 74 |
+
)
|
| 75 |
+
self._cookie_lock = cookie_lock if cookie_lock is not None else threading.Lock()
|
| 76 |
+
|
| 77 |
+
self.reset()
|
| 78 |
+
|
| 79 |
+
def reset(self) -> Optional[FrameDataRaw]:
|
| 80 |
+
"""Reset the environment and return the initial frame data.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
FrameDataRaw object with initial game state, or None if reset failed.
|
| 84 |
+
"""
|
| 85 |
+
try:
|
| 86 |
+
url = f"{self.base_url}/api/cmd/RESET"
|
| 87 |
+
headers = {
|
| 88 |
+
"X-Api-Key": self.arc_api_key,
|
| 89 |
+
"Content-Type": "application/json",
|
| 90 |
+
}
|
| 91 |
+
payload = {
|
| 92 |
+
"card_id": self.scorecard_id,
|
| 93 |
+
"game_id": self.environment_info.game_id,
|
| 94 |
+
}
|
| 95 |
+
if self._guid:
|
| 96 |
+
payload["guid"] = self._guid
|
| 97 |
+
|
| 98 |
+
with self._cookie_lock:
|
| 99 |
+
self._session.cookies.update(self._master_cookie_jar) # type: ignore[no-untyped-call]
|
| 100 |
+
|
| 101 |
+
response = self._session.post(
|
| 102 |
+
url, json=payload, headers=headers, timeout=10
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
with self._cookie_lock:
|
| 106 |
+
self._master_cookie_jar.update(self._session.cookies) # type: ignore[no-untyped-call]
|
| 107 |
+
|
| 108 |
+
response.raise_for_status()
|
| 109 |
+
response_data = response.json()
|
| 110 |
+
|
| 111 |
+
# Convert API response to FrameDataRaw
|
| 112 |
+
frame_data_raw = self._convert_to_frame_data_raw(response_data)
|
| 113 |
+
if frame_data_raw:
|
| 114 |
+
# Store guid from response
|
| 115 |
+
self._guid = response_data.get("guid")
|
| 116 |
+
# Setup recording file now that guid is set
|
| 117 |
+
if self.save_recording and self._guid:
|
| 118 |
+
self._setup_recording_file()
|
| 119 |
+
self._set_last_response(frame_data_raw)
|
| 120 |
+
self.logger.info(
|
| 121 |
+
f"Successfully reset game {self.environment_info.game_id}, guid={self._guid}, scorecard_id={self.scorecard_id}"
|
| 122 |
+
)
|
| 123 |
+
return frame_data_raw
|
| 124 |
+
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
except requests.exceptions.RequestException as e:
|
| 128 |
+
self.logger.error(
|
| 129 |
+
f"Failed to reset game {self.environment_info.game_id}: {e}",
|
| 130 |
+
exc_info=True,
|
| 131 |
+
)
|
| 132 |
+
return None
|
| 133 |
+
except Exception as e:
|
| 134 |
+
self.logger.exception(
|
| 135 |
+
f"Unexpected error while resetting game {self.environment_info.game_id}: {e}"
|
| 136 |
+
)
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
def step(
|
| 140 |
+
self,
|
| 141 |
+
action: GameAction,
|
| 142 |
+
data: Optional[dict[str, Any]] = None,
|
| 143 |
+
reasoning: Optional[dict[str, Any]] = None,
|
| 144 |
+
) -> Optional[FrameDataRaw]:
|
| 145 |
+
"""Perform a step in the environment.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
action: The game action to perform.
|
| 149 |
+
data: Optional action data dictionary (for complex actions, should contain "x" and "y").
|
| 150 |
+
reasoning: Optional reasoning dictionary.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
FrameDataRaw object with updated game state, or None if step failed.
|
| 154 |
+
"""
|
| 155 |
+
if self._guid is None:
|
| 156 |
+
self.logger.error("Cannot step: game not reset. Call reset() first.")
|
| 157 |
+
return None
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
# Determine action endpoint
|
| 161 |
+
if action == GameAction.RESET:
|
| 162 |
+
action_name = "RESET"
|
| 163 |
+
else:
|
| 164 |
+
action_name = f"ACTION{action.value}"
|
| 165 |
+
|
| 166 |
+
url = f"{self.base_url}/api/cmd/{action_name}"
|
| 167 |
+
headers = {
|
| 168 |
+
"X-Api-Key": self.arc_api_key,
|
| 169 |
+
"Content-Type": "application/json",
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
# Build payload
|
| 173 |
+
payload = {
|
| 174 |
+
"game_id": self.environment_info.game_id,
|
| 175 |
+
"guid": self._guid,
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
# Add x, y coordinates for complex actions
|
| 179 |
+
if data:
|
| 180 |
+
if "x" in data:
|
| 181 |
+
payload["x"] = data["x"]
|
| 182 |
+
if "y" in data:
|
| 183 |
+
payload["y"] = data["y"]
|
| 184 |
+
|
| 185 |
+
# Add reasoning if provided
|
| 186 |
+
if reasoning:
|
| 187 |
+
payload["reasoning"] = json.dumps(reasoning)
|
| 188 |
+
|
| 189 |
+
with self._cookie_lock:
|
| 190 |
+
self._session.cookies.update(self._master_cookie_jar) # type: ignore[no-untyped-call]
|
| 191 |
+
|
| 192 |
+
response = self._session.post(
|
| 193 |
+
url, json=payload, headers=headers, timeout=10
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
with self._cookie_lock:
|
| 197 |
+
self._master_cookie_jar.update(self._session.cookies) # type: ignore[no-untyped-call]
|
| 198 |
+
|
| 199 |
+
response.raise_for_status()
|
| 200 |
+
response_data = response.json()
|
| 201 |
+
|
| 202 |
+
# Convert API response to FrameDataRaw
|
| 203 |
+
frame_data_raw = self._convert_to_frame_data_raw(response_data)
|
| 204 |
+
if frame_data_raw:
|
| 205 |
+
self._set_last_response(frame_data_raw, reasoning=reasoning)
|
| 206 |
+
return frame_data_raw
|
| 207 |
+
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
except requests.exceptions.RequestException as e:
|
| 211 |
+
response_text = e.response.text if e.response is not None else ""
|
| 212 |
+
response_body = f" Response body: {response_text}" if response_text else ""
|
| 213 |
+
self.logger.error(
|
| 214 |
+
f"Failed to perform action {action.name} for game {self.environment_info.game_id}: {e}{response_body}",
|
| 215 |
+
exc_info=True,
|
| 216 |
+
)
|
| 217 |
+
return None
|
| 218 |
+
except Exception as e:
|
| 219 |
+
self.logger.exception(
|
| 220 |
+
f"Unexpected error while performing action {action.name}: {e}"
|
| 221 |
+
)
|
| 222 |
+
return None
|
| 223 |
+
|
| 224 |
+
def _convert_to_frame_data_raw(
|
| 225 |
+
self, response_data: dict[str, Any]
|
| 226 |
+
) -> Optional[FrameDataRaw]:
|
| 227 |
+
"""Convert API response dictionary to FrameDataRaw.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
response_data: Dictionary from API response.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
FrameDataRaw object if successful, None otherwise.
|
| 234 |
+
"""
|
| 235 |
+
try:
|
| 236 |
+
# First, try to parse as FrameData (Pydantic model)
|
| 237 |
+
frame_data = FrameData.model_validate(response_data)
|
| 238 |
+
|
| 239 |
+
# Convert FrameData to FrameDataRaw
|
| 240 |
+
frame_data_raw = FrameDataRaw()
|
| 241 |
+
frame_data_raw.game_id = frame_data.game_id
|
| 242 |
+
# Convert frame from list of lists of lists to list of ndarrays
|
| 243 |
+
frame_data_raw.frame = [
|
| 244 |
+
np.array(frame_layer, dtype=np.int8) for frame_layer in frame_data.frame
|
| 245 |
+
]
|
| 246 |
+
frame_data_raw.state = frame_data.state
|
| 247 |
+
frame_data_raw.levels_completed = frame_data.levels_completed
|
| 248 |
+
frame_data_raw.win_levels = frame_data.win_levels
|
| 249 |
+
frame_data_raw.action_input = frame_data.action_input
|
| 250 |
+
frame_data_raw.guid = frame_data.guid
|
| 251 |
+
frame_data_raw.full_reset = getattr(frame_data, "full_reset", False)
|
| 252 |
+
frame_data_raw.available_actions = frame_data.available_actions
|
| 253 |
+
|
| 254 |
+
return frame_data_raw
|
| 255 |
+
|
| 256 |
+
except Exception as e:
|
| 257 |
+
self.logger.error(
|
| 258 |
+
f"Failed to convert API response to FrameDataRaw: {e}",
|
| 259 |
+
exc_info=True,
|
| 260 |
+
)
|
| 261 |
+
return None
|
arcprize__ARC-AGI/arc_agi/rendering.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rendering utilities for ARC-AGI-3 environments."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
from typing import Any, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import matplotlib.animation as animation
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
|
| 11 |
+
HAS_MATPLOTLIB = True
|
| 12 |
+
except ImportError:
|
| 13 |
+
plt = None
|
| 14 |
+
animation = None
|
| 15 |
+
HAS_MATPLOTLIB = False
|
| 16 |
+
|
| 17 |
+
from arcengine import FrameDataRaw
|
| 18 |
+
from numpy import ndarray
|
| 19 |
+
|
| 20 |
+
# Color mapping for frame values (0-15)
|
| 21 |
+
COLOR_MAP: dict[int, str] = {
|
| 22 |
+
0: "#FFFFFFFF", # White
|
| 23 |
+
1: "#CCCCCCFF", # Off-white
|
| 24 |
+
2: "#999999FF", # neutral Light
|
| 25 |
+
3: "#666666FF", # neutral
|
| 26 |
+
4: "#333333FF", # Off Black
|
| 27 |
+
5: "#000000FF", # Black
|
| 28 |
+
6: "#E53AA3FF", # Magenta
|
| 29 |
+
7: "#FF7BCCFF", # Magenta Light
|
| 30 |
+
8: "#F93C31FF", # Red
|
| 31 |
+
9: "#1E93FFFF", # Blue
|
| 32 |
+
10: "#88D8F1FF", # Blue Light
|
| 33 |
+
11: "#FFDC00FF", # Yellow
|
| 34 |
+
12: "#FF851BFF", # Orange
|
| 35 |
+
13: "#921231FF", # Maroon
|
| 36 |
+
14: "#4FCC30FF", # Green
|
| 37 |
+
15: "#A356D6FF", # Purple
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
|
| 42 |
+
"""Convert hex color string to RGB tuple.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
hex_color: Hex color string (e.g., "#FFFFFFFF").
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
RGB tuple (r, g, b).
|
| 49 |
+
"""
|
| 50 |
+
# Remove '#' and convert to int
|
| 51 |
+
hex_color = hex_color.lstrip("#")
|
| 52 |
+
# Parse RGBA hex (8 chars) or RGB hex (6 chars)
|
| 53 |
+
if len(hex_color) == 8:
|
| 54 |
+
r = int(hex_color[0:2], 16)
|
| 55 |
+
g = int(hex_color[2:4], 16)
|
| 56 |
+
b = int(hex_color[4:6], 16)
|
| 57 |
+
# Alpha is ignored for display
|
| 58 |
+
else:
|
| 59 |
+
r = int(hex_color[0:2], 16)
|
| 60 |
+
g = int(hex_color[2:4], 16)
|
| 61 |
+
b = int(hex_color[4:6], 16)
|
| 62 |
+
return (r, g, b)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def frame_to_rgb_array(
|
| 66 |
+
steps: int,
|
| 67 |
+
frame: ndarray,
|
| 68 |
+
scale: int = 4,
|
| 69 |
+
color_map: Optional[dict[int, str]] = None,
|
| 70 |
+
) -> ndarray:
|
| 71 |
+
"""Convert a frame to an RGB numpy array for matplotlib.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
frame: 2D numpy array (64x64) with values 0-15.
|
| 75 |
+
scale: Upscaling factor (default 4, so 64x64 -> 256x256).
|
| 76 |
+
color_map: Optional color mapping dict. Uses default if None.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
3D numpy array (height, width, 3) with RGB values.
|
| 80 |
+
"""
|
| 81 |
+
import numpy as np
|
| 82 |
+
|
| 83 |
+
if color_map is None:
|
| 84 |
+
color_map = COLOR_MAP
|
| 85 |
+
|
| 86 |
+
height, width = frame.shape
|
| 87 |
+
upscaled_height = height * scale
|
| 88 |
+
upscaled_width = width * scale
|
| 89 |
+
|
| 90 |
+
# Create RGB array
|
| 91 |
+
rgb_array = np.zeros((upscaled_height, upscaled_width, 3), dtype=np.uint8)
|
| 92 |
+
|
| 93 |
+
# Fill pixels
|
| 94 |
+
for y in range(height):
|
| 95 |
+
for x in range(width):
|
| 96 |
+
value = int(frame[y, x])
|
| 97 |
+
hex_color = color_map.get(value, "#000000FF")
|
| 98 |
+
rgb = hex_to_rgb(hex_color)
|
| 99 |
+
|
| 100 |
+
# Fill the scaled block
|
| 101 |
+
for dy in range(scale):
|
| 102 |
+
for dx in range(scale):
|
| 103 |
+
rgb_array[y * scale + dy, x * scale + dx] = rgb
|
| 104 |
+
|
| 105 |
+
return rgb_array
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def render_frames(
|
| 109 |
+
steps: int,
|
| 110 |
+
frame_data: FrameDataRaw,
|
| 111 |
+
default_fps: Optional[int] = None,
|
| 112 |
+
scale: int = 4,
|
| 113 |
+
color_map: Optional[dict[int, str]] = None,
|
| 114 |
+
) -> None:
|
| 115 |
+
"""Render multiple frames with optional FPS control using matplotlib.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
frame_data: FrameDataRaw object containing frame data and other information.
|
| 119 |
+
default_fps: Optional FPS for frame timing. If None, displays immediately.
|
| 120 |
+
scale: Upscaling factor (default 4, so 64x64 -> 256x256).
|
| 121 |
+
color_map: Optional color mapping dict. Uses default if None.
|
| 122 |
+
"""
|
| 123 |
+
if not HAS_MATPLOTLIB or plt is None or animation is None:
|
| 124 |
+
raise ImportError(
|
| 125 |
+
"matplotlib is required for rendering. Install with: pip install matplotlib"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
frames = frame_data.frame
|
| 129 |
+
if not frames:
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
# Convert frames to RGB arrays
|
| 133 |
+
frame_images = [
|
| 134 |
+
frame_to_rgb_array(steps, frame, scale, color_map) for frame in frames
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
# Calculate interval between frames if FPS is specified
|
| 138 |
+
interval = (1000.0 / default_fps) if default_fps and default_fps > 0 else 100
|
| 139 |
+
|
| 140 |
+
# Create figure and axis
|
| 141 |
+
fig, ax = plt.subplots(figsize=(8, 8))
|
| 142 |
+
ax.axis("off")
|
| 143 |
+
ax.set_title("ARC-AGI-3 Environment")
|
| 144 |
+
|
| 145 |
+
# Display first frame
|
| 146 |
+
im = ax.imshow(frame_images[0], interpolation="nearest")
|
| 147 |
+
plt.tight_layout()
|
| 148 |
+
|
| 149 |
+
def update_frame(frame_num: int) -> Tuple[Any, ...]:
|
| 150 |
+
"""Update the displayed frame."""
|
| 151 |
+
if frame_num < len(frame_images):
|
| 152 |
+
im.set_array(frame_images[frame_num])
|
| 153 |
+
return (im,)
|
| 154 |
+
return (im,)
|
| 155 |
+
|
| 156 |
+
# Create animation that plays automatically
|
| 157 |
+
# Keep reference to prevent garbage collection
|
| 158 |
+
anim = animation.FuncAnimation(
|
| 159 |
+
fig,
|
| 160 |
+
update_frame,
|
| 161 |
+
frames=len(frame_images),
|
| 162 |
+
interval=interval,
|
| 163 |
+
blit=False,
|
| 164 |
+
repeat=False,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Show the plot - animation will play automatically
|
| 168 |
+
# Use non-blocking mode so frames play and code continues
|
| 169 |
+
plt.ion() # Turn on interactive mode
|
| 170 |
+
plt.show(block=False)
|
| 171 |
+
|
| 172 |
+
# Wait for animation to complete (frames * interval + small buffer)
|
| 173 |
+
if interval > 0:
|
| 174 |
+
total_time = len(frame_images) * interval / 1000.0
|
| 175 |
+
else:
|
| 176 |
+
total_time = len(frame_images) * 0.1 # Default 100ms per frame
|
| 177 |
+
|
| 178 |
+
# Small initial pause to ensure window appears and animation starts
|
| 179 |
+
time.sleep(0.1)
|
| 180 |
+
|
| 181 |
+
# Use plt.pause to process events and let animation play
|
| 182 |
+
# This ensures the animation actually renders
|
| 183 |
+
plt.pause(total_time + 0.1)
|
| 184 |
+
|
| 185 |
+
# Keep animation reference alive until we're done
|
| 186 |
+
# Close the figure after animation completes
|
| 187 |
+
plt.close(fig)
|
| 188 |
+
plt.ioff() # Turn off interactive mode
|
| 189 |
+
|
| 190 |
+
# Explicitly delete animation after closing to avoid warnings
|
| 191 |
+
del anim
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def rgb_to_ansi(rgb: tuple[int, int, int]) -> str:
|
| 195 |
+
"""Convert RGB tuple to ANSI color code.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
rgb: RGB tuple (r, g, b).
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
ANSI escape sequence for the color.
|
| 202 |
+
"""
|
| 203 |
+
r, g, b = rgb
|
| 204 |
+
return f"\033[38;2;{r};{g};{b}m"
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def render_frames_terminal(
|
| 208 |
+
steps: int,
|
| 209 |
+
frame_data: FrameDataRaw,
|
| 210 |
+
default_fps: Optional[int] = None,
|
| 211 |
+
scale: int = 1,
|
| 212 |
+
color_map: Optional[dict[int, str]] = None,
|
| 213 |
+
skip_deplay: bool = False,
|
| 214 |
+
) -> None:
|
| 215 |
+
"""Render frames in the terminal using ANSI color codes, overwriting in place.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
frame_data: FrameDataRaw object containing frame data and other information.
|
| 219 |
+
default_fps: Optional FPS for frame timing. If None, displays immediately.
|
| 220 |
+
scale: Scaling factor (default 1, terminal uses 2 chars per pixel for better visibility).
|
| 221 |
+
color_map: Optional color mapping dict. Uses default if None.
|
| 222 |
+
"""
|
| 223 |
+
frames = frame_data.frame
|
| 224 |
+
if not frames:
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
if color_map is None:
|
| 228 |
+
color_map = COLOR_MAP
|
| 229 |
+
|
| 230 |
+
# Check if terminal supports colors
|
| 231 |
+
if not sys.stdout.isatty():
|
| 232 |
+
print(
|
| 233 |
+
"Warning: Not a terminal, colors may not display correctly", file=sys.stderr
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Calculate delay between frames (default 5 FPS if not specified)
|
| 237 |
+
fps = default_fps if default_fps and default_fps > 0 else 5
|
| 238 |
+
delay = 1.0 / fps
|
| 239 |
+
|
| 240 |
+
# ANSI codes
|
| 241 |
+
RESET = "\033[0m"
|
| 242 |
+
HOME = "\033[H" # Move cursor to home position (top-left)
|
| 243 |
+
HIDE_CURSOR = "\033[?25l" # Hide cursor
|
| 244 |
+
SHOW_CURSOR = "\033[?25h" # Show cursor
|
| 245 |
+
# Use block character for better visibility (2 chars wide)
|
| 246 |
+
BLOCK = "██"
|
| 247 |
+
|
| 248 |
+
# Get frame dimensions
|
| 249 |
+
height, width = frames[0].shape
|
| 250 |
+
|
| 251 |
+
# Build frame strings for all frames (as single strings to reduce flicker)
|
| 252 |
+
frame_strings = []
|
| 253 |
+
for frame_idx, frame in enumerate(frames):
|
| 254 |
+
# Build entire frame as one string
|
| 255 |
+
frame_str = f"Step: {steps} - State: {frame_data.state.name}\n\n"
|
| 256 |
+
|
| 257 |
+
# Frame content - build all lines first, then join
|
| 258 |
+
frame_lines = []
|
| 259 |
+
for y in range(height):
|
| 260 |
+
line_parts = []
|
| 261 |
+
for x in range(width):
|
| 262 |
+
value = int(frame[y, x])
|
| 263 |
+
hex_color = color_map.get(value, "#000000FF")
|
| 264 |
+
rgb = hex_to_rgb(hex_color)
|
| 265 |
+
ansi_color = rgb_to_ansi(rgb)
|
| 266 |
+
# Use block character (2 chars) for better visibility
|
| 267 |
+
line_parts.append(f"{ansi_color}{BLOCK}{RESET}")
|
| 268 |
+
frame_lines.append("".join(line_parts))
|
| 269 |
+
|
| 270 |
+
frame_str += "\n".join(frame_lines)
|
| 271 |
+
frame_strings.append(frame_str)
|
| 272 |
+
|
| 273 |
+
# Hide cursor to reduce flicker
|
| 274 |
+
print(HIDE_CURSOR, end="", flush=True)
|
| 275 |
+
|
| 276 |
+
try:
|
| 277 |
+
# First frame: clear screen and display in single operation to reduce flicker
|
| 278 |
+
print(f"{HOME}\033[2J{frame_strings[0]}", end="", flush=True)
|
| 279 |
+
|
| 280 |
+
# Update frames in place - single operation per frame to minimize flicker
|
| 281 |
+
for frame_idx in range(1, len(frames)):
|
| 282 |
+
# Single operation: move home + print new frame (no separate operations)
|
| 283 |
+
print(f"{HOME}{frame_strings[frame_idx]}", end="", flush=True)
|
| 284 |
+
# Sleep for 1/fps seconds between frames
|
| 285 |
+
if not skip_deplay:
|
| 286 |
+
time.sleep(delay)
|
| 287 |
+
finally:
|
| 288 |
+
# Always show cursor again
|
| 289 |
+
print(SHOW_CURSOR, end="", flush=True)
|
| 290 |
+
|
| 291 |
+
# Reset terminal colors and move cursor below the frame
|
| 292 |
+
print(f"\n{RESET}", end="", flush=True)
|
| 293 |
+
if not skip_deplay:
|
| 294 |
+
time.sleep(delay)
|
arcprize__ARC-AGI/arc_agi/scorecard.py
ADDED
|
@@ -0,0 +1,1012 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import uuid
|
| 5 |
+
from datetime import datetime, timedelta, timezone
|
| 6 |
+
from typing import Any, List, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
from arcengine import FrameDataRaw, GameState
|
| 9 |
+
from pydantic import BaseModel, Field, computed_field
|
| 10 |
+
|
| 11 |
+
from .models import EnvironmentInfo
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
if not logger.handlers:
|
| 16 |
+
handler = logging.StreamHandler(sys.stdout)
|
| 17 |
+
handler.setLevel(logging.INFO)
|
| 18 |
+
handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
|
| 19 |
+
logger.addHandler(handler)
|
| 20 |
+
|
| 21 |
+
logger.setLevel(logging.INFO)
|
| 22 |
+
logger.propagate = False
|
| 23 |
+
|
| 24 |
+
DEFAULT_STALE_MINUTES = 15 # hard-coded fallback
|
| 25 |
+
DEFAULT_MAX_OPEN_FOR_MINUTES = 4320 # hard-coded fallback - 3 days (72 hours)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_MIN, _MAX = 1, 60 # sanity window (optional)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _get_stale_minutes() -> int:
|
| 32 |
+
"""Read STALE_MINUTES from the environment, fall back to default,
|
| 33 |
+
and clamp to a safe range.
|
| 34 |
+
"""
|
| 35 |
+
raw = os.getenv("STALE_MINUTES", str(DEFAULT_STALE_MINUTES))
|
| 36 |
+
try:
|
| 37 |
+
value = int(raw)
|
| 38 |
+
except ValueError:
|
| 39 |
+
logging.warning(
|
| 40 |
+
"STALE_MINUTES=%r is not an int; using default=%d",
|
| 41 |
+
raw,
|
| 42 |
+
DEFAULT_STALE_MINUTES,
|
| 43 |
+
)
|
| 44 |
+
value = DEFAULT_STALE_MINUTES
|
| 45 |
+
|
| 46 |
+
if not _MIN <= value <= _MAX:
|
| 47 |
+
logging.warning("STALE_MINUTES=%d outside %d–%d; clamping", value, _MIN, _MAX)
|
| 48 |
+
value = max(_MIN, min(_MAX, value))
|
| 49 |
+
|
| 50 |
+
return value
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
STALE_MINUTES = _get_stale_minutes()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _max_open_for_minutes() -> int:
|
| 57 |
+
"""Read MAX_OPEN_F1OR_MINUTES from the environment, fall back to default,
|
| 58 |
+
and clamp to a safe range.
|
| 59 |
+
"""
|
| 60 |
+
raw = os.getenv("MAX_OPEN_FOR_MINUTES", str(DEFAULT_MAX_OPEN_FOR_MINUTES))
|
| 61 |
+
try:
|
| 62 |
+
value = int(raw)
|
| 63 |
+
except ValueError:
|
| 64 |
+
logger.warning(
|
| 65 |
+
"MAX_OPEN_FOR_MINUTES=%r is not an int; using default=%d",
|
| 66 |
+
raw,
|
| 67 |
+
DEFAULT_MAX_OPEN_FOR_MINUTES,
|
| 68 |
+
)
|
| 69 |
+
value = DEFAULT_MAX_OPEN_FOR_MINUTES
|
| 70 |
+
|
| 71 |
+
if not _MAX <= value <= _MAX * 24 * 7:
|
| 72 |
+
logger.warning(
|
| 73 |
+
"MAX_OPEN_FOR_MINUTES=%d outside %d–%d; clamping",
|
| 74 |
+
value,
|
| 75 |
+
_MAX,
|
| 76 |
+
_MAX * 24 * 7,
|
| 77 |
+
)
|
| 78 |
+
value = max(_MAX, min(_MAX * 24 * 7, value))
|
| 79 |
+
|
| 80 |
+
return value
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
MAX_OPEN_FOR_MINUTES = _max_open_for_minutes()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class EnvironmentScore(BaseModel):
|
| 87 |
+
"""Score for an environment run."""
|
| 88 |
+
|
| 89 |
+
id: Optional[str] = None
|
| 90 |
+
guid: Optional[str] = None
|
| 91 |
+
score: float
|
| 92 |
+
levels_completed: int
|
| 93 |
+
actions: int
|
| 94 |
+
resets: Optional[int] = None
|
| 95 |
+
state: Optional[GameState] = None
|
| 96 |
+
completed: Optional[bool] = None
|
| 97 |
+
level_scores: Optional[list[float]] = None
|
| 98 |
+
level_actions: Optional[list[int]] = None
|
| 99 |
+
level_baseline_actions: Optional[list[int]] = None
|
| 100 |
+
number_of_levels: Optional[int] = None
|
| 101 |
+
number_of_environments: Optional[int] = 0
|
| 102 |
+
message: Optional[str] = None
|
| 103 |
+
|
| 104 |
+
def model_dump_json(self, *, exclude_none: bool = True, **kwargs: Any) -> str:
|
| 105 |
+
"""Serialize to JSON string, excluding None fields by default.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
exclude_none: If True, exclude fields that are None. Defaults to True.
|
| 109 |
+
**kwargs: Additional arguments passed to parent model_dump_json.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
JSON string representation of the model.
|
| 113 |
+
"""
|
| 114 |
+
return super().model_dump_json(exclude_none=exclude_none, **kwargs)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class EnvironmentScoreCalculator:
|
| 118 |
+
"""Calculator for environment scores."""
|
| 119 |
+
|
| 120 |
+
def __init__(
|
| 121 |
+
self,
|
| 122 |
+
id: Optional[str] = None,
|
| 123 |
+
resets: Optional[int] = None,
|
| 124 |
+
state: Optional[GameState] = None,
|
| 125 |
+
guid: Optional[str] = None,
|
| 126 |
+
) -> None:
|
| 127 |
+
"""Initialize the calculator.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
id: Identifier for the environment run.
|
| 131 |
+
resets: Optional number of resets.
|
| 132 |
+
"""
|
| 133 |
+
self.id = id
|
| 134 |
+
self.guid = guid
|
| 135 |
+
self.resets = resets
|
| 136 |
+
self.level_indices: list[int] = []
|
| 137 |
+
self.level_scores: list[float] = []
|
| 138 |
+
self.levels_completed: int = 0
|
| 139 |
+
self.actions: int = 0
|
| 140 |
+
self.environments: set[str] = set()
|
| 141 |
+
self.state: Optional[GameState] = state
|
| 142 |
+
self.completed: Optional[bool] = None
|
| 143 |
+
self.level_actions: list[int] = []
|
| 144 |
+
self.level_baseline_actions: list[int] = []
|
| 145 |
+
|
| 146 |
+
def add_level(
|
| 147 |
+
self,
|
| 148 |
+
level_index: int,
|
| 149 |
+
completed: bool,
|
| 150 |
+
actions_taken: int,
|
| 151 |
+
baseline_actions: int,
|
| 152 |
+
game_id: Optional[str] = None,
|
| 153 |
+
) -> None:
|
| 154 |
+
"""Add a level to the score calculation.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
completed: Whether the level was completed.
|
| 158 |
+
actions_taken: Number of actions taken to complete the level.
|
| 159 |
+
baseline_actions: Baseline number of actions for the level.
|
| 160 |
+
"""
|
| 161 |
+
self.actions += actions_taken
|
| 162 |
+
|
| 163 |
+
if game_id:
|
| 164 |
+
self.environments.add(game_id)
|
| 165 |
+
|
| 166 |
+
if completed:
|
| 167 |
+
self.levels_completed += 1
|
| 168 |
+
# Calculate score as ((baseline_actions / actions_taken)^2 * 100) max 100
|
| 169 |
+
if actions_taken > 0:
|
| 170 |
+
score = ((baseline_actions / actions_taken) ** 2) * 100
|
| 171 |
+
score = min(score, 115.0) # Cap at 115
|
| 172 |
+
else:
|
| 173 |
+
score = 0.0
|
| 174 |
+
self.level_indices.append(level_index)
|
| 175 |
+
self.level_scores.append(score)
|
| 176 |
+
self.level_actions.append(actions_taken)
|
| 177 |
+
self.level_baseline_actions.append(baseline_actions)
|
| 178 |
+
else:
|
| 179 |
+
# Not completed, append 0
|
| 180 |
+
self.level_indices.append(level_index)
|
| 181 |
+
self.level_scores.append(0.0)
|
| 182 |
+
self.level_actions.append(actions_taken)
|
| 183 |
+
self.level_baseline_actions.append(baseline_actions)
|
| 184 |
+
|
| 185 |
+
def to_score(self, include_levels: bool = True) -> EnvironmentScore:
|
| 186 |
+
"""Convert the calculator to an EnvironmentScore.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
EnvironmentScore with average of level_scores as the score.
|
| 190 |
+
"""
|
| 191 |
+
# Calculate average of level_scores
|
| 192 |
+
max_weights = 0
|
| 193 |
+
if len(self.level_scores) > 0:
|
| 194 |
+
total_score = 0.0
|
| 195 |
+
total_weights = 0
|
| 196 |
+
for i in range(len(self.level_scores)):
|
| 197 |
+
weight = self.level_indices[i]
|
| 198 |
+
total_score += self.level_scores[i] * weight
|
| 199 |
+
total_weights += weight
|
| 200 |
+
if self.level_scores[i] > 0:
|
| 201 |
+
max_weights += weight
|
| 202 |
+
|
| 203 |
+
# Calculate average of level_scores
|
| 204 |
+
score = total_score / total_weights
|
| 205 |
+
max_score = max_weights / total_weights * 100
|
| 206 |
+
score = min(score, max_score)
|
| 207 |
+
else:
|
| 208 |
+
score = 0.0
|
| 209 |
+
|
| 210 |
+
return EnvironmentScore(
|
| 211 |
+
id=self.id,
|
| 212 |
+
guid=self.guid,
|
| 213 |
+
score=score,
|
| 214 |
+
levels_completed=self.levels_completed,
|
| 215 |
+
actions=self.actions,
|
| 216 |
+
resets=self.resets,
|
| 217 |
+
state=self.state,
|
| 218 |
+
completed=self.completed,
|
| 219 |
+
level_scores=self.level_scores if include_levels else None,
|
| 220 |
+
level_actions=self.level_actions if include_levels else None,
|
| 221 |
+
level_baseline_actions=self.level_baseline_actions
|
| 222 |
+
if include_levels
|
| 223 |
+
else None,
|
| 224 |
+
number_of_levels=len(self.level_scores) if not include_levels else None,
|
| 225 |
+
number_of_environments=len(self.environments)
|
| 226 |
+
if not include_levels
|
| 227 |
+
else None,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class EnvironmentScoreList(BaseModel):
|
| 232 |
+
"""List of EnvironmentScore objects."""
|
| 233 |
+
|
| 234 |
+
id: str
|
| 235 |
+
runs: List[EnvironmentScore] = Field(default_factory=list)
|
| 236 |
+
|
| 237 |
+
@computed_field(return_type=float) # type: ignore[prop-decorator]# type:
|
| 238 |
+
@property
|
| 239 |
+
def score(self) -> float:
|
| 240 |
+
"""Return the average score of the runs."""
|
| 241 |
+
return max(run.score for run in self.runs)
|
| 242 |
+
|
| 243 |
+
@computed_field(return_type=int) # type: ignore[prop-decorator]# type:
|
| 244 |
+
@property
|
| 245 |
+
def actions(self) -> int:
|
| 246 |
+
"""Return the total number of actions."""
|
| 247 |
+
return sum(run.actions for run in self.runs)
|
| 248 |
+
|
| 249 |
+
@computed_field(return_type=int) # type: ignore[prop-decorator]# type:
|
| 250 |
+
@property
|
| 251 |
+
def levels_completed(self) -> int:
|
| 252 |
+
"""Return the total number of levels completed."""
|
| 253 |
+
return max(run.levels_completed for run in self.runs)
|
| 254 |
+
|
| 255 |
+
@computed_field(return_type=bool) # type: ignore[prop-decorator]# type:
|
| 256 |
+
@property
|
| 257 |
+
def completed(self) -> bool:
|
| 258 |
+
"""Return True if all runs are completed."""
|
| 259 |
+
return any(run.completed for run in self.runs)
|
| 260 |
+
|
| 261 |
+
@computed_field(return_type=int) # type: ignore[prop-decorator]# type:
|
| 262 |
+
@property
|
| 263 |
+
def level_count(self) -> int:
|
| 264 |
+
"""Return the total number of levels."""
|
| 265 |
+
return max(
|
| 266 |
+
len(run.level_scores) if run.level_scores else 0 for run in self.runs
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
@computed_field(return_type=int) # type: ignore[prop-decorator]# type:
|
| 270 |
+
@property
|
| 271 |
+
def resets(self) -> int:
|
| 272 |
+
"""Return the total number of resets."""
|
| 273 |
+
return sum(run.resets if run.resets else 0 for run in self.runs)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class EnvironmentScorecard(BaseModel):
|
| 277 |
+
"""Scorecard with computed environment scores."""
|
| 278 |
+
|
| 279 |
+
source_url: Optional[str] = None
|
| 280 |
+
tags: Optional[list[str]] = None
|
| 281 |
+
opaque: Optional[Any] = None
|
| 282 |
+
card_id: str
|
| 283 |
+
api_key: Optional[str] = None
|
| 284 |
+
score: float = 0.0
|
| 285 |
+
environments: List[EnvironmentScoreList] = Field(default_factory=list)
|
| 286 |
+
tags_scores: List[EnvironmentScore] = Field(default_factory=list)
|
| 287 |
+
open_at: datetime = Field(
|
| 288 |
+
default_factory=lambda: datetime.now(timezone.utc),
|
| 289 |
+
exclude=True,
|
| 290 |
+
)
|
| 291 |
+
last_update: datetime = Field(
|
| 292 |
+
default_factory=lambda: datetime.now(timezone.utc),
|
| 293 |
+
exclude=True,
|
| 294 |
+
)
|
| 295 |
+
competition_mode: Optional[bool] = False
|
| 296 |
+
|
| 297 |
+
def get(self, game_id: Optional[str] = None) -> dict[str, Any]:
|
| 298 |
+
if game_id is not None:
|
| 299 |
+
for environment in self.environments:
|
| 300 |
+
for run in environment.runs:
|
| 301 |
+
if run.id == game_id:
|
| 302 |
+
return run.model_dump()
|
| 303 |
+
return {}
|
| 304 |
+
return self.model_dump()
|
| 305 |
+
|
| 306 |
+
def __str__(self) -> str:
|
| 307 |
+
return self.model_dump_json(indent=2)
|
| 308 |
+
|
| 309 |
+
@computed_field(return_type=int)
|
| 310 |
+
def total_environments_completed(self) -> int:
|
| 311 |
+
"""Return the number of environments that are completed."""
|
| 312 |
+
return sum(1 if env.completed else 0 for env in self.environments)
|
| 313 |
+
|
| 314 |
+
@computed_field(return_type=int)
|
| 315 |
+
def total_environments(self) -> int:
|
| 316 |
+
"""Return the total number of environments."""
|
| 317 |
+
return len(self.environments)
|
| 318 |
+
|
| 319 |
+
@computed_field(return_type=int)
|
| 320 |
+
def total_levels_completed(self) -> int:
|
| 321 |
+
"""Return the total number of levels completed."""
|
| 322 |
+
return sum(env.levels_completed for env in self.environments)
|
| 323 |
+
|
| 324 |
+
@computed_field(return_type=int)
|
| 325 |
+
def total_levels(self) -> int:
|
| 326 |
+
"""Return the total number of levels."""
|
| 327 |
+
return sum(env.level_count for env in self.environments)
|
| 328 |
+
|
| 329 |
+
@computed_field(return_type=int)
|
| 330 |
+
def total_actions(self) -> int:
|
| 331 |
+
"""Return the total number of resets."""
|
| 332 |
+
return sum(env.actions for env in self.environments)
|
| 333 |
+
|
| 334 |
+
def find_environment(self, id_prefix: str) -> Optional[EnvironmentScoreList]:
|
| 335 |
+
for environment in self.environments:
|
| 336 |
+
if environment.id.startswith(id_prefix):
|
| 337 |
+
return environment
|
| 338 |
+
return None
|
| 339 |
+
|
| 340 |
+
def model_dump_json(self, *, exclude_none: bool = True, **kwargs: Any) -> str:
|
| 341 |
+
"""Serialize to JSON string, excluding None fields by default.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
exclude_none: If True, exclude fields that are None. Defaults to True.
|
| 345 |
+
**kwargs: Additional arguments passed to parent model_dump_json.
|
| 346 |
+
|
| 347 |
+
Returns:
|
| 348 |
+
JSON string representation of the model.
|
| 349 |
+
"""
|
| 350 |
+
return super().model_dump_json(exclude_none=exclude_none, **kwargs)
|
| 351 |
+
|
| 352 |
+
@classmethod
|
| 353 |
+
def _raw_scores_from_card(
|
| 354 |
+
self, card: "Card", idx: int
|
| 355 |
+
) -> tuple[list[int], list[float], list[int]]:
|
| 356 |
+
"""Return the raw score from the card."""
|
| 357 |
+
actions_by_level = (
|
| 358 |
+
card.actions_by_level[idx] if idx < len(card.actions_by_level) else []
|
| 359 |
+
)
|
| 360 |
+
prev_actions = 0
|
| 361 |
+
actions: list[int] = []
|
| 362 |
+
scores: list[float] = []
|
| 363 |
+
baseline_actions: list[int] = []
|
| 364 |
+
for level_idx in range(len(actions_by_level)):
|
| 365 |
+
actions_at_level = actions_by_level[level_idx]
|
| 366 |
+
level_actions = actions_at_level[1] - prev_actions
|
| 367 |
+
actions.append(level_actions)
|
| 368 |
+
scores.append(0.0)
|
| 369 |
+
baseline_actions.append(-1) # indicate not available
|
| 370 |
+
prev_actions = actions_at_level[1]
|
| 371 |
+
|
| 372 |
+
if card.states[idx] != GameState.WIN:
|
| 373 |
+
actions.append(card.actions[idx] - prev_actions)
|
| 374 |
+
scores.append(0.0)
|
| 375 |
+
baseline_actions.append(-1) # indicate not available
|
| 376 |
+
|
| 377 |
+
return actions, scores, baseline_actions
|
| 378 |
+
|
| 379 |
+
@classmethod
|
| 380 |
+
def _calculate_score(
|
| 381 |
+
cls,
|
| 382 |
+
card: "Card",
|
| 383 |
+
game_id: str,
|
| 384 |
+
idx: int,
|
| 385 |
+
env_info: EnvironmentInfo | None,
|
| 386 |
+
tags_scores: dict[str, EnvironmentScoreCalculator] | None,
|
| 387 |
+
do_private_tags: bool = False,
|
| 388 |
+
) -> EnvironmentScore:
|
| 389 |
+
"""Calculate the score for a single card."""
|
| 390 |
+
levels_completed = card.levels_completed[idx]
|
| 391 |
+
guid = card.guids[idx]
|
| 392 |
+
actions = card.actions[idx] if idx < len(card.actions) else 0
|
| 393 |
+
resets = card.resets[idx] if idx < len(card.resets) else 0
|
| 394 |
+
state = card.states[idx] if idx < len(card.states) else GameState.NOT_PLAYED
|
| 395 |
+
completed = state == GameState.WIN
|
| 396 |
+
|
| 397 |
+
# Find matching EnvironmentInfo
|
| 398 |
+
if not env_info:
|
| 399 |
+
only_level_actions, scores, baseline_actions = cls._raw_scores_from_card(
|
| 400 |
+
card, idx
|
| 401 |
+
)
|
| 402 |
+
return EnvironmentScore(
|
| 403 |
+
id=card.game_id,
|
| 404 |
+
guid=guid,
|
| 405 |
+
score=0.0,
|
| 406 |
+
levels_completed=levels_completed,
|
| 407 |
+
actions=actions,
|
| 408 |
+
resets=resets,
|
| 409 |
+
state=state,
|
| 410 |
+
completed=completed,
|
| 411 |
+
level_actions=only_level_actions,
|
| 412 |
+
level_baseline_actions=baseline_actions,
|
| 413 |
+
level_scores=scores,
|
| 414 |
+
message=f"No Matching EnvironmentInfo found for {game_id}",
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
# Check if baseline_actions are available
|
| 418 |
+
if env_info.baseline_actions is None or len(env_info.baseline_actions) == 0:
|
| 419 |
+
# No baseline actions available
|
| 420 |
+
only_level_actions, scores, baseline_actions = cls._raw_scores_from_card(
|
| 421 |
+
card, idx
|
| 422 |
+
)
|
| 423 |
+
return EnvironmentScore(
|
| 424 |
+
id=card.game_id,
|
| 425 |
+
guid=guid,
|
| 426 |
+
score=0.0,
|
| 427 |
+
levels_completed=levels_completed,
|
| 428 |
+
actions=actions,
|
| 429 |
+
resets=resets,
|
| 430 |
+
state=state,
|
| 431 |
+
completed=completed,
|
| 432 |
+
level_actions=only_level_actions,
|
| 433 |
+
level_baseline_actions=baseline_actions,
|
| 434 |
+
level_scores=scores,
|
| 435 |
+
message="Human baseline actions are not available for this environment",
|
| 436 |
+
)
|
| 437 |
+
elif len(env_info.baseline_actions) < len(card.actions_by_level[idx]):
|
| 438 |
+
# No baseline actions available
|
| 439 |
+
only_level_actions, scores, baseline_actions = cls._raw_scores_from_card(
|
| 440 |
+
card, idx
|
| 441 |
+
)
|
| 442 |
+
return EnvironmentScore(
|
| 443 |
+
id=card.game_id,
|
| 444 |
+
guid=guid,
|
| 445 |
+
score=0.0,
|
| 446 |
+
levels_completed=levels_completed,
|
| 447 |
+
actions=actions,
|
| 448 |
+
resets=resets,
|
| 449 |
+
state=state,
|
| 450 |
+
completed=completed,
|
| 451 |
+
level_actions=only_level_actions,
|
| 452 |
+
level_baseline_actions=baseline_actions,
|
| 453 |
+
level_scores=scores,
|
| 454 |
+
message="Human baseline actions size mismatch",
|
| 455 |
+
)
|
| 456 |
+
else:
|
| 457 |
+
# Calculate score using EnvironmentScoreCalculator
|
| 458 |
+
calculator = EnvironmentScoreCalculator(
|
| 459 |
+
resets=resets, guid=guid, state=state
|
| 460 |
+
)
|
| 461 |
+
calculator.completed = completed
|
| 462 |
+
|
| 463 |
+
# Process each level
|
| 464 |
+
# We need to determine how many levels were attempted and completed
|
| 465 |
+
# The actions_by_level list contains tuples of (level, actions) when level changed
|
| 466 |
+
actions_by_level = (
|
| 467 |
+
card.actions_by_level[idx] if idx < len(card.actions_by_level) else []
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# If we have actions_by_level, use that to determine level progression
|
| 471 |
+
# if actions_by_level:
|
| 472 |
+
# actions_by_level contains (level_completed, actions_at_that_point)
|
| 473 |
+
# We need to calculate actions per level
|
| 474 |
+
prev_actions = 0
|
| 475 |
+
for level_idx in range(len(env_info.baseline_actions)):
|
| 476 |
+
baseline = env_info.baseline_actions[level_idx]
|
| 477 |
+
if level_idx < len(actions_by_level):
|
| 478 |
+
level, actions_at_level = actions_by_level[level_idx]
|
| 479 |
+
level_actions = actions_at_level - prev_actions
|
| 480 |
+
level_completed = level_idx < len(actions_by_level) or completed
|
| 481 |
+
prev_actions = actions_at_level
|
| 482 |
+
else:
|
| 483 |
+
level_completed = False
|
| 484 |
+
level_actions = card.actions[idx] - prev_actions
|
| 485 |
+
prev_actions = card.actions[idx]
|
| 486 |
+
calculator.add_level(
|
| 487 |
+
level_index=level_idx + 1,
|
| 488 |
+
completed=level_completed,
|
| 489 |
+
actions_taken=level_actions,
|
| 490 |
+
baseline_actions=baseline,
|
| 491 |
+
)
|
| 492 |
+
if tags_scores is not None:
|
| 493 |
+
if env_info.tags:
|
| 494 |
+
for tag in env_info.tags:
|
| 495 |
+
tag_score = tags_scores.get(tag)
|
| 496 |
+
if not tag_score:
|
| 497 |
+
tag_score = EnvironmentScoreCalculator(id=tag)
|
| 498 |
+
tags_scores[tag] = tag_score
|
| 499 |
+
tag_score.add_level(
|
| 500 |
+
level_index=level_idx + 1,
|
| 501 |
+
completed=level_completed,
|
| 502 |
+
actions_taken=level_actions,
|
| 503 |
+
baseline_actions=baseline,
|
| 504 |
+
game_id=game_id,
|
| 505 |
+
)
|
| 506 |
+
if do_private_tags:
|
| 507 |
+
if env_info.private_tags is not None:
|
| 508 |
+
for tag in env_info.private_tags:
|
| 509 |
+
tag = f"private_{tag}"
|
| 510 |
+
tag_score = tags_scores.get(tag)
|
| 511 |
+
if not tag_score:
|
| 512 |
+
tag_score = EnvironmentScoreCalculator(id=tag)
|
| 513 |
+
tags_scores[tag] = tag_score
|
| 514 |
+
tag_score.add_level(
|
| 515 |
+
level_index=level_idx + 1,
|
| 516 |
+
completed=level_completed,
|
| 517 |
+
actions_taken=level_actions,
|
| 518 |
+
baseline_actions=baseline,
|
| 519 |
+
game_id=game_id,
|
| 520 |
+
)
|
| 521 |
+
if env_info.level_tags and level_idx < len(env_info.level_tags):
|
| 522 |
+
level_tags = env_info.level_tags[level_idx]
|
| 523 |
+
for tag in level_tags:
|
| 524 |
+
tag = f"private_{tag}"
|
| 525 |
+
tag_score = tags_scores.get(tag)
|
| 526 |
+
if not tag_score:
|
| 527 |
+
tag_score = EnvironmentScoreCalculator(id=tag)
|
| 528 |
+
tags_scores[tag] = tag_score
|
| 529 |
+
tag_score.add_level(
|
| 530 |
+
level_index=level_idx + 1,
|
| 531 |
+
completed=level_completed,
|
| 532 |
+
actions_taken=level_actions,
|
| 533 |
+
baseline_actions=baseline,
|
| 534 |
+
game_id=game_id,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
return calculator.to_score()
|
| 538 |
+
|
| 539 |
+
@classmethod
|
| 540 |
+
def from_scorecard(
|
| 541 |
+
cls,
|
| 542 |
+
scorecard: "Scorecard",
|
| 543 |
+
environment_infos: List[EnvironmentInfo],
|
| 544 |
+
do_private_tags: bool = False,
|
| 545 |
+
) -> "EnvironmentScorecard":
|
| 546 |
+
"""Create EnvironmentScorecard from Scorecard and EnvironmentInfos.
|
| 547 |
+
|
| 548 |
+
Args:
|
| 549 |
+
scorecard: The Scorecard to compute from.
|
| 550 |
+
environment_infos: List of EnvironmentInfo objects to match against.
|
| 551 |
+
|
| 552 |
+
Returns:
|
| 553 |
+
EnvironmentScorecard with computed scores.
|
| 554 |
+
"""
|
| 555 |
+
# Create a mapping of game_id to EnvironmentInfo
|
| 556 |
+
# Match by full game_id (which may include version)
|
| 557 |
+
env_info_map: dict[str, EnvironmentInfo] = {}
|
| 558 |
+
for env_info in environment_infos:
|
| 559 |
+
# Use full game_id as key (e.g., "bt11" or "bt11-fd9df0622a1a")
|
| 560 |
+
env_info_map[env_info.game_id] = env_info
|
| 561 |
+
|
| 562 |
+
# Compute environment scores from cards
|
| 563 |
+
# For each game_id, we'll track the best score (highest levels_completed)
|
| 564 |
+
game_scores: dict[str, EnvironmentScoreList] = {}
|
| 565 |
+
tags_scores: dict[str, EnvironmentScoreCalculator] = {}
|
| 566 |
+
|
| 567 |
+
for game_id, card in scorecard.cards.items():
|
| 568 |
+
# Find the idx with the highest levels_completed
|
| 569 |
+
best_idx = -1
|
| 570 |
+
best_levels_completed = -1
|
| 571 |
+
for idx, levels_completed in enumerate(card.levels_completed):
|
| 572 |
+
if levels_completed > best_levels_completed:
|
| 573 |
+
best_levels_completed = levels_completed
|
| 574 |
+
best_idx = idx
|
| 575 |
+
|
| 576 |
+
# If no valid play found, skip this card
|
| 577 |
+
if best_idx == -1 or best_idx >= len(card.guids):
|
| 578 |
+
continue
|
| 579 |
+
|
| 580 |
+
all_scores: List[EnvironmentScore] = []
|
| 581 |
+
for idx, levels_completed in enumerate(card.levels_completed):
|
| 582 |
+
if idx == best_idx:
|
| 583 |
+
score = cls._calculate_score(
|
| 584 |
+
card,
|
| 585 |
+
game_id,
|
| 586 |
+
best_idx,
|
| 587 |
+
env_info_map.get(game_id),
|
| 588 |
+
tags_scores,
|
| 589 |
+
do_private_tags,
|
| 590 |
+
)
|
| 591 |
+
else:
|
| 592 |
+
score = cls._calculate_score(
|
| 593 |
+
card,
|
| 594 |
+
game_id,
|
| 595 |
+
idx,
|
| 596 |
+
env_info_map.get(game_id),
|
| 597 |
+
None,
|
| 598 |
+
do_private_tags,
|
| 599 |
+
)
|
| 600 |
+
all_scores.append(score)
|
| 601 |
+
|
| 602 |
+
if all_scores and len(all_scores) > 0:
|
| 603 |
+
game_scores[game_id] = EnvironmentScoreList(id=game_id, runs=all_scores)
|
| 604 |
+
|
| 605 |
+
# Convert dict to list
|
| 606 |
+
environment_list = list(game_scores.values())
|
| 607 |
+
tags_list = [
|
| 608 |
+
calculator.to_score(include_levels=False)
|
| 609 |
+
for calculator in tags_scores.values()
|
| 610 |
+
]
|
| 611 |
+
|
| 612 |
+
# Calculate average score
|
| 613 |
+
if len(environment_list) > 0:
|
| 614 |
+
avg_score = sum(env_score.score for env_score in environment_list) / len(
|
| 615 |
+
environment_list
|
| 616 |
+
)
|
| 617 |
+
else:
|
| 618 |
+
avg_score = 0.0
|
| 619 |
+
|
| 620 |
+
return cls(
|
| 621 |
+
source_url=scorecard.source_url,
|
| 622 |
+
tags=scorecard.tags,
|
| 623 |
+
opaque=scorecard.opaque,
|
| 624 |
+
card_id=scorecard.card_id,
|
| 625 |
+
api_key=scorecard.api_key,
|
| 626 |
+
score=avg_score,
|
| 627 |
+
environments=environment_list,
|
| 628 |
+
tags_scores=tags_list,
|
| 629 |
+
open_at=scorecard.open_at,
|
| 630 |
+
last_update=scorecard.last_update,
|
| 631 |
+
competition_mode=scorecard.competition_mode,
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
class Card(BaseModel):
|
| 636 |
+
"""
|
| 637 |
+
A single scorecard for a single game. A game can be played more than
|
| 638 |
+
once, we track each play with lists of card properties (scores, states, actions)
|
| 639 |
+
"""
|
| 640 |
+
|
| 641 |
+
game_id: str
|
| 642 |
+
total_plays: int = 0
|
| 643 |
+
|
| 644 |
+
guids: list[str] = Field(default_factory=list)
|
| 645 |
+
levels_completed: list[int] = Field(default_factory=list)
|
| 646 |
+
states: list[GameState] = Field(default_factory=list)
|
| 647 |
+
actions: list[int] = Field(default_factory=list)
|
| 648 |
+
actions_by_level: list[list[tuple[int, int]]] = Field(
|
| 649 |
+
default_factory=list, exclude=False
|
| 650 |
+
)
|
| 651 |
+
resets: list[int] = Field(default_factory=list)
|
| 652 |
+
|
| 653 |
+
@property
|
| 654 |
+
def idx(self) -> int:
|
| 655 |
+
# lists are zero indexed by play_count starts at 1
|
| 656 |
+
return self.total_plays - 1
|
| 657 |
+
|
| 658 |
+
@property
|
| 659 |
+
def started(self) -> bool:
|
| 660 |
+
return self.total_plays > 0
|
| 661 |
+
|
| 662 |
+
@property
|
| 663 |
+
def level_completed(self) -> Optional[int]:
|
| 664 |
+
return self.levels_completed[self.idx] if self.started else None
|
| 665 |
+
|
| 666 |
+
@property
|
| 667 |
+
def most_levels_completed(self) -> int:
|
| 668 |
+
return max(self.levels_completed) if self.started else 0
|
| 669 |
+
|
| 670 |
+
@property
|
| 671 |
+
def state(self) -> GameState:
|
| 672 |
+
return self.states[self.idx] if self.started else GameState.NOT_PLAYED
|
| 673 |
+
|
| 674 |
+
@property
|
| 675 |
+
def action_count(self) -> Optional[int]:
|
| 676 |
+
return self.actions[self.idx] if self.started else None
|
| 677 |
+
|
| 678 |
+
@computed_field(return_type=int)
|
| 679 |
+
def total_actions(self) -> int:
|
| 680 |
+
return sum(self.actions)
|
| 681 |
+
|
| 682 |
+
def get_total_actions(self) -> int:
|
| 683 |
+
return sum(self.actions)
|
| 684 |
+
|
| 685 |
+
def index_of_guid(self, match: str) -> int:
|
| 686 |
+
# Iterate backwards since a guid can be reused and we want the most recent
|
| 687 |
+
for idx in range(len(self.guids) - 1, -1, -1):
|
| 688 |
+
if self.guids[idx] == match:
|
| 689 |
+
return idx
|
| 690 |
+
return self.total_plays - 1
|
| 691 |
+
|
| 692 |
+
def inc_play_count(self, guid: str) -> None:
|
| 693 |
+
self.total_plays += 1
|
| 694 |
+
self.guids.append(guid)
|
| 695 |
+
self.levels_completed.append(0)
|
| 696 |
+
self.states.append(GameState.NOT_FINISHED)
|
| 697 |
+
self.actions.append(0)
|
| 698 |
+
self.resets.append(0)
|
| 699 |
+
self.actions_by_level.append([])
|
| 700 |
+
|
| 701 |
+
def inc_reset_count(self, guid: str) -> None:
|
| 702 |
+
if self.started:
|
| 703 |
+
self.resets[self.index_of_guid(guid)] += 1
|
| 704 |
+
self.actions[self.index_of_guid(guid)] += 1
|
| 705 |
+
|
| 706 |
+
def set_levels_completed(self, guid: str, current_levels_completed: int) -> None:
|
| 707 |
+
if self.started:
|
| 708 |
+
index = self.index_of_guid(guid)
|
| 709 |
+
existing_levels_completed = self.levels_completed[index]
|
| 710 |
+
if current_levels_completed != existing_levels_completed:
|
| 711 |
+
self.actions_by_level[index].append(
|
| 712 |
+
(current_levels_completed, self.actions[index])
|
| 713 |
+
)
|
| 714 |
+
self.levels_completed[index] = current_levels_completed
|
| 715 |
+
|
| 716 |
+
def set_state(self, guid: str, state: GameState) -> None:
|
| 717 |
+
if self.started:
|
| 718 |
+
self.states[self.index_of_guid(guid)] = state
|
| 719 |
+
|
| 720 |
+
def inc_action_count(self, guid: str) -> None:
|
| 721 |
+
if self.started:
|
| 722 |
+
self.actions[self.index_of_guid(guid)] += 1
|
| 723 |
+
|
| 724 |
+
# def to_json(self) -> dict[str, Union[str, int, list[int], list[str]]]:
|
| 725 |
+
# return {
|
| 726 |
+
# "game_id": self.game_id,
|
| 727 |
+
# "total_plays": self.play_count,
|
| 728 |
+
# "total_actions": self.total_action_count,
|
| 729 |
+
# "scores": self.scores,
|
| 730 |
+
# "states": [s.name for s in self.states],
|
| 731 |
+
# "actions": self.action_counts,
|
| 732 |
+
# }
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
class Scorecard(BaseModel):
|
| 736 |
+
"""
|
| 737 |
+
Tracks and holds the scorecard for all games
|
| 738 |
+
"""
|
| 739 |
+
|
| 740 |
+
games: list[str] = Field(default_factory=list, exclude=True)
|
| 741 |
+
cards: dict[str, Card] = Field(default_factory=dict)
|
| 742 |
+
source_url: Optional[str] = None
|
| 743 |
+
tags: Optional[list[str]] = None
|
| 744 |
+
opaque: Optional[Any] = Field(default=None)
|
| 745 |
+
card_id: str = ""
|
| 746 |
+
api_key: str = ""
|
| 747 |
+
open_at: datetime = Field(
|
| 748 |
+
default_factory=lambda: datetime.now(timezone.utc),
|
| 749 |
+
exclude=True,
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
last_update: datetime = Field(
|
| 753 |
+
default_factory=lambda: datetime.now(timezone.utc),
|
| 754 |
+
exclude=True,
|
| 755 |
+
)
|
| 756 |
+
competition_mode: Optional[bool] = False
|
| 757 |
+
|
| 758 |
+
def model_post_init(self, __context: Any) -> None:
|
| 759 |
+
if not self.cards:
|
| 760 |
+
self.cards = {}
|
| 761 |
+
|
| 762 |
+
def new_play(self, game_id: str, guid: str) -> None:
|
| 763 |
+
if game_id not in self.cards:
|
| 764 |
+
self.cards[game_id] = Card.model_validate({"game_id": game_id})
|
| 765 |
+
if game_id in self.cards:
|
| 766 |
+
self.cards[game_id].inc_play_count(guid)
|
| 767 |
+
|
| 768 |
+
def reset(self, game_id: str, guid: str) -> None:
|
| 769 |
+
if game_id in self.cards:
|
| 770 |
+
self.cards[game_id].inc_reset_count(guid)
|
| 771 |
+
|
| 772 |
+
def take_action(self, game_id: str, guid: str) -> None:
|
| 773 |
+
if game_id in self.cards:
|
| 774 |
+
self.cards[game_id].inc_action_count(guid)
|
| 775 |
+
|
| 776 |
+
def win(self, game_id: str, guid: str) -> None:
|
| 777 |
+
if game_id in self.cards:
|
| 778 |
+
self.cards[game_id].set_state(
|
| 779 |
+
guid,
|
| 780 |
+
GameState.WIN,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def game_over(self, game_id: str, guid: str) -> None:
|
| 784 |
+
if game_id in self.cards:
|
| 785 |
+
self.cards[game_id].set_state(guid, GameState.GAME_OVER)
|
| 786 |
+
|
| 787 |
+
def set_levels_completed(
|
| 788 |
+
self, game_id: str, guid: str, level_completed: int
|
| 789 |
+
) -> None:
|
| 790 |
+
if game_id in self.cards:
|
| 791 |
+
self.cards[game_id].set_levels_completed(guid, level_completed)
|
| 792 |
+
|
| 793 |
+
def get(self, game_id: Optional[str] = None) -> dict[str, Any]:
|
| 794 |
+
if game_id is not None:
|
| 795 |
+
card = self.cards.get(game_id)
|
| 796 |
+
return {game_id: card.model_dump()} if card else {}
|
| 797 |
+
return {k: v.model_dump() for k, v in self.cards.items()}
|
| 798 |
+
|
| 799 |
+
def get_card(self, game_id: str) -> Card:
|
| 800 |
+
return self.cards[game_id]
|
| 801 |
+
|
| 802 |
+
@computed_field(return_type=int)
|
| 803 |
+
def won(self) -> int:
|
| 804 |
+
return sum([GameState.WIN in g.states for k, g in self.cards.items()])
|
| 805 |
+
|
| 806 |
+
@computed_field(return_type=int)
|
| 807 |
+
def played(self) -> int:
|
| 808 |
+
return sum([len(g.states) > 0 for k, g in self.cards.items()])
|
| 809 |
+
|
| 810 |
+
@computed_field(return_type=int)
|
| 811 |
+
def total_actions(self) -> int:
|
| 812 |
+
return sum([g.get_total_actions() for k, g in self.cards.items()])
|
| 813 |
+
|
| 814 |
+
@computed_field(return_type=int)
|
| 815 |
+
def levels_completed(self) -> int:
|
| 816 |
+
return sum([g.most_levels_completed for k, g in self.cards.items()])
|
| 817 |
+
|
| 818 |
+
def get_json_for(self, game_id: str) -> dict[str, Any]:
|
| 819 |
+
card = self.cards.get(game_id)
|
| 820 |
+
return {
|
| 821 |
+
"won": self.won,
|
| 822 |
+
"played": self.played,
|
| 823 |
+
"total_actions": self.total_actions,
|
| 824 |
+
"levels_completed": self.levels_completed,
|
| 825 |
+
"cards": {game_id: card.model_dump()} if card else {},
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
def has_environment(self, game_id: str) -> bool:
|
| 829 |
+
for key, _ in self.cards.items():
|
| 830 |
+
if key.startswith(game_id):
|
| 831 |
+
return True
|
| 832 |
+
return False
|
| 833 |
+
|
| 834 |
+
def update_scorecard(
|
| 835 |
+
self, guid: str, data: FrameDataRaw, full_reset: bool
|
| 836 |
+
) -> GameState:
|
| 837 |
+
game_id = data.game_id
|
| 838 |
+
# Needs to happen first
|
| 839 |
+
if data.action_input and data.action_input.id.value in [0]:
|
| 840 |
+
if full_reset:
|
| 841 |
+
self.new_play(game_id, guid)
|
| 842 |
+
else:
|
| 843 |
+
self.reset(game_id, guid)
|
| 844 |
+
if data.action_input and data.action_input.id.value in [1, 2, 3, 4, 5, 6, 7]:
|
| 845 |
+
self.take_action(game_id, guid)
|
| 846 |
+
if data.state:
|
| 847 |
+
if data.state == GameState.GAME_OVER:
|
| 848 |
+
self.game_over(game_id, guid)
|
| 849 |
+
elif data.state == GameState.WIN:
|
| 850 |
+
self.win(game_id, guid)
|
| 851 |
+
self.set_levels_completed(game_id, guid, data.levels_completed)
|
| 852 |
+
|
| 853 |
+
self.last_update = datetime.now(timezone.utc)
|
| 854 |
+
|
| 855 |
+
card = self.cards.get(game_id)
|
| 856 |
+
return (
|
| 857 |
+
card.states[card.index_of_guid(guid)]
|
| 858 |
+
if card and card.started
|
| 859 |
+
else GameState.NOT_PLAYED
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
class ScorecardManager:
|
| 864 |
+
"""
|
| 865 |
+
Manages the scorecard for all games
|
| 866 |
+
"""
|
| 867 |
+
|
| 868 |
+
scorecards: dict[str, Scorecard]
|
| 869 |
+
guids: dict[str, str]
|
| 870 |
+
games: list[str]
|
| 871 |
+
idle_for: timedelta
|
| 872 |
+
max_open_for: timedelta
|
| 873 |
+
|
| 874 |
+
def __init__(
|
| 875 |
+
self,
|
| 876 |
+
games: list[str] = [],
|
| 877 |
+
recordings_dir: Optional[str] = None,
|
| 878 |
+
) -> None:
|
| 879 |
+
self.scorecards = {}
|
| 880 |
+
self.guids = {}
|
| 881 |
+
self.games = games
|
| 882 |
+
self.idle_for = timedelta(minutes=STALE_MINUTES)
|
| 883 |
+
self.max_open_for = timedelta(minutes=MAX_OPEN_FOR_MINUTES)
|
| 884 |
+
self.recordings_dir = recordings_dir or os.getenv(
|
| 885 |
+
"RECORDINGS_DIR", "recordings"
|
| 886 |
+
)
|
| 887 |
+
logger.info(
|
| 888 |
+
f"Initialized ScorecardManager with idle_for={self.idle_for} and max_open_for={self.max_open_for}"
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
def set_idle_for(self, idle_for: int) -> None:
|
| 892 |
+
self.idle_for = timedelta(minutes=idle_for)
|
| 893 |
+
logger.info(f"Updated idle_for to {self.idle_for}")
|
| 894 |
+
|
| 895 |
+
def idle_duration_for(self, card_id: str) -> Optional[timedelta]:
|
| 896 |
+
"""Return how long since last_update for this scorecard, or None if unknown."""
|
| 897 |
+
sc = self.scorecards.get(card_id)
|
| 898 |
+
if sc is None:
|
| 899 |
+
return None
|
| 900 |
+
return datetime.now(timezone.utc) - sc.last_update
|
| 901 |
+
|
| 902 |
+
def should_auto_close_scorecard(self, card_id: str) -> bool:
|
| 903 |
+
"""True if this scorecard still matches auto-close rules (same logic as get_stale_cards)."""
|
| 904 |
+
sc = self.scorecards.get(card_id)
|
| 905 |
+
if sc is None:
|
| 906 |
+
return False
|
| 907 |
+
now = datetime.now(timezone.utc)
|
| 908 |
+
idle = now - sc.last_update
|
| 909 |
+
open_for = now - sc.open_at
|
| 910 |
+
return idle >= self.idle_for or open_for >= self.max_open_for
|
| 911 |
+
|
| 912 |
+
def get_stale_cards(self) -> List[str]:
|
| 913 |
+
now = datetime.now(timezone.utc)
|
| 914 |
+
stale_ids: List[str] = []
|
| 915 |
+
for cid, sc in self.scorecards.items():
|
| 916 |
+
idle = now - sc.last_update
|
| 917 |
+
open_for = now - sc.open_at
|
| 918 |
+
if idle >= self.idle_for:
|
| 919 |
+
stale_ids.append(cid)
|
| 920 |
+
logger.info(
|
| 921 |
+
"[get_stale_cards] stale scorecard card_id=%s idle=%s (%.1fs) "
|
| 922 |
+
"threshold=%s (%.1fs)",
|
| 923 |
+
cid,
|
| 924 |
+
idle,
|
| 925 |
+
idle.total_seconds(),
|
| 926 |
+
self.idle_for,
|
| 927 |
+
self.idle_for.total_seconds(),
|
| 928 |
+
)
|
| 929 |
+
elif open_for >= self.max_open_for:
|
| 930 |
+
stale_ids.append(cid)
|
| 931 |
+
logger.info(
|
| 932 |
+
"[get_stale_cards] scorecard open too long card_id=%s open_for=%s (%.1fs) "
|
| 933 |
+
"threshold=%s (%.1fs)",
|
| 934 |
+
cid,
|
| 935 |
+
open_for,
|
| 936 |
+
open_for.total_seconds(),
|
| 937 |
+
self.max_open_for,
|
| 938 |
+
self.max_open_for.total_seconds(),
|
| 939 |
+
)
|
| 940 |
+
return stale_ids
|
| 941 |
+
|
| 942 |
+
def new_scorecard(
|
| 943 |
+
self,
|
| 944 |
+
source_url: Optional[str],
|
| 945 |
+
tags: Optional[list[str]],
|
| 946 |
+
api_key: str,
|
| 947 |
+
opaque: Any | None,
|
| 948 |
+
competition_mode: bool | None = None,
|
| 949 |
+
) -> str:
|
| 950 |
+
card_id = str(uuid.uuid4())
|
| 951 |
+
self.scorecards[card_id] = Scorecard.model_validate(
|
| 952 |
+
{
|
| 953 |
+
"games": self.games,
|
| 954 |
+
"source_url": source_url,
|
| 955 |
+
"tags": tags,
|
| 956 |
+
"card_id": card_id,
|
| 957 |
+
"api_key": api_key,
|
| 958 |
+
"opaque": opaque,
|
| 959 |
+
"competition_mode": competition_mode,
|
| 960 |
+
}
|
| 961 |
+
)
|
| 962 |
+
return card_id
|
| 963 |
+
|
| 964 |
+
def get_dummy_scorecard(self) -> Scorecard:
|
| 965 |
+
return Scorecard.model_validate({"games": self.games})
|
| 966 |
+
|
| 967 |
+
def close_scorecard(
|
| 968 |
+
self, card_id: str, api_key: str | None
|
| 969 |
+
) -> Tuple[Scorecard, list[str], list[str]] | Tuple[None, None, None]:
|
| 970 |
+
guids: list[str] = []
|
| 971 |
+
game_id_with_guids: list[str] = []
|
| 972 |
+
scorecard = self.scorecards.get(card_id)
|
| 973 |
+
if scorecard and (api_key is None or scorecard.api_key == api_key):
|
| 974 |
+
for card in scorecard.cards.values():
|
| 975 |
+
guids.extend(card.guids)
|
| 976 |
+
game_id_with_guids.extend(f"{g}.{card.game_id}" for g in card.guids)
|
| 977 |
+
del self.scorecards[card_id]
|
| 978 |
+
for guid in guids:
|
| 979 |
+
if guid in self.guids:
|
| 980 |
+
del self.guids[guid]
|
| 981 |
+
|
| 982 |
+
return scorecard, guids, list(set(game_id_with_guids))
|
| 983 |
+
|
| 984 |
+
return None, None, None
|
| 985 |
+
|
| 986 |
+
def get_scorecard(self, card_id: str, api_key: str) -> Scorecard | None:
|
| 987 |
+
scorecard = self.scorecards.get(card_id)
|
| 988 |
+
if scorecard and scorecard.api_key == api_key:
|
| 989 |
+
return scorecard
|
| 990 |
+
return None
|
| 991 |
+
|
| 992 |
+
def get_scorecard_from_guid(self, guid: str) -> Scorecard | None:
|
| 993 |
+
card_id = self.guids.get(guid)
|
| 994 |
+
if card_id is not None:
|
| 995 |
+
return self.scorecards.get(card_id)
|
| 996 |
+
return None
|
| 997 |
+
|
| 998 |
+
def add_game(self, card_id: str, guid: str) -> None:
|
| 999 |
+
scorecard = self.scorecards.get(card_id)
|
| 1000 |
+
if scorecard:
|
| 1001 |
+
self.guids[guid] = card_id
|
| 1002 |
+
|
| 1003 |
+
def update_scorecard(
|
| 1004 |
+
self, guid: str, data: FrameDataRaw, full_reset: bool = True
|
| 1005 |
+
) -> GameState:
|
| 1006 |
+
card_id = self.guids.get(guid)
|
| 1007 |
+
if not card_id:
|
| 1008 |
+
return GameState.NOT_PLAYED
|
| 1009 |
+
scorecard = self.scorecards.get(card_id)
|
| 1010 |
+
if scorecard is None:
|
| 1011 |
+
return GameState.NOT_PLAYED
|
| 1012 |
+
return scorecard.update_scorecard(guid, data, full_reset)
|
arcprize__ARC-AGI/arc_agi/server.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
from arcengine import FrameDataRaw, GameAction
|
| 4 |
+
from flask import Flask, Response
|
| 5 |
+
|
| 6 |
+
from .api import RestAPI
|
| 7 |
+
from .base import Arcade
|
| 8 |
+
from .scorecard import EnvironmentScorecard
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def create_app(
|
| 12 |
+
arcade: Arcade,
|
| 13 |
+
competition_mode: bool = False,
|
| 14 |
+
save_all_recordings: bool = False,
|
| 15 |
+
include_frame_data: bool = True,
|
| 16 |
+
add_cookie: Optional[Callable[[Response, str], Response]] = None,
|
| 17 |
+
on_scorecard_close: Optional[Callable[[EnvironmentScorecard], None]] = None,
|
| 18 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 19 |
+
) -> Tuple[Flask, RestAPI]:
|
| 20 |
+
"""Create and configure the Flask application."""
|
| 21 |
+
app = Flask(__name__)
|
| 22 |
+
api = RestAPI(
|
| 23 |
+
arcade=arcade,
|
| 24 |
+
competition_mode=competition_mode,
|
| 25 |
+
save_all_recordings=save_all_recordings,
|
| 26 |
+
include_frame_data=include_frame_data,
|
| 27 |
+
add_cookie=add_cookie,
|
| 28 |
+
on_scorecard_close=on_scorecard_close,
|
| 29 |
+
renderer=renderer,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
app.api = api
|
| 33 |
+
|
| 34 |
+
# api routes
|
| 35 |
+
app.add_url_rule(
|
| 36 |
+
"/api/games",
|
| 37 |
+
methods=["GET"],
|
| 38 |
+
view_func=lambda: api.get_games(),
|
| 39 |
+
endpoint="games",
|
| 40 |
+
)
|
| 41 |
+
app.add_url_rule(
|
| 42 |
+
"/api/games/<game_id>",
|
| 43 |
+
methods=["GET"],
|
| 44 |
+
view_func=lambda game_id: api.get_game_info(game_id=game_id),
|
| 45 |
+
endpoint="game_by_id",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
app.add_url_rule(
|
| 49 |
+
"/api/scorecard/open",
|
| 50 |
+
methods=["POST"],
|
| 51 |
+
view_func=lambda: api.new_scorecard(),
|
| 52 |
+
endpoint="open_scorecard",
|
| 53 |
+
)
|
| 54 |
+
app.add_url_rule(
|
| 55 |
+
"/api/scorecard/close",
|
| 56 |
+
methods=["POST"],
|
| 57 |
+
view_func=lambda: api.close_scorecard(),
|
| 58 |
+
endpoint="close_scorecard",
|
| 59 |
+
)
|
| 60 |
+
app.add_url_rule(
|
| 61 |
+
"/api/scorecard/<card_id>",
|
| 62 |
+
methods=["GET"],
|
| 63 |
+
view_func=lambda card_id: api.get_scorecard(card_id=card_id),
|
| 64 |
+
endpoint="scorecard",
|
| 65 |
+
)
|
| 66 |
+
app.add_url_rule(
|
| 67 |
+
"/api/scorecard/<card_id>/<game_id>",
|
| 68 |
+
methods=["GET"],
|
| 69 |
+
view_func=lambda card_id, game_id: api.get_scorecard(
|
| 70 |
+
card_id=card_id, game_id=game_id
|
| 71 |
+
),
|
| 72 |
+
endpoint="scorecard_with_gameid",
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
app.add_url_rule(
|
| 76 |
+
"/api/cmd/RESET",
|
| 77 |
+
methods=["POST"],
|
| 78 |
+
view_func=lambda: api.cmd(action=GameAction.RESET),
|
| 79 |
+
endpoint="reset",
|
| 80 |
+
)
|
| 81 |
+
app.add_url_rule(
|
| 82 |
+
"/api/cmd/ACTION1",
|
| 83 |
+
methods=["POST"],
|
| 84 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION1),
|
| 85 |
+
endpoint="action1",
|
| 86 |
+
)
|
| 87 |
+
app.add_url_rule(
|
| 88 |
+
"/api/cmd/ACTION2",
|
| 89 |
+
methods=["POST"],
|
| 90 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION2),
|
| 91 |
+
endpoint="action2",
|
| 92 |
+
)
|
| 93 |
+
app.add_url_rule(
|
| 94 |
+
"/api/cmd/ACTION3",
|
| 95 |
+
methods=["POST"],
|
| 96 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION3),
|
| 97 |
+
endpoint="action3",
|
| 98 |
+
)
|
| 99 |
+
app.add_url_rule(
|
| 100 |
+
"/api/cmd/ACTION4",
|
| 101 |
+
methods=["POST"],
|
| 102 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION4),
|
| 103 |
+
endpoint="action4",
|
| 104 |
+
)
|
| 105 |
+
app.add_url_rule(
|
| 106 |
+
"/api/cmd/ACTION5",
|
| 107 |
+
methods=["POST"],
|
| 108 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION5),
|
| 109 |
+
endpoint="action5",
|
| 110 |
+
)
|
| 111 |
+
app.add_url_rule(
|
| 112 |
+
"/api/cmd/ACTION6",
|
| 113 |
+
methods=["POST"],
|
| 114 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION6),
|
| 115 |
+
endpoint="action6",
|
| 116 |
+
)
|
| 117 |
+
app.add_url_rule(
|
| 118 |
+
"/api/cmd/ACTION7",
|
| 119 |
+
methods=["POST"],
|
| 120 |
+
view_func=lambda: api.cmd(action=GameAction.ACTION7),
|
| 121 |
+
endpoint="action7",
|
| 122 |
+
)
|
| 123 |
+
app.add_url_rule(
|
| 124 |
+
"/api/healthcheck",
|
| 125 |
+
methods=["GET"],
|
| 126 |
+
view_func=lambda: ("okay", 200, {"Content-Type": "text/plain"}),
|
| 127 |
+
endpoint="healthcheck",
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
return app, api
|
arcprize__ARC-AGI/arc_agi/wrapper.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ezone
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Callable, Optional
|
| 8 |
+
|
| 9 |
+
from arcengine import FrameDataRaw, GameAction
|
| 10 |
+
|
| 11 |
+
from .models import EnvironmentInfo
|
| 12 |
+
from .scorecard import ScorecardManager
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class EnvironmentWrapper:
|
| 16 |
+
"""Base wrapper class for ARC-AGI-3 environments.
|
| 17 |
+
|
| 18 |
+
This class provides a common interface for interacting with environments,
|
| 19 |
+
whether they are local or remote. Subclasses should implement the `reset`
|
| 20 |
+
and `step` methods to provide environment-specific behavior.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
environment_info: EnvironmentInfo,
|
| 26 |
+
logger: logging.Logger,
|
| 27 |
+
scorecard_id: str,
|
| 28 |
+
save_recording: bool = False,
|
| 29 |
+
include_frame_data: bool = True,
|
| 30 |
+
recordings_dir: str = "recordings",
|
| 31 |
+
scorecard_manager: Optional[ScorecardManager] = None,
|
| 32 |
+
renderer: Optional[Callable[[int, FrameDataRaw], None]] = None,
|
| 33 |
+
) -> None:
|
| 34 |
+
"""Initialize the environment wrapper.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
environment_info: Information about the environment.
|
| 38 |
+
logger: Logger instance for logging.
|
| 39 |
+
scorecard_id: Optional scorecard ID for tracking runs.
|
| 40 |
+
save_recording: Whether to save recordings to JSONL file.
|
| 41 |
+
include_frame_data: Whether to include frame data in the recording file.
|
| 42 |
+
recordings_dir: Directory to save recordings.
|
| 43 |
+
scorecard_manager: Optional scorecard manager for tracking.
|
| 44 |
+
renderer: Optional callable that accepts FrameDataRaw and performs custom rendering.
|
| 45 |
+
"""
|
| 46 |
+
self.environment_info = environment_info
|
| 47 |
+
self.logger = logger
|
| 48 |
+
self.scorecard_id = scorecard_id
|
| 49 |
+
self.save_recording = save_recording
|
| 50 |
+
self.include_frame_data = include_frame_data
|
| 51 |
+
self.recordings_dir = recordings_dir
|
| 52 |
+
self.scorecard_manager = scorecard_manager
|
| 53 |
+
self.renderer = renderer
|
| 54 |
+
self._last_response: Optional[FrameDataRaw] = None
|
| 55 |
+
self._guid: Optional[str] = None
|
| 56 |
+
self._recording_filename: Optional[Path] = None
|
| 57 |
+
self._steps: int = 0
|
| 58 |
+
# Note: _setup_recording_file() should be called after guid is set
|
| 59 |
+
|
| 60 |
+
def reset(self) -> Optional[FrameDataRaw]:
|
| 61 |
+
"""Reset the environment.
|
| 62 |
+
|
| 63 |
+
This method should be overridden by subclasses to provide
|
| 64 |
+
environment-specific reset behavior.
|
| 65 |
+
"""
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
def step(
|
| 69 |
+
self,
|
| 70 |
+
action: GameAction,
|
| 71 |
+
data: Optional[dict[str, Any]] = None,
|
| 72 |
+
reasoning: Optional[dict[str, Any]] = None,
|
| 73 |
+
) -> Optional[FrameDataRaw]:
|
| 74 |
+
"""Perform a step in the environment.
|
| 75 |
+
|
| 76 |
+
This method should be overridden by subclasses to provide
|
| 77 |
+
environment-specific step behavior.
|
| 78 |
+
"""
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
def _setup_recording_file(self) -> None:
|
| 82 |
+
"""Set up the recording file path for JSONL output."""
|
| 83 |
+
if not self._guid:
|
| 84 |
+
self.logger.warning("Cannot setup recording file: guid not set")
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
# Create directory structure: {recordings_dir}/{scorecard_id}/
|
| 89 |
+
recording_dir = Path(self.recordings_dir) / self.scorecard_id
|
| 90 |
+
recording_dir.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
|
| 92 |
+
# Create filename: {game_id}-{guid}.jsonl
|
| 93 |
+
filename = f"{self.environment_info.game_id}-{self._guid}.jsonl"
|
| 94 |
+
self._recording_filename = recording_dir / filename
|
| 95 |
+
|
| 96 |
+
self.logger.info(f"Recording to {self._recording_filename}")
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
self.logger.error(
|
| 100 |
+
f"Failed to setup recording file: {e}",
|
| 101 |
+
exc_info=True,
|
| 102 |
+
)
|
| 103 |
+
self._recording_filename = None
|
| 104 |
+
|
| 105 |
+
def _record(self, data: dict[str, Any]) -> None:
|
| 106 |
+
"""Records an event to the file.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
data: Dictionary (JSON-serializable) to record.
|
| 110 |
+
"""
|
| 111 |
+
if not self.save_recording or not self._recording_filename:
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
event: dict[str, Any] = {}
|
| 116 |
+
event["timestamp"] = datetime.now(timezone.utc).isoformat()
|
| 117 |
+
event["data"] = data
|
| 118 |
+
|
| 119 |
+
with open(self._recording_filename, "a", encoding="utf-8") as f:
|
| 120 |
+
json.dump(event, f)
|
| 121 |
+
f.write("\n")
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
self.logger.error(
|
| 125 |
+
f"Failed to write to recording file: {e}",
|
| 126 |
+
exc_info=True,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
def _set_last_response(
|
| 130 |
+
self, resp: FrameDataRaw, reasoning: Optional[dict[str, Any]] = None
|
| 131 |
+
) -> None:
|
| 132 |
+
"""Set the last response from the environment.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
resp: The FrameDataRaw response from the environment.
|
| 136 |
+
reasoning: Optional reasoning dictionary to include in recording.
|
| 137 |
+
"""
|
| 138 |
+
self._last_response = resp
|
| 139 |
+
|
| 140 |
+
# Save to recording file if enabled
|
| 141 |
+
if self.save_recording:
|
| 142 |
+
# Convert FrameDataRaw to JSON-serializable dict
|
| 143 |
+
data: dict[str, Any] = {
|
| 144 |
+
"game_id": resp.game_id,
|
| 145 |
+
"state": resp.state.name
|
| 146 |
+
if hasattr(resp.state, "name")
|
| 147 |
+
else str(resp.state),
|
| 148 |
+
"levels_completed": resp.levels_completed,
|
| 149 |
+
"win_levels": resp.win_levels,
|
| 150 |
+
"action_input": {
|
| 151 |
+
"id": resp.action_input.id.name
|
| 152 |
+
if hasattr(resp.action_input.id, "name")
|
| 153 |
+
else str(resp.action_input.id),
|
| 154 |
+
"data": resp.action_input.data,
|
| 155 |
+
"reasoning": reasoning
|
| 156 |
+
if reasoning
|
| 157 |
+
else resp.action_input.reasoning,
|
| 158 |
+
}
|
| 159 |
+
if resp.action_input
|
| 160 |
+
else None,
|
| 161 |
+
"guid": resp.guid,
|
| 162 |
+
"full_reset": getattr(resp, "full_reset", False),
|
| 163 |
+
"available_actions": resp.available_actions,
|
| 164 |
+
}
|
| 165 |
+
if self.include_frame_data:
|
| 166 |
+
data["frame"] = [
|
| 167 |
+
frame_layer.tolist()
|
| 168 |
+
if hasattr(frame_layer, "tolist")
|
| 169 |
+
else frame_layer
|
| 170 |
+
for frame_layer in resp.frame
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
self._record(data)
|
| 174 |
+
|
| 175 |
+
# Render frames if renderer is set
|
| 176 |
+
self._steps += 1
|
| 177 |
+
if self.renderer is not None and resp.frame:
|
| 178 |
+
try:
|
| 179 |
+
self.renderer(self._steps, resp)
|
| 180 |
+
except Exception as e:
|
| 181 |
+
self.logger.error(
|
| 182 |
+
f"Failed to render frames: {e}",
|
| 183 |
+
exc_info=True,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Update scorecard if manager is available
|
| 187 |
+
if self.scorecard_manager and resp.guid and len(resp.frame) > 0:
|
| 188 |
+
try:
|
| 189 |
+
# Register guid with scorecard if not already registered
|
| 190 |
+
self.scorecard_manager.add_game(self.scorecard_id, resp.guid)
|
| 191 |
+
|
| 192 |
+
# Update scorecard
|
| 193 |
+
self.scorecard_manager.update_scorecard(
|
| 194 |
+
resp.guid, resp, resp.full_reset
|
| 195 |
+
)
|
| 196 |
+
except Exception as e:
|
| 197 |
+
self.logger.error(
|
| 198 |
+
f"Failed to update scorecard: {e}",
|
| 199 |
+
exc_info=True,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def observation_space(self) -> Optional[FrameDataRaw]:
|
| 204 |
+
"""Get the observation space (last response data).
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
The FrameDataRaw object from the last response, or None if no
|
| 208 |
+
response has been set yet.
|
| 209 |
+
"""
|
| 210 |
+
return self._last_response
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def action_space(self) -> list[GameAction]:
|
| 214 |
+
"""Get the action space (available actions).
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
A list of GameAction objects converted from the available_actions
|
| 218 |
+
in the last response. Returns an empty list if no response has
|
| 219 |
+
been set yet or if available_actions is empty.
|
| 220 |
+
"""
|
| 221 |
+
if self._last_response is None or not self._last_response.available_actions:
|
| 222 |
+
return []
|
| 223 |
+
|
| 224 |
+
return [
|
| 225 |
+
GameAction.from_id(action_id)
|
| 226 |
+
for action_id in self._last_response.available_actions
|
| 227 |
+
]
|
| 228 |
+
|
| 229 |
+
@property
|
| 230 |
+
def info(self) -> EnvironmentInfo:
|
| 231 |
+
"""Get the environment information.
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
The EnvironmentInfo object for this environment.
|
| 235 |
+
"""
|
| 236 |
+
return self.environment_info
|
arcprize__ARC-AGI/test_environment_files/game1/bt11.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from arcengine import (
|
| 2 |
+
ARCBaseGame,
|
| 3 |
+
Camera,
|
| 4 |
+
GameAction,
|
| 5 |
+
Level,
|
| 6 |
+
Sprite,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
# Create sprites dictionary with all sprite definitions
|
| 10 |
+
sprites = {
|
| 11 |
+
"bad": Sprite(
|
| 12 |
+
pixels=[
|
| 13 |
+
[8],
|
| 14 |
+
],
|
| 15 |
+
name="bad",
|
| 16 |
+
visible=True,
|
| 17 |
+
collidable=True,
|
| 18 |
+
),
|
| 19 |
+
"good": Sprite(
|
| 20 |
+
pixels=[
|
| 21 |
+
[14],
|
| 22 |
+
],
|
| 23 |
+
name="good",
|
| 24 |
+
visible=True,
|
| 25 |
+
collidable=True,
|
| 26 |
+
),
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# Create levels array with all level definitions
|
| 30 |
+
levels = [
|
| 31 |
+
# Level 1
|
| 32 |
+
Level(
|
| 33 |
+
sprites=[],
|
| 34 |
+
grid_size=(8, 8),
|
| 35 |
+
),
|
| 36 |
+
# Level 2
|
| 37 |
+
Level(
|
| 38 |
+
sprites=[],
|
| 39 |
+
grid_size=(16, 16),
|
| 40 |
+
),
|
| 41 |
+
# Level 3
|
| 42 |
+
Level(
|
| 43 |
+
sprites=[],
|
| 44 |
+
grid_size=(32, 32),
|
| 45 |
+
),
|
| 46 |
+
# Level 4
|
| 47 |
+
Level(
|
| 48 |
+
sprites=[],
|
| 49 |
+
grid_size=(40, 40),
|
| 50 |
+
),
|
| 51 |
+
# Level 5
|
| 52 |
+
Level(
|
| 53 |
+
sprites=[],
|
| 54 |
+
grid_size=(48, 48),
|
| 55 |
+
),
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
BACKGROUND_COLOR = 5
|
| 59 |
+
|
| 60 |
+
PADDING_COLOR = 3
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Bt11(ARCBaseGame):
|
| 64 |
+
_won: bool = True
|
| 65 |
+
_depth: int = 0
|
| 66 |
+
_position: int = 0
|
| 67 |
+
|
| 68 |
+
def __init__(self) -> None:
|
| 69 |
+
# Create camera
|
| 70 |
+
camera = Camera(
|
| 71 |
+
background=BACKGROUND_COLOR,
|
| 72 |
+
letter_box=PADDING_COLOR,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Initialize the base game
|
| 76 |
+
super().__init__(
|
| 77 |
+
game_id="bt11", levels=levels, camera=camera, available_actions=[3, 4]
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def step(self) -> None:
|
| 81 |
+
# Add here any logic you want
|
| 82 |
+
if self.action.id == GameAction.ACTION3: # Move Left
|
| 83 |
+
if self._depth > 0:
|
| 84 |
+
self._position -= 1
|
| 85 |
+
sprite_name = "good"
|
| 86 |
+
if not self._won:
|
| 87 |
+
sprite_name = "bad"
|
| 88 |
+
self.current_level.add_sprite(
|
| 89 |
+
sprites[sprite_name].clone().set_position(self._position, self._depth)
|
| 90 |
+
)
|
| 91 |
+
self._depth += 1
|
| 92 |
+
elif self.action.id == GameAction.ACTION4: # Move Right
|
| 93 |
+
self._position += 1
|
| 94 |
+
self.current_level.add_sprite(
|
| 95 |
+
sprites["bad"].clone().set_position(self._position, self._depth)
|
| 96 |
+
)
|
| 97 |
+
self._won = False
|
| 98 |
+
self._depth += 1
|
| 99 |
+
|
| 100 |
+
if self._depth >= self.camera.width // 2:
|
| 101 |
+
if self._won:
|
| 102 |
+
self.next_level()
|
| 103 |
+
else:
|
| 104 |
+
self.lose()
|
| 105 |
+
|
| 106 |
+
self.complete_action()
|
| 107 |
+
|
| 108 |
+
def on_set_level(self, level: Level) -> None:
|
| 109 |
+
self._won = True
|
| 110 |
+
self._depth = 0
|
| 111 |
+
self._position = self.camera.width // 2 - 1
|
arcprize__ARC-AGI/test_environment_files/game1/metadata.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"game_id": "bt11-fd9df0622a1a",
|
| 3 |
+
"title": "BT11",
|
| 4 |
+
"tags": ["tag1", "tag2"],
|
| 5 |
+
"private_tags": ["private_tag1", "private_tag2"],
|
| 6 |
+
"level_tags": [["level_tag1"], ["level_tag2"], ["level_tag3"], ["level_tag4"], ["level_tag5"]],
|
| 7 |
+
"baseline_actions": [4, 8, 16, 20, 24],
|
| 8 |
+
"date_downloaded": "2024-01-20T12:00:00Z"
|
| 9 |
+
}
|
arcprize__ARC-AGI/test_environment_files/game2/subdir/bt33.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from arcengine import (
|
| 2 |
+
ARCBaseGame,
|
| 3 |
+
Camera,
|
| 4 |
+
GameAction,
|
| 5 |
+
Level,
|
| 6 |
+
Sprite,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
# Create sprites dictionary with all sprite definitions
|
| 10 |
+
sprites = {
|
| 11 |
+
"bad": Sprite(
|
| 12 |
+
pixels=[
|
| 13 |
+
[8],
|
| 14 |
+
],
|
| 15 |
+
name="bad",
|
| 16 |
+
visible=True,
|
| 17 |
+
collidable=True,
|
| 18 |
+
scale=1,
|
| 19 |
+
),
|
| 20 |
+
"good": Sprite(
|
| 21 |
+
pixels=[
|
| 22 |
+
[14],
|
| 23 |
+
],
|
| 24 |
+
name="good",
|
| 25 |
+
visible=True,
|
| 26 |
+
collidable=True,
|
| 27 |
+
scale=1,
|
| 28 |
+
),
|
| 29 |
+
"left": Sprite(
|
| 30 |
+
pixels=[
|
| 31 |
+
[14, 14],
|
| 32 |
+
[14, -1],
|
| 33 |
+
],
|
| 34 |
+
name="left",
|
| 35 |
+
visible=True,
|
| 36 |
+
collidable=True,
|
| 37 |
+
tags=["sys_click"],
|
| 38 |
+
),
|
| 39 |
+
"right": Sprite(
|
| 40 |
+
pixels=[
|
| 41 |
+
[8, 8],
|
| 42 |
+
[-1, 8],
|
| 43 |
+
],
|
| 44 |
+
name="right",
|
| 45 |
+
visible=True,
|
| 46 |
+
collidable=True,
|
| 47 |
+
tags=["sys_click"],
|
| 48 |
+
),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# Create levels array with all level definitions
|
| 52 |
+
levels = [
|
| 53 |
+
# Level 1
|
| 54 |
+
Level(
|
| 55 |
+
sprites=[],
|
| 56 |
+
grid_size=(8, 8),
|
| 57 |
+
),
|
| 58 |
+
# Level 2
|
| 59 |
+
Level(
|
| 60 |
+
sprites=[],
|
| 61 |
+
grid_size=(16, 16),
|
| 62 |
+
),
|
| 63 |
+
# Level 3
|
| 64 |
+
Level(
|
| 65 |
+
sprites=[],
|
| 66 |
+
grid_size=(32, 32),
|
| 67 |
+
),
|
| 68 |
+
# Level 4
|
| 69 |
+
Level(
|
| 70 |
+
sprites=[],
|
| 71 |
+
grid_size=(40, 40),
|
| 72 |
+
),
|
| 73 |
+
# Level 5
|
| 74 |
+
Level(
|
| 75 |
+
sprites=[],
|
| 76 |
+
grid_size=(48, 48),
|
| 77 |
+
),
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
BACKGROUND_COLOR = 5
|
| 81 |
+
|
| 82 |
+
PADDING_COLOR = 3
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Bt33(ARCBaseGame):
|
| 86 |
+
_won: bool = True
|
| 87 |
+
_depth: int = 0
|
| 88 |
+
_placement: int = 0
|
| 89 |
+
|
| 90 |
+
def __init__(self) -> None:
|
| 91 |
+
# Create camera
|
| 92 |
+
camera = Camera(
|
| 93 |
+
background=BACKGROUND_COLOR,
|
| 94 |
+
letter_box=PADDING_COLOR,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# Initialize the base game
|
| 98 |
+
super().__init__(
|
| 99 |
+
game_id="bt33", levels=levels, camera=camera, available_actions=[6]
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def step(self) -> None:
|
| 103 |
+
# Add here any logic you want
|
| 104 |
+
if self.action.id == GameAction.ACTION6:
|
| 105 |
+
x = self.action.data.get("x", 0)
|
| 106 |
+
y = self.action.data.get("y", 0)
|
| 107 |
+
|
| 108 |
+
coords = self.camera.display_to_grid(x, y)
|
| 109 |
+
if coords:
|
| 110 |
+
sprite = self.current_level.get_sprite_at(coords[0], coords[1])
|
| 111 |
+
if sprite and sprite.name == "left":
|
| 112 |
+
if self._depth > 0:
|
| 113 |
+
self._placement -= 1
|
| 114 |
+
sprite_name = "good"
|
| 115 |
+
if not self._won:
|
| 116 |
+
sprite_name = "bad"
|
| 117 |
+
self.current_level.add_sprite(
|
| 118 |
+
sprites[sprite_name]
|
| 119 |
+
.clone()
|
| 120 |
+
.set_position(self._placement, self._depth)
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
self._depth += 1
|
| 124 |
+
elif sprite and sprite.name == "right":
|
| 125 |
+
self._placement += 1
|
| 126 |
+
self.current_level.add_sprite(
|
| 127 |
+
sprites["bad"]
|
| 128 |
+
.clone()
|
| 129 |
+
.set_position(self._placement, self._depth)
|
| 130 |
+
)
|
| 131 |
+
self._won = False
|
| 132 |
+
self._depth += 1
|
| 133 |
+
|
| 134 |
+
if self._depth >= self.camera.width // 2:
|
| 135 |
+
if self._won:
|
| 136 |
+
self.next_level()
|
| 137 |
+
else:
|
| 138 |
+
self.lose()
|
| 139 |
+
|
| 140 |
+
self.complete_action()
|
| 141 |
+
|
| 142 |
+
def on_set_level(self, level: Level) -> None:
|
| 143 |
+
self._depth = 0
|
| 144 |
+
self._placement = self.camera.width // 2 - 1
|
| 145 |
+
self._won = True
|
| 146 |
+
scale = self._current_level_index
|
| 147 |
+
if scale == 0:
|
| 148 |
+
self.current_level.add_sprite(
|
| 149 |
+
sprites["left"].clone().set_position(0, 0).set_scale(1)
|
| 150 |
+
)
|
| 151 |
+
self.current_level.add_sprite(
|
| 152 |
+
sprites["right"]
|
| 153 |
+
.clone()
|
| 154 |
+
.set_position(self.camera.width - 2, 0)
|
| 155 |
+
.set_scale(1)
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
self.current_level.add_sprite(
|
| 159 |
+
sprites["left"].clone().set_position(0, 0).set_scale(scale)
|
| 160 |
+
)
|
| 161 |
+
self.current_level.add_sprite(
|
| 162 |
+
sprites["right"]
|
| 163 |
+
.clone()
|
| 164 |
+
.set_position(self.camera.width - (2 * scale), 0)
|
| 165 |
+
.set_scale(scale)
|
| 166 |
+
)
|
arcprize__ARC-AGI/test_environment_files/game2/subdir/metadata.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"game_id": "bt33-a7c3f9d18b4e",
|
| 3 |
+
"title": "BT33",
|
| 4 |
+
"tags": ["tag3", "tag4"],
|
| 5 |
+
"private_tags": ["private_tag3", "private_tag4"],
|
| 6 |
+
"level_tags": [["level_tag3"], ["level_tag4"], ["level_tag5"]],
|
| 7 |
+
"baseline_actions": [10, 15, 20],
|
| 8 |
+
"class_name": "Bt33",
|
| 9 |
+
"date_downloaded": "2024-01-19T10:00:00Z"
|
| 10 |
+
}
|
arcprize__ARC-AGI/tests/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for ARC-AGI"""
|
| 2 |
+
|
| 3 |
+
from .test_base import (
|
| 4 |
+
TestARCAGI3BooleanParsing,
|
| 5 |
+
TestARCAGI3Defaults,
|
| 6 |
+
TestARCAGI3EdgeCases,
|
| 7 |
+
TestARCAGI3EnvironmentVariables,
|
| 8 |
+
)
|
| 9 |
+
from .test_listen_and_serve import TestListenAndServe
|
| 10 |
+
from .test_local_wrapper import TestLocalEnvironmentWrapper
|
| 11 |
+
from .test_models import TestEnvironmentInfo
|
| 12 |
+
from .test_scorecard import (
|
| 13 |
+
TestEnvironmentScore,
|
| 14 |
+
TestEnvironmentScorecard,
|
| 15 |
+
TestScorecard,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"TestARCAGI3Defaults",
|
| 20 |
+
"TestARCAGI3EnvironmentVariables",
|
| 21 |
+
"TestARCAGI3BooleanParsing",
|
| 22 |
+
"TestARCAGI3EdgeCases",
|
| 23 |
+
"TestEnvironmentInfo",
|
| 24 |
+
"TestLocalEnvironmentWrapper",
|
| 25 |
+
"TestEnvironmentScore",
|
| 26 |
+
"TestEnvironmentScorecard",
|
| 27 |
+
"TestScorecard",
|
| 28 |
+
"TestListenAndServe",
|
| 29 |
+
]
|
arcprize__ARC-AGI/tests/test_base.py
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the ARCAGI3 base class using unittest."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from unittest.mock import MagicMock, patch
|
| 8 |
+
|
| 9 |
+
import requests
|
| 10 |
+
|
| 11 |
+
# Create a mock dotenv module before any imports
|
| 12 |
+
_mock_dotenv = MagicMock()
|
| 13 |
+
_mock_dotenv.load_dotenv = MagicMock()
|
| 14 |
+
sys.modules["dotenv"] = _mock_dotenv
|
| 15 |
+
|
| 16 |
+
# Now import arcagi3 - the mock will be used instead of real dotenv
|
| 17 |
+
from arc_agi import Arcade, OperationMode # noqa: E402
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestARCAGI3Defaults(unittest.TestCase):
|
| 21 |
+
"""Test ARCAGI3 with default values."""
|
| 22 |
+
|
| 23 |
+
def setUp(self):
|
| 24 |
+
"""Clear environment variables before each test."""
|
| 25 |
+
self.env_vars_to_clear = [
|
| 26 |
+
"ARC_API_KEY",
|
| 27 |
+
"ARC_BASE_URL",
|
| 28 |
+
"OPERATION_MODE",
|
| 29 |
+
"OFFLINE_ONLY",
|
| 30 |
+
"ONLINE_ONLY",
|
| 31 |
+
"COMPETITION_MODE",
|
| 32 |
+
"LISTEN_BINDINGS",
|
| 33 |
+
"ENVIRONMENTS_DIR",
|
| 34 |
+
]
|
| 35 |
+
for var in self.env_vars_to_clear:
|
| 36 |
+
os.environ.pop(var, None)
|
| 37 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 38 |
+
|
| 39 |
+
def tearDown(self):
|
| 40 |
+
"""Clean up environment variables after each test."""
|
| 41 |
+
for var in self.env_vars_to_clear:
|
| 42 |
+
os.environ.pop(var, None)
|
| 43 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 44 |
+
|
| 45 |
+
def test_default_initialization(self):
|
| 46 |
+
"""Test that default values are used when no parameters are provided."""
|
| 47 |
+
client = Arcade()
|
| 48 |
+
|
| 49 |
+
self.assertEqual(client.arc_api_key, "test-key-123")
|
| 50 |
+
self.assertEqual(client.arc_base_url, "https://three.arcprize.org")
|
| 51 |
+
self.assertEqual(client.operation_mode, OperationMode.NORMAL)
|
| 52 |
+
self.assertEqual(client.environments_dir, "environment_files")
|
| 53 |
+
|
| 54 |
+
def test_constructor_parameters(self):
|
| 55 |
+
"""Test that constructor parameters are used correctly."""
|
| 56 |
+
client = Arcade(
|
| 57 |
+
arc_api_key="test-key-123",
|
| 58 |
+
arc_base_url="https://custom.example.com",
|
| 59 |
+
operation_mode=OperationMode.OFFLINE,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
self.assertEqual(client.arc_api_key, "test-key-123")
|
| 63 |
+
self.assertEqual(client.arc_base_url, "https://custom.example.com")
|
| 64 |
+
self.assertEqual(client.operation_mode, OperationMode.OFFLINE)
|
| 65 |
+
|
| 66 |
+
def test_default_logger_created(self):
|
| 67 |
+
"""Test that a default logger is created when None is passed."""
|
| 68 |
+
client = Arcade()
|
| 69 |
+
|
| 70 |
+
self.assertIsNotNone(client.logger)
|
| 71 |
+
self.assertIsInstance(client.logger, logging.Logger)
|
| 72 |
+
# Check that logger has a StreamHandler pointing to stdout
|
| 73 |
+
handlers = client.logger.handlers
|
| 74 |
+
self.assertGreater(len(handlers), 0)
|
| 75 |
+
stdout_handlers = [h for h in handlers if isinstance(h, logging.StreamHandler)]
|
| 76 |
+
self.assertGreater(len(stdout_handlers), 0)
|
| 77 |
+
|
| 78 |
+
def test_custom_logger_used(self):
|
| 79 |
+
"""Test that a custom logger is used when provided."""
|
| 80 |
+
custom_logger = logging.getLogger("custom_test_logger")
|
| 81 |
+
custom_logger.setLevel(logging.DEBUG)
|
| 82 |
+
client = Arcade(logger=custom_logger)
|
| 83 |
+
|
| 84 |
+
self.assertEqual(client.logger, custom_logger)
|
| 85 |
+
self.assertEqual(client.logger.name, "custom_test_logger")
|
| 86 |
+
self.assertEqual(client.logger.level, logging.DEBUG)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class TestARCAGI3EnvironmentVariables(unittest.TestCase):
|
| 90 |
+
"""Test ARCAGI3 with environment variable overrides."""
|
| 91 |
+
|
| 92 |
+
def setUp(self):
|
| 93 |
+
"""Clear environment variables before each test."""
|
| 94 |
+
self.env_vars_to_clear = [
|
| 95 |
+
"ARC_API_KEY",
|
| 96 |
+
"ARC_BASE_URL",
|
| 97 |
+
"OPERATION_MODE",
|
| 98 |
+
"OFFLINE_ONLY",
|
| 99 |
+
"ONLINE_ONLY",
|
| 100 |
+
"COMPETITION_MODE",
|
| 101 |
+
"LISTEN_BINDINGS",
|
| 102 |
+
"ENVIRONMENTS_DIR",
|
| 103 |
+
]
|
| 104 |
+
for var in self.env_vars_to_clear:
|
| 105 |
+
os.environ.pop(var, None)
|
| 106 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 107 |
+
|
| 108 |
+
def tearDown(self):
|
| 109 |
+
"""Clean up environment variables after each test."""
|
| 110 |
+
for var in self.env_vars_to_clear:
|
| 111 |
+
os.environ.pop(var, None)
|
| 112 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 113 |
+
|
| 114 |
+
def test_arc_api_key_from_env(self):
|
| 115 |
+
"""Test that constructor argument overrides environment variable."""
|
| 116 |
+
os.environ["ARC_API_KEY"] = "env-key-456"
|
| 117 |
+
client = Arcade(
|
| 118 |
+
operation_mode=OperationMode.OFFLINE, arc_api_key="constructor-key"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
self.assertEqual(client.arc_api_key, "constructor-key")
|
| 122 |
+
|
| 123 |
+
def test_arc_base_url_from_env(self):
|
| 124 |
+
"""Test that constructor argument overrides environment variable."""
|
| 125 |
+
os.environ["ARC_BASE_URL"] = "https://env.example.com"
|
| 126 |
+
client = Arcade(
|
| 127 |
+
operation_mode=OperationMode.OFFLINE,
|
| 128 |
+
arc_base_url="https://constructor.example.com",
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self.assertEqual(client.arc_base_url, "https://constructor.example.com")
|
| 132 |
+
|
| 133 |
+
def test_operation_mode_from_constructor_overrides_env(self):
|
| 134 |
+
"""Test that constructor argument overrides OPERATION_MODE env var."""
|
| 135 |
+
os.environ["OPERATION_MODE"] = "normal"
|
| 136 |
+
client = Arcade(operation_mode=OperationMode.OFFLINE)
|
| 137 |
+
|
| 138 |
+
self.assertEqual(client.operation_mode, OperationMode.OFFLINE)
|
| 139 |
+
|
| 140 |
+
def test_operation_mode_from_env_when_normal_passed(self):
|
| 141 |
+
"""Test that when NORMAL is passed (default), env var is still checked."""
|
| 142 |
+
os.environ["OPERATION_MODE"] = "offline"
|
| 143 |
+
client = Arcade(operation_mode=OperationMode.NORMAL)
|
| 144 |
+
|
| 145 |
+
self.assertEqual(client.operation_mode, OperationMode.OFFLINE)
|
| 146 |
+
|
| 147 |
+
def test_operation_mode_online_from_constructor_overrides_env(self):
|
| 148 |
+
"""Test that constructor ONLINE overrides env var."""
|
| 149 |
+
os.environ["OPERATION_MODE"] = "normal"
|
| 150 |
+
client = Arcade(operation_mode=OperationMode.ONLINE)
|
| 151 |
+
|
| 152 |
+
self.assertEqual(client.operation_mode, OperationMode.ONLINE)
|
| 153 |
+
|
| 154 |
+
def test_operation_mode_from_env_when_default(self):
|
| 155 |
+
"""Test that OPERATION_MODE env is used when default NORMAL is used."""
|
| 156 |
+
os.environ["OPERATION_MODE"] = "online"
|
| 157 |
+
client = Arcade()
|
| 158 |
+
|
| 159 |
+
self.assertEqual(client.operation_mode, OperationMode.ONLINE)
|
| 160 |
+
|
| 161 |
+
def test_operation_mode_competition(self):
|
| 162 |
+
"""Test that constructor ONLINE overrides env var."""
|
| 163 |
+
os.environ["OPERATION_MODE"] = "competition"
|
| 164 |
+
client = Arcade()
|
| 165 |
+
|
| 166 |
+
self.assertEqual(client.operation_mode, OperationMode.COMPETITION)
|
| 167 |
+
|
| 168 |
+
def test_operation_mode_competition_from_env_overrides_constructor(self):
|
| 169 |
+
"""Test that constructor ONLINE overrides env var."""
|
| 170 |
+
os.environ["OPERATION_MODE"] = "competition"
|
| 171 |
+
client = Arcade(operation_mode=OperationMode.ONLINE)
|
| 172 |
+
|
| 173 |
+
self.assertEqual(client.operation_mode, OperationMode.COMPETITION)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class TestARCAGI3BooleanParsing(unittest.TestCase):
|
| 177 |
+
"""Test boolean/enum parsing from environment variables."""
|
| 178 |
+
|
| 179 |
+
def setUp(self):
|
| 180 |
+
"""Clear environment variables before each test."""
|
| 181 |
+
self.env_vars_to_clear = [
|
| 182 |
+
"OPERATION_MODE",
|
| 183 |
+
"OFFLINE_ONLY",
|
| 184 |
+
"ONLINE_ONLY",
|
| 185 |
+
"COMPETITION_MODE",
|
| 186 |
+
]
|
| 187 |
+
for var in self.env_vars_to_clear:
|
| 188 |
+
os.environ.pop(var, None)
|
| 189 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 190 |
+
|
| 191 |
+
def tearDown(self):
|
| 192 |
+
"""Clean up environment variables after each test."""
|
| 193 |
+
for var in self.env_vars_to_clear:
|
| 194 |
+
os.environ.pop(var, None)
|
| 195 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 196 |
+
|
| 197 |
+
def test_operation_mode_env_normal_when_offline_false(self):
|
| 198 |
+
"""Test that OFFLINE_ONLY=false yields NORMAL when no other env set."""
|
| 199 |
+
os.environ["OFFLINE_ONLY"] = "false"
|
| 200 |
+
client = Arcade()
|
| 201 |
+
self.assertEqual(client.operation_mode, OperationMode.NORMAL)
|
| 202 |
+
|
| 203 |
+
def test_operation_mode_env_online_false_yields_normal(self):
|
| 204 |
+
"""Test that ONLINE_ONLY=false with no OPERATION_MODE yields NORMAL."""
|
| 205 |
+
os.environ["ONLINE_ONLY"] = "false"
|
| 206 |
+
client = Arcade()
|
| 207 |
+
self.assertEqual(client.operation_mode, OperationMode.NORMAL)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class TestARCAGI3EdgeCases(unittest.TestCase):
|
| 211 |
+
"""Test edge cases and special scenarios."""
|
| 212 |
+
|
| 213 |
+
def setUp(self):
|
| 214 |
+
"""Clear environment variables before each test."""
|
| 215 |
+
self.env_vars_to_clear = [
|
| 216 |
+
"ARC_API_KEY",
|
| 217 |
+
"ARC_BASE_URL",
|
| 218 |
+
"OPERATION_MODE",
|
| 219 |
+
"OFFLINE_ONLY",
|
| 220 |
+
"ONLINE_ONLY",
|
| 221 |
+
"COMPETITION_MODE",
|
| 222 |
+
"LISTEN_BINDINGS",
|
| 223 |
+
"ENVIRONMENTS_DIR",
|
| 224 |
+
]
|
| 225 |
+
for var in self.env_vars_to_clear:
|
| 226 |
+
os.environ.pop(var, None)
|
| 227 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 228 |
+
|
| 229 |
+
def tearDown(self):
|
| 230 |
+
"""Clean up environment variables after each test."""
|
| 231 |
+
for var in self.env_vars_to_clear:
|
| 232 |
+
os.environ.pop(var, None)
|
| 233 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 234 |
+
|
| 235 |
+
def test_empty_string_api_key(self):
|
| 236 |
+
"""Test that empty string API key is handled correctly."""
|
| 237 |
+
client = Arcade(arc_api_key="")
|
| 238 |
+
|
| 239 |
+
self.assertEqual(client.arc_api_key, "test-key-123")
|
| 240 |
+
|
| 241 |
+
def test_constructor_overrides_when_env_not_set(self):
|
| 242 |
+
"""Test that constructor values are used when env vars are not set."""
|
| 243 |
+
client = Arcade(
|
| 244 |
+
arc_api_key="constructor-key",
|
| 245 |
+
arc_base_url="https://constructor.url",
|
| 246 |
+
operation_mode=OperationMode.ONLINE,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
self.assertEqual(client.arc_api_key, "constructor-key")
|
| 250 |
+
self.assertEqual(client.arc_base_url, "https://constructor.url")
|
| 251 |
+
self.assertEqual(client.operation_mode, OperationMode.ONLINE)
|
| 252 |
+
|
| 253 |
+
def test_all_env_vars_set(self):
|
| 254 |
+
"""Test that all environment variables can be set simultaneously."""
|
| 255 |
+
os.environ["ARC_API_KEY"] = "env-api-key"
|
| 256 |
+
os.environ["ARC_BASE_URL"] = "https://env.url"
|
| 257 |
+
os.environ["OPERATION_MODE"] = "online"
|
| 258 |
+
|
| 259 |
+
client = Arcade()
|
| 260 |
+
|
| 261 |
+
self.assertEqual(client.arc_api_key, "env-api-key")
|
| 262 |
+
self.assertEqual(client.arc_base_url, "https://env.url")
|
| 263 |
+
self.assertEqual(client.operation_mode, OperationMode.ONLINE)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class TestARCAGI3EnvironmentsDirScanning(unittest.TestCase):
|
| 267 |
+
"""Test environments_dir scanning functionality."""
|
| 268 |
+
|
| 269 |
+
def setUp(self):
|
| 270 |
+
"""Clear environment variables before each test."""
|
| 271 |
+
self.env_vars_to_clear = ["ENVIRONMENTS_DIR"]
|
| 272 |
+
for var in self.env_vars_to_clear:
|
| 273 |
+
os.environ.pop(var, None)
|
| 274 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 275 |
+
|
| 276 |
+
def tearDown(self):
|
| 277 |
+
"""Clean up environment variables after each test."""
|
| 278 |
+
for var in self.env_vars_to_clear:
|
| 279 |
+
os.environ.pop(var, None)
|
| 280 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 281 |
+
|
| 282 |
+
def test_environments_dir_scanning(self):
|
| 283 |
+
"""Test that environments_dir scanning finds metadata.json files."""
|
| 284 |
+
import tempfile
|
| 285 |
+
from pathlib import Path
|
| 286 |
+
|
| 287 |
+
# Create a temporary directory structure
|
| 288 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 289 |
+
environments_dir = Path(tmpdir) / "environments"
|
| 290 |
+
environments_dir.mkdir()
|
| 291 |
+
|
| 292 |
+
# Create environment1 with metadata.json
|
| 293 |
+
env1_dir = environments_dir / "env1"
|
| 294 |
+
env1_dir.mkdir()
|
| 295 |
+
metadata1 = env1_dir / "metadata.json"
|
| 296 |
+
metadata1.write_text(
|
| 297 |
+
'{"game_id": "test1", "title": "Test1", "tags": ["tag1"], "baseline_actions": [10]}',
|
| 298 |
+
encoding="utf-8",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# Create environment2 in subdirectory
|
| 302 |
+
env2_dir = environments_dir / "env2" / "subdir"
|
| 303 |
+
env2_dir.mkdir(parents=True)
|
| 304 |
+
metadata2 = env2_dir / "metadata.json"
|
| 305 |
+
metadata2.write_text(
|
| 306 |
+
'{"game_id": "test2", "title": "Test2", "tags": ["tag2"], "baseline_actions": [20]}',
|
| 307 |
+
encoding="utf-8",
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# Create invalid metadata file (should be skipped)
|
| 311 |
+
env3_dir = environments_dir / "env3"
|
| 312 |
+
env3_dir.mkdir()
|
| 313 |
+
metadata3 = env3_dir / "metadata.json"
|
| 314 |
+
metadata3.write_text("invalid json", encoding="utf-8")
|
| 315 |
+
|
| 316 |
+
# Initialize ARCAGI3 with environments_dir
|
| 317 |
+
client = Arcade(environments_dir=str(environments_dir))
|
| 318 |
+
|
| 319 |
+
# Should have found 2 valid environments
|
| 320 |
+
self.assertEqual(len(client.available_environments), 2)
|
| 321 |
+
# Check that both environments were found (order may vary)
|
| 322 |
+
environment_ids = {env.game_id for env in client.available_environments}
|
| 323 |
+
self.assertEqual(environment_ids, {"test1", "test2"})
|
| 324 |
+
|
| 325 |
+
def test_environments_dir_none(self):
|
| 326 |
+
"""Test that environments_dir can be explicitly set to None."""
|
| 327 |
+
client = Arcade(environments_dir=None)
|
| 328 |
+
|
| 329 |
+
self.assertIsNone(client.environments_dir)
|
| 330 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 331 |
+
|
| 332 |
+
def test_environments_dir_default(self):
|
| 333 |
+
"""Test that environments_dir defaults to 'environment_files'."""
|
| 334 |
+
client = Arcade()
|
| 335 |
+
|
| 336 |
+
self.assertEqual(client.environments_dir, "environment_files")
|
| 337 |
+
|
| 338 |
+
def test_environments_dir_nonexistent(self):
|
| 339 |
+
"""Test that non-existent environments_dir is handled gracefully."""
|
| 340 |
+
client = Arcade(environments_dir="/nonexistent/path")
|
| 341 |
+
|
| 342 |
+
self.assertEqual(client.environments_dir, "/nonexistent/path")
|
| 343 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 344 |
+
|
| 345 |
+
def test_environments_dir_from_env(self):
|
| 346 |
+
"""Test that environments_dir can be set from environment variable when constructor uses default."""
|
| 347 |
+
import tempfile
|
| 348 |
+
from pathlib import Path
|
| 349 |
+
|
| 350 |
+
# Create a temporary directory with metadata
|
| 351 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 352 |
+
environments_dir = Path(tmpdir) / "environments"
|
| 353 |
+
environments_dir.mkdir()
|
| 354 |
+
env_dir = environments_dir / "env1"
|
| 355 |
+
env_dir.mkdir()
|
| 356 |
+
metadata = env_dir / "metadata.json"
|
| 357 |
+
metadata.write_text(
|
| 358 |
+
'{"game_id": "env-test", "title": "EnvTest", "tags": ["tag1"], "baseline_actions": [10]}',
|
| 359 |
+
encoding="utf-8",
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
os.environ["ENVIRONMENTS_DIR"] = str(environments_dir)
|
| 363 |
+
try:
|
| 364 |
+
# No constructor arg, should use env var
|
| 365 |
+
client = Arcade()
|
| 366 |
+
|
| 367 |
+
self.assertEqual(client.environments_dir, str(environments_dir))
|
| 368 |
+
self.assertEqual(len(client.available_environments), 1)
|
| 369 |
+
self.assertEqual(client.available_environments[0].game_id, "env-test")
|
| 370 |
+
finally:
|
| 371 |
+
os.environ.pop("ENVIRONMENTS_DIR", None)
|
| 372 |
+
|
| 373 |
+
def test_environments_dir_empty_directory(self):
|
| 374 |
+
"""Test that empty environments_dir results in no environments."""
|
| 375 |
+
import tempfile
|
| 376 |
+
from pathlib import Path
|
| 377 |
+
|
| 378 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 379 |
+
environments_dir = Path(tmpdir) / "environments"
|
| 380 |
+
environments_dir.mkdir()
|
| 381 |
+
|
| 382 |
+
client = Arcade(environments_dir=str(environments_dir))
|
| 383 |
+
|
| 384 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 385 |
+
|
| 386 |
+
def test_environments_dir_with_test_files(self):
|
| 387 |
+
"""Test scanning the test_environment_files directory."""
|
| 388 |
+
from pathlib import Path
|
| 389 |
+
|
| 390 |
+
test_environments_dir = Path(__file__).parent.parent / "test_environment_files"
|
| 391 |
+
if test_environments_dir.exists():
|
| 392 |
+
client = Arcade(environments_dir=str(test_environments_dir))
|
| 393 |
+
|
| 394 |
+
# Should find at least 2 metadata.json files
|
| 395 |
+
self.assertGreaterEqual(len(client.available_environments), 2)
|
| 396 |
+
# Check that the expected environments are found
|
| 397 |
+
environment_ids = {env.game_id for env in client.available_environments}
|
| 398 |
+
self.assertIn("bt11-fd9df0622a1a", environment_ids)
|
| 399 |
+
self.assertIn("tg62-12345678", environment_ids)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class TestARCAGI3APIFetching(unittest.TestCase):
|
| 403 |
+
"""Test API fetching functionality."""
|
| 404 |
+
|
| 405 |
+
def setUp(self):
|
| 406 |
+
"""Clear environment variables before each test."""
|
| 407 |
+
self.env_vars_to_clear = [
|
| 408 |
+
"ENVIRONMENTS_DIR",
|
| 409 |
+
"OPERATION_MODE",
|
| 410 |
+
"OFFLINE_ONLY",
|
| 411 |
+
"ONLINE_ONLY",
|
| 412 |
+
"ARC_API_KEY",
|
| 413 |
+
]
|
| 414 |
+
for var in self.env_vars_to_clear:
|
| 415 |
+
os.environ.pop(var, None)
|
| 416 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 417 |
+
|
| 418 |
+
def tearDown(self):
|
| 419 |
+
"""Clean up environment variables after each test."""
|
| 420 |
+
for var in self.env_vars_to_clear:
|
| 421 |
+
os.environ.pop(var, None)
|
| 422 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 423 |
+
|
| 424 |
+
@patch("arc_agi.base.requests.get")
|
| 425 |
+
def test_api_fetch_when_not_offline(self, mock_get):
|
| 426 |
+
"""Test that API is called when not in OFFLINE mode."""
|
| 427 |
+
# Mock API response
|
| 428 |
+
mock_response = MagicMock()
|
| 429 |
+
mock_response.json.return_value = [
|
| 430 |
+
{
|
| 431 |
+
"game_id": "api-game-1",
|
| 432 |
+
"title": "API Game 1",
|
| 433 |
+
"tags": ["api-tag"],
|
| 434 |
+
"baseline_actions": [10, 20],
|
| 435 |
+
}
|
| 436 |
+
]
|
| 437 |
+
mock_response.raise_for_status = MagicMock()
|
| 438 |
+
mock_get.return_value = mock_response
|
| 439 |
+
|
| 440 |
+
client = Arcade(
|
| 441 |
+
arc_api_key="test-api-key",
|
| 442 |
+
operation_mode=OperationMode.NORMAL,
|
| 443 |
+
environments_dir=None, # No local scanning
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
# Verify API was called
|
| 447 |
+
mock_get.assert_called_once()
|
| 448 |
+
call_args = mock_get.call_args
|
| 449 |
+
self.assertEqual(call_args[0][0], "https://three.arcprize.org/api/games")
|
| 450 |
+
self.assertEqual(call_args[1]["headers"]["X-API-Key"], "test-api-key")
|
| 451 |
+
|
| 452 |
+
# Verify environment was added
|
| 453 |
+
self.assertEqual(len(client.available_environments), 1)
|
| 454 |
+
self.assertEqual(client.available_environments[0].game_id, "api-game-1")
|
| 455 |
+
|
| 456 |
+
@patch("arc_agi.base.requests.get")
|
| 457 |
+
def test_api_not_fetched_when_offline(self, mock_get):
|
| 458 |
+
"""Test that API is not called when in OFFLINE mode."""
|
| 459 |
+
_ = Arcade(
|
| 460 |
+
arc_api_key="test-api-key",
|
| 461 |
+
operation_mode=OperationMode.OFFLINE,
|
| 462 |
+
environments_dir=None,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# Verify API was not called
|
| 466 |
+
mock_get.assert_not_called()
|
| 467 |
+
|
| 468 |
+
@patch("arc_agi.base.requests.get")
|
| 469 |
+
def test_api_merge_with_local_environments(self, mock_get):
|
| 470 |
+
"""Test that API environments are merged with local environments."""
|
| 471 |
+
import tempfile
|
| 472 |
+
from pathlib import Path
|
| 473 |
+
|
| 474 |
+
# Mock API response
|
| 475 |
+
mock_response = MagicMock()
|
| 476 |
+
mock_response.json.return_value = [
|
| 477 |
+
{
|
| 478 |
+
"game_id": "api-game-1",
|
| 479 |
+
"title": "API Game 1",
|
| 480 |
+
"tags": ["api-tag"],
|
| 481 |
+
"baseline_actions": [10],
|
| 482 |
+
}
|
| 483 |
+
]
|
| 484 |
+
mock_response.raise_for_status = MagicMock()
|
| 485 |
+
mock_get.return_value = mock_response
|
| 486 |
+
|
| 487 |
+
# Create local environment with different game_id
|
| 488 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 489 |
+
environments_dir = Path(tmpdir) / "environments"
|
| 490 |
+
environments_dir.mkdir()
|
| 491 |
+
env_dir = environments_dir / "env1"
|
| 492 |
+
env_dir.mkdir()
|
| 493 |
+
metadata = env_dir / "metadata.json"
|
| 494 |
+
metadata.write_text(
|
| 495 |
+
'{"game_id": "local-game-1", "title": "Local Game 1", "tags": ["local-tag"], "baseline_actions": [5]}',
|
| 496 |
+
encoding="utf-8",
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
client = Arcade(
|
| 500 |
+
arc_api_key="test-api-key",
|
| 501 |
+
operation_mode=OperationMode.NORMAL,
|
| 502 |
+
environments_dir=str(environments_dir),
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
# Should have both local and API environments
|
| 506 |
+
self.assertEqual(len(client.available_environments), 2)
|
| 507 |
+
game_ids = {env.game_id for env in client.available_environments}
|
| 508 |
+
self.assertEqual(game_ids, {"local-game-1", "api-game-1"})
|
| 509 |
+
|
| 510 |
+
@patch("arc_agi.base.requests.get")
|
| 511 |
+
def test_api_removes_duplicate_game_ids(self, mock_get):
|
| 512 |
+
"""Test that duplicate game_ids from API are not added if they exist locally."""
|
| 513 |
+
import tempfile
|
| 514 |
+
from pathlib import Path
|
| 515 |
+
|
| 516 |
+
# Mock API response with same game_id as local
|
| 517 |
+
mock_response = MagicMock()
|
| 518 |
+
mock_response.json.return_value = [
|
| 519 |
+
{
|
| 520 |
+
"game_id": "duplicate-game",
|
| 521 |
+
"title": "API Version",
|
| 522 |
+
"tags": ["api-tag"],
|
| 523 |
+
"baseline_actions": [10],
|
| 524 |
+
}
|
| 525 |
+
]
|
| 526 |
+
mock_response.raise_for_status = MagicMock()
|
| 527 |
+
mock_get.return_value = mock_response
|
| 528 |
+
|
| 529 |
+
# Create local environment with same game_id
|
| 530 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 531 |
+
environments_dir = Path(tmpdir) / "environments"
|
| 532 |
+
environments_dir.mkdir()
|
| 533 |
+
env_dir = environments_dir / "env1"
|
| 534 |
+
env_dir.mkdir()
|
| 535 |
+
metadata = env_dir / "metadata.json"
|
| 536 |
+
metadata.write_text(
|
| 537 |
+
'{"game_id": "duplicate-game", "title": "Local Version", "tags": ["local-tag"], "baseline_actions": [5]}',
|
| 538 |
+
encoding="utf-8",
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
client = Arcade(
|
| 542 |
+
arc_api_key="test-api-key",
|
| 543 |
+
operation_mode=OperationMode.NORMAL,
|
| 544 |
+
environments_dir=str(environments_dir),
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
# Should only have one environment (local version, API duplicate ignored)
|
| 548 |
+
self.assertEqual(len(client.available_environments), 1)
|
| 549 |
+
self.assertEqual(client.available_environments[0].game_id, "duplicate-game")
|
| 550 |
+
# Should be the local version (scanned first)
|
| 551 |
+
self.assertEqual(client.available_environments[0].title, "Local Version")
|
| 552 |
+
|
| 553 |
+
@patch("arc_agi.base.requests.get")
|
| 554 |
+
def test_api_no_key_skips_fetch(self, mock_get):
|
| 555 |
+
"""Test that API is not called when no API key is provided."""
|
| 556 |
+
_ = Arcade(
|
| 557 |
+
arc_api_key="", # Empty API key
|
| 558 |
+
operation_mode=OperationMode.NORMAL,
|
| 559 |
+
environments_dir=None,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
# Verify API was not called
|
| 563 |
+
mock_get.assert_not_called()
|
| 564 |
+
|
| 565 |
+
@patch("arc_agi.base.requests.get")
|
| 566 |
+
def test_api_error_handled_gracefully(self, mock_get):
|
| 567 |
+
"""Test that API errors are handled gracefully."""
|
| 568 |
+
# Mock API error
|
| 569 |
+
mock_get.side_effect = requests.exceptions.RequestException("Network error")
|
| 570 |
+
|
| 571 |
+
client = Arcade(
|
| 572 |
+
arc_api_key="test-api-key",
|
| 573 |
+
operation_mode=OperationMode.NORMAL,
|
| 574 |
+
environments_dir=None,
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
# Should not raise exception, just have no environments
|
| 578 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 579 |
+
|
| 580 |
+
@patch("arc_agi.base.requests.get")
|
| 581 |
+
def test_api_http_error_handled_gracefully(self, mock_get):
|
| 582 |
+
"""Test that HTTP errors are handled gracefully."""
|
| 583 |
+
# Mock HTTP error response
|
| 584 |
+
mock_response = MagicMock()
|
| 585 |
+
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError(
|
| 586 |
+
"404 Not Found"
|
| 587 |
+
)
|
| 588 |
+
mock_get.return_value = mock_response
|
| 589 |
+
|
| 590 |
+
client = Arcade(
|
| 591 |
+
arc_api_key="test-api-key",
|
| 592 |
+
operation_mode=OperationMode.NORMAL,
|
| 593 |
+
environments_dir=None,
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
# Should not raise exception, just have no environments
|
| 597 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 598 |
+
|
| 599 |
+
@patch("arc_agi.base.requests.get")
|
| 600 |
+
def test_api_invalid_response_handled_gracefully(self, mock_get):
|
| 601 |
+
"""Test that invalid API responses are handled gracefully."""
|
| 602 |
+
# Mock invalid JSON response
|
| 603 |
+
mock_response = MagicMock()
|
| 604 |
+
mock_response.json.side_effect = ValueError("Invalid JSON")
|
| 605 |
+
mock_response.raise_for_status = MagicMock()
|
| 606 |
+
mock_get.return_value = mock_response
|
| 607 |
+
|
| 608 |
+
client = Arcade(
|
| 609 |
+
arc_api_key="test-api-key",
|
| 610 |
+
operation_mode=OperationMode.NORMAL,
|
| 611 |
+
environments_dir=None,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
# Should not raise exception, just have no environments
|
| 615 |
+
self.assertEqual(len(client.available_environments), 0)
|
| 616 |
+
|
| 617 |
+
@patch("arc_agi.base.requests.get")
|
| 618 |
+
def test_api_custom_base_url(self, mock_get):
|
| 619 |
+
"""Test that API uses custom base_url."""
|
| 620 |
+
# Mock API response
|
| 621 |
+
mock_response = MagicMock()
|
| 622 |
+
mock_response.json.return_value = []
|
| 623 |
+
mock_response.raise_for_status = MagicMock()
|
| 624 |
+
mock_get.return_value = mock_response
|
| 625 |
+
|
| 626 |
+
_ = Arcade(
|
| 627 |
+
arc_api_key="test-api-key",
|
| 628 |
+
arc_base_url="https://custom.example.com",
|
| 629 |
+
operation_mode=OperationMode.NORMAL,
|
| 630 |
+
environments_dir=None,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
# Verify API was called with custom URL
|
| 634 |
+
call_args = mock_get.call_args
|
| 635 |
+
self.assertEqual(call_args[0][0], "https://custom.example.com/api/games")
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
if __name__ == "__main__":
|
| 639 |
+
unittest.main()
|
arcprize__ARC-AGI/tests/test_listen_and_serve.py
ADDED
|
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for listen_and_serve: offline server with online client."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import socket
|
| 6 |
+
import sys
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
import unittest
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from unittest.mock import MagicMock
|
| 12 |
+
|
| 13 |
+
from requests.exceptions import HTTPError
|
| 14 |
+
|
| 15 |
+
_mock_dotenv = MagicMock()
|
| 16 |
+
_mock_dotenv.load_dotenv = MagicMock()
|
| 17 |
+
sys.modules["dotenv"] = _mock_dotenv
|
| 18 |
+
|
| 19 |
+
from arcengine import GameAction # noqa: E402
|
| 20 |
+
|
| 21 |
+
from arc_agi import ( # noqa: E402
|
| 22 |
+
Arcade,
|
| 23 |
+
OperationMode,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _find_free_port() -> int:
|
| 28 |
+
"""Bind to port 0 to get an OS-assigned free port."""
|
| 29 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 30 |
+
s.bind(("127.0.0.1", 0))
|
| 31 |
+
return s.getsockname()[1]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestListenAndServe(unittest.TestCase):
|
| 35 |
+
"""Test listen_and_serve with offline server and online client."""
|
| 36 |
+
|
| 37 |
+
def setUp(self) -> None:
|
| 38 |
+
"""Set up test fixtures."""
|
| 39 |
+
self.env_vars_to_clear = [
|
| 40 |
+
"ARC_API_KEY",
|
| 41 |
+
"ARC_BASE_URL",
|
| 42 |
+
"OFFLINE_ONLY",
|
| 43 |
+
"ONLINE_ONLY",
|
| 44 |
+
"COMPETITION_MODE",
|
| 45 |
+
"LISTEN_BINDINGS",
|
| 46 |
+
"ENVIRONMENTS_DIR",
|
| 47 |
+
]
|
| 48 |
+
for var in self.env_vars_to_clear:
|
| 49 |
+
os.environ.pop(var, None)
|
| 50 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 51 |
+
|
| 52 |
+
self.logger = logging.getLogger("test")
|
| 53 |
+
self.logger.setLevel(logging.INFO)
|
| 54 |
+
|
| 55 |
+
test_dir = Path(__file__).parent.parent / "test_environment_files"
|
| 56 |
+
self.environments_dir = str(test_dir)
|
| 57 |
+
|
| 58 |
+
def tearDown(self) -> None:
|
| 59 |
+
"""Clean up after tests."""
|
| 60 |
+
for var in self.env_vars_to_clear:
|
| 61 |
+
os.environ.pop(var, None)
|
| 62 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 63 |
+
|
| 64 |
+
def test_offline_server_online_client_four_action3_levels_completed_one(
|
| 65 |
+
self,
|
| 66 |
+
) -> None:
|
| 67 |
+
"""Spin up Arcade in offline mode with test_environment_files, serve backend,
|
| 68 |
+
then use online client to play bt11: four ACTION3 steps yield levels_completed=1."""
|
| 69 |
+
if not Path(self.environments_dir).exists():
|
| 70 |
+
self.skipTest("test_environment_files not found")
|
| 71 |
+
|
| 72 |
+
port = _find_free_port()
|
| 73 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 74 |
+
|
| 75 |
+
# Server: offline Arcade with test_environment_files
|
| 76 |
+
server_arc = Arcade(
|
| 77 |
+
operation_mode=OperationMode.OFFLINE,
|
| 78 |
+
environments_dir=self.environments_dir,
|
| 79 |
+
arc_api_key="test-key-123",
|
| 80 |
+
logger=self.logger,
|
| 81 |
+
)
|
| 82 |
+
self.assertGreater(
|
| 83 |
+
len(server_arc.available_environments),
|
| 84 |
+
0,
|
| 85 |
+
"Server should have at least one environment from test_environment_files",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Run server in background thread (blocking listen_and_serve)
|
| 89 |
+
server_error: list[Exception] = []
|
| 90 |
+
|
| 91 |
+
def run_server() -> None:
|
| 92 |
+
try:
|
| 93 |
+
server_arc.listen_and_serve(
|
| 94 |
+
host="127.0.0.1",
|
| 95 |
+
port=port,
|
| 96 |
+
use_reloader=False,
|
| 97 |
+
)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
server_error.append(e)
|
| 100 |
+
|
| 101 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 102 |
+
server_thread.start()
|
| 103 |
+
|
| 104 |
+
# Give server time to bind
|
| 105 |
+
time.sleep(1.5)
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
# Client: online Arcade pointing at localhost
|
| 109 |
+
client_arc = Arcade(
|
| 110 |
+
operation_mode=OperationMode.ONLINE,
|
| 111 |
+
arc_base_url=base_url,
|
| 112 |
+
arc_api_key="test-key-123",
|
| 113 |
+
logger=self.logger,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Open scorecard on server (POST /api/scorecard/open)
|
| 117 |
+
card_id = client_arc.create_scorecard()
|
| 118 |
+
self.assertIsNotNone(card_id, "Should get card_id from server")
|
| 119 |
+
|
| 120 |
+
# Make remote wrapper for bt11
|
| 121 |
+
env = client_arc.make(game_id="bt11", scorecard_id=card_id)
|
| 122 |
+
self.assertIsNotNone(env, "Should create remote environment")
|
| 123 |
+
|
| 124 |
+
# get starting frame and play four ACTION3 steps
|
| 125 |
+
start_frame = env.observation_space
|
| 126 |
+
self.assertIsNotNone(start_frame, "Reset should return frame")
|
| 127 |
+
initial_level = start_frame.levels_completed
|
| 128 |
+
|
| 129 |
+
for i in range(4):
|
| 130 |
+
frame = env.step(GameAction.ACTION3)
|
| 131 |
+
self.assertIsNotNone(frame, f"Step {i + 1} should return frame")
|
| 132 |
+
|
| 133 |
+
final_frame = env.observation_space
|
| 134 |
+
self.assertIsNotNone(final_frame)
|
| 135 |
+
self.assertEqual(
|
| 136 |
+
final_frame.levels_completed,
|
| 137 |
+
1,
|
| 138 |
+
"Four ACTION3 steps should result in levels_completed=1",
|
| 139 |
+
)
|
| 140 |
+
self.assertGreater(
|
| 141 |
+
final_frame.levels_completed,
|
| 142 |
+
initial_level,
|
| 143 |
+
"levels_completed should have increased",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
result = client_arc.close_scorecard(scorecard_id=card_id)
|
| 147 |
+
self.assertIsNotNone(result, "Close should return scorecard")
|
| 148 |
+
self.assertIs(
|
| 149 |
+
result.competition_mode,
|
| 150 |
+
False,
|
| 151 |
+
"Scorecard should not have a competition_mode",
|
| 152 |
+
)
|
| 153 |
+
finally:
|
| 154 |
+
if server_error:
|
| 155 |
+
raise server_error[0]
|
| 156 |
+
|
| 157 |
+
def test_competition_mode_on_client_can_open_multiple_scorecards(
|
| 158 |
+
self,
|
| 159 |
+
) -> None:
|
| 160 |
+
if not Path(self.environments_dir).exists():
|
| 161 |
+
self.skipTest("test_environment_files not found")
|
| 162 |
+
|
| 163 |
+
port = _find_free_port()
|
| 164 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 165 |
+
|
| 166 |
+
server_arc = Arcade(
|
| 167 |
+
operation_mode=OperationMode.OFFLINE,
|
| 168 |
+
environments_dir=self.environments_dir,
|
| 169 |
+
arc_api_key="test-key-123",
|
| 170 |
+
logger=self.logger,
|
| 171 |
+
)
|
| 172 |
+
self.assertGreater(
|
| 173 |
+
len(server_arc.available_environments),
|
| 174 |
+
0,
|
| 175 |
+
"Server should have at least one environment from test_environment_files",
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
server_error: list[Exception] = []
|
| 179 |
+
|
| 180 |
+
def run_server() -> None:
|
| 181 |
+
try:
|
| 182 |
+
server_arc.listen_and_serve(
|
| 183 |
+
host="127.0.0.1",
|
| 184 |
+
port=port,
|
| 185 |
+
use_reloader=False,
|
| 186 |
+
)
|
| 187 |
+
except Exception as e:
|
| 188 |
+
server_error.append(e)
|
| 189 |
+
|
| 190 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 191 |
+
server_thread.start()
|
| 192 |
+
|
| 193 |
+
time.sleep(1.5)
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
client_arc = Arcade(
|
| 197 |
+
operation_mode=OperationMode.COMPETITION,
|
| 198 |
+
arc_base_url=base_url,
|
| 199 |
+
arc_api_key="test-key-123",
|
| 200 |
+
logger=self.logger,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
card_id_1 = client_arc.create_scorecard()
|
| 204 |
+
self.assertIsNotNone(card_id_1, "Should get card_id from server")
|
| 205 |
+
|
| 206 |
+
card_id_2 = client_arc.create_scorecard()
|
| 207 |
+
self.assertIsNotNone(card_id_2, "Should get card_id from server")
|
| 208 |
+
finally:
|
| 209 |
+
if server_error:
|
| 210 |
+
raise server_error[0]
|
| 211 |
+
|
| 212 |
+
def test_competition_mode_on_sever_can_not_open_multiple_scorecards(
|
| 213 |
+
self,
|
| 214 |
+
) -> None:
|
| 215 |
+
if not Path(self.environments_dir).exists():
|
| 216 |
+
self.skipTest("test_environment_files not found")
|
| 217 |
+
|
| 218 |
+
port = _find_free_port()
|
| 219 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 220 |
+
|
| 221 |
+
server_arc = Arcade(
|
| 222 |
+
operation_mode=OperationMode.OFFLINE,
|
| 223 |
+
environments_dir=self.environments_dir,
|
| 224 |
+
arc_api_key="test-key-123",
|
| 225 |
+
logger=self.logger,
|
| 226 |
+
)
|
| 227 |
+
self.assertGreater(
|
| 228 |
+
len(server_arc.available_environments),
|
| 229 |
+
0,
|
| 230 |
+
"Server should have at least one environment from test_environment_files",
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
server_error: list[Exception] = []
|
| 234 |
+
|
| 235 |
+
def run_server() -> None:
|
| 236 |
+
try:
|
| 237 |
+
server_arc.listen_and_serve(
|
| 238 |
+
host="127.0.0.1",
|
| 239 |
+
port=port,
|
| 240 |
+
use_reloader=False,
|
| 241 |
+
competition_mode=True,
|
| 242 |
+
)
|
| 243 |
+
except Exception as e:
|
| 244 |
+
server_error.append(e)
|
| 245 |
+
|
| 246 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 247 |
+
server_thread.start()
|
| 248 |
+
|
| 249 |
+
time.sleep(1.5)
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
client_arc = Arcade(
|
| 253 |
+
operation_mode=OperationMode.COMPETITION,
|
| 254 |
+
arc_base_url=base_url,
|
| 255 |
+
arc_api_key="test-key-123",
|
| 256 |
+
logger=self.logger,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
card_id_1 = client_arc.create_scorecard()
|
| 260 |
+
self.assertIsNotNone(card_id_1, "Should get card_id from server")
|
| 261 |
+
|
| 262 |
+
with self.assertRaises(HTTPError):
|
| 263 |
+
client_arc.create_scorecard()
|
| 264 |
+
finally:
|
| 265 |
+
if server_error:
|
| 266 |
+
raise server_error[0]
|
| 267 |
+
|
| 268 |
+
def test_competition_mode_scorecard_create_and_close_when_client_is_competition(
|
| 269 |
+
self,
|
| 270 |
+
) -> None:
|
| 271 |
+
if not Path(self.environments_dir).exists():
|
| 272 |
+
self.skipTest("test_environment_files not found")
|
| 273 |
+
|
| 274 |
+
port = _find_free_port()
|
| 275 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 276 |
+
|
| 277 |
+
server_arc = Arcade(
|
| 278 |
+
operation_mode=OperationMode.OFFLINE,
|
| 279 |
+
environments_dir=self.environments_dir,
|
| 280 |
+
arc_api_key="test-key-123",
|
| 281 |
+
logger=self.logger,
|
| 282 |
+
)
|
| 283 |
+
self.assertGreater(
|
| 284 |
+
len(server_arc.available_environments),
|
| 285 |
+
0,
|
| 286 |
+
"Server should have at least one environment from test_environment_files",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
server_error: list[Exception] = []
|
| 290 |
+
|
| 291 |
+
def run_server() -> None:
|
| 292 |
+
try:
|
| 293 |
+
server_arc.listen_and_serve(
|
| 294 |
+
host="127.0.0.1",
|
| 295 |
+
port=port,
|
| 296 |
+
use_reloader=False,
|
| 297 |
+
)
|
| 298 |
+
except Exception as e:
|
| 299 |
+
server_error.append(e)
|
| 300 |
+
|
| 301 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 302 |
+
server_thread.start()
|
| 303 |
+
|
| 304 |
+
time.sleep(1.5)
|
| 305 |
+
|
| 306 |
+
try:
|
| 307 |
+
client_arc = Arcade(
|
| 308 |
+
operation_mode=OperationMode.COMPETITION,
|
| 309 |
+
arc_base_url=base_url,
|
| 310 |
+
arc_api_key="test-key-123",
|
| 311 |
+
logger=self.logger,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
card_id = client_arc.create_scorecard()
|
| 315 |
+
self.assertIsNotNone(card_id, "Should get card_id from server")
|
| 316 |
+
|
| 317 |
+
result = client_arc.close_scorecard(scorecard_id=card_id)
|
| 318 |
+
self.assertIsNotNone(result, "Close should return scorecard")
|
| 319 |
+
self.assertIs(
|
| 320 |
+
result.competition_mode,
|
| 321 |
+
True,
|
| 322 |
+
"Scorecard should have competition_mode=True",
|
| 323 |
+
)
|
| 324 |
+
finally:
|
| 325 |
+
if server_error:
|
| 326 |
+
raise server_error[0]
|
| 327 |
+
|
| 328 |
+
def test_competition_mode_scorecard_create_and_close_when_server_is_competition(
|
| 329 |
+
self,
|
| 330 |
+
) -> None:
|
| 331 |
+
if not Path(self.environments_dir).exists():
|
| 332 |
+
self.skipTest("test_environment_files not found")
|
| 333 |
+
|
| 334 |
+
port = _find_free_port()
|
| 335 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 336 |
+
|
| 337 |
+
server_arc = Arcade(
|
| 338 |
+
operation_mode=OperationMode.OFFLINE,
|
| 339 |
+
environments_dir=self.environments_dir,
|
| 340 |
+
arc_api_key="test-key-123",
|
| 341 |
+
logger=self.logger,
|
| 342 |
+
)
|
| 343 |
+
self.assertGreater(
|
| 344 |
+
len(server_arc.available_environments),
|
| 345 |
+
0,
|
| 346 |
+
"Server should have at least one environment from test_environment_files",
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
server_error: list[Exception] = []
|
| 350 |
+
|
| 351 |
+
def run_server() -> None:
|
| 352 |
+
try:
|
| 353 |
+
server_arc.listen_and_serve(
|
| 354 |
+
host="127.0.0.1",
|
| 355 |
+
port=port,
|
| 356 |
+
use_reloader=False,
|
| 357 |
+
competition_mode=True,
|
| 358 |
+
)
|
| 359 |
+
except Exception as e:
|
| 360 |
+
server_error.append(e)
|
| 361 |
+
|
| 362 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 363 |
+
server_thread.start()
|
| 364 |
+
|
| 365 |
+
time.sleep(1.5)
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
client_arc = Arcade(
|
| 369 |
+
operation_mode=OperationMode.ONLINE,
|
| 370 |
+
arc_base_url=base_url,
|
| 371 |
+
arc_api_key="test-key-123",
|
| 372 |
+
logger=self.logger,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
card_id = client_arc.create_scorecard()
|
| 376 |
+
self.assertIsNotNone(card_id, "Should get card_id from server")
|
| 377 |
+
|
| 378 |
+
# This should throw an exception from the rest server
|
| 379 |
+
with self.assertRaises(HTTPError):
|
| 380 |
+
client_arc.get_scorecard(scorecard_id=card_id)
|
| 381 |
+
|
| 382 |
+
result = client_arc.close_scorecard(scorecard_id=card_id)
|
| 383 |
+
self.assertIsNotNone(result, "Close should return scorecard")
|
| 384 |
+
self.assertIs(
|
| 385 |
+
result.competition_mode,
|
| 386 |
+
True,
|
| 387 |
+
"Scorecard should have competition_mode=True",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# Make sure the scoreard has all the environments
|
| 391 |
+
self.assertIsNotNone(
|
| 392 |
+
result.find_environment("bt11"), "Should have bt11 in the scorecard"
|
| 393 |
+
)
|
| 394 |
+
self.assertIsNotNone(
|
| 395 |
+
result.find_environment("bt33"), "Should have bt33 in the scorecard"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
finally:
|
| 399 |
+
if server_error:
|
| 400 |
+
raise server_error[0]
|
| 401 |
+
|
| 402 |
+
def test_competition_mode_can_only_create_one_instance_of_an_environment(
|
| 403 |
+
self,
|
| 404 |
+
) -> None:
|
| 405 |
+
if not Path(self.environments_dir).exists():
|
| 406 |
+
self.skipTest("test_environment_files not found")
|
| 407 |
+
|
| 408 |
+
port = _find_free_port()
|
| 409 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 410 |
+
|
| 411 |
+
server_arc = Arcade(
|
| 412 |
+
operation_mode=OperationMode.OFFLINE,
|
| 413 |
+
environments_dir=self.environments_dir,
|
| 414 |
+
arc_api_key="test-key-123",
|
| 415 |
+
logger=self.logger,
|
| 416 |
+
)
|
| 417 |
+
self.assertGreater(
|
| 418 |
+
len(server_arc.available_environments),
|
| 419 |
+
0,
|
| 420 |
+
"Server should have at least one environment from test_environment_files",
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
server_error: list[Exception] = []
|
| 424 |
+
|
| 425 |
+
def run_server() -> None:
|
| 426 |
+
try:
|
| 427 |
+
server_arc.listen_and_serve(
|
| 428 |
+
host="127.0.0.1",
|
| 429 |
+
port=port,
|
| 430 |
+
use_reloader=False,
|
| 431 |
+
)
|
| 432 |
+
except Exception as e:
|
| 433 |
+
server_error.append(e)
|
| 434 |
+
|
| 435 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 436 |
+
server_thread.start()
|
| 437 |
+
|
| 438 |
+
time.sleep(1.5)
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
client_arc_normal = Arcade(
|
| 442 |
+
operation_mode=OperationMode.ONLINE,
|
| 443 |
+
arc_base_url=base_url,
|
| 444 |
+
arc_api_key="test-key-123",
|
| 445 |
+
logger=self.logger,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
normal_card_id = client_arc_normal.create_scorecard()
|
| 449 |
+
self.assertIsNotNone(normal_card_id, "Should get card_id from server")
|
| 450 |
+
|
| 451 |
+
normal_env_1 = client_arc_normal.make(
|
| 452 |
+
game_id="bt11", scorecard_id=normal_card_id
|
| 453 |
+
)
|
| 454 |
+
self.assertIsNotNone(normal_env_1, "Should get emv from server")
|
| 455 |
+
normal_env_2 = client_arc_normal.make(
|
| 456 |
+
game_id="bt11", scorecard_id=normal_card_id
|
| 457 |
+
)
|
| 458 |
+
self.assertIsNotNone(normal_env_2, "Should get card_id from server")
|
| 459 |
+
|
| 460 |
+
normal_scorecard = client_arc_normal.close_scorecard(
|
| 461 |
+
scorecard_id=normal_card_id
|
| 462 |
+
)
|
| 463 |
+
normal_env_score = normal_scorecard.find_environment("bt11")
|
| 464 |
+
self.assertIsNotNone(normal_env_score, "Should get a environment")
|
| 465 |
+
self.assertEqual(len(normal_env_score.runs), 2, "Should have 2 runs")
|
| 466 |
+
|
| 467 |
+
client_arc_comp = Arcade(
|
| 468 |
+
operation_mode=OperationMode.COMPETITION,
|
| 469 |
+
arc_base_url=base_url,
|
| 470 |
+
arc_api_key="test-key-987",
|
| 471 |
+
logger=self.logger,
|
| 472 |
+
)
|
| 473 |
+
comp_card_id = client_arc_comp.create_scorecard()
|
| 474 |
+
self.assertIsNotNone(comp_card_id, "Should get card_id from server")
|
| 475 |
+
|
| 476 |
+
comp_env_1 = client_arc_comp.make(game_id="bt11", scorecard_id=comp_card_id)
|
| 477 |
+
self.assertIsNotNone(comp_env_1, "Should get env from server")
|
| 478 |
+
comp_env_2 = client_arc_comp.make(
|
| 479 |
+
game_id="bt11", scorecard_id=comp_card_id
|
| 480 |
+
) # This should raise an error
|
| 481 |
+
self.assertIsNotNone(comp_env_2, "should get an env")
|
| 482 |
+
self.assertIsNone(
|
| 483 |
+
comp_env_2.observation_space, "Should not get a observation space"
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
comp_scorecard = client_arc_comp.close_scorecard(scorecard_id=comp_card_id)
|
| 487 |
+
comp_env_score = comp_scorecard.find_environment("bt11")
|
| 488 |
+
self.assertIsNotNone(comp_env_score, "Should get a environment")
|
| 489 |
+
self.assertEqual(len(comp_env_score.runs), 1, "Should have 1 runs")
|
| 490 |
+
|
| 491 |
+
finally:
|
| 492 |
+
if server_error:
|
| 493 |
+
raise server_error[0]
|
| 494 |
+
|
| 495 |
+
def test_competition_mode_can_only_reset_levels(
|
| 496 |
+
self,
|
| 497 |
+
) -> None:
|
| 498 |
+
if not Path(self.environments_dir).exists():
|
| 499 |
+
self.skipTest("test_environment_files not found")
|
| 500 |
+
|
| 501 |
+
port = _find_free_port()
|
| 502 |
+
base_url = f"http://127.0.0.1:{port}"
|
| 503 |
+
|
| 504 |
+
server_arc = Arcade(
|
| 505 |
+
operation_mode=OperationMode.OFFLINE,
|
| 506 |
+
environments_dir=self.environments_dir,
|
| 507 |
+
arc_api_key="test-key-123",
|
| 508 |
+
logger=self.logger,
|
| 509 |
+
)
|
| 510 |
+
self.assertGreater(
|
| 511 |
+
len(server_arc.available_environments),
|
| 512 |
+
0,
|
| 513 |
+
"Server should have at least one environment from test_environment_files",
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
server_error: list[Exception] = []
|
| 517 |
+
|
| 518 |
+
def run_server() -> None:
|
| 519 |
+
try:
|
| 520 |
+
server_arc.listen_and_serve(
|
| 521 |
+
host="127.0.0.1",
|
| 522 |
+
port=port,
|
| 523 |
+
use_reloader=False,
|
| 524 |
+
)
|
| 525 |
+
except Exception as e:
|
| 526 |
+
server_error.append(e)
|
| 527 |
+
|
| 528 |
+
server_thread = threading.Thread(target=run_server, daemon=True)
|
| 529 |
+
server_thread.start()
|
| 530 |
+
|
| 531 |
+
time.sleep(1.5)
|
| 532 |
+
|
| 533 |
+
try:
|
| 534 |
+
client_arc_normal = Arcade(
|
| 535 |
+
operation_mode=OperationMode.ONLINE,
|
| 536 |
+
arc_base_url=base_url,
|
| 537 |
+
arc_api_key="test-key-123",
|
| 538 |
+
logger=self.logger,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
normal_card_id = client_arc_normal.create_scorecard()
|
| 542 |
+
self.assertIsNotNone(normal_card_id, "Should get card_id from server")
|
| 543 |
+
|
| 544 |
+
normal_env_1 = client_arc_normal.make(
|
| 545 |
+
game_id="bt11", scorecard_id=normal_card_id
|
| 546 |
+
)
|
| 547 |
+
self.assertIsNotNone(normal_env_1, "Should get env from server")
|
| 548 |
+
|
| 549 |
+
for i in range(4):
|
| 550 |
+
frame = normal_env_1.step(GameAction.ACTION3)
|
| 551 |
+
self.assertIsNotNone(frame, f"Step {i + 1} should return frame")
|
| 552 |
+
|
| 553 |
+
normal_final_frame = normal_env_1.observation_space
|
| 554 |
+
self.assertIsNotNone(normal_final_frame)
|
| 555 |
+
self.assertEqual(
|
| 556 |
+
normal_final_frame.levels_completed,
|
| 557 |
+
1,
|
| 558 |
+
"Four ACTION3 steps should result in levels_completed=1",
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
normal_reset_frame = normal_env_1.reset()
|
| 562 |
+
self.assertIsNotNone(normal_reset_frame)
|
| 563 |
+
self.assertEqual(
|
| 564 |
+
normal_reset_frame.levels_completed,
|
| 565 |
+
0,
|
| 566 |
+
"Full reset should have put us back to the starting level",
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# Full reset should have 2 runs
|
| 570 |
+
normal_scorecard = client_arc_normal.close_scorecard(
|
| 571 |
+
scorecard_id=normal_card_id
|
| 572 |
+
)
|
| 573 |
+
normal_env_score = normal_scorecard.find_environment("bt11")
|
| 574 |
+
self.assertIsNotNone(normal_env_score, "Should get a environment")
|
| 575 |
+
self.assertEqual(len(normal_env_score.runs), 2, "Should have 2 runs")
|
| 576 |
+
|
| 577 |
+
client_arc_comp = Arcade(
|
| 578 |
+
operation_mode=OperationMode.COMPETITION,
|
| 579 |
+
arc_base_url=base_url,
|
| 580 |
+
arc_api_key="test-key-987",
|
| 581 |
+
logger=self.logger,
|
| 582 |
+
)
|
| 583 |
+
comp_card_id = client_arc_comp.create_scorecard()
|
| 584 |
+
self.assertIsNotNone(comp_card_id, "Should get card_id from server")
|
| 585 |
+
|
| 586 |
+
comp_env_1 = client_arc_comp.make(game_id="bt11", scorecard_id=comp_card_id)
|
| 587 |
+
self.assertIsNotNone(comp_env_1, "Should get env from server")
|
| 588 |
+
|
| 589 |
+
for i in range(4):
|
| 590 |
+
frame = comp_env_1.step(GameAction.ACTION3)
|
| 591 |
+
self.assertIsNotNone(frame, f"Step {i + 1} should return frame")
|
| 592 |
+
|
| 593 |
+
comp_final_frame = comp_env_1.observation_space
|
| 594 |
+
self.assertIsNotNone(comp_final_frame)
|
| 595 |
+
self.assertEqual(
|
| 596 |
+
comp_final_frame.levels_completed,
|
| 597 |
+
1,
|
| 598 |
+
"Four ACTION3 steps should result in levels_completed=1",
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
comp_reset_frame = comp_env_1.step(GameAction.RESET)
|
| 602 |
+
self.assertIsNotNone(comp_reset_frame)
|
| 603 |
+
self.assertEqual(
|
| 604 |
+
comp_reset_frame.levels_completed,
|
| 605 |
+
1,
|
| 606 |
+
"Full reset not have happend and thuse levels_completed should be 1",
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# a second level reset shouldn't reset the game either
|
| 610 |
+
comp_reset_frame = comp_env_1.step(GameAction.RESET)
|
| 611 |
+
self.assertIsNotNone(comp_reset_frame)
|
| 612 |
+
self.assertEqual(
|
| 613 |
+
comp_reset_frame.levels_completed,
|
| 614 |
+
1,
|
| 615 |
+
"Full reset not have happend and thuse levels_completed should be 1",
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
# a third level reset shouldn't reset the game either, this time via reset()
|
| 619 |
+
comp_reset_frame = comp_env_1.reset()
|
| 620 |
+
self.assertIsNotNone(comp_reset_frame)
|
| 621 |
+
self.assertEqual(
|
| 622 |
+
comp_reset_frame.levels_completed,
|
| 623 |
+
1,
|
| 624 |
+
"Full reset not have happend and thuse levels_completed should be 1",
|
| 625 |
+
)
|
| 626 |
+
# a fourth level reset shouldn't reset the game either, this time via reset()
|
| 627 |
+
comp_reset_frame = comp_env_1.reset()
|
| 628 |
+
self.assertIsNotNone(comp_reset_frame)
|
| 629 |
+
self.assertEqual(
|
| 630 |
+
comp_reset_frame.levels_completed,
|
| 631 |
+
1,
|
| 632 |
+
"Full reset not have happend and thuse levels_completed should be 1",
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
# No full reset should happen and thus we should have 1 run
|
| 636 |
+
comp_scorecard = client_arc_comp.close_scorecard(scorecard_id=comp_card_id)
|
| 637 |
+
comp_env_score = comp_scorecard.find_environment("bt11")
|
| 638 |
+
self.assertIsNotNone(comp_env_score, "Should get a environment")
|
| 639 |
+
self.assertEqual(len(comp_env_score.runs), 1, "Should have 1 runs")
|
| 640 |
+
self.assertEqual(
|
| 641 |
+
comp_env_score.runs[0].actions,
|
| 642 |
+
8,
|
| 643 |
+
"Should have 8 actions, even the failed reset counts as an action",
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
finally:
|
| 647 |
+
if server_error:
|
| 648 |
+
raise server_error[0]
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
if __name__ == "__main__":
|
| 652 |
+
unittest.main()
|
arcprize__ARC-AGI/tests/test_local_wrapper.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for LocalEnvironmentWrapper using unittest."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from unittest.mock import MagicMock
|
| 9 |
+
|
| 10 |
+
_mock_dotenv = MagicMock()
|
| 11 |
+
_mock_dotenv.load_dotenv = MagicMock()
|
| 12 |
+
sys.modules["dotenv"] = _mock_dotenv
|
| 13 |
+
|
| 14 |
+
from arcengine import GameAction, GameState # noqa: E402
|
| 15 |
+
|
| 16 |
+
from arc_agi import Arcade, OperationMode # noqa: E402
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestLocalEnvironmentWrapper(unittest.TestCase):
|
| 20 |
+
"""Test LocalEnvironmentWrapper functionality."""
|
| 21 |
+
|
| 22 |
+
def setUp(self):
|
| 23 |
+
"""Set up test fixtures."""
|
| 24 |
+
self.env_vars_to_clear = [
|
| 25 |
+
"ARC_API_KEY",
|
| 26 |
+
"ARC_BASE_URL",
|
| 27 |
+
"OFFLINE_ONLY",
|
| 28 |
+
"ONLINE_ONLY",
|
| 29 |
+
"COMPETITION_MODE",
|
| 30 |
+
"LISTEN_BINDINGS",
|
| 31 |
+
"ENVIRONMENTS_DIR",
|
| 32 |
+
]
|
| 33 |
+
for var in self.env_vars_to_clear:
|
| 34 |
+
os.environ.pop(var, None)
|
| 35 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 36 |
+
|
| 37 |
+
# Set up logger
|
| 38 |
+
self.logger = logging.getLogger("test")
|
| 39 |
+
self.logger.setLevel(logging.INFO)
|
| 40 |
+
|
| 41 |
+
# Set environments_dir to test_environment_files
|
| 42 |
+
test_dir = Path(__file__).parent.parent / "test_environment_files"
|
| 43 |
+
self.environments_dir = str(test_dir)
|
| 44 |
+
|
| 45 |
+
def tearDown(self):
|
| 46 |
+
"""Clean up after tests."""
|
| 47 |
+
for var in self.env_vars_to_clear:
|
| 48 |
+
os.environ.pop(var, None)
|
| 49 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 50 |
+
|
| 51 |
+
def test_make_bt11_without_version(self):
|
| 52 |
+
"""Test making bt11 game without version (should find latest)."""
|
| 53 |
+
client = Arcade(
|
| 54 |
+
operation_mode=OperationMode.OFFLINE,
|
| 55 |
+
environments_dir=self.environments_dir,
|
| 56 |
+
logger=self.logger,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
wrapper = client.make(game_id="bt11", scorecard_id="test-scorecard-1")
|
| 60 |
+
|
| 61 |
+
self.assertIsNotNone(wrapper, "Wrapper should be created")
|
| 62 |
+
self.assertEqual(wrapper.environment_info.game_id, "bt11-fd9df0622a1a")
|
| 63 |
+
self.assertEqual(wrapper.scorecard_id, "test-scorecard-1")
|
| 64 |
+
self.assertIsNotNone(wrapper.environment_info.local_dir)
|
| 65 |
+
|
| 66 |
+
def test_make_bt11_with_version(self):
|
| 67 |
+
"""Test making bt11 game with specific version."""
|
| 68 |
+
client = Arcade(
|
| 69 |
+
operation_mode=OperationMode.OFFLINE,
|
| 70 |
+
environments_dir=self.environments_dir,
|
| 71 |
+
logger=self.logger,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
wrapper = client.make(
|
| 75 |
+
game_id="bt11-fd9df0622a1a", scorecard_id="test-scorecard-2"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
self.assertIsNotNone(wrapper, "Wrapper should be created")
|
| 79 |
+
self.assertEqual(wrapper.environment_info.game_id, "bt11-fd9df0622a1a")
|
| 80 |
+
self.assertEqual(wrapper.scorecard_id, "test-scorecard-2")
|
| 81 |
+
self.assertIsNotNone(wrapper.environment_info.local_dir)
|
| 82 |
+
|
| 83 |
+
def test_make_bt11_reset(self):
|
| 84 |
+
"""Test that reset() works and returns FrameDataRaw."""
|
| 85 |
+
client = Arcade(
|
| 86 |
+
operation_mode=OperationMode.OFFLINE,
|
| 87 |
+
environments_dir=self.environments_dir,
|
| 88 |
+
logger=self.logger,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
wrapper = client.make(game_id="bt11", scorecard_id="test-reset")
|
| 92 |
+
|
| 93 |
+
self.assertIsNotNone(wrapper)
|
| 94 |
+
|
| 95 |
+
# Test reset
|
| 96 |
+
frame_data = wrapper.reset()
|
| 97 |
+
self.assertIsNotNone(frame_data, "Reset should return FrameDataRaw")
|
| 98 |
+
self.assertEqual(frame_data.game_id, "bt11-fd9df0622a1a")
|
| 99 |
+
self.assertEqual(frame_data.state, GameState.NOT_FINISHED)
|
| 100 |
+
|
| 101 |
+
# Check observation_space
|
| 102 |
+
obs = wrapper.observation_space
|
| 103 |
+
self.assertIsNotNone(obs)
|
| 104 |
+
self.assertEqual(obs.game_id, "bt11-fd9df0622a1a")
|
| 105 |
+
|
| 106 |
+
def test_make_bt11_four_action3_steps(self):
|
| 107 |
+
"""Test that four ACTION3 (move left) steps get past the first level."""
|
| 108 |
+
client = Arcade(
|
| 109 |
+
operation_mode=OperationMode.OFFLINE,
|
| 110 |
+
environments_dir=self.environments_dir,
|
| 111 |
+
logger=self.logger,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
wrapper = client.make(game_id="bt11", scorecard_id="test-action3")
|
| 115 |
+
|
| 116 |
+
self.assertIsNotNone(wrapper)
|
| 117 |
+
|
| 118 |
+
# Reset the game
|
| 119 |
+
reset_frame = wrapper.reset()
|
| 120 |
+
self.assertIsNotNone(reset_frame)
|
| 121 |
+
self.assertEqual(reset_frame.state, GameState.NOT_FINISHED)
|
| 122 |
+
initial_level = reset_frame.levels_completed
|
| 123 |
+
|
| 124 |
+
# Perform four ACTION3 (move left) actions
|
| 125 |
+
for i in range(4):
|
| 126 |
+
frame_data = wrapper.step(GameAction.ACTION3)
|
| 127 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 128 |
+
self.logger.info(
|
| 129 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# After 4 ACTION3 steps, should have advanced to next level
|
| 133 |
+
# Score should have increased (level completion increases score)
|
| 134 |
+
final_frame = wrapper.observation_space
|
| 135 |
+
self.assertIsNotNone(final_frame)
|
| 136 |
+
self.assertGreater(
|
| 137 |
+
final_frame.levels_completed,
|
| 138 |
+
initial_level,
|
| 139 |
+
"Score should increase after completing first level",
|
| 140 |
+
)
|
| 141 |
+
self.assertNotEqual(
|
| 142 |
+
final_frame.state,
|
| 143 |
+
GameState.GAME_OVER,
|
| 144 |
+
"Game should not be over after 4 ACTION3 steps",
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Verify we can see the action space
|
| 148 |
+
action_space = wrapper.action_space
|
| 149 |
+
self.assertGreater(len(action_space), 0, "Action space should have actions")
|
| 150 |
+
self.assertIn(GameAction.ACTION3, action_space, "ACTION3 should be available")
|
| 151 |
+
|
| 152 |
+
def test_make_bt11_that_command_at_game_over_does_not_add_to_scorecard(self):
|
| 153 |
+
"""Test that four ACTION3 (move left) steps get past the first level."""
|
| 154 |
+
client = Arcade(
|
| 155 |
+
operation_mode=OperationMode.OFFLINE,
|
| 156 |
+
environments_dir=self.environments_dir,
|
| 157 |
+
logger=self.logger,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
card_id = client.create_scorecard()
|
| 161 |
+
|
| 162 |
+
wrapper = client.make(game_id="bt11", scorecard_id=card_id)
|
| 163 |
+
|
| 164 |
+
self.assertIsNotNone(wrapper)
|
| 165 |
+
|
| 166 |
+
# Perform four ACTION3 (move left) actions, this gets us past the first level
|
| 167 |
+
for i in range(4):
|
| 168 |
+
frame_data = wrapper.step(GameAction.ACTION3)
|
| 169 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 170 |
+
self.logger.info(
|
| 171 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# Perform eight ACTION4 (move right) actions to get to game over
|
| 175 |
+
for i in range(8):
|
| 176 |
+
frame_data = wrapper.step(GameAction.ACTION4)
|
| 177 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 178 |
+
self.logger.info(
|
| 179 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
self.assertEqual(frame_data.state, GameState.GAME_OVER)
|
| 183 |
+
|
| 184 |
+
# Perform one ACTION4 (move left) action to get send a game over to a bad game
|
| 185 |
+
frame_data = wrapper.step(GameAction.ACTION4)
|
| 186 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 187 |
+
self.assertEqual(len(frame_data.frame), 0)
|
| 188 |
+
|
| 189 |
+
wrapper.reset()
|
| 190 |
+
|
| 191 |
+
# Perform eight ACTION3 (move left) actions, this gets us past the second level
|
| 192 |
+
for i in range(8):
|
| 193 |
+
frame_data = wrapper.step(GameAction.ACTION3)
|
| 194 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 195 |
+
self.logger.info(
|
| 196 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
scorecard = client.get_scorecard(card_id)
|
| 200 |
+
|
| 201 |
+
# Step count for level 2 should be 17, 8 ACTION4s for Game Over, 1 RESET, 8 ACTION3s for Level 2
|
| 202 |
+
self.assertEqual(scorecard.environments[0].runs[0].level_actions[1], 17)
|
| 203 |
+
|
| 204 |
+
def test_make_invalid_game_id(self):
|
| 205 |
+
"""Test that invalid game_id format returns None."""
|
| 206 |
+
client = Arcade(
|
| 207 |
+
operation_mode=OperationMode.OFFLINE,
|
| 208 |
+
environments_dir=self.environments_dir,
|
| 209 |
+
logger=self.logger,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
wrapper = client.make(game_id="invalid", scorecard_id="test")
|
| 213 |
+
self.assertIsNone(wrapper, "Invalid game_id should return None")
|
| 214 |
+
|
| 215 |
+
def test_make_game_not_found(self):
|
| 216 |
+
"""Test that non-existent game returns None."""
|
| 217 |
+
client = Arcade(
|
| 218 |
+
operation_mode=OperationMode.OFFLINE,
|
| 219 |
+
environments_dir=self.environments_dir,
|
| 220 |
+
logger=self.logger,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
wrapper = client.make(game_id="xxxx", scorecard_id="test")
|
| 224 |
+
self.assertIsNone(wrapper, "Non-existent game should return None")
|
| 225 |
+
|
| 226 |
+
def test_make_with_wrong_version(self):
|
| 227 |
+
"""Test that wrong version returns None."""
|
| 228 |
+
client = Arcade(
|
| 229 |
+
operation_mode=OperationMode.OFFLINE,
|
| 230 |
+
environments_dir=self.environments_dir,
|
| 231 |
+
logger=self.logger,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
wrapper = client.make(game_id="bt11-wrongversion", scorecard_id="test")
|
| 235 |
+
self.assertIsNone(wrapper, "Wrong version should return None")
|
| 236 |
+
|
| 237 |
+
def test_make_bt11_fd9df0622a1b_with_action6(self):
|
| 238 |
+
"""Test that bt33-a7c3f9d18b4e loads and four ACTION6 (GLICK) actions with x=1, y=1 get past the first level."""
|
| 239 |
+
client = Arcade(
|
| 240 |
+
operation_mode=OperationMode.OFFLINE,
|
| 241 |
+
environments_dir=self.environments_dir,
|
| 242 |
+
logger=self.logger,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
wrapper = client.make(game_id="bt33-a7c3f9d18b4e", scorecard_id="test-action6")
|
| 246 |
+
|
| 247 |
+
self.assertIsNotNone(wrapper, "Wrapper should be created")
|
| 248 |
+
self.assertEqual(wrapper.environment_info.game_id, "bt33-a7c3f9d18b4e")
|
| 249 |
+
self.assertEqual(wrapper.scorecard_id, "test-action6")
|
| 250 |
+
self.assertIsNotNone(wrapper.environment_info.local_dir)
|
| 251 |
+
|
| 252 |
+
# Reset the game
|
| 253 |
+
reset_frame = wrapper.reset()
|
| 254 |
+
self.assertIsNotNone(reset_frame)
|
| 255 |
+
self.assertEqual(reset_frame.state, GameState.NOT_FINISHED)
|
| 256 |
+
initial_level = reset_frame.levels_completed
|
| 257 |
+
|
| 258 |
+
# Perform four ACTION6 (GLICK) actions with x=1, y=1
|
| 259 |
+
for i in range(4):
|
| 260 |
+
frame_data = wrapper.step(GameAction.ACTION6, data={"x": 1, "y": 1})
|
| 261 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 262 |
+
self.logger.info(
|
| 263 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
# After 4 ACTION6 steps, should have advanced to next level
|
| 267 |
+
# Score should have increased (level completion increases score)
|
| 268 |
+
final_frame = wrapper.observation_space
|
| 269 |
+
self.assertIsNotNone(final_frame)
|
| 270 |
+
self.assertGreater(
|
| 271 |
+
final_frame.levels_completed,
|
| 272 |
+
initial_level,
|
| 273 |
+
"Score should increase after completing first level",
|
| 274 |
+
)
|
| 275 |
+
self.assertNotEqual(
|
| 276 |
+
final_frame.state,
|
| 277 |
+
GameState.GAME_OVER,
|
| 278 |
+
"Game should not be over after 4 ACTION6 steps",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
# Verify we can see the action space
|
| 282 |
+
action_space = wrapper.action_space
|
| 283 |
+
self.assertGreater(len(action_space), 0, "Action space should have actions")
|
| 284 |
+
self.assertIn(GameAction.ACTION6, action_space, "ACTION6 should be available")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
if __name__ == "__main__":
|
| 288 |
+
unittest.main()
|
arcprize__ARC-AGI/tests/test_models.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the EnvironmentInfo model using unittest."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import unittest
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
|
| 7 |
+
from pydantic import ValidationError
|
| 8 |
+
|
| 9 |
+
from arc_agi import EnvironmentInfo
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestEnvironmentInfo(unittest.TestCase):
|
| 13 |
+
"""Test EnvironmentInfo model."""
|
| 14 |
+
|
| 15 |
+
def test_create_from_dict(self):
|
| 16 |
+
"""Test creating EnvironmentInfo from a dictionary."""
|
| 17 |
+
data = {
|
| 18 |
+
"game_id": "tg61-28585068",
|
| 19 |
+
"title": "TG61",
|
| 20 |
+
"tags": ["tag1", "tag2"],
|
| 21 |
+
"baseline_actions": [12, 17, 18, 22, 50],
|
| 22 |
+
}
|
| 23 |
+
env_info = EnvironmentInfo(**data)
|
| 24 |
+
|
| 25 |
+
self.assertEqual(env_info.game_id, "tg61-28585068")
|
| 26 |
+
self.assertEqual(env_info.title, "TG61")
|
| 27 |
+
self.assertEqual(env_info.tags, ["tag1", "tag2"])
|
| 28 |
+
self.assertEqual(env_info.baseline_actions, [12, 17, 18, 22, 50])
|
| 29 |
+
# date_downloaded should default to now
|
| 30 |
+
self.assertIsNotNone(env_info.date_downloaded)
|
| 31 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 32 |
+
# class_name should default to first 4 chars of game_id capitalized
|
| 33 |
+
self.assertEqual(env_info.class_name, "Tg61")
|
| 34 |
+
|
| 35 |
+
def test_create_from_keyword_args(self):
|
| 36 |
+
"""Test creating EnvironmentInfo from keyword arguments."""
|
| 37 |
+
env_info = EnvironmentInfo(
|
| 38 |
+
game_id="tg61-28585068",
|
| 39 |
+
title="TG61",
|
| 40 |
+
tags=["tag1", "tag2"],
|
| 41 |
+
baseline_actions=[12, 17, 18, 22, 50],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
self.assertEqual(env_info.game_id, "tg61-28585068")
|
| 45 |
+
self.assertEqual(env_info.title, "TG61")
|
| 46 |
+
self.assertEqual(env_info.tags, ["tag1", "tag2"])
|
| 47 |
+
self.assertEqual(env_info.baseline_actions, [12, 17, 18, 22, 50])
|
| 48 |
+
# date_downloaded should default to now
|
| 49 |
+
self.assertIsNotNone(env_info.date_downloaded)
|
| 50 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 51 |
+
# class_name should default to first 4 chars of game_id capitalized
|
| 52 |
+
self.assertEqual(env_info.class_name, "Tg61")
|
| 53 |
+
|
| 54 |
+
def test_serialize_to_json(self):
|
| 55 |
+
"""Test serializing EnvironmentInfo to JSON string."""
|
| 56 |
+
env_info = EnvironmentInfo(
|
| 57 |
+
game_id="tg61-28585068",
|
| 58 |
+
title="TG61",
|
| 59 |
+
tags=["tag1", "tag2"],
|
| 60 |
+
baseline_actions=[12, 17, 18, 22, 50],
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
json_str = env_info.model_dump_json()
|
| 64 |
+
self.assertIsInstance(json_str, str)
|
| 65 |
+
|
| 66 |
+
# Parse JSON to verify structure
|
| 67 |
+
parsed = json.loads(json_str)
|
| 68 |
+
self.assertEqual(parsed["game_id"], "tg61-28585068")
|
| 69 |
+
self.assertEqual(parsed["title"], "TG61")
|
| 70 |
+
self.assertEqual(parsed["tags"], ["tag1", "tag2"])
|
| 71 |
+
self.assertEqual(parsed["baseline_actions"], [12, 17, 18, 22, 50])
|
| 72 |
+
# Defaults should be set
|
| 73 |
+
self.assertIsNotNone(parsed["date_downloaded"])
|
| 74 |
+
self.assertEqual(parsed["class_name"], "Tg61")
|
| 75 |
+
|
| 76 |
+
def test_deserialize_from_json_string(self):
|
| 77 |
+
"""Test deserializing EnvironmentInfo from JSON string."""
|
| 78 |
+
json_str = '{"game_id": "tg61-28585068", "title": "TG61", "tags": ["tag1", "tag2"], "baseline_actions": [12, 17, 18, 22, 50]}'
|
| 79 |
+
|
| 80 |
+
env_info = EnvironmentInfo.model_validate_json(json_str)
|
| 81 |
+
|
| 82 |
+
self.assertEqual(env_info.game_id, "tg61-28585068")
|
| 83 |
+
self.assertEqual(env_info.title, "TG61")
|
| 84 |
+
self.assertEqual(env_info.tags, ["tag1", "tag2"])
|
| 85 |
+
self.assertEqual(env_info.baseline_actions, [12, 17, 18, 22, 50])
|
| 86 |
+
|
| 87 |
+
def test_deserialize_from_json_bytes(self):
|
| 88 |
+
"""Test deserializing EnvironmentInfo from JSON bytes."""
|
| 89 |
+
json_bytes = b'{"game_id": "tg61-28585068", "title": "TG61", "tags": ["tag1", "tag2"], "baseline_actions": [12, 17, 18, 22, 50]}'
|
| 90 |
+
|
| 91 |
+
env_info = EnvironmentInfo.model_validate_json(json_bytes)
|
| 92 |
+
|
| 93 |
+
self.assertEqual(env_info.game_id, "tg61-28585068")
|
| 94 |
+
self.assertEqual(env_info.title, "TG61")
|
| 95 |
+
self.assertEqual(env_info.tags, ["tag1", "tag2"])
|
| 96 |
+
self.assertEqual(env_info.baseline_actions, [12, 17, 18, 22, 50])
|
| 97 |
+
|
| 98 |
+
def test_round_trip_json(self):
|
| 99 |
+
"""Test round-trip serialization: object -> JSON -> object."""
|
| 100 |
+
original = EnvironmentInfo(
|
| 101 |
+
game_id="tg61-28585068",
|
| 102 |
+
title="TG61",
|
| 103 |
+
tags=["tag1", "tag2"],
|
| 104 |
+
baseline_actions=[12, 17, 18, 22, 50],
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
json_str = original.model_dump_json()
|
| 108 |
+
restored = EnvironmentInfo.model_validate_json(json_str)
|
| 109 |
+
|
| 110 |
+
self.assertEqual(original.game_id, restored.game_id)
|
| 111 |
+
self.assertEqual(original.title, restored.title)
|
| 112 |
+
self.assertEqual(original.tags, restored.tags)
|
| 113 |
+
self.assertEqual(original.baseline_actions, restored.baseline_actions)
|
| 114 |
+
|
| 115 |
+
def test_empty_tags(self):
|
| 116 |
+
"""Test EnvironmentInfo with empty tags list."""
|
| 117 |
+
env_info = EnvironmentInfo(
|
| 118 |
+
game_id="test-game",
|
| 119 |
+
title="Test",
|
| 120 |
+
tags=[],
|
| 121 |
+
baseline_actions=[10, 20],
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
self.assertEqual(env_info.tags, [])
|
| 125 |
+
|
| 126 |
+
def test_empty_baseline_actions(self):
|
| 127 |
+
"""Test EnvironmentInfo with empty baseline_actions list."""
|
| 128 |
+
env_info = EnvironmentInfo(
|
| 129 |
+
game_id="test-game",
|
| 130 |
+
title="Test",
|
| 131 |
+
tags=["tag1"],
|
| 132 |
+
baseline_actions=[],
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
self.assertEqual(env_info.baseline_actions, [])
|
| 136 |
+
|
| 137 |
+
def test_missing_game_id(self):
|
| 138 |
+
"""Test that missing game_id raises ValidationError."""
|
| 139 |
+
with self.assertRaises(ValidationError):
|
| 140 |
+
EnvironmentInfo(
|
| 141 |
+
title="TG61",
|
| 142 |
+
tags=["tag1"],
|
| 143 |
+
baseline_actions=[12],
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def test_invalid_game_id_type(self):
|
| 147 |
+
"""Test that invalid game_id type raises ValidationError."""
|
| 148 |
+
with self.assertRaises(ValidationError):
|
| 149 |
+
EnvironmentInfo(
|
| 150 |
+
game_id=12345, # Should be string
|
| 151 |
+
title="TG61",
|
| 152 |
+
tags=["tag1"],
|
| 153 |
+
baseline_actions=[12],
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
def test_invalid_title_type(self):
|
| 157 |
+
"""Test that invalid title type raises ValidationError."""
|
| 158 |
+
with self.assertRaises(ValidationError):
|
| 159 |
+
EnvironmentInfo(
|
| 160 |
+
game_id="tg61-28585068",
|
| 161 |
+
title=12345, # Should be string
|
| 162 |
+
tags=["tag1"],
|
| 163 |
+
baseline_actions=[12],
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def test_invalid_tags_type(self):
|
| 167 |
+
"""Test that invalid tags type raises ValidationError."""
|
| 168 |
+
with self.assertRaises(ValidationError):
|
| 169 |
+
EnvironmentInfo(
|
| 170 |
+
game_id="tg61-28585068",
|
| 171 |
+
title="TG61",
|
| 172 |
+
tags="not-a-list", # Should be list
|
| 173 |
+
baseline_actions=[12],
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def test_invalid_baseline_actions_type(self):
|
| 177 |
+
"""Test that invalid baseline_actions type raises ValidationError."""
|
| 178 |
+
with self.assertRaises(ValidationError):
|
| 179 |
+
EnvironmentInfo(
|
| 180 |
+
game_id="tg61-28585068",
|
| 181 |
+
title="TG61",
|
| 182 |
+
tags=["tag1"],
|
| 183 |
+
baseline_actions="not-a-list", # Should be list
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
def test_baseline_actions_with_numeric_strings(self):
|
| 187 |
+
"""Test that baseline_actions with numeric strings are coerced to integers."""
|
| 188 |
+
# Pydantic v2 auto-coerces numeric strings to integers
|
| 189 |
+
env_info = EnvironmentInfo(
|
| 190 |
+
game_id="tg61-28585068",
|
| 191 |
+
title="TG61",
|
| 192 |
+
tags=["tag1"],
|
| 193 |
+
baseline_actions=["12", "17"], # Will be coerced to [12, 17]
|
| 194 |
+
)
|
| 195 |
+
self.assertEqual(env_info.baseline_actions, [12, 17])
|
| 196 |
+
self.assertIsInstance(env_info.baseline_actions[0], int)
|
| 197 |
+
self.assertIsInstance(env_info.baseline_actions[1], int)
|
| 198 |
+
|
| 199 |
+
def test_baseline_actions_with_non_numeric_strings(self):
|
| 200 |
+
"""Test that baseline_actions with non-numeric strings raises ValidationError."""
|
| 201 |
+
with self.assertRaises(ValidationError):
|
| 202 |
+
EnvironmentInfo(
|
| 203 |
+
game_id="tg61-28585068",
|
| 204 |
+
title="TG61",
|
| 205 |
+
tags=["tag1"],
|
| 206 |
+
baseline_actions=["not-a-number", "also-not-a-number"],
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def test_tags_with_non_strings(self):
|
| 210 |
+
"""Test that tags with non-strings raises ValidationError."""
|
| 211 |
+
with self.assertRaises(ValidationError):
|
| 212 |
+
EnvironmentInfo(
|
| 213 |
+
game_id="tg61-28585068",
|
| 214 |
+
title="TG61",
|
| 215 |
+
tags=[1, 2, 3], # Should be strings
|
| 216 |
+
baseline_actions=[12],
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def test_model_dump(self):
|
| 220 |
+
"""Test model_dump returns dictionary."""
|
| 221 |
+
env_info = EnvironmentInfo(
|
| 222 |
+
game_id="tg61-28585068",
|
| 223 |
+
title="TG61",
|
| 224 |
+
tags=["tag1", "tag2"],
|
| 225 |
+
baseline_actions=[12, 17, 18, 22, 50],
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
dumped = env_info.model_dump()
|
| 229 |
+
self.assertIsInstance(dumped, dict)
|
| 230 |
+
self.assertEqual(dumped["game_id"], "tg61-28585068")
|
| 231 |
+
self.assertEqual(dumped["title"], "TG61")
|
| 232 |
+
self.assertEqual(dumped["tags"], ["tag1", "tag2"])
|
| 233 |
+
self.assertEqual(dumped["baseline_actions"], [12, 17, 18, 22, 50])
|
| 234 |
+
|
| 235 |
+
def test_model_validate_from_dict(self):
|
| 236 |
+
"""Test model_validate creates instance from dictionary."""
|
| 237 |
+
data = {
|
| 238 |
+
"game_id": "tg61-28585068",
|
| 239 |
+
"title": "TG61",
|
| 240 |
+
"tags": ["tag1", "tag2"],
|
| 241 |
+
"baseline_actions": [12, 17, 18, 22, 50],
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
env_info = EnvironmentInfo.model_validate(data)
|
| 245 |
+
|
| 246 |
+
self.assertEqual(env_info.game_id, "tg61-28585068")
|
| 247 |
+
self.assertEqual(env_info.title, "TG61")
|
| 248 |
+
self.assertEqual(env_info.tags, ["tag1", "tag2"])
|
| 249 |
+
self.assertEqual(env_info.baseline_actions, [12, 17, 18, 22, 50])
|
| 250 |
+
|
| 251 |
+
def test_date_downloaded_defaults_to_now(self):
|
| 252 |
+
"""Test that date_downloaded defaults to current time if not provided."""
|
| 253 |
+
from datetime import datetime, timezone
|
| 254 |
+
|
| 255 |
+
env_info = EnvironmentInfo(
|
| 256 |
+
game_id="tg61-28585068",
|
| 257 |
+
title="TG61",
|
| 258 |
+
tags=["tag1"],
|
| 259 |
+
baseline_actions=[12],
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Should be set to a datetime (approximately now)
|
| 263 |
+
self.assertIsNotNone(env_info.date_downloaded)
|
| 264 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 265 |
+
# Should be recent (within last minute)
|
| 266 |
+
now = datetime.now(timezone.utc)
|
| 267 |
+
time_diff = abs((now - env_info.date_downloaded).total_seconds())
|
| 268 |
+
self.assertLess(time_diff, 60)
|
| 269 |
+
|
| 270 |
+
def test_date_downloaded_with_datetime(self):
|
| 271 |
+
"""Test that date_downloaded can be set to a datetime object."""
|
| 272 |
+
download_date = datetime.now(timezone.utc)
|
| 273 |
+
env_info = EnvironmentInfo(
|
| 274 |
+
game_id="tg61-28585068",
|
| 275 |
+
title="TG61",
|
| 276 |
+
tags=["tag1"],
|
| 277 |
+
baseline_actions=[12],
|
| 278 |
+
date_downloaded=download_date,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
self.assertEqual(env_info.date_downloaded, download_date)
|
| 282 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 283 |
+
|
| 284 |
+
def test_date_downloaded_json_serialization(self):
|
| 285 |
+
"""Test that date_downloaded is serialized to ISO format in JSON."""
|
| 286 |
+
download_date = datetime(2024, 1, 15, 10, 30, 45, tzinfo=timezone.utc)
|
| 287 |
+
env_info = EnvironmentInfo(
|
| 288 |
+
game_id="tg61-28585068",
|
| 289 |
+
title="TG61",
|
| 290 |
+
tags=["tag1"],
|
| 291 |
+
baseline_actions=[12],
|
| 292 |
+
date_downloaded=download_date,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
json_str = env_info.model_dump_json()
|
| 296 |
+
parsed = json.loads(json_str)
|
| 297 |
+
|
| 298 |
+
self.assertIn("date_downloaded", parsed)
|
| 299 |
+
# Pydantic v2 serializes UTC as 'Z' format
|
| 300 |
+
self.assertEqual(parsed["date_downloaded"], "2024-01-15T10:30:45Z")
|
| 301 |
+
|
| 302 |
+
def test_date_downloaded_json_deserialization(self):
|
| 303 |
+
"""Test that date_downloaded can be deserialized from ISO format string."""
|
| 304 |
+
json_str = '{"game_id": "tg61-28585068", "title": "TG61", "tags": ["tag1"], "baseline_actions": [12], "date_downloaded": "2024-01-15T10:30:45+00:00"}'
|
| 305 |
+
|
| 306 |
+
env_info = EnvironmentInfo.model_validate_json(json_str)
|
| 307 |
+
|
| 308 |
+
self.assertIsNotNone(env_info.date_downloaded)
|
| 309 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 310 |
+
self.assertEqual(env_info.date_downloaded.year, 2024)
|
| 311 |
+
self.assertEqual(env_info.date_downloaded.month, 1)
|
| 312 |
+
self.assertEqual(env_info.date_downloaded.day, 15)
|
| 313 |
+
|
| 314 |
+
def test_date_downloaded_round_trip(self):
|
| 315 |
+
"""Test round-trip serialization with date_downloaded."""
|
| 316 |
+
download_date = datetime.now(timezone.utc)
|
| 317 |
+
original = EnvironmentInfo(
|
| 318 |
+
game_id="tg61-28585068",
|
| 319 |
+
title="TG61",
|
| 320 |
+
tags=["tag1"],
|
| 321 |
+
baseline_actions=[12],
|
| 322 |
+
date_downloaded=download_date,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
json_str = original.model_dump_json()
|
| 326 |
+
restored = EnvironmentInfo.model_validate_json(json_str)
|
| 327 |
+
|
| 328 |
+
self.assertEqual(original.date_downloaded, restored.date_downloaded)
|
| 329 |
+
self.assertIsInstance(restored.date_downloaded, datetime)
|
| 330 |
+
|
| 331 |
+
def test_date_downloaded_from_dict(self):
|
| 332 |
+
"""Test creating EnvironmentInfo with date_downloaded from dictionary."""
|
| 333 |
+
download_date = datetime.now(timezone.utc)
|
| 334 |
+
data = {
|
| 335 |
+
"game_id": "tg61-28585068",
|
| 336 |
+
"title": "TG61",
|
| 337 |
+
"tags": ["tag1"],
|
| 338 |
+
"baseline_actions": [12],
|
| 339 |
+
"date_downloaded": download_date,
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
env_info = EnvironmentInfo(**data)
|
| 343 |
+
|
| 344 |
+
self.assertEqual(env_info.date_downloaded, download_date)
|
| 345 |
+
|
| 346 |
+
def test_class_name_defaults_from_game_id(self):
|
| 347 |
+
"""Test that class_name defaults to first 4 characters of game_id capitalized."""
|
| 348 |
+
# Test with game_id that has 4+ characters
|
| 349 |
+
env_info = EnvironmentInfo(
|
| 350 |
+
game_id="ls20-ajk315135",
|
| 351 |
+
title="Test",
|
| 352 |
+
tags=["tag1"],
|
| 353 |
+
baseline_actions=[12],
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
self.assertEqual(env_info.class_name, "Ls20")
|
| 357 |
+
|
| 358 |
+
# Test with shorter game_id
|
| 359 |
+
env_info2 = EnvironmentInfo(
|
| 360 |
+
game_id="ab1",
|
| 361 |
+
title="Test",
|
| 362 |
+
tags=["tag1"],
|
| 363 |
+
baseline_actions=[12],
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
self.assertEqual(env_info2.class_name, "Ab1")
|
| 367 |
+
|
| 368 |
+
def test_class_name_with_value(self):
|
| 369 |
+
"""Test that class_name can be set to a string."""
|
| 370 |
+
env_info = EnvironmentInfo(
|
| 371 |
+
game_id="tg61-28585068",
|
| 372 |
+
title="TG61",
|
| 373 |
+
tags=["tag1"],
|
| 374 |
+
baseline_actions=[12],
|
| 375 |
+
class_name="MyGameClass",
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
self.assertEqual(env_info.class_name, "MyGameClass")
|
| 379 |
+
self.assertIsInstance(env_info.class_name, str)
|
| 380 |
+
|
| 381 |
+
def test_class_name_json_serialization(self):
|
| 382 |
+
"""Test that class_name is serialized correctly in JSON."""
|
| 383 |
+
env_info = EnvironmentInfo(
|
| 384 |
+
game_id="tg61-28585068",
|
| 385 |
+
title="TG61",
|
| 386 |
+
tags=["tag1"],
|
| 387 |
+
baseline_actions=[12],
|
| 388 |
+
class_name="MyGameClass",
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
json_str = env_info.model_dump_json()
|
| 392 |
+
parsed = json.loads(json_str)
|
| 393 |
+
|
| 394 |
+
self.assertIn("class_name", parsed)
|
| 395 |
+
self.assertEqual(parsed["class_name"], "MyGameClass")
|
| 396 |
+
|
| 397 |
+
def test_class_name_json_deserialization(self):
|
| 398 |
+
"""Test that class_name can be deserialized from JSON string."""
|
| 399 |
+
json_str = '{"game_id": "tg61-28585068", "title": "TG61", "tags": ["tag1"], "baseline_actions": [12], "class_name": "MyGameClass"}'
|
| 400 |
+
|
| 401 |
+
env_info = EnvironmentInfo.model_validate_json(json_str)
|
| 402 |
+
|
| 403 |
+
self.assertEqual(env_info.class_name, "MyGameClass")
|
| 404 |
+
self.assertIsInstance(env_info.class_name, str)
|
| 405 |
+
|
| 406 |
+
def test_class_name_round_trip(self):
|
| 407 |
+
"""Test round-trip serialization with class_name."""
|
| 408 |
+
original = EnvironmentInfo(
|
| 409 |
+
game_id="tg61-28585068",
|
| 410 |
+
title="TG61",
|
| 411 |
+
tags=["tag1"],
|
| 412 |
+
baseline_actions=[12],
|
| 413 |
+
class_name="MyGameClass",
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
json_str = original.model_dump_json()
|
| 417 |
+
restored = EnvironmentInfo.model_validate_json(json_str)
|
| 418 |
+
|
| 419 |
+
self.assertEqual(original.class_name, restored.class_name)
|
| 420 |
+
|
| 421 |
+
def test_class_name_from_dict(self):
|
| 422 |
+
"""Test creating EnvironmentInfo with class_name from dictionary."""
|
| 423 |
+
data = {
|
| 424 |
+
"game_id": "tg61-28585068",
|
| 425 |
+
"title": "TG61",
|
| 426 |
+
"tags": ["tag1"],
|
| 427 |
+
"baseline_actions": [12],
|
| 428 |
+
"class_name": "MyGameClass",
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
env_info = EnvironmentInfo(**data)
|
| 432 |
+
|
| 433 |
+
self.assertEqual(env_info.class_name, "MyGameClass")
|
| 434 |
+
|
| 435 |
+
def test_class_name_empty_string(self):
|
| 436 |
+
"""Test that class_name can be an empty string (explicit override)."""
|
| 437 |
+
env_info = EnvironmentInfo(
|
| 438 |
+
game_id="tg61-28585068",
|
| 439 |
+
title="TG61",
|
| 440 |
+
tags=["tag1"],
|
| 441 |
+
baseline_actions=[12],
|
| 442 |
+
class_name="",
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
self.assertEqual(env_info.class_name, "")
|
| 446 |
+
|
| 447 |
+
def test_class_name_various_game_ids(self):
|
| 448 |
+
"""Test class_name generation from various game_id formats."""
|
| 449 |
+
test_cases = [
|
| 450 |
+
("ls20-ajk315135", "Ls20"),
|
| 451 |
+
("tg61-28585068", "Tg61"),
|
| 452 |
+
("dr44", "Dr44"),
|
| 453 |
+
("ab1", "Ab1"),
|
| 454 |
+
("a", "A"),
|
| 455 |
+
("ABCD-123", "ABCD"), # Capitalize first letter only, keep rest as-is
|
| 456 |
+
]
|
| 457 |
+
|
| 458 |
+
for game_id, expected_class_name in test_cases:
|
| 459 |
+
with self.subTest(game_id=game_id):
|
| 460 |
+
env_info = EnvironmentInfo(
|
| 461 |
+
game_id=game_id,
|
| 462 |
+
title="Test",
|
| 463 |
+
tags=["tag1"],
|
| 464 |
+
baseline_actions=[12],
|
| 465 |
+
)
|
| 466 |
+
self.assertEqual(env_info.class_name, expected_class_name)
|
| 467 |
+
|
| 468 |
+
def test_date_downloaded_and_class_name_both_default(self):
|
| 469 |
+
"""Test that both defaults work together."""
|
| 470 |
+
env_info = EnvironmentInfo(
|
| 471 |
+
game_id="ls20-test",
|
| 472 |
+
title="Test",
|
| 473 |
+
tags=["tag1"],
|
| 474 |
+
baseline_actions=[12],
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
self.assertIsNotNone(env_info.date_downloaded)
|
| 478 |
+
self.assertIsInstance(env_info.date_downloaded, datetime)
|
| 479 |
+
self.assertEqual(env_info.class_name, "Ls20")
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
if __name__ == "__main__":
|
| 483 |
+
unittest.main()
|
arcprize__ARC-AGI/tests/test_scorecard.py
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for scorecard functionality using unittest."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from unittest.mock import MagicMock
|
| 9 |
+
|
| 10 |
+
# Create a mock dotenv module before any imports
|
| 11 |
+
_mock_dotenv = MagicMock()
|
| 12 |
+
_mock_dotenv.load_dotenv = MagicMock()
|
| 13 |
+
sys.modules["dotenv"] = _mock_dotenv
|
| 14 |
+
|
| 15 |
+
# Now import arcagi3 - the mock will be used instead of real dotenv
|
| 16 |
+
from arcengine import GameAction, GameState # noqa: E402
|
| 17 |
+
|
| 18 |
+
from arc_agi import ( # noqa: E402
|
| 19 |
+
Arcade,
|
| 20 |
+
EnvironmentInfo,
|
| 21 |
+
EnvironmentScore,
|
| 22 |
+
EnvironmentScoreCalculator,
|
| 23 |
+
EnvironmentScorecard,
|
| 24 |
+
OperationMode, # noqa: E402
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestScorecard(unittest.TestCase):
|
| 29 |
+
"""Test scorecard functionality."""
|
| 30 |
+
|
| 31 |
+
def setUp(self):
|
| 32 |
+
"""Set up test fixtures."""
|
| 33 |
+
self.env_vars_to_clear = [
|
| 34 |
+
"ARC_API_KEY",
|
| 35 |
+
"ARC_BASE_URL",
|
| 36 |
+
"OFFLINE_ONLY",
|
| 37 |
+
"ONLINE_ONLY",
|
| 38 |
+
"COMPETITION_MODE",
|
| 39 |
+
"LISTEN_BINDINGS",
|
| 40 |
+
"ENVIRONMENTS_DIR",
|
| 41 |
+
]
|
| 42 |
+
for var in self.env_vars_to_clear:
|
| 43 |
+
os.environ.pop(var, None)
|
| 44 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 45 |
+
|
| 46 |
+
# Set up logger
|
| 47 |
+
self.logger = logging.getLogger("test")
|
| 48 |
+
self.logger.setLevel(logging.INFO)
|
| 49 |
+
|
| 50 |
+
# Set environments_dir to test_environment_files
|
| 51 |
+
test_dir = Path(__file__).parent.parent / "test_environment_files"
|
| 52 |
+
self.environments_dir = str(test_dir)
|
| 53 |
+
|
| 54 |
+
def tearDown(self):
|
| 55 |
+
"""Clean up after tests."""
|
| 56 |
+
for var in self.env_vars_to_clear:
|
| 57 |
+
os.environ.pop(var, None)
|
| 58 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 59 |
+
|
| 60 |
+
def test_scorecard_bt11_four_action3(self):
|
| 61 |
+
"""Test that playing bt11 with 4 Action3 actions results in levels_completed = 1."""
|
| 62 |
+
client = Arcade(
|
| 63 |
+
operation_mode=OperationMode.OFFLINE,
|
| 64 |
+
environments_dir=self.environments_dir,
|
| 65 |
+
logger=self.logger,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Create a scorecard
|
| 69 |
+
scorecard_id = client.create_scorecard()
|
| 70 |
+
self.assertIsNotNone(scorecard_id)
|
| 71 |
+
self.logger.info(f"Created scorecard: {scorecard_id}")
|
| 72 |
+
|
| 73 |
+
# Make the environment
|
| 74 |
+
wrapper = client.make(game_id="bt11", scorecard_id=scorecard_id)
|
| 75 |
+
self.assertIsNotNone(wrapper)
|
| 76 |
+
|
| 77 |
+
# Reset the game
|
| 78 |
+
self.assertIsNotNone(wrapper.observation_space)
|
| 79 |
+
self.assertEqual(wrapper.observation_space.state, GameState.NOT_FINISHED)
|
| 80 |
+
|
| 81 |
+
# Perform four ACTION3 (move left) actions
|
| 82 |
+
for i in range(4):
|
| 83 |
+
frame_data = wrapper.step(GameAction.ACTION3)
|
| 84 |
+
self.assertIsNotNone(frame_data, f"Step {i + 1} should return FrameDataRaw")
|
| 85 |
+
self.logger.info(
|
| 86 |
+
f"Step {i + 1}: state={frame_data.state}, level={frame_data.levels_completed}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Get the scorecard and verify levels_completed
|
| 90 |
+
scorecard = client.get_scorecard(scorecard_id)
|
| 91 |
+
self.assertIsNotNone(scorecard)
|
| 92 |
+
|
| 93 |
+
# Get the card for bt11
|
| 94 |
+
bt11_card = scorecard.environments[0]
|
| 95 |
+
self.assertEqual(bt11_card.id, "bt11-fd9df0622a1a")
|
| 96 |
+
|
| 97 |
+
# Verify levels_completed is 1
|
| 98 |
+
# The card should have one guid (one play)
|
| 99 |
+
self.assertEqual(4, bt11_card.actions)
|
| 100 |
+
|
| 101 |
+
# Check levels_completed for this guid
|
| 102 |
+
self.assertEqual(
|
| 103 |
+
bt11_card.levels_completed,
|
| 104 |
+
1,
|
| 105 |
+
"levels_completed should be 1 after completing first level",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Verify the final frame also shows level 1
|
| 109 |
+
final_frame = wrapper.observation_space
|
| 110 |
+
self.assertIsNotNone(final_frame)
|
| 111 |
+
self.assertEqual(
|
| 112 |
+
final_frame.levels_completed,
|
| 113 |
+
1,
|
| 114 |
+
"Final frame should show levels_completed = 1",
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class TestEnvironmentScore(unittest.TestCase):
|
| 119 |
+
"""Test EnvironmentScore and EnvironmentScoreCalculator."""
|
| 120 |
+
|
| 121 |
+
def test_environment_score_creation(self):
|
| 122 |
+
"""Test that EnvironmentScore can be created with all fields."""
|
| 123 |
+
score = EnvironmentScore(
|
| 124 |
+
id="test-id",
|
| 125 |
+
score=85.5,
|
| 126 |
+
levels_completed=3,
|
| 127 |
+
actions=42,
|
| 128 |
+
resets=2,
|
| 129 |
+
completed=True,
|
| 130 |
+
message="Test message",
|
| 131 |
+
)
|
| 132 |
+
self.assertEqual(score.id, "test-id")
|
| 133 |
+
self.assertEqual(score.score, 85.5)
|
| 134 |
+
self.assertEqual(score.levels_completed, 3)
|
| 135 |
+
self.assertEqual(score.actions, 42)
|
| 136 |
+
self.assertEqual(score.resets, 2)
|
| 137 |
+
self.assertEqual(score.completed, True)
|
| 138 |
+
self.assertEqual(score.message, "Test message")
|
| 139 |
+
|
| 140 |
+
def test_environment_score_optional_fields(self):
|
| 141 |
+
"""Test that EnvironmentScore optional fields work correctly."""
|
| 142 |
+
# Test with all optional fields None
|
| 143 |
+
score = EnvironmentScore(
|
| 144 |
+
id="test-id",
|
| 145 |
+
score=50.0,
|
| 146 |
+
levels_completed=1,
|
| 147 |
+
actions=10,
|
| 148 |
+
)
|
| 149 |
+
self.assertIsNone(score.resets)
|
| 150 |
+
self.assertIsNone(score.completed)
|
| 151 |
+
self.assertIsNone(score.message)
|
| 152 |
+
|
| 153 |
+
# Test with resets but no completed
|
| 154 |
+
score2 = EnvironmentScore(
|
| 155 |
+
id="test-id-2",
|
| 156 |
+
score=75.0,
|
| 157 |
+
levels_completed=2,
|
| 158 |
+
actions=20,
|
| 159 |
+
resets=1,
|
| 160 |
+
)
|
| 161 |
+
self.assertEqual(score2.resets, 1)
|
| 162 |
+
self.assertIsNone(score2.completed)
|
| 163 |
+
|
| 164 |
+
# Test with completed but no resets
|
| 165 |
+
score3 = EnvironmentScore(
|
| 166 |
+
id="test-id-3",
|
| 167 |
+
score=90.0,
|
| 168 |
+
levels_completed=3,
|
| 169 |
+
actions=30,
|
| 170 |
+
completed=False,
|
| 171 |
+
)
|
| 172 |
+
self.assertIsNone(score3.resets)
|
| 173 |
+
self.assertEqual(score3.completed, False)
|
| 174 |
+
|
| 175 |
+
def test_environment_score_calculator_initialization(self):
|
| 176 |
+
"""Test that EnvironmentScoreCalculator initializes correctly."""
|
| 177 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=2)
|
| 178 |
+
self.assertEqual(calculator.id, "test-id")
|
| 179 |
+
self.assertEqual(calculator.resets, 2)
|
| 180 |
+
self.assertEqual(calculator.level_scores, [])
|
| 181 |
+
self.assertEqual(calculator.levels_completed, 0)
|
| 182 |
+
self.assertEqual(calculator.actions, 0)
|
| 183 |
+
self.assertIsNone(calculator.completed)
|
| 184 |
+
|
| 185 |
+
def test_environment_score_calculator_optional_resets(self):
|
| 186 |
+
"""Test that EnvironmentScoreCalculator can be initialized without resets."""
|
| 187 |
+
calculator = EnvironmentScoreCalculator(id="test-id")
|
| 188 |
+
self.assertEqual(calculator.id, "test-id")
|
| 189 |
+
self.assertIsNone(calculator.resets)
|
| 190 |
+
|
| 191 |
+
def test_add_level_completed(self):
|
| 192 |
+
"""Test add_level with completed=True calculates score correctly."""
|
| 193 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 194 |
+
|
| 195 |
+
# Baseline: 10 actions, taken: 5 actions -> score = (10/5) * 100 = 200, capped at 115
|
| 196 |
+
calculator.add_level(
|
| 197 |
+
level_index=1, completed=True, actions_taken=5, baseline_actions=10
|
| 198 |
+
)
|
| 199 |
+
self.assertEqual(calculator.levels_completed, 1)
|
| 200 |
+
self.assertEqual(calculator.actions, 5)
|
| 201 |
+
self.assertEqual(len(calculator.level_scores), 1)
|
| 202 |
+
self.assertEqual(calculator.level_scores[0], 115.0) # Capped at 100
|
| 203 |
+
|
| 204 |
+
def test_add_level_completed_exact_baseline(self):
|
| 205 |
+
"""Test add_level with actions_taken equal to baseline."""
|
| 206 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 207 |
+
|
| 208 |
+
# Baseline: 10 actions, taken: 10 actions -> score = (10/10) * 100 = 100
|
| 209 |
+
calculator.add_level(
|
| 210 |
+
level_index=1, completed=True, actions_taken=10, baseline_actions=10
|
| 211 |
+
)
|
| 212 |
+
self.assertEqual(calculator.levels_completed, 1)
|
| 213 |
+
self.assertEqual(calculator.actions, 10)
|
| 214 |
+
self.assertEqual(calculator.level_scores[0], 100.0)
|
| 215 |
+
|
| 216 |
+
def test_add_level_completed_below_baseline(self):
|
| 217 |
+
"""Test add_level with actions_taken below baseline."""
|
| 218 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 219 |
+
|
| 220 |
+
# Baseline: 10 actions, taken: 8 actions -> score = (10/8) * 100 = 125, capped at 115
|
| 221 |
+
calculator.add_level(
|
| 222 |
+
level_index=1, completed=True, actions_taken=8, baseline_actions=10
|
| 223 |
+
)
|
| 224 |
+
self.assertEqual(calculator.level_scores[0], 115.0) # Capped at 115
|
| 225 |
+
|
| 226 |
+
def test_add_level_completed_above_baseline(self):
|
| 227 |
+
"""Test add_level with actions_taken above baseline."""
|
| 228 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 229 |
+
|
| 230 |
+
# Baseline: 10 actions, taken: 20 actions -> score = (10/20) * 100 = 50
|
| 231 |
+
calculator.add_level(
|
| 232 |
+
level_index=1, completed=True, actions_taken=20, baseline_actions=10
|
| 233 |
+
)
|
| 234 |
+
self.assertEqual(calculator.level_scores[0], 25.0)
|
| 235 |
+
|
| 236 |
+
def test_add_level_not_completed(self):
|
| 237 |
+
"""Test add_level with completed=False appends 0."""
|
| 238 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 239 |
+
|
| 240 |
+
calculator.add_level(
|
| 241 |
+
level_index=1, completed=False, actions_taken=15, baseline_actions=10
|
| 242 |
+
)
|
| 243 |
+
self.assertEqual(calculator.levels_completed, 0) # Not incremented
|
| 244 |
+
self.assertEqual(calculator.actions, 15) # Still added to total
|
| 245 |
+
self.assertEqual(len(calculator.level_scores), 1)
|
| 246 |
+
self.assertEqual(calculator.level_scores[0], 0.0)
|
| 247 |
+
|
| 248 |
+
def test_add_level_zero_actions(self):
|
| 249 |
+
"""Test add_level with zero actions_taken."""
|
| 250 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 251 |
+
|
| 252 |
+
calculator.add_level(
|
| 253 |
+
level_index=1, completed=True, actions_taken=0, baseline_actions=10
|
| 254 |
+
)
|
| 255 |
+
self.assertEqual(calculator.levels_completed, 1)
|
| 256 |
+
self.assertEqual(calculator.actions, 0)
|
| 257 |
+
self.assertEqual(
|
| 258 |
+
calculator.level_scores[0], 0.0
|
| 259 |
+
) # Should be 0 if actions_taken is 0
|
| 260 |
+
|
| 261 |
+
def test_add_level_multiple_levels(self):
|
| 262 |
+
"""Test adding multiple levels."""
|
| 263 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=0)
|
| 264 |
+
|
| 265 |
+
# Level 1: completed with 8 actions (baseline 10) -> score = 125, capped at 115
|
| 266 |
+
calculator.add_level(
|
| 267 |
+
level_index=1, completed=True, actions_taken=8, baseline_actions=10
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Level 2: completed with 12 actions (baseline 10) -> score = (10/12) * 100 = 83.33 ^ 2 = 69.44444444444444
|
| 271 |
+
calculator.add_level(
|
| 272 |
+
level_index=2, completed=True, actions_taken=12, baseline_actions=10
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
# Level 3: not completed
|
| 276 |
+
calculator.add_level(
|
| 277 |
+
level_index=3, completed=False, actions_taken=5, baseline_actions=10
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
self.assertEqual(calculator.levels_completed, 2)
|
| 281 |
+
self.assertEqual(calculator.actions, 25) # 8 + 12 + 5
|
| 282 |
+
self.assertEqual(len(calculator.level_scores), 3)
|
| 283 |
+
self.assertEqual(calculator.level_scores[0], 115.0)
|
| 284 |
+
self.assertAlmostEqual(calculator.level_scores[1], 69.44444444444444, places=5)
|
| 285 |
+
self.assertEqual(calculator.level_scores[2], 0.0)
|
| 286 |
+
|
| 287 |
+
def test_to_score_average(self):
|
| 288 |
+
"""Test that to_score calculates average of level_scores."""
|
| 289 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=2)
|
| 290 |
+
|
| 291 |
+
calculator.add_level(
|
| 292 |
+
level_index=1, completed=True, actions_taken=10, baseline_actions=10
|
| 293 |
+
) # score = 100
|
| 294 |
+
calculator.add_level(
|
| 295 |
+
level_index=2, completed=True, actions_taken=20, baseline_actions=10
|
| 296 |
+
) # score = 50
|
| 297 |
+
calculator.add_level(
|
| 298 |
+
level_index=3, completed=False, actions_taken=5, baseline_actions=10
|
| 299 |
+
) # score = 0
|
| 300 |
+
calculator.completed = True # Set completed flag
|
| 301 |
+
|
| 302 |
+
score = calculator.to_score()
|
| 303 |
+
self.assertIsInstance(score, EnvironmentScore)
|
| 304 |
+
self.assertEqual(score.id, "test-id")
|
| 305 |
+
self.assertEqual(score.resets, 2)
|
| 306 |
+
self.assertEqual(score.completed, True)
|
| 307 |
+
self.assertEqual(score.levels_completed, 2)
|
| 308 |
+
self.assertEqual(score.actions, 35) # 10 + 20 + 5
|
| 309 |
+
# Average: (100 + 25*2 + 0*3) / (1+2+3) = 50.0
|
| 310 |
+
self.assertAlmostEqual(score.score, 25.0, places=5)
|
| 311 |
+
|
| 312 |
+
def test_to_score_empty_levels(self):
|
| 313 |
+
"""Test to_score with no levels added."""
|
| 314 |
+
calculator = EnvironmentScoreCalculator(id="test-id")
|
| 315 |
+
|
| 316 |
+
score = calculator.to_score()
|
| 317 |
+
self.assertEqual(score.id, "test-id")
|
| 318 |
+
self.assertEqual(score.score, 0.0)
|
| 319 |
+
self.assertEqual(score.levels_completed, 0)
|
| 320 |
+
self.assertEqual(score.actions, 0)
|
| 321 |
+
self.assertIsNone(score.resets)
|
| 322 |
+
self.assertIsNone(score.completed)
|
| 323 |
+
|
| 324 |
+
def test_to_score_single_level(self):
|
| 325 |
+
"""Test to_score with single level."""
|
| 326 |
+
calculator = EnvironmentScoreCalculator(id="test-id", resets=1)
|
| 327 |
+
|
| 328 |
+
calculator.add_level(
|
| 329 |
+
level_index=1, completed=True, actions_taken=15, baseline_actions=10
|
| 330 |
+
)
|
| 331 |
+
calculator.completed = False # Set completed flag
|
| 332 |
+
|
| 333 |
+
score = calculator.to_score()
|
| 334 |
+
self.assertEqual(
|
| 335 |
+
score.score, ((10 / 15) ** 2) * 100
|
| 336 |
+
) # Should be exact value, not average of one
|
| 337 |
+
self.assertEqual(score.levels_completed, 1)
|
| 338 |
+
self.assertEqual(score.actions, 15)
|
| 339 |
+
self.assertEqual(score.resets, 1)
|
| 340 |
+
self.assertEqual(score.completed, False)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TestEnvironmentScorecard(unittest.TestCase):
|
| 344 |
+
"""Test EnvironmentScorecard functionality."""
|
| 345 |
+
|
| 346 |
+
def setUp(self):
|
| 347 |
+
"""Set up test fixtures."""
|
| 348 |
+
self.env_vars_to_clear = [
|
| 349 |
+
"ARC_API_KEY",
|
| 350 |
+
"ARC_BASE_URL",
|
| 351 |
+
"OFFLINE_ONLY",
|
| 352 |
+
"ONLINE_ONLY",
|
| 353 |
+
"COMPETITION_MODE",
|
| 354 |
+
"LISTEN_BINDINGS",
|
| 355 |
+
"ENVIRONMENTS_DIR",
|
| 356 |
+
]
|
| 357 |
+
for var in self.env_vars_to_clear:
|
| 358 |
+
os.environ.pop(var, None)
|
| 359 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 360 |
+
|
| 361 |
+
def tearDown(self):
|
| 362 |
+
"""Clean up after tests."""
|
| 363 |
+
for var in self.env_vars_to_clear:
|
| 364 |
+
os.environ.pop(var, None)
|
| 365 |
+
os.environ["ARC_API_KEY"] = "test-key-123"
|
| 366 |
+
|
| 367 |
+
def test_from_scorecard_basic(self):
|
| 368 |
+
"""Test basic EnvironmentScorecard creation."""
|
| 369 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 370 |
+
|
| 371 |
+
# Create a simple scorecard with one game
|
| 372 |
+
card = Card(
|
| 373 |
+
game_id="bt11",
|
| 374 |
+
total_plays=1,
|
| 375 |
+
guids=["guid1"],
|
| 376 |
+
levels_completed=[1],
|
| 377 |
+
actions=[10],
|
| 378 |
+
resets=[0],
|
| 379 |
+
states=[GameState.WIN],
|
| 380 |
+
actions_by_level=[[(1, 10)]],
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
scorecard = Scorecard(
|
| 384 |
+
card_id="test-card",
|
| 385 |
+
api_key="test-key",
|
| 386 |
+
cards={"bt11": card},
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
env_info = EnvironmentInfo(
|
| 390 |
+
game_id="bt11",
|
| 391 |
+
title="BT11",
|
| 392 |
+
baseline_actions=[10],
|
| 393 |
+
tags=["test"],
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 397 |
+
|
| 398 |
+
self.assertEqual(scorecard_result.card_id, "test-card")
|
| 399 |
+
self.assertEqual(scorecard_result.api_key, "test-key")
|
| 400 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 401 |
+
self.assertEqual(scorecard_result.environments[0].id, "bt11")
|
| 402 |
+
self.assertEqual(scorecard_result.environments[0].levels_completed, 1)
|
| 403 |
+
# Score should be (10/10) * 100 = 100
|
| 404 |
+
self.assertAlmostEqual(scorecard_result.environments[0].score, 100.0, places=5)
|
| 405 |
+
self.assertEqual(scorecard_result.score, 100.0) # Average of one score
|
| 406 |
+
|
| 407 |
+
def test_max_score_is_last_level_beaten(self):
|
| 408 |
+
"""Test basic EnvironmentScorecard creation."""
|
| 409 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 410 |
+
|
| 411 |
+
# Create a simple scorecard with one game
|
| 412 |
+
card = Card(
|
| 413 |
+
game_id="bt11",
|
| 414 |
+
total_plays=1,
|
| 415 |
+
guids=["guid1"],
|
| 416 |
+
levels_completed=[1],
|
| 417 |
+
actions=[28],
|
| 418 |
+
resets=[0],
|
| 419 |
+
states=[GameState.NOT_FINISHED],
|
| 420 |
+
actions_by_level=[[(1, 8)]],
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
scorecard = Scorecard(
|
| 424 |
+
card_id="test-card",
|
| 425 |
+
api_key="test-key",
|
| 426 |
+
cards={"bt11": card},
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
env_info = EnvironmentInfo(
|
| 430 |
+
game_id="bt11",
|
| 431 |
+
title="BT11",
|
| 432 |
+
baseline_actions=[10, 10, 10, 10, 10, 10],
|
| 433 |
+
tags=["test"],
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
for i in range(1, 7):
|
| 437 |
+
card.levels_completed[0] = i
|
| 438 |
+
card.actions[0] = i * 8 + 10
|
| 439 |
+
card.actions_by_level[0] = []
|
| 440 |
+
for j in range(1, i + 1):
|
| 441 |
+
card.actions_by_level[0].append((j, j * 8))
|
| 442 |
+
|
| 443 |
+
expected_score = 0
|
| 444 |
+
match i:
|
| 445 |
+
case 1:
|
| 446 |
+
expected_score = 4.76190 # 1/21
|
| 447 |
+
case 2:
|
| 448 |
+
expected_score = 14.28571 # 3/21
|
| 449 |
+
case 3:
|
| 450 |
+
expected_score = 28.57143 # 6/21
|
| 451 |
+
case 4:
|
| 452 |
+
expected_score = 47.61905 # 10/21
|
| 453 |
+
case 5:
|
| 454 |
+
expected_score = 71.42857 # 15/21
|
| 455 |
+
case 6:
|
| 456 |
+
expected_score = 100.0 # 21/21
|
| 457 |
+
|
| 458 |
+
print(f"card {i}: {card}")
|
| 459 |
+
|
| 460 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 461 |
+
scorecard, [env_info]
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
print(f"scorecard_result {i}: {scorecard_result}")
|
| 465 |
+
self.assertEqual(scorecard_result.environments[0].id, "bt11")
|
| 466 |
+
self.assertEqual(scorecard_result.environments[0].levels_completed, i)
|
| 467 |
+
self.assertAlmostEqual(
|
| 468 |
+
scorecard_result.environments[0].score, expected_score, places=3
|
| 469 |
+
)
|
| 470 |
+
self.assertAlmostEqual(scorecard_result.score, expected_score, places=3)
|
| 471 |
+
|
| 472 |
+
def test_from_scorecard_with_level_tags(self):
|
| 473 |
+
"""Test basic EnvironmentScorecard creation."""
|
| 474 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 475 |
+
|
| 476 |
+
# Create a simple scorecard with one game
|
| 477 |
+
card = Card(
|
| 478 |
+
game_id="bt11",
|
| 479 |
+
total_plays=1,
|
| 480 |
+
guids=["guid1"],
|
| 481 |
+
levels_completed=[5],
|
| 482 |
+
actions=[50],
|
| 483 |
+
resets=[0],
|
| 484 |
+
states=[GameState.WIN],
|
| 485 |
+
actions_by_level=[[(1, 10), (2, 20), (3, 30), (4, 40), (5, 45)]],
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
scorecard = Scorecard(
|
| 489 |
+
card_id="test-card",
|
| 490 |
+
api_key="test-key",
|
| 491 |
+
cards={"bt11": card},
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
env_info = EnvironmentInfo(
|
| 495 |
+
game_id="bt11",
|
| 496 |
+
title="BT11",
|
| 497 |
+
baseline_actions=[10, 5, 5, 5, 5],
|
| 498 |
+
tags=["test"],
|
| 499 |
+
level_tags=[[], ["new_mechanic"], [], ["new_mechanic"], ["new_mechanic"]],
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 503 |
+
scorecard, [env_info], do_private_tags=True
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
# Score should be (10/10) * 100 = 100
|
| 507 |
+
self.assertAlmostEqual(scorecard_result.environments[0].score, 55.0, places=5)
|
| 508 |
+
self.assertAlmostEqual(scorecard_result.score, 55.0) # Average of one score
|
| 509 |
+
|
| 510 |
+
tags_by_id = {s.id: s for s in scorecard_result.tags_scores}
|
| 511 |
+
|
| 512 |
+
# Check that shared tag has aggregated scores from both games
|
| 513 |
+
if "private_new_mechanic" in tags_by_id:
|
| 514 |
+
tag_score = tags_by_id["private_new_mechanic"]
|
| 515 |
+
# Should have 2 levels completed (one from each game)
|
| 516 |
+
self.assertEqual(tag_score.levels_completed, 3)
|
| 517 |
+
# new_mechanic score should be (25*2 + 25*4 + 100*5) / 11
|
| 518 |
+
self.assertAlmostEqual(tag_score.score, 59.09090909, places=5)
|
| 519 |
+
else:
|
| 520 |
+
self.fail("private_new_mechanic tag not found")
|
| 521 |
+
|
| 522 |
+
def test_from_scorecard_highest_levels_completed(self):
|
| 523 |
+
"""Test that only the play with highest levels_completed is used."""
|
| 524 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 525 |
+
|
| 526 |
+
# Create a card with multiple plays, where second has higher levels_completed
|
| 527 |
+
card = Card(
|
| 528 |
+
game_id="bt11",
|
| 529 |
+
total_plays=2,
|
| 530 |
+
guids=["guid1", "guid2"],
|
| 531 |
+
levels_completed=[1, 2], # guid2 has higher levels_completed
|
| 532 |
+
actions=[10, 20],
|
| 533 |
+
resets=[0, 0],
|
| 534 |
+
states=[GameState.WIN, GameState.WIN],
|
| 535 |
+
actions_by_level=[[(1, 10)], [(1, 10), (2, 20)]],
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
scorecard = Scorecard(
|
| 539 |
+
card_id="test-card",
|
| 540 |
+
api_key="test-key",
|
| 541 |
+
cards={"bt11": card},
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
env_info = EnvironmentInfo(
|
| 545 |
+
game_id="bt11",
|
| 546 |
+
title="BT11",
|
| 547 |
+
baseline_actions=[10, 15],
|
| 548 |
+
tags=["test"],
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 552 |
+
# Should only have one environment score (for guid2)
|
| 553 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 554 |
+
self.assertEqual(scorecard_result.environments[0].id, "bt11")
|
| 555 |
+
self.assertEqual(scorecard_result.environments[0].levels_completed, 2)
|
| 556 |
+
self.assertEqual(scorecard_result.environments[0].runs[1].guid, "guid2")
|
| 557 |
+
|
| 558 |
+
def test_from_scorecard_multiple_games(self):
|
| 559 |
+
"""Test EnvironmentScorecard with multiple games."""
|
| 560 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 561 |
+
|
| 562 |
+
card1 = Card(
|
| 563 |
+
game_id="bt11",
|
| 564 |
+
total_plays=1,
|
| 565 |
+
guids=["guid1"],
|
| 566 |
+
levels_completed=[1],
|
| 567 |
+
actions=[10],
|
| 568 |
+
resets=[0],
|
| 569 |
+
states=[GameState.WIN],
|
| 570 |
+
actions_by_level=[[(1, 10)]],
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
card2 = Card(
|
| 574 |
+
game_id="am92",
|
| 575 |
+
total_plays=1,
|
| 576 |
+
guids=["guid2"],
|
| 577 |
+
levels_completed=[2],
|
| 578 |
+
actions=[30],
|
| 579 |
+
resets=[1],
|
| 580 |
+
states=[GameState.WIN],
|
| 581 |
+
actions_by_level=[[(1, 15), (2, 30)]],
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
scorecard = Scorecard(
|
| 585 |
+
card_id="test-card",
|
| 586 |
+
api_key="test-key",
|
| 587 |
+
cards={"bt11": card1, "am92": card2},
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
env_info1 = EnvironmentInfo(
|
| 591 |
+
game_id="bt11",
|
| 592 |
+
title="BT11",
|
| 593 |
+
baseline_actions=[10],
|
| 594 |
+
tags=["tag1"],
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
env_info2 = EnvironmentInfo(
|
| 598 |
+
game_id="am92",
|
| 599 |
+
title="AM92",
|
| 600 |
+
baseline_actions=[15, 20],
|
| 601 |
+
tags=["tag2"],
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 605 |
+
scorecard, [env_info1, env_info2]
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
self.assertEqual(len(scorecard_result.environments), 2)
|
| 609 |
+
# Find scores by id
|
| 610 |
+
scores_by_id = {s.id: s for s in scorecard_result.environments}
|
| 611 |
+
self.assertIn("bt11", scores_by_id)
|
| 612 |
+
self.assertIn("am92", scores_by_id)
|
| 613 |
+
|
| 614 |
+
# bt11 score: (10/10) * 100 = 100
|
| 615 |
+
self.assertAlmostEqual(scores_by_id["bt11"].score, 100.0, places=5)
|
| 616 |
+
# am92 score: average of level 1 ((15/15)*100=100) and level 2 ((20/15)*100=133.33, capped at 100)
|
| 617 |
+
# Actually wait, let me recalculate: level 1 took 15 actions (baseline 15) = 100, level 2 took 15 actions (baseline 20) = (20/15)*100 = 133.33 capped at 100
|
| 618 |
+
# So average = (100 + 100) / 2 = 100
|
| 619 |
+
self.assertAlmostEqual(scores_by_id["am92"].score, 100.0, places=5)
|
| 620 |
+
|
| 621 |
+
# Average score should be (100 + 100) / 2 = 100
|
| 622 |
+
self.assertAlmostEqual(scorecard_result.score, 100.0, places=5)
|
| 623 |
+
|
| 624 |
+
def test_from_scorecard_missing_baseline_actions(self):
|
| 625 |
+
"""Test handling of missing baseline_actions."""
|
| 626 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 627 |
+
|
| 628 |
+
card = Card(
|
| 629 |
+
game_id="bt11",
|
| 630 |
+
total_plays=1,
|
| 631 |
+
guids=["guid1"],
|
| 632 |
+
levels_completed=[1],
|
| 633 |
+
actions=[10],
|
| 634 |
+
resets=[0],
|
| 635 |
+
states=[GameState.WIN],
|
| 636 |
+
actions_by_level=[[(1, 10)]],
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
scorecard = Scorecard(
|
| 640 |
+
card_id="test-card",
|
| 641 |
+
api_key="test-key",
|
| 642 |
+
cards={"bt11": card},
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
# EnvironmentInfo without baseline_actions
|
| 646 |
+
env_info = EnvironmentInfo(
|
| 647 |
+
game_id="bt11",
|
| 648 |
+
title="BT11",
|
| 649 |
+
baseline_actions=None,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 653 |
+
|
| 654 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 655 |
+
score = scorecard_result.environments[0]
|
| 656 |
+
self.assertEqual(score.score, 0.0)
|
| 657 |
+
self.assertEqual(
|
| 658 |
+
score.runs[0].message,
|
| 659 |
+
"Human baseline actions are not available for this environment",
|
| 660 |
+
)
|
| 661 |
+
self.assertEqual(score.levels_completed, 1)
|
| 662 |
+
|
| 663 |
+
def test_from_scorecard_baseline_size_mismatch(self):
|
| 664 |
+
"""Test handling of baseline_actions size mismatch."""
|
| 665 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 666 |
+
|
| 667 |
+
card = Card(
|
| 668 |
+
game_id="bt11",
|
| 669 |
+
total_plays=1,
|
| 670 |
+
guids=["guid1"],
|
| 671 |
+
levels_completed=[3], # Completed 3 levels
|
| 672 |
+
actions=[30],
|
| 673 |
+
resets=[0],
|
| 674 |
+
states=[GameState.WIN],
|
| 675 |
+
actions_by_level=[[(1, 10), (2, 20), (3, 30)]],
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
scorecard = Scorecard(
|
| 679 |
+
card_id="test-card",
|
| 680 |
+
api_key="test-key",
|
| 681 |
+
cards={"bt11": card},
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
# EnvironmentInfo with fewer baseline_actions than levels_completed
|
| 685 |
+
env_info = EnvironmentInfo(
|
| 686 |
+
game_id="bt11",
|
| 687 |
+
title="BT11",
|
| 688 |
+
baseline_actions=[10, 15], # Only 2 baselines, but 3 levels completed
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 692 |
+
|
| 693 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 694 |
+
score = scorecard_result.environments[0]
|
| 695 |
+
self.assertEqual(score.score, 0.0)
|
| 696 |
+
self.assertEqual(score.runs[0].message, "Human baseline actions size mismatch")
|
| 697 |
+
self.assertEqual(score.levels_completed, 3)
|
| 698 |
+
|
| 699 |
+
def test_from_scorecard_tags_scores(self):
|
| 700 |
+
"""Test that tags_scores are computed correctly."""
|
| 701 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 702 |
+
|
| 703 |
+
card1 = Card(
|
| 704 |
+
game_id="bt11",
|
| 705 |
+
total_plays=1,
|
| 706 |
+
guids=["guid1"],
|
| 707 |
+
levels_completed=[1],
|
| 708 |
+
actions=[10],
|
| 709 |
+
resets=[0],
|
| 710 |
+
states=[GameState.WIN],
|
| 711 |
+
actions_by_level=[[(1, 20)]],
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
card2 = Card(
|
| 715 |
+
game_id="am92",
|
| 716 |
+
total_plays=1,
|
| 717 |
+
guids=["guid2"],
|
| 718 |
+
levels_completed=[1],
|
| 719 |
+
actions=[15],
|
| 720 |
+
resets=[0],
|
| 721 |
+
states=[GameState.WIN],
|
| 722 |
+
actions_by_level=[[(1, 25)]],
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
scorecard = Scorecard(
|
| 726 |
+
card_id="test-card",
|
| 727 |
+
api_key="test-key",
|
| 728 |
+
cards={"bt11": card1, "am92": card2},
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
env_info1 = EnvironmentInfo(
|
| 732 |
+
game_id="bt11",
|
| 733 |
+
title="BT11",
|
| 734 |
+
baseline_actions=[10],
|
| 735 |
+
tags=["tag1", "shared"], # Has shared tag
|
| 736 |
+
private_tags=["secret"],
|
| 737 |
+
level_tags=[["new_mechanic"]],
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
env_info2 = EnvironmentInfo(
|
| 741 |
+
game_id="am92",
|
| 742 |
+
title="AM92",
|
| 743 |
+
baseline_actions=[15],
|
| 744 |
+
tags=["tag2", "shared"], # Also has shared tag
|
| 745 |
+
private_tags=["secret"],
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 749 |
+
scorecard, [env_info1, env_info2], do_private_tags=True
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
# Should have tag scores for tag1, tag2, and shared
|
| 753 |
+
self.assertGreater(len(scorecard_result.tags_scores), 0)
|
| 754 |
+
tags_by_id = {s.id: s for s in scorecard_result.tags_scores}
|
| 755 |
+
|
| 756 |
+
# Check that shared tag has aggregated scores from both games
|
| 757 |
+
if "shared" in tags_by_id:
|
| 758 |
+
shared_score = tags_by_id["shared"]
|
| 759 |
+
# Should have 2 levels completed (one from each game)
|
| 760 |
+
self.assertEqual(shared_score.levels_completed, 2)
|
| 761 |
+
# Score should be average of both: bt11 (10/10)*100=100, am92 (15/15)*100=100, avg=100
|
| 762 |
+
self.assertAlmostEqual(shared_score.score, 30.5, places=5)
|
| 763 |
+
else:
|
| 764 |
+
self.fail("shared tag not found")
|
| 765 |
+
if "tag1" in tags_by_id:
|
| 766 |
+
shared_score = tags_by_id["tag1"]
|
| 767 |
+
# Should have 2 levels completed (one from each game)
|
| 768 |
+
self.assertEqual(shared_score.levels_completed, 1)
|
| 769 |
+
# Score should be average of both: bt11 (10/10)*100=100, am92 (15/15)*100=100, avg=100
|
| 770 |
+
self.assertAlmostEqual(shared_score.score, 25.0, places=5)
|
| 771 |
+
else:
|
| 772 |
+
self.fail("tag1 tag not found")
|
| 773 |
+
if "tag2" in tags_by_id:
|
| 774 |
+
shared_score = tags_by_id["tag2"]
|
| 775 |
+
# Should have 2 levels completed (one from each game)
|
| 776 |
+
self.assertEqual(shared_score.levels_completed, 1)
|
| 777 |
+
# Score should be average of both: bt11 (10/10)*100=100, am92 (15/15)*100=100, avg=100
|
| 778 |
+
self.assertAlmostEqual(shared_score.score, 36.0, places=5)
|
| 779 |
+
else:
|
| 780 |
+
self.fail("tag2 tag not found")
|
| 781 |
+
if "private_secret" in tags_by_id:
|
| 782 |
+
shared_score = tags_by_id["private_secret"]
|
| 783 |
+
# Should have 2 levels completed (one from each game)
|
| 784 |
+
self.assertEqual(shared_score.levels_completed, 2)
|
| 785 |
+
# Score should be average of both: bt11 (10/10)*100=100, am92 (15/15)*100=100, avg=100
|
| 786 |
+
self.assertAlmostEqual(shared_score.score, 30.5, places=5)
|
| 787 |
+
else:
|
| 788 |
+
self.fail("private_secret tag not found")
|
| 789 |
+
|
| 790 |
+
def test_not_completed_games(self):
|
| 791 |
+
"""Test that tags_scores are computed correctly."""
|
| 792 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 793 |
+
|
| 794 |
+
card1 = Card(
|
| 795 |
+
game_id="bt11",
|
| 796 |
+
total_plays=1,
|
| 797 |
+
guids=["guid1"],
|
| 798 |
+
levels_completed=[1],
|
| 799 |
+
actions=[1000],
|
| 800 |
+
resets=[0],
|
| 801 |
+
states=[GameState.GAME_OVER],
|
| 802 |
+
actions_by_level=[[(1, 20)]],
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
card2 = Card(
|
| 806 |
+
game_id="am92",
|
| 807 |
+
total_plays=1,
|
| 808 |
+
guids=["guid2"],
|
| 809 |
+
levels_completed=[1],
|
| 810 |
+
actions=[1000],
|
| 811 |
+
resets=[0],
|
| 812 |
+
states=[GameState.GAME_OVER],
|
| 813 |
+
actions_by_level=[[(1, 25)]],
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
scorecard = Scorecard(
|
| 817 |
+
card_id="test-card",
|
| 818 |
+
api_key="test-key",
|
| 819 |
+
cards={"bt11": card1, "am92": card2},
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
env_info1 = EnvironmentInfo(
|
| 823 |
+
game_id="bt11",
|
| 824 |
+
title="BT11",
|
| 825 |
+
baseline_actions=[10, 20],
|
| 826 |
+
tags=["tag1", "shared"], # Has shared tag
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
env_info2 = EnvironmentInfo(
|
| 830 |
+
game_id="am92",
|
| 831 |
+
title="AM92",
|
| 832 |
+
baseline_actions=[15, 30, 45],
|
| 833 |
+
tags=["tag2", "shared"], # Also has shared tag
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 837 |
+
scorecard, [env_info1, env_info2]
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
# Should have tag scores for tag1, tag2, and shared
|
| 841 |
+
self.assertGreater(len(scorecard_result.tags_scores), 0)
|
| 842 |
+
tags_by_id = {s.id: s for s in scorecard_result.tags_scores}
|
| 843 |
+
|
| 844 |
+
# Check that shared tag has aggregated scores from both games
|
| 845 |
+
if "shared" in tags_by_id:
|
| 846 |
+
shared_score = tags_by_id["shared"]
|
| 847 |
+
# Should have 2 levels completed (one from each game)
|
| 848 |
+
self.assertEqual(shared_score.levels_completed, 2)
|
| 849 |
+
self.assertAlmostEqual(shared_score.score, 6.7777777, places=5)
|
| 850 |
+
self.assertEqual(shared_score.number_of_levels, 5)
|
| 851 |
+
self.assertEqual(shared_score.number_of_environments, 2)
|
| 852 |
+
if "tag1" in tags_by_id:
|
| 853 |
+
shared_score = tags_by_id["tag1"]
|
| 854 |
+
# Should have 2 levels completed (one from each game)
|
| 855 |
+
self.assertEqual(shared_score.levels_completed, 1)
|
| 856 |
+
self.assertAlmostEqual(shared_score.score, 8.33333333334, places=5)
|
| 857 |
+
self.assertEqual(shared_score.number_of_levels, 2)
|
| 858 |
+
self.assertEqual(shared_score.number_of_environments, 1)
|
| 859 |
+
if "tag2" in tags_by_id:
|
| 860 |
+
shared_score = tags_by_id["tag2"]
|
| 861 |
+
# Should have 2 levels completed (one from each game)
|
| 862 |
+
self.assertEqual(shared_score.levels_completed, 1)
|
| 863 |
+
self.assertAlmostEqual(shared_score.score, 6.0, places=5)
|
| 864 |
+
self.assertEqual(shared_score.number_of_levels, 3)
|
| 865 |
+
self.assertEqual(shared_score.number_of_environments, 1)
|
| 866 |
+
|
| 867 |
+
def test_completed_games_average_score_calculation(self):
|
| 868 |
+
"""Test that top-level score is correctly calculated as average."""
|
| 869 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 870 |
+
|
| 871 |
+
card1 = Card(
|
| 872 |
+
game_id="bt11",
|
| 873 |
+
total_plays=1,
|
| 874 |
+
guids=["guid1"],
|
| 875 |
+
levels_completed=[1],
|
| 876 |
+
actions=[20], # 20 actions for baseline of 10 = 50% score
|
| 877 |
+
resets=[0],
|
| 878 |
+
states=[GameState.WIN],
|
| 879 |
+
actions_by_level=[[(1, 20)]],
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
card2 = Card(
|
| 883 |
+
game_id="am92",
|
| 884 |
+
total_plays=1,
|
| 885 |
+
guids=["guid2"],
|
| 886 |
+
levels_completed=[1],
|
| 887 |
+
actions=[10], # 10 actions for baseline of 10 = 100% score
|
| 888 |
+
resets=[0],
|
| 889 |
+
states=[GameState.WIN],
|
| 890 |
+
actions_by_level=[[(1, 10)]],
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
scorecard = Scorecard(
|
| 894 |
+
card_id="test-card",
|
| 895 |
+
api_key="test-key",
|
| 896 |
+
cards={"bt11": card1, "am92": card2},
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
env_info1 = EnvironmentInfo(
|
| 900 |
+
game_id="bt11",
|
| 901 |
+
title="BT11",
|
| 902 |
+
baseline_actions=[10],
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
env_info2 = EnvironmentInfo(
|
| 906 |
+
game_id="am92",
|
| 907 |
+
title="AM92",
|
| 908 |
+
baseline_actions=[10],
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(
|
| 912 |
+
scorecard, [env_info1, env_info2]
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
# bt11: (10/20)**2 * 100 = 20
|
| 916 |
+
# am92: (10/10) * 100 = 100
|
| 917 |
+
# Average: (25 + 100) / 2 = 75
|
| 918 |
+
self.assertAlmostEqual(scorecard_result.score, 62.5, places=5)
|
| 919 |
+
|
| 920 |
+
def test_from_scorecard_empty_scorecard(self):
|
| 921 |
+
"""Test EnvironmentScorecard with empty scorecard."""
|
| 922 |
+
from arc_agi.scorecard import Scorecard
|
| 923 |
+
|
| 924 |
+
scorecard = Scorecard(
|
| 925 |
+
card_id="test-card",
|
| 926 |
+
api_key="test-key",
|
| 927 |
+
cards={},
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [])
|
| 931 |
+
|
| 932 |
+
self.assertEqual(len(scorecard_result.environments), 0)
|
| 933 |
+
self.assertEqual(len(scorecard_result.tags_scores), 0)
|
| 934 |
+
self.assertEqual(scorecard_result.score, 0.0)
|
| 935 |
+
|
| 936 |
+
def test_from_scorecard_no_matching_env_info(self):
|
| 937 |
+
"""Test EnvironmentScorecard when no matching EnvironmentInfo exists."""
|
| 938 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 939 |
+
|
| 940 |
+
card = Card(
|
| 941 |
+
game_id="bt11",
|
| 942 |
+
total_plays=1,
|
| 943 |
+
guids=["guid1"],
|
| 944 |
+
levels_completed=[1],
|
| 945 |
+
actions=[10],
|
| 946 |
+
resets=[0],
|
| 947 |
+
states=[GameState.WIN],
|
| 948 |
+
actions_by_level=[[(1, 10)]],
|
| 949 |
+
)
|
| 950 |
+
|
| 951 |
+
scorecard = Scorecard(
|
| 952 |
+
card_id="test-card",
|
| 953 |
+
api_key="test-key",
|
| 954 |
+
cards={"bt11": card},
|
| 955 |
+
)
|
| 956 |
+
|
| 957 |
+
# No matching EnvironmentInfo
|
| 958 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [])
|
| 959 |
+
|
| 960 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 961 |
+
score = scorecard_result.environments[0]
|
| 962 |
+
self.assertEqual(score.score, 0.0)
|
| 963 |
+
self.assertEqual(
|
| 964 |
+
score.runs[0].message,
|
| 965 |
+
"No Matching EnvironmentInfo found for bt11",
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
def test_from_scorecard_multiple_plays_same_game(self):
|
| 969 |
+
"""Test that only best play is selected when multiple plays exist."""
|
| 970 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 971 |
+
|
| 972 |
+
# Create card with 3 plays, middle one has highest levels_completed
|
| 973 |
+
card = Card(
|
| 974 |
+
game_id="bt11",
|
| 975 |
+
total_plays=3,
|
| 976 |
+
guids=["guid1", "guid2", "guid3"],
|
| 977 |
+
levels_completed=[1, 3, 2], # guid2 has highest (3)
|
| 978 |
+
actions=[10, 30, 20],
|
| 979 |
+
resets=[0, 0, 0],
|
| 980 |
+
states=[GameState.WIN, GameState.WIN, GameState.WIN],
|
| 981 |
+
actions_by_level=[
|
| 982 |
+
[(1, 10)],
|
| 983 |
+
[(1, 10), (2, 20), (3, 30)],
|
| 984 |
+
[(1, 10), (2, 20)],
|
| 985 |
+
],
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
scorecard = Scorecard(
|
| 989 |
+
card_id="test-card",
|
| 990 |
+
api_key="test-key",
|
| 991 |
+
cards={"bt11": card},
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
env_info = EnvironmentInfo(
|
| 995 |
+
game_id="bt11",
|
| 996 |
+
title="BT11",
|
| 997 |
+
baseline_actions=[10, 15, 20],
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 1001 |
+
# Should only have one environment score (for guid2)
|
| 1002 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 1003 |
+
self.assertEqual(scorecard_result.environments[0].id, "bt11")
|
| 1004 |
+
self.assertEqual(scorecard_result.environments[0].levels_completed, 3)
|
| 1005 |
+
|
| 1006 |
+
def test_realistic_scorecard_for_bt11(self):
|
| 1007 |
+
"""Test that only best play is selected when multiple plays exist."""
|
| 1008 |
+
from arc_agi.scorecard import Card, Scorecard
|
| 1009 |
+
|
| 1010 |
+
# Create card with 3 plays, middle one has highest levels_completed
|
| 1011 |
+
card = Card(
|
| 1012 |
+
game_id="bt11-fd9df0622a1a",
|
| 1013 |
+
total_plays=1,
|
| 1014 |
+
guids=["guid1"],
|
| 1015 |
+
levels_completed=[2], # guid2 has highest (3)
|
| 1016 |
+
actions=[118],
|
| 1017 |
+
resets=[6],
|
| 1018 |
+
states=[GameState.NOT_FINISHED],
|
| 1019 |
+
actions_by_level=[[(1, 4), (2, 12)]],
|
| 1020 |
+
)
|
| 1021 |
+
|
| 1022 |
+
scorecard = Scorecard(
|
| 1023 |
+
card_id="test-card",
|
| 1024 |
+
api_key="test-key",
|
| 1025 |
+
cards={"bt11-fd9df0622a1a": card},
|
| 1026 |
+
)
|
| 1027 |
+
|
| 1028 |
+
env_info = EnvironmentInfo(
|
| 1029 |
+
game_id="bt11-fd9df0622a1a",
|
| 1030 |
+
title="BT11",
|
| 1031 |
+
tags=["tag1", "shared"],
|
| 1032 |
+
baseline_actions=[4, 8, 16, 20, 24],
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
scorecard_result = EnvironmentScorecard.from_scorecard(scorecard, [env_info])
|
| 1036 |
+
|
| 1037 |
+
# Should only have one environment score (for guid2)
|
| 1038 |
+
self.assertEqual(len(scorecard_result.environments), 1)
|
| 1039 |
+
self.assertEqual(scorecard_result.environments[0].id, "bt11-fd9df0622a1a")
|
| 1040 |
+
self.assertEqual(scorecard_result.environments[0].levels_completed, 2)
|
| 1041 |
+
|
| 1042 |
+
envs_by_id = {s.id: s for s in scorecard_result.environments}
|
| 1043 |
+
|
| 1044 |
+
# Check that shared tag has aggregated scores from both games
|
| 1045 |
+
if "bt11-fd9df0622a1a" in envs_by_id:
|
| 1046 |
+
game_score = envs_by_id["bt11-fd9df0622a1a"]
|
| 1047 |
+
# Should have 2 levels completed (one from each game)
|
| 1048 |
+
self.assertEqual(game_score.levels_completed, 2)
|
| 1049 |
+
self.assertAlmostEqual(game_score.score, 20.0, places=5)
|
| 1050 |
+
self.assertEqual(game_score.actions, 118)
|
| 1051 |
+
self.assertEqual(game_score.resets, 6)
|
| 1052 |
+
self.assertEqual(game_score.completed, False)
|
| 1053 |
+
else:
|
| 1054 |
+
self.fail("bt11 environment not found")
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
if __name__ == "__main__":
|
| 1058 |
+
unittest.main()
|