codeShare commited on
Commit
e62da38
Β·
verified Β·
1 Parent(s): e4bdf89

Upload enc_run_klein_edit_aio.ipynb

Browse files
Files changed (1) hide show
  1. enc_run_klein_edit_aio.ipynb +1 -0
enc_run_klein_edit_aio.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"cells":[{"cell_type":"markdown","source":["# Run Klein finetune"],"metadata":{"id":"6UhKYCWzPyrm"}},{"cell_type":"code","execution_count":null,"metadata":{"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","\n","#encryption\n","!pip install -q git+https://github.com/huggingface/diffusers.git --force-reinstall --no-deps\n","!python -m pip cache purge\n","print(\"πŸ” Installing encryption + datasets...\")\n","!pip install -q pynacl datasets\n","\n","print(\"βœ… Cell 1 complete!\")"]},{"cell_type":"code","source":["#@title Set path to zip file on your drive , and set klein edit prompt\n","upload_from_widget = False #@param {type:'boolean'}\n","input_zip_path = '/content/drive/MyDrive/first100.zip' #@param {type:'string'}\n","edit_prompt = 'improve this illustration. balanced color contrast. the background is dark gray.' #@param {type:'string'}\n","\n","# ======================================================\n","\n","# Initialize zip_path; it will be set definitively by this cell or the next.\n","zip_path = None\n","\n","if not upload_from_widget:\n"," zip_path = input_zip_path\n"," print(f\"Using zip from Drive: {zip_path}\")\n","else:\n"," print(\"Widget upload enabled. Please run the next cell to upload your files.\")\n","\n","#---#\n","#@title Upload files via widget\n","import os\n","from google.colab import files\n","import zipfile\n","import shutil\n","\n","if upload_from_widget:\n"," print(\"Please upload your zip file or individual image files now.\")\n"," uploaded = files.upload()\n","\n"," if not uploaded:\n"," raise ValueError(\"No files uploaded. Please upload a zip file or images.\")\n","\n"," if len(uploaded) == 1 and list(uploaded.keys())[0].endswith('.zip'):\n"," # If a single zip file is uploaded\n"," uploaded_filename = list(uploaded.keys())[0]\n"," shutil.move(uploaded_filename, '/content/' + uploaded_filename)\n"," zip_path = '/content/' + uploaded_filename\n"," print(f\"Using uploaded zip file: {zip_path}\")\n"," else:\n"," # If multiple image files are uploaded, create a zip file\n"," temp_img_dir = '/content/uploaded_images_temp'\n"," os.makedirs(temp_img_dir, exist_ok=True)\n","\n"," image_count = 0\n"," for fname, content in uploaded.items():\n"," if fname.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):\n"," with open(os.path.join(temp_img_dir, fname), 'wb') as f:\n"," f.write(content)\n"," image_count += 1\n"," else:\n"," print(f\"Skipping non-image file: {fname}\")\n","\n"," if image_count == 0:\n"," raise ValueError(\"No valid image files uploaded. Please upload images.\")\n","\n"," zip_path = '/content/uploaded_images.zip'\n"," with zipfile.ZipFile(zip_path, 'w') as zf:\n"," for root, _, files_in_dir in os.walk(temp_img_dir):\n"," for file_in_dir in files_in_dir:\n"," zf.write(os.path.join(root, file_in_dir), os.path.basename(file_in_dir))\n"," shutil.rmtree(temp_img_dir)\n"," print(f\"Created zip from {image_count} uploaded images: {zip_path}\")\n","else:\n"," print(\"Widget upload is disabled. Using zip from Drive as specified in the previous cell.\")\n","\n","print(f\"Final zip_path for processing: {zip_path}\")"],"metadata":{"id":"K13pRro0lxAw"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 2**: Build ENCRYPTED INPUT DATASET\n","# =============================================================================\n","\n","import hashlib\n","import io\n","import base64\n","from PIL import Image\n","from datasets import Dataset\n","from nacl.secret import SecretBox\n","from nacl.utils import random\n","import zipfile\n","import glob\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)\"]\n","use_txt_prompts = False #@param {type:\"boolean\"}\n","debug = False #@param {type:\"boolean\"}\n","\n","# πŸ”‘ USER KEY\n","encryption_password = \"banana\" #@param {type:\"string\"}\n","\n","# ===== KEY DERIVATION =====\n","def derive_key(password):\n"," return hashlib.sha256(password.encode()).digest()\n","\n","SECRET_KEY = derive_key(encryption_password)\n","box = SecretBox(SECRET_KEY)\n","\n","# ===== IMAGE SERIALIZATION =====\n","def pil_to_bytes(img):\n"," buf = io.BytesIO()\n"," img.save(buf, format=\"PNG\")\n"," return buf.getvalue()\n","\n","# ===== ENCRYPT =====\n","def encrypt_bytes(data):\n"," nonce = random(SecretBox.NONCE_SIZE)\n"," return box.encrypt(data, nonce)\n","\n","# ====================== LOAD ZIP ======================\n","print(f\"πŸ“¦ Building encrypted dataset from: {zip_path}\")\n","\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","\n","records = []\n","\n","for img_path in image_files:\n"," img = Image.open(img_path).convert(\"RGB\")\n"," img_bytes = pil_to_bytes(img)\n"," enc = encrypt_bytes(img_bytes)\n","\n"," records.append({\n"," \"image_encrypted\": enc\n"," })\n","\n","print(f\"βœ… Encrypted {len(records)} images\")\n","\n","# ====================== SAVE DATASET ======================\n","ds = Dataset.from_list(records)\n","\n","dataset_path = \"/content/encrypted_input_dataset\"\n","ds.save_to_disk(dataset_path)\n","\n","print(f\"πŸ“¦ Saved dataset β†’ {dataset_path}\")"],"metadata":{"cellView":"form","id":"8j04j0GpR8qj"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 3**: Load SDNQ MODEL FROM HF\n","# =============================================================================\n","\n","import torch\n","import gc\n","import os\n","from diffusers import Flux2KleinPipeline\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","# =========================================================\n","# πŸ”₯ LOAD YOUR NEWLY UPLOADED MODEL FROM HF REPO\n","# =========================================================\n","MODEL_ID = \"codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic\" #@param ['codeShare/Flux-Klein-SDNQ-4bit','codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic', 'codeShare/unstableRevolution_SDNQ']\n","\n","print(f\"πŸ”„ Loading model from: {MODEL_ID}\")\n","\n","pipe = Flux2KleinPipeline.from_pretrained(\n"," MODEL_ID,\n"," torch_dtype=torch.float16,\n"," low_cpu_mem_usage=True,\n"," device_map=\"cpu\" # IMPORTANT: prevents VRAM spike at load\n",")\n","\n","print(\"βœ… Base pipeline loaded (CPU-safe)\")\n","\n","# =========================================================\n","# πŸ”₯ APPLY SDNQ OPTIMIZATIONS (AFTER LOAD)\n","# =========================================================\n","print(\"πŸ”₯ Applying SDNQ optimizations...\")\n","\n","os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n","\n","if torch.cuda.is_available():\n"," if triton_is_available:\n"," pipe.transformer = apply_sdnq_options_to_model(\n"," pipe.transformer,\n"," use_quantized_matmul=True\n"," )\n"," pipe.text_encoder = apply_sdnq_options_to_model(\n"," pipe.text_encoder,\n"," use_quantized_matmul=True\n"," )\n"," print(\" βœ… Quantized matmul enabled\")\n","\n","# =========================================================\n","# πŸ”₯ MEMORY OPTIMIZATION (CRITICAL FOR T4 / COLAB)\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 – NEW MODEL READY\")\n","print(\"VRAM usage:\", torch.cuda.memory_allocated() / 1e9, \"GB\")\n","print(\"πŸ‘‰ Run Cell 4 now\")"],"metadata":{"id":"v8DnJ__ZP4r3","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 4**: MULTI-IMAGE INFERENCE (Encrypted Dataset Pipeline)\n","# =============================================================================\n","\n","import os\n","import shutil\n","import glob\n","import torch\n","import gc\n","import datetime\n","import io\n","import hashlib\n","\n","from PIL import Image, ImageDraw\n","from nacl.secret import SecretBox\n","from nacl.utils import random\n","from datasets import load_from_disk, Dataset\n","\n","# ================= SETTINGS =================\n","upload_custom_reference = False #@param {type:\"boolean\"}\n","max_image_dimension = 2048 #@param {type:\"slider\", min:512, max:4096, step:256}\n","add_gray_corners = False #@param {type:\"boolean\"}\n","gray_square_size = 50 #@param {type:\"slider\", min:10, max:200, step:10}\n","\n","save_to_drive_every_n = True #@param {type:\"boolean\"}\n","save_every_n = 10 #@param {type:\"slider\", min:1, max:100, step:1}\n","\n","output_folder = '/content/edited_images_multi'\n","checkpoint_folder = '/content/drive/MyDrive/klein_checkpoints'\n","\n","# ================= CLEAN =================\n","print(\"🧹 Clearing old folders...\")\n","for p in [output_folder]:\n"," if os.path.exists(p):\n"," shutil.rmtree(p)\n","\n","os.makedirs(output_folder, exist_ok=True)\n","os.makedirs(checkpoint_folder, exist_ok=True)\n","\n","# ================= πŸ”‘ KEY =================\n","def derive_key(password):\n"," return hashlib.sha256(password.encode()).digest()\n","\n","SECRET_KEY = derive_key(encryption_password)\n","box = SecretBox(SECRET_KEY)\n","\n","# ================= CRYPTO =================\n","def decrypt_bytes(enc):\n"," return box.decrypt(enc)\n","\n","def encrypt_bytes(data):\n"," nonce = random(SecretBox.NONCE_SIZE)\n"," return box.encrypt(data, nonce)\n","\n","# ================= IMAGE UTILS =================\n","def bytes_to_pil(b):\n"," return Image.open(io.BytesIO(b)).convert(\"RGB\")\n","\n","def pil_to_bytes(img):\n"," buf = io.BytesIO()\n"," img.save(buf, format=\"PNG\")\n"," return buf.getvalue()\n","\n","def add_corner_squares(image, square_size, color=(24,24,24)):\n"," img_copy = image.copy()\n"," draw = ImageDraw.Draw(img_copy)\n"," w, h = img_copy.size\n"," draw.rectangle([(0,0),(square_size,square_size)], fill=color)\n"," draw.rectangle([(w-square_size,0),(w,square_size)], fill=color)\n"," draw.rectangle([(0,h-square_size),(square_size,h)], fill=color)\n"," draw.rectangle([(w-square_size,h-square_size),(w,h)], fill=color)\n"," return img_copy\n","\n","# ================= LOAD DATASET =================\n","dataset_path = \"/content/encrypted_input_dataset\"\n","print(f\"πŸ“¦ Loading encrypted dataset: {dataset_path}\")\n","\n","input_dataset = load_from_disk(dataset_path)\n","print(f\"βœ… Loaded {len(input_dataset)} encrypted samples\")\n","\n","# ================= REFERENCE =================\n","if upload_custom_reference:\n"," from google.colab import files\n"," uploaded = files.upload()\n"," ref_path = list(uploaded.keys())[0]\n"," reference_image_to_pair = Image.open(ref_path).convert(\"RGB\")\n","else:\n"," reference_image_to_pair = Image.new(\"RGB\", (target_width, target_height), \"#181818\")\n","\n","# ================= CHECKPOINT =================\n","def save_checkpoint(batch_files, checkpoint_id):\n"," if not save_to_drive_every_n:\n"," return\n","\n"," zip_path = f\"{checkpoint_folder}/checkpoint_{checkpoint_id}.zip\"\n"," tmp = f\"{checkpoint_folder}/tmp_{checkpoint_id}\"\n","\n"," os.makedirs(tmp, exist_ok=True)\n"," for f in batch_files:\n"," shutil.copy(f, tmp)\n","\n"," shutil.make_archive(zip_path.replace('.zip',''), 'zip', tmp)\n"," shutil.rmtree(tmp)\n","\n"," print(f\"πŸ’Ύ Saved checkpoint: {zip_path}\")\n","\n","# ================= INFERENCE =================\n","print(\"\\nπŸš€ Starting encrypted dataset inference...\")\n","\n","output_dataset_records = []\n","batch_outputs = []\n","checkpoint_id = 0\n","\n","for i, item in enumerate(input_dataset):\n","\n"," gc.collect()\n"," torch.cuda.empty_cache()\n","\n"," # ---------- DECRYPT INPUT ----------\n"," enc_bytes = item[\"image_encrypted\"]\n"," dec_bytes = decrypt_bytes(enc_bytes)\n"," input_image = bytes_to_pil(dec_bytes)\n","\n"," filename = f\"{i}.png\"\n","\n"," # ---------- RESIZE ----------\n"," if max(input_image.width, input_image.height) > max_image_dimension:\n"," aspect = input_image.width / input_image.height\n"," if input_image.width > input_image.height:\n"," input_image = input_image.resize(\n"," (max_image_dimension, int(max_image_dimension / aspect)),\n"," Image.LANCZOS\n"," )\n"," else:\n"," input_image = input_image.resize(\n"," (int(max_image_dimension * aspect), max_image_dimension),\n"," Image.LANCZOS\n"," )\n","\n"," if add_gray_corners:\n"," input_image = add_corner_squares(input_image, gray_square_size)\n","\n"," reference_images = [input_image, reference_image_to_pair]\n","\n"," # ---------- MODEL ----------\n"," result = pipe(\n"," prompt=edit_prompt,\n"," image=reference_images,\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"," # ---------- ENCRYPT OUTPUT ----------\n"," out_bytes = pil_to_bytes(result)\n"," enc_out = encrypt_bytes(out_bytes)\n","\n"," out_path = os.path.join(output_folder, f\"edited_{filename}.enc\")\n","\n"," with open(out_path, \"wb\") as f:\n"," f.write(enc_out)\n","\n"," output_dataset_records.append({\n"," \"image_encrypted\": enc_out\n"," })\n","\n"," batch_outputs.append(out_path)\n","\n"," print(f\"[{i+1}/{len(input_dataset)}] processed\")\n","\n"," # ---------- CHECKPOINT ----------\n"," if save_to_drive_every_n and len(batch_outputs) >= save_every_n:\n"," checkpoint_id += 1\n"," save_checkpoint(batch_outputs, checkpoint_id)\n"," batch_outputs = []\n","\n","# ================= FINAL CHECKPOINT =================\n","if save_to_drive_every_n and len(batch_outputs) > 0:\n"," checkpoint_id += 1\n"," save_checkpoint(batch_outputs, checkpoint_id)\n","\n","print(\"\\nβœ… BATCH COMPLETE!\")\n","\n","# ================= SAVE OUTPUT DATASET =================\n","print(\"πŸ“¦ Saving encrypted output dataset...\")\n","\n","output_dataset = Dataset.from_list(output_dataset_records)\n","\n","output_dataset_path = \"/content/encrypted_output_dataset\"\n","output_dataset.save_to_disk(output_dataset_path)\n","\n","print(f\"βœ… Saved β†’ {output_dataset_path}\")\n","\n","\n","# ================= FINAL ZIP =================\n","timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","final_zip = f\"/content/drive/MyDrive/klein_encrypted_outputs_{timestamp}.zip\"\n","\n","shutil.make_archive(final_zip.replace('.zip',''), 'zip', output_folder)\n","\n","print(f\"πŸ“¦ Final encrypted zip β†’ {final_zip}\")\n","print(\"🎯 DONE\")"],"metadata":{"cellView":"form","id":"Bh8yC1-aS3Wz"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Clean unassigned junk files from VRAM , run this if interrupting the cell script\n","import torch , gc\n","torch.cuda.empty_cache()\n","gc.collect()"],"metadata":{"id":"e46WUV7jMInu","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1777202060819,"user_tz":-120,"elapsed":682,"user":{"displayName":"Nnekos4Lyfe","userId":"11521490251288716219"}},"outputId":"8c7c6809-c91c-4cd8-d572-c0a71de16367"},"execution_count":26,"outputs":[{"output_type":"execute_result","data":{"text/plain":["0"]},"metadata":{},"execution_count":26}]},{"cell_type":"code","source":["# =============================================================================\n","#@markdown # **CELL 5**: Decrypt Dataset / ZIP / ALL CHECKPOINTS β†’ Export ZIP (STREAMING ONLY + SINGLE DOWNLOAD ZIP)\n","# =============================================================================\n","\n","import os\n","import zipfile\n","import io\n","import hashlib\n","from PIL import Image\n","from nacl.secret import SecretBox\n","from datasets import load_from_disk\n","from google.colab import output\n","from google.colab import files # Import google.colab.files\n","\n","# ================= MODE CONTROLS =================\n","process_all_checkpoints = True #@param {type:\"boolean\"}\n","decrypt_from_zip = False #@param {type:\"boolean\"}\n","upload_zip_manually = False #@param {type:\"boolean\"}\n","download_output_zip = True #@param {type:\"boolean\"}\n","\n","dataset_to_decrypt = \"/content/encrypted_output_dataset\" #@param {type:\"string\"}\n","encrypted_zip_path = \"/content/drive/MyDrive/klein_checkpoints/checkpoint_2.zip\" #@param {type:\"string\"}\n","\n","output_zip_name = \"decrypt.zip\" #@param {type:\"string\"}\n","\n","output_base_folder = \"/content/zip_outputs\"\n","os.makedirs(output_base_folder, exist_ok=True)\n","\n","checkpoint_dir = \"/content/drive/MyDrive/klein_checkpoints\"\n","\n","# ================= πŸ”‘ KEY =================\n","def derive_key(password):\n"," return hashlib.sha256(password.encode()).digest()\n","\n","decryption_password = \"banana\" #@param {type:\"string\"}\n","\n","SECRET_KEY = derive_key(decryption_password)\n","box = SecretBox(SECRET_KEY)\n","\n","def decrypt_bytes(enc):\n"," return box.decrypt(enc)\n","\n","# ================= IMAGE IO =================\n","def bytes_to_pil(b):\n"," return Image.open(io.BytesIO(b)).convert(\"RGB\")\n","\n","def pil_to_bytes(img):\n"," buf = io.BytesIO()\n"," img.save(buf, format=\"PNG\")\n"," return buf.getvalue()\n","\n","# ================= PIPE =================\n","def decrypt_stream(enc_bytes_list):\n"," out = []\n"," for enc in enc_bytes_list:\n"," dec = decrypt_bytes(enc)\n"," img = bytes_to_pil(dec)\n"," out.append(pil_to_bytes(img))\n"," return out\n","\n","def decrypt_zip(zip_path):\n"," with zipfile.ZipFile(zip_path, \"r\") as z:\n"," enc_files = [z.read(n) for n in z.namelist() if n.endswith(\".enc\")]\n"," return decrypt_stream(enc_files)\n","\n","def decrypt_dataset(ds):\n"," return decrypt_stream([x[\"image_encrypted\"] for x in ds])\n","\n","# ================= ZIP BUILDER =================\n","def write_images_to_zip(image_bytes_list, out_zip_path):\n"," with zipfile.ZipFile(out_zip_path, \"w\", compression=zipfile.ZIP_DEFLATED) as zf:\n"," for i, img_bytes in enumerate(image_bytes_list):\n"," zf.writestr(f\"{i}.png\", img_bytes)\n","\n","# ================= OUTPUT =================\n","all_image_bytes = [] # <-- unified buffer\n","generated_zips = []\n","\n","# =============================================================================\n","# πŸ”₯ MODE 1: ALL CHECKPOINTS\n","# =============================================================================\n","if process_all_checkpoints:\n","\n"," print(f\"πŸ“‚ Scanning: {checkpoint_dir}\")\n","\n"," checkpoint_zips = sorted([\n"," os.path.join(checkpoint_dir, f)\n"," for f in os.listdir(checkpoint_dir)\n"," if f.endswith(\".zip\") and \"checkpoint\" in f\n"," ])\n","\n"," print(f\"πŸ” Found {len(checkpoint_zips)} checkpoints\")\n","\n"," for idx, zpath in enumerate(checkpoint_zips):\n","\n"," print(f\"πŸ“¦ Processing {zpath}\")\n","\n"," enc_imgs = decrypt_zip(zpath)\n","\n"," if download_output_zip:\n"," all_image_bytes.extend(enc_imgs)\n"," else:\n"," out_zip = os.path.join(\n"," output_base_folder,\n"," f\"decrypted_checkpoint_{idx}.zip\"\n"," )\n"," write_images_to_zip(enc_imgs, out_zip)\n"," generated_zips.append(out_zip)\n","\n","# =============================================================================\n","# πŸ”“ MODE 2: DATASET\n","# =============================================================================\n","elif not decrypt_from_zip:\n","\n"," print(f\"πŸ“¦ Loading dataset: {dataset_to_decrypt}\")\n"," ds = load_from_disk(dataset_to_decrypt)\n","\n"," enc_imgs = decrypt_dataset(ds)\n","\n"," if download_output_zip:\n"," all_image_bytes.extend(enc_imgs)\n"," else:\n"," out_zip = os.path.join(output_base_folder, output_zip_name)\n"," write_images_to_zip(enc_imgs, out_zip)\n"," generated_zips.append(out_zip)\n","\n","# =============================================================================\n","# πŸ”“ MODE 3: SINGLE ZIP\n","# =============================================================================\n","else:\n","\n"," if upload_zip_manually:\n"," print(\"πŸ“€ Upload zip...\")\n"," from google.colab import files\n"," uploaded = files.upload()\n","\n"," zip_name = list(uploaded.keys())[0]\n"," zip_path = \"/content/\" + zip_name\n","\n"," with open(zip_path, \"wb\") as f:\n"," f.write(uploaded[zip_name])\n","\n"," else:\n"," zip_path = encrypted_zip_path\n","\n"," enc_imgs = decrypt_zip(zip_path)\n","\n"," if download_output_zip:\n"," all_image_bytes.extend(enc_imgs)\n"," else:\n"," out_zip = os.path.join(output_base_folder, output_zip_name)\n"," write_images_to_zip(enc_imgs, out_zip)\n"," generated_zips.append(out_zip)\n","\n","# =============================================================================\n","# πŸ“¦ FINAL PACKAGING LOGIC\n","# =============================================================================\n","if download_output_zip:\n","\n"," final_zip = os.path.join(output_base_folder, output_zip_name)\n","\n"," print(f\"πŸ“¦ Building single unified ZIP β†’ {final_zip}\")\n","\n"," write_images_to_zip(all_image_bytes, final_zip)\n","\n"," # The previous method using output.eval_js can sometimes fail for large files\n"," # due to DataCloneError. Using google.colab.files.download is more robust.\n"," files.download(final_zip)\n","\n"," print(\"⬇️ Download triggered via google.colab.files.download\")\n","\n","else:\n","\n"," print(\"πŸ“¦ Multiple ZIP mode output:\")\n"," for z in generated_zips:\n"," print(\" -\", z)\n","\n","print(\"🎯 DONE\")\n"],"metadata":{"cellView":"form","id":"xs2bckRjgWcD"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# πŸ”Œ Auto Disconnect from Drive\n","\n","Results from earlier cell have been saved to your drive as\n","'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":"7eeX3_qpYpwl"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"FQF71-mvmlc1","cellView":"form"},"outputs":[],"source":["# ================================================\n","#@title πŸ”Œ Auto Disconnect Colab Session\n","# ================================================\n","\n","enable = False #@param {type:'boolean'}\n","if enable:\n"," print(\"πŸ”Œ Disconnecting Colab session in 3 seconds...\")\n"," import time\n"," time.sleep(3)\n","\n"," from google.colab import runtime\n"," runtime.unassign()\n","\n"," print(\"Session disconnected.\")"]},{"cell_type":"markdown","source":["# Select Klein processed file to use next"],"metadata":{"id":"s7R3l3-pY5W7"}},{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"ijzwEoboHVPR"},"execution_count":null,"outputs":[]},{"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.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 = 50 #@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 = 60 #@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":"markdown","source":["# βš™οΈ Create composites"],"metadata":{"id":"kVAe29swHo4I"}},{"cell_type":"code","source":["#@markdown Set zip file input path for making composites\n","input_zip_path = \"/content/drive/MyDrive/PROCESSED_klein_processed.zip\" #@param {type:'string'}\n","zip_file_path = input_zip_path"],"metadata":{"id":"IXQKiBVrNPcE"},"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 = 100 #@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","# ────────────────────────────────────────────────\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 100 image composites to choose for lora training\n","\n","//-----//"],"metadata":{"id":"tJlvhf9xDmA7"}}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic/blob/main/run_klein_edit_aio.ipynb","timestamp":1777129973676},{"file_id":"https://huggingface.co/codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic/blob/main/notebooks/klein_edit_aio.ipynb","timestamp":1777127335701},{"file_id":"https://huggingface.co/codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic/blob/main/notebooks/klein_edit_aio.ipynb","timestamp":1776991571771},{"file_id":"https://huggingface.co/codeShare/FLUX.2-klein-AIO-SDNQ-4bit-dynamic/blob/main/notebooks/klein_edit_aio.ipynb","timestamp":1776952244463},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776905776793},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776904822796},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776896778295},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776814708184},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776796861814},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776795061697},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776794307247},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776790556621},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/klein_prepare_lora_set.ipynb","timestamp":1776789720072},{"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":["6UhKYCWzPyrm","s7R3l3-pY5W7","4PjK9a8Sni3A","kVAe29swHo4I"],"gpuType":"T4"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"},"accelerator":"GPU"},"nbformat":4,"nbformat_minor":0}