charliebaby2023 commited on
Commit
3c2f74e
·
verified ·
1 Parent(s): b9c41a1

Update app_demo.py

Browse files
Files changed (1) hide show
  1. app_demo.py +42 -147
app_demo.py CHANGED
@@ -17,123 +17,59 @@ from tqdm import tqdm
17
  from safetensors.torch import load_file
18
  import cv2
19
 
20
-
21
-
22
-
23
-
24
- #DESCRIPTION = '''# Fast Stable Diffusion CPU with Latent Consistency Model
25
- #Distilled from [Dreamshaper v7](https://huggingface.co/Lykon/dreamshaper-7) fine‑tune of SD v1-5.
26
- #'''
27
- #if not torch.cuda.is_available():
28
- #DESCRIPTION += "\n<p>running on CPU.</p>"
29
  MAX_SEED = np.iinfo(np.int32).max
30
  CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES") == "1"
31
  MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "768"))
32
  USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE") == "1"
33
- DTYPE = torch.float32 # torch.float16 works as well, but pictures seem to be a bit worse
34
  api = HfApi()
35
  executor = ThreadPoolExecutor()
36
  model_cache = {}
37
 
38
- #custom
39
  model_id = "Lykon/dreamshaper-xl-v2-turbo"
40
  custom_pipe = DiffusionPipeline.from_pretrained(model_id, custom_pipeline="latent_consistency_txt2img", custom_revision="main")
41
- #1st
42
  pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7", custom_pipeline="latent_consistency_txt2img", custom_revision="main")
43
  pipe.to(torch_device="cpu", torch_dtype=DTYPE)
44
  pipe.safety_checker = None
45
-
46
- # Load pipeline once, disabling NSFW filter at construction time
47
  pipe = StableDiffusionPipeline.from_pretrained(
48
- model_id, safety_checker=None, torch_dtype=DTYPE, use_safetensors=True).to("cpu")
 
49
 
50
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
51
- if randomize_seed:
52
- seed = random.randint(0, MAX_SEED)
53
- return seed
54
 
55
  def save_image(img, profile: gr.OAuthProfile | None, metadata: dict):
56
  unique_name = str(uuid.uuid4()) + '.png'
57
  img.save(unique_name)
58
  gr_user_history.save_image(label=metadata["prompt"], image=img, profile=profile, metadata=metadata)
59
-
60
  return unique_name
61
 
62
- #def save_images(image_array, profile: gr.OAuthProfile | None, metadata: dict):
63
- # with ThreadPoolExecutor() as executor:
64
- # return list(executor.map(
65
- # lambda args: save_image(*args),
66
- # zip(image_array, [profile]*len(image_array), [metadata]*len(image_array))
67
- # ))
68
  def save_images(image_array, profile: gr.OAuthProfile | None, metadata: dict):
69
- paths = []
70
  with ThreadPoolExecutor() as executor:
71
- paths = list(executor.map(save_image, image_array, [profile]*len(image_array), [metadata]*len(image_array)))
72
- return paths
73
 
74
- def generate(
75
- prompt: str,
76
- seed: int = 0,
77
- width: int = 512,
78
- height: int = 512,
79
- guidance_scale: float = 8.0,
80
- num_inference_steps: int = 4,
81
- num_images: int = 1,
82
- randomize_seed: bool = False,
83
- progress = gr.Progress(track_tqdm=True),
84
- profile: gr.OAuthProfile | None = None,
85
- ) -> tuple[list[str], int]:
86
- # prepare seed
87
  seed = randomize_seed_fn(seed, randomize_seed)
88
  torch.manual_seed(seed)
89
  start_time = time.time()
90
- # **Call the pipeline with only supported kwargs:**
91
- outputs = pipe(
92
- prompt=prompt,
93
- negative_prompt="", # required to avoid NoneType in UNet
94
- height=height,
95
- width=width,
96
- guidance_scale=guidance_scale,
97
- num_inference_steps=num_inference_steps,
98
- num_images_per_prompt=num_images,
99
- output_type="pil",
100
- lcm_origin_steps=50,
101
- ).images
102
-
103
- latency = time.time() - start_time
104
- print(f"Generation took {latency:.2f} seconds")
105
-
106
- paths = save_images(
107
- outputs,
108
- profile,
109
- metadata={
110
- "prompt": prompt,
111
- "seed": seed,
112
- "width": width,
113
- "height": height,
114
- "guidance_scale": guidance_scale,
115
- "num_inference_steps": num_inference_steps,
116
- }
117
- )
118
-
119
  return paths, seed
120
 
121
 
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
  def validate_and_list_models(hfuser):
138
  try:
139
  models = api.list_models(author=hfuser)
@@ -141,6 +77,7 @@ def validate_and_list_models(hfuser):
141
  except Exception:
142
  return []
143
 
 
144
  def parse_user_model_dict(user_model_dict_str):
145
  try:
146
  data = ast.literal_eval(user_model_dict_str)
@@ -150,6 +87,7 @@ def parse_user_model_dict(user_model_dict_str):
150
  except Exception:
151
  return {}
152
 
 
153
  def load_model(model_id):
154
  if model_id in model_cache:
155
  return f"{model_id} loaded from cache"
@@ -160,24 +98,23 @@ def load_model(model_id):
160
  except Exception as e:
161
  return f"{model_id} failed to load: {str(e)}"
162
 
 
163
  def run_models(models, parallel):
164
  if parallel:
165
  futures = [executor.submit(load_model, m) for m in models]
166
  return [f.result() for f in futures]
167
- else:
168
- return [load_model(m) for m in models]
169
- #with gr.Blocks(css="style.css") as demo:
170
  with gr.Blocks() as demo:
171
- with gr.Row():
172
- gr.HTML(
173
- f"""
174
  <p id="project-links" align="center">
175
  <a href='https://huggingface.co/spaces/charliebaby2023/Fast_Stable_diffusion_CPU/edit/main/app_demo.py'>Edit this app_demo py file</a>
176
  <p> this is currently running the Lykon/dreamshaper-xl-v2-turbo model</p>
177
  <p><fast stable diffusion, CPU</p>
178
  </p>
179
- """
180
- )
181
  with gr.Column(scale=1):
182
  with gr.Row():
183
  hfuser_input = gr.Textbox(label="Hugging Face Username")
@@ -185,24 +122,18 @@ with gr.Blocks() as demo:
185
  user_model_dict = gr.Textbox(visible=False, label="Dict Input (e.g., {'username': ['model1', 'model2']})")
186
  with gr.Row():
187
  run_btn = gr.Button("Load Models")
188
- with gr.Column(scale=3):
189
  with gr.Row():
190
  parallel_toggle = gr.Checkbox(label="Load in Parallel", value=True)
191
- with gr.Row():
192
  output = gr.Textbox(label="Output", lines=3)
193
 
194
  def update_models(hfuser):
195
  if hfuser:
196
  models = validate_and_list_models(hfuser)
197
- label = f"Models found: {len(models)}"
198
- if len(models) > 0:
199
- return gr.update(choices=models, label=label, visible=True)
200
- else:
201
- return gr.update(choices=models, label=label, visible=False)
202
- else:
203
- models = ''
204
- label = ''
205
- return gr.update(choices=models, label=label, visible=False)
206
 
207
  def update_from_dict(dict_str):
208
  parsed = parse_user_model_dict(dict_str)
@@ -210,28 +141,18 @@ with gr.Blocks() as demo:
210
  return gr.update(), gr.update()
211
  hfuser = next(iter(parsed))
212
  models = parsed[hfuser]
213
- label = f"Models found: {len(models)}"
214
- return gr.update(value=hfuser), gr.update(choices=models, value=models, label=label)
215
- #return gr.update(value=hfuser), gr.update(choices=parsed[hfuser], value=parsed[hfuser])
216
 
217
  hfuser_input.change(update_models, hfuser_input, hfuser_models)
218
  user_model_dict.change(update_from_dict, user_model_dict, [hfuser_input, hfuser_models])
219
  run_btn.click(run_models, [hfuser_models, parallel_toggle], output)
220
 
221
-
222
-
223
  with gr.Group():
224
  with gr.Row():
225
- prompt = gr.Text(
226
- placeholder="Enter your prompt", show_label=False, container=False,
227
- )
228
  run_button = gr.Button("Run", scale=0)
229
- gallery = gr.Gallery(
230
- label="Generated images",
231
- show_label=False,
232
- elem_id="gallery"
233
-
234
- )
235
 
236
  with gr.Accordion("Advanced options", open=False):
237
  seed = gr.Slider(0, MAX_SEED, value=0, step=1, randomize=True, label="Seed")
@@ -244,34 +165,8 @@ with gr.Blocks() as demo:
244
  num_inference_steps = gr.Slider(1, 8, value=4, step=1, label="Inference Steps")
245
  num_images = gr.Slider(1, 8, value=1, step=1, label="Number of Images")
246
 
247
-
248
- with gr.Group():
249
- with gr.Row():
250
- prompt = gr.Text( label="Prompt", show_label=False, max_lines=1, placeholder="Enter your prompt", container=False, )
251
- run_button = gr.Button("Run", scale=0)
252
- result = gr.Gallery( label="Generated images", show_label=False, elem_id="gallery", grid=[2] )
253
- with gr.Accordion("Advanced options", open=False):
254
- seed = gr.Slider(label="Seed",minimum=0,maximum=MAX_SEED,step=1,value=0,randomize=True)
255
- randomize_seed = gr.Checkbox(label="Randomize seed across runs", value=True)
256
- with gr.Row():
257
- width = gr.Slider( label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=512, )
258
- height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=512,)
259
- with gr.Row():
260
- guidance_scale = gr.Slider(label="Guidance scale for base", minimum=2, maximum=14, step=0.1, value=8.0,)
261
- num_inference_steps = gr.Slider(label="Number of inference steps for base", minimum=1, maximum=8, step=1, value=4,)
262
- with gr.Row():
263
- num_images = gr.Slider(label="Number of images", minimum=1, maximum=8, step=1, value=1, visible=True,)
264
- with gr.Accordion("Past generations", open=False):
265
- gr_user_history.render()
266
-
267
- gr.on( triggers=[ prompt.submit, run_button.click, ],
268
  fn=generate,
269
- inputs=[prompt,seed,width,height,guidance_scale,num_inference_steps,num_images,randomize_seed ],
270
- outputs=[result, seed],
271
- api_name="run",
272
  )
273
-
274
- if __name__ == "__main__":
275
- demo.queue(api_open=False)
276
- demo.launch()
277
-
 
17
  from safetensors.torch import load_file
18
  import cv2
19
 
 
 
 
 
 
 
 
 
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES") == "1"
22
  MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "768"))
23
  USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE") == "1"
24
+ DTYPE = torch.float32
25
  api = HfApi()
26
  executor = ThreadPoolExecutor()
27
  model_cache = {}
28
 
 
29
  model_id = "Lykon/dreamshaper-xl-v2-turbo"
30
  custom_pipe = DiffusionPipeline.from_pretrained(model_id, custom_pipeline="latent_consistency_txt2img", custom_revision="main")
 
31
  pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7", custom_pipeline="latent_consistency_txt2img", custom_revision="main")
32
  pipe.to(torch_device="cpu", torch_dtype=DTYPE)
33
  pipe.safety_checker = None
 
 
34
  pipe = StableDiffusionPipeline.from_pretrained(
35
+ model_id, safety_checker=None, torch_dtype=DTYPE, use_safetensors=True).to("cpu")
36
+
37
 
38
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
39
+ return random.randint(0, MAX_SEED) if randomize_seed else seed
40
+
 
41
 
42
  def save_image(img, profile: gr.OAuthProfile | None, metadata: dict):
43
  unique_name = str(uuid.uuid4()) + '.png'
44
  img.save(unique_name)
45
  gr_user_history.save_image(label=metadata["prompt"], image=img, profile=profile, metadata=metadata)
 
46
  return unique_name
47
 
48
+
 
 
 
 
 
49
  def save_images(image_array, profile: gr.OAuthProfile | None, metadata: dict):
 
50
  with ThreadPoolExecutor() as executor:
51
+ return list(executor.map(save_image, image_array, [profile]*len(image_array), [metadata]*len(image_array)))
 
52
 
53
+
54
+ def generate(prompt: str, seed: int = 0, width: int = 512, height: int = 512,
55
+ guidance_scale: float = 8.0, num_inference_steps: int = 4,
56
+ num_images: int = 1, randomize_seed: bool = False,
57
+ progress=gr.Progress(track_tqdm=True),
58
+ profile: gr.OAuthProfile | None = None) -> tuple[list[str], int]:
 
 
 
 
 
 
 
59
  seed = randomize_seed_fn(seed, randomize_seed)
60
  torch.manual_seed(seed)
61
  start_time = time.time()
62
+ outputs = pipe(prompt=prompt, negative_prompt="", height=height, width=width,
63
+ guidance_scale=guidance_scale, num_inference_steps=num_inference_steps,
64
+ num_images_per_prompt=num_images, output_type="pil", lcm_origin_steps=50).images
65
+ print(f"Generation took {time.time() - start_time:.2f} seconds")
66
+ paths = save_images(outputs, profile, metadata={"prompt": prompt, "seed": seed,
67
+ "width": width, "height": height,
68
+ "guidance_scale": guidance_scale,
69
+ "num_inference_steps": num_inference_steps})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  return paths, seed
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def validate_and_list_models(hfuser):
74
  try:
75
  models = api.list_models(author=hfuser)
 
77
  except Exception:
78
  return []
79
 
80
+
81
  def parse_user_model_dict(user_model_dict_str):
82
  try:
83
  data = ast.literal_eval(user_model_dict_str)
 
87
  except Exception:
88
  return {}
89
 
90
+
91
  def load_model(model_id):
92
  if model_id in model_cache:
93
  return f"{model_id} loaded from cache"
 
98
  except Exception as e:
99
  return f"{model_id} failed to load: {str(e)}"
100
 
101
+
102
  def run_models(models, parallel):
103
  if parallel:
104
  futures = [executor.submit(load_model, m) for m in models]
105
  return [f.result() for f in futures]
106
+ return [load_model(m) for m in models]
107
+
108
+
109
  with gr.Blocks() as demo:
110
+ with gr.Row():
111
+ gr.HTML("""
 
112
  <p id="project-links" align="center">
113
  <a href='https://huggingface.co/spaces/charliebaby2023/Fast_Stable_diffusion_CPU/edit/main/app_demo.py'>Edit this app_demo py file</a>
114
  <p> this is currently running the Lykon/dreamshaper-xl-v2-turbo model</p>
115
  <p><fast stable diffusion, CPU</p>
116
  </p>
117
+ """)
 
118
  with gr.Column(scale=1):
119
  with gr.Row():
120
  hfuser_input = gr.Textbox(label="Hugging Face Username")
 
122
  user_model_dict = gr.Textbox(visible=False, label="Dict Input (e.g., {'username': ['model1', 'model2']})")
123
  with gr.Row():
124
  run_btn = gr.Button("Load Models")
125
+ with gr.Column(scale=3):
126
  with gr.Row():
127
  parallel_toggle = gr.Checkbox(label="Load in Parallel", value=True)
128
+ with gr.Row():
129
  output = gr.Textbox(label="Output", lines=3)
130
 
131
  def update_models(hfuser):
132
  if hfuser:
133
  models = validate_and_list_models(hfuser)
134
+ label = f"Models found: {len(models)}"
135
+ return gr.update(choices=models, label=label, visible=bool(models))
136
+ return gr.update(choices=[], label='', visible=False)
 
 
 
 
 
 
137
 
138
  def update_from_dict(dict_str):
139
  parsed = parse_user_model_dict(dict_str)
 
141
  return gr.update(), gr.update()
142
  hfuser = next(iter(parsed))
143
  models = parsed[hfuser]
144
+ label = f"Models found: {len(models)}"
145
+ return gr.update(value=hfuser), gr.update(choices=models, value=models, label=label)
 
146
 
147
  hfuser_input.change(update_models, hfuser_input, hfuser_models)
148
  user_model_dict.change(update_from_dict, user_model_dict, [hfuser_input, hfuser_models])
149
  run_btn.click(run_models, [hfuser_models, parallel_toggle], output)
150
 
 
 
151
  with gr.Group():
152
  with gr.Row():
153
+ prompt = gr.Text(placeholder="Enter your prompt", show_label=False, container=False)
 
 
154
  run_button = gr.Button("Run", scale=0)
155
+ gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery")
 
 
 
 
 
156
 
157
  with gr.Accordion("Advanced options", open=False):
158
  seed = gr.Slider(0, MAX_SEED, value=0, step=1, randomize=True, label="Seed")
 
165
  num_inference_steps = gr.Slider(1, 8, value=4, step=1, label="Inference Steps")
166
  num_images = gr.Slider(1, 8, value=1, step=1, label="Number of Images")
167
 
168
+ run_button.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  fn=generate,
170
+ inputs=[prompt, seed, width, height, guidance_scale, num_inference_steps, num_images, randomize_seed],
171
+ outputs=[gallery, seed]
 
172
  )