SrGuanche commited on
Commit
4f515d1
·
verified ·
1 Parent(s): c92178b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -33
app.py CHANGED
@@ -2,60 +2,50 @@ import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
  from langdetect import detect
4
 
5
- # --- Configuración de modelos ---
6
- MODEL_NAME = "distilgpt2" # Modelo ligero y estable en CPU
7
- TRANSLATE_TO_ES_MODEL = "Helsinki-NLP/opus-mt-mul-es"
8
- TRANSLATE_FROM_ES_MODEL = "Helsinki-NLP/opus-mt-es-mul"
9
 
10
  # --- Cargar modelos ---
11
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
12
  model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
13
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1)
14
 
15
- translator_to_es = pipeline("translation", model=TRANSLATE_TO_ES_MODEL, device=-1)
16
- translator_from_es = pipeline("translation", model=TRANSLATE_FROM_ES_MODEL, device=-1)
17
 
18
- # --- Funciones de traducción ---
19
- def translate_to_es(text):
20
  try:
21
  lang = detect(text)
22
  except:
23
  lang = "es"
24
- if lang != "es":
25
- try:
26
- translated = translator_to_es(text, max_length=200)[0]["translation_text"]
27
- except:
28
- translated = text
29
- return translated, lang
30
- return text, "es"
31
 
32
- def translate_from_es(text, lang):
33
- if lang != "es":
34
- try:
35
- translated = translator_from_es(text, max_length=200)[0]["translation_text"]
36
- except:
37
- translated = text
38
- return translated
39
  return text
40
 
41
- # --- Función principal del chatbot ---
42
  def answer(history, message):
43
  if not message.strip():
44
  return history, ""
45
 
46
- # Detectar idioma y traducir a español si es necesario
47
- msg_es, lang = translate_to_es(message)
48
 
49
- # Construir contexto
50
  context = ""
51
  for user, bot in history[-6:]:
52
  context += f"Usuario: {user}\nIA: {bot}\n"
53
  context += f"Usuario: {msg_es}\nIA:"
54
 
55
- # Generar respuesta en español
56
  output = generator(
57
  context,
58
- max_new_tokens=100, # límite de tokens para reducir uso de memoria
59
  do_sample=True,
60
  top_k=40,
61
  top_p=0.9,
@@ -67,16 +57,13 @@ def answer(history, message):
67
  else:
68
  response_es = output
69
 
70
- # Traducir de vuelta al idioma original
71
- response_final = translate_from_es(response_es, lang)
72
-
73
- # Añadir al historial
74
  history.append((message, response_final))
75
  return history, ""
76
 
77
  # --- Interfaz Gradio ---
78
  with gr.Blocks() as demo:
79
- gr.Markdown("# 🤖 Chatbot Multilenguaje (Optimizado CPU)")
80
  chat = gr.Chatbot()
81
  msg = gr.Textbox(placeholder="Escribe tu mensaje…")
82
  clear_btn = gr.Button("Limpiar")
 
2
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
  from langdetect import detect
4
 
5
+ # --- Modelos ---
6
+ MODEL_NAME = "distilgpt2" # Chatbot ligero y libre
7
+ EN_ES_MODEL = "Helsinki-NLP/opus-mt-en-es"
8
+ ES_EN_MODEL = "Helsinki-NLP/opus-mt-es-en"
9
 
10
  # --- Cargar modelos ---
11
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
12
  model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
13
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1)
14
 
15
+ translator_en_es = pipeline("translation", model=EN_ES_MODEL, device=-1)
16
+ translator_es_en = pipeline("translation", model=ES_EN_MODEL, device=-1)
17
 
18
+ # --- Funciones ---
19
+ def translate_message(text):
20
  try:
21
  lang = detect(text)
22
  except:
23
  lang = "es"
24
+ if lang.startswith("en"):
25
+ text_es = translator_en_es(text, max_length=100)[0]["translation_text"]
26
+ return text_es, lang
27
+ return text, lang
 
 
 
28
 
29
+ def translate_response(text, lang):
30
+ if lang.startswith("en"):
31
+ text_en = translator_es_en(text, max_length=100)[0]["translation_text"]
32
+ return text_en
 
 
 
33
  return text
34
 
 
35
  def answer(history, message):
36
  if not message.strip():
37
  return history, ""
38
 
39
+ msg_es, lang = translate_message(message)
 
40
 
 
41
  context = ""
42
  for user, bot in history[-6:]:
43
  context += f"Usuario: {user}\nIA: {bot}\n"
44
  context += f"Usuario: {msg_es}\nIA:"
45
 
 
46
  output = generator(
47
  context,
48
+ max_new_tokens=100,
49
  do_sample=True,
50
  top_k=40,
51
  top_p=0.9,
 
57
  else:
58
  response_es = output
59
 
60
+ response_final = translate_response(response_es, lang)
 
 
 
61
  history.append((message, response_final))
62
  return history, ""
63
 
64
  # --- Interfaz Gradio ---
65
  with gr.Blocks() as demo:
66
+ gr.Markdown("# 🤖 Chatbot Español/Inglés (Solo gratuito)")
67
  chat = gr.Chatbot()
68
  msg = gr.Textbox(placeholder="Escribe tu mensaje…")
69
  clear_btn = gr.Button("Limpiar")