|
import openai |
|
import os |
|
import streamlit as st |
|
from PIL import Image |
|
|
|
def translate_to_japanese(api_key, text): |
|
""" |
|
Translates English text to Japanese using OpenAI's API and provides pronunciation. |
|
""" |
|
|
|
if not api_key: |
|
return "Error: API key is missing." |
|
if not text: |
|
return "Error: Input text is empty." |
|
|
|
|
|
openai.api_key = api_key |
|
|
|
|
|
messages_translation = [ |
|
{"role": "system", "content": "You are a helpful translator."}, |
|
{"role": "user", "content": f"Translate the following English text to Japanese:\n\n{text}"} |
|
] |
|
|
|
try: |
|
|
|
response_translation = openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=messages_translation, |
|
max_tokens=150, |
|
temperature=0.5 |
|
) |
|
|
|
|
|
japanese_translation = response_translation.choices[0].message['content'].strip() |
|
|
|
|
|
messages_pronunciation = [ |
|
{"role": "system", "content": "You are a helpful assistant who provides the Romaji (Japanese pronunciation in Latin script) of Japanese text."}, |
|
{"role": "user", "content": f"Provide the Romaji pronunciation for the following Japanese text:\n\n{japanese_translation}"} |
|
] |
|
|
|
|
|
response_pronunciation = openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=messages_pronunciation, |
|
max_tokens=150, |
|
temperature=0.5 |
|
) |
|
|
|
|
|
pronunciation = response_pronunciation.choices[0].message['content'].strip() |
|
return japanese_translation, pronunciation |
|
|
|
except openai.error.OpenAIError as e: |
|
return f"OpenAI API error: {str(e)}", None |
|
except Exception as e: |
|
return f"An unexpected error occurred: {str(e)}", None |
|
|
|
|
|
st.title("English to Japanese Translator with Pronunciation") |
|
st.markdown("Translate English text into Japanese and get its pronunciation (Romaji) using OpenAI's API.") |
|
|
|
|
|
translateimg = Image.open("Untitled.png") |
|
st.image(translateimg, use_container_width=True) |
|
|
|
|
|
api_key = os.getenv("OPENAI_API_KEY") |
|
|
|
|
|
english_text = st.text_area("Enter the English text to translate") |
|
|
|
|
|
if st.button("Translate"): |
|
if api_key and english_text: |
|
japanese_text, pronunciation = translate_to_japanese(api_key, english_text) |
|
if pronunciation: |
|
st.markdown("### Translation Result:") |
|
st.write(f"**Japanese Output:** {japanese_text}") |
|
st.write(f"**Pronunciation:** {pronunciation}") |
|
else: |
|
st.error(japanese_text) |
|
else: |
|
if not api_key: |
|
st.error("API key is missing. Please add it as a secret in Hugging Face Settings.") |
|
else: |
|
st.error("Please provide text to translate.") |
|
|