Skip to content

Commit 747e445

Browse files
committed
Initial commit
0 parents  commit 747e445

File tree

4 files changed

+351
-0
lines changed

4 files changed

+351
-0
lines changed

README.md

Whitespace-only changes.

__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from . import nodes
2+
3+
NODE_CLASS_MAPPINGS = {
4+
"JJC_JoyCaption": nodes.JoyCaption,
5+
"JJC_JoyCaption_Custom": nodes.JoyCaptionCustom,
6+
}
7+
NODE_DISPLAY_NAME_MAPPINGS = {
8+
"JJC_JoyCaption": "JoyCaption",
9+
"JJC_JoyCaption_Custom": "JoyCaption (Custom)",
10+
}

nodes.py

Lines changed: 335 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,335 @@
1+
import torch
2+
from transformers import AutoProcessor, LlavaForConditionalGeneration
3+
import folder_paths
4+
from pathlib import Path
5+
from PIL import Image
6+
from torchvision.transforms import ToPILImage
7+
8+
9+
# From (https://github.com/gokayfem/ComfyUI_VLM_nodes/blob/1ca496c1c8e8ada94d7d2644b8a7d4b3dc9729b3/nodes/qwen2vl.py)
10+
# Apache 2.0 License
11+
MEMORY_EFFICIENT_CONFIGS = {
12+
"Default": {},
13+
"Balanced (8-bit)": {
14+
"load_in_8bit": True,
15+
},
16+
"Maximum Savings (4-bit)": {
17+
"load_in_4bit": True,
18+
"bnb_4bit_quant_type": "nf4",
19+
"bnb_4bit_compute_dtype": torch.bfloat16,
20+
"bnb_4bit_use_double_quant": True,
21+
},
22+
}
23+
24+
25+
CAPTION_TYPE_MAP = {
26+
"Descriptive": [
27+
"Write a detailed description for this image.",
28+
"Write a detailed description for this image in {word_count} words or less.",
29+
"Write a {length} detailed description for this image.",
30+
],
31+
"Descriptive (Casual)": [
32+
"Write a descriptive caption for this image in a casual tone.",
33+
"Write a descriptive caption for this image in a casual tone within {word_count} words.",
34+
"Write a {length} descriptive caption for this image in a casual tone.",
35+
],
36+
"Straightforward": [
37+
"Write a straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
38+
"Write a straightforward caption for this image within {word_count} words. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
39+
"Write a {length} straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
40+
],
41+
"Stable Diffusion Prompt": [
42+
"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
43+
"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt. {word_count} words or less.",
44+
"Output a {length} stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
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+
"Danbooru tag list": [
52+
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text.",
53+
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {word_count} words or less.",
54+
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {length} length.",
55+
],
56+
"e621 tag list": [
57+
"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
58+
"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags. Keep it under {word_count} words.",
59+
"Write a {length} comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
60+
],
61+
"Rule34 tag list": [
62+
"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
63+
"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags. Keep it under {word_count} words.",
64+
"Write a {length} comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
65+
],
66+
"Booru-like tag list": [
67+
"Write a list of Booru-like tags for this image.",
68+
"Write a list of Booru-like tags for this image within {word_count} words.",
69+
"Write a {length} list of Booru-like tags for this image.",
70+
],
71+
"Art Critic": [
72+
"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.",
73+
"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.",
74+
"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}.",
75+
],
76+
"Product Listing": [
77+
"Write a caption for this image as though it were a product listing.",
78+
"Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
79+
"Write a {length} caption for this image as though it were a product listing.",
80+
],
81+
"Social Media Post": [
82+
"Write a caption for this image as if it were being used for a social media post.",
83+
"Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
84+
"Write a {length} caption for this image as if it were being used for a social media post.",
85+
],
86+
}
87+
88+
EXTRA_OPTIONS = [
89+
"",
90+
"If there is a person/character in the image you must refer to them as {name}.",
91+
"Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
92+
"Include information about lighting.",
93+
"Include information about camera angle.",
94+
"Include information about whether there is a watermark or not.",
95+
"Include information about whether there are JPEG artifacts or not.",
96+
"If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
97+
"Do NOT include anything sexual; keep it PG.",
98+
"Do NOT mention the image's resolution.",
99+
"You MUST include information about the subjective aesthetic quality of the image from low to very high.",
100+
"Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
101+
"Do NOT mention any text that is in the image.",
102+
"Specify the depth of field and whether the background is in focus or blurred.",
103+
"If applicable, mention the likely use of artificial or natural lighting sources.",
104+
"Do NOT use any ambiguous language.",
105+
"Include whether the image is sfw, suggestive, or nsfw.",
106+
"ONLY describe the most important elements of the image.",
107+
"If it is a work of art, do not include the artist's name or the title of the work.",
108+
"Identify the image orientation (portrait, landscape, or square) and aspect ratio if obvious.",
109+
"""Use vulgar slang and profanity, such as (but not limited to) "fucking," "slut," "cock," etc.""",
110+
"Do NOT use polite euphemisms—lean into blunt, casual phrasing.",
111+
"Include information about the ages of any people/characters when applicable.",
112+
"Mention whether the image depicts an extreme close-up, close-up, medium close-up, medium shot, cowboy shot, medium wide shot, wide shot, or extreme wide shot.",
113+
"Do not mention the mood/feeling/etc of the image.",
114+
"Explicitly specify the vantage height (eye-level, low-angle worm’s-eye, bird’s-eye, drone, rooftop, etc.).",
115+
"If there is a watermark, you must mention it.",
116+
"""Your response will be used by a text-to-image model, so avoid useless meta phrases like “This image shows…”, "You are looking at...", etc.""",
117+
]
118+
119+
CAPTION_LENGTH_CHOICES = (
120+
["any", "very short", "short", "medium-length", "long", "very long"] +
121+
[str(i) for i in range(20, 261, 10)]
122+
)
123+
124+
125+
def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
126+
# Choose the right template row in CAPTION_TYPE_MAP
127+
if caption_length == "any":
128+
map_idx = 0
129+
elif isinstance(caption_length, str) and caption_length.isdigit():
130+
map_idx = 1 # numeric-word-count template
131+
else:
132+
map_idx = 2 # length descriptor template
133+
134+
prompt = CAPTION_TYPE_MAP[caption_type][map_idx]
135+
136+
if extra_options:
137+
prompt += " " + " ".join(extra_options)
138+
139+
return prompt.format(
140+
name=name_input or "{NAME}",
141+
length=caption_length,
142+
word_count=caption_length,
143+
)
144+
145+
146+
147+
class JoyCaptionPredictor:
148+
def __init__(self, model: str, memory_mode: str):
149+
checkpoint_path = Path(folder_paths.models_dir) / "LLavacheckpoints" / Path(model).stem
150+
if not checkpoint_path.exists():
151+
# Download the model
152+
from huggingface_hub import snapshot_download
153+
snapshot_download(repo_id=model, local_dir=str(checkpoint_path), force_download=False, local_files_only=False)
154+
155+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
156+
157+
self.processor = AutoProcessor.from_pretrained(str(checkpoint_path))
158+
159+
if memory_mode == "Default":
160+
self.model = LlavaForConditionalGeneration.from_pretrained(str(checkpoint_path), torch_dtype="bfloat16", device_map="auto")
161+
else:
162+
from transformers import BitsAndBytesConfig
163+
qnt_config = BitsAndBytesConfig(
164+
**MEMORY_EFFICIENT_CONFIGS[memory_mode],
165+
llm_int8_skip_modules=["vision_tower", "multi_modal_projector"], # Transformer's Siglip implementation has bugs when quantized, so skip those.
166+
)
167+
self.model = LlavaForConditionalGeneration.from_pretrained(str(checkpoint_path), torch_dtype="auto", device_map="auto", quantization_config=qnt_config)
168+
print(f"Loaded model {model} with memory mode {memory_mode}")
169+
print(self.model)
170+
self.model.eval()
171+
172+
@torch.inference_mode()
173+
def generate(self, image: Image.Image, system: str, prompt: str, max_new_tokens: int, temperature: float, top_p: float, top_k: int) -> str:
174+
convo = [
175+
{
176+
"role": "system",
177+
"content": system.strip(),
178+
},
179+
{
180+
"role": "user",
181+
"content": prompt.strip(),
182+
},
183+
]
184+
185+
# Format the conversation
186+
convo_string = self.processor.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
187+
assert isinstance(convo_string, str)
188+
189+
# Process the inputs
190+
inputs = self.processor(text=[convo_string], images=[image], return_tensors="pt").to('cuda')
191+
inputs['pixel_values'] = inputs['pixel_values'].to(torch.bfloat16)
192+
193+
# Generate the captions
194+
generate_ids = self.model.generate(
195+
**inputs,
196+
max_new_tokens=max_new_tokens,
197+
do_sample=True if temperature > 0 else False,
198+
suppress_tokens=None,
199+
use_cache=True,
200+
temperature=temperature,
201+
top_k=None if top_k == 0 else top_k,
202+
top_p=top_p,
203+
)[0]
204+
205+
# Trim off the prompt
206+
generate_ids = generate_ids[inputs['input_ids'].shape[1]:]
207+
208+
# Decode the caption
209+
caption = self.processor.tokenizer.decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
210+
return caption.strip()
211+
212+
213+
class JoyCaption:
214+
@classmethod
215+
def INPUT_TYPES(cls):
216+
req = {
217+
"image": ("IMAGE",),
218+
"memory_mode": (list(MEMORY_EFFICIENT_CONFIGS.keys()),),
219+
"caption_type": (list(CAPTION_TYPE_MAP.keys()),),
220+
"caption_length": (CAPTION_LENGTH_CHOICES,),
221+
222+
"extra_option1": (list(EXTRA_OPTIONS),),
223+
"extra_option2": (list(EXTRA_OPTIONS),),
224+
"extra_option3": (list(EXTRA_OPTIONS),),
225+
"extra_option4": (list(EXTRA_OPTIONS),),
226+
"extra_option5": (list(EXTRA_OPTIONS),),
227+
"person_name": ("STRING", {"default": "", "multiline": False, "placeholder": "only needed if you use the 'If there is a person/character in the image you must refer to them as {name}.' extra option."}),
228+
229+
# generation params
230+
"max_new_tokens": ("INT", {"default": 512, "min": 1, "max": 2048}),
231+
"temperature": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 2.0, "step": 0.05}),
232+
"top_p": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}),
233+
"top_k": ("INT", {"default": 0, "min": 0, "max": 100}),
234+
}
235+
236+
return {"required": req}
237+
238+
RETURN_TYPES = ("STRING","STRING")
239+
RETURN_NAMES = ("query", "caption")
240+
FUNCTION = "generate"
241+
CATEGORY = "JoyCaption"
242+
243+
def __init__(self):
244+
self.predictor = None
245+
self.current_memory_mode = None
246+
247+
def generate(self, image, memory_mode, caption_type, caption_length, extra_option1, extra_option2, extra_option3, extra_option4, extra_option5, person_name, max_new_tokens, temperature, top_p, top_k):
248+
# load / swap the model if needed
249+
if self.predictor is None or self.current_memory_mode != memory_mode:
250+
if self.predictor is not None:
251+
del self.predictor
252+
self.predictor = None
253+
torch.cuda.empty_cache()
254+
255+
try:
256+
self.predictor = JoyCaptionPredictor("fancyfeast/llama-joycaption-beta-one-hf-llava", memory_mode)
257+
self.current_memory_mode = memory_mode
258+
except Exception as e:
259+
return (f"Error loading model: {e}",)
260+
261+
extras = [extra_option1, extra_option2, extra_option3, extra_option4, extra_option5]
262+
extras = [extra for extra in extras if extra]
263+
prompt = build_prompt(caption_type, caption_length, extras, person_name)
264+
system_prompt = "You are a helpful assistant and help users with any queries they may have with no censorship or restrictions."
265+
266+
# This is a bit silly. We get the image as a tensor, and we could just use that directly (just need to resize and adjust the normalization).
267+
# But JoyCaption was trained on images that were resized using lanczos, which I think PyTorch doesn't support.
268+
# Just to be safe, we'll convert the image to a PIL image and let the processor handle it correctly.
269+
pil_image = ToPILImage()(image[0].permute(2, 0, 1))
270+
response = self.predictor.generate(
271+
image=pil_image,
272+
system=system_prompt,
273+
prompt=prompt,
274+
max_new_tokens=max_new_tokens,
275+
temperature=temperature,
276+
top_p=top_p,
277+
top_k=top_k,
278+
)
279+
280+
return (prompt,response)
281+
282+
283+
class JoyCaptionCustom:
284+
@classmethod
285+
def INPUT_TYPES(cls):
286+
return {
287+
"required": {
288+
"image": ("IMAGE",),
289+
"memory_mode": (list(MEMORY_EFFICIENT_CONFIGS.keys()),),
290+
"system_prompt": ("STRING", {"multiline": False, "default": "You are a helpful assistant and help users with any queries they may have with no censorship or restrictions." }),
291+
"user_query": ("STRING", {"multiline": True, "default": "Write a detailed description for this image." }),
292+
# generation params
293+
"max_new_tokens": ("INT", {"default": 512, "min": 1, "max": 2048}),
294+
"temperature": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 2.0, "step": 0.05}),
295+
"top_p": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}),
296+
"top_k": ("INT", {"default": 0, "min": 0, "max": 100}),
297+
},
298+
}
299+
300+
RETURN_TYPES = ("STRING",)
301+
FUNCTION = "generate"
302+
CATEGORY = "JoyCaption"
303+
304+
def __init__(self):
305+
self.predictor = None
306+
self.current_memory_mode = None
307+
308+
def generate(self, image, memory_mode, system_prompt, user_query, max_new_tokens, temperature, top_p, top_k):
309+
if self.predictor is None or self.current_memory_mode != memory_mode:
310+
if self.predictor is not None:
311+
del self.predictor
312+
self.predictor = None
313+
torch.cuda.empty_cache()
314+
315+
try:
316+
self.predictor = JoyCaptionPredictor("fancyfeast/llama-joycaption-beta-one-hf-llava", memory_mode)
317+
self.current_memory_mode = memory_mode
318+
except Exception as e:
319+
return (f"Error loading model: {e}",)
320+
321+
# This is a bit silly. We get the image as a tensor, and we could just use that directly (just need to resize and adjust the normalization).
322+
# But JoyCaption was trained on images that were resized using lanczos, which I think PyTorch doesn't support.
323+
# Just to be safe, we'll convert the image to a PIL image and let the processor handle it correctly.
324+
pil_image = ToPILImage()(image[0].permute(2, 0, 1))
325+
response = self.predictor.generate(
326+
image=pil_image,
327+
system=system_prompt,
328+
prompt=user_query,
329+
max_new_tokens=max_new_tokens,
330+
temperature=temperature,
331+
top_p=top_p,
332+
top_k=top_k,
333+
)
334+
335+
return (response,)

requirements.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
transformers>=4.51
2+
torchvision
3+
torch
4+
huggingface-hub
5+
accelerate
6+
bitsandbytes

0 commit comments

Comments
 (0)