rairo commited on
Commit
7dc8075
·
verified ·
1 Parent(s): cdfbca8

Update image_gen.py

Browse files
Files changed (1) hide show
  1. image_gen.py +75 -50
image_gen.py CHANGED
@@ -1,8 +1,6 @@
1
  # -----------------------
2
  # Image Generation
3
  # -----------------------
4
-
5
-
6
  import os
7
  import re
8
  import time
@@ -87,15 +85,20 @@ def standardize_and_validate_image(file_path):
87
 
88
  def generate_image(prompt_text, style, model="hf"):
89
  """
90
- Generate an image from a text prompt using either Hugging Face's, Pollinations Turbo's,
91
- or Google's Gemini API.
 
 
 
 
92
  Args:
93
- prompt_text (str): The text prompt for image generation.
94
- style (str or None): The style of the image (used for HF and Gemini models).
95
- model (str): Which model to use ("hf" for Hugging Face, "pollinations_turbo" for Pollinations Turbo,
96
- or "gemini" for Google's Gemini).
 
97
  Returns:
98
- tuple: A tuple containing the generated PIL.Image and a Base64 string of the image.
99
  """
100
  try:
101
  if model == "pollinations_turbo":
@@ -108,60 +111,104 @@ def generate_image(prompt_text, style, model="hf"):
108
  print(f"Error from image generation API: {response.status_code}")
109
  return None, None
110
  image_bytes = response.content
111
-
112
  elif model == "gemini":
113
  # For Google's Gemini model
114
  try:
115
-
116
- # Get API key from environment variable
117
  g_api_key = os.getenv("GEMINI")
118
  if not g_api_key:
119
  logger.error("GEMINI_API_KEY not found in environment variables")
120
  print("Google Gemini API key is missing. Please set the GEMINI_API_KEY environment variable.")
121
  return None, None
122
-
123
  # Initialize Gemini client
124
  client = genai.Client(api_key=g_api_key)
125
-
126
  # Enhance prompt with style
127
  enhanced_prompt = f"image of {prompt_text} in {style} style, high quality, detailed illustration"
128
-
129
  # Generate content
130
  response = client.models.generate_content(
131
  model="models/gemini-2.0-flash-exp",
132
  contents=enhanced_prompt,
133
  config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])
134
  )
135
-
136
  # Extract image from response
137
  for part in response.candidates[0].content.parts:
138
  if part.inline_data is not None:
139
  image = Image.open(BytesIO(part.inline_data.data))
140
-
141
  # Convert to base64 string
142
  buffered = io.BytesIO()
143
  image.save(buffered, format="JPEG")
144
  img_str = base64.b64encode(buffered.getvalue()).decode()
145
-
146
  return image, img_str
147
-
148
  # If no image was found in the response
149
  logger.error("No image was found in the Gemini API response")
150
  print("Gemini API didn't return an image")
151
  return None, None
152
-
153
  except ImportError:
154
  logger.error("Google Gemini libraries not installed")
155
- st.error("Google Gemini libraries not installed. Install with 'pip install google-genai'")
156
  return None, None
157
-
158
  except Exception as e:
159
  logger.error(f"Gemini API error: {str(e)}")
160
  print(f"Error from Gemini image generation: {str(e)}")
161
  return None, None
162
-
163
- else: # Default to Hugging Face model
164
- # For Hugging Face model, include style details in the prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  enhanced_prompt = f"{prompt_text} in {style} style, high quality, detailed illustration"
166
  model_id = "black-forest-labs/FLUX.1-dev"
167
  api_url = f"https://api-inference.huggingface.co/models/{model_id}"
@@ -173,43 +220,21 @@ def generate_image(prompt_text, style, model="hf"):
173
  return None, None
174
  image_bytes = response.content
175
 
176
- # For HF and Pollinations models that return image bytes
177
  if model != "gemini":
178
  image = Image.open(io.BytesIO(image_bytes))
179
  buffered = io.BytesIO()
180
  image.save(buffered, format="JPEG")
181
  img_str = base64.b64encode(buffered.getvalue()).decode()
182
  return image, img_str
183
-
184
  except Exception as e:
185
  print(f"Error generating image: {e}")
186
  logger.error(f"Image generation error: {str(e)}")
187
-
188
  # Return a placeholder image in case of failure
189
  return Image.new('RGB', (1024, 1024), color=(200,200,200)), None
190
 
191
- def generate_image_with_retry(prompt_text, style, model="hf", max_retries=3):
192
- """
193
- Attempt to generate an image using generate_image, retrying up to max_retries if needed.
194
- Args:
195
- prompt_text (str): The text prompt for image generation.
196
- style (str or None): The style of the image (ignored for Pollinations Turbo).
197
- model (str): Which model to use ("hf" or "pollinations_turbo").
198
- max_retries (int): Maximum number of retries.
199
- Returns:
200
- tuple: The generated image and its Base64 string.
201
- """
202
- for attempt in range(max_retries):
203
- try:
204
- if attempt > 0:
205
- time.sleep(2 ** attempt)
206
- return generate_image(prompt_text, style, model=model)
207
- except Exception as e:
208
- logger.error(f"Attempt {attempt+1} failed: {e}")
209
- if attempt == max_retries - 1:
210
- raise
211
- return None, None
212
-
213
  # edit image function
214
  def edit_section_image(image_url: str, gemini_prompt: str):
215
  """
 
1
  # -----------------------
2
  # Image Generation
3
  # -----------------------
 
 
4
  import os
5
  import re
6
  import time
 
85
 
86
  def generate_image(prompt_text, style, model="hf"):
87
  """
88
+ Generate an image from a text prompt using one of the following:
89
+ - Hugging Face's FLUX.1-dev
90
+ - Pollinations Turbo
91
+ - Google's Gemini
92
+ - Pexels API (for a real photo instead of AI)
93
+
94
  Args:
95
+ prompt_text (str): The text prompt for image generation or search.
96
+ style (str or None): The style of the image (used for HF and Gemini models, ignored for Pexels).
97
+ model (str): Which model to use
98
+ ("hf", "pollinations_turbo", "gemini", or "pexels").
99
+
100
  Returns:
101
+ tuple: (PIL.Image, base64_string) or (None, None) on error.
102
  """
103
  try:
104
  if model == "pollinations_turbo":
 
111
  print(f"Error from image generation API: {response.status_code}")
112
  return None, None
113
  image_bytes = response.content
114
+
115
  elif model == "gemini":
116
  # For Google's Gemini model
117
  try:
 
 
118
  g_api_key = os.getenv("GEMINI")
119
  if not g_api_key:
120
  logger.error("GEMINI_API_KEY not found in environment variables")
121
  print("Google Gemini API key is missing. Please set the GEMINI_API_KEY environment variable.")
122
  return None, None
123
+
124
  # Initialize Gemini client
125
  client = genai.Client(api_key=g_api_key)
126
+
127
  # Enhance prompt with style
128
  enhanced_prompt = f"image of {prompt_text} in {style} style, high quality, detailed illustration"
129
+
130
  # Generate content
131
  response = client.models.generate_content(
132
  model="models/gemini-2.0-flash-exp",
133
  contents=enhanced_prompt,
134
  config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])
135
  )
136
+
137
  # Extract image from response
138
  for part in response.candidates[0].content.parts:
139
  if part.inline_data is not None:
140
  image = Image.open(BytesIO(part.inline_data.data))
 
141
  # Convert to base64 string
142
  buffered = io.BytesIO()
143
  image.save(buffered, format="JPEG")
144
  img_str = base64.b64encode(buffered.getvalue()).decode()
 
145
  return image, img_str
146
+
147
  # If no image was found in the response
148
  logger.error("No image was found in the Gemini API response")
149
  print("Gemini API didn't return an image")
150
  return None, None
151
+
152
  except ImportError:
153
  logger.error("Google Gemini libraries not installed")
154
+ print("Google Gemini libraries not installed. Install with 'pip install google-genai'")
155
  return None, None
156
+
157
  except Exception as e:
158
  logger.error(f"Gemini API error: {str(e)}")
159
  print(f"Error from Gemini image generation: {str(e)}")
160
  return None, None
161
+
162
+ elif model == "pexels":
163
+ # ---------- NEW BRANCH FOR PEXELS -----------
164
+ pexels_api_key = os.getenv("PEXELS_API_KEY")
165
+ if not pexels_api_key:
166
+ logger.error("PEXELS_API_KEY not found in environment variables")
167
+ print("Pexels API key is missing. Please set the PEXELS_API_KEY environment variable.")
168
+ return None, None
169
+
170
+ # Call Pexels search endpoint
171
+ # e.g. GET https://api.pexels.com/v1/search?query={prompt_text}&per_page=1
172
+
173
+ search_url = "https://api.pexels.com/v1/search"
174
+ headers_pexels = {
175
+ "Authorization": pexels_api_key
176
+ }
177
+ params = {
178
+ "query": prompt_text,
179
+ "per_page": 1
180
+ }
181
+ response = requests.get(search_url, headers=headers_pexels, params=params)
182
+ if response.status_code != 200:
183
+ logger.error(f"Pexels API error: {response.status_code}, {response.text}")
184
+ print(f"Error from Pexels API: {response.status_code}")
185
+ return None, None
186
+
187
+ data = response.json()
188
+ photos = data.get("photos", [])
189
+ if not photos:
190
+ logger.error("No photos found for the given prompt on Pexels")
191
+ print("No photos found on Pexels for this prompt.")
192
+ return None, None
193
+
194
+ # Take the first photo
195
+ photo = photos[0]
196
+ # We can pick "src" => "original" or "large2x", etc.
197
+ image_url = photo["src"].get("large2x") or photo["src"].get("original")
198
+ if not image_url:
199
+ logger.error("No suitable image URL found in Pexels photo object")
200
+ return None, None
201
+
202
+ # Download the image
203
+ img_resp = requests.get(image_url)
204
+ if img_resp.status_code != 200:
205
+ logger.error(f"Failed to download Pexels image from {image_url}")
206
+ return None, None
207
+
208
+ image_bytes = img_resp.content
209
+
210
+ else:
211
+ # Default to Hugging Face model
212
  enhanced_prompt = f"{prompt_text} in {style} style, high quality, detailed illustration"
213
  model_id = "black-forest-labs/FLUX.1-dev"
214
  api_url = f"https://api-inference.huggingface.co/models/{model_id}"
 
220
  return None, None
221
  image_bytes = response.content
222
 
223
+ # For HF, Pollinations, or Pexels that return image bytes
224
  if model != "gemini":
225
  image = Image.open(io.BytesIO(image_bytes))
226
  buffered = io.BytesIO()
227
  image.save(buffered, format="JPEG")
228
  img_str = base64.b64encode(buffered.getvalue()).decode()
229
  return image, img_str
230
+
231
  except Exception as e:
232
  print(f"Error generating image: {e}")
233
  logger.error(f"Image generation error: {str(e)}")
234
+
235
  # Return a placeholder image in case of failure
236
  return Image.new('RGB', (1024, 1024), color=(200,200,200)), None
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  # edit image function
239
  def edit_section_image(image_url: str, gemini_prompt: str):
240
  """