svjack commited on
Commit
6d16183
·
verified ·
1 Parent(s): da6ec9e

Upload caption_generator_ds.py

Browse files
Files changed (1) hide show
  1. caption_generator_ds.py +291 -0
caption_generator_ds.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ python caption_generator.py /path/to/input /path/to/output/directory --caption_type "Descriptive" --caption_length "long" --extra_options 0 2 5 --name_input "John"
3
+ '''
4
+ '''
5
+ python caption_generator_ds.py "svjack/Genshin-Impact-Portrait-with-Tags-Filtered-IID-Gender" \
6
+ --caption_column="joy-caption" \
7
+ --output_path="gen_single_cap_dir" \
8
+ --caption_type="Descriptive" \
9
+ --caption_length="long" \
10
+ --extra_options 0 2 5 \
11
+ --name_input="Traveler"
12
+ '''
13
+
14
+ import argparse
15
+ from pathlib import Path
16
+ import torch
17
+ from torch import nn
18
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
19
+ from datasets import load_dataset # 引入 Hugging Face Dataset
20
+ from PIL import Image
21
+ import torchvision.transforms.functional as TVF
22
+ from tqdm import tqdm # 引入 tqdm 用于显示进度条
23
+
24
+ # Constants
25
+ CLIP_PATH = "google/siglip-so400m-patch14-384"
26
+ CHECKPOINT_PATH = Path("cgrkzexw-599808")
27
+
28
+ # Extra options with IDs for easy selection
29
+ EXTRA_OPTIONS = [
30
+ "If there is a person/character in the image you must refer to them as {name}.",
31
+ "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
32
+ "Include information about lighting.",
33
+ "Include information about camera angle.",
34
+ "Include information about whether there is a watermark or not.",
35
+ "Include information about whether there are JPEG artifacts or not.",
36
+ "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
37
+ "Do NOT include anything sexual; keep it PG.",
38
+ "Do NOT mention the image's resolution.",
39
+ "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
40
+ "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
41
+ "Do NOT mention any text that is in the image.",
42
+ "Specify the depth of field and whether the background is in focus or blurred.",
43
+ "If applicable, mention the likely use of artificial or natural lighting sources.",
44
+ "Do NOT use any ambiguous language.",
45
+ "Include whether the image is sfw, suggestive, or nsfw.",
46
+ "ONLY describe the most important elements of the image."
47
+ ]
48
+
49
+ CAPTION_TYPE_MAP = {
50
+ "Descriptive": [
51
+ "Write a descriptive caption for this image in a formal tone.",
52
+ "Write a descriptive caption for this image in a formal tone within {word_count} words.",
53
+ "Write a {length} descriptive caption for this image in a formal tone.",
54
+ ],
55
+ "Descriptive (Informal)": [
56
+ "Write a descriptive caption for this image in a casual tone.",
57
+ "Write a descriptive caption for this image in a casual tone within {word_count} words.",
58
+ "Write a {length} descriptive caption for this image in a casual tone.",
59
+ ],
60
+ "Training Prompt": [
61
+ "Write a stable diffusion prompt for this image.",
62
+ "Write a stable diffusion prompt for this image within {word_count} words.",
63
+ "Write a {length} stable diffusion prompt for this image.",
64
+ ],
65
+ "MidJourney": [
66
+ "Write a MidJourney prompt for this image.",
67
+ "Write a MidJourney prompt for this image within {word_count} words.",
68
+ "Write a {length} MidJourney prompt for this image.",
69
+ ],
70
+ "Booru tag list": [
71
+ "Write a list of Booru tags for this image.",
72
+ "Write a list of Booru tags for this image within {word_count} words.",
73
+ "Write a {length} list of Booru tags for this image.",
74
+ ],
75
+ "Booru-like tag list": [
76
+ "Write a list of Booru-like tags for this image.",
77
+ "Write a list of Booru-like tags for this image within {word_count} words.",
78
+ "Write a {length} list of Booru-like tags for this image.",
79
+ ],
80
+ "Art Critic": [
81
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
82
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
83
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
84
+ ],
85
+ "Product Listing": [
86
+ "Write a caption for this image as though it were a product listing.",
87
+ "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
88
+ "Write a {length} caption for this image as though it were a product listing.",
89
+ ],
90
+ "Social Media Post": [
91
+ "Write a caption for this image as if it were being used for a social media post.",
92
+ "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
93
+ "Write a {length} caption for this image as if it were being used for a social media post.",
94
+ ],
95
+ }
96
+
97
+ # Image Adapter
98
+ class ImageAdapter(nn.Module):
99
+ def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
100
+ super().__init__()
101
+ self.deep_extract = deep_extract
102
+ if self.deep_extract:
103
+ input_features = input_features * 5
104
+ self.linear1 = nn.Linear(input_features, output_features)
105
+ self.activation = nn.GELU()
106
+ self.linear2 = nn.Linear(output_features, output_features)
107
+ self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
108
+ self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
109
+ self.other_tokens = nn.Embedding(3, output_features)
110
+ self.other_tokens.weight.data.normal_(mean=0.0, std=0.02)
111
+
112
+ def forward(self, vision_outputs: torch.Tensor):
113
+ if self.deep_extract:
114
+ x = torch.concat((vision_outputs[-2], vision_outputs[3], vision_outputs[7], vision_outputs[13], vision_outputs[20]), dim=-1)
115
+ else:
116
+ x = vision_outputs[-2]
117
+ x = self.ln1(x)
118
+ if self.pos_emb is not None:
119
+ x = x + self.pos_emb
120
+ x = self.linear1(x)
121
+ x = self.activation(x)
122
+ x = self.linear2(x)
123
+ other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
124
+ x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
125
+ return x
126
+
127
+ def get_eot_embedding(self):
128
+ return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
129
+
130
+ # Load models
131
+ def load_models():
132
+ print("Loading CLIP")
133
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
134
+ clip_model = AutoModel.from_pretrained(CLIP_PATH)
135
+ clip_model = clip_model.vision_model
136
+ checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu')
137
+ checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
138
+ clip_model.load_state_dict(checkpoint)
139
+ clip_model.eval()
140
+ clip_model.requires_grad_(False)
141
+ clip_model.to("cuda")
142
+
143
+ print("Loading tokenizer")
144
+ tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
145
+
146
+ print("Loading LLM")
147
+ text_model = AutoModelForCausalLM.from_pretrained(CHECKPOINT_PATH / "text_model", device_map=0, torch_dtype=torch.bfloat16)
148
+ text_model.eval()
149
+
150
+ print("Loading image adapter")
151
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False)
152
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
153
+ image_adapter.eval()
154
+ image_adapter.to("cuda")
155
+
156
+ return clip_processor, clip_model, tokenizer, text_model, image_adapter
157
+
158
+ # Generate caption
159
+ @torch.no_grad()
160
+ def generate_caption(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str, clip_processor, clip_model, tokenizer, text_model, image_adapter):
161
+ torch.cuda.empty_cache()
162
+
163
+ # Build prompt
164
+ length = None if caption_length == "any" else caption_length
165
+ if isinstance(length, str):
166
+ try:
167
+ length = int(length)
168
+ except ValueError:
169
+ pass
170
+ map_idx = 0 if length is None else 1 if isinstance(length, int) else 2
171
+ prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
172
+
173
+ if len(extra_options) > 0:
174
+ prompt_str += " " + " ".join(extra_options)
175
+ prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
176
+
177
+ if custom_prompt.strip() != "":
178
+ prompt_str = custom_prompt.strip()
179
+
180
+ # Preprocess image
181
+ image = input_image.resize((384, 384), Image.LANCZOS)
182
+ pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
183
+ pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
184
+ pixel_values = pixel_values.to('cuda')
185
+
186
+ # Embed image
187
+ with torch.amp.autocast_mode.autocast('cuda', enabled=True):
188
+ vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
189
+ embedded_images = image_adapter(vision_outputs.hidden_states)
190
+ embedded_images = embedded_images.to('cuda')
191
+
192
+ # Build conversation
193
+ convo = [
194
+ {"role": "system", "content": "You are a helpful image captioner."},
195
+ {"role": "user", "content": prompt_str},
196
+ ]
197
+ convo_string = tokenizer.apply_chat_template(convo, tokenize=False, add_generation_prompt=True)
198
+ convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
199
+ prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
200
+ convo_tokens = convo_tokens.squeeze(0)
201
+ prompt_tokens = prompt_tokens.squeeze(0)
202
+
203
+ # Calculate where to inject the image
204
+ eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
205
+ preamble_len = eot_id_indices[1] - prompt_tokens.shape[0]
206
+
207
+ # Embed the tokens
208
+ convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to('cuda'))
209
+
210
+ # Construct the input
211
+ input_embeds = torch.cat([
212
+ convo_embeds[:, :preamble_len],
213
+ embedded_images.to(dtype=convo_embeds.dtype),
214
+ convo_embeds[:, preamble_len:],
215
+ ], dim=1).to('cuda')
216
+
217
+ input_ids = torch.cat([
218
+ convo_tokens[:preamble_len].unsqueeze(0),
219
+ torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
220
+ convo_tokens[preamble_len:].unsqueeze(0),
221
+ ], dim=1).to('cuda')
222
+ attention_mask = torch.ones_like(input_ids)
223
+
224
+ # Generate caption
225
+ generate_ids = text_model.generate(input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, suppress_tokens=None)
226
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
227
+ if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
228
+ generate_ids = generate_ids[:, :-1]
229
+ caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
230
+
231
+ return prompt_str, caption.strip()
232
+
233
+ # Main function
234
+ def main():
235
+ parser = argparse.ArgumentParser(description="Generate captions for images in a Hugging Face Dataset.")
236
+ parser.add_argument("dataset_name", type=str, help="Name of the Hugging Face Dataset")
237
+ parser.add_argument("--image_column", type=str, default="image", help="Name of the column containing images (default: 'image')")
238
+ parser.add_argument("--caption_column", type=str, default="caption", help="Name of the column to save captions (default: 'caption')")
239
+ parser.add_argument("--caption_type", type=str, default="Descriptive", choices=CAPTION_TYPE_MAP.keys(), help="Type of caption to generate")
240
+ parser.add_argument("--caption_length", type=str, default="long", help="Length of the caption")
241
+ parser.add_argument("--extra_options", nargs="*", type=int, default=[], help="Extra options for caption generation (provide IDs separated by spaces)")
242
+ parser.add_argument("--name_input", type=str, default="", help="Name of the person/character in the image (if applicable)")
243
+ parser.add_argument("--custom_prompt", type=str, default="", help="Custom prompt to override default settings")
244
+ parser.add_argument("--output_path", type=str, required=True, help="Path to save the dataset with captions")
245
+ args = parser.parse_args()
246
+
247
+ # Map extra option IDs to their corresponding strings
248
+ selected_extra_options = [EXTRA_OPTIONS[i] for i in args.extra_options]
249
+
250
+ # Load models
251
+ clip_processor, clip_model, tokenizer, text_model, image_adapter = load_models()
252
+
253
+ # Load dataset
254
+ print(f"Loading dataset: {args.dataset_name}")
255
+ dataset = load_dataset(args.dataset_name)
256
+ len_ = len(dataset["train"])
257
+ len_ = 10
258
+
259
+ # Initialize a list to store captions
260
+ captions = []
261
+
262
+ # Generate captions for each image in the dataset
263
+ print("Generating captions...")
264
+ for idx, example in enumerate(tqdm(dataset["train"].select(range(len_)), desc="Processing images")):
265
+ try:
266
+ # Generate caption
267
+ prompt_str, caption = generate_caption(example[args.image_column], args.caption_type, args.caption_length, selected_extra_options, args.name_input, args.custom_prompt, clip_processor, clip_model, tokenizer, text_model, image_adapter)
268
+ captions.append(caption)
269
+ # Print the generated caption
270
+ print(f"Caption for image {idx + 1}: {caption}")
271
+ except Exception as e:
272
+ print(f"Error processing image {idx + 1}: {e}")
273
+ captions.append("") # 如果出错,保存空字符串
274
+ print(f"Caption for image {idx + 1}: [Error]")
275
+
276
+ # Add captions to the dataset
277
+ print("Adding captions to the dataset...")
278
+ dataset = dataset["train"].select(range(len_)).add_column(args.caption_column, captions) # 将 captions 添加到数据集
279
+
280
+ # Save the dataset with captions
281
+ print(f"Saving dataset to {args.output_path}")
282
+ dataset.save_to_disk(args.output_path)
283
+
284
+ print("Done!")
285
+
286
+ if __name__ == "__main__":
287
+ # Print extra options with IDs for reference
288
+ print("Extra Options:")
289
+ for i, option in enumerate(EXTRA_OPTIONS):
290
+ print(f"{i}: {option}")
291
+ main()