Datasets:
Tags:
Not-For-All-Audiences
Upload Joycaption_Alpha_One.ipynb
Browse files
Joycaption_Alpha_One.ipynb
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"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","# @markdown Use a custom prompt to instruct the image captioning model\n","custom_prompt = 'Write a natural language prompt using e621 and/or danbooru tags in multiple sentences of 400 words or tags' # @param {type:'string'}\n","enable_custom_prompt = False # @param {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.autocast_mode\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"," (\"descriptive\", \"formal\", False, True): [\"Write a descriptive caption for this image in a formal tone within {word_count} words.\"],\n"," (\"descriptive\", \"formal\", True, False): [\"Write a {length} descriptive caption for this image in a formal tone.\"],\n"," (\"descriptive\", \"informal\", False, False): [\"Write a descriptive caption for this image in a casual tone.\"],\n"," (\"descriptive\", \"informal\", False, True): [\"Write a descriptive caption for this image in a casual tone within {word_count} words.\"],\n"," (\"descriptive\", \"informal\", True, False): [\"Write a {length} descriptive caption for this image in a casual tone.\"],\n"," (\"training_prompt\", \"formal\", False, False): [\"Write a stable diffusion prompt for this image.\"],\n"," (\"training_prompt\", \"formal\", False, True): [\"Write a stable diffusion prompt for this image within {word_count} words.\"],\n"," (\"training_prompt\", \"formal\", True, False): [\"Write a {length} stable diffusion prompt for this image.\"],\n"," (\"rng-tags\", \"formal\", False, False): [\"Write a list of Booru tags for this image.\"],\n"," (\"rng-tags\", \"formal\", False, True): [\"Write a list of Booru tags for this image within {word_count} words.\"],\n"," (\"rng-tags\", \"formal\", True, False): [\"Write a {length} list of Booru tags for this image.\"],\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","source":["#urls=[\"https://imx.to/i/67yoyb\",\"https://imx.to/i/67yovt\",\"https://imx.to/i/67yozl\",\"https://imx.to/i/67yows\",\"https://imx.to/i/67youk\",\"https://imx.to/i/67yoxy\",\"https://imx.to/i/67yoz9\",\"https://imx.to/i/67yown\",\"https://imx.to/i/67youc\",\"https://imx.to/i/67yovj\",\"https://imx.to/i/67yoyw\",\"https://imx.to/i/67yowf\",\"https://imx.to/i/67yp0d\",\"https://imx.to/i/67yoxb\",\"https://imx.to/i/67yov6\",\"https://imx.to/i/67yoym\",\"https://imx.to/i/67yozz\",\"https://imx.to/i/67yox4\",\"https://imx.to/i/67yow1\",\"https://imx.to/i/67yowz\",\"https://imx.to/i/67youn\",\"https://imx.to/i/67yovy\",\"https://imx.to/i/67yozm\",\"https://imx.to/i/67yowt\",\"https://imx.to/i/67yoxz\",\"https://imx.to/i/67yovn\",\"https://imx.to/i/67yozb\",\"https://imx.to/i/67you7\",\"https://imx.to/i/67yoxc\",\"https://imx.to/i/67yov4\",\"https://imx.to/i/67yow6\",\"https://imx.to/i/67yozv\",\"https://imx.to/i/67yovv\",\"https://imx.to/i/67yozo\",\"https://imx.to/i/67youh\",\"https://imx.to/i/67yowm\",\"https://imx.to/i/67youd\",\"https://imx.to/i/67yoxr\",\"https://imx.to/i/67yovf\",\"https://imx.to/i/67yoyx\",\"https://imx.to/i/67yowg\",\"https://imx.to/i/67yp0e\",\"https://imx.to/i/67yoxh\",\"https://imx.to/i/67yov7\",\"https://imx.to/i/67yoyl\",\"https://imx.to/i/67yp02\",\"https://imx.to/i/67yox3\",\"https://imx.to/i/67youw\",\"https://imx.to/i/67yoyh\",\"https://imx.to/i/67yow2\",\"https://imx.to/i/67yozu\",\"https://imx.to/i/67yox0\",\"https://imx.to/i/67xj9p\",\"https://imx.to/i/67yowo\",\"https://imx.to/i/67yoxk\",\"https://imx.to/i/67yovi\",\"https://imx.to/i/67xjad\",\"https://imx.to/i/67yoyo\",\"https://imx.to/i/67yow7\",\"https://imx.to/i/67youx\",\"https://imx.to/i/67xjar\",\"https://imx.to/i/67xja5\",\"https://imx.to/i/67you6\",\"https://imx.to/i/67yoxt\",\"https://imx.to/i/67yoyy\",\"https://imx.to/i/67yp0f\",\"https://imx.to/i/67yoxl\",\"https://imx.to/i/67yow8\",\"https://imx.to/i/67xja3\",\"https://imx.to/i/67yp04\",\"https://imx.to/i/67youv\",\"https://imx.to/i/67yozw\",\"https://imx.to/i/67xjaj\",\"https://imx.to/i/67yoye\",\"https://imx.to/i/67yowy\",\"https://imx.to/i/67youl\",\"https://imx.to/i/67xjac\",\"https://imx.to/i/67yoy4\",\"https://imx.to/i/67yovq\",\"https://imx.to/i/67yozf\",\"https://imx.to/i/67yowq\",\"https://imx.to/i/67youb\",\"https://imx.to/i/67yove\",\"https://imx.to/i/67yoz3\",\"https://imx.to/i/67xja1\",\"https://imx.to/i/67yowi\",\"https://imx.to/i/67yoxm\",\"https://imx.to/i/67yov9\",\"https://imx.to/i/67yoyq\",\"https://imx.to/i/67yp05\",\"https://imx.to/i/67youz\",\"https://imx.to/i/67yozx\",\"https://imx.to/i/67yoyf\",\"https://imx.to/i/67xjaa\",\"https://imx.to/i/67yovx\",\"https://imx.to/i/67yozq\",\"https://imx.to/i/67yovr\",\"https://imx.to/i/67xja6\",\"https://imx.to/i/67yoxn\",\"https://imx.to/i/67yovc\",\"https://imx.to/i/67yow9\",\"https://imx.to/i/67yox8\",\"https://imx.to/i/67yoyj\",\"https://imx.to/i/67yow5\",\"https://imx.to/i/67xjao\",\"https://imx.to/i/67yox1\",\"https://imx.to/i/67youq\",\"https://imx.to/i/67yoyg\",\"https://imx.to/i/67youi\",\"https://imx.to/i/67yovs\",\"https://imx.to/i/67yoxv\",\"https://imx.to/i/67yoz5\",\"https://imx.to/i/67yp0g\",\"https://imx.to/i/67yoxo\",\"https://imx.to/i/67yoys\",\"https://imx.to/i/67yowa\",\"https://imx.to/i/67yp09\",\"https://imx.to/i/67yox7\",\"https://imx.to/i/67youy\",\"https://imx.to/i/67yoyk\",\"https://imx.to/i/67yp00\",\"https://imx.to/i/67yozr\",\"https://imx.to/i/67yowx\",\"https://imx.to/i/67youo\",\"https://imx.to/i/67yoy5\",\"https://imx.to/i/67xja9\",\"https://imx.to/i/67yoxp\",\"https://imx.to/i/67yoyt\",\"https://imx.to/i/67yp08\",\"https://imx.to/i/67yoyn\",\"https://imx.to/i/67xja7\",\"https://imx.to/i/67yozs\",\"https://imx.to/i/67yoy9\",\"https://imx.to/i/67yoze\",\"https://imx.to/i/67youg\",\"https://imx.to/i/67yous\",\"https://imx.to/i/67xjal\",\"https://imx.to/i/67yoy8\",\"https://imx.to/i/67yovu\",\"https://imx.to/i/67yoxx\",\"https://imx.to/i/67yoz7\",\"https://imx.to/i/67xj9s\",\"https://imx.to/i/67yoyv\",\"https://imx.to/i/67yovp\",\"https://imx.to/i/67yoww\",\"https://imx.to/i/67yoy1\",\"https://imx.to/i/67you8\",\"https://imx.to/i/67yoyr\",\"https://imx.to/i/67yp0b\",\"https://imx.to/i/67xjaq\",\"https://imx.to/i/67yovh\",\"https://imx.to/i/67yoyu\",\"https://imx.to/i/67yowc\",\"https://imx.to/i/67yp0c\",\"https://imx.to/i/67yov3\",\"https://imx.to/i/67yox2\",\"https://imx.to/i/67yout\",\"https://imx.to/i/67xjaf\",\"https://imx.to/i/67yoya\",\"https://imx.to/i/67yowk\",\"https://imx.to/i/67you9\",\"https://imx.to/i/67yoxq\",\"https://imx.to/i/67yov2\",\"https://imx.to/i/67youp\",\"https://imx.to/i/67yovz\",\"https://imx.to/i/67yowr\",\"https://imx.to/i/67youf\",\"https://imx.to/i/67yoxw\",\"https://imx.to/i/67yovk\",\"https://imx.to/i/67xjab\",\"https://imx.to/i/67yow0\",\"https://imx.to/i/67yozt\",\"https://imx.to/i/67yoyc\",\"https://imx.to/i/67yozk\",\"https://imx.to/i/67yowl\",\"https://imx.to/i/67yov1\",\"https://imx.to/i/67yoy2\",\"https://imx.to/i/67yovm\",\"https://imx.to/i/67yozd\",\"https://imx.to/i/67yowp\",\"https://imx.to/i/67youe\",\"https://imx.to/i/67xj9t\",\"https://imx.to/i/67xja2\",\"https://imx.to/i/67xjai\",\"https://imx.to/i/67xjah\",\"https://imx.to/i/67xjas\",\"https://imx.to/i/67xja8\",\"https://imx.to/i/67xjae\",\"https://imx.to/i/67xja4\",\"https://imx.to/i/67xjap\",\"https://imx.to/i/67xj9n\",\"https://imx.to/i/67xjat\",\"https://imx.to/i/67xj9z\",\"https://imx.to/i/67xj9r\",\"https://imx.to/i/67xj9w\",\"https://imx.to/i/67xj9x\",\"https://imx.to/i/67xja0\",\"https://imx.to/i/67xj9o\",\"https://imx.to/i/67xj9q\",\"https://imx.to/i/67xj9u\",\"https://imx.to/i/67xjak\",\"https://imx.to/i/67xj9v\",\"https://imx.to/i/67xjam\",\"https://imx.to/i/67xj9y\",\"https://imx.to/i/67xjan\",\"https://imx.to/i/67xjag\",\"https://imx.to/i/67yovd\",\"https://imx.to/i/67yowd\",\"https://imx.to/i/67yp0a\",\"https://imx.to/i/67yox9\",\"https://imx.to/i/67yoy6\",\"https://imx.to/i/67yp01\",\"https://imx.to/i/67yovg\",\"https://imx.to/i/67yowe\",\"https://imx.to/i/67your\",\"https://imx.to/i/67yoyd\",\"https://imx.to/i/67yoy0\",\"https://imx.to/i/67yoza\",\"https://imx.to/i/67you5\",\"https://imx.to/i/67yoxs\",\"https://imx.to/i/67yp0h\",\"https://imx.to/i/67yoxi\",\"https://imx.to/i/67yov5\",\"https://imx.to/i/67yoyp\",\"https://imx.to/i/67yp03\",\"https://imx.to/i/67yox5\",\"https://imx.to/i/67yov0\",\"https://imx.to/i/67yoyi\",\"https://imx.to/i/67yozn\",\"https://imx.to/i/67yowv\",\"https://imx.to/i/67yovo\",\"https://imx.to/i/67yozc\",\"https://imx.to/i/67youa\",\"https://imx.to/i/67yoxu\",\"https://imx.to/i/67yoz4\",\"https://imx.to/i/67yowh\",\"https://imx.to/i/67yoxj\",\"https://imx.to/i/67yov8\",\"https://imx.to/i/67yp06\",\"https://imx.to/i/67youu\",\"https://imx.to/i/67yow3\",\"https://imx.to/i/67yozy\",\"https://imx.to/i/67yozp\",\"https://imx.to/i/67yoy3\",\"https://imx.to/i/67yovw\",\"https://imx.to/i/67yoz6\",\"https://imx.to/i/67yova\",\"https://imx.to/i/67yox6\",\"https://imx.to/i/67yowj\",\"https://imx.to/i/67yp0i\",\"https://imx.to/i/67yowb\",\"https://imx.to/i/67yovl\",\"https://imx.to/i/67yoz8\",\"https://imx.to/i/67yoxa\",\"https://imx.to/i/67youm\"]\n","#!pip install wget\n","%cd /content/\n","for url in urls:\n"," # Extract the image ID from the URL\n"," image_id = url.split('/')[-1]\n"," # Construct the wget command\n"," !wget {url} -O '{image_id}.jpg'\n"," #print(command)\n","\n","\n","\n","\n"],"metadata":{"id":"sysTcSuu5roy"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["\n","\n","\n","# @markdown Use a custom prompt to instruct the image captioning model\n","custom_prompt = '' # @param {type:'string'}\n","enable_custom_prompt = True # @param {type:'boolean'}\n","if not enable_custom_prompt: custom_prompt = 'Describe the image in 400 words'\n","\n","CAPTION_TYPE_MAP = {\n"," (\"descriptive\", \"formal\", False, False): [f\"{custom_prompt}\"],\n"," (\"descriptive\", \"formal\", False, True): [\"Write a descriptive caption for this image in a formal tone within {word_count} words.\"],\n"," (\"descriptive\", \"formal\", True, False): [\"Write a {length} descriptive caption for this image in a formal tone.\"],\n"," (\"descriptive\", \"informal\", False, False): [\"Write a descriptive caption for this image in a casual tone.\"],\n"," (\"descriptive\", \"informal\", False, True): [\"Write a descriptive caption for this image in a casual tone within {word_count} words.\"],\n"," (\"descriptive\", \"informal\", True, False): [\"Write a {length} descriptive caption for this image in a casual tone.\"],\n"," (\"training_prompt\", \"formal\", False, False): [\"Write a stable diffusion prompt for this image.\"],\n"," (\"training_prompt\", \"formal\", False, True): [\"Write a stable diffusion prompt for this image within {word_count} words.\"],\n"," (\"training_prompt\", \"formal\", True, False): [\"Write a {length} stable diffusion prompt for this image.\"],\n"," (\"rng-tags\", \"formal\", False, False): [\"Write a list of Booru tags for this image.\"],\n"," (\"rng-tags\", \"formal\", False, True): [\"Write a list of Booru tags for this image within {word_count} words.\"],\n"," (\"rng-tags\", \"formal\", True, False): [\"Write a {length} list of Booru tags for this image.\"],\n","}"],"metadata":{"id":"_qrUZ7jRIxIf"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":6,"metadata":{"id":"PjO3Wc4kzR08","executionInfo":{"status":"ok","timestamp":1753119103713,"user_tz":-120,"elapsed":1,"user":{"displayName":"","userId":""}}},"outputs":[],"source":["# @markdown higher temperature = prompt creativity (default 0.6) <br> higher top_p = higher noise reduction in latent embedding (default 0.9)\n","temperature = 1.75 # @param {type:'slider',min:0.5,max:4.0,step:0.05}\n","top_p = 0.75 # @param {type:'slider',min:0.1,max:0.95,step:0.05}\n","temperature = float(temperature)\n","top_p = float(top_p)\n","prompt_str = 'invent words you think about when seeing this image'\n","#-----#\n","num=1\n","\n","@torch.no_grad()\n","def stream_chat(input_image: Image.Image, caption_type: str, caption_tone: str, caption_length: str | int) -> str:\n"," torch.cuda.empty_cache()\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","execution_count":null,"metadata":{"id":"mhccTDyzirVn"},"outputs":[],"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\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"," os.remove(filename)\n"," continue\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"," #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(0.8*h))\n"," image.crop(box).save(f'{num}_{index}.jpeg','JPEG')\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}\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"J811UZU6xZEo"},"outputs":[],"source":["\n","import os\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/splits/'\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"," input_image = Image.open(f\"{filename}\").convert('RGB')\n"," caption = stream_chat(input_image, \"descriptive\", \"formal\", \"any\")\n"," print(f\"...\\n\\n...caption for {filename}\\n\\n...\")\n"," print(caption)\n"," #---------#\n"," %cd {tgt_folder}\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"," num = num+1"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"5EztLCjkPq4U"},"outputs":[],"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":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}
|
|
|
|
| 1 |
+
{"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","# @markdown Use a custom prompt to instruct the image captioning model\n","custom_prompt = '' # @param {type:'string'}\n","enable_custom_prompt = False # @param {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.autocast_mode\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"," (\"descriptive\", \"formal\", False, True): [\"Write a descriptive caption for this image in a formal tone within {word_count} words.\"],\n"," (\"descriptive\", \"formal\", True, False): [\"Write a {length} descriptive caption for this image in a formal tone.\"],\n"," (\"descriptive\", \"informal\", False, False): [\"Write a descriptive caption for this image in a casual tone.\"],\n"," (\"descriptive\", \"informal\", False, True): [\"Write a descriptive caption for this image in a casual tone within {word_count} words.\"],\n"," (\"descriptive\", \"informal\", True, False): [\"Write a {length} descriptive caption for this image in a casual tone.\"],\n"," (\"training_prompt\", \"formal\", False, False): [\"Write a stable diffusion prompt for this image.\"],\n"," (\"training_prompt\", \"formal\", False, True): [\"Write a stable diffusion prompt for this image within {word_count} words.\"],\n"," (\"training_prompt\", \"formal\", True, False): [\"Write a {length} stable diffusion prompt for this image.\"],\n"," (\"rng-tags\", \"formal\", False, False): [\"Write a list of Booru tags for this image.\"],\n"," (\"rng-tags\", \"formal\", False, True): [\"Write a list of Booru tags for this image within {word_count} words.\"],\n"," (\"rng-tags\", \"formal\", True, False): [\"Write a {length} list of Booru tags for this image.\"],\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","source":["\n","\n","\n","# @markdown Use a custom prompt to instruct the image captioning model\n","custom_prompt = '' # @param {type:'string'}\n","enable_custom_prompt = True # @param {type:'boolean'}\n","if not enable_custom_prompt: custom_prompt = 'Describe the image in 400 words'\n","\n","CAPTION_TYPE_MAP = {\n"," (\"descriptive\", \"formal\", False, False): [f\"{custom_prompt}\"],\n"," (\"descriptive\", \"formal\", False, True): [\"Write a descriptive caption for this image in a formal tone within {word_count} words.\"],\n"," (\"descriptive\", \"formal\", True, False): [\"Write a {length} descriptive caption for this image in a formal tone.\"],\n"," (\"descriptive\", \"informal\", False, False): [\"Write a descriptive caption for this image in a casual tone.\"],\n"," (\"descriptive\", \"informal\", False, True): [\"Write a descriptive caption for this image in a casual tone within {word_count} words.\"],\n"," (\"descriptive\", \"informal\", True, False): [\"Write a {length} descriptive caption for this image in a casual tone.\"],\n"," (\"training_prompt\", \"formal\", False, False): [\"Write a stable diffusion prompt for this image.\"],\n"," (\"training_prompt\", \"formal\", False, True): [\"Write a stable diffusion prompt for this image within {word_count} words.\"],\n"," (\"training_prompt\", \"formal\", True, False): [\"Write a {length} stable diffusion prompt for this image.\"],\n"," (\"rng-tags\", \"formal\", False, False): [\"Write a list of Booru tags for this image.\"],\n"," (\"rng-tags\", \"formal\", False, True): [\"Write a list of Booru tags for this image within {word_count} words.\"],\n"," (\"rng-tags\", \"formal\", True, False): [\"Write a {length} list of Booru tags for this image.\"],\n","}"],"metadata":{"id":"_qrUZ7jRIxIf"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":2,"metadata":{"id":"PjO3Wc4kzR08","executionInfo":{"status":"ok","timestamp":1753175226290,"user_tz":-120,"elapsed":6,"user":{"displayName":"","userId":""}}},"outputs":[],"source":["# @markdown higher temperature = prompt creativity (default 0.6) <br> higher top_p = higher noise reduction in latent embedding (default 0.9)\n","temperature = 1.75 # @param {type:'slider',min:0.5,max:4.0,step:0.05}\n","top_p = 0.75 # @param {type:'slider',min:0.1,max:0.95,step:0.05}\n","temperature = float(temperature)\n","top_p = float(top_p)\n","prompt_str = 'invent words you think about when seeing this image'\n","#-----#\n","num=1\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":{"colab":{"base_uri":"https://localhost:8080/"},"id":"c60a6jW-YwsN","executionInfo":{"status":"ok","timestamp":1753178920159,"user_tz":-120,"elapsed":213,"user":{"displayName":"","userId":""}},"outputId":"9da43a21-1b0e-49af-bba5-29ebd16c3cc4"},"execution_count":45,"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: 000.jpeg \n"," extracting: 001.jpeg \n"," extracting: 002.jpeg \n"," extracting: 003.jpeg \n"," extracting: 004.jpeg \n"," extracting: 005.jpeg \n"," extracting: 006.jpeg \n"," extracting: 007.jpeg \n"," extracting: 008.jpeg \n"," extracting: 009.jpeg \n"," extracting: 010.jpeg \n"," extracting: 011.jpeg \n"," extracting: 012.jpeg \n"," extracting: 013.jpeg \n"," extracting: 014.jpeg \n"," extracting: 015.jpeg \n"," extracting: 016.jpeg \n"," extracting: 017.jpeg \n"," extracting: 018.jpeg \n"," extracting: 019.jpeg \n"," extracting: 020.jpeg \n"," extracting: 021.jpeg \n"," extracting: 022.jpeg \n"," extracting: 023.jpeg \n"," extracting: 024.jpeg \n"," extracting: 025.jpeg \n"," extracting: 026.jpeg \n"," extracting: 027.jpeg \n"," extracting: 028.jpeg \n"," extracting: 029.jpeg \n"," extracting: 030.jpeg \n"," extracting: 031.jpeg \n"," extracting: 032.jpeg \n"," extracting: 033.jpeg \n"]}]},{"cell_type":"code","execution_count":46,"metadata":{"id":"mhccTDyzirVn","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1753178923854,"user_tz":-120,"elapsed":1036,"user":{"displayName":"","userId":""}},"outputId":"29c5640b-32df-420f-ca1d-88570262ccfb"},"outputs":[{"output_type":"stream","name":"stdout","text":["Splitting all images found under /content/... \n"," into 1 along x-axis\n","/content\n","027.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, breasts, black hair, underboob, squatting, multicolored hair, twintails, purple hair, navel, sneakers, full body, purple eyes, medium breasts, realistic, fingerless gloves, shoes\n","purple eyes,squatting,navel,purple hair,sneakers,underboob,medium breasts,1girl,solo,black hair,fingerless gloves,twintails,shoes,breasts,multicolored hair,full body,realistic\n","/content/split\n","022.jpeg\n","/content\n","/content/split\n","/content\n","swimsuit, 1girl, solo, one-piece swimsuit, water, arms up, armpits, goggles, looking up, short hair, red one-piece swimsuit, competition swimsuit, flat chest\n","1girl,goggles,competition swimsuit,red one-piece swimsuit,one-piece swimsuit,arms up,flat chest,water,short hair,solo,looking up,swimsuit,armpits\n","/content/split\n","012.jpeg\n","/content\n","/content/split\n","/content\n","long hair, red footwear, thighhighs, gloves, skirt, sitting, crop top, black hair, suspenders, black skirt, fingerless gloves, 1girl, tank top, elbow gloves, sports bra, black thighhighs, suspender skirt, shoes, comparison, red eyes, armpits, looking at viewer, breasts, white tank top, jewelry, full body, midriff, elbow pads, black gloves, boots\n","shoes,midriff,boots,black skirt,comparison,full body,gloves,thighhighs,red footwear,1girl,jewelry,black hair,sitting,red eyes,suspender skirt,black thighhighs,elbow pads,looking at viewer,tank top,sports bra,breasts,fingerless gloves,elbow gloves,skirt,black gloves,armpits,crop top,suspenders,long hair,white tank top\n","/content/split\n","009.jpeg\n","/content\n","/content/split\n","/content\n","1girl, long hair, skirt, gloves, thighhighs, crop top, black hair, black skirt, tank top, white tank top, fingerless gloves, suspenders, low-tied long hair, elbow gloves, breasts, suspender skirt, black thighhighs, red footwear, multiple views, midriff, elbow pads, large breasts, arm guards, red eyes, jewelry, zettai ryouiki, earrings\n","suspender skirt,multiple views,thighhighs,elbow gloves,black thighhighs,white tank top,jewelry,long hair,zettai ryouiki,black skirt,midriff,large breasts,suspenders,gloves,tank top,breasts,1girl,red eyes,crop top,arm guards,elbow pads,red footwear,skirt,earrings,low-tied long hair,fingerless gloves,black hair\n","/content/split\n","028.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, see-through, pants, earrings, navel, jewelry, twintails, midriff, green eyes, shoes, full body, sneakers, dark skin, blonde hair, dark-skinned female, underwear, hands in pockets, crop top, long hair, standing, panties, lips, shirt, looking at viewer, breasts\n","earrings,dark-skinned female,lips,see-through,sneakers,shoes,breasts,dark skin,twintails,looking at viewer,full body,shirt,long hair,crop top,jewelry,green eyes,underwear,blonde hair,standing,solo,midriff,panties,1girl,pants,navel,hands in pockets\n","/content/split\n","023.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, blue eyes, long hair, reflection, skirt, signature, black hair, realistic, looking at viewer, lips, sleeveless, red shirt, blonde hair\n","blue eyes,black hair,looking at viewer,sleeveless,blonde hair,lips,signature,long hair,1girl,solo,realistic,reflection,red shirt,skirt\n","/content/split\n","016.jpeg\n","/content\n","/content/split\n","/content\n","1girl, skirt, thighhighs, gloves, long hair, red footwear, crop top, suspenders, fingerless gloves, black hair, black skirt, tank top, elbow gloves, suspender skirt, black thighhighs, comparison, breasts, white tank top, midriff, solo, boots, multiple views, elbow pads, navel, photo background, black gloves, sports bra, low-tied long hair\n","navel,red footwear,tank top,photo background,solo,black thighhighs,midriff,breasts,gloves,black hair,suspender skirt,black gloves,low-tied long hair,black skirt,crop top,elbow pads,sports bra,suspenders,thighhighs,fingerless gloves,boots,multiple views,white tank top,skirt,elbow gloves,long hair,1girl,comparison\n","/content/split\n","031.jpeg\n","/content\n","/content/split\n","/content\n","solo, jewelry, 1girl, wings, white hair, necklace, earrings, pants, standing, shirt, hands in pockets, white footwear, long hair, full body, multicolored hair, feathered wings, short sleeves, angel wings, piercing, shoes, black shirt, ear piercing, black pants, t-shirt, tattoo\n","white footwear,shirt,ear piercing,multicolored hair,feathered wings,1girl,earrings,black shirt,white hair,t-shirt,necklace,long hair,short sleeves,standing,jewelry,full body,pants,solo,angel wings,piercing,tattoo,black pants,shoes,hands in pockets,wings\n","/content/split\n","003.jpeg\n","/content\n","/content/split\n","/content\n","shirt, thighhighs, 1girl, black hair, white shirt, choker, black choker, sleeveless, skirt, collared shirt, ribbon, outdoors, sleeveless shirt, blurry, hair between eyes, black skirt, single hair bun, hair bun, crossed arms, shirt tucked in, shorts, blurry background, green eyes, short hair, night, realistic, black ribbon, black footwear\n","sleeveless,black hair,skirt,shirt tucked in,black ribbon,1girl,ribbon,crossed arms,outdoors,collared shirt,shorts,shirt,hair between eyes,blurry,sleeveless shirt,thighhighs,night,blurry background,short hair,white shirt,realistic,hair bun,black skirt,black choker,choker,black footwear,green eyes,single hair bun\n","/content/split\n","025.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, photo background, pantyhose, ass, fishnets, fishnet pantyhose, looking at viewer, looking back, shorts, freckles, smile, brown hair, blurry background, from behind\n","ass,brown hair,photo background,from behind,solo,pantyhose,looking at viewer,looking back,smile,freckles,fishnets,fishnet pantyhose,1girl,blurry background,shorts\n","/content/split\n","030.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, twintails, skirt, sitting, multicolored clothes, photo background, long hair, swimsuit, outdoors, sky, rooftop\n","rooftop,solo,long hair,photo background,skirt,1girl,outdoors,multicolored clothes,sky,swimsuit,twintails,sitting\n","/content/split\n","024.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, freckles, jewelry, necklace, realistic, tattoo, brown hair, lips, black hair, tank top\n","jewelry,solo,tank top,1girl,necklace,tattoo,lips,black hair,brown hair,freckles,realistic\n","/content/split\n","000.jpeg\n","/content\n","/content/split\n","/content\n","1girl, thighhighs, choker, shirt, shorts, black hair, black choker, shirt tucked in, black shorts, sleeveless, white shirt, collared shirt, high-waist shorts, sleeveless shirt, green eyes, ribbon, multiple views, single hair bun, hair bun, looking at viewer, hair between eyes\n","black shorts,hair bun,shirt,green eyes,black hair,hair between eyes,black choker,collared shirt,white shirt,multiple views,thighhighs,choker,shirt tucked in,single hair bun,shorts,1girl,sleeveless,sleeveless shirt,ribbon,looking at viewer,high-waist shorts\n","/content/split\n","002.jpeg\n","/content\n","/content/split\n","/content\n","skirt, long hair, gloves, black skirt, crop top, black hair, thighhighs, fingerless gloves, navel, suspenders, tank top, midriff, suspender skirt, elbow gloves, hands on hips, 1girl, breasts, swept bangs, elbow pads, comparison, white tank top, low-tied long hair, black thighhighs, blurry\n","thighhighs,low-tied long hair,white tank top,elbow gloves,tank top,suspenders,gloves,skirt,elbow pads,hands on hips,fingerless gloves,black thighhighs,midriff,breasts,crop top,swept bangs,long hair,blurry,1girl,black skirt,suspender skirt,comparison,black hair,navel\n","/content/split\n","004.jpeg\n","/content\n","/content/split\n","/content\n","shirt, black hair, thighhighs, choker, black choker, 1girl, white shirt, looking at viewer, sleeveless, sitting, shorts, black shorts, collared shirt, green eyes, sleeveless shirt, armpits, short hair, black footwear, shirt tucked in, high heels, ribbon\n","high heels,1girl,ribbon,black footwear,green eyes,black choker,shirt,choker,collared shirt,white shirt,armpits,sleeveless shirt,shirt tucked in,black shorts,sitting,short hair,looking at viewer,shorts,thighhighs,black hair,sleeveless\n","/content/split\n","021.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, boots, long hair, photo background, outdoors, brown hair, breasts, tree, black footwear, armlet, nature, day, standing, realistic, bodysuit, full body, parted lips, looking at viewer\n","nature,day,black footwear,long hair,full body,standing,bodysuit,armlet,tree,realistic,brown hair,outdoors,solo,looking at viewer,boots,photo background,parted lips,1girl,breasts\n","/content/split\n","015.jpeg\n","/content\n","/content/split\n","/content\n","1girl, skirt, thighhighs, long hair, gloves, red footwear, crop top, black hair, suspenders, breasts, black skirt, tank top, elbow gloves, multiple views, large breasts, white tank top, comparison, suspender skirt, elbow pads, black thighhighs, full body, fingerless gloves, reference inset, sports bra, midriff, photo background, arms up, black gloves, jewelry, low-tied long hair\n","comparison,full body,large breasts,jewelry,skirt,suspender skirt,black gloves,black skirt,1girl,multiple views,low-tied long hair,thighhighs,sports bra,black hair,suspenders,fingerless gloves,black thighhighs,red footwear,arms up,midriff,white tank top,elbow gloves,gloves,reference inset,tank top,long hair,elbow pads,breasts,photo background,crop top\n","/content/split\n","029.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, dark skin, dark-skinned female, very dark skin, breasts, brown hair, swimsuit, jewelry, earrings, lips, navel, medium breasts, thigh strap\n","jewelry,1girl,navel,dark-skinned female,medium breasts,solo,breasts,brown hair,lips,thigh strap,very dark skin,swimsuit,dark skin,earrings\n","/content/split\n","001.jpeg\n","/content\n","/content/split\n","/content\n","1girl, thighhighs, shirt, choker, shorts, black choker, black shorts, black hair, white shirt, sleeveless, shirt tucked in, sleeveless shirt, high-waist shorts, collared shirt, ribbon, green eyes, hair bun, single hair bun, multiple views, hair between eyes, looking at viewer, blurry background, short hair\n","blurry background,single hair bun,multiple views,green eyes,shorts,black shorts,sleeveless shirt,white shirt,choker,looking at viewer,ribbon,sleeveless,short hair,hair between eyes,hair bun,high-waist shorts,black hair,shirt tucked in,collared shirt,shirt,1girl,black choker,thighhighs\n","/content/split\n","010.jpeg\n","/content\n","/content/split\n","/content\n","nipples, blonde hair, 2girls, multiple girls, breasts, long hair, jewelry, collar, smile, tattoo, bracelet, nude, ponytail, closed eyes, realistic, ass, small breasts\n","nude,small breasts,multiple girls,2girls,ass,realistic,bracelet,long hair,smile,tattoo,collar,jewelry,closed eyes,breasts,blonde hair,ponytail,nipples\n","/content/split\n","007.jpeg\n","/content\n","/content/split\n","/content\n","black hair, gloves, 1girl, jacket, fingerless gloves, boots, necktie, shorts, torn clothes, tail, short hair, cosplay, black gloves, red necktie, red nails, skirt, reference inset, multiple views\n","tail,fingerless gloves,multiple views,reference inset,short hair,black gloves,shorts,skirt,gloves,boots,torn clothes,red nails,1girl,necktie,red necktie,black hair,cosplay,jacket\n","/content/split\n","017.jpeg\n","/content\n","/content/split\n","/content\n","1girl, long hair, skirt, crop top, black hair, thighhighs, gloves, suspenders, comparison, tank top, midriff, black skirt, suspender skirt, fingerless gloves, photo inset, elbow gloves, black thighhighs, low-tied long hair, red eyes, multiple views, breasts, white tank top, solo, reference inset, navel, realistic\n","black hair,fingerless gloves,long hair,suspenders,photo inset,skirt,comparison,reference inset,solo,breasts,1girl,navel,realistic,suspender skirt,elbow gloves,low-tied long hair,multiple views,tank top,crop top,black skirt,white tank top,thighhighs,midriff,red eyes,gloves,black thighhighs\n","/content/split\n","026.jpeg\n","/content\n","/content/split\n","/content\n","1girl, solo, fishnets, swimsuit, black hair, bikini, pantyhose, fishnet pantyhose, brown eyes, breasts, lips\n","bikini,breasts,solo,pantyhose,1girl,fishnets,lips,swimsuit,brown eyes,fishnet pantyhose,black hair\n","/content/split\n","032.jpeg\n","/content\n","/content/split\n","/content\n","blurry, walking, 1girl, gloves, solo focus, blurry background, shoes, backpack, jumpsuit, outdoors, brown hair, pants, multiple others, short hair\n","solo focus,blurry background,pants,multiple others,gloves,jumpsuit,1girl,shoes,short hair,walking,outdoors,blurry,backpack,brown hair\n","/content/split\n","033.jpeg\n","/content\n","/content/split\n","/content\n","1girl, fishnets, multicolored hair, gloves, fingerless gloves, boots, twintails, jewelry, nail polish, pink hair, breasts, solo focus, full body, black footwear, makeup, bangs, standing, long hair, bare shoulders, green hair, indoors, dress, gothic, spiked bracelet, bracelet, pantyhose, blunt bangs, black gloves, spikes, gradient hair\n","full body,dress,black footwear,green hair,long hair,1girl,bracelet,multicolored hair,breasts,gloves,spiked bracelet,blunt bangs,black gloves,standing,twintails,pink hair,bangs,gradient hair,indoors,pantyhose,bare shoulders,fingerless gloves,spikes,jewelry,fishnets,gothic,boots,nail polish,solo focus,makeup\n","/content/split\n","011.jpeg\n","/content\n","/content/split\n","/content\n","1girl, thighhighs, long hair, skirt, crop top, gloves, black hair, suspenders, multiple views, tank top, black skirt, suspender skirt, white tank top, midriff, elbow gloves, black thighhighs, breasts, navel, elbow pads, fingerless gloves, low-tied long hair, sports bra, arm guards, zettai ryouiki, red eyes, jewelry\n","1girl,zettai ryouiki,black thighhighs,white tank top,crop top,sports bra,thighhighs,suspender skirt,midriff,navel,gloves,tank top,red eyes,long hair,elbow gloves,breasts,multiple views,black hair,skirt,elbow pads,low-tied long hair,fingerless gloves,suspenders,black skirt,arm guards,jewelry\n","/content/split\n","014.jpeg\n","/content\n","/content/split\n","/content\n","gag, bdsm, bound, nipples, ball gag, bondage, gagged, breasts, small breasts, navel, shibari, black hair, piercing, shorts, 2girls, jewelry, multiple girls, nipple piercing, bikini, swimsuit, realistic, rope, pink bikini, looking at viewer, long hair, 1girl, brown eyes, necklace\n","bdsm,piercing,bound,gagged,multiple girls,breasts,navel,gag,looking at viewer,rope,long hair,small breasts,pink bikini,shorts,bondage,swimsuit,jewelry,shibari,1girl,brown eyes,necklace,nipples,black hair,realistic,nipple piercing,ball gag,2girls,bikini\n","/content/split\n","005.jpeg\n","/content\n","/content/split\n","/content\n","1girl, skirt, thighhighs, long hair, gloves, crop top, black skirt, red footwear, black hair, suspenders, tank top, fingerless gloves, navel, breasts, suspender skirt, elbow gloves, midriff, white tank top, multiple views, elbow pads, low-tied long hair, black thighhighs, swept bangs, large breasts, zettai ryouiki, comparison, jewelry, armpits, arm guards, arms up\n","black thighhighs,breasts,white tank top,swept bangs,thighhighs,skirt,large breasts,red footwear,1girl,arm guards,suspenders,arms up,multiple views,black skirt,long hair,elbow pads,suspender skirt,black hair,armpits,zettai ryouiki,elbow gloves,comparison,crop top,tank top,low-tied long hair,fingerless gloves,navel,jewelry,gloves,midriff\n","/content/split\n","020.jpeg\n","/content\n","/content/split\n","/content\n","1girl, skirt, long hair, red footwear, thighhighs, gloves, crop top, black hair, black skirt, tank top, squatting, suspenders, fingerless gloves, elbow gloves, white tank top, earrings, multiple views, breasts, jewelry, black thighhighs, low-tied long hair, arm guards, suspender skirt, elbow pads, midriff, black gloves, large breasts\n","arm guards,black hair,large breasts,skirt,crop top,elbow pads,low-tied long hair,elbow gloves,squatting,black thighhighs,suspenders,suspender skirt,gloves,black gloves,white tank top,breasts,fingerless gloves,long hair,1girl,thighhighs,black skirt,earrings,multiple views,tank top,jewelry,midriff,red footwear\n","/content/split\n","019.jpeg\n","/content\n","/content/split\n","/content\n","1girl, skirt, thighhighs, long hair, gloves, crop top, black hair, navel, red footwear, black skirt, tank top, suspenders, fingerless gloves, white tank top, midriff, suspender skirt, elbow gloves, multiple views, black thighhighs, elbow pads, low-tied long hair, stairs, breasts, zettai ryouiki, crossed arms, standing, arm guards\n","elbow pads,navel,thighhighs,breasts,multiple views,arm guards,skirt,long hair,1girl,red footwear,tank top,fingerless gloves,black thighhighs,low-tied long hair,black skirt,zettai ryouiki,stairs,black hair,suspender skirt,standing,elbow gloves,suspenders,crop top,white tank top,crossed arms,gloves,midriff\n","/content/split\n","018.jpeg\n","/content\n","/content/split\n","/content\n","gloves, 1girl, dark skin, black hair, multiple views, harness, piercing, long hair, elbow gloves, black gloves, bondage outfit, navel, dark-skinned female, navel piercing, collar, white background, simple background, breasts, nipple piercing, small breasts, lips, looking at viewer, bdsm\n","simple background,black gloves,harness,navel piercing,looking at viewer,piercing,nipple piercing,breasts,dark-skinned female,bdsm,white background,lips,collar,navel,small breasts,gloves,1girl,black hair,dark skin,long hair,multiple views,elbow gloves,bondage outfit\n","/content/split\n","006.jpeg\n","/content\n","/content/split\n","/content\n","thighhighs, 1girl, black hair, skirt, shirt, choker, sitting, black choker, white shirt, high heels, sleeveless, looking at viewer, black footwear, short hair, sleeveless shirt, green eyes, ribbon, black skirt, cosplay, blurry background, hair between eyes, blurry, collared shirt\n","sleeveless shirt,sleeveless,black choker,green eyes,hair between eyes,high heels,black skirt,1girl,cosplay,short hair,blurry background,thighhighs,sitting,white shirt,black footwear,looking at viewer,skirt,blurry,choker,black hair,collared shirt,ribbon,shirt\n","/content/split\n","008.jpeg\n","/content\n","/content/split\n","/content\n","black hair, shorts, necktie, gloves, torn clothes, boots, red necktie, torn legwear, short hair, 2girls, pantyhose, multiple girls, black gloves, black shorts, animal ears, armpits, bangs, breasts, thighhighs, parted lips, shirt, looking at viewer, fingerless gloves, arms up, sitting, realistic\n","black shorts,looking at viewer,arms up,animal ears,shorts,fingerless gloves,armpits,torn clothes,parted lips,torn legwear,red necktie,necktie,breasts,thighhighs,realistic,shirt,2girls,black gloves,bangs,multiple girls,short hair,gloves,pantyhose,boots,black hair,sitting\n","/content/split\n","013.jpeg\n","/content\n","/content/split\n","/content\n","multiple girls, nipples, 3girls, breasts, ass, thighhighs, piercing, tattoo, long hair, navel piercing, pubic hair, black hair, realistic, underwear, nipple piercing, brown hair, panties, nude, medium breasts, smile, female pubic hair, pussy, looking at viewer, back tattoo\n","back tattoo,3girls,ass,looking at viewer,medium breasts,nipple piercing,brown hair,female pubic hair,black hair,pubic hair,tattoo,nude,breasts,smile,thighhighs,panties,multiple girls,underwear,piercing,pussy,realistic,long hair,navel piercing,nipples\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(0.8*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"," print(tags)\n"," prompt_str = f'Please describe the image in 400 words using danbooru tags : {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":"04d62428-8373-4162-c292-f895a541a1d2"},"outputs":[{"metadata":{"tags":null},"name":"stdout","output_type":"stream","text":["/content\n","15_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : suspender skirt,multiple views,thighhighs,elbow gloves,black thighhighs,white tank top,jewelry,long hair,zettai ryouiki,black skirt,midriff,large breasts,suspenders,gloves,tank top,breasts,1girl,red eyes,crop top,arm guards,elbow pads,red footwear,skirt,earrings,low-tied long hair,fingerless gloves,black hair\n","...\n","\n","...caption for 15_0.jpeg\n","\n","...\n","Photographing Tifa Lockhart from Final Fantasy VII by Cosplay. They are in 2 styles of clothing, both very skimpy and exposing her toned abs, breasts, long hair, red arm guards and black thigh highs that end with white tops, with suspenders.\n","The first pose features her reaching towards the viewer in front of metallic scaffolding. She has pale skin and a slender, curvy body that highlights her chest and abdomen through the top, a small black pleated miniskirt and black gauntlets and gloves for combat moves. She's framed by a mix of rust and metallic colours with a red and black colour palette against black-and-white tones. The other image shows her walking up an old staircase, arms held aloft and slightly sideways, looking over her shoulder and out at, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","14_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : shoes,midriff,boots,black skirt,comparison,full body,gloves,thighhighs,red footwear,1girl,jewelry,black hair,sitting,red eyes,suspender skirt,black thighhighs,elbow pads,looking at viewer,tank top,sports bra,breasts,fingerless gloves,elbow gloves,skirt,black gloves,armpits,crop top,suspenders,long hair,white tank top\n","...\n","\n","...caption for 14_0.jpeg\n","\n","...\n","Tifa Lockhart from Final Fantasy VII, digital illustration in CG, two faces side-by-side reflecting each other in a reflective mirror. In this CGI illustration, you see her from the front against a staircase background on her way up, where a railing is partially seen behind her. Her dark hair is shoulder length and styled straight in one solid piece that partially falls forward, and bangs cover her eyes. She appears relaxed or resting with her left arm resting in front of her on a stair step and her right arm resting against her knee. She sits with legs spread out and wears elbow-length black leather fingerless gloves. Her upper body has visible muscles under her cropped shirt and her midriff and arms are well-muscled. Black suspender-like bands are hooked to her black mini-skirt that is pulled, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","16_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : earrings,dark-skinned female,lips,see-through,sneakers,shoes,breasts,dark skin,twintails,looking at viewer,full body,shirt,long hair,crop top,jewelry,green eyes,underwear,blonde hair,standing,solo,midriff,panties,1girl,pants,navel,hands in pockets\n","...\n","\n","...caption for 16_0.jpeg\n","\n","...\n","Brightly colored, surreal, and slightly psychedelic digital art photograph, featuring two young women standing against a backdrop of vertical boards dyed and arranged in a rainbow array of bright blues, purples, and oranges.\n","\n","The focal character of the image appears to be wearing an outfit comprised of a lime green fishnet cropped top and fishnet loose pants. They pair it with matching fishnet socks in lime green and wear blue high-top sneakers on their feet. Her face appears fresh, unsmiling and her long wavy hair flows with platinum blonde locks cascading down.\n","\n","She sports bright eye-shadow in neon green and is accessorized with ornate turquoise floral-shaped earrings that extend several inches down her ears. Matching flower pins and turquoise bracelets adorn her wrists.\n","\n","Another smaller figure of equal femininity and in an identical garb can be seen partially cropped and off to the right of her side. Their hands are planted inside the, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","37_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : 1girl,zettai ryouiki,black thighhighs,white tank top,crop top,sports bra,thighhighs,suspender skirt,midriff,navel,gloves,tank top,red eyes,long hair,elbow gloves,breasts,multiple views,black hair,skirt,elbow pads,low-tied long hair,fingerless gloves,suspenders,black skirt,arm guards,jewelry\n","...\n","\n","...caption for 37_0.jpeg\n","\n","...\n","Two side by side images of a white female in cosplay posing with one photo showing off to the side. In her late twenties, she is a tall lanky type, with black short and slightly curled hair. The cosplay, designed from \"Final Fantasy VII\", portrays her as a battle ready character with minimal attire for easy maneuvering: gloves, leather straps, suspenders and knee-length shorts. Her top looks to be some mix of crop top and sports bra with a small black square design and shoulder pad attachments. She's positioned as a tough soldier, confident and slightly sultry with her arm in a dramatic curl on the back shot. Rusty steel industrial scenery with an overcast sky and muted grey palette of textures completes the background with various platforms and mechanical parts behind her., and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","41_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : elbow pads,navel,thighhighs,breasts,multiple views,arm guards,skirt,long hair,1girl,red footwear,tank top,fingerless gloves,black thighhighs,low-tied long hair,black skirt,zettai ryouiki,stairs,black hair,suspender skirt,standing,elbow gloves,suspenders,crop top,white tank top,crossed arms,gloves,midriff\n","...\n","\n","...caption for 41_0.jpeg\n","\n","...\n","Cosplay of Aerith from Final Fantasy, on an elevated staircase in a ruined industrial complex, holding red gauntlets, black thigh-high stockings, suspenders, short hair under white and black Aerith hat and collar, wearing crop top, looking over shoulder with an indifferent gaze, photo montage, realistic photo cosplay, holding black shoulder bag under arm, midriff exposed, metal, black arm-guards and elbow gloves, black skirt with silver under layer and buckle, holding a weapon in other hands, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","30_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : blurry background,single hair bun,multiple views,green eyes,shorts,black shorts,sleeveless shirt,white shirt,choker,looking at viewer,ribbon,sleeveless,short hair,hair between eyes,hair bun,high-waist shorts,black hair,shirt tucked in,collared shirt,shirt,1girl,black choker,thighhighs\n","...\n","\n","...caption for 30_0.jpeg\n","\n","...\n","Sword Art Online\n","Side profile of Asuna\n","Another side profile of her (left and right of pic)\n","Black choker\n","Short sleeve, white shirt with a big bowtie, very tight\n","Blade-like choker and short\n","Black and white shorts, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","25_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : thighhighs,low-tied long hair,white tank top,elbow gloves,tank top,suspenders,gloves,skirt,elbow pads,hands on hips,fingerless gloves,black thighhighs,midriff,breasts,crop top,swept bangs,long hair,blurry,1girl,black skirt,suspender skirt,comparison,black hair,navel\n","...\n","\n","...caption for 25_0.jpeg\n","\n","...\n","photographic,abs,cloak off,high_tech_cloth,2d background,1up,armor,cropped midriff,skilled hand,hand_on_waist,breast hold,black shorts,hands up,bloodshot eyes,girl next door face,twilight,blue eyes,metal clothes,standing,armored clothes,armor sleeve,autograph,small breasts,looking aside,half_cloak,skimpy,high tech armor,low_cloak,front,arm sleeves,high-heel,short hair,autographer,short sleeves,medium breasts,short_skirt,black_gloves,cross eyed,large_navel,cracked,hand_on_hip,medium skin tone,puffy eye,large breasts,standing with hands on hips,clothed breast hold,crimson sky, and a logo of a black bar with rainbow glitch art outline that says 'FLUX Chroma V46' psychadelic art\n","/content/tmp\n","20_0.jpeg\n","/content/split\n","Prompt: Please describe the image in 400 words using danbooru tags : sleeveless,black hair,skirt,shirt tucked in,black ribbon,1girl,ribbon,crossed arms,outdoors,collared shirt,shorts,shirt,hair between eyes,blurry,sleeveless shirt,thighhighs,night,blurry background,short hair,white shirt,realistic,hair bun,black skirt,black choker,choker,black footwear,green eyes,single hair bun\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 write the danbooru tags'\n"," if os.path.exists(f'{src_folder}{textpath}'):\n"," with open(f'{textpath}', 'r') as file:\n"," prompt_str = 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}')\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\"{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}')\n"," num = num+1"]},{"cell_type":"code","execution_count":44,"metadata":{"id":"5EztLCjkPq4U","colab":{"base_uri":"https://localhost:8080/","height":54},"executionInfo":{"status":"ok","timestamp":1753178892488,"user_tz":-120,"elapsed":109,"user":{"displayName":"","userId":""}},"outputId":"4c9d9def-26b4-4100-f180-ba0bd614ae02"},"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":44}],"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":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}
|