Lawrence-cj commited on
Commit
e097f87
1 Parent(s): c746b18

first commit

Browse files
Files changed (6) hide show
  1. .idea/.gitignore +11 -0
  2. README.md +2 -1
  3. app.py +299 -0
  4. pixart-lcm.png +0 -0
  5. requirements.txt +13 -0
  6. style.css +1 -0
.idea/.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
9
+
10
+ *.xml
11
+ *.iml
README.md CHANGED
@@ -10,4 +10,5 @@ pinned: false
10
  license: openrail
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
10
  license: openrail
11
  ---
12
 
13
+ Inference Code: https://github.com/PixArt-alpha/PixArt-alpha
14
+ Paper: https://arxiv.org/abs/2310.00426
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import annotations
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+ current_file_path = Path(__file__).resolve()
7
+ sys.path.insert(0, str(current_file_path.parent.parent))
8
+ import random
9
+ import gradio as gr
10
+ import numpy as np
11
+ import uuid
12
+ from diffusers import PixArtAlphaPipeline, LatentConsistencyModelPipeline, LCMScheduler
13
+ import torch
14
+ from typing import Tuple
15
+ from datetime import datetime
16
+
17
+
18
+ DESCRIPTION = """![Logo](./pixart-lcm.png)
19
+ # PixArt-Alpha LCM 1024px
20
+ #### [PixArt-Alpha 1024px](https://github.com/PixArt-alpha/PixArt-alpha) is a transformer-based text-to-image diffusion system trained on text embeddings from T5. This demo uses the [PixArt-alpha/PixArt-XL-2-1024-MS](https://huggingface.co/PixArt-alpha/PixArt-XL-2-1024-MS) checkpoint.
21
+ #### English prompts ONLY; 提示词仅限英文
22
+ Don't want to queue? Try [OpenXLab](https://openxlab.org.cn/apps/detail/PixArt-alpha/PixArt-alpha) or [Google Colab Demo](https://colab.research.google.com/drive/1jZ5UZXk7tcpTfVwnX33dDuefNMcnW9ME?usp=sharing).
23
+ """
24
+ if not torch.cuda.is_available():
25
+ DESCRIPTION += "\n<p>Running on CPU �� This demo does not work on CPU.</p>"
26
+
27
+ MAX_SEED = np.iinfo(np.int32).max
28
+ CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "1") == "1"
29
+ MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "2048"))
30
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
31
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
32
+ PORT = int(os.getenv("DEMO_PORT", "15432"))
33
+
34
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
35
+
36
+
37
+ style_list = [
38
+ {
39
+ "name": "(No style)",
40
+ "prompt": "{prompt}",
41
+ "negative_prompt": "",
42
+ },
43
+ {
44
+ "name": "Cinematic",
45
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
46
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
47
+ },
48
+ {
49
+ "name": "Photographic",
50
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
51
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
52
+ },
53
+ {
54
+ "name": "Anime",
55
+ "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed",
56
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
57
+ },
58
+ {
59
+ "name": "Manga",
60
+ "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style",
61
+ "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style",
62
+ },
63
+ {
64
+ "name": "Digital Art",
65
+ "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed",
66
+ "negative_prompt": "photo, photorealistic, realism, ugly",
67
+ },
68
+ {
69
+ "name": "Pixel art",
70
+ "prompt": "pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics",
71
+ "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic",
72
+ },
73
+ {
74
+ "name": "Fantasy art",
75
+ "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy",
76
+ "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white",
77
+ },
78
+ {
79
+ "name": "Neonpunk",
80
+ "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional",
81
+ "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured",
82
+ },
83
+ {
84
+ "name": "3D Model",
85
+ "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting",
86
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
87
+ },
88
+ ]
89
+
90
+
91
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
92
+ STYLE_NAMES = list(styles.keys())
93
+ DEFAULT_STYLE_NAME = "(No style)"
94
+ NUM_IMAGES_PER_PROMPT = 1
95
+
96
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
97
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
98
+ if not negative:
99
+ negative = ""
100
+ return p.replace("{prompt}", positive), n + negative
101
+
102
+
103
+ if torch.cuda.is_available():
104
+
105
+ pipe = PixArtAlphaPipeline.from_pretrained(
106
+ # "PixArt-alpha/PixArt-LCM-XL-2-1024-MS",
107
+ 'output_cv/pixartlcm-xl2-img1024_ft_singlebr_MJ1-5filter_vae_lr2e5_ema80/checkpoints/epoch_1_step_1600_diffusers',
108
+ torch_dtype=torch.float16,
109
+ use_safetensors=True,
110
+ )
111
+
112
+ if os.getenv('CONSISTENCY_DECODER', False):
113
+ print("Using DALL-E 3 Consistency Decoder")
114
+ pipe.vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16)
115
+
116
+ if ENABLE_CPU_OFFLOAD:
117
+ pipe.enable_model_cpu_offload()
118
+ else:
119
+ pipe.to(device)
120
+ print("Loaded on Device!")
121
+
122
+ # speed-up T5
123
+ pipe.text_encoder.to_bettertransformer()
124
+
125
+ if USE_TORCH_COMPILE:
126
+ pipe.transformer = torch.compile(pipe.transformer, mode="reduce-overhead", fullgraph=True)
127
+ print("Model Compiled!")
128
+
129
+
130
+ def save_image(img):
131
+ unique_name = str(uuid.uuid4()) + '.png'
132
+ save_path = os.path.join(f'output/online_demo_img/{datetime.now().date()}')
133
+ os.makedirs(save_path, exist_ok=True)
134
+ unique_name = os.path.join(save_path, unique_name)
135
+ img.save(unique_name)
136
+ return unique_name
137
+
138
+
139
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
140
+ if randomize_seed:
141
+ seed = random.randint(0, MAX_SEED)
142
+ return seed
143
+
144
+
145
+ def generate(
146
+ prompt: str,
147
+ negative_prompt: str = "",
148
+ style: str = DEFAULT_STYLE_NAME,
149
+ use_negative_prompt: bool = False,
150
+ seed: int = 0,
151
+ width: int = 1024,
152
+ height: int = 1024,
153
+ inference_steps: int = 4,
154
+ randomize_seed: bool = False,
155
+ use_resolution_binning: bool = True,
156
+ progress=gr.Progress(track_tqdm=True),
157
+ ):
158
+ seed = int(randomize_seed_fn(seed, randomize_seed))
159
+ generator = torch.Generator().manual_seed(seed)
160
+
161
+ if not use_negative_prompt:
162
+ negative_prompt = None # type: ignore
163
+ prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
164
+
165
+ images = pipe(
166
+ prompt=prompt,
167
+ width=width,
168
+ height=height,
169
+ guidance_scale=0.,
170
+ num_inference_steps=inference_steps,
171
+ generator=generator,
172
+ num_images_per_prompt=NUM_IMAGES_PER_PROMPT,
173
+ use_resolution_binning=use_resolution_binning,
174
+ output_type="pil",
175
+ ).images
176
+
177
+ image_paths = [save_image(img) for img in images]
178
+ print(image_paths)
179
+ return image_paths, seed
180
+
181
+
182
+ examples = [
183
+ "A small cactus with a happy face in the Sahara desert.",
184
+ "an astronaut sitting in a diner, eating fries, cinematic, analog film",
185
+ "Pirate ship trapped in a cosmic maelstrom nebula, rendered in cosmic beach whirlpool engine, volumetric lighting, spectacular, ambient lights, light pollution, cinematic atmosphere, art nouveau style, illustration art artwork by SenseiJaye, intricate detail.",
186
+ "stars, water, brilliantly, gorgeous large scale scene, a little girl, in the style of dreamy realism, light gold and amber, blue and pink, brilliantly illuminated in the background.",
187
+ "professional portrait photo of an anthropomorphic cat wearing fancy gentleman hat and jacket walking in autumn forest.",
188
+ "beautiful lady, freckles, big smile, blue eyes, short ginger hair, dark makeup, wearing a floral blue vest top, soft light, dark grey background",
189
+ "Spectacular Tiny World in the Transparent Jar On the Table, interior of the Great Hall, Elaborate, Carved Architecture, Anatomy, Symetrical, Geometric and Parameteric Details, Precision Flat line Details, Pattern, Dark fantasy, Dark errie mood and ineffably mysterious mood, Technical design, Intricate Ultra Detail, Ornate Detail, Stylized and Futuristic and Biomorphic Details, Architectural Concept, Low contrast Details, Cinematic Lighting, 8k, by moebius, Fullshot, Epic, Fullshot, Octane render, Unreal ,Photorealistic, Hyperrealism",
190
+ "anthropomorphic profile of the white snow owl Crystal priestess , art deco painting, pretty and expressive eyes, ornate costume, mythical, ethereal, intricate, elaborate, hyperrealism, hyper detailed, 3D, 8K, Ultra Realistic, high octane, ultra resolution, amazing detail, perfection, In frame, photorealistic, cinematic lighting, visual clarity, shading , Lumen Reflections, Super-Resolution, gigapixel, color grading, retouch, enhanced, PBR, Blender, V-ray, Procreate, zBrush, Unreal Engine 5, cinematic, volumetric, dramatic, neon lighting, wide angle lens ,no digital painting blur",
191
+ "The parametric hotel lobby is a sleek and modern space with plenty of natural light. The lobby is spacious and open with a variety of seating options. The front desk is a sleek white counter with a parametric design. The walls are a light blue color with parametric patterns. The floor is a light wood color with a parametric design. There are plenty of plants and flowers throughout the space. The overall effect is a calm and relaxing space. occlusion, moody, sunset, concept art, octane rendering, 8k, highly detailed, concept art, highly detailed, beautiful scenery, cinematic, beautiful light, hyperreal, octane render, hdr, long exposure, 8K, realistic, fog, moody, fire and explosions, smoke, 50mm f2.8",
192
+ ]
193
+
194
+ with gr.Blocks(css="scripts/style.css") as demo:
195
+ gr.Markdown(DESCRIPTION)
196
+ gr.DuplicateButton(
197
+ value="Duplicate Space for private use",
198
+ elem_id="duplicate-button",
199
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
200
+ )
201
+ with gr.Group():
202
+ with gr.Row():
203
+ prompt = gr.Text(
204
+ label="Prompt",
205
+ show_label=False,
206
+ max_lines=1,
207
+ placeholder="Enter your prompt",
208
+ container=False,
209
+ )
210
+ run_button = gr.Button("Run", scale=0)
211
+ result = gr.Gallery(label="Result", columns=NUM_IMAGES_PER_PROMPT, show_label=False)
212
+ with gr.Accordion("Advanced options", open=False):
213
+ with gr.Row():
214
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=False, visible=False)
215
+ style_selection = gr.Radio(
216
+ show_label=True,
217
+ container=True,
218
+ interactive=True,
219
+ choices=STYLE_NAMES,
220
+ value=DEFAULT_STYLE_NAME,
221
+ label="Image Style",
222
+ )
223
+ negative_prompt = gr.Text(
224
+ label="Negative prompt",
225
+ max_lines=1,
226
+ placeholder="Enter a negative prompt",
227
+ visible=False,
228
+ )
229
+ seed = gr.Slider(
230
+ label="Seed",
231
+ minimum=0,
232
+ maximum=MAX_SEED,
233
+ step=1,
234
+ value=0,
235
+ )
236
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
237
+ with gr.Row(visible=True):
238
+ width = gr.Slider(
239
+ label="Width",
240
+ minimum=256,
241
+ maximum=MAX_IMAGE_SIZE,
242
+ step=32,
243
+ value=1024,
244
+ )
245
+ height = gr.Slider(
246
+ label="Height",
247
+ minimum=256,
248
+ maximum=MAX_IMAGE_SIZE,
249
+ step=32,
250
+ value=1024,
251
+ )
252
+ with gr.Row():
253
+ inference_steps = gr.Slider(
254
+ label="LCM inference steps",
255
+ minimum=1,
256
+ maximum=30,
257
+ step=1,
258
+ value=4,
259
+ )
260
+ gr.Examples(
261
+ examples=examples,
262
+ inputs=prompt,
263
+ outputs=[result, seed],
264
+ fn=generate,
265
+ cache_examples=CACHE_EXAMPLES,
266
+ )
267
+
268
+ use_negative_prompt.change(
269
+ fn=lambda x: gr.update(visible=x),
270
+ inputs=use_negative_prompt,
271
+ outputs=negative_prompt,
272
+ api_name=False,
273
+ )
274
+
275
+ gr.on(
276
+ triggers=[
277
+ prompt.submit,
278
+ negative_prompt.submit,
279
+ run_button.click,
280
+ ],
281
+ fn=generate,
282
+ inputs=[
283
+ prompt,
284
+ negative_prompt,
285
+ style_selection,
286
+ use_negative_prompt,
287
+ seed,
288
+ width,
289
+ height,
290
+ inference_steps,
291
+ randomize_seed,
292
+ ],
293
+ outputs=[result, seed],
294
+ api_name="run",
295
+ )
296
+
297
+
298
+ if __name__ == "__main__":
299
+ demo.queue(max_size=20).launch()
pixart-lcm.png ADDED
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ git+https://github.com/huggingface/diffusers
2
+ accelerate
3
+ transformers
4
+ gradio==4.1.1
5
+ Pillow==10.1.0
6
+ sentencepiece==0.1.99
7
+ optimum
8
+ beautifulsoup4
9
+ ftfy
10
+ --extra-index-url https://download.pytorch.org/whl/cu118
11
+ torch==2.0.1
12
+
13
+
style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ .gradio-container{width:680px!important}