Spaces:
Runtime error
Runtime error
AJ-Gazin
commited on
Commit
·
bd5362f
1
Parent(s):
0672660
moved all functionality to api, improved performance
Browse files
app.py
CHANGED
@@ -1,17 +1,25 @@
|
|
1 |
import gradio as gr
|
2 |
-
from openai import OpenAI, APIConnectionError, BadRequestError
|
3 |
from gradio_client import Client
|
|
|
4 |
import os
|
5 |
from dotenv import load_dotenv
|
6 |
-
|
7 |
if os.path.exists('.env'):
|
8 |
load_dotenv()
|
9 |
-
access_token =
|
10 |
-
client
|
11 |
-
|
12 |
-
SYSTEM_PROMPT = """You are an advanced multilingual text transformation AI. Your role is to transform the provided text based on specific tasks, ensuring the core meaning remains intact. Each transformation should be distinct, creative, and suitable for the intended audience. Generate exactly 3 distinct variations of the transformed text, separated by '---'. Pay attention to language nuances, style, and context to enhance clarity and engagement."""
|
13 |
|
14 |
def validate_api_key(api_key):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
try:
|
16 |
openai_client = OpenAI(api_key=api_key)
|
17 |
openai_client.models.list()
|
@@ -20,98 +28,62 @@ def validate_api_key(api_key):
|
|
20 |
return False
|
21 |
|
22 |
def check_api_key(api_key):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
if validate_api_key(api_key):
|
24 |
return "Connection successful"
|
25 |
else:
|
26 |
return "Connection failed: Invalid API key"
|
27 |
|
28 |
-
def
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
try:
|
45 |
-
response = openai_client.chat.completions.create(
|
46 |
-
model="gpt-3.5-turbo",
|
47 |
-
messages=messages,
|
48 |
-
temperature=temperature,
|
49 |
-
max_tokens=800
|
50 |
-
)
|
51 |
-
english_text = response.choices[0].message.content.strip()
|
52 |
-
options = english_text.split('---')
|
53 |
-
|
54 |
-
while len(options) < 3:
|
55 |
-
options.append("")
|
56 |
-
|
57 |
-
return [option.strip() for option in options]
|
58 |
-
except (APIConnectionError, BadRequestError) as e:
|
59 |
-
return [f"API request failed: {str(e)}", "", ""]
|
60 |
-
|
61 |
-
def translate_text(api_key, english_text, translation, temperature):
|
62 |
-
if translation == "English":
|
63 |
-
options = english_text.split('---')
|
64 |
-
return [option.strip() for option in options]
|
65 |
-
|
66 |
-
openai_client = OpenAI(api_key=api_key)
|
67 |
-
messages = [
|
68 |
-
{"role": "system", "content": f"Translate the following text into {translation} while maintaining the original tone and context. Provide 3 unique variations, separated by '---'."},
|
69 |
-
{"role": "user", "content": english_text},
|
70 |
-
]
|
71 |
-
|
72 |
try:
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
76 |
temperature=temperature,
|
77 |
-
|
78 |
)
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
while len(options) < 3:
|
83 |
-
options.append("")
|
84 |
-
|
85 |
-
return [option.strip() for option in options]
|
86 |
-
except (APIConnectionError, BadRequestError) as e:
|
87 |
-
return [f"API request failed: {str(e)}", "", ""]
|
88 |
-
|
89 |
-
def nlp_interface(api_key, description, tone, channel, customizations, translation, temperature):
|
90 |
-
english_options = generate_english_text(api_key, description, tone, channel, customizations, temperature)
|
91 |
-
|
92 |
-
if "API request failed" in english_options[0]:
|
93 |
-
return english_options
|
94 |
-
|
95 |
-
english_text = "---".join(english_options)
|
96 |
-
translated_options = translate_text(api_key, english_text, translation, temperature)
|
97 |
-
|
98 |
-
return translated_options
|
99 |
-
|
100 |
-
def add_customization(customization, current_customizations):
|
101 |
-
result = client.predict(
|
102 |
-
customization=customization,
|
103 |
-
current_customizations=current_customizations,
|
104 |
-
api_name="/add_customization"
|
105 |
-
)
|
106 |
-
return result
|
107 |
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
else:
|
113 |
-
return f"<div style='color: red;'>{status}</div>", gr.update(value="Please enter API Key", interactive=False), ""
|
114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
description = """
|
116 |
<div style='text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 20px;'>Welcome to the Promo Text Modulator Demo!</div>
|
117 |
|
@@ -124,56 +96,45 @@ description = """
|
|
124 |
</div>
|
125 |
"""
|
126 |
|
127 |
-
# JS codelet to force dark mode
|
128 |
-
js_func = """
|
129 |
-
function refresh() {
|
130 |
-
const url = new URL(window.location);
|
131 |
-
|
132 |
-
if (url.searchParams.get('__theme') !== 'dark') {
|
133 |
-
url.searchParams.set('__theme', 'dark');
|
134 |
-
window.location.href = url.href;
|
135 |
-
}
|
136 |
-
}
|
137 |
-
"""
|
138 |
-
|
139 |
with gr.Blocks(js=js_func, css=".connection-status { text-align: center; margin-top: 20px; color: inherit; }") as demo:
|
140 |
gr.Markdown(description)
|
141 |
|
142 |
api_key_input = gr.Textbox(label="Your OpenAI API Key", type="password")
|
143 |
connect_btn = gr.Button("Connect")
|
144 |
connection_status = gr.HTML(visible=True, elem_classes=["connection-status"])
|
145 |
-
hidden_api_key = gr.State("")
|
146 |
|
147 |
text_modulator = gr.Blocks()
|
148 |
|
149 |
with text_modulator:
|
150 |
with gr.Row():
|
151 |
with gr.Column():
|
152 |
-
|
|
|
153 |
tone_input = gr.Dropdown(["Friendly and inviting", "Authoritative and confident", "Informative", "Enthusiastic and energetic", "Inspirational", "Exclusive and luxurious"], label="Tone", allow_custom_value=True)
|
154 |
channel_input = gr.Dropdown(["Facebook", "Instagram", "LinkedIn", "Twitter", "Viber", "Telegram", "Email"], label="Channel", allow_custom_value=True)
|
155 |
|
156 |
customizations_input = gr.Dropdown(
|
157 |
-
["Modernize", "Expand", "Add emojis", "Simplify language", "Improve writing", "Correct spelling"],
|
158 |
label="Text Customizations",
|
159 |
info="Select customization options",
|
160 |
show_label=True,
|
161 |
-
multiselect=True
|
|
|
162 |
)
|
163 |
|
164 |
-
translation_input = gr.Dropdown(["English", "Moldovan", "Belarusian", "Albanian", "Russian", "Arabic", "Ukrainian", "French", "Kazakh", "Bosnian", "Armenian", "Serbian", "Tajik", "Azerbaijani", "Uzbek", "Romanian", "Spanish"], label="Translation", allow_custom_value=
|
165 |
temperature_input = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label="Model Temperature", value=0.7)
|
166 |
|
167 |
submit_btn = gr.Button("Please enter API Key", interactive=False)
|
168 |
|
169 |
with gr.Column():
|
170 |
-
output1 = gr.Textbox(label="
|
171 |
-
output2 = gr.Textbox(label="
|
172 |
-
output3 = gr.Textbox(label="
|
173 |
|
174 |
submit_btn.click(
|
175 |
nlp_interface,
|
176 |
-
inputs=[
|
177 |
outputs=[output1, output2, output3]
|
178 |
)
|
179 |
|
@@ -186,10 +147,17 @@ with gr.Blocks(js=js_func, css=".connection-status { text-align: center; margin-
|
|
186 |
inputs=[description_input, tone_input, channel_input, customizations_input, translation_input]
|
187 |
)
|
188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
connect_btn.click(
|
190 |
fn=connect,
|
191 |
inputs=[api_key_input],
|
192 |
-
outputs=[connection_status, submit_btn
|
193 |
)
|
194 |
|
195 |
demo.launch(share=True)
|
|
|
1 |
import gradio as gr
|
|
|
2 |
from gradio_client import Client
|
3 |
+
from openai import OpenAI, APIConnectionError, BadRequestError
|
4 |
import os
|
5 |
from dotenv import load_dotenv
|
6 |
+
|
7 |
if os.path.exists('.env'):
|
8 |
load_dotenv()
|
9 |
+
access_token = os.getenv('PRIVATE_ACCESS_KEY') # both in hidden env & hf secrets.
|
10 |
+
# Initialize the client for the private space
|
11 |
+
client = Client("neuronslabs/Text_modulator", hf_token = access_token)
|
|
|
12 |
|
13 |
def validate_api_key(api_key):
|
14 |
+
"""
|
15 |
+
Validate the provided OpenAI API key by attempting to list the available models.
|
16 |
+
|
17 |
+
Args:
|
18 |
+
api_key (str): The OpenAI API key to validate.
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
bool: True if the API key is valid, False otherwise.
|
22 |
+
"""
|
23 |
try:
|
24 |
openai_client = OpenAI(api_key=api_key)
|
25 |
openai_client.models.list()
|
|
|
28 |
return False
|
29 |
|
30 |
def check_api_key(api_key):
|
31 |
+
"""
|
32 |
+
Check the validity of the provided OpenAI API key and return the connection status.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
api_key (str): The OpenAI API key to check.
|
36 |
+
|
37 |
+
Returns:
|
38 |
+
str: "Connection successful" if the API key is valid, "Connection failed: Invalid API key" otherwise.
|
39 |
+
"""
|
40 |
if validate_api_key(api_key):
|
41 |
return "Connection successful"
|
42 |
else:
|
43 |
return "Connection failed: Invalid API key"
|
44 |
|
45 |
+
def nlp_interface(api_key, description, tone, channel, customizations, translation, temperature):
|
46 |
+
"""
|
47 |
+
Main function to generate and translate text based on user input via the private space API.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
api_key (str): The OpenAI API key.
|
51 |
+
description (str): The text description to generate variations for.
|
52 |
+
tone (str): The desired tone for the generated text.
|
53 |
+
channel (str): The channel for which the text is being generated.
|
54 |
+
customizations (list): List of text customizations.
|
55 |
+
translation (str): The target language for translation.
|
56 |
+
temperature (float): The temperature value for the model.
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
tuple: Three text variations.
|
60 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
try:
|
62 |
+
result = client.predict(
|
63 |
+
api_key=api_key,
|
64 |
+
description=description,
|
65 |
+
tone=tone,
|
66 |
+
channel=channel,
|
67 |
+
customizations=customizations,
|
68 |
+
translation=translation,
|
69 |
temperature=temperature,
|
70 |
+
api_name="/nlp_interface"
|
71 |
)
|
72 |
+
return result[0], result[1], result[2]
|
73 |
+
except Exception as e:
|
74 |
+
return f"API request failed: {str(e)}", "", ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
+
# JS codelet to force dark mode
|
77 |
+
js_func = """
|
78 |
+
function refresh() {
|
79 |
+
const url = new URL(window.location);
|
|
|
|
|
80 |
|
81 |
+
if (url.searchParams.get('__theme') !== 'dark') {
|
82 |
+
url.searchParams.set('__theme', 'dark');
|
83 |
+
window.location.href = url.href;
|
84 |
+
}
|
85 |
+
}
|
86 |
+
"""
|
87 |
description = """
|
88 |
<div style='text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 20px;'>Welcome to the Promo Text Modulator Demo!</div>
|
89 |
|
|
|
96 |
</div>
|
97 |
"""
|
98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
with gr.Blocks(js=js_func, css=".connection-status { text-align: center; margin-top: 20px; color: inherit; }") as demo:
|
100 |
gr.Markdown(description)
|
101 |
|
102 |
api_key_input = gr.Textbox(label="Your OpenAI API Key", type="password")
|
103 |
connect_btn = gr.Button("Connect")
|
104 |
connection_status = gr.HTML(visible=True, elem_classes=["connection-status"])
|
|
|
105 |
|
106 |
text_modulator = gr.Blocks()
|
107 |
|
108 |
with text_modulator:
|
109 |
with gr.Row():
|
110 |
with gr.Column():
|
111 |
+
|
112 |
+
description_input = gr.Textbox(lines=3, label="Description and Details")
|
113 |
tone_input = gr.Dropdown(["Friendly and inviting", "Authoritative and confident", "Informative", "Enthusiastic and energetic", "Inspirational", "Exclusive and luxurious"], label="Tone", allow_custom_value=True)
|
114 |
channel_input = gr.Dropdown(["Facebook", "Instagram", "LinkedIn", "Twitter", "Viber", "Telegram", "Email"], label="Channel", allow_custom_value=True)
|
115 |
|
116 |
customizations_input = gr.Dropdown(
|
117 |
+
["Modernize", "Expand", "Add emojis", "Simplify language", "Improve writing", "Correct spelling", "Shorten"],
|
118 |
label="Text Customizations",
|
119 |
info="Select customization options",
|
120 |
show_label=True,
|
121 |
+
multiselect=True,
|
122 |
+
allow_custom_value=False
|
123 |
)
|
124 |
|
125 |
+
translation_input = gr.Dropdown(["English", "Moldovan", "Belarusian", "Albanian", "Russian", "Arabic", "Ukrainian", "French", "Kazakh", "Bosnian", "Armenian", "Serbian", "Tajik", "Azerbaijani", "Uzbek", "Romanian", "Spanish"], label="Translation", allow_custom_value=True)
|
126 |
temperature_input = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label="Model Temperature", value=0.7)
|
127 |
|
128 |
submit_btn = gr.Button("Please enter API Key", interactive=False)
|
129 |
|
130 |
with gr.Column():
|
131 |
+
output1 = gr.Textbox(label="Option 1")
|
132 |
+
output2 = gr.Textbox(label="Option 2")
|
133 |
+
output3 = gr.Textbox(label="Option 3")
|
134 |
|
135 |
submit_btn.click(
|
136 |
nlp_interface,
|
137 |
+
inputs=[api_key_input, description_input, tone_input, channel_input, customizations_input, translation_input, temperature_input],
|
138 |
outputs=[output1, output2, output3]
|
139 |
)
|
140 |
|
|
|
147 |
inputs=[description_input, tone_input, channel_input, customizations_input, translation_input]
|
148 |
)
|
149 |
|
150 |
+
def connect(api_key):
|
151 |
+
status = check_api_key(api_key)
|
152 |
+
if "successful" in status:
|
153 |
+
return gr.update(value=f"<div style='color: green; font-size: 20px;'>{status}</div>", visible=True), gr.update(value="Submit", interactive=True)
|
154 |
+
else:
|
155 |
+
return gr.update(value=f"<div style='color: red;'>{status}</div>", visible=True), gr.update(value="Please enter API Key", interactive=False)
|
156 |
+
|
157 |
connect_btn.click(
|
158 |
fn=connect,
|
159 |
inputs=[api_key_input],
|
160 |
+
outputs=[connection_status, submit_btn]
|
161 |
)
|
162 |
|
163 |
demo.launch(share=True)
|