import gradio as gr from openai import OpenAI import os from PIL import Image import numpy as np from datetime import datetime # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def array_to_image_path(image_array): if image_array is None: raise ValueError("No image provided. Please upload an image before submitting.") img = Image.fromarray(np.uint8(image_array)) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"image_{timestamp}.png" img.save(filename) full_path = os.path.abspath(filename) return full_path # Function to generate product description using OpenAI API def generate_product_description(image, text_input=None): # Convert the image to a path (simulated handling) image_path = array_to_image_path(image) # Use a generated link from the Gradio app # If share=True is set, the image will be available via a public URL # Make sure the provided URL is accessible and correct in context image_url = image_path # Replace this with actual URL when using Gradio's share functionality # API request completion = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ {"type": "text", "text": text_input or "What's in this image?"}, { "type": "image_url", "image_url": {"url": image_url}, }, ], } ], ) # Extract and return the generated message return completion.choices[0].message css = """ #output { height: 500px; overflow: auto; border: 1px solid #ccc; } """ with gr.Blocks(css=css) as demo: gr.Markdown("WordLift Product Description Generation - [GPT-4o-mini Demo]") with gr.Tab(label="WordLift Product Description Generation"): with gr.Row(): with gr.Column(): input_img = gr.Image(label="Input Picture") text_input = gr.Textbox(label="Additional Instructions (Optional)") submit_btn = gr.Button(value="Submit") with gr.Column(): output_text = gr.Textbox(label="Output Text") submit_btn.click( generate_product_description, [input_img, text_input], [output_text] ) # Set share=True to create a public URL demo.queue(api_open=False) demo.launch(debug=True, share=True)