Deadmon commited on
Commit
29eca87
·
verified ·
1 Parent(s): 74eccbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -28
app.py CHANGED
@@ -1,12 +1,16 @@
 
1
  import requests
 
 
 
2
 
3
- def generate_kontext_image(input_image_url, prompt="transform this image", width=1024, height=1024, seed=-1, model="kontext", nologo=True, enhance=False):
4
  """
5
  Generate a transformed image using the Kontext model from Pollinations API.
6
 
7
  Args:
8
- input_image_url (str): URL of the input image to transform.
9
- prompt (str): Prompt for the transformation (default: 'transform this image').
10
  width (int): Width of the output image (default: 1024).
11
  height (int): Height of the output image (default: 1024).
12
  seed (int): Random seed for generation (default: -1 for random).
@@ -15,8 +19,17 @@ def generate_kontext_image(input_image_url, prompt="transform this image", width
15
  enhance (bool): Whether to enhance the image (default: False).
16
 
17
  Returns:
18
- bytes: Raw image data if successful, None otherwise.
19
  """
 
 
 
 
 
 
 
 
 
20
  # Construct the API URL with query parameters
21
  base_url = "https://image.pollinations.ai/prompt"
22
  query_params = {
@@ -36,33 +49,78 @@ def generate_kontext_image(input_image_url, prompt="transform this image", width
36
 
37
  # Check if the request was successful
38
  if response.status_code == 200:
39
- return response.content # Return raw image data
 
 
 
 
 
40
  else:
41
- print(f"Error: API request failed with status code {response.status_code}")
42
- return None
43
  except requests.RequestException as e:
44
- print(f"Error: Failed to connect to the API - {e}")
45
- return None
 
 
 
46
 
47
- # Example usage
48
- if __name__ == "__main__":
49
- # Replace with a valid input image URL
50
- input_image = "https://example.com/input-image.jpg"
51
- output_image_data = generate_kontext_image(
52
- input_image_url=input_image,
53
- prompt="transform this image into a surreal painting",
54
- width=800,
55
- height=600,
56
- seed=42,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  model="kontext",
58
- nologo=True,
59
- enhance=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
61
 
62
- # Save the output image if successful
63
- if output_image_data:
64
- with open("output_image.jpg", "wb") as f:
65
- f.write(output_image_data)
66
- print("Image saved as output_image.jpg")
67
- else:
68
- print("Failed to generate image")
 
1
+ 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).
 
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 = {
 
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():
106
+ input_image = gr.Image(type="pil", label="Upload Image")
107
+ prompt = gr.Textbox(label="Prompt", placeholder="e.g., transform this image into a surreal painting")
108
+ width = gr.Slider(minimum=256, maximum=2048, value=1024, step=1, label="Width")
109
+ height = gr.Slider(minimum=256, maximum=2048, value=1024, step=1, label="Height")
110
+ seed = gr.Number(value=-1, label="Seed (-1 for random)", precision=0)
111
+ nologo = gr.Checkbox(value=True, label="No Logo")
112
+ enhance = gr.Checkbox(value=False, label="Enhance Image")
113
+ submit_button = gr.Button("Generate Image")
114
+
115
+ with gr.Column():
116
+ output = gr.Image(label="Generated Image")
117
+
118
+ submit_button.click(
119
+ fn=app_interface,
120
+ inputs=[input_image, prompt, width, height, seed, nologo, enhance],
121
+ outputs=output
122
  )
123
 
124
+ # Launch the app
125
+ if __name__ == "__main__":
126
+ demo.launch()