waifu/weather.py
2026-05-19 22:13:49 -06:00

250 lines
8.3 KiB
Python

"""Clima vía Open-Meteo (gratis, sin API key)."""
import json
import re
from datetime import datetime
from zoneinfo import ZoneInfo
import requests as http_requests
TIMEOUT = 12
GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
# WMO weather codes → icon key + descriptions
_WMO = {
0: ("clear", {"es": "Despejado", "en": "Clear sky"}),
1: ("mostly-clear", {"es": "Mayormente despejado","en": "Mainly clear"}),
2: ("partly-cloudy",{"es": "Parcialmente nublado","en": "Partly cloudy"}),
3: ("cloudy", {"es": "Nublado", "en": "Overcast"}),
45: ("fog", {"es": "Niebla", "en": "Fog"}),
48: ("fog", {"es": "Niebla helada", "en": "Depositing rime fog"}),
51: ("drizzle", {"es": "Llovizna ligera", "en": "Light drizzle"}),
53: ("drizzle", {"es": "Llovizna", "en": "Drizzle"}),
55: ("drizzle", {"es": "Llovizna intensa", "en": "Heavy drizzle"}),
61: ("rain", {"es": "Lluvia ligera", "en": "Light rain"}),
63: ("rain", {"es": "Lluvia", "en": "Rain"}),
65: ("rain-heavy", {"es": "Lluvia fuerte", "en": "Heavy rain"}),
71: ("snow", {"es": "Nieve ligera", "en": "Light snow"}),
73: ("snow", {"es": "Nieve", "en": "Snow"}),
75: ("snow", {"es": "Nieve intensa", "en": "Heavy snow"}),
80: ("showers", {"es": "Chubascos ligeros", "en": "Light showers"}),
81: ("showers", {"es": "Chubascos", "en": "Showers"}),
82: ("showers-heavy",{"es": "Chubascos fuertes", "en": "Heavy showers"}),
95: ("thunder", {"es": "Tormenta", "en": "Thunderstorm"}),
96: ("thunder", {"es": "Tormenta con granizo","en": "Thunderstorm with hail"}),
99: ("thunder", {"es": "Tormenta con granizo","en": "Thunderstorm with hail"}),
}
WEATHER_TOOL = {
"type": "function",
"function": {
"name": "get_weather",
"description": (
"Obtiene el clima ACTUAL y de hoy para una ciudad o ubicación. "
"Úsala cuando pregunten por el tiempo, clima, temperatura, lluvia, "
"hace calor/frío hoy, etc. No uses web_search para clima."
),
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Ciudad o lugar, ej. 'Madrid', 'Ciudad de México'. Vacío = ubicación del usuario.",
},
},
"required": [],
},
},
}
WEATHER_PROMPT = """
CLIMA:
Si el system prompt incluye «DATOS DE CLIMA», responde con esos datos de forma natural.
No uses web_search para preguntas de clima/tiempo/temperatura.
"""
_WEATHER_WORDS = re.compile(
r"\b("
r"clima|tiempo|temperatura|lluvia|llover|lloviendo|llovizna|"
r"calor|fr[ií]o|nublado|soleado|tormenta|"
r"weather|forecast|rain|raining|snow|hot|cold|humidity|wind"
r")\b",
re.I,
)
_LOC_PATTERNS = (
re.compile(
r"(?:clima|tiempo|temperatura|weather|forecast)\s+(?:en|de|del|la|in|for|at)\s+"
r"(.+?)(?:\?|[.!]|$)",
re.I,
),
re.compile(
r"(?:en|in|for|at)\s+(.+?)\s+(?:clima|tiempo|weather|forecast)",
re.I,
),
re.compile(
r"(?:qué|que|how(?:'s|\s+is)|what(?:'s|\s+is))\s+(?:el\s+)?(?:clima|tiempo|weather)"
r".*?(?:en|in|for|at)\s+(.+?)(?:\?|[.!]|$)",
re.I,
),
)
_TRAILING_NOISE = re.compile(
r"\b(hoy|today|ahora|now|actual(?:mente)?|currently|por favor|please)\b.*",
re.I,
)
_CITY_ALIASES = {
"tokio": "Tokyo",
"tokyo": "Tokyo",
"cdmx": "Ciudad de México",
"mexico df": "Ciudad de México",
"df": "Ciudad de México",
"nueva york": "New York",
"new york city": "New York",
"ny": "New York",
"la": "Los Angeles",
"bs as": "Buenos Aires",
"buenos aires": "Buenos Aires",
}
def _clean_location(raw: str) -> str:
loc = _TRAILING_NOISE.sub("", (raw or "").strip()).strip(" ,.:;!?-")
if not loc:
return ""
key = loc.lower()
return _CITY_ALIASES.get(key, loc)
def parse_weather_request(text: str) -> tuple[bool, str]:
"""(is_weather, location). location vacío = usar geolocalización del usuario."""
if not text or not _WEATHER_WORDS.search(text):
return False, ""
for pat in _LOC_PATTERNS:
m = pat.search(text)
if m:
loc = _clean_location(m.group(1))
if loc:
return True, loc
return True, ""
def _desc(code: int, lang: str) -> tuple[str, str]:
icon, labels = _WMO.get(code, ("cloudy", {"es": "Nublado", "en": "Cloudy"}))
return labels.get(lang[:2].lower(), labels["en"]), icon
def _geocode(name: str) -> dict | None:
r = http_requests.get(
GEOCODE_URL,
params={"name": name, "count": 1, "language": "es", "format": "json"},
timeout=TIMEOUT,
)
r.raise_for_status()
results = r.json().get("results") or []
return results[0] if results else None
def get_weather(
location: str = "",
lang: str = "es",
lat: float | None = None,
lon: float | None = None,
) -> dict:
"""Devuelve {ok, text, widget?}."""
lang_k = lang[:2].lower() if lang else "es"
place_name = ""
loc = (location or "").strip()
if loc:
geo = _geocode(loc)
if not geo:
return {
"ok": False,
"text": f"No encontré la ubicación «{loc}». Prueba con otra ciudad.",
}
lat = geo["latitude"]
lon = geo["longitude"]
place_name = geo.get("name", loc)
if geo.get("admin1"):
place_name += f", {geo['admin1']}"
if geo.get("country"):
place_name += f", {geo['country']}"
elif lat is not None and lon is not None:
place_name = "Tu ubicación" if lang_k == "es" else "Your location"
else:
return {
"ok": False,
"text": (
"No tengo tu ubicación. Dime una ciudad, ej. «clima en Madrid», "
"o activa la geolocalización en el navegador."
),
}
r = http_requests.get(
FORECAST_URL,
params={
"latitude": lat,
"longitude": lon,
"current": "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m",
"daily": "weather_code,temperature_2m_max,temperature_2m_min",
"timezone": "auto",
"forecast_days": 1,
},
timeout=TIMEOUT,
)
r.raise_for_status()
data = r.json()
cur = data.get("current") or {}
daily = data.get("daily") or {}
code = int(cur.get("weather_code", 3))
description, icon = _desc(code, lang_k)
temp = cur.get("temperature_2m")
humidity = cur.get("relative_humidity_2m")
wind = cur.get("wind_speed_10m")
tz = data.get("timezone", "UTC")
try:
today = datetime.now(ZoneInfo(tz)).strftime("%Y-%m-%d")
except Exception:
today = datetime.utcnow().strftime("%Y-%m-%d")
tmax = (daily.get("temperature_2m_max") or [None])[0]
tmin = (daily.get("temperature_2m_min") or [None])[0]
widget = {
"location": place_name,
"date": today,
"description": description,
"icon": icon,
"code": code,
"temp": round(temp) if temp is not None else None,
"tempMax": round(tmax) if tmax is not None else None,
"tempMin": round(tmin) if tmin is not None else None,
"humidity": humidity,
"wind": round(wind) if wind is not None else None,
"unit": "°C",
}
if lang_k == "es":
text = (
f"Clima en {place_name} hoy ({today}): {description}, "
f"{round(temp)}°C (mín {round(tmin)}° / máx {round(tmax)}°), "
f"humedad {humidity}%, viento {round(wind)} km/h."
)
else:
text = (
f"Weather in {place_name} today ({today}): {description}, "
f"{round(temp)}°C (low {round(tmin)}° / high {round(tmax)}°), "
f"humidity {humidity}%, wind {round(wind)} km/h."
)
return {"ok": True, "text": text, "widget": widget}
def get_weather_text_only(location: str, lang: str, lat=None, lon=None) -> str:
result = get_weather(location, lang, lat, lon)
return result["text"]