File size: 10,560 Bytes
8c83e8e | 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 | """
Intent parser for Simu — MSKit's AI assistant.
Parses natural language into structured simulation requests.
Two-tier approach:
1. Rule-based fast parser (zero-latency, no model needed)
2. LLM-augmented extraction (SmolLM2, used for ambiguous inputs)
Intent schema:
{
"sim_type": "random_walk" | "projectile" | "water_flow" | "agent" | "traffic" | "profile",
"location": {"lat": float, "lon": float, "name": str},
"params": { ... sim-specific params ... },
"confidence": float, # 0.0–1.0
"raw": str, # original user text
"explanation": str, # what Simu understood
}
"""
from __future__ import annotations
import re
import math
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Well-known city coordinates
# ---------------------------------------------------------------------------
CITIES: Dict[str, Tuple[float, float]] = {
"tokyo": (35.6762, 139.6503),
"london": (51.5074, -0.1278),
"paris": (48.8566, 2.3522),
"new york": (40.7128, -74.0060),
"new york city": (40.7128, -74.0060),
"nyc": (40.7128, -74.0060),
"los angeles": (34.0522, -118.2437),
"la": (34.0522, -118.2437),
"sydney": (-33.8688, 151.2093),
"melbourne": (-37.8136, 144.9631),
"singapore": (1.3521, 103.8198),
"hong kong": (22.3193, 114.1694),
"dubai": (25.2048, 55.2708),
"zurich": (47.3769, 8.5417),
"berlin": (52.5200, 13.4050),
"madrid": (40.4168, -3.7038),
"munich": (48.1351, 11.5820),
"hamburg": (53.5753, 9.9935),
"toronto": (43.6532, -79.3832),
"chicago": (41.8781, -87.6298),
"seattle": (47.6062, -122.3321),
"san francisco": (37.7749, -122.4194),
"sf": (37.7749, -122.4194),
"boston": (42.3601, -71.0589),
"seoul": (37.5665, 127.0000),
"beijing": (39.9042, 116.4074),
"shanghai": (31.2304, 121.4737),
"bangkok": (13.7563, 100.5018),
"jakarta": (-6.2088, 106.8456),
"mumbai": (19.0760, 72.8777),
"delhi": (28.6139, 77.2090),
"cairo": (30.0444, 31.2357),
"nairobi": (-1.2921, 36.8219),
"johannesburg": (-26.2041, 28.0473),
"buenos aires": (-34.6037, -58.3816),
"sao paulo": (-23.5505, -46.6333),
"mexico city": (19.4326, -99.1332),
"rome": (41.9028, 12.4964),
"amsterdam": (52.3676, 4.9041),
"stockholm": (59.3293, 18.0686),
"oslo": (59.9139, 10.7522),
"vienna": (48.2082, 16.3738),
"prague": (50.0755, 14.4378),
"warsaw": (52.2297, 21.0122),
"istanbul": (41.0082, 28.9784),
"moscow": (55.7558, 37.6173),
"mount fuji": (35.3606, 138.7274),
"fuji": (35.3606, 138.7274),
"alps": (46.5000, 8.5000),
"himalayas": (27.9881, 86.9250),
"everest": (27.9881, 86.9250),
"amazon": (-3.4653, -62.2159),
"sahara": (23.4162, 25.6628),
"grand canyon": (36.1069, -112.1129),
"yellowstone": (44.4280, -110.5885),
}
# ---------------------------------------------------------------------------
# Sim type keywords
# ---------------------------------------------------------------------------
SIM_PATTERNS = {
"random_walk": [
r"\brandom\s*walk\b", r"\bwalk\b", r"\bwander\b", r"\bwandering\b",
r"\bhiker\b", r"\bhike\b", r"\bstroll\b", r"\bwalk(?:ing)?\b",
r"\bexplore\b", r"\bexploring\b",
],
"projectile": [
r"\bprojectile\b", r"\bballist", r"\blaunch\b", r"\bthrow\b",
r"\bshoot\b", r"\bfire\b", r"\bcannon\b", r"\bmissile\b",
r"\btrajectory\b", r"\bdrop\b", r"\bcatapult\b", r"\brange\b",
],
"water_flow": [
r"\bwater\b", r"\bflow\b", r"\briver\b", r"\bflood\b",
r"\brunoff\b", r"\brain\b", r"\bstream\b", r"\bdrain(?:age)?\b",
r"\bwaterfall\b", r"\bsimulate.*water\b", r"\bflood\b",
],
"agent": [
r"\bagent\b", r"\bnavigate\b", r"\bnavigation\b", r"\bpath\b",
r"\breinforcement\b", r"\brl\b", r"\bgo\s+from\b", r"\btravel\b",
r"\broute.*agent\b", r"\bfind.*way\b",
],
"traffic": [
r"\btraffic\b", r"\bcongestion\b", r"\bcommute\b", r"\bjam\b",
r"\bspeed.*road\b", r"\broad.*speed\b", r"\bdriving\b",
],
"profile": [
r"\bprofile\b", r"\bcross.?section\b", r"\belevation.*between\b",
r"\bterrain.*between\b", r"\bheight.*profile\b",
],
}
# ---------------------------------------------------------------------------
# Parameter patterns
# ---------------------------------------------------------------------------
_STEPS_RE = re.compile(r"(\d+)\s*steps?", re.I)
_SPEED_RE = re.compile(r"(\d+(?:\.\d+)?)\s*(?:m/?s|meters?\s*per\s*second)", re.I)
_KMH_RE = re.compile(r"(\d+(?:\.\d+)?)\s*km/?h", re.I)
_ANGLE_RE = re.compile(r"(\d+(?:\.\d+)?)\s*(?:degree|°)\s*(?:angle|elevation)?", re.I)
_AZIMUTH_RE = re.compile(r"(\d+(?:\.\d+)?)\s*(?:degree|°)?\s*(?:azimuth|bearing|heading)", re.I)
_RADIUS_RE = re.compile(r"(\d+(?:\.\d+)?)\s*km\s*radius", re.I)
_LAT_RE = re.compile(r"lat(?:itude)?\s*[=:]?\s*(-?\d+(?:\.\d+)?)", re.I)
_LON_RE = re.compile(r"lon(?:gitude)?\s*[=:]?\s*(-?\d+(?:\.\d+)?)", re.I)
_COORD_RE = re.compile(r"(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)")
_TO_RE = re.compile(r"\bto\s+(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)", re.I)
def _find_location(text: str) -> Optional[Dict[str, Any]]:
"""Extract a location from text. Returns dict with lat, lon, name."""
t = text.lower()
# Explicit lat/lon
lat_m = _LAT_RE.search(text)
lon_m = _LON_RE.search(text)
if lat_m and lon_m:
return {"lat": float(lat_m.group(1)), "lon": float(lon_m.group(1)), "name": "custom"}
# Bare coordinate pair "35.6, 139.7"
coord_m = _COORD_RE.search(text)
if coord_m:
la, lo = float(coord_m.group(1)), float(coord_m.group(2))
if -90 <= la <= 90 and -180 <= lo <= 180:
return {"lat": la, "lon": lo, "name": "custom"}
# Named city — longest match wins
matches = [(name, coords) for name, coords in CITIES.items() if name in t]
if matches:
best = max(matches, key=lambda x: len(x[0]))
return {"lat": best[1][0], "lon": best[1][1], "name": best[0].title()}
return None
def _find_sim_type(text: str) -> Tuple[str, float]:
"""Return (sim_type, confidence)."""
t = text.lower()
scores: Dict[str, int] = {}
for sim, patterns in SIM_PATTERNS.items():
score = sum(1 for p in patterns if re.search(p, t))
if score:
scores[sim] = score
if not scores:
return "random_walk", 0.3 # default
best = max(scores, key=scores.get)
confidence = min(0.5 + scores[best] * 0.2, 1.0)
return best, confidence
def _extract_params(sim_type: str, text: str) -> Dict[str, Any]:
"""Extract simulation-specific parameters from text."""
params: Dict[str, Any] = {}
steps_m = _STEPS_RE.search(text)
if steps_m:
params["steps"] = int(steps_m.group(1))
speed_m = _SPEED_RE.search(text)
if speed_m:
params["speed_ms"] = float(speed_m.group(1))
kmh_m = _KMH_RE.search(text)
if kmh_m:
params["speed_ms"] = float(kmh_m.group(1)) / 3.6
if sim_type == "projectile":
angle_m = _ANGLE_RE.search(text)
if angle_m:
params["elevation_deg"] = float(angle_m.group(1))
az_m = _AZIMUTH_RE.search(text)
if az_m:
params["azimuth_deg"] = float(az_m.group(1))
# compass directions
for direction, az in [("north", 0), ("northeast", 45), ("east", 90),
("southeast", 135), ("south", 180),
("southwest", 225), ("west", 270), ("northwest", 315)]:
if direction in text.lower():
params.setdefault("azimuth_deg", az)
if sim_type == "water_flow":
r_m = _RADIUS_RE.search(text)
if r_m:
params["patch_km"] = float(r_m.group(1))
if sim_type == "random_walk":
params.setdefault("steps", 500)
if "steep" in text.lower() or "mountain" in text.lower():
params["slope_bias"] = 0.8
elif "flat" in text.lower() or "plain" in text.lower():
params["slope_bias"] = 0.1
# Two-point destination (for agent / profile)
to_m = _TO_RE.search(text)
if to_m:
params["target_lat"] = float(to_m.group(1))
params["target_lon"] = float(to_m.group(2))
return params
def parse_intent(text: str) -> Dict[str, Any]:
"""
Parse a natural language simulation request into a structured intent dict.
Pure rule-based — instant, no model required.
"""
sim_type, confidence = _find_sim_type(text)
location = _find_location(text)
params = _extract_params(sim_type, text)
# Default location if none found
if location is None:
location = {"lat": 35.6762, "lon": 139.6503, "name": "Tokyo (default)"}
confidence *= 0.7
explanation = _explain(sim_type, location, params)
return {
"sim_type": sim_type,
"location": location,
"params": params,
"confidence": round(confidence, 2),
"raw": text,
"explanation": explanation,
}
def _explain(sim_type: str, location: Dict, params: Dict) -> str:
sim_labels = {
"random_walk": "a slope-biased random walk",
"projectile": "a ballistic trajectory",
"water_flow": "a water runoff simulation",
"agent": "a terrain-navigating AI agent episode",
"traffic": "a traffic + congestion query",
"profile": "an elevation profile transect",
}
label = sim_labels.get(sim_type, sim_type)
loc = location["name"]
parts = [f"Run {label} at {loc}"]
if "steps" in params:
parts.append(f"{params['steps']} steps")
if "speed_ms" in params:
parts.append(f"{params['speed_ms']*3.6:.0f} km/h")
if "elevation_deg" in params:
parts.append(f"{params['elevation_deg']}° launch angle")
if "azimuth_deg" in params:
parts.append(f"{params['azimuth_deg']}° bearing")
return ", ".join(parts) + "."
|