Sebastiankay commited on
Commit
1676cb9
1 Parent(s): 0562d19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -220
app.py CHANGED
@@ -1,220 +1,196 @@
1
- import os, sys, json, re, base64, random, requests, shutil
2
- import gradio as gr
3
- from datetime import datetime
4
- import urllib.parse
5
- from groq import Groq
6
- from exif import Image
7
- from PIL import Image as PILImage
8
- import colorsys
9
-
10
- MAX_SEED = 9999
11
- MAX_IMAGE_SIZE = 2048
12
-
13
- GROQ_APIKEY_PROMPTENHANCE = os.environ["GROQ_APIKEY_PROMPTENHANCE"]
14
-
15
-
16
- # delete cache folder if exist and create new
17
- CACHE_DIR = os.path.join(os.path.dirname(__file__), "cache")
18
- IMAGE_DIR = os.path.join(CACHE_DIR, "images")
19
- if os.path.exists(CACHE_DIR):
20
- shutil.rmtree(CACHE_DIR)
21
- os.makedirs(CACHE_DIR)
22
- os.makedirs(IMAGE_DIR)
23
-
24
- RES = os.path.join(os.path.dirname(__file__), "_res")
25
-
26
- custom_css = RES + "/_custom.css"
27
- custom_js = RES + "/_custom.js"
28
-
29
-
30
- title = "Pollinations Image Generator"
31
- description = "Pollinations API + Randomizer"
32
-
33
-
34
- theme = gr.themes.Soft(
35
- primary_hue="amber",
36
- radius_size="sm",
37
- )
38
-
39
-
40
- def read_exif(image_path):
41
- with open(image_path, "rb") as src:
42
- img = Image(src)
43
- img_comment = json.loads(img.user_comment)
44
-
45
- # checking if the key exists before removing
46
- if "concept" in img_comment:
47
- img_comment.pop("concept")
48
-
49
- return img_comment
50
-
51
-
52
- def read_image_exfi_data(image_path):
53
- print("Imagepath:", image_path)
54
- img_exif_make, img_exif_comment = read_exif(image_path)
55
- return None, image_path, img_exif_comment
56
-
57
-
58
- def groq_enhance_process(Prompt):
59
- client = Groq(api_key=GROQ_APIKEY_PROMPTENHANCE)
60
-
61
- SYSTEMPROMPT = os.path.join(RES, "groq_systemmessage_prompt_enhance.json")
62
- with open(SYSTEMPROMPT, "r") as f:
63
- SYSTEMPROMPT = json.load(f)
64
-
65
- completion = client.chat.completions.create(
66
- model="llama-3.1-70b-versatile",
67
- messages=[SYSTEMPROMPT, {"role": "user", "content": Prompt}],
68
- temperature=0.8,
69
- max_tokens=8000,
70
- top_p=0.9,
71
- stream=False,
72
- stop=None,
73
- )
74
-
75
- if completion.choices[0].message.content != "":
76
- enhanced_prompt = completion.choices[0].message.content
77
-
78
- return enhanced_prompt
79
-
80
-
81
- def enhance_process(Prompt):
82
- encode_prompt = urllib.parse.quote(Prompt)
83
- request_url = f"https://image.pollinations.ai/prompt/{encode_prompt}?model=turbo&width=512&height=512&nologo=true&enhance=true&nofeed=true"
84
- print(request_url)
85
- response = requests.get(request_url)
86
- if response.status_code == 200:
87
- filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".png"
88
- file_path = os.path.join(CACHE_DIR, filename)
89
- with open(file_path, "wb") as f:
90
- f.write(response.content)
91
- img_exif_comment = read_exif(file_path)
92
- prompt_value = img_exif_comment.get("prompt", "")
93
- prompt_value = prompt_value.replace(Prompt, "").strip()
94
- print(prompt_value)
95
- return prompt_value
96
-
97
-
98
- def image_get_colors(image_path):
99
- img = PILImage.open(image_path)
100
- img = img.convert("RGB")
101
- pixels = list(img.getdata())
102
-
103
- # Erzeuge eine Liste mit den Häufigkeiten der Farben
104
- colors = []
105
- for pixel in pixels:
106
- r, g, b = pixel
107
- h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
108
- if v > 0.5: # Filteriere hellere Farben aus
109
- continue
110
- if v > 0.99: # Filteriere Weiß aus
111
- continue
112
- colors.append((h, s, v))
113
-
114
- # Ermittle die dominante Farbe
115
- dominant_color = max(colors, key=lambda x: x[2])
116
- dominant_color_rgb = colorsys.hsv_to_rgb(dominant_color[0], dominant_color[1], dominant_color[2])
117
- dominant_color_rgb = [int(c * 255) for c in dominant_color_rgb]
118
- print(dominant_color_rgb)
119
-
120
- return dominant_color_rgb
121
-
122
-
123
- def process(Prompt, image_width, image_height, image_seed, randomize_seed):
124
-
125
- used_seed = random.randint(0, MAX_SEED) if image_seed == 0 or randomize_seed else image_seed
126
-
127
- timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
128
- filename = timestamp + ".png"
129
- # file_path = os.path.join(filename_dir, filename)
130
- file_path = os.path.join(IMAGE_DIR, filename)
131
-
132
- encode_prompt = urllib.parse.quote(Prompt)
133
- request_url = f"https://image.pollinations.ai/prompt/{encode_prompt}?model=flux&width={image_width}&height={image_height}&nologo=true&enhance=false&nofeed=true&seed={used_seed}"
134
- print(request_url)
135
- response = requests.get(request_url)
136
- if response.status_code == 200:
137
- with open(file_path, "wb") as f:
138
- f.write(response.content)
139
-
140
- img_exif_comment = read_exif(file_path)
141
- img_dominant_color = image_get_colors(file_path)
142
-
143
- return ({"value": file_path, "__type__": "update"}, {"value": request_url, "visible": True, "__type__": "update"}, used_seed, img_exif_comment, {"visible": True, "__type__": "update"}, {"value": Prompt, "visible": True, "__type__": "update"}, {"value": file_path, "visible": True, "__type__": "update"})
144
-
145
-
146
- with gr.Blocks(theme=theme, css=custom_css) as demo:
147
- with gr.Tab("Image Generator"):
148
- with gr.Row():
149
- with gr.Column(scale=1):
150
- with gr.Row():
151
- text_prompt = gr.Textbox(label="Prompt", show_label=False, lines=12, max_lines=18, placeholder="Enter your Image prompt here...", elem_classes="prompt-input", autofocus=True)
152
- with gr.Row():
153
- with gr.Column(scale=2, elem_classes="image_size_selctor_wrapper"):
154
- image_width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, value=1024, step=128, elem_classes="image-width-selector")
155
- image_height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, value=683, step=128, elem_classes="image-height-selector")
156
- # with gr.Row():
157
- # image_ratio_buttons = gr.Radio(["16:9", "4:3", "3:2", "1:1"], value="3:2", label="Bild Größe", interactive=True, elem_classes="image-ratio-buttons", container=True, show_label=False)
158
- # switch_width_height = gr.Button("🔁", size="sm", elem_id="switchRatioBtn", elem_classes="switch-ratio-btn", variant="primary")
159
- with gr.Row():
160
- with gr.Column():
161
- image_seed = gr.Slider(label="Seed", minimum=0, step=1, value=42, maximum=MAX_SEED)
162
- randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
163
- with gr.Row():
164
- run_button = gr.Button("Erstellen", variant="primary", elem_classes="run_button")
165
- enhance_button = gr.Button("Prompt verbessern", variant="secondary", elem_classes="enhance-button")
166
-
167
- with gr.Column(scale=3):
168
- with gr.Row():
169
- with gr.Column(scale=3):
170
- output_image = gr.Image(show_label=False, height=720)
171
- with gr.Column(scale=1):
172
- image_informations = gr.Markdown("""## Bildinformationen""", visible=False)
173
- # textbox_your_prompt = gr.Textbox(label="Dein Prmopt", lines=2, max_lines=4, interactive=False, show_copy_button=True)
174
- textbox_prompt = gr.Textbox("Bild Prompt", lines=4, max_lines=8, interactive=False, show_copy_button=True, visible=False)
175
- image_download_button = gr.DownloadButton("Bild herunterladen", value=None, elem_classes="download-button", variant="Primary", visible=False)
176
-
177
- # output_image = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery", columns=[1], rows=[1], object_fit="contain", height="768")
178
- output_url = gr.Textbox(label="Output URL", show_label=True, interactive=False, show_copy_button=True, visible=False)
179
- outpu_image_comment = gr.Json(visible=False)
180
- # output_image = gr.Image(label="Generated image", show_label=True, height=720, show_share_button=False)
181
- # gallery = gr.Gallery(label="Generated Gallery", show_label=True, elem_id="gallery", columns=[3], rows=[1], object_fit="contain", height="auto", type="filepath")
182
- # testimage = gr.Image(value="images/2024-08-22/2024-08-22_00-45-31.png", type="pil")
183
- # gr.HTML("<div>")
184
- # for image_path in os.listdir(images_dir):
185
- # gr.HTML(f'<img src="images/2024-08-21/{image_path}" />')
186
- # gr.HTML("</div>")
187
-
188
- def switch_image_size_values(image_width, image_height):
189
- return image_height, image_width
190
-
191
- switch_width_height.click(fn=switch_image_size_values, inputs=[image_width, image_height], outputs=[image_width, image_height])
192
-
193
- run_button.click(fn=process, inputs=[text_prompt, image_width, image_height, image_seed, randomize_seed], outputs=[output_image, output_url, image_seed, outpu_image_comment, image_informations, textbox_prompt, image_download_button])
194
- enhance_button.click(fn=groq_enhance_process, inputs=[text_prompt], outputs=[text_prompt])
195
-
196
- demo.launch()
197
-
198
- """
199
- ## Endpoint
200
- GET https://image.pollinations.ai/prompt/{prompt}
201
-
202
- ## Description
203
- This endpoint generates an image based on the provided prompt and optional parameters. It returns a raw image file.
204
-
205
- ## Parameters
206
- - prompt (required): The text description of the image you want to generate. Should be URL-encoded.
207
- - model (optional): The model to use for generation. Options: 'flux' or 'turbo'. Default: 'turbo'
208
- - seed (optional): Seed for reproducible results. Default: random
209
- - width (optional): Width of the generated image. Default: 1024
210
- - height (optional): Height of the generated image. Default: 1024
211
- - nologo (optional): Set to 'true' to turn off the rendering of the logo
212
- - nofeed (optional): Set to 'true' to prevent the image from appearing in the public feed
213
- - enhance (optional): Set to 'true' or 'false' to turn on or off prompt enhancing (passes prompts through an LLM to add detail)
214
-
215
- ## Example Usage
216
- https://image.pollinations.ai/prompt/A%20beautiful%20sunset%20over%20the%20ocean?model=flux&width=1280&height=720&seed=42&nologo=true&enhance=true
217
-
218
- ## Response
219
- The API returns a raw image file (typically JPEG or PNG) as the response body.
220
- """
 
1
+ import os, sys, json, re, base64, random, requests, shutil
2
+ import gradio as gr
3
+ from datetime import datetime
4
+ import urllib.parse
5
+ from groq import Groq
6
+ from exif import Image
7
+ from PIL import Image as PILImage
8
+ import colorsys
9
+
10
+ MAX_SEED = 9999
11
+ MAX_IMAGE_SIZE = 2048
12
+
13
+ GROQ_APIKEY_PROMPTENHANCE = os.environ["GROQ_APIKEY_PROMPTENHANCE"]
14
+
15
+
16
+ # delete cache folder if exist and create new
17
+ CACHE_DIR = os.path.join(os.path.dirname(__file__), "cache")
18
+ IMAGE_DIR = os.path.join(CACHE_DIR, "images")
19
+ if os.path.exists(CACHE_DIR):
20
+ shutil.rmtree(CACHE_DIR)
21
+ os.makedirs(CACHE_DIR)
22
+ os.makedirs(IMAGE_DIR)
23
+
24
+ RES = os.path.join(os.path.dirname(__file__), "_res")
25
+
26
+ custom_css = RES + "/_custom.css"
27
+ custom_js = RES + "/_custom.js"
28
+
29
+
30
+ title = "Pollinations Image Generator"
31
+ description = "Pollinations API + Randomizer"
32
+
33
+
34
+ theme = gr.themes.Soft(
35
+ primary_hue="amber",
36
+ radius_size="sm",
37
+ )
38
+
39
+
40
+ def read_exif(image_path):
41
+ with open(image_path, "rb") as src:
42
+ img = Image(src)
43
+ img_comment = json.loads(img.user_comment)
44
+
45
+ # checking if the key exists before removing
46
+ if "concept" in img_comment:
47
+ img_comment.pop("concept")
48
+
49
+ return img_comment
50
+
51
+
52
+ def read_image_exfi_data(image_path):
53
+ print("Imagepath:", image_path)
54
+ img_exif_make, img_exif_comment = read_exif(image_path)
55
+ return None, image_path, img_exif_comment
56
+
57
+
58
+ def groq_enhance_process(Prompt):
59
+ client = Groq(api_key=GROQ_APIKEY_PROMPTENHANCE)
60
+
61
+ SYSTEMPROMPT = os.path.join(RES, "groq_systemmessage_prompt_enhance.json")
62
+ with open(SYSTEMPROMPT, "r") as f:
63
+ SYSTEMPROMPT = json.load(f)
64
+
65
+ completion = client.chat.completions.create(
66
+ model="llama-3.1-70b-versatile",
67
+ messages=[SYSTEMPROMPT, {"role": "user", "content": Prompt}],
68
+ temperature=0.8,
69
+ max_tokens=8000,
70
+ top_p=0.9,
71
+ stream=False,
72
+ stop=None,
73
+ )
74
+
75
+ if completion.choices[0].message.content != "":
76
+ enhanced_prompt = completion.choices[0].message.content
77
+
78
+ return enhanced_prompt
79
+
80
+
81
+ def enhance_process(Prompt):
82
+ encode_prompt = urllib.parse.quote(Prompt)
83
+ request_url = f"https://image.pollinations.ai/prompt/{encode_prompt}?model=turbo&width=512&height=512&nologo=true&enhance=true&nofeed=true"
84
+ print(request_url)
85
+ response = requests.get(request_url)
86
+ if response.status_code == 200:
87
+ filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".png"
88
+ file_path = os.path.join(CACHE_DIR, filename)
89
+ with open(file_path, "wb") as f:
90
+ f.write(response.content)
91
+ img_exif_comment = read_exif(file_path)
92
+ prompt_value = img_exif_comment.get("prompt", "")
93
+ prompt_value = prompt_value.replace(Prompt, "").strip()
94
+ print(prompt_value)
95
+ return prompt_value
96
+
97
+
98
+ def image_get_colors(image_path):
99
+ img = PILImage.open(image_path)
100
+ img = img.convert("RGB")
101
+ pixels = list(img.getdata())
102
+
103
+ # Erzeuge eine Liste mit den Häufigkeiten der Farben
104
+ colors = []
105
+ for pixel in pixels:
106
+ r, g, b = pixel
107
+ h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
108
+ if v > 0.5: # Filteriere hellere Farben aus
109
+ continue
110
+ if v > 0.99: # Filteriere Weiß aus
111
+ continue
112
+ colors.append((h, s, v))
113
+
114
+ # Ermittle die dominante Farbe
115
+ dominant_color = max(colors, key=lambda x: x[2])
116
+ dominant_color_rgb = colorsys.hsv_to_rgb(dominant_color[0], dominant_color[1], dominant_color[2])
117
+ dominant_color_rgb = [int(c * 255) for c in dominant_color_rgb]
118
+ print(dominant_color_rgb)
119
+
120
+ return dominant_color_rgb
121
+
122
+
123
+ def process(Prompt, image_width, image_height, image_seed, randomize_seed):
124
+
125
+ used_seed = random.randint(0, MAX_SEED) if image_seed == 0 or randomize_seed else image_seed
126
+
127
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
128
+ filename = timestamp + ".png"
129
+ # file_path = os.path.join(filename_dir, filename)
130
+ file_path = os.path.join(IMAGE_DIR, filename)
131
+
132
+ encode_prompt = urllib.parse.quote(Prompt)
133
+ request_url = f"https://image.pollinations.ai/prompt/{encode_prompt}?model=flux&width={image_width}&height={image_height}&nologo=true&enhance=false&nofeed=true&seed={used_seed}"
134
+ print(request_url)
135
+ response = requests.get(request_url)
136
+ if response.status_code == 200:
137
+ with open(file_path, "wb") as f:
138
+ f.write(response.content)
139
+
140
+ img_exif_comment = read_exif(file_path)
141
+ img_dominant_color = image_get_colors(file_path)
142
+
143
+ return ({"value": file_path, "__type__": "update"}, {"value": request_url, "visible": True, "__type__": "update"}, used_seed, img_exif_comment, {"visible": True, "__type__": "update"}, {"value": Prompt, "visible": True, "__type__": "update"}, {"value": file_path, "visible": True, "__type__": "update"})
144
+
145
+
146
+ with gr.Blocks(theme=theme, css=custom_css) as demo:
147
+ with gr.Tab("Image Generator"):
148
+ with gr.Row():
149
+ with gr.Column(scale=1):
150
+ with gr.Row():
151
+ text_prompt = gr.Textbox(label="Prompt", show_label=False, lines=12, max_lines=18, placeholder="Enter your Image prompt here...", elem_classes="prompt-input", autofocus=True)
152
+ with gr.Row():
153
+ with gr.Column(scale=2, elem_classes="image_size_selctor_wrapper"):
154
+ image_width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, value=1024, step=128, elem_classes="image-width-selector")
155
+ image_height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, value=683, step=128, elem_classes="image-height-selector")
156
+ # with gr.Row():
157
+ # image_ratio_buttons = gr.Radio(["16:9", "4:3", "3:2", "1:1"], value="3:2", label="Bild Größe", interactive=True, elem_classes="image-ratio-buttons", container=True, show_label=False)
158
+ # switch_width_height = gr.Button("🔁", size="sm", elem_id="switchRatioBtn", elem_classes="switch-ratio-btn", variant="primary")
159
+ with gr.Row():
160
+ with gr.Column():
161
+ image_seed = gr.Slider(label="Seed", minimum=0, step=1, value=42, maximum=MAX_SEED)
162
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
163
+ with gr.Row():
164
+ run_button = gr.Button("Erstellen", variant="primary", elem_classes="run_button")
165
+ enhance_button = gr.Button("Prompt verbessern", variant="secondary", elem_classes="enhance-button")
166
+
167
+ with gr.Column(scale=3):
168
+ with gr.Row():
169
+ with gr.Column(scale=3):
170
+ output_image = gr.Image(show_label=False, height=720)
171
+ with gr.Column(scale=1):
172
+ image_informations = gr.Markdown("""## Bildinformationen""", visible=False)
173
+ # textbox_your_prompt = gr.Textbox(label="Dein Prmopt", lines=2, max_lines=4, interactive=False, show_copy_button=True)
174
+ textbox_prompt = gr.Textbox("Bild Prompt", lines=4, max_lines=8, interactive=False, show_copy_button=True, visible=False)
175
+ image_download_button = gr.DownloadButton("Bild herunterladen", value=None, elem_classes="download-button", variant="Primary", visible=False)
176
+
177
+ # output_image = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery", columns=[1], rows=[1], object_fit="contain", height="768")
178
+ output_url = gr.Textbox(label="Output URL", show_label=True, interactive=False, show_copy_button=True, visible=False)
179
+ outpu_image_comment = gr.Json(visible=False)
180
+ # output_image = gr.Image(label="Generated image", show_label=True, height=720, show_share_button=False)
181
+ # gallery = gr.Gallery(label="Generated Gallery", show_label=True, elem_id="gallery", columns=[3], rows=[1], object_fit="contain", height="auto", type="filepath")
182
+ # testimage = gr.Image(value="images/2024-08-22/2024-08-22_00-45-31.png", type="pil")
183
+ # gr.HTML("<div>")
184
+ # for image_path in os.listdir(images_dir):
185
+ # gr.HTML(f'<img src="images/2024-08-21/{image_path}" />')
186
+ # gr.HTML("</div>")
187
+
188
+ def switch_image_size_values(image_width, image_height):
189
+ return image_height, image_width
190
+
191
+ # switch_width_height.click(fn=switch_image_size_values, inputs=[image_width, image_height], outputs=[image_width, image_height])
192
+
193
+ run_button.click(fn=process, inputs=[text_prompt, image_width, image_height, image_seed, randomize_seed], outputs=[output_image, output_url, image_seed, outpu_image_comment, image_informations, textbox_prompt, image_download_button])
194
+ enhance_button.click(fn=groq_enhance_process, inputs=[text_prompt], outputs=[text_prompt])
195
+
196
+ demo.launch()