File size: 1,935 Bytes
75b5d8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import gradio as gr
import requests
import os
from dotenv import load_dotenv

# --- CONFIGURACIÓN ---
load_dotenv()
MI_TOKEN = os.getenv("HF_TOKEN") 

MODELO = "Helsinki-NLP/opus-mt-es-en"

API_URL = f"https://router.huggingface.co/hf-inference/models/{MODELO}"
HEADERS = {"Authorization": f"Bearer {MI_TOKEN}"}

def traducir_texto(texto):
    if not texto:
        return "Escribe algo..."

    print(f"📡 Enviando a traducir ({MODELO})...")

    payload = {"inputs": texto}

    try:
        response = requests.post(API_URL, headers=HEADERS, json=payload)
        
        # Leemos el resultado crudo
        datos = response.json()
        
        if response.status_code == 200:      
            if isinstance(datos, list) and len(datos) > 0:
                return datos[0].get('translation_text', 'No se pudo traducir')
            elif isinstance(datos, dict):
                return datos.get('translation_text', str(datos))
            else:
                return str(datos)

        elif response.status_code == 503:
            return "⏳ El modelo está cargando (Cold Boot). Espera 20 segundos y reintenta."
        
        else:
            return f"❌ Error {response.status_code}: {response.text}"

    except Exception as e:
        return f"Error de conexión: {e}"

# Interfaz
ui = gr.Interface(
    fn=traducir_texto,
    inputs=gr.Textbox(
        label="Texto en Español", 
        placeholder="Escribe aquí (ej: La accesibilidad es vital para la empresa)",
        lines=3
    ),
    outputs=gr.Textbox(label="Traducción al Inglés (Modelo Helsinki-NLP)"),
    title="🌍 Traductor Empresarial",
    description="Herramienta de eliminación de barreras idiomáticas usando IA.",
    examples=[
        ["La inteligencia artificial transforma los negocios."],
        ["Es necesario firmar el contrato antes del lunes."]
    ],
    flagging_mode="never"
)

if __name__ == "__main__":
    ui.launch()