patrickvonplaten commited on
Commit
b1e31fd
·
2 Parent(s): 86171b9 8cfdc75

Merge branch 'main' of https://huggingface.co/diffusers/tools

Browse files
Files changed (2) hide show
  1. controlnet_img2img.py +77 -0
  2. parti_prompts.py +26 -19
controlnet_img2img.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+ import os
4
+ from huggingface_hub import HfApi
5
+ from pathlib import Path
6
+ from diffusers.utils import load_image
7
+ import cv2
8
+ from PIL import Image
9
+ import numpy as np
10
+
11
+ from diffusers import (
12
+ ControlNetModel,
13
+ StableDiffusionControlNetImg2ImgPipeline,
14
+ StableDiffusionControlNetInpaintPipeline,
15
+ DiffusionPipeline,
16
+ UniPCMultistepScheduler,
17
+ )
18
+ import sys
19
+
20
+ checkpoint = sys.argv[1]
21
+
22
+ # image = load_image(
23
+ # "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png"
24
+ # )
25
+
26
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
27
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
28
+ image = load_image(img_url).resize((512, 512))
29
+ mask_image = load_image(mask_url).resize((512, 512))
30
+
31
+ np_image = np.array(image)
32
+
33
+ low_threshold = 100
34
+ high_threshold = 200
35
+
36
+ np_image = cv2.Canny(np_image, low_threshold, high_threshold)
37
+ np_image = np_image[:, :, None]
38
+ np_image = np.concatenate([np_image, np_image, np_image], axis=2)
39
+ canny_image = Image.fromarray(np_image)
40
+
41
+ controlnet = ControlNetModel.from_pretrained(checkpoint, torch_dtype=torch.float16)
42
+ # pipe = DiffusionPipeline.from_pretrained(
43
+ # "runwayml/stable-diffusion-inpainting", controlnet=controlnet, torch_dtype=torch.float16, custom_pipeline="stable_diffusion_controlnet_inpaint"
44
+ # )
45
+ pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
46
+ "runwayml/stable-diffusion-inpainting",
47
+ controlnet=controlnet,
48
+ torch_dtype=torch.float16,
49
+ )
50
+
51
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
52
+ pipe.enable_model_cpu_offload()
53
+
54
+ generator = torch.manual_seed(0)
55
+ text_prompt="a blue dog"
56
+ # out_image = pipe("A blue dog", num_inference_steps=50, generator=generator, image=image, mask_image=mask_image, controlnet_conditioning_image=canny_image).images[0]
57
+ out_image = pipe(
58
+ text_prompt,
59
+ num_inference_steps=20,
60
+ generator=generator,
61
+ image=image,
62
+ mask_image=mask_image,
63
+ control_image=canny_image,
64
+ ).images[0]
65
+
66
+ path = os.path.join(Path.home(), "images", "aa.png")
67
+ out_image.save(path)
68
+
69
+ api = HfApi()
70
+
71
+ api.upload_file(
72
+ path_or_fileobj=path,
73
+ path_in_repo=path.split("/")[-1],
74
+ repo_id="patrickvonplaten/images",
75
+ repo_type="dataset",
76
+ )
77
+ print("https://huggingface.co/datasets/patrickvonplaten/images/blob/main/aa.png")
parti_prompts.py CHANGED
@@ -1,6 +1,7 @@
1
  #!/usr/bin/env python3
2
  from diffusers import DiffusionPipeline, DDIMScheduler
3
  import argparse
 
4
  import torch
5
  from datasets import load_dataset
6
  import PIL
@@ -12,12 +13,12 @@ def resize(image: PIL.Image):
12
  return image.resize(IMAGE_OUTPUT_SIZE, resample=PIL.Image.Resampling.LANCZOS)
13
 
14
  def get_sd_eval(ckpt, guidance_scale=7.5):
15
- pipe = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=torch.float16)
16
  pipe.to("cuda")
17
- pipe.scheduler = DDIMScheduler.from_config(pipe.config)
18
 
19
- def sd_eval(prompt):
20
- images = pipe(prompt, num_inference_steps=100, guidance_scale=guidance_scale).images
21
  images = [resize(image) for image in images]
22
  return images
23
 
@@ -28,28 +29,29 @@ def get_karlo_eval(ckpt):
28
  pipe.to("cuda")
29
 
30
  def karlo_eval(prompt):
31
- images = pipe(prompt, prior_num_inference_steps=50, decoder_num_inference_steps=100).images
32
  return images
33
 
34
  return karlo_eval
35
 
36
  def get_if_eval(ckpt):
37
- pipe_low = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=torch.float16)
38
  pipe_low.enable_model_cpu_offload()
39
 
40
- pipe_up = DiffusionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0", text_encoder=pipe_low.text_encoder, torch_dtype=torch.float16)
41
  pipe_up.enable_model_cpu_offload()
42
 
43
- def sd_eval(prompt):
44
- images = pipe_low(prompt, num_inference_steps=100, output_type="pt").images
45
- images = pipe_up(promtp=prompt, images=images, num_inference_steps=100).images
 
46
  return images
47
 
48
- return sd_eval
49
 
50
  MODELS = {
51
  "runwayml/stable-diffusion-v1-5": get_sd_eval,
52
- "stabilityai/stable-diffusion-v2-1": get_sd_eval,
53
  "kakaobrain/karlo-alpha": get_karlo_eval,
54
  "DeepFloyd/IF-I-XL-v1.0": get_if_eval,
55
  }
@@ -59,24 +61,29 @@ MODELS = {
59
 
60
  if __name__ == "__main__":
61
  parser = argparse.ArgumentParser(description='Run Parti Prompt Evaluation')
62
- parser.add_argument('model_repo_or_id', type=str, help='ID or URL of the model repository.', required=True)
63
  parser.add_argument('--dataset_repo_or_id', type=str, default='diffusers/prompt_generations', help='ID or URL of the dataset repository (default: "diffusers/prompt_generations")')
64
  parser.add_argument('--batch_size', type=int, default=8, help="Batch size for the eval function")
65
  parser.add_argument('--upload_to_hub', action='store_true', help='whether to upload the dataset to the Hugging Face dataset hub')
 
66
 
67
  args = parser.parse_args()
68
 
69
- eval_fn = MODELS[args.model_repo_or_id](args.model_repo_or_id)
 
70
 
71
- dataset = load_dataset("nateraw/parti-prompts")
72
 
73
  def map_fn(batch):
74
- batch["images"] = eval_fn(batch["prompt"])
 
 
 
75
  return batch
76
 
77
- dataset_images = dataset.map(map_fn, batched=True, batch_size=8)
78
 
79
  if args.upload_to_hub:
80
- dataset.push_to_hub(args.dataset_repo_or_id)
81
  else:
82
- dataset.save_to_disk(args.dataset_repo_or_id.split("/")[-1])
 
1
  #!/usr/bin/env python3
2
  from diffusers import DiffusionPipeline, DDIMScheduler
3
  import argparse
4
+ from diffusers.pipelines.stable_diffusion import safety_checker
5
  import torch
6
  from datasets import load_dataset
7
  import PIL
 
13
  return image.resize(IMAGE_OUTPUT_SIZE, resample=PIL.Image.Resampling.LANCZOS)
14
 
15
  def get_sd_eval(ckpt, guidance_scale=7.5):
16
+ pipe = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=torch.float16, safety_checker=None)
17
  pipe.to("cuda")
18
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
19
 
20
+ def sd_eval(prompt, generator=None):
21
+ images = pipe(prompt, generator=generator, num_inference_steps=NUM_INFERENCE_STEPS, guidance_scale=guidance_scale).images
22
  images = [resize(image) for image in images]
23
  return images
24
 
 
29
  pipe.to("cuda")
30
 
31
  def karlo_eval(prompt):
32
+ images = pipe(prompt, prior_num_inference_steps=50, decoder_num_inference_steps=NUM_INFERENCE_STEPS).images
33
  return images
34
 
35
  return karlo_eval
36
 
37
  def get_if_eval(ckpt):
38
+ pipe_low = DiffusionPipeline.from_pretrained(ckpt, safety_checker=None, watermarker=None, torch_dtype=torch.float16, variant="fp16")
39
  pipe_low.enable_model_cpu_offload()
40
 
41
+ pipe_up = DiffusionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0", safety_checker=None, watermarker=None, text_encoder=pipe_low.text_encoder, torch_dtype=torch.float16, variant="fp16")
42
  pipe_up.enable_model_cpu_offload()
43
 
44
+ def if_eval(prompt, generator=None):
45
+ prompt_embeds, negative_prompt_embeds = pipe_low.encode_prompt(prompt)
46
+ images = pipe_low(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=NUM_INFERENCE_STEPS, generator=generator, output_type="pt").images
47
+ images = pipe_up(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, image=images, num_inference_steps=NUM_INFERENCE_STEPS, generator=generator).images
48
  return images
49
 
50
+ return if_eval
51
 
52
  MODELS = {
53
  "runwayml/stable-diffusion-v1-5": get_sd_eval,
54
+ "stabilityai/stable-diffusion-2-1": get_sd_eval,
55
  "kakaobrain/karlo-alpha": get_karlo_eval,
56
  "DeepFloyd/IF-I-XL-v1.0": get_if_eval,
57
  }
 
61
 
62
  if __name__ == "__main__":
63
  parser = argparse.ArgumentParser(description='Run Parti Prompt Evaluation')
64
+ parser.add_argument('model_repo_or_id', type=str, help='ID or URL of the model repository.')
65
  parser.add_argument('--dataset_repo_or_id', type=str, default='diffusers/prompt_generations', help='ID or URL of the dataset repository (default: "diffusers/prompt_generations")')
66
  parser.add_argument('--batch_size', type=int, default=8, help="Batch size for the eval function")
67
  parser.add_argument('--upload_to_hub', action='store_true', help='whether to upload the dataset to the Hugging Face dataset hub')
68
+ parser.add_argument('--seed', type=int, default=0, help='Random seed')
69
 
70
  args = parser.parse_args()
71
 
72
+ dataset = load_dataset("nateraw/parti-prompts")["train"]
73
+ # dataset = dataset.select(range(4))
74
 
75
+ eval_fn = MODELS[args.model_repo_or_id](args.model_repo_or_id)
76
 
77
  def map_fn(batch):
78
+ generators = [torch.Generator(device="cuda").manual_seed(args.seed) for _ in range(args.batch_size)]
79
+ batch["images"] = eval_fn(batch["Prompt"], generator=generators)
80
+ batch["model_name"] = len(batch["images"]) * [args.model_repo_or_id]
81
+ batch["seed"] = len(batch["images"]) * [args.seed]
82
  return batch
83
 
84
+ dataset_images = dataset.map(map_fn, batched=True, batch_size=args.batch_size)
85
 
86
  if args.upload_to_hub:
87
+ dataset_images.push_to_hub(args.dataset_repo_or_id)
88
  else:
89
+ dataset_images.save_to_disk(args.dataset_repo_or_id.split("/")[-1])