Pratap2002 commited on
Commit
117bce9
·
verified ·
1 Parent(s): 8ce3212

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -63
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import streamlit as st
2
- from PIL import Image
3
  import io
4
  import base64
5
  import google.generativeai as genai
@@ -15,6 +15,7 @@ import pytesseract
15
  from fontTools.ttLib import TTFont
16
  from langchain_groq import ChatGroq
17
  import logging
 
18
 
19
 
20
  # Load environment variables
@@ -36,11 +37,8 @@ model = genai.GenerativeModel(
36
  generation_config=generation_config,
37
  )
38
 
39
- API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
40
- headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
41
 
42
- # Set up Tesseract path
43
- pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Adjust this path as needed
44
 
45
  # Set up Groq LLM
46
  llm = ChatGroq(
@@ -49,6 +47,7 @@ llm = ChatGroq(
49
  model_name="llama-3.1-70b-versatile"
50
  )
51
 
 
52
  # Content from agent.py
53
  def generate_advertisement_prompt(description):
54
  prompt = f"""
@@ -87,38 +86,21 @@ def advertisement_generator():
87
 
88
  post_description = st.text_input("Enter a brief description for your advertisement post:")
89
 
90
- if st.button("Generate Advertisement Elements"):
91
  if post_description:
92
- with st.spinner("Generating advertisement elements..."):
93
  final_prompt = generate_advertisement_prompt(post_description)
94
- st.subheader("Generated Advertisement Prompt:")
95
 
96
  st.text_area(label="Final Prompt", value=final_prompt.strip(), height=200)
97
  else:
98
- st.warning("Please enter a description for your advertisement post.")
99
 
100
  # Content from image_generation.py
101
  logging.basicConfig(level=logging.DEBUG)
102
  logger = logging.getLogger(__name__)
103
 
104
- def query(payload):
105
- try:
106
- response = requests.post(API_URL, headers=headers, json=payload)
107
- response.raise_for_status()
108
-
109
- logger.debug(f"API response status code: {response.status_code}")
110
- logger.debug(f"API response headers: {response.headers}")
111
-
112
- return response.content
113
- except requests.exceptions.RequestException as e:
114
- logger.error(f"Request failed: {str(e)}")
115
- st.error(f"Request failed: {str(e)}")
116
- return None
117
-
118
- def increase_image_quality(image, scale_factor):
119
- width, height = image.size
120
- new_size = (width * scale_factor, height * scale_factor)
121
- return image.resize(new_size, Image.LANCZOS)
122
 
123
  def generate_poster():
124
  #st.header("Generate Social Media Post")
@@ -133,7 +115,7 @@ def generate_poster():
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)
@@ -144,13 +126,13 @@ def generate_poster():
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":
149
  dimensions = st.selectbox("Select Image Dimensions", ["1920x1080", "1280x720", "2560x1440"])
150
  elif aspect_ratio == "4:5":
151
- dimensions = st.selectbox("Select Image Dimensions", ["1080x1350", "1200x1500", "1600x2000"])
152
  elif aspect_ratio == "9:16":
153
- dimensions = st.selectbox("Select Image Dimensions", ["1080x1920", "1350x2400", "1600x2844"])
154
 
155
  design_style = st.selectbox("Select Design Style", [
156
  "Minimalistic", "Bold/Graphic", "Elegant", "Playful/Fun",
@@ -190,35 +172,23 @@ def generate_poster():
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)
@@ -304,14 +274,9 @@ def generate_image_prompt(image):
304
  return response.text
305
 
306
  def generate_new_image(prompt):
307
- # Add a random seed to ensure different images
308
- seed = random.randint(1, 1000000)
309
- payload = {
310
- "inputs": prompt,
311
- "parameters": {"seed": seed}
312
- }
313
- response = requests.post(API_URL, headers=headers, json=payload)
314
- return Image.open(io.BytesIO(response.content))
315
 
316
  # Part 2: Image Editing
317
 
 
1
  import streamlit as st
2
+ from PIL import Image, ImageFont, ImageDraw
3
  import io
4
  import base64
5
  import google.generativeai as genai
 
15
  from fontTools.ttLib import TTFont
16
  from langchain_groq import ChatGroq
17
  import logging
18
+ from huggingface_hub import InferenceClient
19
 
20
 
21
  # Load environment variables
 
37
  generation_config=generation_config,
38
  )
39
 
 
 
40
 
41
+ pytesseract.pytesseract.tesseract_cmd = r'Tesseract-OCR\tesseract.exe'
 
42
 
43
  # Set up Groq LLM
44
  llm = ChatGroq(
 
47
  model_name="llama-3.1-70b-versatile"
48
  )
49
 
50
+
51
  # Content from agent.py
52
  def generate_advertisement_prompt(description):
53
  prompt = f"""
 
86
 
87
  post_description = st.text_input("Enter a brief description for your advertisement post:")
88
 
89
+ if st.button("Generate Image Prompt"):
90
  if post_description:
91
+ with st.spinner("Prompt Enhancer..."):
92
  final_prompt = generate_advertisement_prompt(post_description)
93
+ st.subheader("Generated Image Prompt:")
94
 
95
  st.text_area(label="Final Prompt", value=final_prompt.strip(), height=200)
96
  else:
97
+ st.warning("Please enter a description for your post.")
98
 
99
  # Content from image_generation.py
100
  logging.basicConfig(level=logging.DEBUG)
101
  logger = logging.getLogger(__name__)
102
 
103
+ client = InferenceClient("black-forest-labs/FLUX.1-dev", token=os.getenv('HF_TOKEN'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  def generate_poster():
106
  #st.header("Generate Social Media Post")
 
115
  st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
116
 
117
  if st.session_state.get('show_ad_generator', False):
118
+ with st.expander("Prompt Enhancer :arrow_right:", expanded=True):
119
  advertisement_generator()
120
 
121
  st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
 
126
  aspect_ratio = st.selectbox("Select Image Aspect Ratio", ["1:1", "16:9", "4:5", "9:16"])
127
  with col2:
128
  if aspect_ratio == "1:1":
129
+ dimensions = st.selectbox("Select Image Dimensions", ["1024x1024", "1200x1200", "1504x1504"])
130
  elif aspect_ratio == "16:9":
131
  dimensions = st.selectbox("Select Image Dimensions", ["1920x1080", "1280x720", "2560x1440"])
132
  elif aspect_ratio == "4:5":
133
+ dimensions = st.selectbox("Select Image Dimensions", ["1080x1344", "1200x1504", "1600x2000"])
134
  elif aspect_ratio == "9:16":
135
+ dimensions = st.selectbox("Select Image Dimensions", ["1080x1920", "1344x2400", "1600x2848"])
136
 
137
  design_style = st.selectbox("Select Design Style", [
138
  "Minimalistic", "Bold/Graphic", "Elegant", "Playful/Fun",
 
172
 
173
  st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
174
 
 
 
 
 
 
175
  if generate_button:
176
+ # Generate 4 different variations of the prompt with enhanced realism and attention-grabbing elements
177
+ prompt_variations = [
178
+ f"Create a hyper-realistic, professional {post_type.lower()} that demands attention. The image should feature stunning {selected_color.lower() if selected_color != 'None' else 'vibrant'} colors with perfect lighting and shadows. Header: \"{header}\". Sub-header: \"{sub_header}\". Implement a {design_style.lower()} aesthetic with photorealistic textures and materials. Main focus: {description}. Use cinema-quality composition with {aspect_ratio} aspect ratio at {width}x{height}. Include dramatic lighting effects, subtle lens flares, and professional-grade depth of field. The design should incorporate cutting-edge {random.choice(['3D elements', 'metallic accents', 'glass effects', 'neon highlights'])} to create visual interest. Ensure 8K ultra-high resolution with perfect clarity. Text should be crystal clear and expertly integrated. Create a powerful visual hierarchy that guides the viewer's eye. Make it look like it was shot by a professional photographer with high-end equipment. Variation {i+1}/4 with unique {random.choice(['golden hour lighting', 'studio lighting', 'natural daylight', 'dramatic spotlights'])}. Seed: {random.randint(1, 999999)}"
179
+ for i in range(4)
180
+ ]
 
 
 
 
 
 
181
 
182
  generated_images = []
183
+ for i, prompt in enumerate(prompt_variations):
184
  with st.spinner(f"Generating Graphic {i+1}..."):
185
+ logger.info(f"Generating Graphic {i+1} with prompt: {prompt}")
 
 
 
186
 
187
+ # Generate image using FLUX model with random seed
188
+ random_seed = random.randint(1, 999999)
189
+ image = client.text_to_image(prompt, seed=random_seed)
190
+
191
+ if image:
192
  # Add logo if provided
193
  if logo:
194
  logo_image = Image.open(logo)
 
274
  return response.text
275
 
276
  def generate_new_image(prompt):
277
+ # Generate image using FLUX model with random seed
278
+ random_seed = random.randint(1, 999999)
279
+ return client.text_to_image(prompt, seed=random_seed)
 
 
 
 
 
280
 
281
  # Part 2: Image Editing
282