Deadmon commited on
Commit
3b40681
·
verified ·
1 Parent(s): ad8ed5b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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).
13
+ model (str): Model to use (default: 'kontext').
14
+ nologo (bool): Whether to exclude logo (default: True).
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 = {
23
+ "model": model,
24
+ "image": input_image_url,
25
+ "width": width,
26
+ "height": height,
27
+ "seed": seed,
28
+ "nologo": str(nologo).lower(),
29
+ "enhance": str(enhance).lower()
30
+ }
31
+ api_url = f"{base_url}/{prompt.replace(' ', '%20')}"
32
+
33
+ try:
34
+ # Make the API request
35
+ response = requests.get(api_url, params=query_params, stream=True)
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")