Spaces:
Runtime error
Runtime error
import gradio as gr | |
from gradio_client import Client | |
from openai import OpenAI, APIConnectionError, BadRequestError | |
import os | |
from dotenv import load_dotenv | |
if os.path.exists('.env'): | |
load_dotenv() | |
access_token = os.getenv('PRIVATE_ACCESS_KEY') # both in hidden env & hf secrets. | |
# Initialize the client for the private space | |
client = Client("neuronslabs/Text_modulator", hf_token = access_token) | |
def validate_api_key(api_key): | |
""" | |
Validate the provided OpenAI API key by attempting to list the available models. | |
Args: | |
api_key (str): The OpenAI API key to validate. | |
Returns: | |
bool: True if the API key is valid, False otherwise. | |
""" | |
try: | |
openai_client = OpenAI(api_key=api_key) | |
openai_client.models.list() | |
return True | |
except Exception: | |
return False | |
def check_api_key(api_key): | |
""" | |
Check the validity of the provided OpenAI API key and return the connection status. | |
Args: | |
api_key (str): The OpenAI API key to check. | |
Returns: | |
str: "Connection successful" if the API key is valid, "Connection failed: Invalid API key" otherwise. | |
""" | |
if validate_api_key(api_key): | |
return "Connection successful" | |
else: | |
return "Connection failed: Invalid API key" | |
def nlp_interface(api_key, description, tone, channel, customizations, translation, temperature): | |
""" | |
Main function to generate and translate text based on user input via the private space API. | |
Args: | |
api_key (str): The OpenAI API key. | |
description (str): The text description to generate variations for. | |
tone (str): The desired tone for the generated text. | |
channel (str): The channel for which the text is being generated. | |
customizations (list): List of text customizations. | |
translation (str): The target language for translation. | |
temperature (float): The temperature value for the model. | |
Returns: | |
tuple: Three text variations. | |
""" | |
try: | |
result = client.predict( | |
api_key=api_key, | |
description=description, | |
tone=tone, | |
channel=channel, | |
customizations=customizations, | |
translation=translation, | |
temperature=temperature, | |
api_name="/nlp_interface" | |
) | |
return result[0], result[1], result[2] | |
except Exception as e: | |
return f"API request failed: {str(e)}", "", "" | |
# 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; | |
} | |
} | |
""" | |
description = """ | |
<div style='text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 20px;'>Welcome to the Promo Text Modulator Demo!</div> | |
<div style='font-size: 16px; line-height: 1.5;'> | |
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. | |
<br><br> | |
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. | |
<br><br> | |
Start by entering your OpenAI API key and see how your text can be transformed into engaging content that's perfect for any audience. | |
<br><br> | |
<a href="https://www.loom.com/share/56ef5778e2754ab19d90b3801da4ecc0" target="_blank">🎮 Demo Video</a> | |
</div> | |
""" | |
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"]) | |
text_modulator = gr.Blocks() | |
with text_modulator: | |
with gr.Row(): | |
with gr.Column(): | |
description_input = gr.Textbox(lines=3, label="Description and Details") | |
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", "Shorten"], | |
label="Text Customizations", | |
info="Select customization options", | |
show_label=True, | |
multiselect=True, | |
allow_custom_value=False | |
) | |
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) | |
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="Option 1") | |
output2 = gr.Textbox(label="Option 2") | |
output3 = gr.Textbox(label="Option 3") | |
submit_btn.click( | |
nlp_interface, | |
inputs=[api_key_input, 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] | |
) | |
def connect(api_key): | |
status = check_api_key(api_key) | |
if "successful" in status: | |
return gr.update(value=f"<div style='color: green; font-size: 20px;'>{status}</div>", visible=True), gr.update(value="Submit", interactive=True) | |
else: | |
return gr.update(value=f"<div style='color: red;'>{status}</div>", visible=True), gr.update(value="Please enter API Key", interactive=False) | |
connect_btn.click( | |
fn=connect, | |
inputs=[api_key_input], | |
outputs=[connection_status, submit_btn] | |
) | |
demo.launch(share=True) | |