nniehaus commited on
Commit
820a120
·
verified ·
1 Parent(s): a786921

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -140
app.py CHANGED
@@ -66,6 +66,14 @@ st.markdown("""
66
  border-radius: 5px;
67
  margin-bottom: 20px;
68
  }
 
 
 
 
 
 
 
 
69
  </style>
70
  """, unsafe_allow_html=True)
71
 
@@ -85,92 +93,58 @@ if "prompt_history" not in st.session_state:
85
  if "image_history" not in st.session_state:
86
  st.session_state["image_history"] = []
87
 
88
- # IMPORTANT: In a real application, this would be securely stored in environment variables or secrets management
89
- # For demonstration purposes only, we're using a placeholder value
90
- OPENAI_API_KEY = st.secrets.get("OPENAI_API_KEY", "YOUR_API_KEY_STORED_IN_SECRETS")
91
 
92
  # Functions
93
- def generate_image_from_prompt(prompt, api_key=OPENAI_API_KEY, model="gpt-4o"):
 
 
 
 
94
  headers = {
95
  "Content-Type": "application/json",
96
  "Authorization": f"Bearer {api_key}"
97
  }
98
 
99
- # Create a system message directing the model to create high-quality marketing graphics,
100
- # with specific emphasis on lead magnets if not specified
101
- system_message = """You are an expert graphic designer specialized in creating professional marketing and lead magnet materials.
102
- You excel at creating attention-grabbing graphics that convert viewers into leads and customers.
103
-
104
- When creating lead magnets or marketing graphics:
105
- 1. Make text highly readable with strong contrast against backgrounds
106
- 2. Use a clear visual hierarchy to guide the viewer's eye
107
- 3. Include compelling visual elements that reinforce the value proposition
108
- 4. Ensure the design conveys professionalism and trustworthiness
109
- 5. Position call-to-action elements prominently
110
-
111
- If the user hasn't specified certain design elements, use your expertise to:
112
- - Choose appropriate color schemes that evoke the right emotional response for the topic
113
- - Select fonts that match the industry and target audience
114
- - Add visual elements that enhance the message without cluttering
115
- - Create a composition that works well for digital marketing purposes"""
116
-
117
- # Enhance the user's prompt with specific guidance for marketing images
118
- enhanced_prompt = f"""Create a professional lead magnet or marketing graphic that will drive conversions based on this description:
119
 
120
  {prompt}
121
 
122
- Even if details are minimal, create a complete, professional design making appropriate assumptions.
123
- Make this graphic immediately usable as a marketing asset with:
124
- 1. Attention-grabbing visual elements
125
- 2. Clear, compelling text hierarchy
126
- 3. Professional design elements that inspire trust
127
- 4. Perfect readability with appropriate contrast and spacing
128
- 5. A composition that drives the viewer toward the call-to-action
129
 
130
- The image should look like it was created by an expert marketing designer specifically to generate leads and conversions.
131
- """
 
 
132
 
133
  data = {
134
- "model": model,
135
- "messages": [
136
- {"role": "system", "content": system_message},
137
- {"role": "user", "content": enhanced_prompt}
138
- ],
139
- "max_tokens": 4096
140
  }
141
 
142
  try:
143
  response = requests.post(
144
- "https://api.openai.com/v1/chat/completions",
145
  headers=headers,
146
- json=data
 
147
  )
148
 
149
  if response.status_code == 200:
150
  response_data = response.json()
151
- content = response_data["choices"][0]["message"]["content"]
152
-
153
- # Extract image URL if present
154
- if "![" in content and "](" in content:
155
- image_url = content.split("](")[1].split(")")[0]
156
- if image_url.startswith("https://"):
157
- return {"success": True, "image_url": image_url, "message": "Image generated successfully!"}
158
-
159
- # If using the newer image generation where the image is embedded in the response
160
- if "image_url" in content or "data:image" in content:
161
- # For newer versions where image content might be directly embedded
162
- image_matches = re.findall(r'(https://[^\s]+\.(?:png|jpg|jpeg|gif))', content)
163
- if image_matches:
164
- return {"success": True, "image_url": image_matches[0], "message": "Image generated successfully!"}
165
- elif "data:image" in content:
166
- # Handle base64 encoded image if present
167
- base64_match = re.search(r'data:image/[^;]+;base64,([^"]+)', content)
168
- if base64_match:
169
- base64_data = base64_match.group(1)
170
- return {"success": True, "image_data": base64_data, "message": "Image generated successfully!"}
171
-
172
- return {"success": False, "message": "Could not extract image from response. The model may need additional prompting."}
173
-
174
  else:
175
  error_message = f"API Error: {response.status_code}"
176
  if response.text:
@@ -181,6 +155,9 @@ The image should look like it was created by an expert marketing designer specif
181
  except:
182
  error_message += f" - {response.text[:200]}"
183
  return {"success": False, "message": error_message}
 
 
 
184
  except Exception as e:
185
  return {"success": False, "message": f"Error: {str(e)}"}
186
 
@@ -252,9 +229,9 @@ with col1:
252
  ]
253
 
254
  for i, example in enumerate(example_prompts):
255
- if st.button(f"Example {i+1}", key=f"example_{i}"):
256
  st.session_state["example_prompt"] = example
257
- st.experimental_rerun()
258
 
259
  st.markdown('</div>', unsafe_allow_html=True)
260
 
@@ -292,61 +269,58 @@ with col1:
292
  st.markdown('</div>', unsafe_allow_html=True)
293
 
294
  # Build the prompt
295
- if "current_prompt" in st.session_state:
296
- complete_prompt = st.session_state["current_prompt"]
297
- del st.session_state["current_prompt"]
298
- else:
299
- # Simplified prompt building
300
- if quick_description:
301
- prompt_parts = [quick_description]
 
302
 
303
- # Add business info if provided
304
- if 'business_name' in locals() and business_name:
305
- prompt_parts.append(f"Business Name: {business_name}")
306
- if 'business_type' in locals() and business_type:
307
- prompt_parts.append(f"Business Type: {business_type}")
308
-
309
- # Add style info if provided
310
- if 'color_scheme' in locals() and color_scheme:
311
- prompt_parts.append(f"Color Scheme: {color_scheme}")
312
- if 'image_style' in locals() and image_style == "Custom" and 'custom_style' in locals() and custom_style:
313
- prompt_parts.append(f"Style: {custom_style}")
314
- elif 'image_style' in locals() and image_style != "Custom":
315
- prompt_parts.append(f"Style: {image_style}")
316
-
317
- # Add aspect ratio
318
- if "Square" in aspect_ratio:
319
- prompt_parts.append("Create a square (1:1) image")
320
- elif "Landscape" in aspect_ratio:
321
- prompt_parts.append("Create a landscape (16:9) format image")
322
- elif "Portrait" in aspect_ratio:
323
- prompt_parts.append("Create a portrait (9:16) format image")
324
- elif "Social Media" in aspect_ratio:
325
- prompt_parts.append("Optimize dimensions for social media sharing")
326
 
327
- # Add special instructions if provided
328
- if 'special_instructions' in locals() and special_instructions:
329
- prompt_parts.append(special_instructions)
330
-
331
- complete_prompt = ". ".join(prompt_parts)
332
- else:
333
- complete_prompt = ""
 
 
 
 
 
 
 
 
 
 
334
 
335
  # Generate button
336
  generate_button = st.button(
337
  "🎨 Generate My Graphic",
338
- disabled=not quick_description,
339
  use_container_width=True
340
  )
341
 
342
  if not quick_description:
343
  st.info("Please describe what type of lead magnet or marketing graphic you want to create")
 
 
344
 
345
  # Display generated image
346
  with col2:
347
  st.markdown('<div class="custom-subheader">Generated Graphic</div>', unsafe_allow_html=True)
348
 
349
- if generate_button:
350
  with st.spinner("Creating your graphic... This may take up to 60 seconds"):
351
  # Save the prompt to history
352
  if complete_prompt not in st.session_state["prompt_history"]:
@@ -358,25 +332,15 @@ with col2:
358
  result = generate_image_from_prompt(complete_prompt)
359
 
360
  if result["success"]:
361
- # Handle image URL or base64 data
362
- if "image_url" in result:
363
- try:
364
- response = requests.get(result["image_url"])
365
- img = Image.open(BytesIO(response.content))
366
- st.session_state["generated_image"] = img
367
- except Exception as e:
368
- st.error(f"Error loading image: {str(e)}")
369
- elif "image_data" in result:
370
- try:
371
- img_data = base64.b64decode(result["image_data"])
372
- img = Image.open(BytesIO(img_data))
373
- st.session_state["generated_image"] = img
374
- except Exception as e:
375
- st.error(f"Error decoding image: {str(e)}")
376
  else:
377
  st.error(result["message"])
378
- if "API key" in result["message"]:
379
- st.warning("There was an issue with the API key. Please try again or contact support.")
380
 
381
  if st.session_state["generated_image"] is not None:
382
  st.markdown('<div class="generated-image">', unsafe_allow_html=True)
@@ -407,30 +371,27 @@ with col2:
407
  result = generate_image_from_prompt(complete_prompt)
408
 
409
  if result["success"]:
410
- if "image_url" in result:
411
- try:
412
- response = requests.get(result["image_url"])
413
- img = Image.open(BytesIO(response.content))
414
- st.session_state["generated_image"] = img
415
- except Exception as e:
416
- st.error(f"Error loading image: {str(e)}")
417
- elif "image_data" in result:
418
- try:
419
- img_data = base64.b64decode(result["image_data"])
420
- img = Image.open(BytesIO(img_data))
421
- st.session_state["generated_image"] = img
422
- except Exception as e:
423
- st.error(f"Error decoding image: {str(e)}")
424
  else:
425
  st.error(result["message"])
426
  else:
427
- st.info("Your generated graphic will appear here. Describe what you want in the text area and click 'Generate My Graphic'.")
428
- # Placeholder image
429
- st.image("https://via.placeholder.com/800x800.png?text=Your+Graphic+Will+Appear+Here", use_column_width=True)
 
 
 
 
430
 
431
  # Footer with simplified disclaimer
432
  st.markdown("""
433
  <div class="footnote">
434
- <p><strong>Note:</strong> This tool uses OpenAI's latest 4o Image Generation technology to create high-quality marketing graphics and lead magnets. For best results, be specific about what type of lead magnet or marketing content you're creating.</p>
435
  </div>
436
  """, unsafe_allow_html=True)
 
66
  border-radius: 5px;
67
  margin-bottom: 20px;
68
  }
69
+ .placeholder-area {
70
+ border: 2px dashed #ddd;
71
+ border-radius: 10px;
72
+ padding: 40px;
73
+ text-align: center;
74
+ background-color: #f8f9fa;
75
+ color: #666;
76
+ }
77
  </style>
78
  """, unsafe_allow_html=True)
79
 
 
93
  if "image_history" not in st.session_state:
94
  st.session_state["image_history"] = []
95
 
96
+ # Get API key from secrets
97
+ OPENAI_API_KEY = st.secrets.get("OPENAI_API_KEY", "")
 
98
 
99
  # Functions
100
+ def generate_image_from_prompt(prompt, api_key=OPENAI_API_KEY):
101
+ """Generate image using OpenAI's DALL-E API"""
102
+ if not api_key or api_key == "YOUR_API_KEY_STORED_IN_SECRETS":
103
+ return {"success": False, "message": "OpenAI API key not configured. Please add your API key to Hugging Face Spaces secrets."}
104
+
105
  headers = {
106
  "Content-Type": "application/json",
107
  "Authorization": f"Bearer {api_key}"
108
  }
109
 
110
+ # Enhanced prompt for marketing graphics
111
+ enhanced_prompt = f"""Create a professional, high-quality lead magnet or marketing graphic with the following specifications:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  {prompt}
114
 
115
+ Design requirements:
116
+ - Make text highly readable with strong contrast
117
+ - Use professional color schemes and typography
118
+ - Include compelling visual elements that reinforce the value proposition
119
+ - Ensure the design conveys professionalism and trustworthiness
120
+ - Create a composition optimized for digital marketing
121
+ - Make it immediately usable as a marketing asset that drives conversions
122
 
123
+ The final image should look like it was created by an expert marketing designer specifically to generate leads and customer engagement."""
124
+
125
+ # Determine image size based on aspect ratio
126
+ size = "1024x1024" # Default square
127
 
128
  data = {
129
+ "model": "dall-e-3",
130
+ "prompt": enhanced_prompt,
131
+ "n": 1,
132
+ "size": size,
133
+ "quality": "standard"
 
134
  }
135
 
136
  try:
137
  response = requests.post(
138
+ "https://api.openai.com/v1/images/generations",
139
  headers=headers,
140
+ json=data,
141
+ timeout=60
142
  )
143
 
144
  if response.status_code == 200:
145
  response_data = response.json()
146
+ image_url = response_data["data"][0]["url"]
147
+ return {"success": True, "image_url": image_url, "message": "Image generated successfully!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  else:
149
  error_message = f"API Error: {response.status_code}"
150
  if response.text:
 
155
  except:
156
  error_message += f" - {response.text[:200]}"
157
  return {"success": False, "message": error_message}
158
+
159
+ except requests.exceptions.Timeout:
160
+ return {"success": False, "message": "Request timed out. Please try again."}
161
  except Exception as e:
162
  return {"success": False, "message": f"Error: {str(e)}"}
163
 
 
229
  ]
230
 
231
  for i, example in enumerate(example_prompts):
232
+ if st.button(f"Use Example {i+1}", key=f"example_{i}"):
233
  st.session_state["example_prompt"] = example
234
+ st.rerun()
235
 
236
  st.markdown('</div>', unsafe_allow_html=True)
237
 
 
269
  st.markdown('</div>', unsafe_allow_html=True)
270
 
271
  # Build the prompt
272
+ if quick_description:
273
+ prompt_parts = [quick_description]
274
+
275
+ # Add business info if provided
276
+ if 'business_name' in locals() and business_name:
277
+ prompt_parts.append(f"Business Name: {business_name}")
278
+ if 'business_type' in locals() and business_type:
279
+ prompt_parts.append(f"Business Type: {business_type}")
280
 
281
+ # Add style info if provided
282
+ if 'color_scheme' in locals() and color_scheme:
283
+ prompt_parts.append(f"Color Scheme: {color_scheme}")
284
+ if 'image_style' in locals() and image_style == "Custom" and 'custom_style' in locals() and custom_style:
285
+ prompt_parts.append(f"Style: {custom_style}")
286
+ elif 'image_style' in locals() and image_style != "Custom":
287
+ prompt_parts.append(f"Style: {image_style}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
+ # Add aspect ratio
290
+ if "Square" in aspect_ratio:
291
+ prompt_parts.append("Create a square (1:1) image")
292
+ elif "Landscape" in aspect_ratio:
293
+ prompt_parts.append("Create a landscape (16:9) format image")
294
+ elif "Portrait" in aspect_ratio:
295
+ prompt_parts.append("Create a portrait (9:16) format image")
296
+ elif "Social Media" in aspect_ratio:
297
+ prompt_parts.append("Optimize dimensions for social media sharing")
298
+
299
+ # Add special instructions if provided
300
+ if 'special_instructions' in locals() and special_instructions:
301
+ prompt_parts.append(special_instructions)
302
+
303
+ complete_prompt = ". ".join(prompt_parts)
304
+ else:
305
+ complete_prompt = ""
306
 
307
  # Generate button
308
  generate_button = st.button(
309
  "🎨 Generate My Graphic",
310
+ disabled=not quick_description or not OPENAI_API_KEY,
311
  use_container_width=True
312
  )
313
 
314
  if not quick_description:
315
  st.info("Please describe what type of lead magnet or marketing graphic you want to create")
316
+ elif not OPENAI_API_KEY:
317
+ st.error("OpenAI API key not configured. Please add your API key to Hugging Face Spaces secrets.")
318
 
319
  # Display generated image
320
  with col2:
321
  st.markdown('<div class="custom-subheader">Generated Graphic</div>', unsafe_allow_html=True)
322
 
323
+ if generate_button and complete_prompt and OPENAI_API_KEY:
324
  with st.spinner("Creating your graphic... This may take up to 60 seconds"):
325
  # Save the prompt to history
326
  if complete_prompt not in st.session_state["prompt_history"]:
 
332
  result = generate_image_from_prompt(complete_prompt)
333
 
334
  if result["success"]:
335
+ try:
336
+ response = requests.get(result["image_url"])
337
+ img = Image.open(BytesIO(response.content))
338
+ st.session_state["generated_image"] = img
339
+ st.success("✅ Image generated successfully!")
340
+ except Exception as e:
341
+ st.error(f"Error loading image: {str(e)}")
 
 
 
 
 
 
 
 
342
  else:
343
  st.error(result["message"])
 
 
344
 
345
  if st.session_state["generated_image"] is not None:
346
  st.markdown('<div class="generated-image">', unsafe_allow_html=True)
 
371
  result = generate_image_from_prompt(complete_prompt)
372
 
373
  if result["success"]:
374
+ try:
375
+ response = requests.get(result["image_url"])
376
+ img = Image.open(BytesIO(response.content))
377
+ st.session_state["generated_image"] = img
378
+ st.success(" Image regenerated successfully!")
379
+ except Exception as e:
380
+ st.error(f"Error loading image: {str(e)}")
 
 
 
 
 
 
 
381
  else:
382
  st.error(result["message"])
383
  else:
384
+ # Custom placeholder instead of external image
385
+ st.markdown("""
386
+ <div class="placeholder-area">
387
+ <h3>🎨 Your Graphic Will Appear Here</h3>
388
+ <p>Describe what you want in the text area and click 'Generate My Graphic' to create your marketing graphic.</p>
389
+ </div>
390
+ """, unsafe_allow_html=True)
391
 
392
  # Footer with simplified disclaimer
393
  st.markdown("""
394
  <div class="footnote">
395
+ <p><strong>Note:</strong> This tool uses OpenAI's DALL-E 3 technology to create high-quality marketing graphics and lead magnets. For best results, be specific about what type of lead magnet or marketing content you're creating.</p>
396
  </div>
397
  """, unsafe_allow_html=True)