File size: 1,925 Bytes
004d6c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cf4b2e
 
 
 
 
004d6c1
 
 
6cf4b2e
 
 
004d6c1
 
 
 
 
6cf4b2e
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
55
56
57
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.")