codeShare commited on
Commit
7da3978
Β·
verified Β·
1 Parent(s): eb7b486

Upload dino_tagger.ipynb

Browse files
Files changed (1) hide show
  1. dino_tagger.ipynb +1 -1
dino_tagger.ipynb CHANGED
@@ -1 +1 @@
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":["# =============================================\n","# Cell 1: Setup - Dependencies, Model Download & Load Tagger\n","# =============================================\n","\n","# Install required packages\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","print(\"Downloading model files from Hugging Face...\")\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","# Import and initialize the Tagger\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=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n"," dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,\n"," max_size=1024\n",")\n","\n","print(f\"βœ… Tagger successfully loaded on {tagger.device}\")"],"metadata":{"id":"rWxLOedwHio3","outputId":"3b4fde9b-2e32-438d-a71c-10d123580bcc","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Downloading model files from Hugging Face...\n"]}]},{"cell_type":"code","source":["# =============================================\n","# Cell 2: Upload Images β†’ Tag β†’ Generate output.zip\n","# =============================================\n","\n","# Upload images (you can select multiple files at once)\n","print(\"Please upload your images (PNG, JPG, JPEG, WEBP, BMP supported)...\")\n","uploaded = files.upload()\n","\n","# Filter only image files\n","image_paths = [f for f in uploaded.keys() if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp'))]\n","\n","if not image_paths:\n"," print(\"❌ No valid image files were uploaded.\")\n","else:\n"," print(f\"βœ… Uploaded {len(image_paths)} image(s). Starting processing...\")\n","\n"," # Prepare output folder\n"," output_dir = Path(\"/content/output\")\n"," output_dir.mkdir(exist_ok=True)\n","\n"," # Process each image\n"," for i, img_name in enumerate(image_paths, start=1):\n"," print(f\"[{i}/{len(image_paths)}] Processing: {img_name}\")\n","\n"," # Get tags (top 50 by confidence)\n"," tags = tagger.predict(img_name, topk=50)\n","\n"," # Save image as numbered JPG\n"," img = Image.open(img_name).convert(\"RGB\")\n"," new_img_path = output_dir / f\"{i}.jpg\"\n"," img.save(new_img_path, \"JPEG\", quality=95)\n","\n"," # Save tags as .txt (one tag per line, highest confidence first)\n"," tag_file = output_dir / f\"{i}.txt\"\n"," with open(tag_file, \"w\", encoding=\"utf-8\") as f:\n"," for tag, prob in tags:\n"," f.write(f\"{tag}\\n\") # Change to f\"{tag} {prob:.4f}\\n\" if you want scores\n","\n"," print(f\" β†’ Saved {i}.jpg + {i}.txt ({len(tags)} tags)\")\n","\n"," # Create zip file\n"," zip_path = \"/content/output.zip\"\n"," with zipfile.ZipFile(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! Zip file created: {zip_path}\")\n"," files.download(zip_path)"],"metadata":{"id":"-faezdNzHoN6"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dino_tagger.ipynb","timestamp":1774880489123},{"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}
 
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":["# =============================================\n","# Cell 1: Setup - Dependencies, Model & Tagger\n","# =============================================\n","\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","from google.colab import widgets # for form support\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\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=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n"," dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,\n"," max_size=1024\n",")\n","\n","print(f\"βœ… Tagger loaded successfully on {tagger.device}\")"],"metadata":{"id":"hoi7qhsSJPE0"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================\n","# Cell 2: Upload Images β†’ Tag β†’ Download ZIP\n","# =============================================\n","\n","# @title Tagger Settings\n","threshold_percent = 85 # @param {type:\"slider\", min:1, max:95, step:1}\n","max_tags = 75 # @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","print(f\"Settings β†’ Threshold: {threshold_percent}% | Max tags: {max_tags} | Force max tags: {use_max_tags} | Commas: {add_commas}\\n\")\n","\n","# Upload images\n","print(\"Please upload your images (multiple files supported)...\")\n","uploaded = files.upload()\n","\n","image_paths = [f for f in uploaded.keys() if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.bmp'))]\n","\n","if not image_paths:\n"," print(\"❌ No valid images uploaded.\")\n","else:\n"," print(f\"βœ… {len(image_paths)} image(s) uploaded. Processing...\\n\")\n","\n"," output_dir = Path(\"/content/output\")\n"," output_dir.mkdir(exist_ok=True)\n","\n"," threshold = threshold_percent / 100.0\n","\n"," for i, img_name in enumerate(image_paths, start=1):\n"," print(f\"[{i}/{len(image_paths)}] Processing: {img_name}\")\n","\n"," # Decide prediction mode\n"," if use_max_tags:\n"," tags_list = tagger.predict(img_name, topk=max_tags, threshold=None)\n"," else:\n"," tags_list = tagger.predict(img_name, topk=None, threshold=threshold)\n"," # Limit to max_tags even when using 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_name).convert(\"RGB\")\n"," new_img_path = output_dir / f\"{i}.jpg\"\n"," img.save(new_img_path, \"JPEG\", quality=95)\n","\n"," # Prepare tag string\n"," tags_only = [tag for tag, prob in tags_list]\n","\n"," if add_commas:\n"," tag_text = \" , \".join(tags_only)\n"," else:\n"," tag_text = \" \".join(tags_only)\n","\n"," # Save as single-line text file\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 zip\n"," zip_path = \"/content/output.zip\"\n"," with zipfile.ZipFile(zip_path, \"w\") as zipf:\n"," for file in sorted(output_dir.iterdir()):\n"," zipf.write(file, file.name)\n","\n"," print(f\"\\nβœ… All done! Output saved to {zip_path}\")\n"," files.download(zip_path)"],"metadata":{"id":"-IefzYMXJRVw"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"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}