import spaces import gradio as gr import triton from huggingface_hub import InferenceClient from torch import nn from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM, BitsAndBytesConfig from pathlib import Path import torch import torch.amp.autocast_mode from PIL import Image import os import torchvision.transforms.functional as TVF import gc CLIP_PATH = "google/siglip-so400m-patch14-384" CHECKPOINT_PATH = Path("/content/joy-caption-alpha-two/cgrkzexw-599808") TITLE = """

Bullseye's JoyCaption Alpha Two

Unleash the power of AI-driven image captioning!

""" CAPTION_TYPE_MAP = { "Descriptive": ["Write a descriptive caption for this image in a formal tone.", "Write a descriptive caption for this image in a formal tone within {word_count} words.", "Write a {length} descriptive caption for this image in a formal tone."], "Descriptive (Informal)": ["Write a descriptive caption for this image in a casual tone.", "Write a descriptive caption for this image in a casual tone within {word_count} words.", "Write a {length} descriptive caption for this image in a casual tone."], "Training Prompt": ["Write a stable diffusion prompt for this image.", "Write a stable diffusion prompt for this image within {word_count} words.", "Write a {length} stable diffusion prompt for this image."], "MidJourney": ["Write a MidJourney prompt for this image.", "Write a MidJourney prompt for this image within {word_count} words.", "Write a {length} MidJourney prompt for this image."], "Booru tag list": ["Write a list of Booru tags for this image.", "Write a list of Booru tags for this image within {word_count} words.", "Write a {length} list of Booru tags for this image."], "Booru-like tag list": ["Write a list of Booru-like tags for this image.", "Write a list of Booru-like tags for this image within {word_count} words.", "Write a {length} list of Booru-like tags for this image."], "Art Critic": ["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.", "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.", "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}."], "Product Listing": ["Write a caption for this image as though it were a product listing.", "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.", "Write a {length} caption for this image as though it were a product listing."], "Social Media Post": ["Write a caption for this image as if it were being used for a social media post.", "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.", "Write a {length} caption for this image as if it were being used for a social media post."], } HF_TOKEN = os.environ.get("HF_TOKEN", None) class ImageAdapter(nn.Module): def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool): super().__init__() self.deep_extract = deep_extract if self.deep_extract: input_features = input_features * 5 self.linear1 = nn.Linear(input_features, output_features) self.activation = nn.GELU() self.linear2 = nn.Linear(output_features, output_features) self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features) self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features)) # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>) self.other_tokens = nn.Embedding(3, output_features) self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3 def forward(self, vision_outputs: torch.Tensor): if self.deep_extract: x = torch.concat(( vision_outputs[-2], vision_outputs[3], vision_outputs[7], vision_outputs[13], vision_outputs[20], ), dim=-1) assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}" else: x = vision_outputs[-2] x = self.ln1(x) if self.pos_emb is not None: assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}" x = x + self.pos_emb x = self.linear1(x) x = self.activation(x) x = self.linear2(x) # <|image_start|>, IMAGE, <|image_end|> other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1)) assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}" x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1) return x def get_eot_embedding(self): return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0) # Load CLIP print("Loading CLIP") clip_processor = AutoProcessor.from_pretrained(CLIP_PATH) clip_model = AutoModel.from_pretrained(CLIP_PATH, torch_dtype=torch.float16) clip_model = clip_model.vision_model assert (CHECKPOINT_PATH / "clip_model.pt").exists() print("Loading VLM's custom vision model") checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu') checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()} clip_model.load_state_dict(checkpoint) del checkpoint clip_model.eval() clip_model.requires_grad_(False) clip_model.to("cuda") clip_model = torch.compile(clip_model) # Tokenizer print("Loading tokenizer") tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True) assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}" # LLM print("Loading LLM") print("Loading VLM's custom text model") # Configure 4-bit quantization with more aggressive settings bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True, llm_int8_enable_fp32_cpu_offload=True ) text_model = AutoModelForCausalLM.from_pretrained( CHECKPOINT_PATH / "text_model", device_map="auto", quantization_config=bnb_config, torch_dtype=torch.float16, low_cpu_mem_usage=True ) # Enable memory efficient attention text_model.config.use_memory_efficient_attention = True text_model.gradient_checkpointing_enable() text_model.eval() text_model = torch.compile(text_model) # Image Adapter print("Loading image adapter") image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False) image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu")) image_adapter.eval() image_adapter.to("cuda") image_adapter = torch.compile(image_adapter) # Optimize CLIP model clip_model = clip_model.half() # Convert to FP16 clip_model.eval() clip_model.requires_grad_(False) clip_model = torch.compile(clip_model) # Optimize image adapter image_adapter = image_adapter.half() # Convert to FP16 image_adapter.eval() image_adapter.requires_grad_(False) image_adapter = torch.compile(image_adapter) @spaces.GPU() @torch.no_grad() def stream_chat(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str) -> tuple[str, str]: # Clear memory at the start torch.cuda.empty_cache() gc.collect() # Build prompt string length = None if caption_length == "any" else caption_length if isinstance(length, str): try: length = int(length) except ValueError: pass # Build prompt if length is None: map_idx = 0 elif isinstance(length, int): map_idx = 1 elif isinstance(length, str): map_idx = 2 else: raise ValueError(f"Invalid caption length: {length}") prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx] # Add extra options if len(extra_options) > 0: prompt_str += " " + " ".join(extra_options) # Add name, length, word_count prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length) if custom_prompt.strip() != "": prompt_str = custom_prompt.strip() # Resize image to exact dimensions needed image = input_image.resize((384, 384), Image.LANCZOS) image = image.convert('RGB') pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0 pixel_values = TVF.normalize(pixel_values, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) pixel_values = pixel_values.to('cuda', dtype=torch.float16) # Process image with optimized memory usage with torch.amp.autocast('cuda', dtype=torch.float16): vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True) embedded_images = image_adapter(vision_outputs.hidden_states) embedded_images = embedded_images.to('cuda', dtype=torch.float16) # Build the conversation with minimal overhead convo = [ {"role": "system", "content": "You are a helpful image captioner."}, {"role": "user", "content": prompt_str}, ] # Format and tokenize efficiently convo_string = tokenizer.apply_chat_template(convo, tokenize=False, add_generation_prompt=True) convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False) prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False) convo_tokens = convo_tokens.squeeze(0) prompt_tokens = prompt_tokens.squeeze(0) # Calculate injection point eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist() preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Prepare input tensors efficiently convo_tokens = convo_tokens.unsqueeze(0).to('cuda') convo_embeds = text_model.model.embed_tokens(convo_tokens) input_embeds = torch.cat([ convo_embeds[:, :preamble_len], embedded_images, convo_embeds[:, preamble_len:], ], dim=1).to('cuda', dtype=torch.float16) input_ids = torch.cat([ convo_tokens[:, :preamble_len], torch.zeros((1, embedded_images.shape[1]), dtype=torch.long, device='cuda'), convo_tokens[:, preamble_len:], ], dim=1) attention_mask = torch.ones_like(input_ids) # Generate with optimized settings with torch.amp.autocast('cuda', dtype=torch.float16): generate_ids = text_model.generate( input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, use_cache=True, pad_token_id=tokenizer.pad_token_id, num_beams=1, # Disable beam search for faster generation temperature=0.7, # Lower temperature for more focused generation top_p=0.9, # Nucleus sampling for efficiency repetition_penalty=1.2, # Prevent repetition ) # Process output efficiently generate_ids = generate_ids[:, input_ids.shape[1]:] if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"): generate_ids = generate_ids[:, :-1] caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)[0] # Clear memory del vision_outputs, embedded_images, input_embeds, generate_ids torch.cuda.empty_cache() gc.collect() return prompt_str, caption.strip() def process_directory(directory_path, caption_type, caption_length, extra_options, name_input, custom_prompt): processed_images = [] captions = [] for filename in os.listdir(directory_path): if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): img_path = os.path.join(directory_path, filename) img = Image.open(img_path) _, caption = stream_chat(img, caption_type, caption_length, extra_options, name_input, custom_prompt) # Save caption to a .txt file txt_filename = os.path.splitext(filename)[0] + '.txt' txt_path = os.path.join(directory_path, txt_filename) with open(txt_path, 'w', encoding='utf-8') as f: f.write(caption) processed_images.append(img_path) captions.append(caption) return processed_images, "\n\n".join(captions) # Join captions with double newline for readability def process_and_display(images, caption_type, caption_length, extra_options, name_input, custom_prompt): processed_images = [] captions = [] for img_file in images: img = Image.open(img_file.name) _, caption = stream_chat(img, caption_type, caption_length, extra_options, name_input, custom_prompt) processed_images.append(img_file.name) captions.append(caption) return processed_images, "\n\n".join(captions) # Join captions with double newline for readability def process_input(input_images, directory_path, caption_type, caption_length, extra_options, name_input, custom_prompt): if directory_path: return process_directory(directory_path, caption_type, caption_length, extra_options, name_input, custom_prompt) elif input_images: return process_and_display(input_images, caption_type, caption_length, extra_options, name_input, custom_prompt) else: return [], "" # Custom CSS for a futuristic, neon-inspired theme custom_css = """ @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap'); body { background-color: #000000; color: #00FFFF; font-family: 'Orbitron', sans-serif; } .gradio-container { background: linear-gradient(45deg, #1a1a2e, #16213e); border: 2px solid #FF00FF; border-radius: 15px; box-shadow: 0 0 20px #FF00FF; } .input-box, .output-box { background-color: rgba(15, 52, 96, 0.7); border: 1px solid #00FFFF; border-radius: 10px; padding: 15px; margin: 10px 0; box-shadow: 0 0 10px #00FFFF; } .input-box label, .output-box label { color: #FF00FF; font-weight: bold; text-shadow: 0 0 5px #FF00FF; } .gr-button { background: linear-gradient(45deg, #4a0e4e, #7a1e82); border: none; color: #FFFFFF; font-weight: bold; text-transform: uppercase; transition: all 0.3s ease; } .gr-button:hover { background: linear-gradient(45deg, #7a1e82, #4a0e4e); box-shadow: 0 0 15px #FF00FF; transform: scale(1.05); } .gr-dropdown { background-color: #0f3460; border: 1px solid #00FFFF; color: #FFFFFF; } .gr-checkbox-group { background-color: rgba(15, 52, 96, 0.7); border: 1px solid #00FFFF; border-radius: 10px; padding: 10px; } .gr-checkbox-group label { color: #FFFFFF; } .gr-form { border: 1px solid #FF00FF; border-radius: 10px; padding: 20px; margin: 10px 0; background: rgba(26, 26, 46, 0.7); } .gr-input { background-color: #0f3460; border: 1px solid #00FFFF; color: #FFFFFF; border-radius: 5px; } .gr-input:focus { box-shadow: 0 0 10px #00FFFF; } .gr-panel { border: 1px solid #FF00FF; border-radius: 10px; background: rgba(22, 33, 62, 0.7); } """ with gr.Blocks(css=custom_css) as demo: gr.HTML(TITLE) with gr.Row(): with gr.Column(scale=1): input_images = gr.File(file_count="multiple", label="📸 Upload Images", elem_classes="input-box") directory_input = gr.Textbox(label="📁 Or Enter Directory Path", elem_classes="input-box") with gr.Column(scale=2): with gr.Group(): caption_type = gr.Dropdown( choices=list(CAPTION_TYPE_MAP.keys()), label="🎭 Caption Type", value="Descriptive", elem_classes="input-box" ) caption_length = gr.Dropdown( choices=["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)], label="📏 Caption Length", value="long", elem_classes="input-box" ) with gr.Accordion("🔧 Advanced Options", open=False): extra_options = gr.CheckboxGroup( choices=[ "If there is a person/character in the image you must refer to them as {name}.", "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).", "Include information about lighting.", "Include information about camera angle.", "Include information about whether there is a watermark or not.", "Include information about whether there are JPEG artifacts or not.", "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.", "Do NOT include anything sexual; keep it PG.", "Do NOT mention the image's resolution.", "You MUST include information about the subjective aesthetic quality of the image from low to very high.", "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.", "Do NOT mention any text that is in the image.", "Specify the depth of field and whether the background is in focus or blurred.", "If applicable, mention the likely use of artificial or natural lighting sources.", "Do NOT use any ambiguous language.", "Include whether the image is sfw, suggestive, or nsfw.", "ONLY describe the most important elements of the image." ], label="Extra Options", elem_classes="input-box" ) name_input = gr.Textbox(label="👤 Person/Character Name (if applicable)", elem_classes="input-box") gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.") custom_prompt = gr.Textbox(label="🎨 Custom Prompt (optional, will override all other settings)", elem_classes="input-box") gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.") with gr.Row(): run_button = gr.Button("🚀 Generate Captions", elem_classes="gr-button") with gr.Row(): output_gallery = gr.Gallery(label="Processed Images", elem_classes="output-box") output_text = gr.Textbox(label="Generated Captions", elem_classes="output-box", lines=10) run_button.click( fn=process_input, inputs=[input_images, directory_input, caption_type, caption_length, extra_options, name_input, custom_prompt], outputs=[output_gallery, output_text] ) if __name__ == "__main__": demo.launch(share=True)