|
import gradio as gr |
|
from transformers import pipeline, AutoTokenizer |
|
import numpy as np |
|
from pydub import AudioSegment |
|
import librosa |
|
|
|
|
|
pipe = pipeline( |
|
"automatic-speech-recognition", |
|
model="Akashpb13/Hausa_xlsr", |
|
tokenizer="Akashpb13/Hausa_xlsr" |
|
) |
|
translator = pipeline("text2text-generation", model="Baghdad99/saad-hausa-text-to-english-text") |
|
tts = pipeline("text-to-speech", model="Baghdad99/english_voice_tts") |
|
|
|
def translate_speech(audio_input): |
|
print(f"Type of audio: {type(audio_data_tuple)}, Value of audio: {audio_data_tuple}") |
|
|
|
if isinstance(audio_input, tuple): |
|
|
|
sample_rate, audio_data = audio_input |
|
else: |
|
|
|
audio_data, sample_rate = librosa.load(audio_input, sr=None) |
|
|
|
|
|
audio_data_normalized = audio_data / np.iinfo(audio_data.dtype).max |
|
|
|
|
|
audio_data_float64 = audio_data_normalized.astype(np.float64) |
|
|
|
|
|
output = pipe(audio_data_float64) |
|
|
|
print(f"Output: {output}") |
|
|
|
|
|
if 'text' in output: |
|
transcription = output["text"] |
|
else: |
|
print("The output does not contain 'text'") |
|
return |
|
|
|
|
|
print(f"Transcription: {transcription}") |
|
|
|
|
|
translated_text = translator(transcription, return_tensors="pt") |
|
print(f"Translated text: {translated_text}") |
|
|
|
|
|
if 'generated_token_ids' in translated_text[0]: |
|
|
|
translated_text_str = translator.tokenizer.decode(translated_text[0]['generated_token_ids']) |
|
else: |
|
print("The translated text does not contain 'generated_token_ids'") |
|
return |
|
|
|
|
|
print(f"Translated text string: {translated_text_str}") |
|
|
|
|
|
synthesised_speech = tts(translated_text_str) |
|
print(f"Synthesised speech: {synthesised_speech}") |
|
|
|
|
|
if 'audio' in synthesised_speech: |
|
synthesised_speech_data = synthesised_speech['audio'] |
|
else: |
|
print("The synthesised speech does not contain 'audio'") |
|
return |
|
|
|
|
|
synthesised_speech_data = synthesised_speech_data.flatten() |
|
|
|
|
|
print(f"Synthesised speech data type: {type(synthesised_speech_data)}, Synthesised speech data shape: {synthesised_speech_data.shape}") |
|
|
|
|
|
synthesised_speech = (synthesised_speech_data * 32767).astype(np.int16) |
|
|
|
return 16000, synthesised_speech |
|
|
|
|
|
iface = gr.Interface( |
|
fn=translate_speech, |
|
inputs=gr.inputs.Audio(type="filepath"), |
|
outputs=gr.outputs.Audio(type="numpy"), |
|
title="Hausa to English Translation", |
|
description="Realtime demo for Hausa to English translation using speech recognition and text-to-speech synthesis." |
|
) |
|
|
|
iface.launch() |
|
|