-
Notifications
You must be signed in to change notification settings - Fork 0
/
text_to_image.py
135 lines (117 loc) · 3.55 KB
/
text_to_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import csv
import json
import os
import random
from argparse import ArgumentParser, Namespace
from pathlib import Path
import torch
from diffusers import EulerDiscreteScheduler, StableDiffusionPipeline
from tqdm import tqdm
def set_seed(seed):
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def generate_valid_image(
pipe,
num_inference_steps,
prompt,
image_path,
seed
):
valid_image = False
while not valid_image:
set_seed(seed)
output = pipe(prompt, num_inference_steps=num_inference_steps)
image = output.images[0]
nsfw_content_detected = output.nsfw_content_detected
if not nsfw_content_detected:
valid_image = True
image.save(image_path)
seed += 1
def main(args):
device = args.device
num_inference_steps = args.num_inference_steps
scheduler = EulerDiscreteScheduler.from_pretrained(args.model_id,
subfolder="scheduler")
pipe = StableDiffusionPipeline.from_pretrained(args.model_id,
scheduler=scheduler,
revision="fp16",
torch_dtype=torch.float16)
pipe = pipe.to(device)
with open(args.prompt_json_path, encoding="utf-8") as f:
prompt_jsons = [json.loads(line) for line in f.readlines()]
data = {}
for idx, prompt_json in tqdm(enumerate(prompt_jsons), desc="Generate images"):
prompt = ' '.join(prompt_json["sentence"][:-1]) + '.'
ner = prompt_json["ner"]
start, end, label = ner
image_path = f"{args.output_image_dir}/{idx}.png"
if not os.path.isfile(image_path):
generate_valid_image(pipe, num_inference_steps, prompt, image_path, args.seed)
data[idx] = {
"sentence": prompt_json["sentence"],
"start": start,
"end": end,
"label": label,
"image_path": image_path
}
with open(args.data_json_path, 'w+') as f:
json.dump(data, f, indent=4)
def parse_args():
parser = ArgumentParser()
parser.add_argument(
"-p",
"--prompt_json_path",
type=Path,
help="Path to the text data.",
default="./prompt.json",
)
parser.add_argument(
"-m",
"--model_id",
type=str,
help="Pretrain model name.",
default="stabilityai/stable-diffusion-2-base",
)
parser.add_argument(
"-o",
"--output_image_dir",
type=Path,
help="Directory to the output images.",
default="./image_root",
)
parser.add_argument(
"-s",
"--seed",
type=int,
help="random seed",
default=48763
)
parser.add_argument(
"-d",
"--device",
type=torch.device,
help="cpu, cuda, cuda:0, cuda:1",
default="cuda"
)
parser.add_argument(
"-n",
"--num_inference_steps",
type=int,
default=50
)
parser.add_argument(
"--data_json_path",
type=Path,
default="./data.json"
)
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
args.output_image_dir.mkdir(exist_ok=True, parents=True)
main(args)