Deadmon commited on
Commit
729985a
·
verified ·
1 Parent(s): e0c18b5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -50
app.py CHANGED
@@ -2,36 +2,53 @@ import gradio as gr
2
  import requests
3
  from PIL import Image
4
  import io
5
- import os
6
 
7
- def generate_kontext_image(input_image, prompt, width=1024, height=1024, seed=-1, model="kontext", nologo=True, enhance=False):
8
  """
9
- Generate a transformed image using the Kontext model from Pollinations API.
10
 
11
  Args:
12
  input_image (PIL.Image): Input image to transform.
13
  prompt (str): Prompt for the transformation.
14
- width (int): Width of the output image (default: 1024).
15
- height (int): Height of the output image (default: 1024).
16
- seed (int): Random seed for generation (default: -1 for random).
17
- model (str): Model to use (default: 'kontext').
18
- nologo (bool): Whether to exclude logo (default: True).
19
- enhance (bool): Whether to enhance the image (default: False).
20
 
21
  Returns:
22
  PIL.Image or str: Generated image or error message.
23
  """
24
- # Save the uploaded image temporarily to get a public URL
25
- temp_image_path = "temp_input_image.jpg"
26
- input_image.save(temp_image_path)
27
-
28
- # Note: In a production environment, you should upload the image to a public URL
29
- # For this example, we'll assume the image is accessible locally or via a public URL
30
- # Replace with actual public URL if deploying (e.g., upload to a cloud service)
31
- input_image_url = "https://example.com/input-image.jpg" # Placeholder; replace with actual URL
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- # Construct the API URL with query parameters
34
  base_url = "https://image.pollinations.ai/prompt"
 
 
 
 
 
35
  query_params = {
36
  "model": model,
37
  "image": input_image_url,
@@ -41,65 +58,51 @@ def generate_kontext_image(input_image, prompt, width=1024, height=1024, seed=-1
41
  "nologo": str(nologo).lower(),
42
  "enhance": str(enhance).lower()
43
  }
44
- api_url = f"{base_url}/{prompt.replace(' ', '%20')}"
45
 
46
  try:
47
  # Make the API request
48
  response = requests.get(api_url, params=query_params, stream=True)
 
 
 
 
 
49
 
50
- # Check if the request was successful
51
- if response.status_code == 200:
52
- # Convert response content to PIL Image
53
- output_image = Image.open(io.BytesIO(response.content))
54
- # Clean up temporary file
55
- if os.path.exists(temp_image_path):
56
- os.remove(temp_image_path)
57
- return output_image
58
- else:
59
- return f"Error: API request failed with status code {response.status_code}"
60
  except requests.RequestException as e:
61
- return f"Error: Failed to connect to the API - {e}"
62
- finally:
63
- # Ensure temporary file is removed even if an error occurs
64
- if os.path.exists(temp_image_path):
65
- os.remove(temp_image_path)
 
 
 
66
 
67
  def app_interface(input_image, prompt, width, height, seed, nologo, enhance):
68
  """
69
  Gradio interface function to handle user inputs and display results.
70
-
71
- Args:
72
- input_image (PIL.Image): Uploaded image.
73
- prompt (str): Transformation prompt.
74
- width (int): Output image width.
75
- height (int): Output image height.
76
- seed (int): Random seed.
77
- nologo (bool): Exclude logo.
78
- enhance (bool): Enhance image.
79
-
80
- Returns:
81
- PIL.Image or str: Generated image or error message.
82
  """
83
  if input_image is None:
84
  return "Please upload an image."
85
  if not prompt:
86
  return "Please provide a prompt."
87
 
 
88
  return generate_kontext_image(
89
  input_image=input_image,
90
  prompt=prompt,
91
  width=width,
92
  height=height,
93
  seed=seed,
94
- model="kontext",
95
  nologo=nologo,
96
  enhance=enhance
97
  )
98
 
99
  # Define the Gradio interface
100
- with gr.Blocks(title="Kontext Image Transformation") as demo:
101
- gr.Markdown("# Kontext Image Transformation App")
102
- gr.Markdown("Upload an image, provide a transformation prompt, and generate a new image using the Kontext model.")
103
 
104
  with gr.Row():
105
  with gr.Column():
 
2
  import requests
3
  from PIL import Image
4
  import io
 
5
 
6
+ def generate_kontext_image(input_image, prompt, width=1024, height=1024, seed=-1, model="dreamshaper", nologo=True, enhance=False):
7
  """
8
+ Generate a transformed image using the Pollinations API.
9
 
10
  Args:
11
  input_image (PIL.Image): Input image to transform.
12
  prompt (str): Prompt for the transformation.
13
+ width (int): Width of the output image.
14
+ height (int): Height of the output image.
15
+ seed (int): Random seed for generation (-1 for random).
16
+ model (str): Model to use (default: 'dreamshaper').
17
+ nologo (bool): Whether to exclude logo.
18
+ enhance (bool): Whether to enhance the image.
19
 
20
  Returns:
21
  PIL.Image or str: Generated image or error message.
22
  """
23
+ # Step 1: Convert the input PIL Image to bytes for uploading.
24
+ image_bytes = io.BytesIO()
25
+ input_image.save(image_bytes, format='JPEG')
26
+ image_bytes.seek(0)
27
+
28
+ input_image_url = ""
29
+ # Step 2: Upload the image bytes to get a public URL.
30
+ try:
31
+ upload_response = requests.post(
32
+ 'https://image.pollinations.ai/upload',
33
+ files={'file': ('input_image.jpg', image_bytes, 'image/jpeg')}
34
+ )
35
+ upload_response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
36
+ upload_result = upload_response.json()
37
+ input_image_url = upload_result.get('ipfs')
38
+
39
+ if not input_image_url:
40
+ return "Error: Could not retrieve a public URL after uploading the image."
41
+
42
+ except requests.RequestException as e:
43
+ return f"Error: Failed to upload the image to the server - {e}"
44
 
45
+ # Step 3: Use the public URL to make the final image generation request.
46
  base_url = "https://image.pollinations.ai/prompt"
47
+
48
+ # URL-encode the prompt to handle spaces and special characters
49
+ encoded_prompt = requests.utils.quote(prompt)
50
+ api_url = f"{base_url}/{encoded_prompt}"
51
+
52
  query_params = {
53
  "model": model,
54
  "image": input_image_url,
 
58
  "nologo": str(nologo).lower(),
59
  "enhance": str(enhance).lower()
60
  }
 
61
 
62
  try:
63
  # Make the API request
64
  response = requests.get(api_url, params=query_params, stream=True)
65
+ response.raise_for_status()
66
+
67
+ # Convert response content to a PIL Image and return it
68
+ output_image = Image.open(io.BytesIO(response.content))
69
+ return output_image
70
 
 
 
 
 
 
 
 
 
 
 
71
  except requests.RequestException as e:
72
+ error_details = str(e)
73
+ try:
74
+ # Try to get a more specific error message from the API response
75
+ error_details = e.response.json().get("message", e.response.text)
76
+ except:
77
+ pass # Keep the original exception text if parsing fails
78
+ return f"Error: API request failed. Details: {error_details}"
79
+
80
 
81
  def app_interface(input_image, prompt, width, height, seed, nologo, enhance):
82
  """
83
  Gradio interface function to handle user inputs and display results.
 
 
 
 
 
 
 
 
 
 
 
 
84
  """
85
  if input_image is None:
86
  return "Please upload an image."
87
  if not prompt:
88
  return "Please provide a prompt."
89
 
90
+ # Using 'dreamshaper' as it's a free and effective model for this task
91
  return generate_kontext_image(
92
  input_image=input_image,
93
  prompt=prompt,
94
  width=width,
95
  height=height,
96
  seed=seed,
97
+ model="dreamshaper",
98
  nologo=nologo,
99
  enhance=enhance
100
  )
101
 
102
  # Define the Gradio interface
103
+ with gr.Blocks(title="Image Transformation") as demo:
104
+ gr.Markdown("# Image Transformation App")
105
+ gr.Markdown("Upload an image, provide a transformation prompt, and generate a new image.")
106
 
107
  with gr.Row():
108
  with gr.Column():