ehristoforu commited on
Commit
05797c3
1 Parent(s): d322544

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -218
app.py CHANGED
@@ -1,39 +1,57 @@
1
  import gradio as gr
2
- from datasets import load_dataset
3
- from PIL import Image
4
-
5
- import re
6
- import os
7
  import requests
 
 
 
 
8
 
9
- from share_btn import community_icon_html, loading_icon_html, share_js
10
-
11
- from huggingface_hub import login
12
- login(token=os.environ.get("HF_READ_TOKEN"))
13
 
14
- word_list_dataset = load_dataset("shawarmas/Censored-Words", data_files="test.txt", use_auth_token=True)
15
- word_list = word_list_dataset["train"]['text']
16
 
17
- is_gpu_busy = False
18
- def infer(prompt, negative, scale):
19
- global is_gpu_busy
20
- for filter in word_list:
21
- if re.search(rf"\b{filter}\b", prompt):
22
- raise gr.Error("Unsafe content found. Please try again with different prompts.")
23
-
24
  images = []
25
- url = os.getenv('JAX_BACKEND_URL')
26
- HF_TOKEN = os.environ.get("HF_READ_TOKEN")
27
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
28
- payload = {'prompt': prompt, 'negative_prompt': negative, 'guidance_scale': scale}
29
- images_request = requests.post(url, headers=headers, json = payload)
30
- for image in images_request.json()["images"]:
31
- image_b64 = (f"data:image/jpeg;base64,{image}")
32
- images.append(image_b64)
33
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  return images
35
-
36
-
37
  css = """
38
  .gradio-container {
39
  font-family: 'IBM Plex Sans', sans-serif;
@@ -146,7 +164,7 @@ css = """
146
  #share-btn-container .wrap {
147
  display: none !important;
148
  }
149
-
150
  .gr-form{
151
  flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
152
  }
@@ -158,196 +176,19 @@ css = """
158
  .image_duplication{position: absolute; width: 100px; left: 50px}
159
  """
160
 
161
- block = gr.Blocks(css=css)
162
-
163
- examples = [
164
- [
165
- 'A high tech solarpunk utopia in the Amazon rainforest',
166
- 'low quality',
167
- 9
168
- ],
169
- [
170
- 'A pikachu fine dining with a view to the Eiffel Tower',
171
- 'low quality',
172
- 9
173
- ],
174
- [
175
- 'A mecha robot in a favela in expressionist style',
176
- 'low quality, 3d, photorealistic',
177
- 9
178
- ],
179
- [
180
- 'an insect robot preparing a delicious meal',
181
- 'low quality, illustration',
182
- 9
183
- ],
184
- [
185
- "A small cabin on top of a snowy mountain in the style of Disney, artstation",
186
- 'low quality, ugly',
187
- 9
188
- ],
189
- ]
190
-
191
-
192
- with block:
193
- gr.HTML(
194
- """
195
- <div style="text-align: center; margin: 0 auto;">
196
- <div
197
- style="
198
- display: inline-flex;
199
- align-items: center;
200
- gap: 0.8rem;
201
- font-size: 1.75rem;
202
- "
203
- >
204
- <svg
205
- width="0.65em"
206
- height="0.65em"
207
- viewBox="0 0 115 115"
208
- fill="none"
209
- xmlns="http://www.w3.org/2000/svg"
210
- >
211
- <rect width="23" height="23" fill="white"></rect>
212
- <rect y="69" width="23" height="23" fill="white"></rect>
213
- <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
214
- <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
215
- <rect x="46" width="23" height="23" fill="white"></rect>
216
- <rect x="46" y="69" width="23" height="23" fill="white"></rect>
217
- <rect x="69" width="23" height="23" fill="black"></rect>
218
- <rect x="69" y="69" width="23" height="23" fill="black"></rect>
219
- <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
220
- <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
221
- <rect x="115" y="46" width="23" height="23" fill="white"></rect>
222
- <rect x="115" y="115" width="23" height="23" fill="white"></rect>
223
- <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
224
- <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
225
- <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
226
- <rect x="92" y="69" width="23" height="23" fill="white"></rect>
227
- <rect x="69" y="46" width="23" height="23" fill="white"></rect>
228
- <rect x="69" y="115" width="23" height="23" fill="white"></rect>
229
- <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
230
- <rect x="46" y="46" width="23" height="23" fill="black"></rect>
231
- <rect x="46" y="115" width="23" height="23" fill="black"></rect>
232
- <rect x="46" y="69" width="23" height="23" fill="black"></rect>
233
- <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
234
- <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
235
- <rect x="23" y="69" width="23" height="23" fill="black"></rect>
236
- </svg>
237
- <h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
238
- Stable Diffusion 2.1 Demo
239
- </h1>
240
- </div>
241
- <p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
242
- Stable Diffusion 2.1 is the latest text-to-image model from StabilityAI. <a style="text-decoration: underline;" href="https://huggingface.co/spaces/stabilityai/stable-diffusion-1">Access Stable Diffusion 1 Space here</a><br>For faster generation and API
243
- access you can try
244
- <a
245
- href="http://beta.dreamstudio.ai/"
246
- style="text-decoration: underline;"
247
- target="_blank"
248
- >DreamStudio Beta</a
249
- >.</a>
250
- </p>
251
- </div>
252
- """
253
- )
254
  with gr.Group():
255
- with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
256
- with gr.Column():
257
- text = gr.Textbox(
258
- label="Enter your prompt",
259
- show_label=False,
260
- max_lines=1,
261
- placeholder="Enter your prompt",
262
- elem_id="prompt-text-input",
263
- ).style(
264
- border=(True, False, True, True),
265
- rounded=(True, False, False, True),
266
- container=False,
267
- )
268
- negative = gr.Textbox(
269
- label="Enter your negative prompt",
270
- show_label=False,
271
- max_lines=1,
272
- placeholder="Enter a negative prompt",
273
- elem_id="negative-prompt-text-input",
274
- ).style(
275
- border=(True, False, True, True),
276
- rounded=(True, False, False, True),
277
- container=False,
278
- )
279
- btn = gr.Button("Generate image").style(
280
- margin=False,
281
- rounded=(False, True, True, False),
282
- full_width=False,
283
- )
284
-
285
- gallery = gr.Gallery(
286
- label="Generated images", show_label=False, elem_id="gallery"
287
- ).style(grid=[2], height="auto")
288
-
289
- with gr.Group(elem_id="container-advanced-btns"):
290
- #advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")
291
- with gr.Group(elem_id="share-btn-container"):
292
- community_icon = gr.HTML(community_icon_html)
293
- loading_icon = gr.HTML(loading_icon_html)
294
- share_button = gr.Button("Share to community", elem_id="share-btn")
295
 
 
296
  with gr.Accordion("Advanced settings", open=False):
297
- # gr.Markdown("Advanced settings are temporarily unavailable")
298
- # samples = gr.Slider(label="Images", minimum=1, maximum=4, value=4, step=1)
299
- # steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=45, step=1)
300
- guidance_scale = gr.Slider(
301
- label="Guidance Scale", minimum=0, maximum=50, value=9, step=0.1
302
- )
303
- # seed = gr.Slider(
304
- # label="Seed",
305
- # minimum=0,
306
- # maximum=2147483647,
307
- # step=1,
308
- # randomize=True,
309
- # )
310
 
311
- ex = gr.Examples(examples=examples, fn=infer, inputs=[text, negative, guidance_scale], outputs=[gallery, community_icon, loading_icon, share_button], cache_examples=False)
312
- ex.dataset.headers = [""]
313
- negative.submit(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
314
- text.submit(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
315
- btn.click(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
316
-
317
- #advanced_button.click(
318
- # None,
319
- # [],
320
- # text,
321
- # _js="""
322
- # () => {
323
- # const options = document.querySelector("body > gradio-app").querySelector("#advanced-options");
324
- # options.style.display = ["none", ""].includes(options.style.display) ? "flex" : "none";
325
- # }""",
326
- #)
327
- share_button.click(
328
- None,
329
- [],
330
- [],
331
- _js=share_js,
332
- )
333
- gr.HTML(
334
- """
335
- <div class="footer">
336
- <p>Model by <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">StabilityAI</a> - backend running JAX on TPUs due to generous support of <a href="https://sites.research.google/trc/about/" style="text-decoration: underline;" target="_blank">Google TRC program</a> - Gradio Demo by 🤗 Hugging Face
337
- </p>
338
- </div>
339
- """
340
- )
341
- with gr.Accordion(label="License", open=False):
342
- gr.HTML(
343
- """<div class="acknowledgments">
344
- <p><h4>LICENSE</h4>
345
- The model is licensed with a <a href="https://huggingface.co/stabilityai/stable-diffusion-2/blob/main/LICENSE-MODEL" style="text-decoration: underline;" target="_blank">CreativeML OpenRAIL++</a> license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank" style="text-decoration: underline;" target="_blank">read the license</a></p>
346
- <p><h4>Biases and content acknowledgment</h4>
347
- Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. The model was trained on the <a href="https://laion.ai/blog/laion-5b/" style="text-decoration: underline;" target="_blank">LAION-5B dataset</a>, which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes. You can read more in the <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" style="text-decoration: underline;" target="_blank">model card</a></p>
348
- </div>
349
- """
350
- )
351
-
352
 
353
- block.queue(concurrency_count=80, max_size=100).launch(max_threads=150)
 
1
  import gradio as gr
 
 
 
 
 
2
  import requests
3
+ import io
4
+ import random
5
+ import os
6
+ from PIL import Image
7
 
8
+ API_URL = os.getenv("API_URL")
9
+ API_TOKEN = os.getenv("HF_READ_TOKEN")
10
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
 
11
 
 
 
12
 
13
+ def query(prompt, is_negative=False, image_style="None style", steps=50, cfg_scale=7, seed=None, num_images=2):
 
 
 
 
 
 
14
  images = []
15
+ for _ in range(num_images):
16
+ if image_style == "None style":
17
+ payload = {
18
+ "inputs": prompt + ", 8k",
19
+ "is_negative": is_negative,
20
+ "steps": steps,
21
+ "cfg_scale": cfg_scale,
22
+ "seed": seed if seed is not None else random.randint(-1, 2147483647)
23
+ }
24
+ elif image_style == "Cinematic":
25
+ payload = {
26
+ "inputs": prompt + ", realistic, detailed, textured, skin, hair, eyes, by Alex Huguet, Mike Hill, Ian Spriggs, JaeCheol Park, Marek Denko",
27
+ "is_negative": is_negative + ", abstract, cartoon, stylized",
28
+ "steps": steps,
29
+ "cfg_scale": cfg_scale,
30
+ "seed": seed if seed is not None else random.randint(-1, 2147483647)
31
+ }
32
+ elif image_style == "Digital Art":
33
+ payload = {
34
+ "inputs": prompt + ", faded , vintage , nostalgic , by Jose Villa , Elizabeth Messina , Ryan Brenizer , Jonas Peterson , Jasmine Star",
35
+ "is_negative": is_negative + ", sharp , modern , bright",
36
+ "steps": steps,
37
+ "cfg_scale": cfg_scale,
38
+ "seed": seed if seed is not None else random.randint(-1, 2147483647)
39
+ }
40
+ elif image_style == "Portrait":
41
+ payload = {
42
+ "inputs": prompt + ", soft light, sharp, exposure blend, medium shot, bokeh, (hdr:1.4), high contrast, (cinematic, teal and orange:0.85), (muted colors, dim colors, soothing tones:1.3), low saturation, (hyperdetailed:1.2), (noir:0.4), (natural skin texture, hyperrealism, soft light, sharp:1.2)",
43
+ "is_negative": is_negative,
44
+ "steps": steps,
45
+ "cfg_scale": cfg_scale,
46
+ "seed": seed if seed is not None else random.randint(-1, 2147483647)
47
+ }
48
+
49
+ image_bytes = requests.post(API_URL, headers=headers, json=payload).content
50
+ image = Image.open(io.BytesIO(image_bytes))
51
+ images.append(image)
52
  return images
53
+
54
+
55
  css = """
56
  .gradio-container {
57
  font-family: 'IBM Plex Sans', sans-serif;
 
164
  #share-btn-container .wrap {
165
  display: none !important;
166
  }
167
+
168
  .gr-form{
169
  flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
170
  }
 
176
  .image_duplication{position: absolute; width: 100px; left: 50px}
177
  """
178
 
179
+ with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  with gr.Group():
181
+ with gr.Box():
182
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
183
+ with gr.Column:
184
+ text_prompt = gr.Textbox(label="Prompt", placeholder="a cute cat", max_lines=1, elem_id="prompt-text-input").style(border=(True, False, True, True), rounded=(True, False, False, True), container=False)
185
+ negative_prompt = gr.Textbox(label="Negative Prompt", value="text, blurry, fuzziness", max_lines=1, elem_id="negative-prompt-text-input").style(border=(True, False, True, True), rounded=(True, False, False, True), container=False)
186
+ text_button = gr.Button("Generate").style(margin=False, rounded=(False, True, True, False), full_width=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
+ gallery_output = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="auto")
189
  with gr.Accordion("Advanced settings", open=False):
190
+ image_style = gr.Radio(label="Style", choices=["None style", "Cinematic", "Digital Art", "Portrait"], value="None style")
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
+ text_button.click(query, inputs=[text_prompt, negative_prompt, image_style], outputs=gallery_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
+ demo.launch(show_api=False)