svjack commited on
Commit
958e49a
·
verified ·
1 Parent(s): 19e1ed1

Create caption_generator_name_ds.py

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