File size: 1,615 Bytes
a4c60ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from transformers import pipeline
import os
from gtts import gTTS

# Initialize the Hugging Face model pipeline
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")  # Example for English to French translation

# Function to translate text
def translate_text(text, src_lang, target_lang):
    # Translate using the Hugging Face pipeline
    translation = translator(text, src_lang=src_lang, tgt_lang=target_lang)
    return translation[0]['translation_text']

# Function to convert text to speech
def text_to_speech(text, lang='en'):
    tts = gTTS(text=text, lang=lang, slow=False)
    tts.save("output.mp3")
    return "output.mp3"

# Streamlit UI
st.title("Multilingual Text Translator and Text-to-Speech")
st.write("Enter the text below to translate and convert to speech")

# Text input for the user
input_text = st.text_area("Enter text to translate:")

# Language selection
src_lang = st.selectbox("Select source language", ["en", "fr", "es", "de", "it"])
target_lang = st.selectbox("Select target language", ["fr", "en", "es", "de", "it"])

if st.button("Translate and Convert to Speech"):
    if input_text:
        # Translate the text
        translated_text = translate_text(input_text, src_lang, target_lang)
        st.write(f"Translated Text: {translated_text}")

        # Convert the translated text to speech
        audio_file = text_to_speech(translated_text, lang=target_lang)
        st.audio(audio_file)

        # Remove the generated audio file after use
        os.remove(audio_file)
    else:
        st.error("Please enter text to translate.")