Download code/minigrid_protocol.py from zhangdw/minigrid: direct link, hf CLI and curl.
- Browser
- Download file 2.22 kB
-
https://huggingface.co/datasets/zhangdw/minigrid/resolve/main/code/minigrid_protocol.py
- Command line
-
hf download hf://datasets/zhangdw/minigrid/code/minigrid_protocol.py
-
curl -L -o minigrid_protocol.py https://huggingface.co/datasets/zhangdw/minigrid/resolve/main/code/minigrid_protocol.py
2.22 kB
| """MiniGrid v1 grammar and native policy action IDs (drop/done are not actions).""" | |
| import re | |
| from dataclasses import dataclass | |
| ACTIONS = {"left": 0, "right": 1, "forward": 2, "pickup": 3, "toggle": 5} | |
| _ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") | |
| def normalize_action(action): | |
| normalized = str(action).strip().translate(_ASCII_LOWER) | |
| if normalized not in ACTIONS: | |
| raise ValueError("MiniGrid action must be left, right, forward, pickup, or toggle") | |
| return normalized | |
| class ParsedAction: | |
| action: str | None | |
| reason: str = "" | |
| attempted_action: str = "unavailable" | |
| def valid(self): | |
| return self.action is not None | |
| def parse_response(response, *, hit_limit=False): | |
| # Padding/terminal special tokens are removed by the tokenizer, never prose. | |
| text = str(response) | |
| blocks = re.findall(r"<action>(.*?)</action>", text, re.S) | |
| attempted = "unavailable" | |
| if len(blocks) == 1 and text.count("<action>") == text.count("</action>") == 1: | |
| try: | |
| attempted = normalize_action(blocks[0]) | |
| except ValueError: | |
| pass | |
| reason = "" | |
| tags = ("<think>", "</think>", "<action>", "</action>") | |
| if hit_limit and not blocks: | |
| reason = "truncated_action" | |
| elif any(text.count(tag) > 1 for tag in tags): | |
| reason = "multiple_blocks" | |
| elif not all(tag in text for tag in tags[:2]): | |
| reason = "missing_think_block" | |
| elif not all(tag in text for tag in tags[2:]): | |
| reason = "missing_action_block" | |
| else: | |
| match = re.fullmatch(r"\s*<think>(.*?)</think>\s*<action>(.*?)</action>\s*", text, re.S) | |
| if match is None or any(tag in match[1] or tag in match[2] for tag in tags): | |
| reason = "malformed_format" | |
| else: | |
| payload = match[2].strip().translate(_ASCII_LOWER) | |
| if payload in ACTIONS: | |
| return ParsedAction(payload, attempted_action=payload) | |
| words = re.findall("[a-z]+", payload) | |
| reason = "multiple_actions" if sum(word in ACTIONS for word in words) >= 2 else "unsupported_action" | |
| return ParsedAction(None, reason, attempted) | |