ha-en / app.py
Baghdad99's picture
Update app.py
d822bd4
raw
history blame
2.71 kB
import gradio as gr
from transformers import pipeline, VitsModel, AutoTokenizer
import torch
import numpy as np
# Load the pipeline for speech recognition and translation
pipe = pipeline(
"automatic-speech-recognition",
model="Baghdad99/saad-speech-recognition-hausa-audio-to-text",
tokenizer="Baghdad99/saad-speech-recognition-hausa-audio-to-text"
)
translator = pipeline("text2text-generation", model="Baghdad99/saad-hausa-text-to-english-text")
# Load the VITS model for text-to-speech synthesis
tts_model = VitsModel.from_pretrained("Baghdad99/english_voice_tts")
tts_tokenizer = AutoTokenizer.from_pretrained("Baghdad99/english_voice_tts")
# Define the function to translate speech
def translate_speech(audio):
# Separate the sample rate and the audio data
sample_rate, audio_data = audio
# Use the speech recognition pipeline to transcribe the audio
output = pipe(audio_data)
print(f"Output: {output}") # Print the output to see what it contains
# Check if the output contains 'text'
if 'text' in output:
transcription = output["text"]
else:
print("The output does not contain 'text'")
return
# Use the translation pipeline to translate the transcription
translated_text = translator(transcription, return_tensors="pt")
print(f"Translated text: {translated_text}") # Print the translated text to see what it contains
# Check if the translated text contains 'generated_token_ids'
if 'generated_token_ids' in translated_text[0]:
# Decode the tokens into text
translated_text_str = translator.tokenizer.decode(translated_text[0]['generated_token_ids'])
else:
print("The translated text does not contain 'generated_token_ids'")
return
# Use the VITS model to synthesize the translated text
tts_inputs = tts_tokenizer(translated_text_str, return_tensors="pt")
with torch.no_grad():
synthesised_speech = tts_model(**tts_inputs).waveform
print(f"Synthesised speech: {synthesised_speech}") # Print the synthesised speech to see what it contains
# Define the max_range variable
max_range = 1.0 # You can adjust this value based on your requirements
synthesised_speech = (synthesised_speech.numpy() * max_range).astype(np.float32)
return 16000, synthesised_speech
# Define the Gradio interface
iface = gr.Interface(
fn=translate_speech,
inputs=gr.inputs.Audio(source="microphone", type="numpy"),
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()