File size: 1,461 Bytes
fc36b1f
 
 
 
 
129ab6f
 
fc36b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import openai
import os

from openai import OpenAI
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))


st.title('Marketing Content Translation!')


# Text input for translation
marketing_text = st.text_area('Enter the text to be translated', 'Hello, World!')

# Dropdown for selecting target language
target_language = st.selectbox('Select the target language', ['Spanish', 'French', 'Hindi', 'Other'])



if target_language == 'Other':
    other_language = st.text_input('Enter the target language', 'Japanese')
    target_language = other_language


# Button to trigger translation
translate_submit = st.button('Translate')

def stream_translation(text, target_language):
    """ Generator that streams the translation response. """
    prompt = f'Translate the following text to {target_language}: \n{text}'
    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[
            {"role": "user", "content": prompt}
        ],
        temperature=1,
        max_tokens=2000,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
        stream=True  # Enable streaming
    )
    for chunk in response:
        if chunk.choices[0].delta and chunk.choices[0].delta.content:
            yield chunk.choices[0].delta.content

if translate_submit:
    # Using st.write_stream to display the streamed response
    st.write_stream(stream_translation(marketing_text, target_language))