fix: Mejorar logging de traducción y timeout
- Añadir logs detallados para debugging de traducciones - Aumentar timeout de 10s a 30s para peticiones largas - Registrar vistas TranslationButton globalmente
This commit is contained in:
@@ -141,13 +141,8 @@ async def on_message(message):
|
||||
text_to_translate = mention_pattern.sub(replace_mention, text_escaped)
|
||||
save_message(message.id, message.guild.id, message.author.id, text_to_translate, mentions_map, 'discord')
|
||||
|
||||
# Creamos una vista filtrada basada en la persistente para mostrar solo los botones activos
|
||||
# Pero los botones mantienen sus custom_ids globales
|
||||
from botdiscord.ui import TranslationButton
|
||||
view = discord.ui.View(timeout=None)
|
||||
|
||||
# Cargamos mapeos para etiquetas de botones
|
||||
from botdiscord.translate import get_name_to_code, get_flag_mapping
|
||||
name_to_code = get_name_to_code("discord")
|
||||
flag_mapping = get_flag_mapping("discord")
|
||||
code_to_name = {v: k for k, v in name_to_code.items()}
|
||||
|
||||
@@ -51,7 +51,6 @@ NAME_TO_CODE = {}
|
||||
|
||||
async def _do_translate_request(session, url, text, target_code):
|
||||
"""Función interna para realizar una única petición de traducción."""
|
||||
# Verificamos si el segmento tiene al menos una letra de cualquier idioma
|
||||
if not text.strip() or not re.search(r'[a-zA-Z\u00C0-\u017F]', text):
|
||||
return text
|
||||
|
||||
@@ -63,14 +62,17 @@ async def _do_translate_request(session, url, text, target_code):
|
||||
}
|
||||
|
||||
try:
|
||||
async with session.post(url, json=payload, timeout=10) as resp:
|
||||
async with session.post(url, json=payload, timeout=30) as resp:
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
translated = data.get("translatedText", text)
|
||||
print(f"[TRANSLATE] Segmento traducido: '{text[:30]}...' -> '{translated[:30]}...'")
|
||||
return translated
|
||||
else:
|
||||
print(f"[TRANSLATE] Error HTTP {resp.status}")
|
||||
return text
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
print(f"[TRANSLATE] Error en petición: {e}")
|
||||
return text
|
||||
|
||||
async def translate_text(text: str, target_lang: str) -> str:
|
||||
@@ -79,15 +81,15 @@ async def translate_text(text: str, target_lang: str) -> str:
|
||||
print(f"[TRANSLATE] URL no configurada")
|
||||
return text
|
||||
|
||||
print(f"[TRANSLATE] target_lang recibido: {target_lang}")
|
||||
print(f"[TRANSLATE] NAME_TO_CODE: {NAME_TO_CODE}")
|
||||
print(f"[TRANSLATE] target_lang recibido: '{target_lang}'")
|
||||
|
||||
target_code = NAME_TO_CODE.get(target_lang, target_lang)
|
||||
print(f"[TRANSLATE] target_code resuelto: {target_code}")
|
||||
print(f"[TRANSLATE] target_code resuelto: '{target_code}'")
|
||||
print(f"[TRANSLATE] texto a traducir: '{text[:100]}...' (largo: {len(text)})")
|
||||
|
||||
# Segmentación mejorada
|
||||
segments = re.split(r'([.!?]+\s*|\n+)', text)
|
||||
segments = [s for s in segments if s]
|
||||
print(f"[TRANSLATE] Segmentos: {len(segments)}")
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
tasks = []
|
||||
@@ -96,7 +98,9 @@ async def translate_text(text: str, target_lang: str) -> str:
|
||||
|
||||
translated_segments = await asyncio.gather(*tasks)
|
||||
|
||||
return "".join(translated_segments)
|
||||
result = "".join(translated_segments)
|
||||
print(f"[TRANSLATE] Resultado final: '{result[:100]}...'")
|
||||
return result
|
||||
|
||||
def translate_text_sync(text: str, target_lang: str) -> str:
|
||||
"""Versión síncrona de translate_text utilizando un hilo separado."""
|
||||
|
||||
@@ -30,6 +30,8 @@ class TranslationButton(discord.ui.Button):
|
||||
return
|
||||
|
||||
original_msg_id = interaction.message.reference.message_id
|
||||
print(f"[UI] Traduciendo mensaje {original_msg_id} a {self.lang_code}")
|
||||
|
||||
db_msg = get_message(original_msg_id)
|
||||
|
||||
if not db_msg:
|
||||
@@ -39,12 +41,17 @@ class TranslationButton(discord.ui.Button):
|
||||
text = db_msg['content']
|
||||
mentions_map = db_msg['mentions_map']
|
||||
|
||||
print(f"[UI] Texto original: {text}")
|
||||
|
||||
# Traducción
|
||||
cached = get_cached_translation(original_msg_id, self.lang_code)
|
||||
if cached:
|
||||
translated = cached
|
||||
print(f"[UI] Usando traducción cacheada: {translated}")
|
||||
else:
|
||||
print(f"[UI] Traduciendo con translate_text...")
|
||||
translated = await translate_text(text, self.lang_code)
|
||||
print(f"[UI] Traducción resultado: {translated}")
|
||||
save_translation(original_msg_id, self.lang_code, translated)
|
||||
|
||||
translated = html.unescape(translated)
|
||||
@@ -71,17 +78,33 @@ class TranslationButton(discord.ui.Button):
|
||||
await interaction.edit_original_response(content=translated, view=new_view)
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"[ERROR UI] {e}")
|
||||
traceback.print_exc()
|
||||
await interaction.followup.send(f"❌ Error: {str(e)}", ephemeral=True)
|
||||
|
||||
class PersistentTranslationView(discord.ui.View):
|
||||
def __init__(self):
|
||||
super().__init__(timeout=None)
|
||||
# Cargamos los botones iniciales usando los datos de la base de datos
|
||||
db_langs = get_available_languages()
|
||||
for lang in db_langs:
|
||||
self.add_item(TranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
|
||||
|
||||
_global_views = {}
|
||||
|
||||
def get_message_translation_view(guild_id: int):
|
||||
view_key = f"msg_trans_{guild_id}"
|
||||
if view_key not in _global_views:
|
||||
_global_views[view_key] = discord.ui.View(timeout=None)
|
||||
active_codes = get_active_languages(guild_id)
|
||||
if not active_codes:
|
||||
active_codes = get_bot_languages("discord")
|
||||
db_langs = get_available_languages()
|
||||
for lang in db_langs:
|
||||
if lang['code'] in active_codes:
|
||||
_global_views[view_key].add_item(TranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
|
||||
return _global_views[view_key]
|
||||
|
||||
class ConfigSelect(discord.ui.Select):
|
||||
def __init__(self, guild_id: int, bot_type: str = "discord"):
|
||||
lang_mapping = get_lang_mapping(bot_type)
|
||||
|
||||
Reference in New Issue
Block a user