Pratap2002 commited on
Commit
8ce3212
·
verified ·
1 Parent(s): 0b1f1ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -118
app.py CHANGED
@@ -123,20 +123,26 @@ def increase_image_quality(image, scale_factor):
123
  def generate_poster():
124
  #st.header("Generate Social Media Post")
125
  description = st.text_input("Enter prompt for Advertisement:")
126
- if st.button("✨", key="ad_generator_button"):
127
- st.session_state.show_ad_generator = True
 
 
 
 
 
 
128
 
129
  if st.session_state.get('show_ad_generator', False):
130
  with st.expander("Advertisement Generator :arrow_right:", expanded=True):
131
  advertisement_generator()
132
 
133
- st.header("Graphic Type")
 
134
  col1, col2 = st.columns(2)
135
  with col1:
136
  post_type = st.selectbox("Select Post Type", ["Instagram advertisement post", "Facebook advertisement post", "Twitter advertisement post", "Other"])
137
  aspect_ratio = st.selectbox("Select Image Aspect Ratio", ["1:1", "16:9", "4:5", "9:16"])
138
  with col2:
139
- # Add dimension selection based on aspect ratio
140
  if aspect_ratio == "1:1":
141
  dimensions = st.selectbox("Select Image Dimensions", ["1080x1080", "1200x1200", "1500x1500"])
142
  elif aspect_ratio == "16:9":
@@ -151,12 +157,12 @@ def generate_poster():
151
  "Corporate/Professional", "Retro/Vintage", "Modern/Contemporary", "Illustrative/Artistic"
152
  ])
153
 
 
 
154
  # Extract width and height from the selected dimensions
155
  width, height = map(int, dimensions.split('x'))
156
-
157
- st.header("Content")
158
 
159
- with st.expander("Content Details", expanded=False):
160
  header = st.text_input("Enter Header for Advertisement:")
161
  sub_header = st.text_input("Enter Sub-header for Advertisement:")
162
  # Allow multiple user prompts
@@ -166,9 +172,9 @@ def generate_poster():
166
  user_prompt = st.text_area(f"Enter Descriptions to display in the image (Descriptions {i+1}):")
167
  user_prompts.append(user_prompt)
168
 
169
- st.header("Branding")
170
 
171
- with st.expander("Branding Details", expanded=False):
172
  # Add color selection with predefined options
173
  color_options = ["None", "Black", "White", "Red", "Blue", "Green", "Yellow", "Purple"]
174
  selected_color = st.selectbox("Choose a dominant color for the image", color_options)
@@ -181,102 +187,104 @@ def generate_poster():
181
  "Left Middle", "Right Middle",
182
  "Bottom Left", "Bottom Middle", "Bottom Right"
183
  ])
184
-
185
- num_images = st.number_input("Number of Images", min_value=4, max_value=100, value=4)
186
 
187
- # Create a column layout to center the button
188
- col1, col2, col3 = st.columns([1, 2, 1])
189
 
190
- # Place the button in the middle column and increase its width
191
- with col2:
192
- if st.button("Generate Graphics", use_container_width=True):
193
- base_prompt = f"Create a minimalistic and realistic poster image with the following text as the header: '{header}'. Use '{sub_header}' as the sub-header. Use this design style and go with this {design_style.lower()} style for the post. Include the following text as the description for the advertisement: {description}. The image should have an aspect ratio of {aspect_ratio} and dimensions of {width}x{height}. Use {selected_color.lower()} as the dominant color in the image. Ensure the image is in 4k high resolution. And do not include any extra text in the image only instruction text included.And try to fill the vacant part with releveng images. Make the design clean and elegant, focusing on simplicity and realism."
194
-
195
- if post_type == "Other":
196
- full_prompt = f"{base_prompt} The image should be suitable for general use across various platforms."
197
- else:
198
- full_prompt = f"{base_prompt} This image is specifically for a {post_type.lower()}."
199
-
200
- # Add user prompts to full_prompt if provided
201
- for i, user_prompt in enumerate(user_prompts):
202
- if user_prompt:
203
- full_prompt += f" Include the following text in the image (Prompt {i+1}): '{user_prompt}'."
204
-
205
- generated_images = []
206
- for i in range(num_images):
207
- with st.spinner(f"Generating Graphic {i+1}..."):
208
- logger.info(f"Generating Graphic {i+1} with prompt: {full_prompt}")
209
- # Add a random seed to ensure different images
210
- seed = random.randint(1, 1000000)
211
- image_bytes = query({"inputs": full_prompt, "parameters": {"seed": seed, "width": width, "height": height}})
 
 
 
 
 
 
212
 
213
- if image_bytes:
214
- image = Image.open(io.BytesIO(image_bytes))
 
 
 
 
215
 
216
- # Add logo if provided
217
- if logo:
218
- logo_image = Image.open(logo)
219
- logo_width = int(image.width * 0.15) # 15% of the image width
220
- logo_height = int(logo_image.height * (logo_width / logo_image.width))
221
- logo_image = logo_image.resize((logo_width, logo_height), Image.LANCZOS)
222
-
223
- padding = int(image.width * 0.02) # Fixed 2% padding
224
-
225
- if logo_position == "None":
226
- # Randomly choose a corner for logo placement
227
- corner = random.choice(["Top Left", "Top Right", "Bottom Left", "Bottom Right"])
228
- if corner == "Top Left":
229
- position = (padding, padding)
230
- elif corner == "Top Right":
231
- position = (image.width - logo_width - padding, padding)
232
- elif corner == "Bottom Left":
233
- position = (padding, image.height - logo_height - padding)
234
- else: # Bottom Right
235
- position = (image.width - logo_width - padding, image.height - logo_height - padding)
236
- else:
237
- if logo_position == "Top Left":
238
- position = (padding, padding)
239
- elif logo_position == "Top Middle":
240
- position = ((image.width - logo_width) // 2, padding)
241
- elif logo_position == "Top Right":
242
- position = (image.width - logo_width - padding, padding)
243
- elif logo_position == "Bottom Left":
244
- position = (padding, image.height - logo_height - padding)
245
- elif logo_position == "Bottom Middle":
246
- position = ((image.width - logo_width) // 2, image.height - logo_height - padding)
247
- else: # Bottom Right
248
- position = (image.width - logo_width - padding, image.height - logo_height - padding)
249
 
250
- # Create a new image with an alpha channel
251
- combined_image = Image.new('RGBA', image.size, (0, 0, 0, 0))
252
- combined_image.paste(image, (0, 0))
253
-
254
- # Convert logo to RGBA if it's not already
255
- if logo_image.mode != 'RGBA':
256
- logo_image = logo_image.convert('RGBA')
257
-
258
- combined_image.paste(logo_image, position, logo_image)
259
-
260
- # Convert back to RGB for compatibility
261
- image = combined_image.convert('RGB')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
- generated_images.append(image)
 
 
264
 
265
- # Display generated image
266
- st.image(image, caption=f"Generated Poster {i+1}", use_column_width=True)
267
 
268
- # Provide download option for the generated image
269
- buf = io.BytesIO()
270
- image.save(buf, format="PNG")
271
- byte_im = buf.getvalue()
272
- st.download_button(
273
- label=f"Download generated Graphic {i+1}",
274
- data=byte_im,
275
- file_name=f"generated_Graphic_{i+1}.png",
276
- mime="image/png"
277
- )
278
- else:
279
- st.error(f"Failed to generate Graphic {i+1}")
 
 
 
 
 
 
 
 
 
 
280
 
281
  # Content from image_to_image.py
282
  def encode_image(image):
@@ -289,7 +297,7 @@ def generate_image_prompt(image):
289
 
290
  prompt_parts = [
291
  {"mime_type": "image/png", "data": base64.b64decode(encoded_image)},
292
- "Analyze this image and generate a detailed prompt that could be used to recreate this image using an AI image generation model. Include key visual elements, style, composition, and any other relevant details but do not include any kind of text elements."
293
  ]
294
 
295
  response = model.generate_content(prompt_parts)
@@ -547,11 +555,24 @@ def remove_background(image):
547
 
548
  # Main Streamlit App
549
  def main():
550
- # Add logo to the middle of the sidebar
551
  logo = Image.open("Mark8 AI.png") # Replace with your logo path
552
- col1, col2, col3 = st.sidebar.columns([1, 2, 1])
553
- with col2:
554
- st.image(logo, width=150)
 
 
 
 
 
 
 
 
 
 
 
 
 
555
 
556
  # Initialize session state for page
557
  if 'page' not in st.session_state:
@@ -562,7 +583,19 @@ def main():
562
  st.title(title)
563
  st.write(description)
564
 
565
- if st.sidebar.button("Poster Generation"):
 
 
 
 
 
 
 
 
 
 
 
 
566
  st.session_state.page = "poster_generation"
567
 
568
  if st.sidebar.button("Image to Image Generation"):
@@ -575,16 +608,16 @@ def main():
575
  st.session_state.page = "advertisement_generator"
576
 
577
  if st.session_state.page == "text_to_image":
578
- display_title_and_description("Graphic Generator", "Transform your ideas into stunning visuals.")
579
  text_to_image_generation()
580
  elif st.session_state.page == "image_editing":
581
- display_title_and_description("Graphic Generator", "Enhance and modify your images with powerful tools.")
582
  image_editing()
583
  elif st.session_state.page == "poster_generation":
584
- display_title_and_description("Graphic Generator", "Create eye-catching posters for various platforms.")
585
  generate_poster()
586
  elif st.session_state.page == "advertisement_generator":
587
- display_title_and_description("Graphic Generator", "Create compelling advertisements with AI assistance.")
588
  advertisement_generator()
589
 
590
  def text_to_image_generation():
@@ -604,23 +637,13 @@ def text_to_image_generation():
604
  st.text_area(label="", value=generated_prompt.strip(), height=200, key="generated_prompt", disabled=True)
605
  st.session_state['saved_prompt'] = generated_prompt.strip()
606
 
607
- # Add multiple text elements
608
- st.subheader("Add Text Elements")
609
- num_text_elements = st.number_input("Number of text elements to add:", min_value=1, max_value=5, value=1)
610
- text_elements = []
611
- for i in range(num_text_elements):
612
- text_element = st.text_input(f"Enter text {i+1} to add to the image:")
613
- if text_element:
614
- text_elements.append(f'text on image: "{text_element}"')
615
- text_element_prompt = ", ".join(text_elements)
616
-
617
  # User input prompt
618
  st.subheader("Additional Prompt")
619
  user_prompt = st.text_input("Enter additional prompt details:")
620
 
621
  # Combine prompts
622
  saved_prompt = st.session_state.get('saved_prompt', '')
623
- final_prompt = f"{saved_prompt}, {text_element_prompt}, {user_prompt}".strip()
624
 
625
  st.subheader("Final Prompt")
626
  final_prompt_area = st.text_area("Final prompt for image generation:", value=final_prompt, height=150, key="final_prompt")
 
123
  def generate_poster():
124
  #st.header("Generate Social Media Post")
125
  description = st.text_input("Enter prompt for Advertisement:")
126
+ col1, col2 = st.columns(2) # Equal width columns
127
+ with col1:
128
+ if st.button("✨Enhance My Prompt", key="ad_generator_button", use_container_width=True):
129
+ st.session_state.show_ad_generator = True
130
+ with col2:
131
+ generate_button = st.button("Generate Graphics", use_container_width=True)
132
+
133
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
134
 
135
  if st.session_state.get('show_ad_generator', False):
136
  with st.expander("Advertisement Generator :arrow_right:", expanded=True):
137
  advertisement_generator()
138
 
139
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
140
+
141
  col1, col2 = st.columns(2)
142
  with col1:
143
  post_type = st.selectbox("Select Post Type", ["Instagram advertisement post", "Facebook advertisement post", "Twitter advertisement post", "Other"])
144
  aspect_ratio = st.selectbox("Select Image Aspect Ratio", ["1:1", "16:9", "4:5", "9:16"])
145
  with col2:
 
146
  if aspect_ratio == "1:1":
147
  dimensions = st.selectbox("Select Image Dimensions", ["1080x1080", "1200x1200", "1500x1500"])
148
  elif aspect_ratio == "16:9":
 
157
  "Corporate/Professional", "Retro/Vintage", "Modern/Contemporary", "Illustrative/Artistic"
158
  ])
159
 
160
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
161
+
162
  # Extract width and height from the selected dimensions
163
  width, height = map(int, dimensions.split('x'))
 
 
164
 
165
+ with st.expander("Add Content : Header, Sub-header and Descriptions", expanded=False):
166
  header = st.text_input("Enter Header for Advertisement:")
167
  sub_header = st.text_input("Enter Sub-header for Advertisement:")
168
  # Allow multiple user prompts
 
172
  user_prompt = st.text_area(f"Enter Descriptions to display in the image (Descriptions {i+1}):")
173
  user_prompts.append(user_prompt)
174
 
175
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
176
 
177
+ with st.expander("Add Branding : Logo and Color", expanded=False):
178
  # Add color selection with predefined options
179
  color_options = ["None", "Black", "White", "Red", "Blue", "Green", "Yellow", "Purple"]
180
  selected_color = st.selectbox("Choose a dominant color for the image", color_options)
 
187
  "Left Middle", "Right Middle",
188
  "Bottom Left", "Bottom Middle", "Bottom Right"
189
  ])
 
 
190
 
191
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
 
192
 
193
+ # Add number of images to generate (hidden from user)
194
+ #num_images = st.number_input("Number of images to generate", min_value=4, max_value=100, value=1)
195
+
196
+ num_images = 4
197
+
198
+ if generate_button:
199
+ base_prompt = f"Create a minimalistic and realistic poster image with the following text as the header: '{header}'. Use '{sub_header}' as the sub-header. Use this design style and go with this {design_style.lower()} style for the post. Include the following text as the description for the advertisement: {description}. The image should have an aspect ratio of {aspect_ratio} and dimensions of {width}x{height}. Use {selected_color.lower()} as the dominant color in the image. Ensure the image is in 4k high resolution. And do not include any extra text in the image only instruction text included.And try to fill the vacant part with releveng images. Make the design clean and elegant, focusing on simplicity and realism."
200
+
201
+ if post_type == "Other":
202
+ full_prompt = f"{base_prompt} The image should be suitable for general use across various platforms."
203
+ else:
204
+ full_prompt = f"{base_prompt} This image is specifically for a {post_type.lower()}."
205
+
206
+ # Add user prompts to full_prompt if provided
207
+ for i, user_prompt in enumerate(user_prompts):
208
+ if user_prompt:
209
+ full_prompt += f" Include the following text in the image (Prompt {i+1}): '{user_prompt}'."
210
+
211
+ generated_images = []
212
+ for i in range(num_images):
213
+ with st.spinner(f"Generating Graphic {i+1}..."):
214
+ logger.info(f"Generating Graphic {i+1} with prompt: {full_prompt}")
215
+ # Add a random seed to ensure different images
216
+ seed = random.randint(1, 1000000)
217
+ image_bytes = query({"inputs": full_prompt, "parameters": {"seed": seed, "width": width, "height": height}})
218
+
219
+ if image_bytes:
220
+ image = Image.open(io.BytesIO(image_bytes))
221
 
222
+ # Add logo if provided
223
+ if logo:
224
+ logo_image = Image.open(logo)
225
+ logo_width = int(image.width * 0.15) # 15% of the image width
226
+ logo_height = int(logo_image.height * (logo_width / logo_image.width))
227
+ logo_image = logo_image.resize((logo_width, logo_height), Image.LANCZOS)
228
 
229
+ padding = int(image.width * 0.02) # Fixed 2% padding
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
+ if logo_position == "None":
232
+ # Randomly choose a corner for logo placement
233
+ corner = random.choice(["Top Left", "Top Right", "Bottom Left", "Bottom Right"])
234
+ if corner == "Top Left":
235
+ position = (padding, padding)
236
+ elif corner == "Top Right":
237
+ position = (image.width - logo_width - padding, padding)
238
+ elif corner == "Bottom Left":
239
+ position = (padding, image.height - logo_height - padding)
240
+ else: # Bottom Right
241
+ position = (image.width - logo_width - padding, image.height - logo_height - padding)
242
+ else:
243
+ if logo_position == "Top Left":
244
+ position = (padding, padding)
245
+ elif logo_position == "Top Middle":
246
+ position = ((image.width - logo_width) // 2, padding)
247
+ elif logo_position == "Top Right":
248
+ position = (image.width - logo_width - padding, padding)
249
+ elif logo_position == "Bottom Left":
250
+ position = (padding, image.height - logo_height - padding)
251
+ elif logo_position == "Bottom Middle":
252
+ position = ((image.width - logo_width) // 2, image.height - logo_height - padding)
253
+ else: # Bottom Right
254
+ position = (image.width - logo_width - padding, image.height - logo_height - padding)
255
+
256
+ # Create a new image with an alpha channel
257
+ combined_image = Image.new('RGBA', image.size, (0, 0, 0, 0))
258
+ combined_image.paste(image, (0, 0))
259
 
260
+ # Convert logo to RGBA if it's not already
261
+ if logo_image.mode != 'RGBA':
262
+ logo_image = logo_image.convert('RGBA')
263
 
264
+ combined_image.paste(logo_image, position, logo_image)
 
265
 
266
+ # Convert back to RGB for compatibility
267
+ image = combined_image.convert('RGB')
268
+
269
+ generated_images.append(image)
270
+
271
+ # Display generated image
272
+ st.image(image, caption=f"Generated Poster {i+1}", use_column_width=True)
273
+
274
+ # Provide download option for the generated image
275
+ buf = io.BytesIO()
276
+ image.save(buf, format="PNG")
277
+ byte_im = buf.getvalue()
278
+ st.download_button(
279
+ label=f"Download generated Graphic {i+1}",
280
+ data=byte_im,
281
+ file_name=f"generated_Graphic_{i+1}.png",
282
+ mime="image/png"
283
+ )
284
+ else:
285
+ st.error(f"Failed to generate Graphic {i+1}")
286
+
287
+ st.markdown("<div style='height: 15px;'></div>", unsafe_allow_html=True)
288
 
289
  # Content from image_to_image.py
290
  def encode_image(image):
 
297
 
298
  prompt_parts = [
299
  {"mime_type": "image/png", "data": base64.b64decode(encoded_image)},
300
+ "Analyze this image and generate a detailed prompt that could be used to recreate this image using an AI image generation model. Include key visual elements, style, composition,text element, and any other relevant details."
301
  ]
302
 
303
  response = model.generate_content(prompt_parts)
 
555
 
556
  # Main Streamlit App
557
  def main():
558
+ # Add logo to the center of the sidebar
559
  logo = Image.open("Mark8 AI.png") # Replace with your logo path
560
+ st.sidebar.markdown(
561
+ """
562
+ <style>
563
+ .sidebar-logo {
564
+ display: flex;
565
+ justify-content: center;
566
+ align-items: center;
567
+ padding: 1rem 0;
568
+ }
569
+ </style>
570
+ """,
571
+ unsafe_allow_html=True
572
+ )
573
+ st.sidebar.markdown('<div class="sidebar-logo">', unsafe_allow_html=True)
574
+ st.sidebar.image(logo, width=150)
575
+ st.sidebar.markdown('</div>', unsafe_allow_html=True)
576
 
577
  # Initialize session state for page
578
  if 'page' not in st.session_state:
 
583
  st.title(title)
584
  st.write(description)
585
 
586
+ # Create even-shaped buttons in the sidebar
587
+ button_style = """
588
+ <style>
589
+ div.stButton > button {
590
+ width: 100%;
591
+ height: 3em;
592
+ margin-bottom: 10px;
593
+ }
594
+ </style>
595
+ """
596
+ st.sidebar.markdown(button_style, unsafe_allow_html=True)
597
+
598
+ if st.sidebar.button("Designer"):
599
  st.session_state.page = "poster_generation"
600
 
601
  if st.sidebar.button("Image to Image Generation"):
 
608
  st.session_state.page = "advertisement_generator"
609
 
610
  if st.session_state.page == "text_to_image":
611
+ display_title_and_description("Mark8 Designer", "Transform your ideas into stunning visuals.")
612
  text_to_image_generation()
613
  elif st.session_state.page == "image_editing":
614
+ display_title_and_description("Mark8 Designer", "Enhance and modify your images with powerful tools.")
615
  image_editing()
616
  elif st.session_state.page == "poster_generation":
617
+ display_title_and_description("Mark8 Designer", "Create eye-catching posters for various platforms.")
618
  generate_poster()
619
  elif st.session_state.page == "advertisement_generator":
620
+ display_title_and_description("Mark8 Designer", "Create compelling advertisements with AI assistance.")
621
  advertisement_generator()
622
 
623
  def text_to_image_generation():
 
637
  st.text_area(label="", value=generated_prompt.strip(), height=200, key="generated_prompt", disabled=True)
638
  st.session_state['saved_prompt'] = generated_prompt.strip()
639
 
 
 
 
 
 
 
 
 
 
 
640
  # User input prompt
641
  st.subheader("Additional Prompt")
642
  user_prompt = st.text_input("Enter additional prompt details:")
643
 
644
  # Combine prompts
645
  saved_prompt = st.session_state.get('saved_prompt', '')
646
+ final_prompt = f"{saved_prompt}, {user_prompt}".strip()
647
 
648
  st.subheader("Final Prompt")
649
  final_prompt_area = st.text_area("Final prompt for image generation:", value=final_prompt, height=150, key="final_prompt")