import gradio as gr
from openai import OpenAI, APIConnectionError, BadRequestError
from gradio_client import Client
# Define the client to interact with the original Gradio app for prompt customization
client = Client("neuronslabs/Text_modulator")
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."""
def validate_api_key(api_key):
try:
client = OpenAI(api_key=api_key)
client.models.list()
return True
except Exception:
return False
def check_api_key(api_key):
if validate_api_key(api_key):
return "Connection successful"
else:
return "Connection failed: Invalid API key"
def generate_english_text(api_key, description, tone, channel, customizations, temperature):
openai_client = OpenAI(api_key=api_key)
customizations = [c.strip() for c in customizations] if customizations else []
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Task: Adjust the text to convey a '{tone}' tone. Ensure the message is clear and engaging. Provide 3 unique variations separated by '---'."},
{"role": "user", "content": f"Text: {description}"},
]
if channel:
messages.append({"role": "user", "content": f"Channel: {channel}"})
if customizations:
messages.append({"role": "user", "content": f"Customizations: {', '.join(customizations)}"})
try:
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=temperature,
max_tokens=800
)
english_text = response.choices[0].message.content.strip()
options = english_text.split('---')
while len(options) < 3:
options.append("")
return [option.strip() for option in options]
except (APIConnectionError, BadRequestError) as e:
return [f"API request failed: {str(e)}", "", ""]
def translate_text(api_key, english_text, translation, temperature):
if translation == "English":
options = english_text.split('---')
return [option.strip() for option in options]
openai_client = OpenAI(api_key=api_key)
messages = [
{"role": "system", "content": f"Translate the following text into {translation} while maintaining the original tone and context. Provide 3 unique variations, separated by '---'."},
{"role": "user", "content": english_text},
]
try:
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=temperature,
max_tokens=800
)
translated_text = response.choices[0].message.content.strip()
options = translated_text.split('---')
while len(options) < 3:
options.append("")
return [option.strip() for option in options]
except (APIConnectionError, BadRequestError) as e:
return [f"API request failed: {str(e)}", "", ""]
def nlp_interface(api_key, description, tone, channel, customizations, translation, temperature):
english_options = generate_english_text(api_key, description, tone, channel, customizations, temperature)
if "API request failed" in english_options[0]:
return english_options
english_text = "---".join(english_options)
translated_options = translate_text(api_key, english_text, translation, temperature)
return translated_options
def add_customization(customization, current_customizations):
result = client.predict(
customization=customization,
current_customizations=current_customizations,
api_name="/add_customization"
)
return result
def connect(api_key):
status = check_api_key(api_key)
if "successful" in status:
return f"
{status}
", gr.update(value="Submit", interactive=True), api_key
else:
return f"{status}
", gr.update(value="Please enter API Key", interactive=False), ""
description = """
Welcome to the Promo Text Modulator Demo!
This app uses AI to help you create customized promotional and advertising text in different styles and languages. Simply enter your text, choose the tone, channel, and any other preferences, and get three unique versions of your promotional content.
The app integrates with the OpenAI API and allows you to adjust parameters like tone, channel, customizations, and translation options. The user-friendly interface makes it easy to input your text and see the results quickly.
Start by entering your OpenAI API key and see how your text can be transformed into engaging content that's perfect for any audience.
"""
# JS codelet to force dark mode
js_func = """
function refresh() {
const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') {
url.searchParams.set('__theme', 'dark');
window.location.href = url.href;
}
}
"""
with gr.Blocks(js=js_func, css=".connection-status { text-align: center; margin-top: 20px; color: inherit; }") as demo:
gr.Markdown(description)
api_key_input = gr.Textbox(label="Your OpenAI API Key", type="password")
connect_btn = gr.Button("Connect")
connection_status = gr.HTML(visible=True, elem_classes=["connection-status"])
hidden_api_key = gr.State("")
text_modulator = gr.Blocks()
with text_modulator:
with gr.Row():
with gr.Column():
description_input = gr.Textbox(lines=3, label="Description")
tone_input = gr.Dropdown(["Friendly and inviting", "Authoritative and confident", "Informative", "Enthusiastic and energetic", "Inspirational", "Exclusive and luxurious"], label="Tone", allow_custom_value=True)
channel_input = gr.Dropdown(["Facebook", "Instagram", "LinkedIn", "Twitter", "Viber", "Telegram", "Email"], label="Channel", allow_custom_value=True)
customizations_input = gr.Dropdown(
["Modernize", "Expand", "Add emojis", "Simplify language", "Improve writing", "Correct spelling"],
label="Text Customizations",
info="Select customization options",
show_label=True,
multiselect=True # Allow multiple selections
)
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=False)
temperature_input = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label="Model Temperature", value=0.7)
submit_btn = gr.Button("Please enter API Key", interactive=False)
with gr.Column():
output1 = gr.Textbox(label="Output 1")
output2 = gr.Textbox(label="Output 2")
output3 = gr.Textbox(label="Output 3")
submit_btn.click(
nlp_interface,
inputs=[hidden_api_key, description_input, tone_input, channel_input, customizations_input, translation_input, temperature_input],
outputs=[output1, output2, output3]
)
gr.Examples(
examples=[
["Get ready for incredible deals! Save up to 50% on our wide selection of products during our annual Summer Sale. Visit our website or store today to take advantage of these limited-time offers.", "Enthusiastic and energetic", "Email", ["Add emojis", "Improve writing"], "English"],
["Introducing our latest innovation: the all-new SmartWatch Pro. With advanced features, sleek design, and unmatched performance, it's the perfect companion for your active lifestyle. Order now and be among the first to experience the future of wearable technology.", "Informative", "Facebook", ["Simplify language"], "French"],
["To our valued customers, we want to express our deepest gratitude for your continued support. As a token of our appreciation, we're offering an exclusive 20% discount on your next purchase. Use code THANKYOU20 at checkout. Your satisfaction is our top priority!", "Friendly and inviting", "Instagram", ["Shorten", "Correct spelling"], "Spanish"]
],
inputs=[description_input, tone_input, channel_input, customizations_input, translation_input]
)
connect_btn.click(
fn=connect,
inputs=[api_key_input],
outputs=[connection_status, submit_btn, hidden_api_key]
)
demo.launch(share=True)