ParthSadaria commited on
Commit
88cbc7b
·
verified ·
1 Parent(s): 37f6788

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +69 -31
main.py CHANGED
@@ -201,7 +201,8 @@ async def get_completion(payload: Payload,request: Request):
201
  raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
202
 
203
  return StreamingResponse(stream_generator(payload_dict), media_type="application/json")
204
- @app.get("/images/generations") #pollinations.ai :) thanks to them check their website
 
205
  async def generate_image(
206
  prompt: str,
207
  model: str = "flux", # Default model
@@ -215,44 +216,81 @@ async def generate_image(
215
  """
216
  Generate an image using the Image Generation API.
217
  """
218
- # Ensure the IMAGE_ENDPOINT is configured
219
  if not image_endpoint:
220
  raise HTTPException(status_code=500, detail="Image endpoint not configured in environment variables.")
221
 
222
- # Construct the URL with the prompt
223
- url = f"{image_endpoint}/{prompt}"
 
 
 
 
 
224
 
225
- # Prepare query parameters
226
- params = {
227
- "model": model,
228
- "seed": seed,
229
- "width": width,
230
- "height": height,
231
- "nologo": nologo,
232
- "private": private,
233
- "enhance": enhance,
234
- }
235
- # Remove keys with None values to avoid invalid params
236
- params = {k: v for k, v in params.items() if v is not None}
 
 
 
 
 
 
 
 
 
237
 
238
  try:
239
- # Send GET request to the image generation endpoint
240
- async with httpx.AsyncClient() as client:
241
- response = await client.get(url, params=params)
242
-
243
- # If the response is not successful, raise an error
244
- if response.status_code != 200:
245
- raise HTTPException(
246
- status_code=response.status_code,
247
- detail=f"Error generating image: {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  )
249
-
250
- # Return the image as a file response
251
- return StreamingResponse(response.iter_content(), media_type="image/jpeg")
252
-
253
  except httpx.RequestError as e:
254
- # Handle request errors
255
- raise HTTPException(status_code=500, detail=f"Error contacting the image endpoint: {str(e)}")
 
256
  @app.get("/playground", response_class=HTMLResponse)
257
  async def playground():
258
  # Open and read the content of playground.html (in the same folder as the app)
 
201
  raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
202
 
203
  return StreamingResponse(stream_generator(payload_dict), media_type="application/json")
204
+ # Remove the duplicated endpoint and combine the functionality
205
+ @app.get("/images/generations") #pollinations.ai thanks to them :)
206
  async def generate_image(
207
  prompt: str,
208
  model: str = "flux", # Default model
 
216
  """
217
  Generate an image using the Image Generation API.
218
  """
219
+ # Validate the image endpoint
220
  if not image_endpoint:
221
  raise HTTPException(status_code=500, detail="Image endpoint not configured in environment variables.")
222
 
223
+ # Validate prompt
224
+ if not prompt or not prompt.strip():
225
+ raise HTTPException(status_code=400, detail="Prompt cannot be empty")
226
+
227
+ # Sanitize and encode the prompt
228
+ sanitized_prompt = prompt.strip()
229
+ encoded_prompt = httpx.QueryParams({'prompt': sanitized_prompt}).get('prompt')
230
 
231
+ # Construct the URL with the encoded prompt
232
+ base_url = image_endpoint.rstrip('/') # Remove trailing slash if present
233
+ url = f"{base_url}/{encoded_prompt}"
234
+
235
+ # Prepare query parameters with validation
236
+ params = {}
237
+
238
+ if model and isinstance(model, str):
239
+ params['model'] = model
240
+ if seed is not None and isinstance(seed, int):
241
+ params['seed'] = seed
242
+ if width is not None and isinstance(width, int) and 64 <= width <= 2048:
243
+ params['width'] = width
244
+ if height is not None and isinstance(height, int) and 64 <= height <= 2048:
245
+ params['height'] = height
246
+ if nologo is not None:
247
+ params['nologo'] = str(nologo).lower()
248
+ if private is not None:
249
+ params['private'] = str(private).lower()
250
+ if enhance is not None:
251
+ params['enhance'] = str(enhance).lower()
252
 
253
  try:
254
+ timeout = httpx.Timeout(30.0) # Set a reasonable timeout
255
+ async with httpx.AsyncClient(timeout=timeout) as client:
256
+ response = await client.get(url, params=params, follow_redirects=True)
257
+
258
+ # Check for various error conditions
259
+ if response.status_code == 404:
260
+ raise HTTPException(status_code=404, detail="Image generation service not found")
261
+ elif response.status_code == 400:
262
+ raise HTTPException(status_code=400, detail="Invalid parameters provided to image service")
263
+ elif response.status_code == 429:
264
+ raise HTTPException(status_code=429, detail="Too many requests to image service")
265
+ elif response.status_code != 200:
266
+ raise HTTPException(
267
+ status_code=response.status_code,
268
+ detail=f"Image generation failed with status code {response.status_code}"
269
+ )
270
+
271
+ # Verify content type
272
+ content_type = response.headers.get('content-type', '')
273
+ if not content_type.startswith('image/'):
274
+ raise HTTPException(
275
+ status_code=500,
276
+ detail=f"Unexpected content type received: {content_type}"
277
+ )
278
+
279
+ return StreamingResponse(
280
+ response.iter_bytes(),
281
+ media_type=content_type,
282
+ headers={
283
+ 'Cache-Control': 'no-cache',
284
+ 'Pragma': 'no-cache'
285
+ }
286
  )
287
+
288
+ except httpx.TimeoutException:
289
+ raise HTTPException(status_code=504, detail="Image generation request timed out")
 
290
  except httpx.RequestError as e:
291
+ raise HTTPException(status_code=500, detail=f"Failed to contact image service: {str(e)}")
292
+ except Exception as e:
293
+ raise HTTPException(status_code=500, detail=f"Unexpected error during image generation: {str(e)}")
294
  @app.get("/playground", response_class=HTMLResponse)
295
  async def playground():
296
  # Open and read the content of playground.html (in the same folder as the app)