File size: 6,063 Bytes
d867b41
 
 
5f5b2d6
 
d867b41
 
 
 
 
5f5b2d6
 
f1df36a
5f5b2d6
f1df36a
d867b41
 
f1df36a
 
 
 
 
 
 
 
 
 
d867b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1df36a
 
 
 
 
 
 
 
 
 
 
5f5b2d6
 
 
f1df36a
 
 
 
5f5b2d6
 
f1df36a
5f5b2d6
 
 
 
 
 
 
f1df36a
 
 
 
 
 
 
 
 
 
5f5b2d6
 
 
 
 
 
f1df36a
d867b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""Some utility functions for the app."""
from base64 import b64encode
from io import BytesIO
import os
import sys
from gtts import gTTS
from mtranslate import translate
from speech_recognition import AudioFile, Recognizer
from transformers import (BlenderbotSmallForConditionalGeneration,
                          BlenderbotSmallTokenizer)
from contextlib import closing
import boto3
from botocore.config import Config

import time


def log_execution_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"Execution time of {func.__name__}: {execution_time} seconds")
        return result
    return wrapper

def stt(audio: object, language: str) -> str:
    """Converts speech to text.

    Args:
        audio: record of user speech

    Returns:
        text (str): recognized speech of user
    """
    r = Recognizer()
    # open the audio file
    with AudioFile(audio) as source:
        # listen for the data (load audio to memory)
        audio_data = r.record(source)
        # recognize (convert from speech to text)
        text = r.recognize_google(audio_data, language=language)
    return text


def to_en_translation(text: str, language: str) -> str:
    """Translates text from specified language to English.

    Args:
        text (str): input text
        language (str): desired language

    Returns:
        str: translated text
    """
    return translate(text, "en", language)


def from_en_translation(text: str, language: str) -> str:
    """Translates text from english to specified language.

    Args:
        text (str): input text
        language (str): desired language

    Returns:
        str: translated text
    """
    return translate(text, language, "en")


class TextGenerationPipeline:
    """Pipeline for text generation of blenderbot model.

    Returns:
        str: generated text
    """

    # load tokenizer and the model
    model_name = "facebook/blenderbot_small-90M"
    tokenizer = BlenderbotSmallTokenizer.from_pretrained(model_name)
    model = BlenderbotSmallForConditionalGeneration.from_pretrained(model_name)

    def __init__(self, **kwargs):
        """Specififying text generation parameters.

        For example: max_length=100 which generates text shorter than
        100 tokens. Visit:
        https://huggingface.co/docs/transformers/main_classes/text_generation
        for more parameters
        """
        self.__dict__.update(kwargs)

    def preprocess(self, text) -> str:
        """Tokenizes input text.

        Args:
            text (str): user specified text

        Returns:
            torch.Tensor (obj): text representation as tensors
        """
        return self.tokenizer(text, return_tensors="pt")

    def postprocess(self, outputs) -> str:
        """Converts tensors into text.

        Args:
            outputs (torch.Tensor obj): model text generation output

        Returns:
            str: generated text
        """
        return self.tokenizer.decode(outputs[0], skip_special_tokens=True)

    def __call__(self, text: str) -> str:
        """Generates text from input text.

        Args:
            text (str): user specified text

        Returns:
            str: generated text
        """
        tokenized_text = self.preprocess(text)
        output = self.model.generate(**tokenized_text, **self.__dict__)
        return self.postprocess(output)


def tts(text: str, language: str) -> object:
    """Converts text into audio object.

    Args:
        text (str): generated answer of bot

    Returns:
        object: text to speech object
    """
    return gTTS(text=text, lang=language, slow=False)


def tts_polly(text: str, language: str) -> object:
    my_config = Config(
        region_name=os.getenv('AWS_REGION', 'us-east-1'),
        # signature_version = 'v4',
        # retries = {
        #     'max_attempts': 10,
        #     'mode': 'standard'
        # }
    )

    client = boto3.client('polly', config=my_config)
    response = client.synthesize_speech(
        Engine='neural',
        OutputFormat='mp3',
        VoiceId='Camila',
        LanguageCode=language,
        Text=text)

    return response


def tts_polly_to_bytesio(polly_object: object) -> bytes:
    # Access the audio stream from the response
    if "AudioStream" in polly_object:
        # Note: Closing the stream is important because the service throttles on the
        # number of parallel connections. Here we are using contextlib.closing to
        # ensure the close method of the stream object will be called automatically
        # at the end of the with statement's scope.
        with closing(polly_object["AudioStream"]) as stream:
            try:
                bytes_object = BytesIO()
                bytes_object.write(stream.read())
                bytes_object.seek(0)
                return bytes_object.getvalue()
            except IOError as error:
                # Could not write to bytes, exit gracefully
                print(error)
                sys.exit(-1)

    else:
        # The response didn't contain audio data, exit gracefully
        print("Could not stream audio")
        sys.exit(-1)


def tts_to_bytesio(tts_object: object) -> bytes:
    """Converts tts object to bytes.

    Args:
        tts_object (object): audio object obtained from gtts

    Returns:
        bytes: audio bytes
    """
    bytes_object = BytesIO()
    tts_object.write_to_fp(bytes_object)
    bytes_object.seek(0)
    return bytes_object.getvalue()


def html_audio_autoplay(bytes: bytes) -> object:
    """Creates html object for autoplaying audio at gradio app.

    Args:
        bytes (bytes): audio bytes

    Returns:
        object: html object that provides audio autoplaying
    """
    b64 = b64encode(bytes).decode()
    html = f"""
    <audio controls autoplay>
    <source src="data:audio/wav;base64,{b64}" type="audio/wav">
    </audio>
    """
    return html