VaneM commited on
Commit
ca7cfd8
·
1 Parent(s): c06b431

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +85 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration, pipeline
3
+ import torch
4
+
5
+
6
+ # Cargamos el modelo para el chat
7
+ model_name = 'facebook/blenderbot-400M-distill'
8
+ tokenizer = BlenderbotTokenizer.from_pretrained(model_name)
9
+ model = BlenderbotForConditionalGeneration.from_pretrained(model_name)
10
+
11
+
12
+ # Cargamos el traductor de ingles a español
13
+ english_model_name = "Helsinki-NLP/opus-mt-en-es"
14
+ translator_en_es = pipeline("translation", model=english_model_name)
15
+
16
+ # Cargamos el traductor de español a ingles
17
+ spanish_model_name = "Helsinki-NLP/opus-mt-es-en"
18
+ translator_es_en = pipeline("translation", model=spanish_model_name)
19
+
20
+
21
+ def take_last_tokens(inputs, note_history, history):
22
+ """Filtrar los últimos 128 tokens"""
23
+ if inputs['input_ids'].shape[1] > 128:
24
+ inputs['input_ids'] = torch.tensor([inputs['input_ids'][0][-128:].tolist()])
25
+ inputs['attention_mask'] = torch.tensor([inputs['attention_mask'][0][-128:].tolist()])
26
+ note_history = ['</s> <s>'.join(note_history[0].split('</s> <s>')[2:])]
27
+ history = history[1:]
28
+ return inputs, note_history, history
29
+
30
+ def add_note_to_history(note, note_history):
31
+ """Añadir una nota a la información histórica del chat"""
32
+ note_history.append(note)
33
+ note_history = '</s> <s>'.join(note_history)
34
+ return [note_history]
35
+
36
+
37
+ def predict(text, history):
38
+ history = history or []
39
+ if history:
40
+ history_useful = ['</s> <s>'.join([str(a[0])+'</s> <s>'+str(a[1]) for a in history])]
41
+ else:
42
+ history_useful = []
43
+ # Traducimos el texto ingresado a ingles
44
+ text_input = translator_es_en(text)[0]['translation_text']
45
+
46
+ # comparamos con el historial y codificamos la nueva entrada del usuario
47
+ history_useful = add_note_to_history(text_input, history_useful)
48
+ inputs = tokenizer(history_useful, return_tensors="pt")
49
+ inputs, history_useful, history = take_last_tokens(inputs, history_useful, history)
50
+
51
+ # Generar una respuesta
52
+ reply_ids = model.generate(**inputs)
53
+ response = tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0]
54
+
55
+ # sumamos la respuesta al historial del chat
56
+ history_useful = add_note_to_history(response, history_useful)
57
+ list_history = history_useful[0].split('</s> <s>')
58
+ history.append((list_history[-2], list_history[-1]))
59
+
60
+ # Obtenemos el resultado en español
61
+ spanish_text = translator_en_es(response)
62
+ result_es = spanish_text[0]['translation_text']
63
+ return result_es, history
64
+
65
+ description = """
66
+ <h2 style="text-align:center">Inicia el chat con la IA que ha sido entrenada para hablar contigo sobre lo que quieras.</h2>
67
+ <h2 style="text-align:center">¡Hablemos!</h2>
68
+ """
69
+ article = """Instrucciones:
70
+ \n1. Inserte el texto en la casilla de texto
71
+ \n2. Presionar 'Enviar' y esperar la respuesta
72
+ \n4. Para enviar otro texto borrar el actual y volver al punto 1.
73
+
74
+ El modelo usa:
75
+ - Modelo conversacional [facebook/blenderbot-400M-distill](https://huggingface.co/facebook/blenderbot-400M-distill?text=Hey+my+name+is+Julien%21+How+are+you%3F),
76
+ - Para las traducciones [Helsinki-NLP](https://huggingface.co/Helsinki-NLP)
77
+ \n ... y mucha magia ☺
78
+ """
79
+
80
+ gr.Interface(fn=predict,
81
+ title="ChatBot Text-to-Text en Español",
82
+ inputs= [gr.Textbox("", max_lines = 5, label = "Inserte su texto aqui") , 'state'],
83
+ outputs = [gr.Textbox("", label = "Respuesta de IA en forma de texto"), 'state'],
84
+ description = description ,
85
+ article = article).launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers==4.21.0
2
+ gradio==3.11.0
3
+ torch==1.12.1
4
+ sacremoses==0.0.53
5
+ sentencepiece==0.1.97