Datasets:
Tags:
Not-For-All-Audiences
File size: 19,325 Bytes
095dc3e | 1 | {"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"pb9bxY0OE81H"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown β
Huggingface download (fast if you have added HF_TOKEN to Colab Secrets in this instance)\n","# =============================================\n","# Cell 1: Setup - Dependencies, HF Hub Download & Tagger (GPU Optimized)\n","# =============================================\n","\n","# Install dependencies\n","!pip install -q torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118\n","!pip install -q huggingface_hub safetensors pillow\n","\n","import torch\n","from PIL import Image\n","import os\n","import zipfile\n","from pathlib import Path\n","from google.colab import files\n","from huggingface_hub import hf_hub_download\n","\n","# Check GPU availability\n","if torch.cuda.is_available():\n"," print(f\"β
GPU detected: {torch.cuda.get_device_name(0)}\")\n"," device = \"cuda\"\n","else:\n"," print(\"β οΈ No GPU found. Running on CPU (will be slower).\")\n"," device = \"cpu\"\n","\n","print(\"Downloading model files via Hugging Face Hub (faster & resumable)...\")\n","\n","# Download using hf_hub_download (recommended way)\n","hf_hub_download(\n"," repo_id=\"lodestones/tagger-experiment\",\n"," filename=\"tagger_proto.safetensors\",\n"," local_dir=\"/content\",\n"," local_dir_use_symlinks=False\n",")\n","\n","hf_hub_download(\n"," repo_id=\"lodestones/tagger-experiment\",\n"," filename=\"tagger_vocab_with_categories.json\",\n"," local_dir=\"/content\",\n"," local_dir_use_symlinks=False\n",")\n","\n","hf_hub_download(\n"," repo_id=\"lodestones/tagger-experiment\",\n"," filename=\"inference_tagger_standalone.py\",\n"," local_dir=\"/content\",\n"," local_dir_use_symlinks=False\n",")\n","\n","print(\"β
Model files downloaded successfully via Hugging Face Hub.\")\n","\n","# Load the Tagger\n","from inference_tagger_standalone import Tagger\n","\n","tagger = Tagger(\n"," checkpoint_path=\"/content/tagger_proto.safetensors\",\n"," vocab_path=\"/content/tagger_vocab_with_categories.json\",\n"," device=device,\n"," dtype=torch.bfloat16 if device == \"cuda\" else torch.float32,\n"," max_size=1024\n",")\n","\n","print(f\"β
Tagger loaded successfully on {tagger.device}\")"],"metadata":{"id":"880QrkhOZLM3","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================\n","# Cell 2: Process Images from Upload or ZIP + Custom Output\n","# =============================================\n","\n","# @title βοΈ Run the tagger (Manual upload)\n","\n","# === Input Mode ===\n","use_manual_upload = True #param {type:\"boolean\"}\n","zip_file_path = \"\" # param {type:\"string\"}\n","\n","# === Tagging Settings ===\n","threshold_percent = 75 # param {type:\"slider\", min:1, max:95, step:1}\n","max_tags = 500 # param {type:\"slider\", min:5, max:150, step:5}\n","use_max_tags = False # param {type:\"boolean\"}\n","add_commas = True # param {type:\"boolean\"}\n","\n","# === Output Settings ===\n","output_zip_path = \"/content/dino_tagger_output.zip\" # @param {type:\"string\"}\n","auto_download = True #param {type:\"boolean\"}\n","\n","print(f\"Input β Manual Upload: {use_manual_upload} | ZIP: '{zip_file_path}'\")\n","print(f\"Output β Save to: '{output_zip_path}' | Auto-download: {auto_download}\")\n","print(f\"Tagging β Threshold: {threshold_percent}% | Max tags: {max_tags} | Force max: {use_max_tags} | Commas: {add_commas}\\n\")\n","\n","# ------------------- Prepare images -------------------\n","output_dir = Path(\"/content/output\")\n","output_dir.mkdir(exist_ok=True)\n","\n","image_files = []\n","\n","if use_manual_upload:\n"," print(\"Please upload your images (multiple files supported)...\")\n"," uploaded = files.upload()\n"," image_files = [f for f in uploaded.keys()\n"," if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp'))]\n"," print(f\"β
Uploaded {len(image_files)} image(s) manually.\")\n","\n","else:\n"," if not zip_file_path or not Path(zip_file_path).exists():\n"," print(f\"β ZIP file not found at: {zip_file_path}\")\n"," else:\n"," print(f\"Extracting images from ZIP: {zip_file_path}\")\n"," extract_dir = Path(\"/content/extracted_images\")\n"," extract_dir.mkdir(exist_ok=True)\n","\n"," with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n"," for ext in ['.png', '.jpg', '.jpeg', '.webp', '.bmp']:\n"," image_files.extend(list(extract_dir.rglob(f\"*{ext}\")))\n"," image_files.extend(list(extract_dir.rglob(f\"*{ext.upper()}\")))\n","\n"," image_files = sorted(set(str(p) for p in image_files))\n"," print(f\"β
Found {len(image_files)} image(s) in the ZIP file.\")\n","\n","# ------------------- Process images -------------------\n","if not image_files:\n"," print(\"β No images found to process.\")\n","else:\n"," print(f\"\\nStarting tagging for {len(image_files)} image(s) on {tagger.device}...\\n\")\n","\n"," threshold = threshold_percent / 100.0\n","\n"," for i, img_path in enumerate(image_files, start=1):\n"," img_name = Path(img_path).name\n"," print(f\"[{i}/{len(image_files)}] Processing: {img_name}\")\n","\n"," # Use GPU-accelerated prediction\n"," if use_max_tags:\n"," tags_list = tagger.predict(img_path, topk=max_tags, threshold=None)\n"," else:\n"," tags_list = tagger.predict(img_path, topk=None, threshold=threshold)\n"," if len(tags_list) > max_tags:\n"," tags_list = tags_list[:max_tags]\n","\n"," # Save image as numbered JPG\n"," img = Image.open(img_path).convert(\"RGB\")\n"," new_img_path = output_dir / f\"{i}.jpg\"\n"," img.save(new_img_path, \"JPEG\", quality=95)\n","\n"," # Prepare single-line tag string\n"," tags_only = [tag for tag, prob in tags_list]\n"," tag_text = \" , \".join(tags_only) if add_commas else \" \".join(tags_only)\n","\n"," # Save tags\n"," tag_file = output_dir / f\"{i}.txt\"\n"," with open(tag_file, \"w\", encoding=\"utf-8\") as f:\n"," f.write(tag_text)\n","\n"," print(f\" β Saved {i}.jpg + {i}.txt ({len(tags_list)} tags)\")\n","\n"," # Create output zip at custom path\n"," final_zip_path = Path(output_zip_path)\n"," final_zip_path.parent.mkdir(parents=True, exist_ok=True)\n","\n"," with zipfile.ZipFile(final_zip_path, \"w\") as zipf:\n"," for file in sorted(output_dir.iterdir()):\n"," zipf.write(file, file.name)\n","\n"," print(f\"\\nβ
Processing complete! Output ZIP saved to: {final_zip_path}\")\n","\n"," # Auto-download if enabled\n"," if auto_download:\n"," files.download(str(final_zip_path))\n"," print(\"π₯ Auto-download triggered.\")\n"," else:\n"," print(\"β
Auto-download disabled. You can manually download the file from the path above.\")"],"metadata":{"id":"aR-oik8TTpNU","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","metadata":{"cellView":"form","id":"d4c348b4"},"source":["# =============================================\n","# Cell 2: Process Images from Upload or ZIP + Custom Output\n","# =============================================\n","\n","# @title π¦ βοΈ Run the tagger using .zip file in Drive + custom options\n","\n","# === Input Mode ===\n","use_manual_upload = False #param {type:\"boolean\"}\n","zip_file_path = \"/content/drive/MyDrive/fetch.zip\" # @param {type:\"string\"}\n","\n","# === Tagging Settings ===\n","threshold_percent = 75 # @param {type:\"slider\", min:1, max:95, step:1}\n","max_tags = 300 # @param {type:\"slider\", min:5, max:500, step:5}\n","use_max_tags = False # @param {type:\"boolean\"}\n","add_commas = True # @param {type:\"boolean\"}\n","\n","# === Output Settings ===\n","output_zip_path = \"/content/drive/MyDrive/dino_tagger_output.zip\" # @param {type:\"string\"}\n","auto_download = False #param {type:\"boolean\"}\n","\n","print(f\"Input β Manual Upload: {use_manual_upload} | ZIP: '{zip_file_path}'\")\n","print(f\"Output β Save to: '{output_zip_path}' | Auto-download: {auto_download}\")\n","print(f\"Tagging β Threshold: {threshold_percent}% | Max tags: {max_tags} | Force max: {use_max_tags} | Commas: {add_commas}\\n\")\n","\n","# ------------------- Prepare images -------------------\n","output_dir = Path(\"/content/output\")\n","output_dir.mkdir(exist_ok=True)\n","\n","image_files = []\n","\n","if use_manual_upload:\n"," print(\"Please upload your images (multiple files supported)...\")\n"," uploaded = files.upload()\n"," image_files = [f for f in uploaded.keys()\n"," if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp'))]\n"," print(f\"β
Uploaded {len(image_files)} image(s) manually.\")\n","\n","else:\n"," if not zip_file_path or not Path(zip_file_path).exists():\n"," print(f\"β ZIP file not found at: {zip_file_path}\")\n"," else:\n"," print(f\"Extracting images from ZIP: {zip_file_path}\")\n"," extract_dir = Path(\"/content/extracted_images\")\n"," extract_dir.mkdir(exist_ok=True)\n","\n"," with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n"," temp_image_files = []\n"," for ext in ['.png', '.jpg', '.jpeg', '.webp', '.bmp']:\n"," temp_image_files.extend(list(extract_dir.rglob(f\"*{ext}\")))\n"," temp_image_files.extend(list(extract_dir.rglob(f\"*{ext.upper()}\")))\n","\n"," # Filter out files from __MACOSX directories that cause issues\n"," image_files = sorted(set(str(p) for p in temp_image_files if \"__MACOSX\" not in str(p)))\n"," print(f\"β
Found {len(image_files)} image(s) in the ZIP file (excluding macOS metadata files).\")\n","\n","# ------------------- Process images -------------------\n","if not image_files:\n"," print(\"β No images found to process.\")\n","else:\n"," print(f\"\\nStarting tagging for {len(image_files)} image(s) on {tagger.device}...\\n\")\n","\n"," threshold = threshold_percent / 100.0\n","\n"," for i, img_path in enumerate(image_files, start=1):\n"," img_name = Path(img_path).name\n"," print(f\"[{i}/{len(image_files)}] Processing: {img_name}\")\n","\n"," # Use GPU-accelerated prediction\n"," if use_max_tags:\n"," tags_list = tagger.predict(img_path, topk=max_tags, threshold=None)\n"," else:\n"," tags_list = tagger.predict(img_path, topk=None, threshold=threshold)\n"," if len(tags_list) > max_tags:\n"," tags_list = tags_list[:max_tags]\n","\n"," # Save image as numbered JPG\n"," img = Image.open(img_path).convert(\"RGB\")\n"," new_img_path = output_dir / f\"{i}.jpg\"\n"," img.save(new_img_path, \"JPEG\", quality=95)\n","\n"," # Prepare single-line tag string\n"," tags_only = [tag for tag, prob in tags_list]\n"," tag_text = \" , \".join(tags_only) if add_commas else \" \".join(tags_only)\n","\n"," # Save tags\n"," tag_file = output_dir / f\"{i}.txt\"\n"," with open(tag_file, \"w\", encoding=\"utf-8\") as f:\n"," f.write(tag_text)\n","\n"," print(f\" β Saved {i}.jpg + {i}.txt ({len(tags_list)} tags)\")\n","\n"," # Create output zip at custom path\n"," final_zip_path = Path(output_zip_path)\n"," final_zip_path.parent.mkdir(parents=True, exist_ok=True)\n","\n"," with zipfile.ZipFile(final_zip_path, \"w\") as zipf:\n"," for file in sorted(output_dir.iterdir()):\n"," zipf.write(file, file.name)\n","\n"," print(f\"\\nβ
Processing complete! Output ZIP saved to: {final_zip_path}\")\n","\n"," # Auto-download if enabled\n"," if auto_download:\n"," files.download(str(final_zip_path))\n"," print(\"π₯ Auto-download triggered.\")\n"," else:\n"," print(\"β
Auto-download disabled. You can manually download the file from the path above.\")"],"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================\n","# Cell 3: Disconnect Runtime After Processing (Optional)\n","# =============================================\n","\n","# @title Disconnect from Session After Completion\n","\n","disconnect_after_run = True # @param {type:\"boolean\"}\n","\n","if disconnect_after_run:\n"," print(\"π Disconnecting Colab runtime in 10 seconds...\")\n"," print(\"This will stop the current session and free up GPU resources.\")\n","\n"," import time\n"," time.sleep(10)\n","\n"," from google.colab import runtime\n"," runtime.unassign()\n","\n"," print(\"β
Runtime disconnected.\")\n","else:\n"," print(\"β
Disconnect option is disabled.\")\n"," print(\"You can manually disconnect via Runtime β Disconnect and delete runtime if needed.\")"],"metadata":{"id":"byGffTyyPgEY","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Image Tagger using lodestones/tagger-experiment\n","\n","This Colab notebook lets you automatically generate **tags** for a batch of images using the [lodestones/tagger-experiment](https://huggingface.co/lodestones/tagger-experiment) model.\n","\n","### Features:\n","- Process images either by **manual upload** or by providing a **ZIP file** containing your images\n","- Adjustable **probability threshold** (only tags above this % are kept when not forcing max tags)\n","- Control the **maximum number of tags** per image\n","- Option to **force the top N tags** (ignores threshold) or strictly respect the probability threshold\n","- Output format: Images saved as `1.jpg`, `2.jpg`, ... and corresponding tags as `1.txt`, `2.txt`, ...\n","- Tags in each `.txt` file are saved as a **single line** β either space-separated or comma-separated\n","- Final result is packaged into a downloadable `output.zip` file\n","\n","### How to use:\n","1. Run **Cell 1** first (installs dependencies and loads the model)\n","2. In **Cell 2**, configure your settings:\n"," - Choose between manual upload or ZIP file input\n"," - Adjust threshold, max tags, and output style using the sliders and checkboxes\n","3. Run **Cell 2** β upload images or point to your ZIP file\n","4. Wait for processing and download the resulting `output.zip`\n","\n","The notebook preserves the original image quality (saved as high-quality JPG) and organizes everything with simple numbered filenames for easy use in training pipelines."],"metadata":{"id":"q-fVFdZqMxRA"}},{"cell_type":"code","source":["#@markdown Download method using wget (backup method)\n","# =============================================\n","# Cell 1: Setup - Dependencies, Model & Tagger (GPU Optimized)\n","# =============================================\n","\n","# Install dependencies\n","!pip install -q torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118\n","!pip install -q safetensors pillow\n","\n","import torch\n","from PIL import Image\n","import os\n","import zipfile\n","from pathlib import Path\n","from google.colab import files\n","\n","# Check GPU availability\n","if torch.cuda.is_available():\n"," print(f\"β
GPU detected: {torch.cuda.get_device_name(0)}\")\n"," device = \"cuda\"\n","else:\n"," print(\"β οΈ No GPU found. Running on CPU (will be slower).\")\n"," device = \"cpu\"\n","\n","print(\"Downloading model files...\")\n","\n","!wget -q https://huggingface.co/lodestones/tagger-experiment/resolve/main/tagger_proto.safetensors -O tagger_proto.safetensors\n","!wget -q https://huggingface.co/lodestones/tagger-experiment/resolve/main/tagger_vocab_with_categories.json -O tagger_vocab_with_categories.json\n","!wget -q https://huggingface.co/lodestones/tagger-experiment/resolve/main/inference_tagger_standalone.py -O inference_tagger_standalone.py\n","\n","print(\"β
Model files downloaded.\")\n","\n","# Load the Tagger with GPU preference\n","from inference_tagger_standalone import Tagger\n","\n","tagger = Tagger(\n"," checkpoint_path=\"tagger_proto.safetensors\",\n"," vocab_path=\"tagger_vocab_with_categories.json\",\n"," device=device, # Explicit GPU if available\n"," dtype=torch.bfloat16 if device == \"cuda\" else torch.float32,\n"," max_size=1024\n",")\n","\n","print(f\"β
Tagger loaded successfully on {tagger.device}\")"],"metadata":{"id":"qEQZt_7nPffG","cellView":"form"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774964848181},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774906863352},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774901938471},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774884683620},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774883563998},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774882033159},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774881268156},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1774879795776},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0} |