codeShare commited on
Commit
4ea37ad
Β·
verified Β·
1 Parent(s): 49d6e1b

Upload klein_prepare_lora_set.ipynb

Browse files
Files changed (1) hide show
  1. klein_prepare_lora_set.ipynb +1 -1
klein_prepare_lora_set.ipynb CHANGED
@@ -1 +1 @@
1
- {"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"r6q_m-6Pmm5w"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Set path to zip file on your drive , and set klein edit prompt\n","input_zip_path = '/content/drive/MyDrive/my_images.zip' #@param {type:'string'}\n","zip_path = input_zip_path\n","edit_prompt = 'remove the background. the background us dark gray. make sure the bare skin against the gray background looks like a real photo. ' #@param }Β₯{type:'string'}"],"metadata":{"id":"K13pRro0lxAw","cellView":"form","executionInfo":{"status":"ok","timestamp":1776774125767,"user_tz":-120,"elapsed":6,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":2,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# βš™οΈ Run Klein Edit (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"πŸ”„ Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"βœ… Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = True #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"βœ… Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}Γ—{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"WdNfo33NXNEa"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 3**: Load QUANTIZED Flux2KleinPipeline + SDNQ optimizations\n","#(model stays in memory)\n","# =============================================================================\n","\n","import torch\n","import gc\n","from diffusers import Flux2KleinPipeline\n","import zipfile\n","import glob\n","import os\n","\n","print(\"πŸ“¦ Installing sdnq...\")\n","!pip install -q sdnq\n","\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"πŸ”„ Loading QUANTIZED Flux2KleinPipeline (4-bit SDNQ + float16 for T4)...\")\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," \"Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic\",\n"," torch_dtype=torch.float16\n",")\n","\n","print(f\"βœ… Pipeline loaded – VRAM: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# ====================== Optimizations for T4 ======================\n","print(\"πŸ”₯ Applying SDNQ + T4 optimizations...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if triton_is_available and torch.cuda.is_available():\n"," pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\n"," pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\n"," print(\" βœ… INT8 MatMul enabled\")\n","\n","pipe.enable_model_cpu_offload()\n","pipe.vae.enable_slicing()\n","pipe.vae.enable_tiling()\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(\"βœ… Cell 3 complete – model is ready!\")\n","print(\" Now go to Cell 4 and run it (you can change zip/prompt in Cell 4 and re-run Cell 4 only)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"q9I9wxghuUGP","cellView":"form"},"outputs":[],"source":["import shutil\n","import datetime\n","import os\n","import glob\n","import zipfile\n","import gc\n","import torch\n","from PIL import Image\n","from google.colab import files\n","\n","# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein + custom/gray reference)\n","# β€’ Uses the **same zip** as Cell 4 but now does true multi-image editing\n","# β€’ First image = your original (the one being edited)\n","# β€’ Second image = your custom uploaded image OR a solid #181818 gray square (perfect for background replacement)\n","# β€’ Re-run this cell only with new values\n","# β€’ Auto-clears old data β†’ processes β†’ saves **only ZIP** to Drive\n","# =============================================================================\n","\n","#edit_prompt = 'remove the background. the background is gray. ' #@param {type:\"string\"}\n","#zip_path = '/content/drive/MyDrive/input_images.zip' #@param {type:\"string\"}\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","\n","output_folder = '/content/edited_images_multi' # ← separate temp folder so it doesn't clash with Cell 4\n","\n","print(\"🧹 Clearing old temporary folders so you can reuse with new zip/prompt...\")\n","if os.path.exists('/content/input_images'):\n"," shutil.rmtree('/content/input_images')\n","if os.path.exists(output_folder):\n"," shutil.rmtree(output_folder)\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# ====================== Unzip + build prompt map ======================\n","print(f\"πŸ“¦ Unzipping: {zip_path}...\")\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall('/content/input_images')\n","\n","image_files = sorted(glob.glob('/content/input_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]\n","print(f\"Found {len(image_files)} images.\")\n","\n","prompt_map = {}\n","txt_count = 0\n","for img_path in image_files:\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," txt_path = os.path.join('/content/input_images', f\"{base}.txt\")\n"," if use_txt_prompts and os.path.exists(txt_path):\n"," with open(txt_path, 'r', encoding='utf-8') as f:\n"," prompt_map[img_path] = f.read().strip()\n"," txt_count += 1\n"," else:\n"," prompt_map[img_path] = None\n","\n","print(f\"Found {txt_count} matching .txt files\")\n","\n","# ====================== Create or load the second reference image (once) ======================\n","uploaded_reference_filepath = None\n","reference_image_to_pair = None # Initialize to None\n","\n","if upload_custom_reference: # Only attempt to get a reference if the checkbox is enabled\n"," print(\"Please upload your reference image now.\")\n"," uploaded_files = files.upload()\n","\n"," if uploaded_files:\n"," uploaded_reference_filepath = list(uploaded_files.keys())[0]\n"," print(f\"βœ… Uploaded reference image: {uploaded_reference_filepath}\")\n"," # Save the uploaded file to a temporary location to be opened by PIL\n"," with open(uploaded_reference_filepath, 'wb') as f:\n"," f.write(uploaded_files[uploaded_reference_filepath])\n","\n"," if uploaded_reference_filepath: # Check if a file was actually uploaded\n"," print(\"πŸ“ Using uploaded reference image...\")\n"," try:\n"," # Open the temporary file\n"," reference_image_to_pair = Image.open(uploaded_reference_filepath).convert(\"RGB\")\n"," #if reference_image_to_pair.size != (target_width, target_height):\n"," # print(f\" ⚠️ Resizing uploaded reference image from {reference_image_to_pair.size} to {target_width}x{target_height}\")\n"," # reference_image_to_pair = reference_image_to_pair.resize((target_width, target_height), Image.LANCZOS)\n"," except Exception as e:\n"," print(f\" ❌ Error loading uploaded image: {e}. Falling back to gray reference.\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n"," else: # If upload_custom_reference is True but no file was uploaded\n"," print(f\"🟩 No custom reference image uploaded. Creating {target_width}x{target_height} #181818 solid gray reference image...\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","else:\n"," print(\"🚫 Custom reference image upload disabled. Will process images without a second reference.\")\n"," # reference_image_to_pair remains None, which is the desired behavior for the pipe call.\n","\n","# Clean up the temporarily saved file if it was uploaded\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\n","\n","# ====================== FULL BATCH MULTI-IMAGE INFERENCE ======================\n","print(f\"\\nπŸš€ Starting batch MULTI-IMAGE edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # Resize input_image if its largest dimension exceeds max_image_dimension\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," print(f\" ⚠️ Resizing {filename} from {input_image.size} to max dimension {max_image_dimension}...\")\n"," aspect_ratio = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," new_width = max_image_dimension\n"," new_height = int(max_image_dimension / aspect_ratio)\n"," else:\n"," new_height = max_image_dimension\n"," new_width = int(max_image_dimension * aspect_ratio)\n"," input_image = input_image.resize((new_width, new_height), Image.LANCZOS)\n","\n"," # === MULTI-IMAGE LIST: base image first, the chosen reference second ===\n"," if reference_image_to_pair is not None:\n"," reference_images = [input_image, reference_image_to_pair]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ + custom reference\")\n"," else:\n"," reference_images = [input_image]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ (no custom reference)\")\n","\n"," current_prompt = prompt_map[img_path] if use_txt_prompts and prompt_map[img_path] is not None else edit_prompt\n","\n"," result = pipe(\n"," prompt=current_prompt,\n"," image=reference_images, # ← KEY: list of images for Klein multi-reference\n"," height=target_height,\n"," width=target_width,\n"," guidance_scale=1.0,\n"," num_inference_steps=4,\n"," generator=torch.Generator(\"cuda\").manual_seed(42),\n"," output_type=\"pil\",\n"," ).images[0]\n","\n"," output_filename = f\"multi_edited_{filename}\"\n"," output_path = os.path.join(output_folder, output_filename)\n"," result.save(output_path)\n","\n"," if debug:\n"," print(f\" β†’ Saved {output_filename} (multi-ref with custom/gray image)\") # Updated message\n","\n","print(\"\\nβ†’ MULTI-IMAGE BATCH COMPLETE!\")\n","\n","# ====================== AUTO ZIP TO DRIVE (unique name) ======================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip_path = f\"/content/drive/MyDrive/klein_processed_{timestamp}.zip\"\n","\n","print(f\"πŸ“¦ Creating zip β†’ {drive_zip_path}\")\n","shutil.make_archive(drive_zip_path.replace('.zip', ''), 'zip', output_folder)\n","\n","print(\"βœ… ALL DONE!\")\n","print(f\"Zip file saved to your Google Drive:\")\n","print(drive_zip_path)"]},{"cell_type":"markdown","source":["# Select klein edited zip file to process next\n","Results from earlier cell have been saved to your drive as <br> 'content/drive/MyDrive/klein_processed_(date_number).zip'\n","\n","You can disconnect from the session , and reconnect to new runtime to prevent conflict in installed libraries. you can run this code on CPU"],"metadata":{"id":"F5NDcZ6rZw6Q"}},{"cell_type":"code","source":["klein_edited_zip_path = '/content/drive/MyDrive/klein_processed_20260421_123232.zip' #@param {type:'string'}\n","zip_path = klein_edited_zip_path"],"metadata":{"cellView":"form","id":"OdcEXFs4oBt_","executionInfo":{"status":"ok","timestamp":1776774896114,"user_tz":-120,"elapsed":7,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":1,"outputs":[]},{"cell_type":"markdown","source":["# βš™οΈ Create 1024x1024 frames from selected klein edited set"],"metadata":{"id":"4PjK9a8Sni3A"}},{"cell_type":"code","source":["#@title πŸ–ΌοΈ **Image Background Processor**\n","#(v2 - Solid #181818 Flood-Fill + Auto-Clear)\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#@markdown ---\n","#**New**: Automatically clears all previous processed images on re-run\n","#(no more mixing old files when you run again)\n","\n","#Run this cell (Shift + Enter)\n","#Fill the form below\n","#Click **Run**\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","#input_zip_path = \"/content/drive/MyDrive/klein_processed.zip\" #@param {type:\"string\", placeholder:\"Paste full path to your ZIP file here\"}\n","input_zip_path = zip_path\n","\n","tolerance_crop = 30 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🟦 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 20 #@param {type:\"slider\", min:10, max:100, step:1}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"πŸ”„ Force remount Drive (recommended)\"}\n","\n","#@markdown ---\n","\n","from google.colab import drive\n","import zipfile\n","import os\n","import shutil # ← NEW for clearing folders\n","from PIL import Image\n","from collections import deque\n","\n","# ========================= CONFIG =========================\n","TARGET_GRAY = (24, 24, 24) # Exact #181818 - do not change\n","# =======================================================\n","\n","print(\"πŸš€ Starting image processor (Solid Background v2 + Auto-Clear)...\")\n","\n","# 1. Mount Google Drive\n","drive.mount('/content/drive', force_remount=force_remount)\n","\n","# 2. Validate ZIP path\n","if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path (e.g. /content/drive/MyDrive/my_photos.zip)\")\n","\n","print(f\"βœ… ZIP found: {input_zip_path}\")\n","\n","# 3. Define working folders\n","extract_dir = '/content/extracted_images'\n","processed_dir = '/content/processed_images'\n","\n","# === NEW: Clear previous processed & extracted images on every run ===\n","for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"🧹 Cleared old folder: {directory}\")\n","os.makedirs(extract_dir, exist_ok=True)\n","os.makedirs(processed_dir, exist_ok=True)\n","print(\"βœ… Fresh folders ready\")\n","\n","# 4. Unzip\n","print(\"πŸ“¦ Unzipping...\")\n","with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","print(f\"βœ… Unzipped to {extract_dir}\")\n","\n","# ==================== HELPER 1: Crop only left & right ====================\n","def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n","\n"," left = width\n"," right = 0\n","\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n","\n"," if left >= right:\n"," return img\n","\n"," return img.crop((left, 0, right + 1, height))\n","\n","# ==================== HELPER 2: FLOOD-FILL BACKGROUND FROM EDGES ====================\n","def adjust_background(img, original_bg_color):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels = img.load()\n"," threshold = bg_replace_threshold\n","\n"," visited = set()\n"," queue = deque()\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # Seed from borders\n"," for x in range(width):\n"," for y in (0, height - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," for y in range(height):\n"," for x in (0, width - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," # Flood fill\n"," while queue:\n"," x, y = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and (nx, ny) not in visited:\n"," px = pixels[nx, ny]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," visited.add((nx, ny))\n"," pixels[nx, ny] = TARGET_GRAY\n"," queue.append((nx, ny))\n","\n"," return img\n","\n","# 5. Process every image\n","print(\"πŸ–ΌοΈ Processing images...\")\n","image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n","processed_count = 0\n","for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," cropped = crop_left_right(original_img)\n"," orig_bg = original_img.getpixel((0, 0))\n"," processed = adjust_background(cropped, orig_bg)\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" βœ… {filename}\")\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n","print(f\"\\nπŸŽ‰ Processed {processed_count} images!\")\n","\n","# 6. Create final ZIP in Drive\n","output_zip_name = \"PROCESSED_\" + os.path.basename(zip_path)\n","output_zip_path = os.path.join(os.path.dirname(zip_path), output_zip_name)\n","zip_path = output_zip_path\n","\n","print(f\"πŸ“¦ Creating final ZIP: {output_zip_name}\")\n","with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n","print(\"\\nβœ… ALL DONE! Solid #181818 background achieved.\")\n","print(f\"πŸ“ Saved to your Drive at:\\n {output_zip_path}\")"],"metadata":{"id":"HN4kta-OpZ4W","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"93JpoQJ77NGu","cellView":"form"},"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 = 0 #@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","#input_zip_path = \"/content/drive/MyDrive/PROCESSED_klein_processed.zip\" #@param {type:\"string\"}\n","zip_file_path = zip_path\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":["# Done!\n","\n","In the zip file /content/drive/MyDrive/vertical_slices_output/vertical_slices.zip , there you will find 500 image composites to choose for lora training"],"metadata":{"id":"tJlvhf9xDmA7"}}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776773678064},{"file_id":"151XI3nRFxLRbwRc8V6OfWyqp-zTnfySv","timestamp":1776764241991},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_edit.ipynb","timestamp":1776702729526},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776687886662},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776366149549},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776287741995},{"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}],"collapsed_sections":["HX3I-YqowwO9","4PjK9a8Sni3A"]},"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":"r6q_m-6Pmm5w"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Set path to zip file on your drive , and set klein edit prompt\n","input_zip_path = '/content/drive/MyDrive/my_images.zip' #@param {type:'string'}\n","zip_path = input_zip_path\n","edit_prompt = 'remove the background. the background us dark gray. make sure the bare skin against the gray background looks like a real photo. ' #@param }Β₯{type:'string'}"],"metadata":{"id":"K13pRro0lxAw","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"HX3I-YqowwO9"},"source":["# βš™οΈ Run Klein Edit (GPU)"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"OXGhsHQwWue_"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 1**: Mount Drive + HF auth\n","# =============================================================================\n","\n","from google.colab import drive, userdata\n","from huggingface_hub import login\n","import torch\n","import os\n","import gc\n","import shutil\n","\n","drive.mount('/content/drive')\n","\n","hf_token = userdata.get('HF_TOKEN')\n","if hf_token:\n"," login(token=hf_token)\n","else:\n"," print(\"⚠️ No HF_TOKEN found in secrets.\")\n","\n","print(\"🧹 Removing old diffusers...\")\n","!pip uninstall -y diffusers > /dev/null 2>&1\n","!rm -rf /usr/local/lib/python3.12/dist-packages/diffusers* ~/.cache/pip/*diffusers*\n","\n","print(\"πŸ”„ Installing latest diffusers...\")\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","\n","print(\"βœ… Cell 1 complete!\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"a1wZv8PrXAe2"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 2**: Fixed settings (resolution + options)\n","# =============================================================================\n","\n","resolution = '1024 x 1024 (Square)' #@param [\"1024 x 1024 (Square)\", \"512 x 1024 (Portrait)\", \"768 x 1024 (Slight Portrait)\", \"1536 x 1024 (Landscape)\", \"2048 x 1024 (Wide Landscape)\"] {type:\"string\"}\n","use_txt_prompts = True #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","res_map = {\n"," \"1024 x 1024 (Square)\": (1024, 1024),\n"," \"512 x 1024 (Portrait)\": (512, 1024),\n"," \"768 x 1024 (Slight Portrait)\": (768, 1024),\n"," \"1536 x 1024 (Landscape)\": (1536, 1024),\n"," \"2048 x 1024 (Wide Landscape)\": (2048, 1024)\n","}\n","target_width, target_height = res_map[resolution]\n","\n","print(\"βœ… Cell 2 settings loaded\")\n","print(f\" Resolution: {target_width}Γ—{target_height}\")\n","print(f\" Use .txt prompts: {use_txt_prompts}\")\n","print(f\" Debug mode: {debug}\")\n","print(\"\\nNow run Cell 3 (model load), then Cell 4 (inference)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"WdNfo33NXNEa"},"outputs":[],"source":["# =============================================================================\n","#@markdown # **CELL 3**: Load QUANTIZED Flux2KleinPipeline + SDNQ optimizations\n","#(model stays in memory)\n","# =============================================================================\n","\n","import torch\n","import gc\n","from diffusers import Flux2KleinPipeline\n","import zipfile\n","import glob\n","import os\n","\n","print(\"πŸ“¦ Installing sdnq...\")\n","!pip install -q sdnq\n","\n","from sdnq.common import use_torch_compile as triton_is_available\n","from sdnq.loader import apply_sdnq_options_to_model\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","\n","print(\"πŸ”„ Loading QUANTIZED Flux2KleinPipeline (4-bit SDNQ + float16 for T4)...\")\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," \"Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic\",\n"," torch_dtype=torch.float16\n",")\n","\n","print(f\"βœ… Pipeline loaded – VRAM: {torch.cuda.memory_allocated() / 1e9:.2f} GB\")\n","\n","# ====================== Optimizations for T4 ======================\n","print(\"πŸ”₯ Applying SDNQ + T4 optimizations...\")\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if triton_is_available and torch.cuda.is_available():\n"," pipe.transformer = apply_sdnq_options_to_model(pipe.transformer, use_quantized_matmul=True)\n"," pipe.text_encoder = apply_sdnq_options_to_model(pipe.text_encoder, use_quantized_matmul=True)\n"," print(\" βœ… INT8 MatMul enabled\")\n","\n","pipe.enable_model_cpu_offload()\n","pipe.vae.enable_slicing()\n","pipe.vae.enable_tiling()\n","\n","gc.collect()\n","torch.cuda.empty_cache()\n","torch.cuda.reset_peak_memory_stats()\n","\n","print(\"βœ… Cell 3 complete – model is ready!\")\n","print(\" Now go to Cell 4 and run it (you can change zip/prompt in Cell 4 and re-run Cell 4 only)\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"q9I9wxghuUGP","cellView":"form"},"outputs":[],"source":["import shutil\n","import datetime\n","import os\n","import glob\n","import zipfile\n","import gc\n","import torch\n","from PIL import Image\n","from google.colab import files\n","\n","# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Klein + custom/gray reference)\n","# β€’ Uses the **same zip** as Cell 4 but now does true multi-image editing\n","# β€’ First image = your original (the one being edited)\n","# β€’ Second image = your custom uploaded image OR a solid #181818 gray square (perfect for background replacement)\n","# β€’ Re-run this cell only with new values\n","# β€’ Auto-clears old data β†’ processes β†’ saves **only ZIP** to Drive\n","# =============================================================================\n","\n","#edit_prompt = 'remove the background. the background is gray. ' #@param {type:\"string\"}\n","#zip_path = '/content/drive/MyDrive/input_images.zip' #@param {type:\"string\"}\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","\n","output_folder = '/content/edited_images_multi' # ← separate temp folder so it doesn't clash with Cell 4\n","\n","print(\"🧹 Clearing old temporary folders so you can reuse with new zip/prompt...\")\n","if os.path.exists('/content/input_images'):\n"," shutil.rmtree('/content/input_images')\n","if os.path.exists(output_folder):\n"," shutil.rmtree(output_folder)\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# ====================== Unzip + build prompt map ======================\n","print(f\"πŸ“¦ Unzipping: {zip_path}...\")\n","with zipfile.ZipFile(zip_path, 'r') as z:\n"," z.extractall('/content/input_images')\n","\n","image_files = sorted(glob.glob('/content/input_images/*.*'))\n","image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]\n","print(f\"Found {len(image_files)} images.\")\n","\n","prompt_map = {}\n","txt_count = 0\n","for img_path in image_files:\n"," base = os.path.splitext(os.path.basename(img_path))[0]\n"," txt_path = os.path.join('/content/input_images', f\"{base}.txt\")\n"," if use_txt_prompts and os.path.exists(txt_path):\n"," with open(txt_path, 'r', encoding='utf-8') as f:\n"," prompt_map[img_path] = f.read().strip()\n"," txt_count += 1\n"," else:\n"," prompt_map[img_path] = None\n","\n","print(f\"Found {txt_count} matching .txt files\")\n","\n","# ====================== Create or load the second reference image (once) ======================\n","uploaded_reference_filepath = None\n","reference_image_to_pair = None # Initialize to None\n","\n","if upload_custom_reference: # Only attempt to get a reference if the checkbox is enabled\n"," print(\"Please upload your reference image now.\")\n"," uploaded_files = files.upload()\n","\n"," if uploaded_files:\n"," uploaded_reference_filepath = list(uploaded_files.keys())[0]\n"," print(f\"βœ… Uploaded reference image: {uploaded_reference_filepath}\")\n"," # Save the uploaded file to a temporary location to be opened by PIL\n"," with open(uploaded_reference_filepath, 'wb') as f:\n"," f.write(uploaded_files[uploaded_reference_filepath])\n","\n"," if uploaded_reference_filepath: # Check if a file was actually uploaded\n"," print(\"πŸ“ Using uploaded reference image...\")\n"," try:\n"," # Open the temporary file\n"," reference_image_to_pair = Image.open(uploaded_reference_filepath).convert(\"RGB\")\n"," #if reference_image_to_pair.size != (target_width, target_height):\n"," # print(f\" ⚠️ Resizing uploaded reference image from {reference_image_to_pair.size} to {target_width}x{target_height}\")\n"," # reference_image_to_pair = reference_image_to_pair.resize((target_width, target_height), Image.LANCZOS)\n"," except Exception as e:\n"," print(f\" ❌ Error loading uploaded image: {e}. Falling back to gray reference.\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n"," else: # If upload_custom_reference is True but no file was uploaded\n"," print(f\"🟩 No custom reference image uploaded. Creating {target_width}x{target_height} #181818 solid gray reference image...\")\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","else:\n"," print(\"🚫 Custom reference image upload disabled. Will process images without a second reference.\")\n"," # reference_image_to_pair remains None, which is the desired behavior for the pipe call.\n","\n","# Clean up the temporarily saved file if it was uploaded\n","if uploaded_reference_filepath and os.path.exists(uploaded_reference_filepath):\n"," os.remove(uploaded_reference_filepath)\n","\n","\n","# ====================== FULL BATCH MULTI-IMAGE INFERENCE ======================\n","print(f\"\\nπŸš€ Starting batch MULTI-IMAGE edit on {len(image_files)} images...\")\n","\n","for i, img_path in enumerate(image_files):\n"," filename = os.path.basename(img_path)\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," input_image = Image.open(img_path).convert(\"RGB\")\n","\n"," # Resize input_image if its largest dimension exceeds max_image_dimension\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," print(f\" ⚠️ Resizing {filename} from {input_image.size} to max dimension {max_image_dimension}...\")\n"," aspect_ratio = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," new_width = max_image_dimension\n"," new_height = int(max_image_dimension / aspect_ratio)\n"," else:\n"," new_height = max_image_dimension\n"," new_width = int(max_image_dimension * aspect_ratio)\n"," input_image = input_image.resize((new_width, new_height), Image.LANCZOS)\n","\n"," # === MULTI-IMAGE LIST: base image first, the chosen reference second ===\n"," if reference_image_to_pair is not None:\n"," reference_images = [input_image, reference_image_to_pair]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ + custom reference\")\n"," else:\n"," reference_images = [input_image]\n"," print(f\"[{i+1}/{len(image_files)}] {filename} β†’ (no custom reference)\")\n","\n"," current_prompt = prompt_map[img_path] if use_txt_prompts and prompt_map[img_path] is not None else edit_prompt\n","\n"," result = pipe(\n"," prompt=current_prompt,\n"," image=reference_images, # ← KEY: list of images for Klein multi-reference\n"," height=target_height,\n"," width=target_width,\n"," guidance_scale=1.0,\n"," num_inference_steps=4,\n"," generator=torch.Generator(\"cuda\").manual_seed(42),\n"," output_type=\"pil\",\n"," ).images[0]\n","\n"," output_filename = f\"multi_edited_{filename}\"\n"," output_path = os.path.join(output_folder, output_filename)\n"," result.save(output_path)\n","\n"," if debug:\n"," print(f\" β†’ Saved {output_filename} (multi-ref with custom/gray image)\") # Updated message\n","\n","print(\"\\nβ†’ MULTI-IMAGE BATCH COMPLETE!\")\n","\n","# ====================== AUTO ZIP TO DRIVE (unique name) ======================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","drive_zip_path = f\"/content/drive/MyDrive/klein_processed_{timestamp}.zip\"\n","\n","print(f\"πŸ“¦ Creating zip β†’ {drive_zip_path}\")\n","shutil.make_archive(drive_zip_path.replace('.zip', ''), 'zip', output_folder)\n","\n","print(\"βœ… ALL DONE!\")\n","print(f\"Zip file saved to your Google Drive:\")\n","print(drive_zip_path)"]},{"cell_type":"markdown","source":["# Select klein edited zip file to process next\n","Results from earlier cell have been saved to your drive as <br> 'content/drive/MyDrive/klein_processed_(date_number).zip'\n","\n","You can disconnect from the session , and reconnect to new runtime to prevent conflict in installed libraries. you can run this code on CPU"],"metadata":{"id":"F5NDcZ6rZw6Q"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"OdcEXFs4oBt_","cellView":"form"},"outputs":[],"source":["import os\n","\n","klein_edited_zip_path = '/content/drive/MyDrive/klein_processed_20260421_123232.zip' #@param {type:'string'}\n","zip_path = klein_edited_zip_path\n","\n","if not os.path.exists(zip_path):\n"," raise FileNotFoundError(f\"❌ Klein edited zip file not found:\\n{zip_path}\\n\\nPlease ensure the path is correct and the file exists in your Drive.\")"]},{"cell_type":"markdown","source":["# βš™οΈ Create 1024x1024 frames from selected klein edited set"],"metadata":{"id":"4PjK9a8Sni3A"}},{"cell_type":"code","source":["#@title πŸ–ΌοΈ **Image Background Processor (v1)**\n","#@markdown ---\n","#@markdown ## Enable Processor V1\n","enable_processor_v1 = False #@param {type:\"boolean\"}\n","\n","#@title πŸ–ΌοΈ **Image Background Processor**\n","#(v2 - Solid #181818 Flood-Fill + Auto-Clear)\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#@markdown ---\n","#**New**: Automatically clears all previous processed images on re-run\n","#(no more mixing old files when you run again)\n","\n","#Run this cell (Shift + Enter)\n","#Fill the form below\n","#Click **Run**\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","#input_zip_path = \"/content/drive/MyDrive/klein_processed.zip\" #@param {type:\"string\", placeholder:\"Paste full path to your ZIP file here\"}\n","input_zip_path = zip_path\n","\n","tolerance_crop = 30 #@param {type:\"slider\", min:0, max:100, step:1, title:\"🟦 Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 20 #@param {type:\"slider\", min:10, max:100, step:1}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"πŸ”„ Force remount Drive (recommended)\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v1:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil # ← NEW for clearing folders\n"," from PIL import Image\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818 - do not change\n"," # =======================================================\n","\n"," print(\"πŸš€ Starting image processor (Solid Background v2 + Auto-Clear)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path (e.g. /content/drive/MyDrive/my_photos.zip)\")\n","\n"," print(f\"βœ… ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # === NEW: Clear previous processed & extracted images on every run ===\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"🧹 Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"βœ… Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"πŸ“¦ Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"βœ… Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n","\n"," left = width\n"," right = 0\n","\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n","\n"," if left >= right:\n"," return img\n","\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FLOOD-FILL BACKGROUND FROM EDGES ====================\n"," def adjust_background(img, original_bg_color):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels = img.load()\n"," threshold = bg_replace_threshold\n","\n"," visited = set()\n"," queue = deque()\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # Seed from borders\n"," for x in range(width):\n"," for y in (0, height - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," for y in range(height):\n"," for x in (0, width - 1):\n"," if (x, y) not in visited:\n"," px = pixels[x, y]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," queue.append((x, y))\n"," visited.add((x, y))\n"," pixels[x, y] = TARGET_GRAY\n","\n"," # Flood fill\n"," while queue:\n"," x, y = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and (nx, ny) not in visited:\n"," px = pixels[nx, ny]\n"," dist = ((px[0] - original_bg_color[0])**2 + (px[1] - original_bg_color[1])**2 + (px[2] - original_bg_color[2])**2) ** 0.5\n"," if dist <= threshold:\n"," visited.add((nx, ny))\n"," pixels[nx, ny] = TARGET_GRAY\n"," queue.append((nx, ny))\n","\n"," return img\n","\n"," # 5. Process every image\n"," print(\"πŸ–ΌοΈ Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," cropped = crop_left_right(original_img)\n"," orig_bg = original_img.getpixel((0, 0))\n"," processed = adjust_background(cropped, orig_bg)\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" βœ… {filename}\")\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\nπŸŽ‰ Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP in Drive\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(zip_path), output_zip_name)\n"," zip_path = output_zip_path\n","\n"," print(f\"πŸ“¦ Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\nβœ… ALL DONE! Solid #181818 background achieved.\")\n"," print(f\"πŸ“ Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"id":"HN4kta-OpZ4W","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title **πŸ–ΌοΈ Image Background Processor V2 (WIP)**\n","#@markdown ---\n","#@markdown ## Enable Processor V2\n","enable_processor_v2 = True #@param {type:\"boolean\"}\n","\n","#@title **πŸ–ΌοΈ Image Background Processor V2 (WIP)**\n","#(v2.7 - **Inverse speck removal** + Border-protected forward speck + % Margin + Solid #181818)\n","\n","#**Crop left/right empty space + Convert *any* gray background to exact #181818**\n","#**New in v2.7**:\n","# β€’ **Inverse speck removal**: finds tiny foreground (subject-colored) specks/islands inside the background and replaces them with solid #181818\n","# β€’ Forward speck removal (previous) still protects any #181818 connected to the outer image edge\n","# β€’ Anti-aliasing is guaranteed to be the **very last step** (after both forward + inverse speck removal)\n","# β€’ All previous features (4-corner BG, % margin, checkboxes, distance-based enclosed speck removal) unchanged\n","\n","# ==================== FORM PARAMETERS ====================\n","\n","input_zip_path = zip_path\n","\n","tolerance_crop = 30 #@param {type:\"slider\", min:0, max:100, step:1, title:\"πŸ”΅ Crop Tolerance (higher = more aggressive cropping)\"}\n","\n","bg_replace_threshold = 10 #@param {type:\"slider\", min:10, max:100, step:1, title:\"🎨 Legacy absolute threshold (kept for compatibility)\"}\n","\n","# ── % Margin for BG color estimation ──\n","bg_margin_percent = 6 #@param {type:\"slider\", min:0, max:50, step:1, title:\"% Margin for BG color estimation (wider = more tolerant to inner-loop gray variations)\"}\n","\n","# ── Feature Checkboxes ──\n","enable_robust_bg_detection = True #@param {type:\"boolean\", title:\"βœ… Use 4-corner robust BG color (best for inner loops)\"}\n","enable_floodfill_background_adjustment = True #@param {type:\"boolean\", title:\"βœ… Enable solid #181818 background replacement\"}\n","enable_small_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"βœ… Forward speck removal: remove tiny #181818 specks on subject\"}\n","enable_inverse_speck_removal = True #@param {type:\"boolean\"}\n","#title:\"βœ… Inverse speck removal: fill tiny subject specks inside background with #181818\"}\n","enable_anti_aliasing = True #@param {type:\"boolean\", title:\"βœ… Smooth edges (Gaussian anti-aliasing)\"}\n","\n","anti_aliasing_strength = 6 #@param {type:\"slider\", min:1, max:40, step:1, title:\" ↳ Anti-aliasing Strength (pixels to blend)\"}\n","\n","# ── Forward speck removal (enclosed only) ──\n","min_floodfill_steps = 8 #@param {type:\"slider\", min:1, max:20, step:1, title:\" ↳ Min floodfill steps to foreground (N) for ENCLOSED BG only (outer-edge-connected BG always protected)\"}\n","\n","# ── Inverse speck removal ──\n","max_inverse_speck_size = 10 #@param {type:\"slider\", min:1, max:100, step:1, title:\" ↳ Max size of foreground specks to fill with #181818\"}\n","\n","force_remount = False #@param {type:\"boolean\", title:\"πŸ”„ Force remount Drive\"}\n","\n","#@markdown ---\n","\n","\n","if enable_processor_v2:\n"," from google.colab import drive\n"," import zipfile\n"," import os\n"," import shutil\n"," from PIL import Image, ImageFilter\n"," from collections import deque\n","\n"," # ========================= CONFIG =========================\n"," TARGET_GRAY = (24, 24, 24) # Exact #181818\n"," # =======================================================\n","\n"," print(\"πŸš€ Starting Image Background Processor v2.7 (Forward + Inverse speck removal)...\")\n","\n"," # 1. Mount Google Drive\n"," drive.mount('/content/drive', force_remount=force_remount)\n","\n"," # 2. Validate ZIP path\n"," if not input_zip_path or not os.path.exists(input_zip_path):\n"," raise FileNotFoundError(f\"❌ ZIP file not found:\\n{input_zip_path}\\n\\nPlease paste the correct full path\")\n","\n"," print(f\"βœ… ZIP found: {input_zip_path}\")\n","\n"," # 3. Define working folders\n"," extract_dir = '/content/extracted_images'\n"," processed_dir = '/content/processed_images'\n","\n"," # Clear previous runs\n"," for directory in [extract_dir, processed_dir]:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n"," print(f\"οΉ… Cleared old folder: {directory}\")\n"," os.makedirs(extract_dir, exist_ok=True)\n"," os.makedirs(processed_dir, exist_ok=True)\n"," print(\"βœ… Fresh folders ready\")\n","\n"," # 4. Unzip\n"," print(\"πŸš€ Unzipping...\")\n"," with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n"," print(f\"βœ… Unzipped to {extract_dir}\")\n","\n"," # ==================== HELPER 1: Crop only left & right ====================\n"," def crop_left_right(img):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n"," width, height = img.size\n"," bg_color = img.getpixel((0, 0))\n"," left = width\n"," right = 0\n"," for x in range(width):\n"," column_is_empty = True\n"," for y in range(height):\n"," px = img.getpixel((x, y))\n"," if any(abs(a - b) > tolerance_crop for a, b in zip(px, bg_color)):\n"," column_is_empty = False\n"," break\n"," if not column_is_empty:\n"," left = min(left, x)\n"," right = max(right, x)\n"," if left >= right:\n"," return img\n"," return img.crop((left, 0, right + 1, height))\n","\n"," # ==================== HELPER 2: FULL BACKGROUND PROCESSOR (v2.7) ====================\n"," def adjust_background(img, original_bg_color,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent):\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n"," pixels_access = img.load()\n"," target_gray = TARGET_GRAY\n"," directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if not (dx == 0 and dy == 0)]\n","\n"," # 1. Identify foreground using % margin\n"," per_channel_margin = int(255 * (bg_margin_percent / 100.0))\n"," is_foreground = [[False for _ in range(height)] for _ in range(width)]\n"," for y in range(height):\n"," for x in range(width):\n"," px = pixels_access[(x, y)]\n"," is_bg = all(abs(px[i] - original_bg_color[i]) <= per_channel_margin for i in range(3))\n"," if not is_bg:\n"," is_foreground[x][y] = True\n","\n"," # 2. Base image: solid #181818 + foreground\n"," base_processed_img = Image.new(\"RGB\", (width, height), target_gray)\n"," base_processed_pixels = base_processed_img.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," base_processed_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," # 3. Forward speck removal (border-protected, enclosed only)\n"," if enable_floodfill_background_adjustment and enable_small_speck_removal:\n"," print(\" πŸ” Running forward speck removal (border-protected)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n","\n"," # Mark border-connected #181818\n"," connected_to_border = [[False] * height for _ in range(width)]\n"," queue = deque()\n"," for x in range(width):\n"," for y_border in [0, height-1]:\n"," if refined_pixels[(x, y_border)] == target_gray and not connected_to_border[x][y_border]:\n"," connected_to_border[x][y_border] = True\n"," queue.append((x, y_border))\n"," for y in range(height):\n"," for x_border in [0, width-1]:\n"," if refined_pixels[(x_border, y)] == target_gray and not connected_to_border[x_border][y]:\n"," connected_to_border[x_border][y] = True\n"," queue.append((x_border, y))\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not connected_to_border[nx][ny] and refined_pixels[(nx, ny)] == target_gray:\n"," connected_to_border[nx][ny] = True\n"," queue.append((nx, ny))\n","\n"," # Distance to foreground (for enclosed BG only)\n"," distance = [[-1] * height for _ in range(width)]\n"," queue = deque()\n"," for y in range(height):\n"," for x in range(width):\n"," if is_foreground[x][y]:\n"," for dx, dy in directions:\n"," nx, ny = x + dx, y + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = 1\n"," queue.append((nx, ny))\n"," break\n"," while queue:\n"," cx, cy = queue.popleft()\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not is_foreground[nx][ny] and distance[nx][ny] == -1:\n"," distance[nx][ny] = distance[cx][cy] + 1\n"," queue.append((nx, ny))\n","\n"," # Revert only enclosed + too-close BG pixels\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] == target_gray:\n"," if not connected_to_border[x][y] and (distance[x][y] == -1 or distance[x][y] < min_floodfill_steps):\n"," refined_pixels[(x, y)] = pixels_access[(x, y)]\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 4. INVERSE speck removal (tiny foreground specks inside background β†’ #181818)\n"," if enable_floodfill_background_adjustment and enable_inverse_speck_removal:\n"," print(\" πŸ” Running inverse speck removal (small FG specks β†’ #181818)...\")\n"," refined_img = base_processed_img.copy()\n"," refined_pixels = refined_img.load()\n"," visited = [[False] * height for _ in range(width)]\n","\n"," for y in range(height):\n"," for x in range(width):\n"," if refined_pixels[(x, y)] != target_gray and not visited[x][y]:\n"," component = []\n"," queue = deque([(x, y)])\n"," visited[x][y] = True\n"," while queue:\n"," cx, cy = queue.popleft()\n"," component.append((cx, cy))\n"," for dx, dy in directions:\n"," nx, ny = cx + dx, cy + dy\n"," if 0 <= nx < width and 0 <= ny < height and not visited[nx][ny] and refined_pixels[(nx, ny)] != target_gray:\n"," visited[nx][ny] = True\n"," queue.append((nx, ny))\n"," # Fill small foreground specks with solid #181818\n"," if len(component) < max_inverse_speck_size:\n"," for px, py in component:\n"," refined_pixels[(px, py)] = target_gray\n","\n"," base_processed_img = refined_img\n"," base_processed_pixels = base_processed_img.load()\n","\n"," # 5. Anti-aliasing – ALWAYS LAST (as requested)\n"," if not enable_anti_aliasing:\n"," return base_processed_img\n","\n"," mask = Image.new(\"L\", (width, height), 0)\n"," mask_pixels = mask.load()\n"," for y in range(height):\n"," for x in range(width):\n"," if base_processed_pixels[(x, y)] != target_gray:\n"," mask_pixels[(x, y)] = 255\n","\n"," blur_radius = anti_aliasing_strength / 2.0\n"," blurred_mask = mask.filter(ImageFilter.GaussianBlur(radius=blur_radius))\n","\n"," solid_bg = Image.new(\"RGB\", (width, height), target_gray)\n"," final_img_with_aa = Image.composite(base_processed_img, solid_bg, blurred_mask)\n","\n"," return final_img_with_aa\n","\n"," # ==================== MAIN PROCESSING LOOP ====================\n"," print(\"πŸš€ Processing images...\")\n"," image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')\n","\n"," processed_count = 0\n"," for filename in os.listdir(extract_dir):\n"," if filename.lower().endswith(image_extensions):\n"," img_path = os.path.join(extract_dir, filename)\n"," try:\n"," with Image.open(img_path) as original_img:\n"," # === ROBUST BACKGROUND COLOR DETECTION ===\n"," cropped = crop_left_right(original_img)\n"," if cropped.mode != 'RGB':\n"," cropped = cropped.convert('RGB')\n","\n"," if enable_robust_bg_detection:\n"," w, h = cropped.size\n"," samples = [\n"," cropped.getpixel((0, 0)),\n"," cropped.getpixel((w-1, 0)),\n"," cropped.getpixel((0, h-1)),\n"," cropped.getpixel((w-1, h-1))\n"," ]\n"," orig_bg = tuple(sum(c) // len(samples) for c in zip(*samples))\n"," print(f\" πŸ“ Using robust 4-corner BG color for {filename}\")\n"," else:\n"," orig_bg = cropped.getpixel((0, 0))\n","\n"," # === PROCESS IMAGE ===\n"," if enable_floodfill_background_adjustment:\n"," processed = adjust_background(\n"," cropped,\n"," orig_bg,\n"," enable_floodfill_background_adjustment,\n"," enable_small_speck_removal,\n"," enable_inverse_speck_removal,\n"," enable_anti_aliasing,\n"," anti_aliasing_strength,\n"," min_floodfill_steps,\n"," max_inverse_speck_size,\n"," bg_margin_percent\n"," )\n"," else:\n"," processed = cropped\n","\n"," out_path = os.path.join(processed_dir, filename)\n"," processed.save(out_path, quality=95 if filename.lower().endswith(('.jpg', '.jpeg')) else None)\n","\n"," processed_count += 1\n"," print(f\" βœ… {filename}\")\n","\n"," except Exception as e:\n"," print(f\" ❌ Skipped {filename}: {e}\")\n","\n"," print(f\"\\nπŸŽ‰ Processed {processed_count} images!\")\n","\n"," # 6. Create final ZIP\n"," output_zip_name = \"PROCESSED_\" + os.path.basename(input_zip_path)\n"," output_zip_path = os.path.join(os.path.dirname(input_zip_path), output_zip_name)\n","\n"," print(f\"πŸš€ Creating final ZIP: {output_zip_name}\")\n"," with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:\n"," for root, _, files in os.walk(processed_dir):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," arcname = os.path.relpath(file_path, processed_dir)\n"," zip_out.write(file_path, arcname)\n","\n"," print(\"\\nβœ… ALL DONE! Solid #181818 everywhere (forward + inverse specks cleaned) + smooth AA last\")\n"," print(f\"πŸ“ Saved to your Drive at:\\n {output_zip_path}\")\n"],"metadata":{"cellView":"form","id":"tFGWg7jNv4mo"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"93JpoQJ77NGu","cellView":"form"},"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 = 0 #@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","#input_zip_path = \"/content/drive/MyDrive/PROCESSED_klein_processed.zip\" #@param {type:\"string\"}\n","zip_file_path = zip_path\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":["# Done!\n","\n","In the zip file /content/drive/MyDrive/vertical_slices_output/vertical_slices.zip , there you will find 500 image composites to choose for lora training"],"metadata":{"id":"tJlvhf9xDmA7"}}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776787634021},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776773678064},{"file_id":"151XI3nRFxLRbwRc8V6OfWyqp-zTnfySv","timestamp":1776764241991},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_edit.ipynb","timestamp":1776702729526},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776687886662},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/vertical_slice_prepper.ipynb","timestamp":1776366149549},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/lora_vertical_slice_dataset_creator.ipynb","timestamp":1776287741995},{"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}],"collapsed_sections":["HX3I-YqowwO9","4PjK9a8Sni3A"]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}