"""Facts Lumi can look up while talking: date and time (always), weather and web search (needs internet). The robot network has no internet; the Thor reaches it through its own Wi-Fi. A proxy can be set instead (one line such as http://192.168.10.200:8888 in proxy.txt next to this file, or HTTPS_PROXY). python assistant/web.py # date/time + is the internet reachable? python assistant/web.py weather Seoul python assistant/web.py search "Jetson Thor" """ import html import datetime import json import math import os import re import sys import time import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor, wait from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # the project folder PROXY_FILE = ROOT / "data" / "proxy.txt" # e.g. http://192.168.10.200:8888 (one line), optional DEFAULT_PLACE = "Seoul" UA = {"User-Agent": "Mozilla/5.0 (X11; Linux aarch64) LumiRobot/1.0"} _online = {"time": 0.0, "ok": False} PLACES = {"seoul": {"name": "Seoul", "latitude": 37.57, "longitude": 126.98}, # known places: no geocoding request "incheon airport": {"name": "Incheon Airport", "latitude": 37.46, "longitude": 126.44}, # the geocoder has "gimpo airport": {"name": "Gimpo Airport", "latitude": 37.56, "longitude": 126.79}} # towns, no airports FIXED = list(PLACES.values()) # Korean names -> the English name the geocoder knows (it finds 부산 as a village "Pusan", 제주 not at all, "Jeju" in Ethiopia) KO_PLACES = { "서울": "Seoul", "부산": "Busan", "인천": "Incheon", "대구": "Daegu", "대전": "Daejeon", "광주": "Gwangju", "울산": "Ulsan", "세종": "Sejong", "수원": "Suwon", "성남": "Seongnam-si", "고양": "Goyang", "용인": "Yongin-si", "창원": "Changwon", "청주": "Cheongju", "전주": "Jeonju", "천안": "Cheonan", "포항": "Pohang", "김해": "Gimhae", "제주": "Jeju City", "제주도": "Jeju City", "서귀포": "Seogwipo", "강릉": "Gangneung", "춘천": "Chuncheon", "원주": "Wonju", "속초": "Sokcho", "경주": "Gyeongju", "여수": "Yeosu", "목포": "Mokpo", "안동": "Andong", "평창": "Pyeongchang", "도쿄": "Tokyo", "오사카": "Osaka", "교토": "Kyoto", "후쿠오카": "Fukuoka", "삿포로": "Sapporo", "베이징": "Beijing", "상하이": "Shanghai", "홍콩": "Hong Kong", "타이베이": "Taipei", "방콕": "Bangkok", "싱가포르": "Singapore", "하노이": "Hanoi", "다낭": "Da Nang", "뉴욕": "New York", "런던": "London", "파리": "Paris", "타슈켄트": "Tashkent", "사마르칸트": "Samarkand", "인천공항": "Incheon Airport", "인천국제공항": "Incheon Airport", "김포공항": "Gimpo Airport", "jeju": "Jeju City", "seongnam": "Seongnam-si", "yongin": "Yongin-si", # the plain English name is found elsewhere } def en_place(place): """'부산', '부산시', '제주도', 'Jeju' -> 'Busan', 'Busan', 'Jeju City', 'Jeju City'; anything else unchanged.""" p = place.strip() return KO_PLACES.get(p.lower()) or (KO_PLACES.get(p[:-1]) if p.endswith(("시", "도")) else None) or p WEATHER_TTL = 600 # s a weather answer is reused (each web request takes ~2 s on the Wi-Fi) _weather = {} # place -> (time, text) def _opener(): proxy = PROXY_FILE.read_text().strip() if PROXY_FILE.exists() else os.environ.get("HTTPS_PROXY", "") handlers = [urllib.request.ProxyHandler({"http": proxy, "https": proxy})] if proxy else [] return urllib.request.build_opener(*handlers) def _get(url, timeout=6, headers=UA): req = urllib.request.Request(url, headers=headers) with _opener().open(req, timeout=timeout) as r: return r.read().decode("utf-8", errors="replace") def online(): """Is the internet reachable? (checked at most every 60 s)""" now = time.time() if now - _online["time"] > 60: _online["time"] = now try: _get("https://api.open-meteo.com/v1/forecast?latitude=37.57&longitude=126.98¤t=temperature_2m", 4) _online["ok"] = True except Exception: _online["ok"] = False return _online["ok"] def now_text(): """Local date and time in words, e.g. 'Monday, 12 October 2026, 15:07'.""" return time.strftime("%A, %d %B %Y, %H:%M") WEATHER_CODES = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", 45: "fog", 48: "fog", 51: "light drizzle", 53: "drizzle", 55: "heavy drizzle", 56: "freezing drizzle", 57: "freezing drizzle", 61: "light rain", 63: "rain", 65: "heavy rain", 66: "freezing rain", 67: "freezing rain", 71: "light snow", 73: "snow", 75: "heavy snow", 77: "snow grains", 80: "rain showers", 81: "rain showers", 82: "violent rain showers", 85: "snow showers", 86: "snow showers", 95: "thunderstorm", 96: "thunderstorm with hail", 99: "thunderstorm with hail"} WEATHER_DAYS = 7 # days of forecast given ("tomorrow", "모레", "this weekend") def weather(place=DEFAULT_PLACE): """Weather now and the days ahead as a short English text, or None without internet.""" place = en_place(place or DEFAULT_PLACE) or DEFAULT_PLACE key = place.lower() if key in _weather and time.time() - _weather[key][0] < WEATHER_TTL: return _weather[key][1] try: loc = _place(place) if not loc: return f"I could not find a place called {place}." w = json.loads(_get( f"https://api.open-meteo.com/v1/forecast?latitude={loc['latitude']}&longitude={loc['longitude']}" "¤t=temperature_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max," f"temperature_2m_min,precipitation_probability_max&timezone=auto&forecast_days={WEATHER_DAYS}")) c, d = w["current"], w["daily"] days = [] for i, day in enumerate(d["time"]): name = datetime.date.fromisoformat(day).strftime("%A %d %B") name = f"Today ({name})" if i == 0 else f"Tomorrow ({name})" if i == 1 else name days.append(f"{name}: {WEATHER_CODES.get(d['weather_code'][i], 'unknown')}, {d['temperature_2m_min'][i]:.0f} " f"to {d['temperature_2m_max'][i]:.0f} degrees, chance of rain " f"{d['precipitation_probability_max'][i]} percent.") text = (f"Weather in {loc['name']} now: {WEATHER_CODES.get(c['weather_code'], 'unknown')}, " f"{c['temperature_2m']:.0f} degrees, wind {c['wind_speed_10m']:.0f} km/h.\n" + "\n".join(days)) _weather[key] = (time.time(), text) return text except Exception: return None WEEKDAYS = {"monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3, "friday": 4, "saturday": 5, "sunday": 6, "월": 0, "화": 1, "수": 2, "목": 3, "금": 4, "토": 5, "일": 6} NUMBER_WORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "이틀": 2, "사흘": 3, "나흘": 4} DAY_AFTER = re.compile(r"\bthe (?:day after|next day|following day)\b(?! tomorrow)|그 ?다음 ?날|다음 ?날|그 ?담 ?날", re.I) DAY_BEFORE = re.compile(r"\bthe day before\b(?! yesterday)|그 ?전 ?날", re.I) FIXED_DAY = re.compile(r"\bday after tomorrow\b|\bday before yesterday\b|내일 ?모레|글피|그저께|그제|모레|" r"(? what a search engine wants KO_ASK = ((r"\bhow old\b|\bage\b|\bbirthday\b|\bwhen was \w+( \w+)? born\b", "나이"), (r"\bhow tall\b|\bheight\b", "키"), (r"\bstocks?( price)?\b|\bshares?( price)?\b", "주가"), (r"\bindex\b|(?=\b(nasdaq|dow jones|kospi|kosdaq|s&p 500)\b)", "지수"), (r"\bstandings?\b|\bfirst place\b|\bin first\b|\branking\b", "순위"), (r"\bscore\b|\bresult\b|\blast (game|match)\b|\bhow did\b", "경기 결과")) # not opening hours: "Louvre 영업시간" brings Korean shops named Louvre # English question -> the Korean word for Naver's answer box (ko_box_query) ASK_WORDS = re.compile(r"\b(what'?s|what|who'?s|who|whom|which|where|when|why|how|is|are|was|were|the|a|an|do|does|did|" r"can|could|you|tell me|please|lumi|right now|i|me|my|and|he|she|his|her|it|its|they|their)\b|" r"[?,.!]", re.I) CURRENCIES = {"USD": ("US dollar", r"dollars?|usd|달러"), "EUR": ("euro", r"euros?|eur\b|유로"), "JPY": ("Japanese yen", r"\byen\b|jpy|엔화|(?<=[\d만] )엔|(?<=[\d만])엔"), "CNY": ("Chinese yuan", r"yuan|renminbi|cny|위안"), "GBP": ("British pound", r"pounds? sterling|british pounds?|gbp|파운드"), "VND": ("Vietnamese dong", r"vietnamese dong|vnd|동화"), "THB": ("Thai baht", r"baht|thb|바트"), "KRW": ("Korean won", r"\bwons?\b|krw|원화")} COINS = {"bitcoin": r"bitcoin|btc|비트 ?코인|빗코인", "ethereum": r"ethereum|\beth\b|이더리움", "ripple": r"\bxrp\b|ripple|리플", "solana": r"solana|솔라나", "dogecoin": r"doge|도지"} RATE_WORDS = re.compile(r"exchange|\brates?\b|convert|환율|환전|in (korean )?wons?\b|\bto (krw|wons?|usd|dollars?)\b|" r"\bkrw\b|원으로|얼마", re.I) _searched = {} # query -> (time, text) _pool = ThreadPoolExecutor(6) def _text(page): """Visible text of an HTML fragment on one line.""" page = re.sub(r"(?is)<(script|style|noscript|svg)[^>]*>.*?\1>", " ", page) return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", page))).strip() def keywords(query): """An English question as search words: "How tall is Son Heung-min?" -> "height Son Heung-min". Naver finds English blogs about grammar for a whole English question, the right pages for the words. Korean stays as it is.""" if re.search(r"[가-힣]", query): return query q = query for asked, word in ASKED_AS: q = re.sub(asked, f" {word} ", q, flags=re.I) return re.sub(r"\s+", " ", ASK_WORDS.sub(" ", q)).strip() or query def _naver(query, boxes_only=False): """The Naver results page as text: answer boxes (exchange rates, stocks, people, sports), web pages, news, blogs; ads, shopping and image strips left out. '' when nothing is found. Naver answers scripts like a browser and has live answer boxes; it reads English questions too. boxes_only: the answer boxes alone (the web results and news have a data-meta-area).""" page = _get("https://search.naver.com/search.naver?query=" + urllib.parse.quote(query), 4, BROWSER) parts = [] for block in re.split(r'(?=