Datasets:
Tags:
Not-For-All-Audiences
Upload civit_caption_prepper.ipynb
Browse files
civit_caption_prepper.ipynb
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"hDzdSOe90dAa"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Google Colab - Text cleaner with multiple replacements & removal\n","# Last updated: removes standalone \"young\" as requested\n","\n","import os\n","import re\n","import zipfile\n","from pathlib import Path\n","from google.colab import files\n","\n","def clean_text(text):\n"," # Step 1: specific replacements (case-insensitive)\n"," text = re.sub(r'\\byoung girl\\b', 'young woman', text, flags=re.IGNORECASE)\n"," text = re.sub(r'\\bswastika\\b', 'manji', text, flags=re.IGNORECASE)\n","\n"," # Step 2: remove standalone \"young\" (case-insensitive)\n"," # \\b = word boundary β won't touch \"younger\", \"youngest\", \"youngling\" etc.\n"," text = re.sub(r'\\byoung\\b', '', text, flags=re.IGNORECASE)\n","\n"," # Step 3: remove all asterisks\n"," text = text.replace('*', '')\n","\n"," # Step 4: normalize all newlines / multiple whitespace β single space\n"," text = re.sub(r'\\s+', ' ', text) # all whitespace sequences β one space\n"," text = text.replace('\\r\\n', ' ').replace('\\n', ' ').replace('\\r', ' ')\n"," text = text.strip() # remove leading/trailing spaces\n","\n"," return text\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"Upload your .txt files (you can select multiple files)\\n\")\n","\n","uploaded = files.upload()\n","\n","output_dir = Path(\"/content/cleaned_files\")\n","output_dir.mkdir(exist_ok=True)\n","\n","processed = 0\n","\n","for filename, content_bytes in uploaded.items():\n"," if not filename.lower().endswith('.txt'):\n"," print(f\"Skipped: {filename} (not .txt)\")\n"," continue\n","\n"," try:\n"," # Try UTF-8 first, fallback to latin-1\n"," try:\n"," text = content_bytes.decode('utf-8')\n"," except UnicodeDecodeError:\n"," text = content_bytes.decode('latin-1', errors='replace')\n","\n"," original_len = len(text)\n"," cleaned = clean_text(text)\n"," cleaned_len = len(cleaned)\n","\n"," out_path = output_dir / filename\n"," with open(out_path, 'w', encoding='utf-8') as f:\n"," f.write(cleaned)\n","\n"," processed += 1\n"," print(f\"β {filename} ({original_len:,} β {cleaned_len:,} chars)\")\n","\n"," except Exception as e:\n"," print(f\"β Failed: {filename} β {str(e)}\")\n","\n","print(f\"\\nProcessed {processed} file(s)\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","if processed > 0:\n"," zip_path = \"/content/cleaned_texts.zip\"\n"," print(\"Creating zip...\")\n","\n"," with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for txt in output_dir.glob(\"*.txt\"):\n"," zf.write(txt, arcname=txt.name)\n"," print(f\" added: {txt.name}\")\n","\n"," print(\"\\nDone. Downloading automatically...\\n\")\n"," files.download(zip_path)\n","\n","else:\n"," print(\"No text files were processed.\")"],"metadata":{"id":"rzsBLe27-Poh"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Zip Cleaner - Remove files containing 'loli' in .txt { run: \"auto\" }\n","from google.colab import drive\n","import os\n","import zipfile\n","from pathlib import Path\n","import shutil\n","from tqdm.auto import tqdm\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","#@markdown ### 1. Mount Google Drive (needed to save result)\n","drive.mount('/content/drive', force_remount=False)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","#@markdown ### 2. Settings\n","zip_path = \"/content/drive/MyDrive/TA-2026-03-09-19-10-24-947477596164084244.zip\" #@param {type:\"string\"}\n","output_zip_name = \"cleaned_dataset.zip\" #@param {type:\"string\"}\n","\n","#@markdown Where to save the final cleaned zip\n","output_folder_on_drive = \"/content/drive/MyDrive/Cleaned_Zips\" #@param {type:\"string\"}\n","\n","#@markdown Case sensitive search? (usually you want False)\n","case_sensitive = False #@param {type:\"boolean\"}\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","if not zip_path:\n"," print(\"β Please provide a zip path\")\n"," raise SystemExit\n","\n","if not os.path.isfile(zip_path):\n"," print(f\"β File not found: {zip_path}\")\n"," print(\"Common correct paths look like:\")\n"," print(\" /content/myfile.zip\")\n"," print(\" /content/drive/MyDrive/datasets/something.zip\")\n"," raise SystemExit\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(f\"π¦ Processing: {zip_path}\")\n","\n","extract_dir = \"/content/extracted_temp\"\n","cleaned_dir = \"/content/cleaned_dataset\"\n","\n","# Remove previous folders if exist\n","shutil.rmtree(extract_dir, ignore_errors=True)\n","shutil.rmtree(cleaned_dir, ignore_errors=True)\n","\n","os.makedirs(extract_dir, exist_ok=True)\n","os.makedirs(cleaned_dir, exist_ok=True)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"π Extracting zip...\")\n","with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"π Scanning files...\")\n","\n","removed_count = 0\n","kept_count = 0\n","\n","all_files = list(Path(extract_dir).rglob(\"*\"))\n","\n","# Group by stem\n","from collections import defaultdict\n","groups = defaultdict(list)\n","\n","for f in all_files:\n"," if f.is_file():\n"," groups[f.stem].append(f)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"π§Ή Cleaning...\")\n","\n","for stem, files in tqdm(groups.items(), desc=\"Processing groups\"):\n"," txt_files = [f for f in files if f.suffix.lower() == '.txt']\n"," img_files = [f for f in files if f.suffix.lower() in {'.jpg','.jpeg','.png','.webp','.gif','.bmp'}]\n","\n"," should_remove = False\n","\n"," if txt_files:\n"," # read the first .txt we find (usually there's only one)\n"," txt_path = txt_files[0]\n"," try:\n"," content = txt_path.read_text(encoding='utf-8', errors='ignore')\n"," if case_sensitive:\n"," if 'loli' in content:\n"," should_remove = True\n"," else:\n"," if 'loli' in content.lower():\n"," should_remove = True\n"," except:\n"," # if we can't read the txt β better keep (safety)\n"," pass\n","\n"," if should_remove:\n"," removed_count += 1\n"," # remove all related files\n"," for f in files:\n"," try:\n"," f.unlink()\n"," except:\n"," pass\n"," else:\n"," # copy kept files to cleaned folder (preserving subfolders)\n"," for f in files:\n"," rel_path = f.relative_to(extract_dir)\n"," target_path = Path(cleaned_dir) / rel_path\n"," target_path.parent.mkdir(parents=True, exist_ok=True)\n"," shutil.copy2(f, target_path)\n"," kept_count += 1\n","\n","print(f\"\\nβ
Done.\")\n","print(f\" Removed groups : {removed_count}\")\n","print(f\" Kept files : {kept_count}\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"\\nπ¦ Creating cleaned zip...\")\n","\n","final_zip_path = f\"/content/{output_zip_name}\"\n","\n","with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for file in tqdm(Path(cleaned_dir).rglob(\"*\"), desc=\"Zipping\"):\n"," if file.is_file():\n"," arcname = file.relative_to(cleaned_dir)\n"," zf.write(file, arcname)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"\\nπΎ Copying to Google Drive...\")\n","os.makedirs(output_folder_on_drive, exist_ok=True)\n","drive_final_path = f\"{output_folder_on_drive.rstrip('/')}/{output_zip_name}\"\n","\n","shutil.copy2(final_zip_path, drive_final_path)\n","print(f\"β Saved to: {drive_final_path}\")\n","\n","# Optional: show size\n","size_mb = os.path.getsize(drive_final_path) / 1024 / 1024\n","print(f\" File size: {size_mb:.1f} MB\")\n","\n","print(\"\\nπ§Ή Cleaning up temporary files...\")\n","shutil.rmtree(extract_dir, ignore_errors=True)\n","shutil.rmtree(cleaned_dir, ignore_errors=True)\n","\n","print(\"\\nFinished! β\")"],"metadata":{"id":"uuD6JuZMTftq"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773080355474},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772998638620},{"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}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|
|
|
|
| 1 |
+
{"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"hDzdSOe90dAa"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title WD Tagger + Loli Filter + Caption Cleaner + Tag Spreading β Drive { run: \"auto\" }\n","from google.colab import drive\n","import os\n","import zipfile\n","from pathlib import Path\n","import shutil\n","from tqdm.auto import tqdm\n","import re\n","!pip install timm pillow pandas requests nltk -q\n","\n","import timm\n","import torch\n","from PIL import Image\n","import torchvision.transforms as transforms\n","import pandas as pd\n","import requests\n","from io import StringIO\n","import nltk\n","from collections import defaultdict\n","\n","# Fix for recent NLTK versions\n","nltk.download('punkt', quiet=True)\n","nltk.download('punkt_tab', quiet=True)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","#@markdown ### Settings\n","drive.mount('/content/drive', force_remount=False)\n","\n","zip_path = \"/content/drive/MyDrive/vertical_slices_output/vertical_slices.zip\" #@param {type:\"string\"}\n","output_zip_name = \"cleaned_tagged_dataset.zip\" #@param {type:\"string\"}\n","output_folder_on_drive = \"/content/drive/MyDrive/Cleaned_Datasets\" #@param {type:\"string\"}\n","\n","case_sensitive_loli_check = False #@param {type:\"boolean\"}\n","tag_probability_threshold = 0.35 #@param {type:\"slider\", min:0.1, max:0.6, step:0.05}\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","if not zip_path or not os.path.isfile(zip_path):\n"," print(\"β Please provide a valid zip file path\")\n"," raise SystemExit\n","\n","print(f\"π¦ Input zip: {zip_path}\")\n","print(f\"π€ Will save: {output_folder_on_drive}/{output_zip_name}\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","extract_dir = Path(\"/content/extracted\")\n","cleaned_dir = Path(\"/content/cleaned_dataset\")\n","\n","shutil.rmtree(extract_dir, ignore_errors=True)\n","shutil.rmtree(cleaned_dir, ignore_errors=True)\n","extract_dir.mkdir(exist_ok=True, parents=True)\n","cleaned_dir.mkdir(exist_ok=True, parents=True)\n","\n","print(\"π Extracting archive...\")\n","with zipfile.ZipFile(zip_path, 'r') as zf:\n"," zf.extractall(extract_dir)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Load WD tagger\n","print(\"π§ Loading WD tagger model...\")\n","tags_url = \"https://huggingface.co/SmilingWolf/wd-vit-tagger-v3/resolve/main/selected_tags.csv\"\n","tags_df = pd.read_csv(StringIO(requests.get(tags_url).text))\n","tags = tags_df['name'].tolist()\n","\n","model = timm.create_model(\"hf_hub:SmilingWolf/wd-vit-tagger-v3\", pretrained=True)\n","\n","# Define device properly (this fixes the .device attribute error)\n","device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n","model = model.eval().to(device)\n","\n","preprocess = transforms.Compose([\n"," transforms.Resize((448, 448)),\n"," transforms.ToTensor(),\n"," transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n","])\n","\n","def get_wd_tags(img_path):\n"," try:\n"," img = Image.open(img_path).convert(\"RGB\")\n"," x = preprocess(img).unsqueeze(0).to(device) # β now using the correct device\n"," with torch.no_grad():\n"," logits = model(x)\n"," probs = torch.sigmoid(logits).squeeze(0).cpu().numpy()\n"," selected = [tags[i] for i, p in enumerate(probs) if p > tag_probability_threshold]\n"," return selected\n"," except Exception as e:\n"," print(f\" tagging failed: {img_path.name} β {str(e)}\")\n"," return []\n","\n","# βββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββ\n","def clean_caption(text: str) -> str:\n"," if not text.strip():\n"," return \"\"\n"," text = re.sub(r'\\byoung girl\\b', 'young woman', text, flags=re.IGNORECASE)\n"," text = re.sub(r'\\bswastika\\b', 'manji', text, flags=re.IGNORECASE)\n"," text = re.sub(r'\\byoung\\b', '', text, flags=re.IGNORECASE)\n"," text = text.replace('*', '')\n"," text = re.sub(r'\\s+', ' ', text)\n"," text = text.replace('\\r\\n', ' ').replace('\\n', ' ').replace('\\r', ' ')\n"," return text.strip()\n","\n","def spread_tags_into_caption(caption: str, new_tags: list) -> str:\n"," if not new_tags:\n"," return clean_caption(caption)\n","\n"," base = clean_caption(caption)\n"," if not base:\n"," return \", \".join(new_tags)\n","\n"," sentences = nltk.sent_tokenize(base)\n"," if len(sentences) <= 1:\n"," return base + \"\\n\\n\" + \", \".join(new_tags)\n","\n"," # Distribute tags between sentences\n"," num_gaps = len(sentences) - 1\n"," tags_per_gap = max(1, len(new_tags) // num_gaps)\n"," extra = len(new_tags) % num_gaps\n","\n"," parts = []\n"," tag_idx = 0\n"," for i, sent in enumerate(sentences):\n"," parts.append(sent.strip())\n"," if i < num_gaps:\n"," cnt = tags_per_gap + (1 if i < extra else 0)\n"," if cnt > 0:\n"," group = new_tags[tag_idx : tag_idx + cnt]\n"," tag_idx += cnt\n"," parts.append(\", \".join(group))\n","\n"," # Remaining tags at the end\n"," if tag_idx < len(new_tags):\n"," parts.append(\", \".join(new_tags[tag_idx:]))\n","\n"," return \"\\n\".join(parts)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"\\nπ Processing files...\\n\")\n","\n","removed = 0\n","kept = 0\n","\n","groups = defaultdict(list)\n","for f in extract_dir.rglob(\"*\"):\n"," if f.is_file():\n"," groups[f.stem].append(f)\n","\n","for stem, files in tqdm(groups.items(), desc=\"Groups\"):\n"," imgs = [f for f in files if f.suffix.lower() in {'.jpg','.jpeg','.png','.webp','.gif','.bmp','.tiff'}]\n"," txts = [f for f in files if f.suffix.lower() == '.txt']\n","\n"," if not imgs:\n"," continue\n","\n"," img = imgs[0] # take the first image\n"," wd_tags = get_wd_tags(img)\n","\n"," has_loli = 'loli' in ((' '.join(wd_tags)).lower() if not case_sensitive_loli_check else ' '.join(wd_tags))\n","\n"," if has_loli:\n"," removed += 1\n"," for f in files:\n"," try: f.unlink()\n"," except: pass\n"," continue\n","\n"," # Keep this pair\n"," kept += 1\n","\n"," # Read original caption if exists\n"," orig_caption = \"\"\n"," if txts:\n"," try:\n"," orig_caption = txts[0].read_text(encoding=\"utf-8\", errors=\"replace\").strip()\n"," except:\n"," pass\n","\n"," # Create improved caption\n"," final_caption = spread_tags_into_caption(orig_caption, wd_tags)\n","\n"," # Copy files to cleaned folder (preserve subfolder structure)\n"," for f in files:\n"," rel = f.relative_to(extract_dir)\n"," dst = cleaned_dir / rel\n"," dst.parent.mkdir(parents=True, exist_ok=True)\n"," shutil.copy2(f, dst)\n","\n"," # Write new caption (overwrite or create .txt)\n"," txt_name = img.stem + \".txt\"\n"," txt_rel = img.relative_to(extract_dir).parent / txt_name\n"," txt_dst = cleaned_dir / txt_rel\n"," txt_dst.parent.mkdir(parents=True, exist_ok=True)\n"," with open(txt_dst, \"w\", encoding=\"utf-8\") as fw:\n"," fw.write(final_caption)\n","\n","print(f\"\\nβ
Done processing\")\n","print(f\" Removed (loli detected): {removed}\")\n","print(f\" Kept & cleaned : {kept}\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"\\nποΈ Creating output zip...\")\n","\n","final_zip = Path(f\"/content/{output_zip_name}\")\n","\n","with zipfile.ZipFile(final_zip, \"w\", zipfile.ZIP_DEFLATED) as zf:\n"," for item in tqdm(cleaned_dir.rglob(\"*\"), desc=\"Zipping\"):\n"," if item.is_file():\n"," arc = item.relative_to(cleaned_dir)\n"," zf.write(item, arc)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"\\nπΎ Copying to Drive...\")\n","os.makedirs(output_folder_on_drive, exist_ok=True)\n","drive_dest = Path(output_folder_on_drive) / output_zip_name\n","shutil.copy2(final_zip, drive_dest)\n","\n","size_mb = final_zip.stat().st_size / (1024 * 1024)\n","print(f\"β Saved: {drive_dest}\")\n","print(f\" Size: {size_mb:.1f} MiB\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββ\n","print(\"\\nπ§Ή Cleaning up temp folders...\")\n","shutil.rmtree(extract_dir, ignore_errors=True)\n","shutil.rmtree(cleaned_dir, ignore_errors=True)\n","\n","print(\"\\nAll finished β\")"],"metadata":{"id":"wTXltVDGXX3z"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773089575687},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773080355474},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772998638620},{"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}
|