Spaces:
Running
Running
File size: 8,706 Bytes
efeed27 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | """
Instruction parser: converts human text into a structured origami task.
Handles variations like:
- "make a paper crane"
- "fold me a crane"
- "i want to make a paper crane"
- "crane please"
- "can you fold a crane?"
- "pack a 1m x 1m mylar sheet as compact as possible"
"""
from __future__ import annotations
import re
from planner.knowledge import ORIGAMI_MODELS, list_known_models
# ---------------------------------------------------------------------------
# Vocabulary for matching
# ---------------------------------------------------------------------------
# Model aliases → canonical name
_MODEL_ALIASES: dict[str, str] = {
# Crane
"crane": "crane",
"tsuru": "crane",
"bird": "crane",
"orizuru": "crane",
# Boat
"boat": "boat",
"hat": "boat",
"paper boat": "boat",
"paper hat": "boat",
# Airplane
"airplane": "airplane",
"aeroplane": "airplane",
"plane": "airplane",
"paper airplane": "airplane",
"paper plane": "airplane",
"dart": "airplane",
"paper dart": "airplane",
# Box
"box": "box",
"masu": "box",
"masu box": "box",
"open box": "box",
# Fortune teller
"fortune teller": "fortune_teller",
"fortune-teller": "fortune_teller",
"cootie catcher": "fortune_teller",
"cootie-catcher": "fortune_teller",
"chatterbox": "fortune_teller",
# Waterbomb / balloon
"waterbomb": "waterbomb",
"water bomb": "waterbomb",
"balloon": "waterbomb",
"paper balloon": "waterbomb",
# Jumping frog
"jumping frog": "jumping_frog",
"frog": "jumping_frog",
"leap frog": "jumping_frog",
}
# Sorted longest-first so multi-word aliases match before single-word ones
_ALIAS_KEYS_SORTED = sorted(_MODEL_ALIASES.keys(), key=len, reverse=True)
_MATERIALS = {
"paper": "paper",
"mylar": "mylar",
"aluminum": "aluminum",
"aluminium": "aluminum",
"metal": "metal",
"nitinol": "nitinol",
"foil": "aluminum",
"cardboard": "cardboard",
"cardstock": "cardstock",
"fabric": "fabric",
"cloth": "fabric",
}
# Intent keywords
_FOLD_VERBS = {
"make", "fold", "create", "build", "construct", "origami",
"craft", "form", "shape", "assemble",
}
_PACK_VERBS = {
"pack", "compress", "compact", "minimize", "reduce", "stow",
"shrink", "deploy", "collapse",
}
_OPTIMIZE_PHRASES = [
"as compact as possible",
"minimize volume",
"minimize packed volume",
"minimize area",
"solar panel",
"stent",
"deployable",
"maximize compactness",
"flatten",
]
# Dimension patterns
_DIM_PATTERNS = [
# "10cm x 10cm", "10 cm x 10 cm"
re.compile(
r"(\d+(?:\.\d+)?)\s*(cm|mm|m|in|inch|inches|ft|feet)\s*[xX\u00d7]\s*(\d+(?:\.\d+)?)\s*(cm|mm|m|in|inch|inches|ft|feet)",
re.IGNORECASE,
),
# "10cm square", "1 meter square"
re.compile(
r"(\d+(?:\.\d+)?)\s*(cm|mm|m|in|inch|inches|ft|feet|meter|meters|metre|metres)\s+square",
re.IGNORECASE,
),
]
_UNIT_TO_M = {
"m": 1.0,
"meter": 1.0,
"meters": 1.0,
"metre": 1.0,
"metres": 1.0,
"cm": 0.01,
"mm": 0.001,
"in": 0.0254,
"inch": 0.0254,
"inches": 0.0254,
"ft": 0.3048,
"feet": 0.3048,
}
# ---------------------------------------------------------------------------
# Parsing helpers
# ---------------------------------------------------------------------------
def _normalise(text: str) -> str:
"""Lower-case and strip extra whitespace."""
return " ".join(text.lower().split())
def _detect_model(text: str) -> str | None:
"""Return canonical model name if one is mentioned, else None."""
norm = _normalise(text)
# Strip out constraint phrases that might contain model-name false positives
# e.g. "into a 15cm x 15cm x 5cm box" should not match "box" as a model
cleaned = re.sub(
r"(?:fit\s+)?(?:in(?:to)?|inside)\s+(?:a\s+)?\d.*?box",
"",
norm,
)
for alias in _ALIAS_KEYS_SORTED:
# Use word-boundary-aware search to avoid partial matches
pattern = r"(?:^|\b)" + re.escape(alias) + r"(?:\b|$)"
if re.search(pattern, cleaned):
return _MODEL_ALIASES[alias]
return None
def _detect_material(text: str) -> str:
"""Return detected material or default 'paper'."""
norm = _normalise(text)
# Check multi-word materials first (none currently, but future-proof)
for keyword, canonical in sorted(_MATERIALS.items(), key=lambda kv: -len(kv[0])):
if keyword in norm:
return canonical
return "paper"
def _detect_dimensions(text: str) -> dict[str, float]:
"""Parse explicit dimensions. Returns {"width": m, "height": m} or defaults."""
for pat in _DIM_PATTERNS:
m = pat.search(text)
if m:
groups = m.groups()
if len(groups) == 4:
# WxH pattern
w = float(groups[0]) * _UNIT_TO_M.get(groups[1].lower(), 1.0)
h = float(groups[2]) * _UNIT_TO_M.get(groups[3].lower(), 1.0)
return {"width": round(w, 6), "height": round(h, 6)}
elif len(groups) == 2:
# "N unit square"
side = float(groups[0]) * _UNIT_TO_M.get(groups[1].lower(), 1.0)
return {"width": round(side, 6), "height": round(side, 6)}
# Default: unit square
return {"width": 1.0, "height": 1.0}
def _detect_constraints(text: str) -> dict:
"""Detect any explicit constraints mentioned in the instruction."""
norm = _normalise(text)
constraints: dict = {}
# Target bounding box: "fit in a 15cm x 15cm x 5cm box"
box_pat = re.compile(
r"fit\s+(?:in(?:to)?|inside)\s+(?:a\s+)?(\d+(?:\.\d+)?)\s*(cm|mm|m)\s*[xX\u00d7]\s*"
r"(\d+(?:\.\d+)?)\s*(cm|mm|m)\s*[xX\u00d7]\s*(\d+(?:\.\d+)?)\s*(cm|mm|m)",
re.IGNORECASE,
)
bm = box_pat.search(norm)
if bm:
g = bm.groups()
constraints["target_box"] = [
float(g[0]) * _UNIT_TO_M.get(g[1], 1.0),
float(g[2]) * _UNIT_TO_M.get(g[3], 1.0),
float(g[4]) * _UNIT_TO_M.get(g[5], 1.0),
]
# Max folds
folds_pat = re.compile(r"(?:max(?:imum)?|at most|no more than)\s+(\d+)\s+fold", re.IGNORECASE)
fm = folds_pat.search(norm)
if fm:
constraints["max_folds"] = int(fm.group(1))
# Compactness emphasis
for phrase in _OPTIMIZE_PHRASES:
if phrase in norm:
constraints["optimize_compactness"] = True
break
# Must deploy
if "deploy" in norm or "unfold" in norm and "clean" in norm:
constraints["must_deploy"] = True
return constraints
def _detect_intent(text: str, model_name: str | None, constraints: dict) -> str:
"""Determine the high-level intent of the instruction."""
norm = _normalise(text)
words = set(norm.split())
# If packing / optimization phrases are present, it's an optimization task
if constraints.get("optimize_compactness"):
return "optimize_packing"
if words & _PACK_VERBS:
return "optimize_packing"
# If a known model is detected, it's a fold_model task
if model_name is not None:
return "fold_model"
# If fold verbs are present but no model, it's a free fold
if words & _FOLD_VERBS:
return "free_fold"
# Fallback: if there's a pattern keyword
pattern_words = {"miura", "tessellation", "pattern", "waterbomb tessellation", "pleat"}
if words & pattern_words:
return "fold_pattern"
return "free_fold"
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def parse_instruction(text: str) -> dict:
"""
Parse a human origami instruction into a structured task.
Args:
text: Natural-language instruction, e.g. "make a paper crane"
Returns:
{
"intent": "fold_model" | "fold_pattern" | "optimize_packing" | "free_fold",
"model_name": str or None,
"material": str,
"dimensions": {"width": float, "height": float},
"constraints": {...},
"raw_instruction": str,
}
"""
model_name = _detect_model(text)
material = _detect_material(text)
dimensions = _detect_dimensions(text)
constraints = _detect_constraints(text)
intent = _detect_intent(text, model_name, constraints)
return {
"intent": intent,
"model_name": model_name,
"material": material,
"dimensions": dimensions,
"constraints": constraints,
"raw_instruction": text,
}
|