feat: implementar traducción multilingüe mediante segmentación de oraciones para Discord y Telegram
This commit is contained in:
@@ -47,13 +47,19 @@ REVERSE_MAPPING = {}
|
||||
FLAG_MAPPING = {}
|
||||
NAME_TO_CODE = {}
|
||||
|
||||
async def translate_text(text: str, target_lang: str) -> str:
|
||||
url = get_libretranslate_url()
|
||||
# Nos aseguramos de enviar el CÓDIGO del idioma (ej. 'en') a la API.
|
||||
# Si recibimos un nombre (ej. 'English'), NAME_TO_CODE lo convierte a 'en'.
|
||||
# Si ya recibimos un código (ej. 'en'), lo usamos directamente.
|
||||
target_code = NAME_TO_CODE.get(target_lang, target_lang)
|
||||
|
||||
import aiohttp
|
||||
import re
|
||||
import asyncio
|
||||
from botdiscord.config import get_libretranslate_url, get_languages
|
||||
from botdiscord.database import get_available_languages, get_bot_languages
|
||||
|
||||
# ... (mantener funciones load_lang_mappings y getters de mapping iguales)
|
||||
|
||||
async def _do_translate_request(session, url, text, target_code):
|
||||
"""Función interna para realizar una única petición de traducción."""
|
||||
if not text.strip() or not re.search(r'[a-zA-ZáéíóúÁÉÍÓÚñÑ]', text):
|
||||
return text
|
||||
|
||||
payload = {
|
||||
"q": text,
|
||||
"source": "auto",
|
||||
@@ -61,16 +67,35 @@ async def translate_text(text: str, target_lang: str) -> str:
|
||||
"format": "html"
|
||||
}
|
||||
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
return data.get("translatedText", text)
|
||||
else:
|
||||
return text # Devolvemos el original si falla la API
|
||||
except Exception:
|
||||
return text # Devolvemos el original si hay error de conexión
|
||||
|
||||
async def translate_text(text: str, target_lang: str) -> str:
|
||||
url = get_libretranslate_url()
|
||||
if not url:
|
||||
return "Error: URL de LibreTranslate no configurada"
|
||||
|
||||
target_code = NAME_TO_CODE.get(target_lang, target_lang)
|
||||
|
||||
# Segmentación: Dividimos por oraciones (. ! ? \n) pero manteniendo los delimitadores
|
||||
# El patrón busca los delimitadores y los incluye en la lista resultante
|
||||
segments = re.split(r'(\. |\! |\? |\n)', text)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
return data.get("translatedText", "Error en la traducción.")
|
||||
else:
|
||||
return f"Error de API: {resp.status}"
|
||||
except Exception as e:
|
||||
return f"Error de conexión: {str(e)}"
|
||||
tasks = []
|
||||
for segment in segments:
|
||||
tasks.append(_do_translate_request(session, url, segment, target_code))
|
||||
|
||||
translated_segments = await asyncio.gather(*tasks)
|
||||
|
||||
return "".join(translated_segments)
|
||||
|
||||
def get_lang_mapping(bot_type: str = None) -> dict:
|
||||
load_lang_mappings(bot_type)
|
||||
|
||||
@@ -68,24 +68,13 @@ def get_lang_keyboard(bot_type="telegram"):
|
||||
return InlineKeyboardMarkup(keyboard)
|
||||
|
||||
async def translate_text_telegram(text: str, target_lang: str) -> str:
|
||||
url = get_libretranslate_url()
|
||||
payload = {
|
||||
"q": text,
|
||||
"source": "auto",
|
||||
"target": target_lang,
|
||||
"format": "text"
|
||||
}
|
||||
# Usamos la función compartida de translate.py para tener segmentación y soporte multilingüe
|
||||
from botdiscord.translate import translate_text
|
||||
translated = await translate_text(text, target_lang)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=10) as resp:
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
return data.get("translatedText", "Error en la traducción.")
|
||||
else:
|
||||
return f"Error de API: {resp.status}"
|
||||
except Exception as e:
|
||||
return f"Error de conexión: {str(e)}"
|
||||
# Desescapamos el HTML para Telegram (evitar " etc)
|
||||
import html
|
||||
return html.unescape(translated)
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
await update.message.reply_text(
|
||||
|
||||
32
plan.md
Normal file
32
plan.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Plan de Acción: Traducción Multilingüe (Discord y Telegram)
|
||||
|
||||
## 1. Problema Identificado
|
||||
Actualmente, ambos bots envían el mensaje completo a LibreTranslate. Con la detección automática (`source: auto`), el motor elige un único idioma dominante. Esto causa que en mensajes mixtos (ej: "Hello! ¿Cómo estás?"), las partes que no coinciden con el idioma detectado no se traduzcan correctamente en ninguna de las dos plataformas.
|
||||
|
||||
## 2. Estrategia de Solución: Segmentación Unificada
|
||||
La solución consiste en crear una lógica de traducción centralizada que divida el texto en unidades lógicas (oraciones) y las traduzca de forma independiente.
|
||||
|
||||
### Fase A: Centralización en `botdiscord/translate.py`
|
||||
1. **Nueva Función Core:** Crear `translate_multilingual_text(text, target_lang)` en el módulo compartido.
|
||||
2. **Uso en Telegram:** Migrar `bottelegram/telegram_bot.py` para que use esta función centralizada en lugar de su propia `translate_text_telegram`.
|
||||
3. **Soporte HTML:** Activar el modo HTML para Telegram también, permitiendo proteger menciones de usuario (`@username`) de forma similar a como se hizo en Discord.
|
||||
|
||||
### Fase B: Segmentación y Paralelismo
|
||||
1. **División:** Usar expresiones regulares (`re.split`) para fragmentar por `.`, `!`, `?` y saltos de línea `\n`.
|
||||
2. **Peticiones Concurrentes:** Utilizar `asyncio.gather` para traducir todos los fragmentos simultáneamente. Esto evita que el bot se vuelva lento a pesar de hacer más peticiones a la API.
|
||||
3. **Detección Localizada:** Al procesar frases cortas, LibreTranslate podrá detectar correctamente el idioma de cada fragmento individual.
|
||||
|
||||
### Fase C: Reconstrucción y Formatos Especiales
|
||||
1. **Discord:** Mantener la protección de etiquetas `<mX />` para menciones de roles y canales.
|
||||
2. **Telegram:** Asegurar que la lógica funcione tanto para mensajes de texto simples como para **pies de foto (captions)** en imágenes, videos y documentos.
|
||||
3. **Ensamblado:** Unir las piezas respetando la puntuación y el espaciado original.
|
||||
|
||||
## 3. Ventajas e Inconvenientes
|
||||
* **Ventaja:** Traducción coherente y completa para usuarios que mezclan idiomas. Sincronización de comportamiento entre Discord y Telegram.
|
||||
* **Inconveniente:** Mayor carga de red hacia la instancia de LibreTranslate. Se recomienda monitorizar el rendimiento del servidor de traducción.
|
||||
|
||||
## 4. Próximos Pasos (Implementación)
|
||||
1. **Refactorizar `botdiscord/translate.py`:** Implementar la lógica de segmentación por oraciones.
|
||||
2. **Actualizar Bot Telegram:** Reemplazar `translate_text_telegram` por la nueva función centralizada.
|
||||
3. **Actualizar Bot Discord:** Modificar el callback en `ui.py` para usar la nueva segmentación.
|
||||
|
||||
Reference in New Issue
Block a user