VaneM commited on
Commit
2da63e8
1 Parent(s): a2a3e5c

upload app.py

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