Sebastiankay commited on
Commit
980e343
1 Parent(s): cc85e57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -42
app.py CHANGED
@@ -52,15 +52,18 @@ custom_head = f"""
52
  <link rel="manifest" href="file=_res/assets/favicons/site.webmanifest">
53
  """
54
 
55
-
56
- theme = gr.themes.Soft(
57
- primary_hue="orange",
58
- radius_size="sm",
59
- neutral_hue=gr.themes.Color(c100="#a6adc8", c200="#9399b2", c300="#7f849c", c400="#6c7086", c50="#cdd6f4", c500="#585b70", c600="#45475a", c700="#313244", c800="#1e1e2e", c900="#181825", c950="#11111b"),
60
- )
61
-
62
  title = "Bilder Builder"
63
 
 
 
 
 
 
64
 
65
  # MARK: READ EXIF
66
  def read_exif(image_path):
@@ -140,13 +143,12 @@ def image_get_dominant_color(image_path):
140
 
141
  return dominant_color_rgb
142
 
143
-
144
- # MARK: PROCESS IMAGE
145
- def process(Prompt, image_width, image_height, image_seed, randomize_seed):
146
  if Prompt == "":
147
- gr.Info("Kein Prompt angegeben, es wird ein zufälliger Prompt generiert.", duration=8)
148
  Prompt = groq_enhance_process("random prompt")
149
 
 
150
  used_seed = random.randint(0, MAX_SEED) if image_seed == 0 or randomize_seed else image_seed
151
  # used_model = "turbo" if int(image_width) > 1024 or int(image_height) > 1024 else "flux" # turbo, flux
152
 
@@ -155,19 +157,37 @@ def process(Prompt, image_width, image_height, image_seed, randomize_seed):
155
  filename = timestamp + "_" + filename_prompt[:100] + ".png"
156
  file_path = os.path.join(IMAGE_DIR, filename)
157
 
158
- encode_prompt = urllib.parse.quote(Prompt)
159
- 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}"
160
- print(request_url)
161
- response = requests.get(request_url)
162
- if response.status_code == 200:
163
- with open(file_path, "wb") as f:
164
- f.write(response.content)
165
-
166
- img_exif_comment = read_exif(file_path)
167
- img_dominant_color = image_get_dominant_color(file_path)
168
- img_width, img_height = image_get_size(file_path)
169
-
170
- return ({"value": Prompt, "__type__": "update"}, {"value": file_path, "__type__": "update"}, {"value": None, "visible": False, "__type__": "update"}, img_exif_comment, {"visible": True, "__type__": "update"}, {"value": Prompt, "visible": True, "__type__": "update"}, img_width, img_height, used_seed, {"value": file_path, "visible": True, "__type__": "update"}, img_dominant_color, used_seed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
 
173
  # MARK: Gradio BLOCKS UI
@@ -187,8 +207,10 @@ with gr.Blocks(theme=theme, head=custom_head, css=custom_css, js=custom_js, titl
187
  with gr.Row(elem_classes="image_size_selctor_wrapper"):
188
  with gr.Column(scale=1):
189
  with gr.Row():
190
- image_width = gr.Number(label="Breite", minimum=256, maximum=MAX_IMAGE_SIZE, value=1024, step=128, elem_id="image_width_selector", elem_classes="image-width-selector", scale=1)
191
- image_height = gr.Number(label="Höhe", minimum=256, maximum=MAX_IMAGE_SIZE, value=683, step=128, elem_id="image_height_selector", elem_classes="image-height-selector", scale=1)
 
 
192
  with gr.Row():
193
  image_ratio_buttons = gr.Radio(["16:9", "4:3", "3:2", "1:1"], value="3:2", label="Querformat", show_label=True, info="Die gängigsten Seitenverhältnissen.", interactive=True, elem_id="image_ratio_buttons", elem_classes="image-ratio-buttons", container=True, scale=2)
194
  switch_width_height = gr.Button("", size="sm", elem_id="switch_width_height", elem_classes="switch-ratio-btn", variant="primary", scale=1)
@@ -200,19 +222,17 @@ with gr.Blocks(theme=theme, head=custom_head, css=custom_css, js=custom_js, titl
200
  with gr.Row():
201
  with gr.Column(scale=1):
202
  with gr.Row():
203
- output_image = gr.Image(show_label=False, min_width=320, scale=3, elem_id="output_image", elem_classes="output-image", type="filepath")
 
204
  with gr.Column(scale=1, visible=False, elem_classes="image-info-wrapper") as image_info_wrapper:
205
- # with gr.Group(visible=False) as image_info_wrapper:
206
  with gr.Group():
207
  image_informations = gr.Markdown("""## Bildinformationen""", visible=True)
208
- # textbox_your_prompt = gr.Textbox(label="Dein Prmopt", lines=2, max_lines=4, interactive=False, show_copy_button=True)
209
  with gr.Row(elem_classes="img-size-wrapper"):
210
  image_info_tb_width = gr.Textbox(label="Breite", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-width")
211
  image_info_tb_height = gr.Textbox(label="Höhe", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-height")
212
  with gr.Row(elem_classes="img-seed-wrapper"):
213
  image_info_tb_seed = gr.Textbox(label="Seed", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-seed")
214
  image_info_tb_prompt = gr.Textbox("Bild Prompt", lines=4, max_lines=8, interactive=False, elem_classes="hide-progress", show_copy_button=True, visible=False)
215
- # image_info_tb_prompt = gr.Textbox("Bild Prompt", lines=4, max_lines=8, interactive=False, show_copy_button=True, visible=True)
216
  image_download_button = gr.DownloadButton("Bild herunterladen", value=None, elem_classes="download-button", variant="primary", visible=False)
217
 
218
  output_url = gr.Textbox(label="Output URL", show_label=True, interactive=False, visible=False)
@@ -225,7 +245,6 @@ with gr.Blocks(theme=theme, head=custom_head, css=custom_css, js=custom_js, titl
225
  def switch_image_ratio_buttons(ratio_value):
226
  ratio_value = ratio_value.split(":")
227
  ratio_value_new = f"{int(ratio_value[1])}:{int(ratio_value[0])}"
228
- print("ratio_value_new:", ratio_value_new)
229
 
230
  if int(ratio_value[1]) > int(ratio_value[0]):
231
  # Querformat
@@ -235,38 +254,45 @@ with gr.Blocks(theme=theme, head=custom_head, css=custom_css, js=custom_js, titl
235
  # Hochformat
236
  new_choises = ["9:16", "3:4", "2:3", "1:1"]
237
  new_label = "Hochformat"
 
 
 
238
 
239
  return {"choices": new_choises, "value": ratio_value_new, "label": new_label, "__type__": "update"}
240
 
241
- def calculate_ratio_values(image_ratio_buttons, image_width, image_height):
242
  ratio_value = image_ratio_buttons.split(":")
243
  if int(ratio_value[0]) > int(ratio_value[1]):
244
  a = 2048
245
  b = int(a * int(ratio_value[1]) / int(ratio_value[0]))
246
  new_width = a
247
  new_height = b
 
248
  elif int(ratio_value[0]) < int(ratio_value[1]):
249
  b = 2048
250
  a = int(b * int(ratio_value[0]) / int(ratio_value[1]))
251
  new_width = a
252
  new_height = b
253
- else:
 
254
  new_width = 2048
255
  new_height = 2048
 
256
 
257
- return new_width, new_height
258
 
259
- switch_width_height.click(fn=switch_image_size_values, inputs=[image_width, image_height], outputs=[image_width, image_height], show_progress="hidden")
260
- switch_width_height.click(fn=switch_image_ratio_buttons, inputs=[image_ratio_buttons], outputs=[image_ratio_buttons], show_progress="hidden")
261
 
262
- image_ratio_buttons.input(fn=calculate_ratio_values, inputs=[image_ratio_buttons, image_width, image_height], outputs=[image_width, image_height], show_progress="hidden")
263
 
264
- run_button.click(fn=lambda: {"interactive": False, "__type__": "update"}, outputs=[run_button]).then(fn=process, inputs=[text_prompt, image_width, image_height, image_seed, randomize_seed], outputs=[text_prompt, output_image, output_url, outpu_image_comment, image_informations, image_info_tb_prompt, image_info_tb_width, image_info_tb_height, image_info_tb_seed, image_download_button, output_dominant_image_color, image_seed]).then(
265
- fn=lambda: {"interactive": True, "__type__": "update"}, outputs=[run_button]
266
- )
267
 
268
- enhance_prompt_button.click(fn=groq_enhance_process, inputs=[text_prompt], outputs=[text_prompt])
269
- random_prompt_button.click(fn=groq_enhance_process, inputs=None, outputs=[text_prompt])
270
 
 
 
271
  # MARK: Gradio LAUNCH
272
  demo.launch()
 
52
  <link rel="manifest" href="file=_res/assets/favicons/site.webmanifest">
53
  """
54
 
55
+ # MARK: GET PREV. IMAGES
56
+ def get_gallery_images(dirpath):
57
+ gallery_images = [dirpath + "/" + s for s in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, s))]
58
+ gallery_images.sort(key=lambda s: os.path.getmtime(s), reverse=True)
59
+ return gallery_images
 
 
60
  title = "Bilder Builder"
61
 
62
+ def get_gallery_images(dirpath):
63
+ gallery_images = [dirpath + "/" + s for s in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, s))]
64
+ gallery_images.sort(key=lambda s: os.path.getmtime(s), reverse=True)
65
+ return gallery_images
66
+
67
 
68
  # MARK: READ EXIF
69
  def read_exif(image_path):
 
143
 
144
  return dominant_color_rgb
145
 
146
+ def process(Prompt, used_model, image_width, image_height, image_ratio, image_seed, randomize_seed):
 
 
147
  if Prompt == "":
148
+ gr.Info("Kein Prompt angegeben, es wird ein zufälliger Prompt generiert.", duration=12)
149
  Prompt = groq_enhance_process("random prompt")
150
 
151
+ image_ratio = "9:16" if image_ratio == "" else image_ratio
152
  used_seed = random.randint(0, MAX_SEED) if image_seed == 0 or randomize_seed else image_seed
153
  # used_model = "turbo" if int(image_width) > 1024 or int(image_height) > 1024 else "flux" # turbo, flux
154
 
 
157
  filename = timestamp + "_" + filename_prompt[:100] + ".png"
158
  file_path = os.path.join(IMAGE_DIR, filename)
159
 
160
+ # Retry-Logik mit requests und Retry
161
+ session = Session()
162
+ retries = Retry(total=3, status_forcelist=[429, 500, 502, 503, 504], backoff_factor=0.3, respect_retry_after_header=True) # Max 3 Versuche # Codes, die wiederholt werden # Exponential Backoff # Retry-Header beachten
163
+ adapter = HTTPAdapter(max_retries=retries)
164
+ session.mount("https://", adapter)
165
+ session.mount("http://", adapter)
166
+
167
+ API_OLD_REQUEST_URL = f"{API_OLD}{urllib.parse.quote(Prompt)}?model=flux&width={image_width}&height={image_height}&nologo=true&enhance=false&nofeed=true&seed={used_seed}"
168
+ API_V1_REQUEST_URL = f"{API_V1_IMAGE}?prompt={urllib.parse.quote(Prompt)}&size={urllib.parse.quote(image_ratio)}&seed={used_seed}&model={used_model.lower()}"
169
+ REQUEST_URL = API_V1_REQUEST_URL if used_model.lower() != "flux-api-old" else API_OLD_REQUEST_URL
170
+ print(REQUEST_URL)
171
+ try:
172
+ response = session.get(REQUEST_URL, timeout=60)
173
+ if response.status_code == 200:
174
+ print("Imagine API Request solved")
175
+ print("Save image to: " + file_path)
176
+ img = PILImage.open(BytesIO(response.content))
177
+ img.save(file_path, "PNG")
178
+
179
+ # img_exif_comment = "" # read_exif(file_path)
180
+ img_dominant_color = image_get_dominant_color(file_path)
181
+ img_width, img_height = image_get_size(file_path)
182
+
183
+ return ({"value": Prompt, "__type__": "update"}, {"value": file_path, "__type__": "update"}, {"value": None, "visible": False, "__type__": "update"}, {"visible": True, "__type__": "update"}, {"value": Prompt, "visible": True, "__type__": "update"}, img_width, img_height, used_seed, {"value": file_path, "visible": True, "__type__": "update"}, img_dominant_color, used_seed)
184
+ else:
185
+ print("Imagine API Request ERROR")
186
+ raise gr.Error("Imagine API Request fehlgeschlagen 💥!", duration=15)
187
+ except requests.exceptions.Timeout:
188
+ raise gr.Error("Zeitüberschreitung beim API-Aufruf", duration=15)
189
+ except requests.exceptions.RequestException as e:
190
+ raise gr.Error(f"Fehler beim API-Aufruf: {e}", duration=15)
191
 
192
 
193
  # MARK: Gradio BLOCKS UI
 
207
  with gr.Row(elem_classes="image_size_selctor_wrapper"):
208
  with gr.Column(scale=1):
209
  with gr.Row():
210
+ select_model = gr.Dropdown(choices=["FLUX", "FLUX-API-OLD", "FLUX-Realism", "FLUX-Pixel", "ANY-DARK", "Stable-Diffusion-XL-Lightning", "Stable-Diffusion-XL-Base"], value="FLUX", label="Model", elem_id="select_model", elem_classes="select-model")
211
+ # with gr.Row():
212
+ image_width = gr.Number(label="Breite", minimum=256, maximum=MAX_IMAGE_SIZE, value=1024, step=128, elem_id="image_width_selector", elem_classes="image-width-selector", scale=1, visible=False)
213
+ image_height = gr.Number(label="Höhe", minimum=256, maximum=MAX_IMAGE_SIZE, value=683, step=128, elem_id="image_height_selector", elem_classes="image-height-selector", scale=1, visible=False)
214
  with gr.Row():
215
  image_ratio_buttons = gr.Radio(["16:9", "4:3", "3:2", "1:1"], value="3:2", label="Querformat", show_label=True, info="Die gängigsten Seitenverhältnissen.", interactive=True, elem_id="image_ratio_buttons", elem_classes="image-ratio-buttons", container=True, scale=2)
216
  switch_width_height = gr.Button("", size="sm", elem_id="switch_width_height", elem_classes="switch-ratio-btn", variant="primary", scale=1)
 
222
  with gr.Row():
223
  with gr.Column(scale=1):
224
  with gr.Row():
225
+ output_image = gr.Image(show_label=False, min_width=320, scale=3, elem_id="output_image", elem_classes="output-image", type="filepath", format="webp")
226
+ # gallery = gr.Gallery(label="Bisher erstellte Bilder", show_label=True, value=get_gallery_images(IMAGE_DIR), elem_id="gallery", columns=[4], object_fit="cover", height="auto", interactive=False, format="webp")
227
  with gr.Column(scale=1, visible=False, elem_classes="image-info-wrapper") as image_info_wrapper:
 
228
  with gr.Group():
229
  image_informations = gr.Markdown("""## Bildinformationen""", visible=True)
 
230
  with gr.Row(elem_classes="img-size-wrapper"):
231
  image_info_tb_width = gr.Textbox(label="Breite", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-width")
232
  image_info_tb_height = gr.Textbox(label="Höhe", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-height")
233
  with gr.Row(elem_classes="img-seed-wrapper"):
234
  image_info_tb_seed = gr.Textbox(label="Seed", lines=1, max_lines=1, interactive=False, show_copy_button=True, elem_classes="image-info-tb-seed")
235
  image_info_tb_prompt = gr.Textbox("Bild Prompt", lines=4, max_lines=8, interactive=False, elem_classes="hide-progress", show_copy_button=True, visible=False)
 
236
  image_download_button = gr.DownloadButton("Bild herunterladen", value=None, elem_classes="download-button", variant="primary", visible=False)
237
 
238
  output_url = gr.Textbox(label="Output URL", show_label=True, interactive=False, visible=False)
 
245
  def switch_image_ratio_buttons(ratio_value):
246
  ratio_value = ratio_value.split(":")
247
  ratio_value_new = f"{int(ratio_value[1])}:{int(ratio_value[0])}"
 
248
 
249
  if int(ratio_value[1]) > int(ratio_value[0]):
250
  # Querformat
 
254
  # Hochformat
255
  new_choises = ["9:16", "3:4", "2:3", "1:1"]
256
  new_label = "Hochformat"
257
+ elif int(ratio_value[1]) == int(ratio_value[0]):
258
+ new_choises = image_ratio_buttons.choices
259
+ new_label = "Quadratisch"
260
 
261
  return {"choices": new_choises, "value": ratio_value_new, "label": new_label, "__type__": "update"}
262
 
263
+ def calculate_ratio_values(image_ratio_buttons):
264
  ratio_value = image_ratio_buttons.split(":")
265
  if int(ratio_value[0]) > int(ratio_value[1]):
266
  a = 2048
267
  b = int(a * int(ratio_value[1]) / int(ratio_value[0]))
268
  new_width = a
269
  new_height = b
270
+ new_label = "Querformat"
271
  elif int(ratio_value[0]) < int(ratio_value[1]):
272
  b = 2048
273
  a = int(b * int(ratio_value[0]) / int(ratio_value[1]))
274
  new_width = a
275
  new_height = b
276
+ new_label = "Hochformat"
277
+ elif int(ratio_value[0]) == int(ratio_value[1]):
278
  new_width = 2048
279
  new_height = 2048
280
+ new_label = "Quadratisch"
281
 
282
+ return {"label": new_label, "__type__": "update"}, new_width, new_height
283
 
284
+ switch_width_height.click(fn=switch_image_size_values, inputs=[image_width, image_height], outputs=[image_width, image_height], show_progress="hidden", show_api=False)
285
+ switch_width_height.click(fn=switch_image_ratio_buttons, inputs=[image_ratio_buttons], outputs=[image_ratio_buttons], show_progress="hidden", show_api=False)
286
 
287
+ image_ratio_buttons.input(fn=calculate_ratio_values, inputs=[image_ratio_buttons], outputs=[image_ratio_buttons, image_width, image_height], show_progress="hidden", show_api=False)
288
 
289
+ run_button.click(fn=lambda: ({"interactive": False, "__type__": "update"}, {"interactive": False, "__type__": "update"}, {"interactive": False, "__type__": "update"}), outputs=[run_button, enhance_prompt_button, random_prompt_button], show_api=False).then(fn=clear_components, outputs=[output_image], show_api=False).then(
290
+ fn=process, inputs=[text_prompt, select_model, image_width, image_height, image_ratio_buttons, image_seed, randomize_seed, gallery], outputs=[text_prompt, output_image, output_url, image_informations, image_info_tb_prompt, image_info_tb_width, image_info_tb_height, image_info_tb_seed, image_download_button, output_dominant_image_color, image_seed, gallery]
291
+ ).then(fn=lambda: ({"interactive": True, "__type__": "update"}, {"interactive": True, "__type__": "update"}, {"interactive": True, "__type__": "update"}), outputs=[run_button, enhance_prompt_button, random_prompt_button], show_api=False)
292
 
293
+ randomize_seed.input(lambda x: {"interactive": False if x == True else True, "__type__": "update"}, inputs=[randomize_seed], outputs=[image_seed], show_api=False)
 
294
 
295
+ enhance_prompt_button.click(fn=groq_enhance_process, inputs=[text_prompt], outputs=[text_prompt], show_api=False)
296
+ random_prompt_button.click(fn=groq_enhance_process, inputs=None, outputs=[text_prompt], show_api=False)
297
  # MARK: Gradio LAUNCH
298
  demo.launch()