Download src/mskit/simu/intent.py from MegaBites-AI/AW3D30-DEM-Tiles: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles/resolve/main/src/mskit/simu/intent.py
- Command line
-
hf download hf://datasets/MegaBites-AI/AW3D30-DEM-Tiles/src/mskit/simu/intent.py
-
curl -L -o intent.py https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles/resolve/main/src/mskit/simu/intent.py
10.6 kB
| """ | |
| 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) + "." | |