File size: 9,518 Bytes
a86434c
 
 
9d582af
f1ea9dc
0672660
 
 
e11daeb
9d582af
a86434c
 
 
 
 
9d582af
 
a86434c
 
 
 
 
 
 
 
 
 
 
 
7666783
a86434c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7666783
a86434c
7666783
 
 
 
a86434c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7666783
 
 
a86434c
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import gradio as gr
from openai import OpenAI, APIConnectionError, BadRequestError
from gradio_client import Client
import os
from dotenv import load_dotenv
# Load environment variables from .env file if it exists -- otherwise use hf secret
if os.path.exists('.env'):
    load_dotenv()
access_token =  os.getenv('PRIVATE_ACCESS_KEY') #both in hidden env & hf secrets.
client = Client("neuronslabs/Text_modulator", hf_token=access_token)

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:
        openai_client = OpenAI(api_key=api_key)
        openai_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"<div style='color: green; font-size: 20px;'>{status}</div>", gr.update(value="Submit", interactive=True), api_key
    else:
        return f"<div style='color: red;'>{status}</div>", gr.update(value="Please enter API Key", interactive=False), ""

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.
</div>
"""

# 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)