mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +00:00
feat(bot): translate all telegram bot messages to spanish
This commit is contained in:
1 parent
1bc1e58781
commit
b690e82f98
3 files changed
+48
-48
No files matched your search
+28
-28
@@ -75,16 +75,16 @@ def load_predictions() -> dict | None:
|
|||||||
or cannot be decoded.
|
or cannot be decoded.
|
||||||
"""
|
"""
|
||||||
if not PREDICTIONS_FILE.exists():
|
if not PREDICTIONS_FILE.exists():
|
||||||
logger.warning("Predictions file not found: %s", PREDICTIONS_FILE)
|
logger.warning("Archivo de predicciones no encontrado: %s", PREDICTIONS_FILE)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with PREDICTIONS_FILE.open(encoding="utf-8") as fh:
|
with PREDICTIONS_FILE.open(encoding="utf-8") as fh:
|
||||||
data = json.load(fh)
|
data = json.load(fh)
|
||||||
logger.info("Predictions loaded from %s", PREDICTIONS_FILE)
|
logger.info("Predicciones cargadas desde %s", PREDICTIONS_FILE)
|
||||||
return data
|
return data
|
||||||
except json.JSONDecodeError as exc:
|
except json.JSONDecodeError as exc:
|
||||||
logger.error("Failed to decode predictions file: %s", exc)
|
logger.error("Error al decodificar el archivo de predicciones: %s", exc)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -129,8 +129,8 @@ def _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str,
|
|||||||
def _message_title(station_name: str, prediction_date: str | None) -> str:
|
def _message_title(station_name: str, prediction_date: str | None) -> str:
|
||||||
"""Return the station header including the prediction date when known."""
|
"""Return the station header including the prediction date when known."""
|
||||||
if prediction_date:
|
if prediction_date:
|
||||||
return f"{station_name} - Prediccion para {prediction_date}"
|
return f"{station_name} - Predicción para {prediction_date}"
|
||||||
return f"{station_name} - Prediccion para manana"
|
return f"{station_name} - Predicción para mañana"
|
||||||
|
|
||||||
|
|
||||||
def format_station_prediction(
|
def format_station_prediction(
|
||||||
@@ -176,7 +176,7 @@ def format_station_prediction(
|
|||||||
source = str(
|
source = str(
|
||||||
prediction.get(
|
prediction.get(
|
||||||
"prediction_source",
|
"prediction_source",
|
||||||
prediction.get("source", "prediccion hibrida (reglas + ML)"),
|
prediction.get("source", "predicción híbrida (reglas + ML)"),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -200,12 +200,12 @@ def format_station_prediction(
|
|||||||
|
|
||||||
weather_lines: list[str] = []
|
weather_lines: list[str] = []
|
||||||
if temp_min is not None and temp_max is not None:
|
if temp_min is not None and temp_max is not None:
|
||||||
weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C")
|
weather_lines.append(f"Temperatura: {temp_min:.0f}ºC / {temp_max:.0f}ºC")
|
||||||
elif temp_max is not None:
|
elif temp_max is not None:
|
||||||
weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C")
|
weather_lines.append(f"Temperatura máxima: {temp_max:.0f}ºC")
|
||||||
|
|
||||||
if snowfall is not None:
|
if snowfall is not None:
|
||||||
weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos")
|
weather_lines.append(f"Nieve: {snowfall:.0f} cm nuevos")
|
||||||
|
|
||||||
if wind_speed is not None and wind_gust is not None:
|
if wind_speed is not None and wind_gust is not None:
|
||||||
weather_lines.append(
|
weather_lines.append(
|
||||||
@@ -239,10 +239,10 @@ def format_station_prediction(
|
|||||||
def _no_prediction_message(station_name: str) -> str:
|
def _no_prediction_message(station_name: str) -> str:
|
||||||
"""Return a friendly error message when prediction data is unavailable."""
|
"""Return a friendly error message when prediction data is unavailable."""
|
||||||
return (
|
return (
|
||||||
f"Lo siento, no hay prediccion disponible para <b>{station_name}</b> en este "
|
f"Lo siento, no hay predicción disponible para <b>{station_name}</b> en este "
|
||||||
f"momento.\n\n"
|
f"momento.\n\n"
|
||||||
f"<i>El pipeline de datos se ejecuta diariamente. "
|
f"<i>El pipeline de datos se ejecuta diariamente. "
|
||||||
f"Intentalo de nuevo mas tarde.</i>"
|
f"Inténtalo de nuevo más tarde.</i>"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -250,8 +250,8 @@ def _unavailable_message() -> str:
|
|||||||
"""Return a message when the predictions file cannot be loaded at all."""
|
"""Return a message when the predictions file cannot be loaded at all."""
|
||||||
return (
|
return (
|
||||||
"No se han podido cargar las predicciones.\n\n"
|
"No se han podido cargar las predicciones.\n\n"
|
||||||
"<i>Asegurate de que el pipeline diario se ha ejecutado correctamente. "
|
"<i>Asegúrate de que el pipeline diario se ha ejecutado correctamente. "
|
||||||
"Intentalo de nuevo mas tarde.</i>"
|
"Inténtalo de nuevo más tarde.</i>"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -263,14 +263,14 @@ def _unavailable_message() -> str:
|
|||||||
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Handle the /start command with a welcome message."""
|
"""Handle the /start command with a welcome message."""
|
||||||
text = (
|
text = (
|
||||||
"<b>Bienvenido al bot de prediccion de estaciones de esqui!</b>\n\n"
|
"<b>¡Bienvenido al bot de predicción de estaciones de esquí!</b>\n\n"
|
||||||
"Este bot te informa sobre las condiciones previstas para el dia "
|
"Este bot te informa sobre las condiciones previstas para el día "
|
||||||
"siguiente en tres estaciones de esqui del norte de Espana:\n\n"
|
"siguiente en tres estaciones de esquí del norte de España:\n\n"
|
||||||
" - <b>Valgrande-Pajares</b>\n"
|
" - <b>Valgrande-Pajares</b>\n"
|
||||||
" - <b>San Isidro</b>\n"
|
" - <b>San Isidro</b>\n"
|
||||||
" - <b>Fuentes de Invierno</b>\n\n"
|
" - <b>Fuentes de Invierno</b>\n\n"
|
||||||
"Las predicciones combinan reglas operacionales y modelos de "
|
"Las predicciones combinan reglas operacionales y modelos de "
|
||||||
"aprendizaje automatico basados en datos meteorologicos.\n\n"
|
"aprendizaje automático basados en datos meteorológicos.\n\n"
|
||||||
"Escribe /help para ver los comandos disponibles."
|
"Escribe /help para ver los comandos disponibles."
|
||||||
)
|
)
|
||||||
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
||||||
@@ -280,9 +280,9 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|||||||
"""Handle the /help command with a list of available commands."""
|
"""Handle the /help command with a list of available commands."""
|
||||||
text = (
|
text = (
|
||||||
"<b>Comandos disponibles:</b>\n\n"
|
"<b>Comandos disponibles:</b>\n\n"
|
||||||
"/pajares — Prediccion para Valgrande-Pajares\n"
|
"/pajares — Predicción para Valgrande-Pajares\n"
|
||||||
"/sanisidro — Prediccion para San Isidro\n"
|
"/sanisidro — Predicción para San Isidro\n"
|
||||||
"/fuentes — Prediccion para Fuentes de Invierno\n"
|
"/fuentes — Predicción para Fuentes de Invierno\n"
|
||||||
"/all — Predicciones para las tres estaciones\n"
|
"/all — Predicciones para las tres estaciones\n"
|
||||||
"/help — Mostrar esta ayuda\n"
|
"/help — Mostrar esta ayuda\n"
|
||||||
)
|
)
|
||||||
@@ -310,7 +310,7 @@ async def _send_station(
|
|||||||
station_predictions = _extract_station_predictions(predictions)
|
station_predictions = _extract_station_predictions(predictions)
|
||||||
station_pred = station_predictions.get(station_key)
|
station_pred = station_predictions.get(station_key)
|
||||||
if not station_pred:
|
if not station_pred:
|
||||||
logger.warning("No prediction entry for station '%s'", station_key)
|
logger.warning("No hay entrada de predicción para la estación '%s'", station_key)
|
||||||
text = _no_prediction_message(station_name)
|
text = _no_prediction_message(station_name)
|
||||||
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
||||||
return
|
return
|
||||||
@@ -322,7 +322,7 @@ async def _send_station(
|
|||||||
predictions.get("prediction_date"),
|
predictions.get("prediction_date"),
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.exception("Error formatting prediction for '%s': %s", station_key, exc)
|
logger.exception("Error al formatear la predicción para '%s': %s", station_key, exc)
|
||||||
text = _no_prediction_message(station_name)
|
text = _no_prediction_message(station_name)
|
||||||
|
|
||||||
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
await update.message.reply_text(text, parse_mode=ParseMode.HTML)
|
||||||
@@ -330,25 +330,25 @@ async def _send_station(
|
|||||||
|
|
||||||
async def cmd_pajares(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_pajares(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Handle the /pajares command — prediction for Valgrande-Pajares."""
|
"""Handle the /pajares command — prediction for Valgrande-Pajares."""
|
||||||
logger.info("User %s requested /pajares", update.effective_user.id)
|
logger.info("El usuario %s solicitó /pajares", update.effective_user.id)
|
||||||
await _send_station(update, "pajares")
|
await _send_station(update, "pajares")
|
||||||
|
|
||||||
|
|
||||||
async def cmd_sanisidro(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_sanisidro(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Handle the /sanisidro command — prediction for San Isidro."""
|
"""Handle the /sanisidro command — prediction for San Isidro."""
|
||||||
logger.info("User %s requested /sanisidro", update.effective_user.id)
|
logger.info("El usuario %s solicitó /sanisidro", update.effective_user.id)
|
||||||
await _send_station(update, "sanisidro")
|
await _send_station(update, "sanisidro")
|
||||||
|
|
||||||
|
|
||||||
async def cmd_fuentes(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_fuentes(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Handle the /fuentes command — prediction for Fuentes de Invierno."""
|
"""Handle the /fuentes command — prediction for Fuentes de Invierno."""
|
||||||
logger.info("User %s requested /fuentes", update.effective_user.id)
|
logger.info("El usuario %s solicitó /fuentes", update.effective_user.id)
|
||||||
await _send_station(update, "fuentes")
|
await _send_station(update, "fuentes")
|
||||||
|
|
||||||
|
|
||||||
async def cmd_all(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def cmd_all(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Handle the /all command — predictions for all three stations."""
|
"""Handle the /all command — predictions for all three stations."""
|
||||||
logger.info("User %s requested /all", update.effective_user.id)
|
logger.info("El usuario %s solicitó /all", update.effective_user.id)
|
||||||
for station_key in ("pajares", "sanisidro", "fuentes"):
|
for station_key in ("pajares", "sanisidro", "fuentes"):
|
||||||
await _send_station(update, station_key)
|
await _send_station(update, station_key)
|
||||||
|
|
||||||
@@ -368,11 +368,11 @@ def main() -> None:
|
|||||||
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
||||||
if not token:
|
if not token:
|
||||||
raise EnvironmentError(
|
raise EnvironmentError(
|
||||||
"La variable de entorno TELEGRAM_BOT_TOKEN no esta definida. "
|
"La variable de entorno TELEGRAM_BOT_TOKEN no está definida. "
|
||||||
"Configura el token del bot antes de iniciar."
|
"Configura el token del bot antes de iniciar."
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info("Iniciando bot de prediccion de esqui...")
|
logger.info("Iniciando bot de predicción de esquí...")
|
||||||
|
|
||||||
app = Application.builder().token(token).build()
|
app = Application.builder().token(token).build()
|
||||||
|
|
||||||
|
|||||||
@@ -69,27 +69,27 @@ def _build_weather_summary(weather_data: dict[str, Any]) -> str:
|
|||||||
temp_max = weather_data.get("temperature_2m_max")
|
temp_max = weather_data.get("temperature_2m_max")
|
||||||
temp_min = weather_data.get("temperature_2m_min")
|
temp_min = weather_data.get("temperature_2m_min")
|
||||||
if temp_max is not None and temp_min is not None:
|
if temp_max is not None and temp_min is not None:
|
||||||
parts.append(f"Temp {temp_min:.0f}–{temp_max:.0f} °C")
|
parts.append(f"Tª {temp_min:.0f}–{temp_max:.0f} °C")
|
||||||
elif temp_max is not None:
|
elif temp_max is not None:
|
||||||
parts.append(f"Temp max {temp_max:.0f} °C")
|
parts.append(f"Tª máx {temp_max:.0f} °C")
|
||||||
|
|
||||||
snowfall = weather_data.get("snowfall_sum")
|
snowfall = weather_data.get("snowfall_sum")
|
||||||
if snowfall is not None and snowfall > 0:
|
if snowfall is not None and snowfall > 0:
|
||||||
parts.append(f"Snow {snowfall:.0f} cm")
|
parts.append(f"Nieve {snowfall:.0f} cm")
|
||||||
|
|
||||||
snow_depth = weather_data.get("snow_depth")
|
snow_depth = weather_data.get("snow_depth")
|
||||||
if snow_depth is not None:
|
if snow_depth is not None:
|
||||||
parts.append(f"Depth {snow_depth:.0f} cm")
|
parts.append(f"Espesor {snow_depth:.0f} cm")
|
||||||
|
|
||||||
precip = weather_data.get("precipitation_sum")
|
precip = weather_data.get("precipitation_sum")
|
||||||
if precip is not None and precip > 0:
|
if precip is not None and precip > 0:
|
||||||
parts.append(f"Rain {precip:.1f} mm")
|
parts.append(f"Lluvia {precip:.1f} mm")
|
||||||
|
|
||||||
wind_gust = weather_data.get("wind_gusts_10m_max")
|
wind_gust = weather_data.get("wind_gusts_10m_max")
|
||||||
if wind_gust is not None:
|
if wind_gust is not None:
|
||||||
parts.append(f"Gusts {wind_gust:.0f} km/h")
|
parts.append(f"Rachas {wind_gust:.0f} km/h")
|
||||||
|
|
||||||
return " | ".join(parts) if parts else "No weather data available."
|
return " | ".join(parts) if parts else "Sin datos meteorológicos disponibles."
|
||||||
|
|
||||||
|
|
||||||
class HybridPredictor:
|
class HybridPredictor:
|
||||||
@@ -413,9 +413,9 @@ class HybridPredictor:
|
|||||||
reasons_text = " ".join(reasons).lower()
|
reasons_text = " ".join(reasons).lower()
|
||||||
|
|
||||||
# Infer crowd from rule reasons text
|
# Infer crowd from rule reasons text
|
||||||
if "high crowd" in reasons_text or "busy" in reasons_text:
|
if "afluencia alto" in reasons_text or "concurrida" in reasons_text:
|
||||||
return "high"
|
return "high"
|
||||||
if "low crowd" in reasons_text:
|
if "afluencia bajo" in reasons_text:
|
||||||
return "low"
|
return "low"
|
||||||
|
|
||||||
# Use ML prediction if available
|
# Use ML prediction if available
|
||||||
|
|||||||
+11
-11
@@ -158,8 +158,8 @@ class RulesEngine:
|
|||||||
if wind_gust >= wind_threshold:
|
if wind_gust >= wind_threshold:
|
||||||
force_closed = True
|
force_closed = True
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Wind gust {wind_gust:.1f} km/h exceeds closure threshold "
|
f"Rachas de viento de {wind_gust:.1f} km/h superan el umbral de cierre de "
|
||||||
f"of {wind_threshold} km/h."
|
f"{wind_threshold} km/h."
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"[%s] Rule 1 fired: wind gust %.1f > %.1f km/h -> force_closed",
|
"[%s] Rule 1 fired: wind gust %.1f > %.1f km/h -> force_closed",
|
||||||
@@ -177,8 +177,8 @@ class RulesEngine:
|
|||||||
force_closed = True
|
force_closed = True
|
||||||
km_factor = 0.0
|
km_factor = 0.0
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Snow depth {snow_depth:.1f} cm is below the minimum "
|
f"El espesor de nieve ({snow_depth:.1f} cm) está por debajo del mínimo "
|
||||||
f"required {min_snow} cm."
|
f"requerido ({min_snow} cm)."
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed",
|
"[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed",
|
||||||
@@ -198,8 +198,8 @@ class RulesEngine:
|
|||||||
):
|
):
|
||||||
km_factor = max(0.0, km_factor - _WARM_RAIN_KM_FACTOR_REDUCTION)
|
km_factor = max(0.0, km_factor - _WARM_RAIN_KM_FACTOR_REDUCTION)
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Temperature {temp_max:.1f} °C above {_RAIN_TEMPERATURE_THRESHOLD_C} °C "
|
f"Temperatura de {temp_max:.1f} °C (superior a {_RAIN_TEMPERATURE_THRESHOLD_C} °C) "
|
||||||
f"with {precip:.1f} mm precipitation; estimated open slopes reduced."
|
f"con {precip:.1f} mm de precipitación; se estima una reducción de pistas abiertas."
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"[%s] Rule 3 fired: temp %.1f °C + rain %.1f mm -> km_factor reduced to %.2f",
|
"[%s] Rule 3 fired: temp %.1f °C + rain %.1f mm -> km_factor reduced to %.2f",
|
||||||
@@ -222,8 +222,8 @@ class RulesEngine:
|
|||||||
):
|
):
|
||||||
force_open = True
|
force_open = True
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Heavy fresh snow ({snowfall_24h:.1f} cm in 24 h) with manageable "
|
f"Nevada intensa ({snowfall_24h:.1f} cm en 24 h) con viento moderado "
|
||||||
f"wind ({wind_speed:.1f} km/h); station very likely open and busy."
|
f"({wind_speed:.1f} km/h); es muy probable que la estación abra y esté concurrida."
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"[%s] Rule 4 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open",
|
"[%s] Rule 4 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open",
|
||||||
@@ -240,15 +240,15 @@ class RulesEngine:
|
|||||||
|
|
||||||
if not is_busy_day and no_fresh_snow and not force_closed:
|
if not is_busy_day and no_fresh_snow and not force_closed:
|
||||||
reasons.append(
|
reasons.append(
|
||||||
"Weekday with no significant fresh snow; crowd level expected to be low."
|
"Día laborable sin nevadas significativas; se espera un nivel de afluencia bajo."
|
||||||
)
|
)
|
||||||
logger.debug("[%s] Rule 5 fired: weekday + no fresh snow -> low crowd", station_name)
|
logger.debug("[%s] Rule 5 fired: weekday + no fresh snow -> low crowd", station_name)
|
||||||
|
|
||||||
# ---- Rule 6: Weekend/holiday + fresh snow -> high crowd ----------
|
# ---- Rule 6: Weekend/holiday + fresh snow -> high crowd ----------
|
||||||
if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed:
|
if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed:
|
||||||
reasons.append(
|
reasons.append(
|
||||||
f"Weekend or holiday with {snowfall_24h:.1f} cm of fresh snow; "
|
f"Fin de semana o festivo con {snowfall_24h:.1f} cm de nieve fresca; "
|
||||||
"crowd level expected to be high."
|
"se espera un nivel de afluencia alto."
|
||||||
)
|
)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"[%s] Rule 6 fired: busy day + fresh snow %.1f cm -> high crowd",
|
"[%s] Rule 6 fired: busy day + fresh snow %.1f cm -> high crowd",
|
||||||
|
|||||||
Reference in new issue
Block a user