File size: 8,375 Bytes
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
fb7e4f3
cf4f031
 
9d616d2
c59a3c0
 
 
 
 
 
 
 
 
cf4f031
c59a3c0
 
 
 
 
 
 
 
cf4f031
 
 
 
 
 
 
9d616d2
c59a3c0
fb7e4f3
 
 
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d616d2
c59a3c0
 
 
 
 
cf4f031
9d616d2
 
 
 
 
 
 
 
 
cf4f031
9d616d2
 
 
 
 
 
cf4f031
c59a3c0
cf4f031
 
 
db6bb35
cf4f031
 
 
 
 
 
 
c59a3c0
 
 
 
 
 
9d616d2
cf4f031
 
 
 
 
db6bb35
 
 
 
 
9d616d2
db6bb35
 
 
cf4f031
db6bb35
cf4f031
 
 
 
 
 
 
 
 
 
 
 
 
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb7e4f3
 
 
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d616d2
9635299
9d616d2
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
 
fb7e4f3
c59a3c0
 
 
 
 
 
 
 
 
 
 
 
fb7e4f3
9d616d2
 
 
 
 
 
 
4b39b8f
 
 
 
9d616d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
from transformers import pipeline
import re
from num2words import num2words
import aiohttp
from aiohttp import ClientSession
from aiohttp_retry import RetryClient, ExponentialRetry
from tqdm import tqdm
import asyncio
import os
from dotenv import load_dotenv
import requests
import ffmpeg
import torch
import aiofiles
import tempfile
import subprocess


# load khaya token from environment
load_dotenv()

# load khaya token
KHAYA_TOKEN = os.getenv("KHAYA_TOKEN")

translation_url = "https://translation-api.ghananlp.org/v1/translate"
tts_url = "https://tts-backend-nlpghana-staging.azurewebsites.net/v0/tts"

translation_hdr = {
    # Request headers
    "Content-Type": "application/json",
    "Cache-Control": "no-cache",
    "Ocp-Apim-Subscription-Key": KHAYA_TOKEN,
}

tts_header = {
    # Request headers
    "Content-Type": "application/json",
    "Cache-Control": "no-cache",
    "Ocp-Apim-Subscription-Key": f"{KHAYA_TOKEN}",
}

LANG_DICT = {"Twi": "tw", "Ewe": "ee"}

# Check if GPU is available
pipe_device = 0 if torch.cuda.is_available() else -1


def replace_numbers_with_words(text):
    def replace(match):
        return num2words(match.group().replace(",", ""), lang="en")

    return re.sub(r"[\d]+[.,\d]+", replace, text)


async def fetch(session, url, headers, data, semaphore, index):
    async with semaphore:
        try:
            async with session.post(
                url, headers=headers, json=data, timeout=10
            ) as response:
                response.raise_for_status()
                return index, await response.json()
        except aiohttp.ClientError as e:
            print(f"Request error: {e}")
            return index, str(e)
        except Exception as e:
            print(f"Unexpected error: {e}")
            return index, str(e)


async def translation_main(sentences, url, headers, lang):
    khaya_translations = [None] * len(sentences)
    semaphore = asyncio.Semaphore(2)  # limit the number of concurrent requests
    retry_options = ExponentialRetry(
        attempts=3,
    )

    async with RetryClient(ClientSession(), retry_options=retry_options) as session:
        tasks = []
        for index, sent in enumerate(sentences):
            data = {"in": sent, "lang": f"en-{lang}"}
            tasks.append(fetch(session, url, headers, data, semaphore, index))

        for f in tqdm(
            asyncio.as_completed(tasks), total=len(tasks), desc="Translating Sentences"
        ):
            index, result = await f
            # TODO: handle error response
            khaya_translations[index] = result

    return khaya_translations


async def convert_text_to_speech(
    session,
    tts_url,
    tts_header,
    text,
    text_index,
    language,
    speaker,
    semaphore,
    output_dir,
):
    speaker_dict = {
        "tw": {"male": "twi_speaker_5", "female": "twi_speaker_7"},
        "ee": {"male": "ewe_speaker_3", "female": None},
    }
    speaker_id = speaker_dict[language][speaker]
    data = {"text": text, "language": language, "speaker_id": speaker_id}

    try:
        async with semaphore:
            async with session.post(tts_url, headers=tts_header, json=data) as response:
                response.raise_for_status()
                output_path = os.path.join(output_dir, f"{text_index}_tts.wav")
                async with aiofiles.open(output_path, "wb") as file:
                    while True:
                        chunk = await response.content.read(16384)
                        if not chunk:
                            break
                        await file.write(chunk)
        return output_path
    except aiohttp.ClientError as e:
        print(f"Request error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")


async def tts_main(khaya_translations, speaker, language):
    with tempfile.TemporaryDirectory() as temp_dir:
        async with aiohttp.ClientSession() as session:
            semaphore = asyncio.Semaphore(3)
            tasks = [
                convert_text_to_speech(
                    session,
                    tts_url,
                    tts_header,
                    sent,
                    text_index,
                    language,
                    speaker,
                    semaphore,
                    temp_dir,
                )
                for text_index, sent in enumerate(khaya_translations)
            ]
            output_files = []
            for task in tqdm(
                asyncio.as_completed(tasks),
                total=len(tasks),
                desc="Converting to Speech",
            ):
                result = await task
                if result:
                    output_files.append(result)

            output_audio = combine_audio_streams(output_files, "combined_audio.wav")
            return output_audio


def extract_audio_from_video(input_video):
    if input_video:
        output_audio_path = f"separated_audio.aac"
        try:
            (
                ffmpeg.input(f"{input_video}")
                .output(f"{output_audio_path}", acodec="copy", vn=None)
                .run(overwrite_output=True)
            )
            print("Audio extracted successfully")
            return output_audio_path
        except ffmpeg.Error as e:
            print(e.stderr.decode())
            raise e


def transcribe_and_preprocess_audio(input_audio):
    asr = pipeline(
        "automatic-speech-recognition",
        model="openai/whisper-large-v3",
        device=pipe_device,
    )
    pipeline_whisper_output = asr(
        f"{input_audio}",
        return_timestamps=True,
    )

    # preprocess the output before machine translation
    sentences = pipeline_whisper_output["text"].split(". ")
    sentences = [el.strip() for el in sentences if el]

    # replace numbers with words
    sentences = [replace_numbers_with_words(sent) for sent in sentences]
    return sentences


def combine_audio_streams(list_of_output_chunks, output_audio):
    list_of_output_chunks = sorted(
        list_of_output_chunks, key=lambda x: int(os.path.basename(x).split("_")[0])
    )
    input_streams = [ffmpeg.input(chunk) for chunk in list_of_output_chunks]
    concatenated = ffmpeg.concat(*input_streams, v=0, a=1).output(f"{output_audio}")

    try:
        concatenated.run(overwrite_output=True)
        return output_audio
    except ffmpeg.Error as e:
        print(e.stderr.decode())


def create_combined_output(input_video, output_audio, output_video):
    try:
        video = ffmpeg.input(f"{input_video}")
        audio = ffmpeg.input(f"{output_audio}")
        (
            ffmpeg.output(
                video["v"],
                audio["a"],
                filename=f"{output_video}",
                vcodec="copy",
            ).run(overwrite_output=True)
        )
        print("Video and audio combined successfully")
        return output_video
    except ffmpeg.Error as e:
        print(e.stderr.decode())
        raise e


def create_combined_output_subprocess(input_video, output_audio, output_video):
    video_duration = get_media_duration(input_video)
    audio_duration = get_media_duration(output_audio)

    speed_factor = calculate_speed_factor(video_duration, audio_duration)
    if speed_factor < 0.5:
        speed_factor = 0.5
    if speed_factor > 100:
        speed_factor = 100
    print(f"Speed factor: {speed_factor}")

    try:
        command = [
            "ffmpeg",
            "-i",
            f"{input_video}",
            "-i",
            f"{output_audio}",
            "-filter:a",
            f"atempo={speed_factor}",
            "-c:v",
            "copy",
            "-map",
            "0:v:0",
            "-map",
            "1:a:0",
            f"{output_video}",
        ]
        subprocess.run(command, check=True)
        print("Video and audio combined successfully")
        return output_video
    except subprocess.CalledProcessError as e:
        print(e.stderr.decode())
        raise e


def get_media_duration(media_file):
    """
    Get the duration of a media file in seconds.
    """
    probe = ffmpeg.probe(media_file)
    duration = float(probe["format"]["duration"])
    return duration


def calculate_speed_factor(video_duration, audio_duration):
    """
    Calculate the speed factor to align audio with video.
    """
    return audio_duration / video_duration