ChuuniZ commited on
Commit
40c6516
·
verified ·
1 Parent(s): 8870709

Upload Joy_caption/app.py

Browse files
Files changed (1) hide show
  1. Joy_caption/app.py +536 -0
Joy_caption/app.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.amp.autocast_mode
3
+ import os
4
+ import sys
5
+ import logging
6
+ import warnings
7
+ import argparse
8
+ from PIL import Image
9
+ from pathlib import Path
10
+ from tqdm import tqdm
11
+ from torch import nn
12
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
13
+ from typing import List, Union
14
+ import torchvision.transforms.functional as TVF
15
+ from peft import PeftModel
16
+ import gc
17
+ import sys
18
+ IS_COLAB = 'google.colab' in sys.modules
19
+
20
+ # Constants
21
+ IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
22
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
23
+ BASE_DIR = Path(__file__).resolve().parent # Define the base directory
24
+ CHECKPOINT_PATH = BASE_DIR / Path("cgrkzexw-599808")
25
+ CLIP_PATH = "google/siglip-so400m-patch14-384"
26
+ DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
27
+ #DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit" # Default in Alpha One Two.
28
+ #DEFAULT_MODEL_PATH = "Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2" # Works better but full weight.
29
+ LORA_PATH = CHECKPOINT_PATH / "text_model"
30
+ CAPTION_TYPE_MAP = {
31
+ "Descriptive": [
32
+ "Write a descriptive caption for this image in a formal tone.",
33
+ "Write a descriptive caption for this image in a formal tone within {word_count} words.",
34
+ "Write a {length} descriptive caption for this image in a formal tone.",
35
+ ],
36
+ "Descriptive (Informal)": [
37
+ "Write a descriptive caption for this image in a casual tone.",
38
+ "Write a descriptive caption for this image in a casual tone within {word_count} words.",
39
+ "Write a {length} descriptive caption for this image in a casual tone.",
40
+ ],
41
+ "Training Prompt": [
42
+ "Write a stable diffusion prompt for this image.",
43
+ "Write a stable diffusion prompt for this image within {word_count} words.",
44
+ "Write a {length} stable diffusion prompt for this image.",
45
+ ],
46
+ "MidJourney": [
47
+ "Write a MidJourney prompt for this image.",
48
+ "Write a MidJourney prompt for this image within {word_count} words.",
49
+ "Write a {length} MidJourney prompt for this image.",
50
+ ],
51
+ "Booru tag list": [
52
+ "Write a list of Booru tags for this image.",
53
+ "Write a list of Booru tags for this image within {word_count} words.",
54
+ "Write a {length} list of Booru tags for this image.",
55
+ ],
56
+ "Booru-like tag list": [
57
+ "Write a list of Booru-like tags for this image.",
58
+ "Write a list of Booru-like tags for this image within {word_count} words.",
59
+ "Write a {length} list of Booru-like tags for this image.",
60
+ ],
61
+ "Art Critic": [
62
+ "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.",
63
+ "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.",
64
+ "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}.",
65
+ ],
66
+ "Product Listing": [
67
+ "Write a caption for this image as though it were a product listing.",
68
+ "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
69
+ "Write a {length} caption for this image as though it were a product listing.",
70
+ ],
71
+ "Social Media Post": [
72
+ "Write a caption for this image as if it were being used for a social media post.",
73
+ "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
74
+ "Write a {length} caption for this image as if it were being used for a social media post.",
75
+ ],
76
+ }
77
+
78
+ class ImageAdapter(nn.Module):
79
+ def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
80
+ super().__init__()
81
+ self.deep_extract = deep_extract
82
+
83
+ if self.deep_extract:
84
+ input_features = input_features * 5
85
+
86
+ self.linear1 = nn.Linear(input_features, output_features)
87
+ self.activation = nn.GELU()
88
+ self.linear2 = nn.Linear(output_features, output_features)
89
+ self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
90
+ self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
91
+
92
+ # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
93
+ self.other_tokens = nn.Embedding(3, output_features)
94
+ self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
95
+
96
+ def forward(self, vision_outputs: torch.Tensor):
97
+ if self.deep_extract:
98
+ x = torch.concat((
99
+ vision_outputs[-2],
100
+ vision_outputs[3],
101
+ vision_outputs[7],
102
+ vision_outputs[13],
103
+ vision_outputs[20],
104
+ ), dim=-1)
105
+ assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
106
+ assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
107
+ else:
108
+ x = vision_outputs[-2]
109
+
110
+ x = self.ln1(x)
111
+
112
+ if self.pos_emb is not None:
113
+ assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
114
+ x = x + self.pos_emb
115
+
116
+ x = self.linear1(x)
117
+ x = self.activation(x)
118
+ x = self.linear2(x)
119
+
120
+ # <|image_start|>, IMAGE, <|image_end|>
121
+ other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
122
+ assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
123
+ x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
124
+
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
+
131
+ # Global Variables
132
+ IS_NF4 = True
133
+ IS_LORA = True
134
+ MODEL_PATH = DEFAULT_MODEL_PATH
135
+ device = "cuda" if torch.cuda.is_available() else "cpu"
136
+ print(f"Running on {device}")
137
+
138
+ warnings.filterwarnings("ignore", category=UserWarning)
139
+ logging.getLogger("transformers").setLevel(logging.ERROR)
140
+
141
+ class ImageAdapter(nn.Module):
142
+ def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
143
+ super().__init__()
144
+ self.deep_extract = deep_extract
145
+
146
+ if self.deep_extract:
147
+ input_features = input_features * 5
148
+
149
+ self.linear1 = nn.Linear(input_features, output_features)
150
+ self.activation = nn.GELU()
151
+ self.linear2 = nn.Linear(output_features, output_features)
152
+ self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
153
+ self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
154
+
155
+ # Mode token
156
+ #self.mode_token = nn.Embedding(n_modes, output_features)
157
+ #self.mode_token.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
158
+
159
+ # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
160
+ self.other_tokens = nn.Embedding(3, output_features)
161
+ self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
162
+
163
+ def forward(self, vision_outputs: torch.Tensor):
164
+ if self.deep_extract:
165
+ x = torch.concat((
166
+ vision_outputs[-2],
167
+ vision_outputs[3],
168
+ vision_outputs[7],
169
+ vision_outputs[13],
170
+ vision_outputs[20],
171
+ ), dim=-1)
172
+ assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
173
+ assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
174
+ else:
175
+ x = vision_outputs[-2]
176
+
177
+ x = self.ln1(x)
178
+
179
+ if self.pos_emb is not None:
180
+ assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
181
+ x = x + self.pos_emb
182
+
183
+ x = self.linear1(x)
184
+ x = self.activation(x)
185
+ x = self.linear2(x)
186
+
187
+ # Mode token
188
+ #mode_token = self.mode_token(mode)
189
+ #assert mode_token.shape == (x.shape[0], mode_token.shape[1], x.shape[2]), f"Expected {(x.shape[0], 1, x.shape[2])}, got {mode_token.shape}"
190
+ #x = torch.cat((x, mode_token), dim=1)
191
+
192
+ # <|image_start|>, IMAGE, <|image_end|>
193
+ other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
194
+ assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
195
+ x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
196
+
197
+ return x
198
+
199
+ def get_eot_embedding(self):
200
+ return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
201
+
202
+ def load_models():
203
+ global MODEL_PATH, IS_NF4, IS_LORA
204
+ try:
205
+ if IS_NF4:
206
+ from transformers import BitsAndBytesConfig
207
+ nf4_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
208
+ bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
209
+ print("Loading in NF4")
210
+ print("Loading CLIP 📎")
211
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
212
+ clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model
213
+ assert (CHECKPOINT_PATH / "clip_model.pt").exists()
214
+ if (CHECKPOINT_PATH / "clip_model.pt").exists():
215
+ print("Loading VLM's custom vision model 📎")
216
+ checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False)
217
+ checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
218
+ clip_model.load_state_dict(checkpoint)
219
+ del checkpoint
220
+ clip_model.eval().requires_grad_(False).to(device)
221
+
222
+ print("Loading tokenizer 🪙")
223
+ tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
224
+ assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
225
+
226
+ print(f"Loading LLM: {MODEL_PATH} 🤖")
227
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, quantization_config=nf4_config).eval()
228
+
229
+ if False and IS_LORA and LORA_PATH.exists(): # omitted
230
+ print("Loading VLM's custom text model 🤖")
231
+ text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, quantization_config=nf4_config)
232
+ text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515
233
+ else: print("VLM's custom text model isn't loaded 🤖")
234
+
235
+ print("Loading image adapter 🖼️")
236
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu")
237
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False))
238
+ image_adapter.eval().to(device)
239
+ else:
240
+ print("Loading in bfloat16")
241
+ print("Loading CLIP 📎")
242
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
243
+ clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model
244
+ if (CHECKPOINT_PATH / "clip_model.pt").exists():
245
+ print("Loading VLM's custom vision model 📎")
246
+ checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False)
247
+ checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
248
+ clip_model.load_state_dict(checkpoint)
249
+ del checkpoint
250
+ clip_model.eval().requires_grad_(False).to(device)
251
+
252
+ print("Loading tokenizer 🪙")
253
+ tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
254
+ assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}"
255
+
256
+ print(f"Loading LLM: {MODEL_PATH} 🤖")
257
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16).eval() # device_map="auto" may cause LoRA issue
258
+
259
+ if IS_LORA and LORA_PATH.exists():
260
+ print("Loading VLM's custom text model 🤖")
261
+ text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device)
262
+ text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515
263
+ else: print("VLM's custom text model isn't loaded 🤖")
264
+
265
+ print("Loading image adapter 🖼️")
266
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu")
267
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False))
268
+ except Exception as e:
269
+ print(f"Error loading models: {e}")
270
+ sys.exit(1)
271
+ finally:
272
+ torch.cuda.empty_cache()
273
+ gc.collect()
274
+ return clip_processor, clip_model, tokenizer, text_model, image_adapter
275
+
276
+ @torch.inference_mode()
277
+ def stream_chat(input_images: List[Image.Image], caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str,
278
+ max_new_tokens: int, top_p: float, temperature: float, batch_size: int, pbar: tqdm, models: tuple) -> List[str]:
279
+ global MODEL_PATH
280
+ clip_processor, clip_model, tokenizer, text_model, image_adapter = models
281
+ torch.cuda.empty_cache()
282
+ all_captions = []
283
+
284
+ # 'any' means no length specified
285
+ length = None if caption_length == "any" else caption_length
286
+
287
+ if isinstance(length, str):
288
+ try:
289
+ length = int(length)
290
+ except ValueError:
291
+ pass
292
+
293
+ # Build prompt
294
+ if length is None:
295
+ map_idx = 0
296
+ elif isinstance(length, int):
297
+ map_idx = 1
298
+ elif isinstance(length, str):
299
+ map_idx = 2
300
+ else:
301
+ raise ValueError(f"Invalid caption length: {length}")
302
+
303
+ prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
304
+
305
+ # Add extra options
306
+ if len(extra_options) > 0:
307
+ prompt_str += " " + " ".join(extra_options)
308
+
309
+ # Add name, length, word_count
310
+ prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
311
+
312
+ if custom_prompt.strip() != "":
313
+ prompt_str = custom_prompt.strip()
314
+
315
+ # For debugging
316
+ print(f"Prompt: {prompt_str}")
317
+
318
+ for i in range(0, len(input_images), batch_size):
319
+ batch = input_images[i:i+batch_size]
320
+
321
+ for input_image in input_images:
322
+ try:
323
+ # Preprocess image
324
+ # NOTE: I found the default processor for so400M to have worse results than just using PIL directly
325
+ #image = clip_processor(images=input_image, return_tensors='pt').pixel_values
326
+ image = input_image.resize((384, 384), Image.LANCZOS)
327
+ pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
328
+ pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
329
+ pixel_values = pixel_values.to(device)
330
+ except ValueError as e:
331
+ print(f"Error processing image: {e}")
332
+ print("Skipping this image and continuing...")
333
+ continue
334
+
335
+ # Embed image
336
+ # This results in Batch x Image Tokens x Features
337
+ with torch.amp.autocast_mode.autocast(device, enabled=True):
338
+ vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
339
+ image_features = vision_outputs.hidden_states
340
+ embedded_images = image_adapter(image_features).to(device)
341
+
342
+ # Build the conversation
343
+ convo = [
344
+ {
345
+ "role": "system",
346
+ "content": "You are a helpful image captioner.",
347
+ },
348
+ {
349
+ "role": "user",
350
+ "content": prompt_str,
351
+ },
352
+ ]
353
+
354
+ # Format the conversation
355
+ convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
356
+ assert isinstance(convo_string, str)
357
+
358
+ # Tokenize the conversation
359
+ # prompt_str is tokenized separately so we can do the calculations below
360
+ convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
361
+ prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
362
+ assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
363
+ convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
364
+ prompt_tokens = prompt_tokens.squeeze(0)
365
+
366
+ # Calculate where to inject the image
367
+ eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
368
+ assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}"
369
+
370
+ preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt
371
+
372
+ # Embed the tokens
373
+ convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to(device))
374
+
375
+ # Construct the input
376
+ input_embeds = torch.cat([
377
+ convo_embeds[:, :preamble_len], # Part before the prompt
378
+ embedded_images.to(dtype=convo_embeds.dtype), # Image
379
+ convo_embeds[:, preamble_len:], # The prompt and anything after it
380
+ ], dim=1).to(device)
381
+
382
+ input_ids = torch.cat([
383
+ convo_tokens[:preamble_len].unsqueeze(0),
384
+ torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input)
385
+ convo_tokens[preamble_len:].unsqueeze(0),
386
+ ], dim=1).to(device)
387
+ attention_mask = torch.ones_like(input_ids)
388
+
389
+ # Debugging
390
+ #print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
391
+
392
+ generate_ids = text_model.generate(input_ids=input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, do_sample=True,
393
+ suppress_tokens=None, max_new_tokens=max_new_tokens, top_p=top_p, temperature=temperature)
394
+
395
+ # Trim off the prompt
396
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
397
+ if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
398
+ generate_ids = generate_ids[:, :-1]
399
+
400
+ caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
401
+ all_captions.append(caption.strip())
402
+
403
+ if pbar:
404
+ pbar.update(len(batch))
405
+
406
+ return all_captions
407
+
408
+ def process_directory(input_dir: Path, output_dir: Path, caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str,
409
+ max_new_tokens: int, top_p: float, temperature: float, batch_size: int, models: tuple):
410
+ output_dir.mkdir(parents=True, exist_ok=True)
411
+ image_files = [f for f in input_dir.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS]
412
+ images_to_process = [f for f in image_files if not (output_dir / f"{f.stem}.txt").exists()]
413
+
414
+ if not images_to_process:
415
+ print("No new images to process.")
416
+ return
417
+
418
+ with tqdm(total=len(images_to_process), desc="Processing images", unit="image") as pbar:
419
+ for i in range(0, len(images_to_process), batch_size):
420
+ batch_files = images_to_process[i:i+batch_size]
421
+ batch_images = [Image.open(f).convert('RGB') for f in batch_files]
422
+
423
+ captions = stream_chat(batch_images, caption_type, caption_length, extra_options, name_input, custom_prompt,
424
+ max_new_tokens, top_p, temperature, batch_size, pbar, models)
425
+
426
+ for file, caption in zip(batch_files, captions):
427
+ with open(output_dir / f"{file.stem}.txt", 'w', encoding='utf-8') as f:
428
+ f.write(caption)
429
+
430
+ for img in batch_images:
431
+ img.close()
432
+
433
+ def parse_arguments():
434
+ parser = argparse.ArgumentParser(description="Process images and generate captions.")
435
+ parser.add_argument("input", nargs='+', help="Input image file or directory (or multiple directories)")
436
+ parser.add_argument("--output", help="Output directory (optional)")
437
+ parser.add_argument("--bs", type=int, default=4, help="Batch size (default: 4)")
438
+ parser.add_argument("--type", type=str, default="Descriptive",
439
+ choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"],
440
+ help='Caption Type (default: "Descriptive")')
441
+ parser.add_argument("--len", default="long",
442
+ choices=["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)],
443
+ help='Caption Length (default: "long")')
444
+ parser.add_argument("--extra", default=[], type=list[str], help='Extra Options',
445
+ choices=[
446
+ "If there is a person/character in the image you must refer to them as {name}.",
447
+ "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
448
+ "Include information about lighting.",
449
+ "Include information about camera angle.",
450
+ "Include information about whether there is a watermark or not.",
451
+ "Include information about whether there are JPEG artifacts or not.",
452
+ "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
453
+ "Do NOT include anything sexual; keep it PG.",
454
+ "Do NOT mention the image's resolution.",
455
+ "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
456
+ "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
457
+ "Do NOT mention any text that is in the image.",
458
+ "Specify the depth of field and whether the background is in focus or blurred.",
459
+ "If applicable, mention the likely use of artificial or natural lighting sources.",
460
+ "Do NOT use any ambiguous language.",
461
+ "Include whether the image is sfw, suggestive, or nsfw.",
462
+ "ONLY describe the most important elements of the image."
463
+ ])
464
+ parser.add_argument("--name", type=str, default="", help='Person/Character Name (if applicable)')
465
+ parser.add_argument("--prompt", type=str, default="", help='Custom Prompt (optional, will override all other settings)')
466
+ parser.add_argument("--model", type=str, default=DEFAULT_MODEL_PATH,
467
+ help='Huggingface LLM repo (default: "unsloth/Meta-Llama-3.1-8B-bnb-4bit")')
468
+ parser.add_argument("--bf16", action="store_true", default=False, help="Use bfloat16 (default: NF4)")
469
+ parser.add_argument("--nolora", action="store_true", default=False, help="Disable VLM's custom text model (default: Enable)")
470
+ parser.add_argument("--tokens", type=int, default=300, help="Max tokens (default: 300)")
471
+ parser.add_argument("--topp", type=float, default=0.9, help="Top-P (default: 0.9)")
472
+ parser.add_argument("--temp", type=float, default=0.6, help="Temperature (default: 0.6)")
473
+ return parser.parse_args()
474
+
475
+ def is_valid_repo(repo_id):
476
+ from huggingface_hub import HfApi
477
+ import re
478
+ try:
479
+ if not re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', repo_id): return False
480
+ api = HfApi()
481
+ if api.repo_exists(repo_id=repo_id): return True
482
+ else: return False
483
+ except Exception as e:
484
+ print(f"Failed to connect {repo_id}. {e}")
485
+ return False
486
+
487
+ def main():
488
+ global MODEL_PATH, IS_NF4, IS_LORA
489
+ args = parse_arguments()
490
+ input_paths = [Path(input_path) for input_path in args.input]
491
+ batch_size = args.bs
492
+ caption_type = args.type
493
+ caption_length = args.len
494
+ extra_options = args.extra
495
+ name_input = args.name
496
+ custom_prompt = args.prompt
497
+ max_new_tokens = args.tokens
498
+ top_p = args.topp
499
+ temperature = args.temp
500
+ IS_NF4 = False if args.bf16 else True
501
+ IS_LORA = False if args.nolora else True
502
+ if is_valid_repo(args.model): MODEL_PATH = args.model
503
+ else: sys.exit(1)
504
+ models = load_models()
505
+
506
+ for input_path in input_paths:
507
+ if input_path.is_file() and input_path.suffix.lower() in IMAGE_EXTENSIONS:
508
+ output_path = input_path.with_suffix('.txt')
509
+ print(f"Processing single image 🎞️: {input_path.name}")
510
+ with tqdm(total=1, desc="Processing image", unit="image") as pbar:
511
+ captions = stream_chat([Image.open(input_path).convert('RGB')], caption_type, caption_length, extra_options, name_input, custom_prompt,
512
+ max_new_tokens, top_p, temperature, 1, pbar, models)
513
+ with open(output_path, 'w', encoding='utf-8') as f:
514
+ f.write(captions[0])
515
+ print(f"Output saved to {output_path}")
516
+ elif input_path.is_dir():
517
+ output_path = Path(args.output) if args.output else input_path
518
+ print(f"Processing directory 📁: {input_path}")
519
+ print(f"Output directory 📦: {output_path}")
520
+ print(f"Batch size 🗄️: {batch_size}")
521
+ process_directory(input_path, output_path, caption_type, caption_length, extra_options, name_input, custom_prompt,
522
+ max_new_tokens, top_p, temperature, batch_size, models)
523
+ else:
524
+ print(f"Invalid input: {input_path}")
525
+ print("Skipping...")
526
+
527
+ if not input_paths:
528
+ print("Usage:")
529
+ print("For single image: python app.py [image_file] [--bs batch_size]")
530
+ print("For directory (same input/output): python app.py [directory] [--bs batch_size]")
531
+ print("For directory (separate input/output): python app.py [directory] --output [output_directory] [--bs batch_size]")
532
+ print("For multiple directories: python app.py [directory1] [directory2] ... [--output output_directory] [--bs batch_size]")
533
+ sys.exit(1)
534
+
535
+ if __name__ == "__main__":
536
+ main()