{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"Dwr7gk5OwuGC"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"1X-s_s971qB7"},"outputs":[],"source":["!apt -y install -qq aria2\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/raw/main/text_model/adapter_config.json -d /content/joy/text_model -o adapter_config.json\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/text_model/adapter_model.safetensors -d /content/joy/text_model -o adapter_model.safetensors\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/clip_model.pt -d /content/joy -o clip_model.pt\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/raw/main/config.yaml -d /content/joy -o config.yaml\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/image_adapter.pt -d /content/joy -o image_adapter.pt\n","\n","!apt -y install -qq aria2\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/raw/main/text_model/adapter_config.json -d /content/joy/text_model -o adapter_config.json\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/text_model/adapter_model.safetensors -d /content/joy/text_model -o adapter_model.safetensors\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/clip_model.pt -d /content/joy -o clip_model.pt\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/raw/main/config.yaml -d /content/joy -o config.yaml\n","!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/camenduru/joy-caption-alpha-one/resolve/main/image_adapter.pt -d /content/joy -o image_adapter.pt\n","\n","# Use a custom prompt to instruct the image captioning model\n","custom_prompt = '' #{type:'string'}\n","enable_custom_prompt = False # {type:'boolean'}\n","if not enable_custom_prompt: custom_prompt = 'Describe the image in 400 words'\n","!pip install peft bitsandbytes\n","!pip install hf_xet\n","from huggingface_hub import InferenceClient\n","from torch import nn\n","from transformers import AutoModel, BitsAndBytesConfig, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM\n","import torch\n","import torch.amp.\n","from PIL import Image\n","import os\n","import torchvision.transforms.functional as TVF\n","\n","CLIP_PATH = \"google/siglip-so400m-patch14-384\"\n","MODEL_PATH = \"unsloth/Meta-Llama-3.1-8B-bnb-4bit\"\n","CAPTION_TYPE_MAP = {\n"," (\"descriptive\", \"formal\", False, False): [f\"{custom_prompt}\"],\n","}\n","\n","class ImageAdapter(nn.Module):\n","\tdef __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):\n","\t\tsuper().__init__()\n","\t\tself.deep_extract = deep_extract\n","\t\tif self.deep_extract:\n","\t\t\tinput_features = input_features * 5\n","\t\tself.linear1 = nn.Linear(input_features, output_features)\n","\t\tself.activation = nn.GELU()\n","\t\tself.linear2 = nn.Linear(output_features, output_features)\n","\t\tself.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)\n","\t\tself.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))\n","\t\tself.other_tokens = nn.Embedding(3, output_features)\n","\t\tself.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3\n","\tdef forward(self, vision_outputs: torch.Tensor):\n","\t\tif self.deep_extract:\n","\t\t\tx = torch.concat((\n","\t\t\t\tvision_outputs[-2],\n","\t\t\t\tvision_outputs[3],\n","\t\t\t\tvision_outputs[7],\n","\t\t\t\tvision_outputs[13],\n","\t\t\t\tvision_outputs[20],\n","\t\t\t), dim=-1)\n","\t\t\tassert len(x.shape) == 3, f\"Expected 3, got {len(x.shape)}\" # batch, tokens, features\n","\t\t\tassert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f\"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}\"\n","\t\telse:\n","\t\t\tx = vision_outputs[-2]\n","\t\tx = self.ln1(x)\n","\t\tif self.pos_emb is not None:\n","\t\t\tassert x.shape[-2:] == self.pos_emb.shape, f\"Expected {self.pos_emb.shape}, got {x.shape[-2:]}\"\n","\t\t\tx = x + self.pos_emb\n","\t\tx = self.linear1(x)\n","\t\tx = self.activation(x)\n","\t\tx = self.linear2(x)\n","\t\tother_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))\n","\t\tassert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f\"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}\"\n","\t\tx = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)\n","\t\treturn x\n","\tdef get_eot_embedding(self):\n","\t\treturn self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)\n","\n","clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)\n","clip_model = AutoModel.from_pretrained(CLIP_PATH)\n","clip_model = clip_model.vision_model\n","checkpoint = torch.load(\"/content/joy/clip_model.pt\", map_location='cpu')\n","checkpoint = {k.replace(\"_orig_mod.module.\", \"\"): v for k, v in checkpoint.items()}\n","clip_model.load_state_dict(checkpoint)\n","# del checkpoint\n","clip_model.eval()\n","clip_model.requires_grad_(False)\n","clip_model.to(\"cuda\")\n","tokenizer = AutoTokenizer.from_pretrained(f'{MODEL_PATH}')\n","#tokenizer = AutoTokenizer.from_pretrained(\"unsloth/Meta-Llama-3.1-8B-bnb-4bit\")\n","assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f\"Tokenizer is of type {type(tokenizer)}\"\n","text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, quantization_config = BitsAndBytesConfig(load_in_8bit=True), device_map=\"auto\", torch_dtype=torch.bfloat16)\n","text_model.load_adapter(\"/content/joy/text_model\")\n","text_model.eval()\n","image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False)\n","image_adapter.load_state_dict(torch.load(\"/content/joy/image_adapter.pt\", map_location=\"cpu\"))\n","image_adapter.eval()\n","image_adapter.to(\"cuda\")"]},{"cell_type":"code","execution_count":24,"metadata":{"id":"PjO3Wc4kzR08","executionInfo":{"status":"ok","timestamp":1753386759521,"user_tz":-120,"elapsed":12,"user":{"displayName":"","userId":""}}},"outputs":[],"source":["# @markdown higher temperature = prompt creativity (default 0.6)
higher top_p = higher noise reduction in latent embedding (default 0.9)\n","temperature = 1.2 # @param {type:'slider',min:0.5,max:4.0,step:0.05}\n","top_p = 0.85 # @param {type:'slider',min:0.1,max:0.95,step:0.05}\n","temperature = float(temperature)\n","top_p = float(top_p)\n","#-----#\n","num=1\n","#import torch\n","#import Image\n","\n","@torch.no_grad()\n","def stream_chat(input_image: Image.Image, prompt_str: str) -> str:\n"," torch.cuda.empty_cache()\n"," length =512\n"," #length = None if caption_length == \"any\" else caption_length\n"," #if isinstance(length, str):\n"," # try:\n"," # length = int(length)\n"," # except ValueError:\n"," # pass\n"," #if caption_type == \"rng-tags\" or caption_type == \"training_prompt\":\n"," # caption_tone = \"formal\"\n"," #prompt_key = (caption_type, caption_tone, isinstance(length, str), isinstance(length, int))\n"," #if prompt_key not in CAPTION_TYPE_MAP:\n"," # raise ValueError(f\"Invalid caption type: {prompt_key}\")\n"," #prompt_str = CAPTION_TYPE_MAP[prompt_key][0].format(length=length, word_count=length)\n"," print(f\"Prompt: {prompt_str}\")\n"," image = input_image.resize((384, 384), Image.LANCZOS)\n"," pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0\n"," pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])\n"," pixel_values = pixel_values.to('cuda')\n"," prompt = tokenizer.encode(prompt_str, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)\n"," with torch.amp.autocast_mode.autocast('cuda', enabled=True):\n"," vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)\n"," image_features = vision_outputs.hidden_states\n"," embedded_images = image_adapter(image_features)\n"," embedded_images = embedded_images.to('cuda')\n"," prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))\n"," 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)}\"\n"," embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))\n"," eot_embed = image_adapter.get_eot_embedding().unsqueeze(0).to(dtype=text_model.dtype)\n"," inputs_embeds = torch.cat([\n"," embedded_bos.expand(embedded_images.shape[0], -1, -1),\n"," embedded_images.to(dtype=embedded_bos.dtype),\n"," prompt_embeds.expand(embedded_images.shape[0], -1, -1),\n"," eot_embed.expand(embedded_images.shape[0], -1, -1),\n"," ], dim=1)\n"," input_ids = torch.cat([\n"," torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),\n"," torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),\n"," prompt,\n"," torch.tensor([[tokenizer.convert_tokens_to_ids(\"<|eot_id|>\")]], dtype=torch.long),\n"," ], dim=1).to('cuda')\n"," attention_mask = torch.ones_like(input_ids)\n"," generate_ids = text_model.generate(input_ids, top_p = top_p , temperature=temperature, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=3000, do_sample=True, suppress_tokens=None) # Uses the default which is temp=0.6, top_p=0.9\n"," generate_ids = generate_ids[:, input_ids.shape[1]:]\n"," if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids(\"<|eot_id|>\"):\n"," generate_ids = generate_ids[:, :-1]\n"," caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]\n"," caption = f'{caption.strip()}'.replace('Prompt: Describe the image in 400 words','')\n"," return caption"]},{"cell_type":"code","source":["\n","%cd /content/\n","!unzip training_data.zip\n","\n","\n","\n","\n","\n","\n","\n"],"metadata":{"id":"c60a6jW-YwsN","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1753386762570,"user_tz":-120,"elapsed":61,"user":{"displayName":"","userId":""}},"outputId":"d1522c03-a056-452d-b017-92f2df0faed8"},"execution_count":25,"outputs":[{"output_type":"stream","name":"stdout","text":["/content\n","Archive: training_data.zip\n"," extracting: 000.txt \n"," extracting: 001.txt \n"," extracting: 002.txt \n"," extracting: 003.txt \n"," extracting: 004.txt \n"," extracting: 005.txt \n"," extracting: 006.txt \n"," extracting: 007.txt \n"," extracting: 008.txt \n"," extracting: 009.txt \n"," extracting: 010.txt \n"," extracting: 011.txt \n"," extracting: 012.txt \n"," extracting: 013.txt \n"," extracting: 014.txt \n"," extracting: 015.txt \n"," extracting: 016.txt \n"," extracting: 017.txt \n"," extracting: 018.txt \n"," extracting: 019.txt \n"," extracting: 020.txt \n"," extracting: 021.txt \n"," extracting: 022.txt \n"," extracting: 023.txt \n"," extracting: 024.txt \n"," extracting: 025.txt \n"," extracting: 026.txt \n"," extracting: 027.txt \n"," extracting: 028.txt \n"," extracting: 029.txt \n"," extracting: 030.txt \n"," extracting: 031.txt \n"," extracting: 032.txt \n"," extracting: 033.txt \n"," extracting: 034.txt \n"," extracting: 035.txt \n"," extracting: 036.txt \n"," extracting: 037.txt \n"," extracting: 038.txt \n"," extracting: 039.txt \n"," extracting: 040.txt \n"," extracting: 041.txt \n"," extracting: 042.txt \n"," extracting: 043.txt \n"," extracting: 044.txt \n"," extracting: 045.txt \n"," extracting: 046.txt \n"," extracting: 047.txt \n"," extracting: 048.txt \n"," extracting: 049.txt \n"," extracting: 050.txt \n"," extracting: 051.txt \n"," extracting: 052.txt \n"," extracting: 053.txt \n"," extracting: 054.txt \n"," extracting: 055.txt \n"," extracting: 056.txt \n"," extracting: 057.txt \n"," extracting: 058.txt \n"," extracting: 059.txt \n"," extracting: 000.jpg \n"," extracting: 001.jpg \n"," extracting: 002.jpg \n"," extracting: 003.jpg \n"," extracting: 004.jpg \n"," extracting: 005.jpg \n"," extracting: 006.jpg \n"," extracting: 007.jpg \n"," extracting: 008.jpg \n"," extracting: 009.jpg \n"," extracting: 010.jpg \n"," extracting: 011.jpg \n"," extracting: 012.jpg \n"," extracting: 013.jpg \n"," extracting: 014.jpg \n"," extracting: 015.jpg \n"," extracting: 016.jpg \n"," extracting: 017.jpg \n"," extracting: 018.jpg \n"," extracting: 019.jpg \n"," extracting: 020.jpg \n"," extracting: 021.jpg \n"," extracting: 022.jpg \n"," extracting: 023.jpg \n"," extracting: 024.jpg \n"," extracting: 025.jpg \n"," extracting: 026.jpg \n"," extracting: 027.jpg \n"," extracting: 028.jpg \n"," extracting: 029.jpg \n"," extracting: 030.jpg \n"," extracting: 031.jpg \n"," extracting: 032.jpg \n"," extracting: 033.jpg \n"," extracting: 034.jpg \n"," extracting: 035.jpg \n"," extracting: 036.jpg \n"," extracting: 037.jpg \n"," extracting: 038.jpg \n"," extracting: 039.jpg \n"," extracting: 040.jpg \n"," extracting: 041.jpg \n"," extracting: 042.jpg \n"," extracting: 043.jpg \n"," extracting: 044.jpg \n"," extracting: 045.jpg \n"," extracting: 046.jpg \n"," extracting: 047.jpg \n"," extracting: 048.jpg \n"," extracting: 049.jpg \n"," extracting: 050.jpg \n"," extracting: 051.jpg \n"," extracting: 052.jpg \n"," extracting: 053.jpg \n"," extracting: 054.jpg \n"," extracting: 055.jpg \n"," extracting: 056.jpg \n"," extracting: 057.jpg \n"," extracting: 058.jpg \n"," extracting: 059.jpg \n"]}]},{"cell_type":"code","execution_count":26,"metadata":{"id":"mhccTDyzirVn","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1753386767706,"user_tz":-120,"elapsed":1275,"user":{"displayName":"","userId":""}},"outputId":"2f9edfd6-5ecc-4ea0-b97e-761617b0fff2"},"outputs":[{"output_type":"stream","name":"stdout","text":["Splitting all images found under /content/... \n"," into 1 along x-axis\n","/content\n","021.jpg\n","/content\n","/content/split\n","/content\n","breasts, multiple girls, 2girls, animal ears, blue eyes, navel, large breasts, weapon, thighhighs, blonde hair, sword, flower, hair flower, fox ears, long hair, hair ornament, animal ear fluff, twintails, holding, sideboob, blue flower, gloves, tail, smile, short hair, virtual youtuber, holding weapon, white hair, fox girl, tiara\n","/content/split\n","041.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1girl, 1boy, couch, red hair, white hair, shirt, necktie, yellow eyes, sitting, letterboxed, crossover, fake screenshot, braided ponytail, braid, english text, white shirt, ringed eyes, black necktie, pants, collared shirt, eyepatch, vest, long sleeves, jacket, holding, short hair, looking at viewer, smile\n","/content/split\n","015.jpg\n","/content\n","/content/split\n","/content\n","1girl, breasts, long hair, halo, solo, wings, large breasts, angel, cleavage, dress, navel, purple hair, white dress, see-through, full body, english text, angel wings, looking at viewer, fake screenshot, subtitled\n","/content/split\n","028.jpg\n","/content\n","/content/split\n","/content\n","motion blur, english text, television, subtitled, 1boy, indoors, male focus, blurry\n","/content/split\n","054.jpg\n","/content\n","/content/split\n","/content\n","1girl, pointy ears, solo, twintails, elf, long hair, microphone, hand on own face, green eyes, upper body, hand on own cheek\n","/content/split\n","010.jpg\n","/content\n","/content/split\n","/content\n","long hair, english text, 1girl, subtitled, monitor, chair, television, blonde hair, computer, curtains, bed, indoors, blanket, brown hair, window, solo, under covers\n","/content/split\n","019.jpg\n","/content\n","/content/split\n","/content\n","blonde hair, solo, english text, purple eyes, 1boy, male focus, subtitled, long hair, cup, shirt, anime coloring, purple shirt, looking at viewer, parody, indoors\n","/content/split\n","042.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1boy, male focus, brown hair, solo, fake screenshot, jacket, open mouth, green eyes, track jacket, english text, anime coloring, parody, upper body, short hair, black shirt\n","/content/split\n","059.jpg\n","/content\n","/content/split\n","/content\n","multiple boys, english text, male focus, facial hair, shirt, subtitled, white shirt, train interior\n","/content/split\n","011.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, brown eyes, brown hair, no headwear, smile, long hair, open mouth, english text, looking at viewer, headset, headphones, pajamas, fake screenshot, solo, shirt, parody, bangs, :d\n","/content/split\n","039.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, necktie, solo, subtitled, formal, drinking glass, english text, suit, facial hair, old man, old, beard, cup, green necktie, grey hair, indoors, sitting, bottle, fake screenshot, plant, alcohol, own hands together, jacket, long sleeves, wine glass, shirt, table\n","/content/split\n","005.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, solo, facial hair, english text, white hair, sunglasses, meme, beard, subtitled, tank top, bald, old man, parody, old, upper body, window, indoors\n","/content/split\n","036.jpg\n","/content\n","/content/split\n","/content\n","1girl, 1boy, couch, red hair, ringed eyes, shirt, yellow eyes, white hair, necktie, braided ponytail, sitting, braid, black necktie, letterboxed, short hair, crossover, collared shirt, indoors, vest\n","/content/split\n","052.jpg\n","/content\n","/content/split\n","/content\n","long hair, blue hair, solo, teeth, clenched teeth, 1girl, hair between eyes, english text, long sleeves, angry\n","/content/split\n","038.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, 1boy, couch, yellow eyes, red hair, english text, eyepatch, white hair, sitting, letterboxed, crossover, shirt, braided ponytail, necktie, ringed eyes, braid, smile, own hands together, indoors, cup, breasts, jacket\n","/content/split\n","000.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, 1boy, coat, breasts, fake screenshot, black hair, parody, cleavage, trench coat, short hair, english text, long hair, blue hair, scene reference\n","/content/split\n","044.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1boy, male focus, brown hair, solo, fake screenshot, green eyes, jacket, hand on own face, anime coloring, looking at viewer, parody, indoors, track jacket, english text, hand on own cheek, short hair, upper body, meme, open mouth\n","/content/split\n","027.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, english text, solo, subtitled, mask, open mouth, superhero, parody, window\n","/content/split\n","020.jpg\n","/content\n","/content/split\n","/content\n","1girl, blonde hair, fake screenshot, blue eyes, breasts, long hair, 1boy, hair ornament, smile, gloves, cleavage, thighhighs, elbow gloves, flower, bikini armor, glasses, chibi, hair flower, sitting\n","/content/split\n","023.jpg\n","/content\n","/content/split\n","/content\n","breasts, multiple girls, weapon, large breasts, long hair, thighhighs, holding, hair ornament, blue eyes, navel, flower, hair flower, gloves, sword, blonde hair, twintails, red hair, holding weapon, headgear, copyright name, armor, panties, sideboob, cleavage, looking at viewer, underwear, polearm, animal ears, hat, black panties\n","/content/split\n","014.jpg\n","/content\n","/content/split\n","/content\n","blonde hair, 1boy, male focus, english text, subtitled, solo, shirt, purple shirt, long hair, blurry, blurry background, instrument, upper body, phonograph\n","/content/split\n","055.jpg\n","/content\n","/content/split\n","/content\n","1girl, 1boy, pointy ears, elf, twintails, long hair, gloves, fingerless gloves, white hair, plant, smile, armor, jacket, blue eyes\n","/content/split\n","033.jpg\n","/content\n","/content/split\n","/content\n","animal ears, 1girl, tail, subtitled, fox ears, fox tail, microphone, 1boy, multiple tails, japanese clothes, english text, mask, holding, fox girl, bangs, short hair, detached sleeves, parody, open mouth, smile, indoors, blush, crossover, red eyes, holding microphone\n","/content/split\n","008.jpg\n","/content\n","/content/split\n","/content\n","blurry, sailor collar, yellow-framed eyewear, glasses, purple eyes, star hair ornament, short hair, 1girl, blurry background, school uniform, shirt, bangs, serafuku, looking at viewer, hair ornament, closed mouth, depth of field, purple hair, neckerchief, smile, yellow neckerchief, star (symbol), parody, upper body\n","/content/split\n","046.jpg\n","/content\n","/content/split\n","/content\n","male focus, 1boy, solo, mole under eye, mole, parody, green eyes, ahoge, shirt, covering mouth, upper body, blonde hair, brown hair, wooden wall, meme\n","/content/split\n","018.jpg\n","/content\n","/content/split\n","/content\n","english text, no humans, text focus, sparkle, parody, logo\n","/content/split\n","035.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, necktie, solo, subtitled, formal, suit, drinking glass, facial hair, sitting, old man, grey hair, cup, english text, beard, old, indoors, green necktie, fake screenshot, bottle, jacket, plant, long sleeves, table, alcohol, shirt, looking at viewer, collared shirt, wine glass\n","/content/split\n","049.jpg\n","/content\n","/content/split\n","/content\n","fake screenshot, multiple boys, brown hair, blue hair, yellow eyes, black hair, 2boys, brown eyes, hair between eyes, open mouth, green eyes, subtitled, sweatdrop, anime coloring, looking at viewer, short hair, one eye closed, bangs, long hair\n","/content/split\n","051.jpg\n","/content\n","/content/split\n","/content\n","phone, cellphone, english text, 1girl, smartphone, chat log, solo, nude, brown hair, long hair\n","/content/split\n","056.jpg\n","/content\n","/content/split\n","/content\n","1girl, pointy ears, subtitled, solo, closed eyes, twintails, english text, long hair, microphone, hand on own face, white hair, upper body, long sleeves, elf\n","/content/split\n","037.jpg\n","/content\n","/content/split\n","/content\n","1girl, 1boy, couch, yellow eyes, white hair, ringed eyes, red hair, shirt, sitting, necktie, braided ponytail, crossover, braid, short hair, sunglasses, letterboxed, eyepatch, own hands together, collared shirt, breasts, black necktie, jacket\n","/content/split\n","012.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, solo, black hair, long hair, open mouth, indoors, hair between eyes, english text, fake screenshot, anime coloring, shirt, brown eyes\n","/content/split\n","009.jpg\n","/content\n","/content/split\n","/content\n","solo, subtitled, 1girl, long hair, black hair, indoors, fake screenshot, hair between eyes, english text, anime coloring, shirt, parody\n","/content/split\n","017.jpg\n","/content\n","/content/split\n","/content\n","english text, mouse (computer), computer, keyboard (computer), monitor, headphones, indoors, chair, laptop, 1boy\n","/content/split\n","007.jpg\n","/content\n","/content/split\n","/content\n","bald, 1boy, male focus, solo, old man, facial hair, subtitled, english text, sweat, old, sunglasses, palm tree, beard, meme, parody, white hair, sky, glasses, cloud, sweatdrop, tree\n","/content/split\n","031.jpg\n","/content\n","/content/split\n","/content\n","english text, television, subtitled, indoors, blurry, no humans, fake screenshot\n","/content/split\n","004.jpg\n","/content\n","/content/split\n","/content\n","bald, 1boy, male focus, solo, facial hair, english text, parody, beard, white hair, old man, tank top, glasses, window, meme, subtitled, old, indoors, red-framed eyewear, mustache, sunglasses\n","/content/split\n","016.jpg\n","/content\n","/content/split\n","/content\n","english text, subtitled, indoors, fake screenshot, holding, pov, tiles\n","/content/split\n","058.jpg\n","/content\n","/content/split\n","/content\n","train interior, male focus, 1boy, spiked hair, blonde hair, solo, sitting, red eyes, shirt, crossed arms, grey shirt, ground vehicle, from side, t-shirt, sweatdrop\n","/content/split\n","013.jpg\n","/content\n","/content/split\n","/content\n","1girl, blonde hair, long hair, bed, english text, curtains, under covers, looking at viewer, green eyes, book, solo, blanket, subtitled, indoors, clock, nude, on bed, yellow eyes, bed sheet\n","/content/split\n","029.jpg\n","/content\n","/content/split\n","/content\n","english text, weapon, multiple boys, sword, subtitled, letterboxed, soldier, armor\n","/content/split\n","050.jpg\n","/content\n","/content/split\n","/content\n","mole under eye, 1boy, mole, male focus, green eyes, phone, teeth, solo, blonde hair, fake screenshot, clenched teeth, holding, subtitled, cellphone, holding phone, parody, bangs, smartphone\n","/content/split\n","048.jpg\n","/content\n","/content/split\n","/content\n","1boy, solo, male focus, closed eyes, subtitled, mole under eye, mole, smile, fake screenshot, blonde hair, parody, upper body, indoors, wooden wall, english text\n","/content/split\n","045.jpg\n","/content\n","/content/split\n","/content\n","1boy, subtitled, male focus, solo, short hair, black hair, jacket, hair slicked back, open mouth, indoors, brown eyes, fake screenshot, track jacket, from side, english text, anime coloring, upper body, profile\n","/content/split\n","043.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1boy, male focus, fake screenshot, solo, clenched teeth, teeth, parody, brown hair, anime coloring, english text, profile\n","/content/split\n","006.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, english text, cup, facial hair, solo, bald, indoors, old man, lamp, white hair, old, table, smoking, subtitled, meme, chair, sunglasses, mustache, sitting, parody, cigarette, beard\n","/content/split\n","001.jpg\n","/content\n","/content/split\n","/content\n","subtitled, multiple boys, 2boys, facial hair, male focus, english text, fake screenshot, hat, beard, parody, black hair, short hair, scene reference, night, jacket, looking at another, upper body, monochrome\n","/content/split\n","003.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, closed eyes, pink hair, solo, english text, blush, smile, close-up, short hair, fake screenshot\n","/content/split\n","057.jpg\n","/content\n","/content/split\n","/content\n","1girl, 1boy, blonde hair, earrings, jewelry, blue eyes, formal, english text, suit, subtitled, long hair, shirt, dress, red dress, meme\n","/content/split\n","024.jpg\n","/content\n","/content/split\n","/content\n","fake screenshot, multiple girls, 6+girls, motor vehicle, multiple boys, ground vehicle, english text, long hair\n","/content/split\n","040.jpg\n","/content\n","/content/split\n","/content\n","1girl, subtitled, 1boy, couch, shirt, white hair, yellow eyes, red hair, necktie, braided ponytail, sitting, letterboxed, ringed eyes, black necktie, braid, english text, crossover, collared shirt, jacket, breasts, white shirt, vest, short hair, jacket on shoulders, pants, eyepatch, long sleeves\n","/content/split\n","022.jpg\n","/content\n","/content/split\n","/content\n","multiple boys, blonde hair, shirt, english text, brown hair, long hair, multiple girls, 2girls, plant, ponytail, subtitled, television, meme, indoors, short hair, yellow shirt, 3boys, black hair, brown eyes, blue shirt, sitting, t-shirt, black shirt, bangs\n","/content/split\n","053.jpg\n","/content\n","/content/split\n","/content\n","long hair, blue hair, solo, open mouth, english text, 1girl, hair between eyes, long sleeves, angry\n","/content/split\n","032.jpg\n","/content\n","/content/split\n","/content\n","1girl, tail, animal ears, fox tail, fox ears, subtitled, solo, multiple tails, microphone, mask, english text, closed eyes, short hair, singing, fox girl, multicolored hair, open mouth, japanese clothes, fox mask, music, mask on head, bangs, holding, blush, sweatdrop, brown hair\n","/content/split\n","030.jpg\n","/content\n","/content/split\n","/content\n","1boy, male focus, mask, superhero, solo, english text, cape, muscular, window, parody, smile, bodysuit, waving, belt\n","/content/split\n","034.jpg\n","/content\n","/content/split\n","/content\n","1girl, solo, black hair, blue eyes, long hair, blush, looking at viewer, sweatdrop, english text, open mouth, subtitled, bangs, portrait, close-up\n","/content/split\n","002.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1girl, 1boy, breasts, black hair, cleavage, long hair, large breasts, coat, lipstick, makeup, english text, parody, turtleneck, short hair, blue eyes, fake screenshot, anime coloring, choker, scarf, collarbone\n","/content/split\n","047.jpg\n","/content\n","/content/split\n","/content\n","subtitled, 1boy, male focus, solo, black hair, indoors, short hair, hair slicked back, jacket, fake screenshot, english text, from side, profile, parody, track jacket, sweatdrop\n","/content/split\n","025.jpg\n","/content\n","/content/split\n","/content\n","1girl, 1boy, breasts, gloves, large breasts, long hair, hat, blue eyes, brown eyes, brown hair\n","/content/split\n","026.jpg\n","/content\n","/content/split\n","/content\n","subtitled, multiple boys, fake screenshot, letterboxed, weapon, english text, armor, sword, parody, helmet, male focus, black hair\n","/content/split\n"]}],"source":["# @markdown Split the image into 20 parts prior to running\n","no_parts = 1 # @param {type:'slider', min:1,max:30,step:1}\n","print(f'Splitting all images found under /content/... \\n into {no_parts} along x-axis')\n","import os,math,random\n","from PIL import Image\n","home_directory = '/content/'\n","using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n","if using_Kaggle : home_directory = '/kaggle/working/'\n","%cd {home_directory}\n","\n","def my_mkdirs(folder):\n"," if os.path.exists(folder)==False:\n"," os.makedirs(folder)\n","\n","\n","tgt_folder = f'/content/tmp/'\n","split_folder = f'/content/split/'\n","my_mkdirs(f'{split_folder}')\n","\n","\n","src_folder = '/content/'\n","suffixes = ['.gif','.png', '.jpeg' , '.webp' , '.jpg']\n","#num = 1\n","for filename in os.listdir(src_folder):\n"," for suffix in suffixes:\n"," if not filename.find(suffix)>-1: continue\n"," #while os.path.exists(f'{tgt_folder}{num}.txt'):num = num+1\n"," print(filename)\n"," %cd {src_folder}\n"," textpath = filename.replace(suffix,'.txt')\n"," #os.remove(f'{filename}')\n"," #continue\n"," image = Image.open(f\"{filename}\").convert('RGB')\n"," w,h=image.size\n"," #grid = product(range(0, h-h%d, d), range(0, w-w%d, d))\n"," divs=no_parts\n"," step=math.floor(w/divs)\n"," %cd {split_folder}\n"," for index in range(divs):\n"," box = (step*index, 0 ,step*(index+1),math.floor(1.0*h))\n"," image.crop(box).save(f'{num}_{index}.jpeg','JPEG')\n"," %cd /content/\n"," if os.path.exists(textpath):\n"," with open(f'{textpath}', 'r') as file:\n"," _tags = file.read()\n","\n"," print(_tags)\n"," if not _tags:continue\n"," tags=''\n"," _tags = [item.strip() for item in f'{_tags}'.split(',')]\n"," random.shuffle(_tags)\n"," for tag in _tags:\n"," tags = tags + tag + ' , '\n"," #----#\n"," tags = (tags + 'AAAA').replace(' , AAAA','')\n"," prompt_str = f' {tags}'\n"," %cd {split_folder}\n"," f = open(f'{num}_{index}.txt','w')\n"," f.write(f'{prompt_str}')\n"," f.close()\n"," #---#\n"," #-----#\n"," #----#\n"," num = num+1\n"," #caption = stream_chat(input_image, \"descriptive\", \"formal\", \"any\")\n"," #print(f\"...\\n\\n...caption for {filename}\\n\\n...\")\n"," #print(caption)\n"," #---------#\n"," #f = open(f\"{num}.txt\", \"w\")\n"," #f.write(f'{caption}')\n"," #f.close()\n"," #input_image.save(f'{num}.jpeg', \"JPEG\")\n"," os.remove(f\"{src_folder}{filename}\")\n"," os.remove(f'{src_folder}{textpath}')"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"J811UZU6xZEo","colab":{"base_uri":"https://localhost:8080/"},"outputId":"8d14c96f-f62c-4c0f-9690-f0b4e3d89221"},"outputs":[{"output_type":"stream","name":"stdout","text":["/content\n","42_0.jpeg\n","/content/split\n","Prompt: Describe the image in 400 words , and the colors in the anime screencap and the subtitles text mole , mole under eye , holding , parody , green eyes , bangs , holding phone , male focus , clenched teeth , 1boy , smartphone , phone , teeth , cellphone , fake screenshot , subtitled , solo , blonde hair\n","...\n","\n","...caption for 42_0.jpeg\n","\n","...\n","A screencap from an anime where a young man is in a comical scene. The main character is a Caucasian male with short blonde hair and green eyes, with a prominent mole just below his right eye. His face is filled with a wild expression, with his teeth clenched as if he was shouting or grinning fiercely. He has a mole above his upper lip and another above his right eye. His face is framed against a dark brown, blurred background suggesting an indoor environment.\n","\n","His right hand grips a dark blue smartphone, the brand clearly marked with 4 cameras at the back. The bottom of the screencap reads, \"Oh my gosh!\", followed by another line in white lowercase, \"Fucking shit!\", suggesting an angry, frustrated reaction. This text sits below his image, aligning perfectly with the frame. The art style of this screencap features smooth shading with clear, defined lines, using traditional 2D animation and a vibrant color palette. mole , mole under eye , holding , parody , green eyes , bangs , holding phone , male focus , clenched teeth , 1boy , smartphone , phone , teeth , cellphone , fake screenshot , subtitled , solo , blonde hair\n","/content/tmp\n","2_0.jpeg\n","/content/split\n","Prompt: Describe the image in 400 words , and the colors in the anime screencap and the subtitles text eyepatch , short hair , letterboxed , braided ponytail , fake screenshot , subtitled , braid , necktie , red hair , english text , pants , holding , smile , sitting , long sleeves , couch , collared shirt , looking at viewer , white shirt , vest , black necktie , yellow eyes , ringed eyes , crossover , 1girl , 1boy , jacket , white hair , shirt\n","...\n","\n","...caption for 2_0.jpeg\n","\n","...\n","\"technically speaking the zero would be nothing\" is a funny dialogue at the bottom. A man sits next to a woman on a couch at a night venue. The man with light white hair is sitting, legs stretched out to each side. He wears a white collared shirt, a black necktie, a dark green vest, a white cap, and a pair of dark rectangular sunglasses. He is leaning back, legs crossed at the ankles. The woman, facing forward, has short reddish hair with a ponytail and a side braid. She's wearing a dark blazer and a beige shirt, a grey skirt, with a drink, a cup, and a phone in her right hand. The background has vertical dark curtains on the left, a wooden chair or table, and a dark brick wall on the eyepatch , short hair , letterboxed , braided ponytail , fake screenshot , subtitled , braid , necktie , red hair , english text , pants , holding , smile , sitting , long sleeves , couch , collared shirt , looking at viewer , white shirt , vest , black necktie , yellow eyes , ringed eyes , crossover , 1girl , 1boy , jacket , white hair , shirt\n","/content/tmp\n","9_0.jpeg\n","/content/split\n","Prompt: Describe the image in 400 words , and the colors in the anime screencap and the subtitles text multiple boys , train interior , english text , facial hair , white shirt , male focus , subtitled , shirt\n","...\n","\n","...caption for 9_0.jpeg\n","\n","...\n","A man is sitting on a train with a book and wearing a blue shirt, light blue tie and black jeans. A woman sits beside him wearing a white shirt with black shorts. They are sitting close to each other with a noticeable distance between their bodies. Text reads, “We are in a fucking tin can…” on the bottom of the image. multiple boys , train interior , english text , facial hair , white shirt , male focus , subtitled , shirt\n","/content/tmp\n","35_0.jpeg\n","/content/split\n","Prompt: Describe the image in 400 words , and the colors in the anime screencap and the subtitles text old man , solo , sunglasses , parody , bald , facial hair , 1boy , meme , english text , subtitled , sky , tree , sweatdrop , palm tree , sweat , white hair , cloud , male focus , beard , glasses , old\n","...\n","\n","...caption for 35_0.jpeg\n","\n","...\n","Close-up of an old man, shown in a humorous anime style with exaggerated features, sweating heavily and looking like he's about to cry, sitting near a palm tree. The man wears a green shirt, large yellow sunglasses with tinted lenses, and appears to be wiping his brow with a hand that's off-screen. His nose is bulbous, and he has short grey hair and a thin, slightly graying beard. The sky and palm tree are drawn in a cartoonish style, and the text on the bottom of the image says, \"and get a lap dance and cum and walk up out of there feeling horrible.\" The setting implies a scene from a sci-fi or fantasy movie. old man , solo , sunglasses , parody , bald , facial hair , 1boy , meme , english text , subtitled , sky , tree , sweatdrop , palm tree , sweat , white hair , cloud , male focus , beard , glasses , old\n","/content/tmp\n","23_0.jpeg\n","/content/split\n","Prompt: Describe the image in 400 words , and the colors in the anime screencap and the subtitles text fox ears , parody , animal ears , mask , blush , subtitled , detached sleeves , 1boy , indoors , 1girl , short hair , english text , crossover , fox girl , open mouth , holding , multiple tails , tail , microphone , holding microphone , japanese clothes , smile , red eyes , bangs , fox tail\n"]}],"source":["\n","import os,random\n","from PIL import Image\n","home_directory = '/content/'\n","using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n","if using_Kaggle : home_directory = '/kaggle/working/'\n","%cd {home_directory}\n","\n","def my_mkdirs(folder):\n"," if os.path.exists(folder)==False:\n"," os.makedirs(folder)\n","\n","\n","tgt_folder = f'/content/tmp/'\n","my_mkdirs(f'{tgt_folder}')\n","split_folder = '/content/split/'\n","src_folder = '/content/'\n","if os.path.exists(f'{split_folder}'): src_folder = f'{split_folder}'\n","suffixes = ['.gif','.png', '.jpeg' , '.webp' , '.jpg']\n","num = 1\n","for filename in os.listdir(src_folder):\n"," for suffix in suffixes:\n"," if not filename.find(suffix)>-1: continue\n"," while os.path.exists(f'{tgt_folder}{num}.txt'):num = num+1\n"," print(filename)\n"," %cd {src_folder}\n"," textpath = filename.replace(suffix,'.txt')\n"," prompt_str = 'Describe the image in 400 words , and the colors in the anime screencap and the subtitles text '\n"," if os.path.exists(f'{src_folder}{textpath}'):\n"," with open(f'{textpath}', 'r') as file:\n"," tags = file.read()\n"," #prompt_str = f'Please improve this prompt : {tags}'\n"," input_image = Image.open(f\"{filename}\").convert('RGB')\n"," caption = stream_chat(input_image, f'{prompt_str} {tags}')\n"," caption = caption + tags\n"," #caption = caption + \", and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\"\n"," print(f\"...\\n\\n...caption for {filename}\\n\\n...\")\n"," print(caption)\n"," #---------#\n"," %cd {tgt_folder}\n"," f = open(f\"a{num}.txt\", \"w\")\n"," f.write(f'{caption}')\n"," f.close()\n"," input_image.save(f'a{num}.jpeg', \"JPEG\")\n"," os.remove(f\"{src_folder}{filename}\")\n"," os.remove(f'{src_folder}{textpath}')\n"," num = num+1"]},{"cell_type":"code","execution_count":23,"metadata":{"id":"5EztLCjkPq4U","colab":{"base_uri":"https://localhost:8080/","height":54},"executionInfo":{"status":"ok","timestamp":1753386278449,"user_tz":-120,"elapsed":258,"user":{"displayName":"","userId":""}},"outputId":"abeea3bf-833a-47ae-f7b8-1f093a214e50"},"outputs":[{"output_type":"stream","name":"stdout","text":["/content\n"]},{"output_type":"execute_result","data":{"text/plain":["'/content/tmp.zip'"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":23}],"source":["import shutil\n","%cd /content/\n","shutil.make_archive('/content/tmp', 'zip', '/content/tmp')"]},{"cell_type":"code","source":["# @markdown Save images of all urls found in image_urls.txt to workspace\n","\n","!wget -i image_urls.txt -P ./splits\n","\n"],"metadata":{"id":"v9UMCh3h_mNj"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"kM4TpfdB1amt"},"outputs":[],"source":["# @markdown Auto-disconnect from Google Colab upon running this cell\n","from google.colab import runtime\n","#runtime.unassign() #Disconnect from runtime"]}],"metadata":{"accelerator":"GPU","colab":{"gpuType":"T4","provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1753386997714},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1753384460583},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1753179095950},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1753120703402},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1752593897385},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1752405756026},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1748859170548},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1747227021653},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1747225778912},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1747224652750},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1746209168116},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1746181687155},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1742303655056},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1740768524003},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1740657473013},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1739796923572},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Joycaption_Alpha_One.ipynb","timestamp":1739735627072}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}