codeShare commited on
Commit
d53d5fe
Β·
verified Β·
1 Parent(s): 1567af3

Upload lora_vertical_slice_dataset_creator.ipynb

Browse files
lora_vertical_slice_dataset_creator.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":["import os\n","import io\n","import random\n","import zipfile\n","from google.colab import drive\n","from PIL import Image\n","import cv2\n","import numpy as np\n","import gc\n","\n","# ────────────────────────────────────────────────\n","# Configuration\n","# ────────────────────────────────────────────────\n","num_frames = 496 #@param {type:\"slider\", min:0, max:1500, step:100}\n","split_images_horizontally = False #@param {type:\"boolean\"}\n","use_manual_upload = False #@param {type:\"boolean\"}\n","\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","#@markdown **ZIP MODE** (when `use_manual_upload` is OFF)\n","#@markdown Paste full path to your zip file\n","zip_file_path = \"/content/drive/MyDrive/warhammer.zip\" #@param {type:\"string\"}\n","\n","# ────────────────────────────────────────────────\n","# Mount Google Drive\n","# ────────────────────────────────────────────────\n","drive_mounted = False\n","drive_output_dir = None\n","\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_base = \"/content/drive/MyDrive\"\n"," drive_output_dir = os.path.join(drive_base, drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(f\"β†’ Google Drive mounted. Output β†’ {drive_output_dir}/vertical_slices.zip\")\n"," except Exception as e:\n"," print(f\"Drive mount failed: {e}\")\n"," save_to_google_drive = False\n"," print(\"β†’ No persistent saving possible.\")\n","else:\n"," print(\"Google Drive saving disabled β†’ output only temporary!\")\n","\n","# ────────────────────────────────────────────────\n","# Settings\n","# ────────────────────────────────────────────────\n","FRAME_SIZE = 1024\n","BORDER_PX = 14\n","INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX\n","num_vertical_panels = 3 #@param {type:\"slider\", min:1, max:12}\n","NUM_SLICES = num_vertical_panels\n","SLICE_WIDTH = INNER_SIZE // NUM_SLICES\n","target_h = INNER_SIZE\n","target_w = SLICE_WIDTH\n","\n","BORDER_COLOR = (24, 24, 24)\n","\n","extract_root = \"/content/extracted_images\"\n","output_dir = \"/content/vertical_slice_frames\"\n","\n","os.makedirs(extract_root, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# ────────────────────────────────────────────────\n","# Helper – load image from source (path or BytesIO)\n","# ────────────────────────────────────────────────\n","def load_image_from_source(source):\n"," \"\"\"Return a fresh RGB PIL Image. Works for both file paths and BytesIO objects.\"\"\"\n"," if isinstance(source, str):\n"," return Image.open(source).convert('RGB')\n"," else: # BytesIO from manual upload\n"," source.seek(0)\n"," return Image.open(source).convert('RGB')\n","\n","# ────────────────────────────────────────────────\n","# Helper – extract ONE random vertical slice from a single image\n","# ────────────────────────────────────────────────\n","def extract_one_vertical_slice(photo, target_w, target_h, border_color):\n"," \"\"\"Resize to target height, then return exactly one slice.\n"," - If resized width < target_w β†’ center-padded with border color\n"," - If resized width >= target_w β†’ random x-coordinate crop\"\"\"\n"," try:\n"," w, h = photo.size\n"," if h <= 0 or w <= 0:\n"," return None\n","\n"," scale = target_h / h\n"," new_w = int(w * scale + 0.5)\n"," if new_w < 1:\n"," return None\n","\n"," resized = photo.resize((new_w, target_h), Image.LANCZOS)\n","\n"," if new_w < target_w:\n"," # Pad with border color (same behavior as original script)\n"," sl = Image.new('RGB', (target_w, target_h), border_color)\n"," sl.paste(resized, ((target_w - new_w)//2, 0))\n"," del resized\n"," return sl\n"," else:\n"," # Random x-coordinate (as requested)\n"," max_start_x = new_w - target_w\n"," start_x = random.randint(0, max_start_x)\n"," crop = resized.crop((start_x, 0, start_x + target_w, target_h))\n"," del resized\n"," return crop\n","\n"," except Exception as e:\n"," print(f\"Error extracting one slice: {e}\")\n"," return None\n","\n","# ────────────────────────────────────────────────\n","# Load ALL sample images first (paths or BytesIO) – low memory\n","# ────────────────────────────────────────────────\n","all_sources = [] # list of str paths (zip) or BytesIO objects (manual upload)\n","\n","print(\"Scanning images...\\n\")\n","\n","if use_manual_upload:\n"," from google.colab import files\n"," print(\"Upload images (jpg/jpeg/png/webp)\")\n"," uploaded = files.upload()\n","\n"," count = 0\n"," for filename, filedata in uploaded.items():\n"," fname_lower = filename.lower()\n"," if fname_lower.startswith('._') or '__macosx' in fname_lower:\n"," continue\n"," if fname_lower.endswith(('.jpg','.jpeg','.png','.webp')):\n"," try:\n"," buf = io.BytesIO(filedata)\n"," # Quick verify\n"," with Image.open(buf) as im:\n"," im.verify()\n"," buf.seek(0)\n"," all_sources.append(buf)\n"," count += 1\n"," if count % 20 == 0:\n"," print(f\"Processed {count} uploaded images...\")\n"," except Exception as e:\n"," print(f\"Skip {filename}: {e}\")\n","\n","else:\n"," if not zip_file_path or not os.path.isfile(zip_file_path):\n"," print(\"Invalid or missing zip path.\")\n"," else:\n"," try:\n"," with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n"," print(\"Extraction finished.\")\n"," except Exception as e:\n"," print(f\"Zip extraction failed: {e}\")\n"," raise\n","\n"," valid_exts = ('.jpg', '.jpeg', '.png', '.webp')\n"," count = 0\n"," for root_dir, _, files in os.walk(extract_root):\n"," if '__MACOSX' in root_dir:\n"," continue\n"," for fname in files:\n"," if fname.startswith('._'):\n"," continue\n"," if fname.lower().endswith(valid_exts):\n"," path = os.path.join(root_dir, fname)\n"," try:\n"," # Quick verify\n"," with Image.open(path) as im:\n"," im.verify()\n"," all_sources.append(path)\n"," count += 1\n"," if count % 20 == 0:\n"," print(f\"Found {count} images...\")\n"," except Exception as e:\n"," print(f\"Skip {fname}: {str(e)}\")\n","\n","print(f\"\\nTotal sample images ready: {len(all_sources)}\")\n","\n","# ────────────────────────────────────────────────\n","# Select N*M images at random β†’ extract ONE random slice per image\n","# ────────────────────────────────────────────────\n","N = NUM_SLICES\n","M = num_frames\n","total_needed = N * M\n","\n","all_slices = []\n","\n","if len(all_sources) == 0 or total_needed == 0:\n"," print(\"No images or no frames requested β€” stopping.\")\n","else:\n"," print(f\"β†’ Picking {total_needed} sample images at random...\")\n"," selected_sources = random.choices(all_sources, k=total_needed)\n","\n"," print(\"β†’ Extracting one random vertical slice from each selected image...\\n\")\n"," for i, source in enumerate(selected_sources):\n"," try:\n"," img = load_image_from_source(source)\n"," slice_img = extract_one_vertical_slice(img, target_w, target_h, BORDER_COLOR)\n"," if slice_img is not None:\n"," all_slices.append(slice_img)\n"," del img\n"," if (i + 1) % 50 == 0:\n"," print(f\"Extracted {len(all_slices)}/{total_needed} slices...\")\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Error on sample {i+1}: {e}\")\n","\n"," print(f\"\\nTotal vertical slices extracted: {len(all_slices)}\")\n","\n","# ────────────────────────────────────────────────\n","# Generate frames\n","# ────────────────────────────────────────────────\n","if len(all_slices) == 0:\n"," print(\"No slices available β€” stopping.\")\n","else:\n"," print(f\"Generating {num_frames} frames...\")\n"," # Shuffle once so slices are randomly distributed across frames\n"," random.shuffle(all_slices)\n","\n"," frame_idx = 0\n"," while frame_idx < num_frames:\n"," start = frame_idx * NUM_SLICES\n"," if start + NUM_SLICES > len(all_slices):\n"," print(f\"β†’ Not enough slices left for frame {frame_idx+1} (stopping early)\")\n"," break\n","\n"," group = all_slices[start : start + NUM_SLICES]\n","\n"," canvas = Image.new('RGB', (INNER_SIZE, INNER_SIZE), (0, 0, 0))\n"," for col in range(NUM_SLICES):\n"," crop = group[col]\n"," canvas.paste(crop, (col * SLICE_WIDTH, 0))\n","\n"," final = Image.new('RGB', (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(canvas, (BORDER_PX, BORDER_PX))\n","\n"," fname = f\"frame_{frame_idx+1:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=82)\n","\n"," del canvas, final\n"," frame_idx += 1\n","\n"," if frame_idx % 50 == 0:\n"," print(f\"Saved {frame_idx}/{num_frames} frames...\")\n"," if frame_idx % 100 == 0:\n"," gc.collect()\n","\n"," print(f\"Finished β€” created {frame_idx} frames\")\n","\n"," # ─── Save fixed-name zip directly to Drive (overwrite) ───\n"," if save_to_google_drive and drive_mounted:\n"," final_zip_name = \"vertical_slices.zip\"\n"," local_zip_path = f\"/content/{final_zip_name}\"\n"," drive_zip_path = os.path.join(drive_output_dir, final_zip_name)\n","\n"," print(\"Creating zip (flat structure)...\")\n","\n"," # Create zip with files at root level\n"," with zipfile.ZipFile(local_zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n"," for fname in sorted(os.listdir(output_dir)):\n"," if fname.endswith('.jpg'):\n"," full_path = os.path.join(output_dir, fname)\n"," zf.write(full_path, arcname=fname) # ← flat: no subfolder\n","\n"," print(\"Copying to Google Drive (will overwrite previous version)...\")\n"," !cp -f \"{local_zip_path}\" \"{drive_zip_path}\"\n","\n"," print(f\"\\nSuccess! Overwritten file:\")\n"," print(f\"β†’ {drive_zip_path}\")\n","\n"," # Optional cleanup (uncomment if you want to free Colab disk space)\n"," # !rm -rf \"{output_dir}\" \"{local_zip_path}\"\n"," print(\"Temporary files kept in /content β€” delete manually if needed.\")\n"," else:\n"," print(\"\\nNo Drive save β†’ frames are only in /content/vertical_slice_frames\")"],"metadata":{"id":"Ux-zCWwMfxD_","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title WD Tagger + TOS Filter + Caption Cleaner + Tag Spreading β†’ Drive (single-line + comma spacing) { 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","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)\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 is_junk_file(path: Path) -> bool:\n"," \"\"\"Skip macOS metadata files and common junk\"\"\"\n"," name = path.name\n"," path_str = str(path)\n"," return (\n"," name.startswith('._') or\n"," '__MACOSX' in path_str or\n"," name in {'.DS_Store', 'Thumbs.db', 'desktop.ini', '.Spotlight-V100', '.Trashes'}\n"," )\n","\n","def normalize_skin_tags(tag_list: list) -> list:\n"," \"\"\"Replace blue_skin / colored_skin with plain 'skin' (only once)\"\"\"\n"," new_list = []\n"," has_skin = False\n"," for t in tag_list:\n"," if t in (\"blue_skin\", \"colored_skin\"):\n"," if not has_skin:\n"," new_list.append(\"skin\")\n"," has_skin = True\n"," else:\n"," new_list.append(t)\n"," return new_list\n","\n","def clean_caption(text: str) -> str:\n"," if not text.strip():\n"," return \"\"\n","\n"," # Remove unwanted characters & patterns\n"," text = text.replace('`', '')\n"," text = text.replace('(', '').replace(')', '')\n"," text = text.replace('*', '')\n","\n"," # Remove word 'small' (standalone, case insensitive)\n"," text = re.sub(r'\\bsmall\\b', '', text, flags=re.IGNORECASE)\n","\n"," # Collapse all whitespace including newlines, tabs, etc.\n"," text = re.sub(r'\\s+', ' ', text)\n","\n"," # Common safety / TOS replacements\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","\n"," return text.strip()\n","\n","def spread_tags_into_caption(caption: str, new_tags: list) -> str:\n"," new_tags = normalize_skin_tags(new_tags)\n","\n"," if not new_tags:\n"," cleaned = clean_caption(caption)\n"," return ' , '.join(cleaned.split(',')).strip() if cleaned else ''\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"," combined = base + \" \" + \" , \".join(new_tags)\n"," else:\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"," combined = \" \".join(parts)\n","\n"," # Final cleanup: normalize comma spacing\n"," combined = re.sub(r'\\s*,\\s*', ' , ', combined)\n"," combined = re.sub(r'\\s+', ' ', combined).strip()\n","\n"," return combined\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() and not is_junk_file(f):\n"," groups[f.stem].append(f)\n","\n","for stem, files in tqdm(groups.items(), desc=\"Groups\"):\n"," # Filter again just in case\n"," valid_files = [f for f in files if not is_junk_file(f)]\n","\n"," imgs = [\n"," f for f in valid_files\n"," if f.suffix.lower() in {'.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff'}\n"," ]\n"," txts = [f for f in valid_files if f.suffix.lower() == '.txt']\n","\n"," if not imgs:\n"," continue\n","\n"," img = imgs[0] # take the first valid image\n"," wd_tags = get_wd_tags(img)\n","\n"," # Loli check (case sensitive or not)\n"," joined_tags = ' '.join(wd_tags)\n"," has_loli = 'loli' in (joined_tags.lower() if not case_sensitive_loli_check else joined_tags)\n","\n"," if has_loli:\n"," removed += 1\n"," # Optional: remove files from temp dir (not strictly needed)\n"," # for f in valid_files: f.unlink(missing_ok=True)\n"," continue\n","\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 final caption\n"," final_caption = spread_tags_into_caption(orig_caption, wd_tags)\n","\n"," # Copy only non-junk files to cleaned folder\n"," for f in valid_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 cleaned caption next to the image\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() and not is_junk_file(item):\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":"DCZpKdWX0UNZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @title Recompose Frames – Variable Columns – Save ZIP to Drive\n","import os\n","import random\n","import zipfile\n","from google.colab import drive\n","from PIL import Image\n","import numpy as np\n","import gc\n","from tqdm.notebook import tqdm\n","\n","# ────────────────────────────────────────────────\n","# Configuration\n","# ────────────────────────────────────────────────\n","#@markdown Input zip path (your previous 1024Γ—1024 frames)\n","input_zip_path = \"/content/drive/MyDrive/my_set.zip\" #@param {type:\"string\"}\n","\n","#@markdown Output folder name on Google Drive\n","drive_output_folder = \"recomposed_variable_columns\" #@param {type:\"string\"}\n","\n","#@markdown How many new frames to generate?\n","num_new_frames = 300 #@param {type:\"slider\", min:200, max:8000, step:100}\n","\n","#@markdown Allowed column counts (at least one must be selected)\n","allow_2_columns = True #@param {type:\"boolean\"}\n","allow_3_columns = False #@param {type:\"boolean\"}\n","allow_4_columns = False #@param {type:\"boolean\"}\n","allow_5_columns = False #@param {type:\"boolean\"}\n","allow_1_column = False #@param {type:\"boolean\"}\n","\n","#@markdown ─── Composition settings ───\n","keep_original_height = True #@param {type:\"boolean\"} # 1024 px tall\n","add_border = True #@param {type:\"boolean\"}\n","border_px = 12\n","border_color = (18, 18, 18)\n","\n","#@markdown JPEG quality\n","save_quality = 83 #@param {type:\"slider\", min:65, max:95, step:1}\n","\n","# ────────────────────────────────────────────────\n","# Mount Drive\n","# ────────────────────────────────────────────────\n","drive.mount('/content/drive', force_remount=False)\n","print()\n","\n","drive_base = \"/content/drive/MyDrive\"\n","output_dir_drive = os.path.join(drive_base, drive_output_folder)\n","os.makedirs(output_dir_drive, exist_ok=True)\n","\n","# ────────────────────────────────────────────────\n","# Prepare local temp folders\n","# ────────────────────────────────────────────────\n","extract_dir = \"/content/extracted_frames\"\n","local_output_dir = \"/content/recomposed_temp\"\n","os.makedirs(extract_dir, exist_ok=True)\n","os.makedirs(local_output_dir, exist_ok=True)\n","\n","# ────────────────────────────────────────────────\n","# 1. Extract input zip\n","# ────────────────────────────────────────────────\n","if not os.path.isfile(input_zip_path):\n"," print(f\"❌ File not found: {input_zip_path}\")\n","else:\n"," print(f\"Extracting {os.path.basename(input_zip_path)} …\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zf:\n"," zf.extractall(extract_dir)\n"," print(\"Extraction done.\\n\")\n","\n"," # ────────────────────────────────────────────────\n"," # 2. Collect all clean vertical strips (~256Γ—1024)\n"," # ────────────────────────────────────────────────\n"," all_strips = []\n"," valid_exts = ('.jpg', '.jpeg', '.png')\n","\n"," print(\"Extracting vertical strips from frames…\")\n"," frame_files = [f for f in os.listdir(extract_dir)\n"," if f.lower().endswith(valid_exts) and not f.startswith('._')]\n","\n"," for fname in tqdm(frame_files):\n"," try:\n"," img = Image.open(os.path.join(extract_dir, fname)).convert('RGB')\n"," w, h = img.size\n"," if w != 1024 or h != 1024:\n"," continue\n","\n"," inner_w = 1024 - 2 * border_px\n"," strip_w = inner_w // 4\n","\n"," for i in range(4):\n"," left = border_px + i * strip_w\n"," strip = img.crop((left, border_px, left + strip_w, 1024 - border_px))\n"," all_strips.append(strip)\n","\n"," del img\n"," gc.collect()\n","\n"," except:\n"," pass\n","\n"," print(f\"\\nCollected {len(all_strips):,} vertical strips.\\n\")\n","\n"," if len(all_strips) < 2:\n"," print(\"❌ Too few strips to create compositions.\")\n"," else:\n"," # ────────────────────────────────────────────────\n"," # 3. Prepare allowed column counts\n"," # ────────────────────────────────────────────────\n"," possible_cols = []\n"," if allow_1_column: possible_cols.append(1)\n"," if allow_2_columns: possible_cols.append(2)\n"," if allow_3_columns: possible_cols.append(3)\n"," if allow_4_columns: possible_cols.append(4)\n"," if allow_5_columns: possible_cols.append(5)\n","\n"," if not possible_cols:\n"," print(\"❌ Please enable at least one column count.\")\n"," else:\n"," print(f\"Allowed column counts: {possible_cols}\\n\")\n","\n"," # ────────────────────────────────────────────────\n"," # 4. Generate new variable-width frames\n"," # ────────────────────────────────────────────────\n"," base_strip_w = all_strips[0].width # usually ~256\n"," target_h = 1024 if keep_original_height else None\n","\n"," print(f\"Generating {num_new_frames} new frames…\")\n","\n"," for i in tqdm(range(num_new_frames)):\n"," num_cols = random.choice(possible_cols)\n"," chosen_strips = random.choices(all_strips, k=num_cols)\n","\n"," # Optional light variation\n"," if random.random() < 0.18:\n"," chosen_strips = [s.transpose(Image.FLIP_LEFT_RIGHT) if random.random() < 0.5 else s\n"," for s in chosen_strips]\n","\n"," canvas_w = num_cols * base_strip_w\n"," canvas_h = target_h if target_h else max(s.height for s in chosen_strips)\n","\n"," canvas = Image.new('RGB', (canvas_w, canvas_h), (0,0,0))\n","\n"," for col, strip in enumerate(chosen_strips):\n"," paste_img = strip\n"," if target_h and strip.height != target_h:\n"," paste_img = strip.resize((base_strip_w, target_h), Image.LANCZOS)\n","\n"," paste_y = (canvas_h - paste_img.height) // 2\n"," canvas.paste(paste_img, (col * base_strip_w, paste_y))\n","\n"," # Add border if requested\n"," if add_border:\n"," bordered = Image.new('RGB', (canvas_w + 2*border_px, canvas_h + 2*border_px), border_color)\n"," bordered.paste(canvas, (border_px, border_px))\n"," final = bordered\n"," else:\n"," final = canvas\n","\n"," # Save\n"," fname = f\"recomp_{i+1:05d}_cols{num_cols}.jpg\"\n"," final.save(os.path.join(local_output_dir, fname), \"JPEG\", quality=save_quality)\n","\n"," if (i+1) % 300 == 0:\n"," gc.collect()\n","\n"," print(f\"\\nCreated {num_new_frames} frames in {local_output_dir}\")\n","\n"," # ────────────────────────────────────────────────\n"," # 5. Zip and copy to Drive\n"," # ────────────────────────────────────────────────\n"," zip_name = f\"recomposed_{len(possible_cols)}options.zip\"\n"," local_zip = f\"/content/{zip_name}\"\n"," drive_zip = os.path.join(output_dir_drive, zip_name)\n","\n"," print(\"\\nCreating zip (flat structure)…\")\n"," with zipfile.ZipFile(local_zip, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n"," for fname in os.listdir(local_output_dir):\n"," if fname.endswith(('.jpg','.jpeg','.png')):\n"," zf.write(os.path.join(local_output_dir, fname), arcname=fname)\n","\n"," print(\"Copying to Google Drive…\")\n"," !cp -f \"{local_zip}\" \"{drive_zip}\"\n","\n"," print(f\"\\nSuccess! ZIP saved to:\")\n"," print(f\"β†’ {drive_zip}\")\n","\n"," # Optional: clean up local files (uncomment if needed)\n"," # !rm -rf \"{local_output_dir}\" \"{local_zip}\"\n"," print(\"\\nTemporary files kept in /content β€” delete manually if disk space is low.\")"],"metadata":{"id":"A3uVQAHkkJXU"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776027716448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1773663661932},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773663290922},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773264797996},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773163850245},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773090196076},{"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}]},"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":"hDzdSOe90dAa"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"6dlmgMn_hOeO"},"outputs":[],"source":["# @title Image Processing Pipeline: Unzip β†’ Crop Content β†’ Filter Height β†’ Save COLORED + WHITE Background Zips to Drive\n","# Run this cell after mounting Drive (it will prompt if needed)\n","\n","from google.colab import drive\n","import os\n","import zipfile\n","import shutil\n","from PIL import Image, ImageChops\n","\n","# Mount Google Drive (run once per session)\n","drive.mount('/content/drive', force_remount=False)\n","\n","# ==================== INPUT: ZIP PATH ====================\n","# Replace the path below with your ZIP file location on Drive\n","zip_path = '/content/drive/MyDrive/lisas.zip' #@param {type:\"string\"}\n","\n","if not os.path.exists(zip_path):\n"," raise FileNotFoundError(f\"ZIP file not found: {zip_path}\\nPlease update the zip_path variable above.\")\n","\n","# ==================== SETUP TEMP DIRECTORIES ====================\n","extract_dir = '/content/extracted_images'\n","colored_bg_dir = '/content/colored_background_images'\n","white_bg_dir = '/content/white_background_images'\n","\n","for d in [extract_dir, colored_bg_dir, white_bg_dir]:\n"," os.makedirs(d, exist_ok=True)\n","\n","# ==================== HELPER FUNCTIONS ====================\n","def crop_to_content_and_bg(im):\n"," \"\"\"Crop empty space using either alpha (transparent) or solid background color.\n"," Returns (cropped_image, background_color) or (None, None) if empty.\"\"\"\n"," if im.size[0] == 0 or im.size[1] == 0:\n"," return None, None\n","\n"," # Get original top-left pixel as potential background color\n"," bg_color = im.getpixel((0, 0))\n","\n"," # Handle transparent images (RGBA / LA / P with transparency)\n"," if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):\n"," try:\n"," alpha = im.split()[-1] # last channel is alpha\n"," bbox = alpha.getbbox()\n"," if bbox:\n"," return im.crop(bbox), None # transparent = treated as COLORED background\n"," except:\n"," pass\n","\n"," # Solid color background case (RGB or fallback)\n"," bg = Image.new(im.mode, im.size, bg_color)\n"," diff = ImageChops.difference(im, bg)\n"," bbox = diff.getbbox()\n"," if bbox:\n"," return im.crop(bbox), bg_color\n"," return None, None\n","\n","\n","def is_light_background(bg_color):\n"," \"\"\"Return True if background is white or light-colored (luminance > 200).\"\"\"\n"," if bg_color is None:\n"," return False\n"," # Handle RGBA\n"," if len(bg_color) == 4:\n"," r, g, b, a = bg_color\n"," if a < 200: # mostly transparent\n"," return False\n"," bg_color = (r, g, b)\n"," r, g, b = bg_color[:3]\n"," # Standard luminance formula\n"," luminance = 0.299 * r + 0.587 * g + 0.114 * b\n"," return luminance > 200\n","\n","\n","# ==================== UNPACK ZIP + CLEAN NON-IMAGE JUNK ====================\n","print(\"πŸ“¦ Unpacking ZIP...\")\n","with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n","# Explicitly remove common non-image junk (Mac __MACOSX folder + ._ files)\n","print(\"🧹 Cleaning non-image items (__MACOSX, ._ files, etc.)...\")\n","macosx_path = os.path.join(extract_dir, '__MACOSX')\n","if os.path.exists(macosx_path):\n"," shutil.rmtree(macosx_path)\n"," print(\" Removed __MACOSX directory.\")\n","\n","# ==================== FIND ALL IMAGES (recursive + extra safety checks) ====================\n","image_paths = []\n","valid_extensions = ('.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff')\n","\n","for root, _, files in os.walk(extract_dir):\n"," # Skip any residual __MACOSX folder (in case it was recreated)\n"," if '__MACOSX' in root:\n"," continue\n"," for file in files:\n"," # Extra safety: ignore Mac hidden files and only keep real images\n"," if (file.lower().endswith(valid_extensions) and\n"," not file.startswith('._') and\n"," not file.startswith('.')): # also catches .DS_Store etc.\n"," image_paths.append(os.path.join(root, file))\n","\n","print(f\"Found {len(image_paths)} valid images to process (non-image junk excluded).\")\n","\n","# ==================== PROCESS EACH IMAGE ====================\n","colored_count = 0\n","white_count = 0\n","\n","for filepath in image_paths:\n"," filename = os.path.basename(filepath)\n"," try:\n"," with Image.open(filepath) as img:\n"," # Convert palette mode if needed\n"," if img.mode == 'P':\n"," img = img.convert('RGBA')\n","\n"," cropped, bg_color = crop_to_content_and_bg(img)\n","\n"," if cropped is None or cropped.height < 1024:\n"," continue\n","\n"," # Decide which folder based on background\n"," if is_light_background(bg_color):\n"," out_dir = white_bg_dir\n"," white_count += 1\n"," else:\n"," out_dir = colored_bg_dir\n"," colored_count += 1\n","\n"," out_path = os.path.join(out_dir, filename)\n"," cropped.save(out_path) # PIL auto-detects format from extension\n","\n"," except Exception as e:\n"," print(f\"⚠️ Skipped {filename}: {e}\")\n","\n","total_kept = colored_count + white_count\n","print(f\"βœ… Processing complete!\")\n","print(f\" β€’ Total images kept (height β‰₯ 1024px): {total_kept}\")\n","print(f\" β€’ Colored background images: {colored_count}\")\n","print(f\" β€’ White / light background images: {white_count}\")\n","\n","# ==================== CREATE ZIPS ====================\n","def make_zip(source_dir, zip_filename):\n"," \"\"\"Create ZIP and exclude any non-image files (extra safety).\"\"\"\n"," zip_full_path = f'/content/{zip_filename}'\n"," with zipfile.ZipFile(zip_full_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for root, _, files in os.walk(source_dir):\n"," for file in files:\n"," if file.lower().endswith(valid_extensions) and not file.startswith('._'):\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, source_dir)\n"," zf.write(file_path, arcname)\n"," return zip_full_path\n","\n","print(\"πŸ—œοΈ Creating ZIP files...\")\n","colored_zip = make_zip(colored_bg_dir, 'colored_background_images.zip')\n","white_zip = make_zip(white_bg_dir, 'white_background_images.zip')\n","\n","# ==================== COPY TO GOOGLE DRIVE ====================\n","drive_colored = '/content/drive/MyDrive/colored_background_images.zip'\n","drive_white = '/content/drive/MyDrive/white_background_images.zip'\n","\n","shutil.copy(colored_zip, drive_colored)\n","shutil.copy(white_zip, drive_white)\n","\n","print(\"πŸŽ‰ DONE!\")\n","print(f\"πŸ“ Colored background images β†’ {drive_colored}\")\n","print(f\"πŸ“ White / light background images β†’ {drive_white}\")\n","print(\"\\nYou can now download the two separate ZIPs from your Google Drive.\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"93JpoQJ77NGu"},"outputs":[],"source":["# ────────────────────────────────────────────────\n","# 🎨 CLEAN ROW β†’ PURE 1024x1024 FRAMES (NO DISTORTION)\n","# ────────────────────────────────────────────────\n","\n","#@markdown ## βš™οΈ Main Settings\n","num_frames = 500 #@param {type:\"slider\", min:10, max:2000, step:10}\n","overlap_percent = 25 #@param {type:\"slider\", min:0, max:50, step:1}\n","min_step_ratio = 0.8 #@param {type:\"slider\", min:0.5, max:1.0, step:0.05}\n","max_step_ratio = 1.0 #@param {type:\"slider\", min:0.8, max:1.5, step:0.05}\n","\n","#@markdown ## 🧱 Border\n","border_width = 8 #@param {type:\"slider\", min:0, max:100}\n","\n","#@markdown ## πŸ’Ύ Input / Output\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","zip_file_path = \"/content/drive/MyDrive/fess.zip\" #@param {type:\"string\"}\n","\n","# ────────────────────────────────────────────────\n","\n","FRAME_SIZE = 1024\n","INNER_SIZE = FRAME_SIZE - 2 * border_width\n","BORDER_COLOR = (24, 24, 24)\n","\n","import os, random, zipfile\n","import numpy as np\n","from PIL import Image\n","from google.colab import drive\n","\n","# ────────────────────────────────────────────────\n","# Mount Drive\n","# ────────────────────────────────────────���───────\n","\n","drive_mounted = False\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_output_dir = os.path.join(\"/content/drive/MyDrive\", drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(\"Drive mounted\")\n"," except:\n"," save_to_google_drive = False\n","\n","# ────────────────────────────────────────────────\n","# Extract ZIP\n","# ────────────────────────────────────────────────\n","\n","extract_root = \"/content/extracted_images\"\n","output_dir = \"/content/frames\"\n","\n","os.makedirs(extract_root, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n","\n","# ────────────────────────────────────────────────\n","# Load images\n","# ────────────────────────────────────────────────\n","\n","valid_exts = ('.jpg','.jpeg','.png','.webp')\n","all_sources = []\n","\n","for root, _, files in os.walk(extract_root):\n"," for f in files:\n"," if f.lower().endswith(valid_exts):\n"," all_sources.append(os.path.join(root, f))\n","\n","print(\"Images found:\", len(all_sources))\n","\n","# ────────────────────────────────────────────────\n","# Build row UNTIL enough width\n","# ────────────────────────────────────────────────\n","\n","def build_row_until_width(all_sources, target_h, overlap_ratio, required_width):\n"," canvas = Image.new(\"RGB\", (required_width, target_h))\n"," x = 0\n","\n"," while x < required_width:\n"," src = random.choice(all_sources)\n","\n"," try:\n"," im = Image.open(src).convert(\"RGB\")\n"," w, h = im.size\n","\n"," scale = target_h / h\n"," new_w = int(w * scale)\n","\n"," im = im.resize((new_w, target_h), Image.LANCZOS)\n","\n"," # overlap\n"," if x > 0:\n"," x -= int(new_w * overlap_ratio)\n","\n"," canvas.paste(im, (x, 0))\n"," x += new_w\n","\n"," except:\n"," continue\n","\n"," return canvas\n","\n","# ────────────────────────────────────────────────\n","# Calculate required width\n","# ────────────────────────────────────────────────\n","\n","overlap_ratio = overlap_percent / 100.0\n","\n","avg_step = (min_step_ratio + max_step_ratio) / 2\n","estimated_width = int(num_frames * INNER_SIZE * avg_step * 1.2)\n","\n","print(\"Building row width:\", estimated_width)\n","\n","row_img = build_row_until_width(\n"," all_sources,\n"," INNER_SIZE,\n"," overlap_ratio,\n"," estimated_width\n",")\n","\n","row_np = np.array(row_img)\n","row_h, row_w = row_np.shape[:2]\n","\n","# ────────────────────────────────────────────────\n","# Generate frames (NO distortion)\n","# ────────────────────────────────────────────────\n","\n","frame_idx = 0\n","x_cursor = 0\n","\n","while x_cursor + INNER_SIZE <= row_w and frame_idx < num_frames:\n","\n"," step = random.randint(\n"," int(INNER_SIZE * min_step_ratio),\n"," int(INNER_SIZE * max_step_ratio)\n"," )\n","\n"," crop = row_np[:, x_cursor:x_cursor + INNER_SIZE]\n","\n"," final = Image.new(\"RGB\", (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(Image.fromarray(crop), (border_width, border_width))\n","\n"," fname = f\"frame_{frame_idx:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=90)\n","\n"," frame_idx += 1\n"," x_cursor += step\n","\n"," if frame_idx % 50 == 0:\n"," print(frame_idx, \"frames done\")\n","\n","print(\"Finished:\", frame_idx)\n","\n","# ────────────────────────────────────────────────\n","# Save ZIP\n","# ────────────────────────────────────────────────\n","\n","if save_to_google_drive and drive_mounted:\n","\n"," zip_path = \"/content/output.zip\"\n"," drive_path = os.path.join(drive_output_dir, \"vertical_slices.zip\")\n","\n"," with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for f in os.listdir(output_dir):\n"," if f.endswith(\".jpg\"):\n"," zf.write(os.path.join(output_dir, f), arcname=f)\n","\n"," !cp -f \"{zip_path}\" \"{drive_path}\"\n","\n"," print(\"Saved to Drive:\", drive_path)"]},{"cell_type":"markdown","source":["From here the dataset is in your drive and the notebook can be safely disconnected"],"metadata":{"id":"Ct1FG-YemBeK"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"DCZpKdWX0UNZ","cellView":"form"},"outputs":[],"source":["#@title WD Tagger + TOS Filter + Caption Cleaner + Tag Spreading β†’ Drive (single-line + comma spacing) { 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","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)\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 is_junk_file(path: Path) -> bool:\n"," \"\"\"Skip macOS metadata files and common junk\"\"\"\n"," name = path.name\n"," path_str = str(path)\n"," return (\n"," name.startswith('._') or\n"," '__MACOSX' in path_str or\n"," name in {'.DS_Store', 'Thumbs.db', 'desktop.ini', '.Spotlight-V100', '.Trashes'}\n"," )\n","\n","def normalize_skin_tags(tag_list: list) -> list:\n"," \"\"\"Replace blue_skin / colored_skin with plain 'skin' (only once)\"\"\"\n"," new_list = []\n"," has_skin = False\n"," for t in tag_list:\n"," if t in (\"blue_skin\", \"colored_skin\"):\n"," if not has_skin:\n"," new_list.append(\"skin\")\n"," has_skin = True\n"," else:\n"," new_list.append(t)\n"," return new_list\n","\n","def clean_caption(text: str) -> str:\n"," if not text.strip():\n"," return \"\"\n","\n"," # Remove unwanted characters & patterns\n"," text = text.replace('`', '')\n"," text = text.replace('(', '').replace(')', '')\n"," text = text.replace('*', '')\n","\n"," # Remove word 'small' (standalone, case insensitive)\n"," text = re.sub(r'\\bsmall\\b', '', text, flags=re.IGNORECASE)\n","\n"," # Collapse all whitespace including newlines, tabs, etc.\n"," text = re.sub(r'\\s+', ' ', text)\n","\n"," # Common safety / TOS replacements\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","\n"," return text.strip()\n","\n","def spread_tags_into_caption(caption: str, new_tags: list) -> str:\n"," new_tags = normalize_skin_tags(new_tags)\n","\n"," if not new_tags:\n"," cleaned = clean_caption(caption)\n"," return ' , '.join(cleaned.split(',')).strip() if cleaned else ''\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"," combined = base + \" \" + \" , \".join(new_tags)\n"," else:\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"," combined = \" \".join(parts)\n","\n"," # Final cleanup: normalize comma spacing\n"," combined = re.sub(r'\\s*,\\s*', ' , ', combined)\n"," combined = re.sub(r'\\s+', ' ', combined).strip()\n","\n"," return combined\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() and not is_junk_file(f):\n"," groups[f.stem].append(f)\n","\n","for stem, files in tqdm(groups.items(), desc=\"Groups\"):\n"," # Filter again just in case\n"," valid_files = [f for f in files if not is_junk_file(f)]\n","\n"," imgs = [\n"," f for f in valid_files\n"," if f.suffix.lower() in {'.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff'}\n"," ]\n"," txts = [f for f in valid_files if f.suffix.lower() == '.txt']\n","\n"," if not imgs:\n"," continue\n","\n"," img = imgs[0] # take the first valid image\n"," wd_tags = get_wd_tags(img)\n","\n"," # Loli check (case sensitive or not)\n"," joined_tags = ' '.join(wd_tags)\n"," has_loli = 'loli' in (joined_tags.lower() if not case_sensitive_loli_check else joined_tags)\n","\n"," if has_loli:\n"," removed += 1\n"," # Optional: remove files from temp dir (not strictly needed)\n"," # for f in valid_files: f.unlink(missing_ok=True)\n"," continue\n","\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 final caption\n"," final_caption = spread_tags_into_caption(orig_caption, wd_tags)\n","\n"," # Copy only non-junk files to cleaned folder\n"," for f in valid_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 cleaned caption next to the image\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() and not is_junk_file(item):\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 βœ“\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"A3uVQAHkkJXU"},"outputs":[],"source":["# @title Recompose Frames – Variable Columns – Save ZIP to Drive\n","import os\n","import random\n","import zipfile\n","from google.colab import drive\n","from PIL import Image\n","import numpy as np\n","import gc\n","from tqdm.notebook import tqdm\n","\n","# ────────────────────────────────────────────────\n","# Configuration\n","# ────────────────────────────────────────────────\n","#@markdown Input zip path (your previous 1024Γ—1024 frames)\n","input_zip_path = \"/content/drive/MyDrive/my_set.zip\" #@param {type:\"string\"}\n","\n","#@markdown Output folder name on Google Drive\n","drive_output_folder = \"recomposed_variable_columns\" #@param {type:\"string\"}\n","\n","#@markdown How many new frames to generate?\n","num_new_frames = 300 #@param {type:\"slider\", min:200, max:8000, step:100}\n","\n","#@markdown Allowed column counts (at least one must be selected)\n","allow_2_columns = True #@param {type:\"boolean\"}\n","allow_3_columns = False #@param {type:\"boolean\"}\n","allow_4_columns = False #@param {type:\"boolean\"}\n","allow_5_columns = False #@param {type:\"boolean\"}\n","allow_1_column = False #@param {type:\"boolean\"}\n","\n","#@markdown ─── Composition settings ───\n","keep_original_height = True #@param {type:\"boolean\"} # 1024 px tall\n","add_border = True #@param {type:\"boolean\"}\n","border_px = 12\n","border_color = (18, 18, 18)\n","\n","#@markdown JPEG quality\n","save_quality = 83 #@param {type:\"slider\", min:65, max:95, step:1}\n","\n","# ────────────────────────────────────────────────\n","# Mount Drive\n","# ────────────────────────────────────────────────\n","drive.mount('/content/drive', force_remount=False)\n","print()\n","\n","drive_base = \"/content/drive/MyDrive\"\n","output_dir_drive = os.path.join(drive_base, drive_output_folder)\n","os.makedirs(output_dir_drive, exist_ok=True)\n","\n","# ────────────────────────────────────────────────\n","# Prepare local temp folders\n","# ────────────────────────────────────────────────\n","extract_dir = \"/content/extracted_frames\"\n","local_output_dir = \"/content/recomposed_temp\"\n","os.makedirs(extract_dir, exist_ok=True)\n","os.makedirs(local_output_dir, exist_ok=True)\n","\n","# ────────────────────────────────────────────────\n","# 1. Extract input zip\n","# ────────────────────────────────────────────────\n","if not os.path.isfile(input_zip_path):\n"," print(f\"❌ File not found: {input_zip_path}\")\n","else:\n"," print(f\"Extracting {os.path.basename(input_zip_path)} …\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zf:\n"," zf.extractall(extract_dir)\n"," print(\"Extraction done.\\n\")\n","\n"," # ────────────────────────────────────────────────\n"," # 2. Collect all clean vertical strips (~256Γ—1024)\n"," # ────────────────────────────────────────────────\n"," all_strips = []\n"," valid_exts = ('.jpg', '.jpeg', '.png')\n","\n"," print(\"Extracting vertical strips from frames…\")\n"," frame_files = [f for f in os.listdir(extract_dir)\n"," if f.lower().endswith(valid_exts) and not f.startswith('._')]\n","\n"," for fname in tqdm(frame_files):\n"," try:\n"," img = Image.open(os.path.join(extract_dir, fname)).convert('RGB')\n"," w, h = img.size\n"," if w != 1024 or h != 1024:\n"," continue\n","\n"," inner_w = 1024 - 2 * border_px\n"," strip_w = inner_w // 4\n","\n"," for i in range(4):\n"," left = border_px + i * strip_w\n"," strip = img.crop((left, border_px, left + strip_w, 1024 - border_px))\n"," all_strips.append(strip)\n","\n"," del img\n"," gc.collect()\n","\n"," except:\n"," pass\n","\n"," print(f\"\\nCollected {len(all_strips):,} vertical strips.\\n\")\n","\n"," if len(all_strips) < 2:\n"," print(\"❌ Too few strips to create compositions.\")\n"," else:\n"," # ────────────────────────────────────────────────\n"," # 3. Prepare allowed column counts\n"," # ────────────────────────────────────────────────\n"," possible_cols = []\n"," if allow_1_column: possible_cols.append(1)\n"," if allow_2_columns: possible_cols.append(2)\n"," if allow_3_columns: possible_cols.append(3)\n"," if allow_4_columns: possible_cols.append(4)\n"," if allow_5_columns: possible_cols.append(5)\n","\n"," if not possible_cols:\n"," print(\"❌ Please enable at least one column count.\")\n"," else:\n"," print(f\"Allowed column counts: {possible_cols}\\n\")\n","\n"," # ────────────────────────────────────────────────\n"," # 4. Generate new variable-width frames\n"," # ────────────────────────────────────────────────\n"," base_strip_w = all_strips[0].width # usually ~256\n"," target_h = 1024 if keep_original_height else None\n","\n"," print(f\"Generating {num_new_frames} new frames…\")\n","\n"," for i in tqdm(range(num_new_frames)):\n"," num_cols = random.choice(possible_cols)\n"," chosen_strips = random.choices(all_strips, k=num_cols)\n","\n"," # Optional light variation\n"," if random.random() < 0.18:\n"," chosen_strips = [s.transpose(Image.FLIP_LEFT_RIGHT) if random.random() < 0.5 else s\n"," for s in chosen_strips]\n","\n"," canvas_w = num_cols * base_strip_w\n"," canvas_h = target_h if target_h else max(s.height for s in chosen_strips)\n","\n"," canvas = Image.new('RGB', (canvas_w, canvas_h), (0,0,0))\n","\n"," for col, strip in enumerate(chosen_strips):\n"," paste_img = strip\n"," if target_h and strip.height != target_h:\n"," paste_img = strip.resize((base_strip_w, target_h), Image.LANCZOS)\n","\n"," paste_y = (canvas_h - paste_img.height) // 2\n"," canvas.paste(paste_img, (col * base_strip_w, paste_y))\n","\n"," # Add border if requested\n"," if add_border:\n"," bordered = Image.new('RGB', (canvas_w + 2*border_px, canvas_h + 2*border_px), border_color)\n"," bordered.paste(canvas, (border_px, border_px))\n"," final = bordered\n"," else:\n"," final = canvas\n","\n"," # Save\n"," fname = f\"recomp_{i+1:05d}_cols{num_cols}.jpg\"\n"," final.save(os.path.join(local_output_dir, fname), \"JPEG\", quality=save_quality)\n","\n"," if (i+1) % 300 == 0:\n"," gc.collect()\n","\n"," print(f\"\\nCreated {num_new_frames} frames in {local_output_dir}\")\n","\n"," # ────────────────────────────────────────────────\n"," # 5. Zip and copy to Drive\n"," # ────────────��───────────────────────────────────\n"," zip_name = f\"recomposed_{len(possible_cols)}options.zip\"\n"," local_zip = f\"/content/{zip_name}\"\n"," drive_zip = os.path.join(output_dir_drive, zip_name)\n","\n"," print(\"\\nCreating zip (flat structure)…\")\n"," with zipfile.ZipFile(local_zip, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n"," for fname in os.listdir(local_output_dir):\n"," if fname.endswith(('.jpg','.jpeg','.png')):\n"," zf.write(os.path.join(local_output_dir, fname), arcname=fname)\n","\n"," print(\"Copying to Google Drive…\")\n"," !cp -f \"{local_zip}\" \"{drive_zip}\"\n","\n"," print(f\"\\nSuccess! ZIP saved to:\")\n"," print(f\"β†’ {drive_zip}\")\n","\n"," # Optional: clean up local files (uncomment if needed)\n"," # !rm -rf \"{local_output_dir}\" \"{local_zip}\"\n"," print(\"\\nTemporary files kept in /content β€” delete manually if disk space is low.\")"]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776178739426},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776027716448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1773663661932},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773663290922},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773264797996},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773163850245},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/civit_caption_prepper.ipynb","timestamp":1773090196076},{"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}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}