-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
164 lines (140 loc) · 10.1 KB
/
app.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import openai
import streamlit as st
import json
class APIPricing:
def __init__(self, model_name):
self.model_name = model_name
with open("api_pricing.json", "r") as f:
data = json.load(f)
self.prompt_price = float(data[model_name]["prompt_price"])
self.completion_price = float(data[model_name]["completion_price"])
def calc_cost(self, text):
self.text = text
user_text, assistant_text = self.split_text()
user_token_count = self.get_token_count(user_text)
assistant_token_count = self.get_token_count(assistant_text)
user_cost = user_token_count * self.prompt_price / 1000
assistant_cost = assistant_token_count * self.completion_price / 1000
total_cost = user_cost + assistant_cost
return total_cost
def split_text(self):
lines = self.text.split("\n")
user_text = [""]
assistant_text = ["## ASSISTANT", "You will be provided with a text in English, and your task is to translate it into French."]
is_user = True
for line in lines:
if line == "## USER":
is_user = True
continue
elif line == "## ASSISTANT":
is_user = False
continue
elif line == "":
continue
if is_user:
user_text.append(line)
else:
assistant_text.append(line)
return " ".join(user_text), " ".join(assistant_text)
def get_token_count(self, text):
encoding = tiktoken.encoding_for_model(self.model_name)
tokens = encoding.encode(text)
return len(tokens)
def main():
# Commented Ferrari-themed sidebar
"""
st.sidebar.markdown(
'''
<style>
[data-testid="stSidebar"] {{
background-image: url('https://upload.wikimedia.org/wikipedia/commons/4/44/Ferrari-Logo.svg');
background-repeat: no-repeat;
padding-top: 80px;
background-position: center;
background-size: 60%;
}}
</style>
''', unsafe_allow_html=True)
st.sidebar.title("Enzo")
"""
# Title with Formula 1 race car icon
st.title("🏎️ Enzo")
# Commented markdown instructions
st.markdown("""
### Instructions:
- **Language Selection**: Choose the language you want to translate your text into.
- **Tone Selection**: Set the tone for translation such as 'Documentation', 'Product Page'.
""")
# Model selection
with open("api_pricing.json", "r") as f:
data = json.load(f)
model_names = data.keys()
selected_model_name = st.selectbox("Select a GPT model", model_names)
# Language selection with Czech and Dutch added
language_prompts = {
"German": "Please translate the following text from English to German, ensuring accuracy and cultural relevance. Pay special attention to business terms and maintain consistency in key concepts (like 'Membership'). Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"French": "Translate this English passage into French, considering regional linguistic variations where applicable. Pay special attention to business terms and key phrases. Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Spanish Mexico": "Convert the below English text into Mexican Spanish, paying close attention to local expressions and idiomatic usage, especially for business terms (like 'Membership'). Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Spanish Neutral": "Translate the following English text into neutral Spanish that is universally understood, while being mindful of idiomatic expressions and key business terms. Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Spanish Spain": "Please adapt the English content into Castilian Spanish, incorporating cultural and regional nuances specific to Spain. Pay attention to key business terms like 'Membership.' Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Portuguese": "Translate the following English text into Portuguese (Portugal or Brazil), ensuring regional differences are respected. Pay special attention to key business terms like 'Membership' to ensure proper meaning is maintained. Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Italian": "Please render the following English passage into Italian, taking care to reflect the linguistic richness and regional variations of Italy. Pay special attention to business terms like 'Membership.' Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Japanese": "Convert the English text below into Japanese, being mindful of the cultural context and nuances. Ensure that key business terms like 'Membership' are translated appropriately. Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"English Australia": "Translate the following English text into Australian English, incorporating local slang and expressions where appropriate. Ensure business terms like 'Membership' are retained or translated meaningfully. Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"English US": "Adapt the following English content into American English, considering regional variations and idiomatic usage. Focus on preserving key business terminology like 'Membership.' Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Czech": "Please translate the following text from English to Czech, ensuring cultural relevance and linguistic accuracy, particularly for business terms like 'Membership.' Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text.",
"Dutch": "Please translate the following English text into Dutch, ensuring that the cultural context and linguistic accuracy are preserved, especially for business terms like 'Membership.' Without any interpretation, recommendation, or suggestion. Focus solely on translating the content while maintaining cultural and linguistic accuracy with the entire text."
}
selected_language_to = st.selectbox("Select a Language", language_prompts.keys())
# Tone selection for translations
tone_options = ["Documentation/Instructions", "Product Page"]
selected_tone = st.selectbox("Select Translation Tone", tone_options)
# Modify the prompt based on the selected tone
tone_prompts = {
"Documentation/Instructions": "Translate the text with a formal and instructional tone.",
"Product Page": "Translate the text with a persuasive and customer-centric tone."
}
selected_tone_prompt = tone_prompts[selected_tone]
# Translation rules
st.markdown("#### Translation Rules")
st.markdown("Define specific rules to override translation logic, such as terms to avoid or prefer.")
translation_rules = st.text_area("Translation Rules (Beta)", help="Specify rules to override the translation output.")
# Prepare initial messages
if "messages" not in st.session_state:
st.session_state["messages"] = []
# Construct the final prompt including tone and rules
final_prompt = f"{language_prompts[selected_language_to]} {selected_tone_prompt}"
if translation_rules:
final_prompt += f"\n\nPlease follow these instructions when translating: {translation_rules}."
if st.session_state["messages"]:
st.session_state["messages"][0]["content"] = final_prompt
else:
st.session_state["messages"].append({"role": "assistant", "content": final_prompt})
# Handle user input and generate translation
if prompt := st.chat_input("Enter text to translate or provide instructions"):
openai_api_key = st.secrets["OPENAI_TOKEN"]
if not openai_api_key:
st.info("Please add your OpenAI API key to continue.")
st.stop()
try:
openai.api_key = openai_api_key
st.session_state.messages.append({"role": "user", "content": prompt})
st.chat_message("user").write(prompt)
# Make the OpenAI API call with hyperparameters for optimal translation
response = openai.chat.completions.create(
model=selected_model_name,
messages=st.session_state.messages,
max_tokens=2000, # Set high token limit for larger translations
temperature=0.7, # Adjust temperature for creativity balance
top_p=1, # Use top-p sampling
frequency_penalty=0.0, # Reduce repeating words
presence_penalty=0.0 # Encourage new topics
)
# Access the response content
msg = response.choices[0].message.content
st.session_state.messages.append({"role": "assistant", "content": msg})
st.chat_message("assistant").write(msg)
except Exception as e:
st.error(f"An error occurred: {e}")
if __name__ == "__main__":
main()