achiru commited on
Commit
e26724d
1 Parent(s): 1afdb30
Files changed (2) hide show
  1. app.py +275 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def create_code(content: str):
46
+ qr = qrcode.QRCode(
47
+ version=1,
48
+ error_correction=qrcode.constants.ERROR_CORRECT_H,
49
+ box_size=16,
50
+ border=0,
51
+ )
52
+ qr.add_data(content)
53
+ qr.make(fit=True)
54
+ img = qr.make_image(fill_color="black", back_color="white")
55
+
56
+ # find smallest image size multiple of 256 that can fit qr
57
+ offset_min = 8 * 16
58
+ w, h = img.size
59
+ w = (w + 255 + offset_min) // 256 * 256
60
+ h = (h + 255 + offset_min) // 256 * 256
61
+ if w > 1024:
62
+ raise gr.Error("QR code is too large, please use a shorter content")
63
+ bg = Image.new('L', (w, h), 255)
64
+
65
+ # align on 16px grid
66
+ coords = ((w - img.size[0]) // 2 // 16 * 16, (h - img.size[1]) // 2 // 16 * 16)
67
+ bg.paste(img, coords)
68
+ return bg
69
+
70
+ def inference(
71
+ qr_code_content: str,
72
+ prompt: str,
73
+ negative_prompt: str,
74
+ guidance_scale: float = 10.0,
75
+ controlnet_conditioning_scale: float = 2.0,
76
+ seed: int = -1,
77
+ sampler = "DPM++ Karras SDE",
78
+ ):
79
+ if prompt is None or prompt == "":
80
+ raise gr.Error("Prompt is required")
81
+
82
+ if qr_code_content is None or qr_code_content == "":
83
+ raise gr.Error("QR Code Content is required")
84
+
85
+ pipe.scheduler = SAMPLER_MAP[sampler](pipe.scheduler.config)
86
+
87
+ generator = torch.manual_seed(seed) if seed != -1 else torch.Generator()
88
+
89
+ print("Generating QR Code from content")
90
+ qrcode_image = create_code(qr_code_content)
91
+
92
+ # hack due to gradio examples
93
+ init_image = qrcode_image
94
+
95
+ out = pipe(
96
+ prompt=prompt,
97
+ negative_prompt=negative_prompt,
98
+ image=qrcode_image,
99
+ width=qrcode_image.width, # type: ignore
100
+ height=qrcode_image.height, # type: ignore
101
+ guidance_scale=float(guidance_scale),
102
+ controlnet_conditioning_scale=float(controlnet_conditioning_scale), # type: ignore
103
+ generator=generator,
104
+ num_inference_steps=40,
105
+ )
106
+ return out.images[0] # type: ignore
107
+
108
+ css = """
109
+ #result_image {
110
+ display: flex;
111
+ place-content: center;
112
+ align-items: center;
113
+ }
114
+ #result_image > img {
115
+ height: auto;
116
+ max-width: 100%;
117
+ width: revert;
118
+ }
119
+ """
120
+
121
+ with gr.Blocks(css=css) as blocks:
122
+ gr.Markdown(
123
+ """
124
+ # QR Code Monster v1.0
125
+
126
+ model used: https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster
127
+
128
+ Welcome to the QR Code Monster!
129
+
130
+ ## Parameters
131
+
132
+ - **Input Text:** The text you want to encode into the QR code
133
+ - **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.
134
+ - **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.
135
+
136
+ 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.
137
+
138
+ We're already working on v2, which is much more powerful, you can try [an early version here](https://qrcodemonster.art)!
139
+
140
+ ## How to Use
141
+
142
+ 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).
143
+ 2. Set your prompt: Choose a prompt to guide the generation process (use all the SD tricks you like: styles, adjectives...).
144
+ 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.
145
+ 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.
146
+ 5. Test the generated QR codes: Scan the generated QR codes to make sure they are readable and meet your requirements.
147
+ """
148
+ )
149
+
150
+ with gr.Row():
151
+ with gr.Column():
152
+ qr_code_content = gr.Textbox(
153
+ label="QR Code Content",
154
+ info="QR Code Content or URL",
155
+ value="",
156
+ )
157
+
158
+ prompt = gr.Textbox(
159
+ label="Prompt",
160
+ info="Prompt that guides the generation towards",
161
+ )
162
+ negative_prompt = gr.Textbox(
163
+ label="Negative Prompt",
164
+ value="ugly, disfigured, low quality, blurry, nsfw",
165
+ )
166
+
167
+ with gr.Accordion(
168
+ label="Params: The generated QR Code functionality is largely influenced by the parameters detailed below",
169
+ open=True,
170
+ ):
171
+ controlnet_conditioning_scale = gr.Slider(
172
+ minimum=0.5,
173
+ maximum=2.5,
174
+ step=0.01,
175
+ value=1.5,
176
+ label="Controlnet Conditioning Scale",
177
+ )
178
+ guidance_scale = gr.Slider(
179
+ minimum=0.0,
180
+ maximum=25.0,
181
+ step=0.25,
182
+ value=7,
183
+ label="Guidance Scale",
184
+ )
185
+ sampler = gr.Dropdown(choices=list(SAMPLER_MAP.keys()), value="DPM++ Karras SDE", label="Sampler")
186
+ seed = gr.Number(
187
+ minimum=-1,
188
+ maximum=9999999999,
189
+ step=1,
190
+ value=2313123,
191
+ label="Seed",
192
+ randomize=True,
193
+ )
194
+ with gr.Row():
195
+ run_btn = gr.Button("Run")
196
+ with gr.Column():
197
+ result_image = gr.Image(label="Result Image", elem_id="result_image")
198
+ run_btn.click(
199
+ inference,
200
+ inputs=[
201
+ qr_code_content,
202
+ prompt,
203
+ negative_prompt,
204
+ guidance_scale,
205
+ controlnet_conditioning_scale,
206
+ seed,
207
+ sampler,
208
+ ],
209
+ outputs=[result_image],
210
+ )
211
+
212
+ gr.Examples(
213
+ examples=[
214
+ [
215
+ "test",
216
+ "Baroque rococo architecture, architectural photography, post apocalyptic New York, hyperrealism, [roots], hyperrealistic, octane render, cinematic, hyper detailed, 8K",
217
+ "",
218
+ 7,
219
+ 1.6,
220
+ 2592353769,
221
+ "Euler a",
222
+ ],
223
+ [
224
+ "test",
225
+ "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",
226
+ "",
227
+ 7,
228
+ 1.57,
229
+ 259235398,
230
+ "Euler a",
231
+ ],
232
+ [
233
+ "test",
234
+ "3 cups of coffee with coffee beans around",
235
+ "",
236
+ 7,
237
+ 1.95,
238
+ 1889601353,
239
+ "Euler a",
240
+ ],
241
+ [
242
+ "sd is cool",
243
+ "A top view picture of a sandy beach with a sand castle, beautiful lighting, 8k, highly detailed",
244
+ "sky",
245
+ 7,
246
+ 1.15,
247
+ 46200,
248
+ "Euler a",
249
+ ],
250
+ [
251
+ "test",
252
+ "A top view picture of a sandy beach, organic shapes, beautiful lighting, bumps and shadows, 8k, highly detailed",
253
+ "sky, water, squares",
254
+ 7,
255
+ 1.25,
256
+ 46220,
257
+ "Euler a",
258
+ ],
259
+ ],
260
+ fn=inference,
261
+ inputs=[
262
+ qr_code_content,
263
+ prompt,
264
+ negative_prompt,
265
+ guidance_scale,
266
+ controlnet_conditioning_scale,
267
+ seed,
268
+ sampler,
269
+ ],
270
+ outputs=[result_image],
271
+ cache_examples=True,
272
+ )
273
+
274
+ blocks.queue(concurrency_count=1, max_size=20)
275
+ blocks.launch(share=bool(os.environ.get("SHARE", False)))
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ diffusers
2
+ transformers
3
+ accelerate
4
+ torch
5
+ xformers
6
+ gradio
7
+ Pillow
8
+ qrcode