File size: 15,301 Bytes
397f6ad c7dae24 37b1bfd 397f6ad 5fc52bb 69beac3 8dc848c 5fc52bb 69beac3 c7dae24 397f6ad c7dae24 f41d654 69beac3 5fc52bb 69beac3 5fc52bb 8dc848c 397f6ad a2d1710 f41d654 397f6ad f41d654 397f6ad c7dae24 f41d654 a2d1710 f41d654 397f6ad c7dae24 f41d654 b0e56f1 397f6ad a2d1710 b0e56f1 f41d654 397f6ad a2d1710 f41d654 a2d1710 f41d654 a2d1710 f41d654 397f6ad c7dae24 f41d654 397f6ad c7dae24 397f6ad f41d654 397f6ad c7dae24 0000f2c c7dae24 0000f2c c7dae24 5d44f1b 69beac3 1b313e6 c7dae24 0000f2c 21ebaa7 c7dae24 0000f2c f41d654 b0e56f1 f41d654 b0e56f1 0000f2c f41d654 0000f2c f41d654 0000f2c c7dae24 0000f2c c568d97 c7dae24 f41d654 8dc848c 69beac3 5fc52bb 5d44f1b 2ea7c21 8dc848c 5d44f1b 2ea7c21 5d44f1b 2ea7c21 8dc848c 5d44f1b 2ea7c21 5d44f1b 2ea7c21 5d44f1b 2ea7c21 8dc848c 5d44f1b c7dae24 5d44f1b c568d97 c7dae24 397f6ad c7dae24 0000f2c |
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
import base64
import requests
import gradio as gr
from PIL import Image
import numpy as np
from datetime import datetime, date
import os
import json
import uuid
from http.cookies import SimpleCookie
# File to store session data
SESSION_FILE = "user_session_data.json"
# OpenAI API Key
api_key = os.getenv("OPENAI_API_KEY")
# Function to check and reset the counter if necessary for a specific user
def check_and_reset_user_counter(user_id):
all_user_data = load_user_session_data(user_id)
user_data = all_user_data[user_id]
today = str(date.today())
if user_data["last_reset_date"] != today:
user_data["last_reset_date"] = today
user_data["test_counter"] = 0
save_user_session_data(all_user_data)
return user_data["test_counter"]
# Function to increment the counter for a specific user
def increment_user_counter(user_id):
all_user_data = load_user_session_data(user_id)
all_user_data[user_id]["test_counter"] += 1
save_user_session_data(all_user_data)
return all_user_data[user_id]["test_counter"]
# Function to get or create user ID from cookie
def get_or_create_user_id(request: gr.Request):
if request is None:
return str(uuid.uuid4())
cookies = SimpleCookie()
cookies.load(request.headers.get('cookie', ''))
user_id = cookies.get('user_id')
if user_id is None:
user_id = str(uuid.uuid4())
cookies['user_id'] = user_id
cookies['user_id']['httponly'] = True
cookies['user_id']['max-age'] = 365 * 24 * 60 * 60 # 1 year
else:
user_id = user_id.value
return user_id, cookies.output(header='', sep=';')
# Function to encode the image
def encode_image(image_array):
# Convert numpy array to an image file and encode it in base64
img = Image.fromarray(np.uint8(image_array))
img_buffer = os.path.join(
"/tmp", f"temp_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
)
img.save(img_buffer, format="JPEG")
with open(img_buffer, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Function to generate product description using OpenAI API
def generate_product_description(image, description_type, custom_instruction=None):
# Encode the uploaded image
base64_image = encode_image(image)
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
# Set the description type or custom instruction
description_prompts = {
"Short Formal π": "Based on the image, craft a concise and compelling product description that highlights key features and benefits in a formal tone.",
"Bullet Points π": "From the image, provide a detailed list of bullet points describing the product's features, benefits, and unique selling points.",
"Amazon Optimized π": "Create an Amazon-style product description based on the image, including key features, benefits, relevant keywords for SEO, and a persuasive call to action.",
"Fashion π": "Generate a stylish and trendy product description for a fashion item shown in the image, emphasizing its design, materials, and how it fits into current fashion trends.",
"Sport π": "Using the image, develop an energetic and engaging product description for a sports-related item, highlighting its performance features and benefits for athletic activities.",
"Technical Specifications βοΈ": "Extract and present the product's technical specifications from the image in a clear and concise manner, suitable for tech-savvy customers.",
"SEO Optimized π": "Write an SEO-friendly product description based on the image, incorporating relevant keywords and phrases to enhance search engine visibility.",
"Social Media Style π±": "Create a catchy and engaging product description suitable for social media platforms, using the image as inspiration.",
"Luxury π": "Craft an elegant and sophisticated product description for the luxury item shown in the image, emphasizing exclusivity, premium quality, and craftsmanship.",
"Kid-Friendly π§Έ": "Generate a fun and appealing product description for a children's product based on the image, using language that resonates with both kids and parents.",
"Health and Beauty π": "Develop a compelling product description for a health or beauty item shown in the image, highlighting its benefits, ingredients, and usage tips.",
"Electronic Gadgets π±": "Write a tech-focused product description for the electronic gadget in the image, focusing on its innovative features, specifications, and user advantages.",
"Eco-Friendly π±": "Create an eco-conscious product description for the environmentally friendly product shown in the image, emphasizing sustainability and green benefits.",
"Personalized Gifts π": "Generate a heartfelt product description for the personalized gift in the image, highlighting customization options and sentimental value.",
"Seasonal Promotion π": "Craft a seasonal promotional product description based on the image, incorporating festive themes and limited-time offers to encourage immediate purchase.",
"Clearance Sale π·οΈ": "Write an urgent and enticing product description for the item in the image, emphasizing discounted prices and limited stock availability.",
"Cross-Selling π": "Develop a product description that not only highlights the item in the image but also suggests complementary products, encouraging additional purchases.",
"Up-Selling β¬οΈ": "Create a persuasive product description that highlights premium features of the item in the image, encouraging customers to consider higher-end versions.",
"Multi-Language Support π": "Provide a product description based on the image in multiple languages to cater to a diverse customer base.",
"User Testimonials β": "Incorporate fictional user testimonials or reviews into the product description based on the image, adding credibility and social proof.",
"Instructional π": "Write a product description that includes usage instructions or assembly steps for the item shown in the image.",
"Bundle Offer π¦": "Craft a product description that promotes the item in the image as part of a bundle deal, highlighting the added value.",
"Gift Guide Entry π": "Generate a product description suitable for inclusion in a gift guide, emphasizing why the item in the image makes a great gift.",
"Limited Edition π": "Create an exclusive product description for the limited-edition item shown in the image, highlighting its uniqueness and scarcity.",
"Subscription Model π": "Write a product description that promotes the item in the image as part of a subscription service, detailing recurring benefits.",
"B2B Focused π’": "Develop a professional product description suitable for business-to-business contexts, emphasizing features relevant to corporate clients.",
}
if description_type == "Other" and custom_instruction:
instruction = custom_instruction
else:
instruction = description_prompts.get(
description_type, "Create a product description based on the image."
)
# Payload with base64 encoded image as a Data URL
payload = {
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": instruction},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
}
],
"max_tokens": 300,
}
response = requests.post(
"https://api.openai.com/v1/chat/completions", headers=headers, json=payload
)
response_data = response.json()
# Handle errors
if response.status_code != 200:
raise ValueError(
f"OpenAI API Error: {response_data.get('error', {}).get('message', 'Unknown Error')}"
)
# Extract and return only the generated message content
return response_data["choices"][0]["message"]["content"]
# Custom CSS to match WordLift style
css = """
body {
font-family: 'Inter', sans-serif;
}
#output {
height: 500px;
overflow: auto;
border: 1px solid #ccc;
}
.redirect-message {
background-color: #f0f0f0;
border: 1px solid #ccc;
padding: 15px;
margin-top: 20px;
border-radius: 5px;
}
"""
# Initialize user ID
user_id = str(uuid.uuid4())
with gr.Blocks(css=css) as demo:
gr.Markdown("<h1>WordLift Product Description Generation - [FREE]</h1>")
with gr.Tab(label="WordLift Product Description Generation"):
with gr.Row():
with gr.Column():
input_img = gr.Image(label="Input Picture", elem_classes="gr-box")
description_type = gr.Dropdown(
label="Select Description Type",
choices=[
"Short Formal π",
"Bullet Points π",
"Amazon Optimized π",
"Fashion π",
"Sport π",
"Technical Specifications βοΈ",
"SEO Optimized π",
"Social Media Style π±",
"Luxury π",
"Kid-Friendly π§Έ",
"Health and Beauty π",
"Electronic Gadgets π±",
"Eco-Friendly π±",
"Personalized Gifts π",
"Seasonal Promotion π",
"Clearance Sale π·οΈ",
"Cross-Selling π",
"Up-Selling β¬οΈ",
"Multi-Language Support π",
"User Testimonials β",
"Instructional π",
"Bundle Offer π¦",
"Gift Guide Entry π",
"Limited Edition π",
"Subscription Model π",
"B2B Focused π’",
"Other",
],
value="Short Formal π",
elem_classes="gr-box"
)
custom_instruction = gr.Textbox(
label="Custom Instruction (Only for 'Other')", visible=False, elem_classes="gr-box"
)
submit_btn = gr.Button(value="Submit", elem_classes="gr-box")
with gr.Column():
output_text = gr.Markdown(label="Output Text", show_copy_button=True, elem_classes="output-text")
redirect_message = gr.Markdown(visible=False, elem_classes="redirect-message")
test_counter_display = gr.Markdown(visible=True, label="Test Counter")
# Toggle visibility of custom instruction based on selected type
def toggle_custom_instruction(type_selection):
return gr.update(visible=(type_selection == "Other"))
description_type.change(
toggle_custom_instruction,
inputs=[description_type],
outputs=[custom_instruction],
)
# Modified function to handle test limit with improved messaging and cookie-based user sessions
def handle_submit(image, description_type, custom_instruction, request: gr.Request):
user_id, cookie = get_or_create_user_id(request)
check_and_reset_user_counter(user_id) # Check and reset counter if it's a new day
test_counter = increment_user_counter(user_id)
if test_counter <= 4:
result = generate_product_description(image, description_type, custom_instruction)
remaining_tests = 4 - test_counter
if remaining_tests > 0:
return (
result,
gr.update(visible=False),
gr.update(interactive=True),
f"You have {remaining_tests} free test(s) remaining today.",
cookie,
)
else:
redirect_text = """
Thank you for trying our product description generation tool!
You've used all 4 of your free tests for today. We hope you found them helpful and insightful.
To unlock unlimited access and discover how our AI-powered solution can revolutionize your content creation process:
[Book a Personalized Demo with Our Experts](https://wordlift.io/book-a-demo/)
During the demo, you'll get:
β’ A tailored walkthrough of our full suite of features
β’ Insights on how to optimize your specific content workflow
β’ Answers to any questions you may have about our solution
We're excited to show you how we can help scale your content creation!
(Your free tests will reset tomorrow, allowing you to try 4 more if you need additional time to decide.)
"""
return (
result,
gr.update(visible=True, value=redirect_text),
gr.update(interactive=False),
"You've used all your free tests for today. We invite you to book a demo for full access!",
cookie,
)
else:
redirect_text = """
Thank you for your interest in our product description generation tool!
You've already used your 4 free tests for today. We hope they've given you a glimpse of how our AI can enhance your content creation.
Ready to explore the full potential of our solution?
[Book a Personalized Demo with Our Experts](https://wordlift.io/book-a-demo/)
In this demo, you'll discover:
β’ How our AI can be customized for your specific needs
β’ Advanced features for scaling your content production
β’ ROI projections based on your current content workflow
Let's discuss how we can help you achieve your content goals!
(Remember, your free tests will reset tomorrow if you need more time to evaluate.)
"""
return (
"",
gr.update(visible=True, value=redirect_text),
gr.update(interactive=False),
"All free tests used. We invite you to book a demo for full access!",
cookie,
)
submit_btn.click(
handle_submit,
inputs=[input_img, description_type, custom_instruction],
outputs=[output_text, redirect_message, submit_btn, test_counter_display],
)
# Launch Gradio app
demo.queue(api_open=False)
demo.launch(debug=True) |