File size: 1,786 Bytes
004d6c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8aad94
004d6c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
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 prompt for translation
    prompt = f"Translate the following English text to Japanese:\n\n{text}"
    
    try:
        # Call the OpenAI API to get the translation
        response = openai.Completion.create(
            engine="gpt-3.5-turbo",  # Use gpt-3.5-turbo or other models if available
            prompt=prompt,
            max_tokens=150,  # Adjust token limit for longer outputs
            temperature=0.5
        )

        # Extract the translated text from the response
        japanese_translation = response.choices[0].text.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.")