xycold commited on
Commit
d4b7b81
1 Parent(s): a64a8bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +289 -0
app.py CHANGED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import qrcode
5
+ from pathlib import Path
6
+ from multiprocessing import cpu_count
7
+ import requests
8
+ import io
9
+ import os
10
+ from PIL import Image
11
+
12
+ from diffusers import (
13
+ StableDiffusionControlNetPipeline,
14
+ ControlNetModel,
15
+ DDIMScheduler,
16
+ DPMSolverMultistepScheduler,
17
+ DEISMultistepScheduler,
18
+ HeunDiscreteScheduler,
19
+ EulerDiscreteScheduler,
20
+ EulerAncestralDiscreteScheduler,
21
+ )
22
+
23
+ controlnet = ControlNetModel.from_pretrained(
24
+ "monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16
25
+ )
26
+
27
+ pipe = StableDiffusionControlNetPipeline.from_pretrained(
28
+ "runwayml/stable-diffusion-v1-5",
29
+ controlnet=controlnet,
30
+ safety_checker=None,
31
+ torch_dtype=torch.float16,
32
+ ).to("cuda")
33
+ pipe.enable_xformers_memory_efficient_attention()
34
+
35
+ SAMPLER_MAP = {
36
+ "DPM++ Karras SDE": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True, algorithm_type="sde-dpmsolver++"),
37
+ "DPM++ Karras": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True),
38
+ "Heun": lambda config: HeunDiscreteScheduler.from_config(config),
39
+ "Euler a": lambda config: EulerAncestralDiscreteScheduler.from_config(config),
40
+ "Euler": lambda config: EulerDiscreteScheduler.from_config(config),
41
+ "DDIM": lambda config: DDIMScheduler.from_config(config),
42
+ "DEIS": lambda config: DEISMultistepScheduler.from_config(config),
43
+ }
44
+
45
+
46
+ def create_code(content: str):
47
+ qr = qrcode.QRCode(
48
+ version=1,
49
+ error_correction=qrcode.constants.ERROR_CORRECT_H,
50
+ box_size=16,
51
+ border=0,
52
+ )
53
+ qr.add_data(content)
54
+ qr.make(fit=True)
55
+ img = qr.make_image(fill_color="black", back_color="white")
56
+
57
+ # find smallest image size multiple of 256 that can fit qr
58
+ offset_min = 8 * 16
59
+ w, h = img.size
60
+ w = (w + 255 + offset_min) // 256 * 256
61
+ h = (h + 255 + offset_min) // 256 * 256
62
+ if w > 1024:
63
+ raise gr.Error("QR code is too large, please use a shorter content")
64
+ bg = Image.new('L', (w, h), 255)
65
+
66
+ # align on 16px grid
67
+ coords = ((w - img.size[0]) // 2 // 16 * 16,
68
+ (h - img.size[1]) // 2 // 16 * 16)
69
+ bg.paste(img, coords)
70
+ return bg
71
+
72
+
73
+ def inference(
74
+ qr_code_content: str,
75
+ prompt: str,
76
+ negative_prompt: str,
77
+ guidance_scale: float = 10.0,
78
+ controlnet_conditioning_scale: float = 2.0,
79
+ seed: int = -1,
80
+ sampler="Euler a",
81
+ ):
82
+ if prompt is None or prompt == "":
83
+ raise gr.Error("Prompt is required")
84
+
85
+ if qr_code_content is None or qr_code_content == "":
86
+ raise gr.Error("QR Code Content is required")
87
+
88
+ pipe.scheduler = SAMPLER_MAP[sampler](pipe.scheduler.config)
89
+
90
+ generator = torch.manual_seed(seed) if seed != -1 else torch.Generator()
91
+
92
+ print("Generating QR Code from content")
93
+ qrcode_image = create_code(qr_code_content)
94
+
95
+ # hack due to gradio examples
96
+ init_image = qrcode_image
97
+
98
+ out = pipe(
99
+ prompt=prompt,
100
+ negative_prompt=negative_prompt,
101
+ image=qrcode_image,
102
+ width=qrcode_image.width,
103
+ height=qrcode_image.height,
104
+ guidance_scale=float(guidance_scale),
105
+ controlnet_conditioning_scale=float(controlnet_conditioning_scale),
106
+ generator=generator,
107
+ num_inference_steps=40,
108
+ )
109
+ return out.images[0]
110
+
111
+
112
+ css = """
113
+ #result_image {
114
+ display: flex;
115
+ place-content: center;
116
+ align-items: center;
117
+ }
118
+ #result_image > img {
119
+ height: auto;
120
+ max-width: 100%;
121
+ width: revert;
122
+ }
123
+ """
124
+
125
+ with gr.Blocks(css=css) as blocks:
126
+ gr.Markdown(
127
+ """
128
+ # QR Code Monster v1.0
129
+ ## QR Code AI Art Generator
130
+ Model used: https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster
131
+ Try our more powerful v2 here: https://qrcodemonster.art!
132
+ <a href="https://huggingface.co/spaces/monster-labs/Controlnet-QRCode-Monster-V1?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
133
+ <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> for no queue on your own hardware.</p>
134
+ """
135
+ )
136
+
137
+ with gr.Row():
138
+ with gr.Column():
139
+ qr_code_content = gr.Textbox(
140
+ label="QR Code Content or URL",
141
+ info="The text you want to encode into the QR code",
142
+ value="",
143
+ )
144
+
145
+ prompt = gr.Textbox(
146
+ label="Prompt",
147
+ info="Prompt that guides the generation towards",
148
+ )
149
+ negative_prompt = gr.Textbox(
150
+ label="Negative Prompt",
151
+ value="ugly, disfigured, low quality, blurry, nsfw",
152
+ info="Prompt that guides the generation away from",
153
+ )
154
+
155
+ with gr.Accordion(
156
+ label="Params: The generated QR Code functionality is largely influenced by the parameters detailed below",
157
+ open=True,
158
+ ):
159
+ controlnet_conditioning_scale = gr.Slider(
160
+ minimum=0.5,
161
+ maximum=2.5,
162
+ step=0.01,
163
+ value=1.5,
164
+ label="Controlnet Conditioning Scale",
165
+ info="""Controls the readability/creativity of the QR code.
166
+ High values: The generated QR code will be more readable.
167
+ Low values: The generated QR code will be more creative.
168
+ """
169
+ )
170
+ guidance_scale = gr.Slider(
171
+ minimum=0.0,
172
+ maximum=25.0,
173
+ step=0.25,
174
+ value=7,
175
+ label="Guidance Scale",
176
+ info="Controls the amount of guidance the text prompt guides the image generation"
177
+ )
178
+ sampler = gr.Dropdown(choices=list(
179
+ SAMPLER_MAP.keys()), value="Euler a", label="Sampler")
180
+ seed = gr.Number(
181
+ minimum=-1,
182
+ maximum=9999999999,
183
+ step=1,
184
+ value=2313123,
185
+ label="Seed",
186
+ randomize=True,
187
+ info="Seed for the random number generator. Set to -1 for a random seed"
188
+ )
189
+ with gr.Row():
190
+ run_btn = gr.Button("Run")
191
+ with gr.Column():
192
+ result_image = gr.Image(label="Result Image", elem_id="result_image")
193
+ run_btn.click(
194
+ inference,
195
+ inputs=[
196
+ qr_code_content,
197
+ prompt,
198
+ negative_prompt,
199
+ guidance_scale,
200
+ controlnet_conditioning_scale,
201
+ seed,
202
+ sampler,
203
+ ],
204
+ outputs=[result_image],
205
+ )
206
+
207
+ gr.Examples(
208
+ examples=[
209
+ [
210
+ "test",
211
+ "Baroque rococo architecture, architectural photography, post apocalyptic New York, hyperrealism, [roots], hyperrealistic, octane render, cinematic, hyper detailed, 8K",
212
+ "",
213
+ 7,
214
+ 1.6,
215
+ 2592353769,
216
+ "Euler a",
217
+ ],
218
+ [
219
+ "https://qrcodemonster.art",
220
+ "a centered render of an ancient tree covered in bio - organic micro organisms growing in a mystical setting, cinematic, beautifully lit, by tomasz alen kopera and peter mohrbacher and craig mullins, 3d, trending on artstation, octane render, 8k",
221
+ "",
222
+ 7,
223
+ 1.57,
224
+ 259235398,
225
+ "Euler a",
226
+ ],
227
+ [
228
+ "test",
229
+ "3 cups of coffee with coffee beans around",
230
+ "",
231
+ 7,
232
+ 1.95,
233
+ 1889601353,
234
+ "Euler a",
235
+ ],
236
+ [
237
+ "https://huggingface.co",
238
+ "A top view picture of a sandy beach with a sand castle, beautiful lighting, 8k, highly detailed",
239
+ "sky",
240
+ 7,
241
+ 1.15,
242
+ 46200,
243
+ "Euler a",
244
+ ],
245
+ [
246
+ "test",
247
+ "A top view picture of a sandy beach, organic shapes, beautiful lighting, bumps and shadows, 8k, highly detailed",
248
+ "sky, water, squares",
249
+ 7,
250
+ 1.25,
251
+ 46220,
252
+ "Euler a",
253
+ ],
254
+ ],
255
+ fn=inference,
256
+ inputs=[
257
+ qr_code_content,
258
+ prompt,
259
+ negative_prompt,
260
+ guidance_scale,
261
+ controlnet_conditioning_scale,
262
+ seed,
263
+ sampler,
264
+ ],
265
+ outputs=[result_image],
266
+ cache_examples=True,
267
+ )
268
+ gr.Markdown(
269
+ """
270
+ ## Notes
271
+ * The generated QR codes may not always be easily readable and may require adjusting the parameters.
272
+ * The prompt affects the quality of the generated QR code.
273
+ * The scan may work better if the phone is held further away from the screen, or if the page is zoomed out.
274
+ ## Parameters
275
+ - **Input Text:** The text you want to encode into the QR code
276
+ - **Prompt:** Input a prompt to guide the QR code generation process, allowing you to control the appearance and style of the generated QR codes. Some are easier than others to generate readable QR codes.
277
+ - **Controlnet Control Scale:** Raise the control scale value to increase the readability of the QR codes or lower it to make the QR codes more creative and distinctive.
278
+ The generated QR codes might not always be easily readable. It might take a few tries with different parameters to find the right balance. This often depends on the prompt, which can be more or less suitable for QR code generation.
279
+ ## How to Use
280
+ 1. Input your text: Pass the text you'd like to encode into the QR code as input. Bigger text means bigger codes, which are less likely to give good results (will ressemble qr codes too much).
281
+ 2. Set your prompt: Choose a prompt to guide the generation process (use all the SD tricks you like: styles, adjectives...).
282
+ 3. Adjust the Controlnet Control Scale: The higher the control scale, the more readable the QR code will be, while a lower control scale leads to a more creative QR code.
283
+ 4. Generate multiple codes: Since not all generated codes may be readable, you'll need to create a few codes with the same parameters to determine if any adjustments are needed.
284
+ 5. Test the generated QR codes: Scan the generated QR codes to make sure they are readable and meet your requirements.
285
+ """
286
+ )
287
+
288
+ blocks.queue(concurrency_count=1, max_size=20, api_open=False)
289
+ blocks.launch(share=bool(os.environ.get("SHARE", False)), show_api=False)