forked from Cyber-BlackCat/ComfyUI_Auto_Caption
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto_caption.py
394 lines (309 loc) · 14 KB
/
auto_caption.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import os
import folder_paths
import torch
import torch.amp.autocast_mode
import re
import numpy as np
from torch import nn
from huggingface_hub import InferenceClient
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
from pathlib import Path
from PIL import Image, ImageOps
from .lib.ximg import *
from .lib.xmodel import *
from comfy.utils import ProgressBar, common_upscale
class JoyModel:
def __init__(self):
self.clip_model = None
self.clip_processor =None
self.tokenizer = None
self.text_model = None
self.image_adapter = None
self.parent = None
def clearCache(self):
self.clip_model = None
self.clip_processor =None
self.tokenizer = None
self.text_model = None
self.image_adapter = None
class ImageAdapter(nn.Module):
def __init__(self, input_features: int, output_features: int):
super().__init__()
self.linear1 = nn.Linear(input_features, output_features)
self.activation = nn.GELU()
self.linear2 = nn.Linear(output_features, output_features)
def forward(self, vision_outputs: torch.Tensor):
x = self.linear1(vision_outputs)
x = self.activation(x)
x = self.linear2(x)
return x
class Joy_Model_load:
def __init__(self):
self.model = None
self.pipeline = JoyModel()
self.pipeline.parent = self
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": (["unsloth/Meta-Llama-3.1-8B-bnb-4bit", "meta-llama/Meta-Llama-3.1-8B"],),
}
}
CATEGORY = "Auto Caption"
RETURN_TYPES = ("JoyModel",)
FUNCTION = "gen"
def loadCheckPoint(self):
# 清除一波
if self.pipeline != None:
self.pipeline.clearCache()
# clip
model_id = "google/siglip-so400m-patch14-384"
CLIP_PATH = download_hg_model(model_id,"clip")
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
clip_model = AutoModel.from_pretrained(
CLIP_PATH,
trust_remote_code=True
)
clip_model = clip_model.vision_model
clip_model.eval()
clip_model.requires_grad_(False)
clip_model.to("cuda")
# LLM
MODEL_PATH = download_hg_model(self.model,"LLM")
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH,use_fast=False)
assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto",trust_remote_code=True)
text_model.eval()
# Image Adapter
adapter_path = os.path.join(folder_paths.models_dir,"Auto_Caption","image_adapter.pt")
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size) # ImageAdapter(clip_model.config.hidden_size, 4096)
image_adapter.load_state_dict(torch.load(adapter_path, map_location="cpu"))
adjusted_adapter = image_adapter #AdjustedImageAdapter(image_adapter, text_model.config.hidden_size)
adjusted_adapter.eval()
adjusted_adapter.to("cuda")
self.pipeline.clip_model = clip_model
self.pipeline.clip_processor = clip_processor
self.pipeline.tokenizer = tokenizer
self.pipeline.text_model = text_model
self.pipeline.image_adapter = adjusted_adapter
def clearCache(self):
if self.pipeline != None:
self.pipeline.clearCache()
def gen(self,model):
if self.model == None or self.model != model or self.pipeline == None:
self.model = model
self.loadCheckPoint()
return (self.pipeline,)
class Auto_Caption:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"JoyModel": ("JoyModel",),
"image": ("IMAGE",),
"prompt": ("STRING", {"multiline": True, "default": "A descriptive caption for this image"},),
"max_new_tokens":("INT", {"default": 1024, "min": 10, "max": 4096, "step": 1}),
"temperature": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 1.0, "step": 0.01}),
"cache": ("BOOLEAN", {"default": False}),
}
}
CATEGORY = "Auto Caption"
RETURN_TYPES = ("STRING",)
FUNCTION = "gen"
def gen(self,JoyModel,image,prompt,max_new_tokens,temperature,cache):
if JoyModel.clip_processor == None :
JoyModel.parent.loadCheckPoint()
clip_processor = JoyModel.clip_processor
tokenizer = JoyModel.tokenizer
clip_model = JoyModel.clip_model
image_adapter = JoyModel.image_adapter
text_model = JoyModel.text_model
input_image = tensor2pil(image)
# Preprocess image
pImge = clip_processor(images=input_image, return_tensors='pt').pixel_values
pImge = pImge.to('cuda')
# Tokenize the prompt
prompt = tokenizer.encode(prompt, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
# Embed image
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
vision_outputs = clip_model(pixel_values=pImge, output_hidden_states=True)
image_features = vision_outputs.hidden_states[-2]
embedded_images = image_adapter(image_features)
embedded_images = embedded_images.to('cuda')
# Embed prompt
prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
assert prompt_embeds.shape == (1, prompt.shape[1], text_model.config.hidden_size), f"Prompt shape is {prompt_embeds.shape}, expected {(1, prompt.shape[1], text_model.config.hidden_size)}"
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
# Construct prompts
inputs_embeds = torch.cat([
embedded_bos.expand(embedded_images.shape[0], -1, -1),
embedded_images.to(dtype=embedded_bos.dtype),
prompt_embeds.expand(embedded_images.shape[0], -1, -1),
], dim=1)
input_ids = torch.cat([
torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
prompt,
], dim=1).to('cuda')
attention_mask = torch.ones_like(input_ids)
generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=max_new_tokens, do_sample=True, top_k=10, temperature=temperature, suppress_tokens=None)
# Trim off the prompt
generate_ids = generate_ids[:, input_ids.shape[1]:]
if generate_ids[0][-1] == tokenizer.eos_token_id:
generate_ids = generate_ids[:, :-1]
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
r = caption.strip()
if cache == False:
JoyModel.parent.clearCache()
return (r,)
class LoadImagesRezise:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"folder": ("STRING", {"default": ""}),
},
"optional": {
"image_load_cap": ("INT", {"default": 50, "min": 0, "step": 1}),
"start_index": ("INT", {"default": 0, "min": 0, "step": 1}),
}
}
RETURN_TYPES = ("IMAGE", "MASK", "INT", "STRING",)
RETURN_NAMES = ("image", "mask", "count", "image_path",)
FUNCTION = "load_images"
CATEGORY = "Auto Caption"
def load_images(self, folder, image_load_cap, start_index):
if not os.path.isdir(folder):
raise FileNotFoundError(f"Folder '{folder}' cannot be found.")
dir_files = os.listdir(folder)
if len(dir_files) == 0:
raise FileNotFoundError(f"No files in directory '{folder}'.")
# Filter files by valid image extensions
valid_extensions = ['.jpg', '.jpeg', '.png', '.webp']
dir_files = [f for f in dir_files if any(f.lower().endswith(ext) for ext in valid_extensions)]
# Sort files based on numeric value extracted from filename
def extract_number(file_name):
match = re.search(r'(\d+)', file_name)
return int(match.group(0)) if match else float('inf') # Use 'inf' if no number is found to push such files at the end
dir_files = sorted(dir_files, key=extract_number)
# Convert to full file paths
dir_files = [os.path.join(folder, x) for x in dir_files]
# Start at the specified start_index
dir_files = dir_files[start_index:]
images = []
masks = []
image_path_list = []
limit_images = False
if image_load_cap > 0:
limit_images = True
image_count = 0
has_non_empty_mask = False
for image_path in dir_files:
if os.path.isdir(image_path):
continue
if limit_images and image_count >= image_load_cap:
break
i = Image.open(image_path)
i = ImageOps.exif_transpose(i) # Handle EXIF orientation
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,] # Add a batch dimension
if 'A' in i.getbands(): # Check for alpha channel
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask) # Invert the alpha mask
has_non_empty_mask = True
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
images.append(image)
masks.append(mask)
image_path_list.append(image_path)
image_count += 1
if len(images) == 1:
return (images[0], masks[0], 1)
elif len(images) > 1:
image1 = images[0]
mask1 = None
for image2 in images[1:]:
if image1.shape[1:] != image2.shape[1:]:
image2 = common_upscale(image2.movedim(-1, 1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1, -1)
image1 = torch.cat((image1, image2), dim=0)
for mask2 in masks[1:]:
if has_non_empty_mask:
if image1.shape[1:3] != mask2.shape:
mask2 = torch.nn.functional.interpolate(mask2.unsqueeze(0).unsqueeze(0), size=(image1.shape[2], image1.shape[1]), mode='bilinear', align_corners=False)
mask2 = mask2.squeeze(0)
else:
mask2 = mask2.unsqueeze(0)
else:
mask2 = mask2.unsqueeze(0)
if mask1 is None:
mask1 = mask2
else:
mask1 = torch.cat((mask1, mask2), dim=0)
return (image1, mask1, len(images), image_path_list)
class LoadManyImages:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"folder": ("STRING", {"default": ""}),
},
"optional": {
"image_load_cap": ("INT", {"default": 50, "min": 0, "step": 1}),
"start_index": ("INT", {"default": 0, "min": 0, "step": 1}),
}
}
RETURN_TYPES = ("IMAGE", "MASK", "INT", "STRING",)
RETURN_NAMES = ("image", "mask", "count", "image_path",)
OUTPUT_IS_LIST = (True, True, True, True)
FUNCTION = "load_images"
CATEGORY = "Auto Caption"
def load_images(self, folder, image_load_cap, start_index):
if not os.path.isdir(folder):
raise FileNotFoundError(f"Folder '{folder}' cannot be found.")
dir_files = os.listdir(folder)
if len(dir_files) == 0:
raise FileNotFoundError(f"No files in directory '{folder}'.")
# Filter files by valid image extensions
valid_extensions = ['.jpg', '.jpeg', '.png', '.webp']
dir_files = [f for f in dir_files if any(f.lower().endswith(ext) for ext in valid_extensions)]
# Sort files based on numeric value extracted from filename
def extract_number(file_name):
match = re.search(r'(\d+)', file_name)
return int(match.group(0)) if match else float('inf') # Use 'inf' if no number is found to push such files at the end
dir_files = sorted(dir_files, key=extract_number)
#
# Convert to full file paths
dir_files = [os.path.join(folder, x) for x in dir_files]
# Start at the specified start_index
dir_files = dir_files[start_index:]
images = []
masks = []
image_path_list = []
limit_images = False
if image_load_cap > 0:
limit_images = True
image_count = 0
for image_path in dir_files:
if os.path.isdir(image_path) and os.path.ex:
continue
if limit_images and image_count >= image_load_cap:
break
i = Image.open(image_path)
i = ImageOps.exif_transpose(i) # Handle EXIF orientation
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands(): # Check for alpha channel
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask) # Invert the alpha mask
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
images.append(image)
masks.append(mask)
image_path_list.append(image_path)
image_count += 1
return (images, masks, image_path_list)