Spaces:
Sleeping
Sleeping
import openai | |
import streamlit as st | |
def translate_to_japanese(api_key, text): | |
""" | |
Translates English text to Japanese using OpenAI's API. | |
""" | |
# Validate input | |
if not api_key: | |
return "Error: API key is missing." | |
if not text: | |
return "Error: Input text is empty." | |
# Set the OpenAI API key | |
openai.api_key = api_key | |
# Define the messages for the chat model | |
messages = [ | |
{"role": "system", "content": "You are a helpful translator."}, | |
{"role": "user", "content": f"Translate the following English text to Japanese:\n\n{text}"} | |
] | |
try: | |
# Call the OpenAI API to get the translation | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", # Use the correct endpoint for chat models | |
messages=messages, | |
max_tokens=150, # Adjust token limit for longer outputs | |
temperature=0.5 | |
) | |
# Extract the translated text from the response | |
japanese_translation = response.choices[0].message['content'].strip() | |
return japanese_translation | |
except openai.error.OpenAIError as e: | |
return f"OpenAI API error: {str(e)}" | |
except Exception as e: | |
return f"An unexpected error occurred: {str(e)}" | |
# Streamlit UI | |
st.title("English to Japanese Translator") | |
st.markdown("Translate English text into Japanese using OpenAI's API.") | |
# Input fields for the API key and text | |
api_key = st.text_input("Enter your OpenAI API key", type="password") | |
english_text = st.text_area("Enter the English text to translate") | |
# Button to trigger the translation | |
if st.button("Translate"): | |
if api_key and english_text: | |
japanese_text = translate_to_japanese(api_key, english_text) | |
st.markdown("### Translation Result:") | |
st.write(japanese_text) | |
else: | |
st.error("Please provide both an API key and text to translate.") | |