cyberandy commited on
Commit
f41d654
·
verified ·
1 Parent(s): 397f6ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -20
app.py CHANGED
@@ -9,26 +9,43 @@ import os
9
  # OpenAI API Key
10
  api_key = os.getenv("OPENAI_API_KEY")
11
 
 
12
  # Function to encode the image
13
  def encode_image(image_array):
14
  # Convert numpy array to an image file and encode it in base64
15
  img = Image.fromarray(np.uint8(image_array))
16
- img_buffer = os.path.join("/tmp", f"temp_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg")
 
 
17
  img.save(img_buffer, format="JPEG")
18
-
19
  with open(img_buffer, "rb") as image_file:
20
  return base64.b64encode(image_file.read()).decode("utf-8")
21
 
 
22
  # Function to generate product description using OpenAI API
23
- def generate_product_description(image, text_input=None):
24
  # Encode the uploaded image
25
  base64_image = encode_image(image)
26
 
27
- headers = {
28
- "Content-Type": "application/json",
29
- "Authorization": f"Bearer {api_key}"
 
 
 
 
 
 
30
  }
31
 
 
 
 
 
 
 
 
32
  # Payload with base64 encoded image as a Data URL
33
  payload = {
34
  "model": "gpt-4o-mini",
@@ -36,28 +53,31 @@ def generate_product_description(image, text_input=None):
36
  {
37
  "role": "user",
38
  "content": [
39
- {"type": "text", "text": text_input or "What's in this image?"},
40
  {
41
  "type": "image_url",
42
- "image_url": {
43
- "url": f"data:image/jpeg;base64,{base64_image}"
44
- }
45
- }
46
- ]
47
  }
48
  ],
49
- "max_tokens": 300
50
  }
51
 
52
- response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
 
 
53
  response_data = response.json()
54
 
55
  # Handle errors
56
  if response.status_code != 200:
57
- raise ValueError(f"OpenAI API Error: {response_data.get('error', {}).get('message', 'Unknown Error')}")
 
 
 
 
 
58
 
59
- # Extract and return the generated message
60
- return response_data["choices"][0]["message"]
61
 
62
  css = """
63
  #output {
@@ -68,18 +88,44 @@ css = """
68
  """
69
 
70
  with gr.Blocks(css=css) as demo:
71
- gr.Markdown("WordLift Product Description Generation - [GPT-4o-mini Demo]")
72
  with gr.Tab(label="WordLift Product Description Generation"):
73
  with gr.Row():
74
  with gr.Column():
75
  input_img = gr.Image(label="Input Picture")
76
- text_input = gr.Textbox(label="Additional Instructions (Optional)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  submit_btn = gr.Button(value="Submit")
78
  with gr.Column():
79
  output_text = gr.Textbox(label="Output Text")
80
 
 
 
 
 
 
 
 
 
 
 
81
  submit_btn.click(
82
- generate_product_description, [input_img, text_input], [output_text]
 
 
83
  )
84
 
85
  # Launch Gradio app
 
9
  # OpenAI API Key
10
  api_key = os.getenv("OPENAI_API_KEY")
11
 
12
+
13
  # Function to encode the image
14
  def encode_image(image_array):
15
  # Convert numpy array to an image file and encode it in base64
16
  img = Image.fromarray(np.uint8(image_array))
17
+ img_buffer = os.path.join(
18
+ "/tmp", f"temp_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
19
+ )
20
  img.save(img_buffer, format="JPEG")
21
+
22
  with open(img_buffer, "rb") as image_file:
23
  return base64.b64encode(image_file.read()).decode("utf-8")
24
 
25
+
26
  # Function to generate product description using OpenAI API
27
+ def generate_product_description(image, description_type, custom_instruction=None):
28
  # Encode the uploaded image
29
  base64_image = encode_image(image)
30
 
31
+ headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
32
+
33
+ # Set the description type or custom instruction
34
+ description_prompts = {
35
+ "Short Formal": "Create a compelling and succinct product description from the image.",
36
+ "Bullet Points": "Provide a detailed product description in bullet points based on the image.",
37
+ "Amazon Optimized": "Write an Amazon-style product description that includes key features, benefits, and a call to action.",
38
+ "Fashion": "Generate a stylish and trendy product description suitable for a fashion item based on the image.",
39
+ "Sport": "Create an energetic and engaging product description for a sports-related item based on the image.",
40
  }
41
 
42
+ if description_type == "Other" and custom_instruction:
43
+ instruction = custom_instruction
44
+ else:
45
+ instruction = description_prompts.get(
46
+ description_type, "Create a product description based on the image."
47
+ )
48
+
49
  # Payload with base64 encoded image as a Data URL
50
  payload = {
51
  "model": "gpt-4o-mini",
 
53
  {
54
  "role": "user",
55
  "content": [
56
+ {"type": "text", "text": instruction},
57
  {
58
  "type": "image_url",
59
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
60
+ },
61
+ ],
 
 
62
  }
63
  ],
64
+ "max_tokens": 300,
65
  }
66
 
67
+ response = requests.post(
68
+ "https://api.openai.com/v1/chat/completions", headers=headers, json=payload
69
+ )
70
  response_data = response.json()
71
 
72
  # Handle errors
73
  if response.status_code != 200:
74
+ raise ValueError(
75
+ f"OpenAI API Error: {response_data.get('error', {}).get('message', 'Unknown Error')}"
76
+ )
77
+
78
+ # Extract and return only the generated message content
79
+ return response_data["choices"][0]["message"]["content"]
80
 
 
 
81
 
82
  css = """
83
  #output {
 
88
  """
89
 
90
  with gr.Blocks(css=css) as demo:
91
+ gr.Markdown("WordLift Product Description Generation - [FREE]")
92
  with gr.Tab(label="WordLift Product Description Generation"):
93
  with gr.Row():
94
  with gr.Column():
95
  input_img = gr.Image(label="Input Picture")
96
+ description_type = gr.Dropdown(
97
+ label="Select Description Type",
98
+ choices=[
99
+ "Short Formal",
100
+ "Bullet Points",
101
+ "Amazon Optimized",
102
+ "Fashion",
103
+ "Sport",
104
+ "Other",
105
+ ],
106
+ value="Short Formal",
107
+ )
108
+ custom_instruction = gr.Textbox(
109
+ label="Custom Instruction (Only for 'Other')", visible=False
110
+ )
111
  submit_btn = gr.Button(value="Submit")
112
  with gr.Column():
113
  output_text = gr.Textbox(label="Output Text")
114
 
115
+ # Toggle visibility of custom instruction based on selected type
116
+ def toggle_custom_instruction(type_selection):
117
+ return gr.update(visible=(type_selection == "Other"))
118
+
119
+ description_type.change(
120
+ toggle_custom_instruction,
121
+ inputs=[description_type],
122
+ outputs=[custom_instruction],
123
+ )
124
+
125
  submit_btn.click(
126
+ generate_product_description,
127
+ [input_img, description_type, custom_instruction],
128
+ [output_text],
129
  )
130
 
131
  # Launch Gradio app