Datasets:
Tags:
Not-For-All-Audiences
File size: 21,012 Bytes
b3e8121 | 1 | {"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"collapsed":true,"id":"at9ImGTxYqn6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import os\n","import io\n","import random\n","import zipfile\n","from google.colab import drive\n","from PIL import Image\n","import cv2\n","import numpy as np\n","import gc\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Configuration\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","num_frames = 1000 #@param {type:\"slider\", min:1, max:1500, step:1}\n","split_images_horizontally = False #@param {type:\"boolean\"}\n","use_manual_upload = False #@param {type:\"boolean\"}\n","\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","#@markdown **ZIP MODE** (when `use_manual_upload` is OFF)\n","#@markdown Paste full path to your zip file\n","zip_file_path = \"/content/drive/MyDrive/fetch.zip\" #@param {type:\"string\"}\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Mount Google Drive\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","drive_mounted = False\n","drive_output_dir = None\n","\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_base = \"/content/drive/MyDrive\"\n"," drive_output_dir = os.path.join(drive_base, drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(f\"β Google Drive mounted. Output β {drive_output_dir}/vertical_slices.zip\")\n"," except Exception as e:\n"," print(f\"Drive mount failed: {e}\")\n"," save_to_google_drive = False\n"," print(\"β No persistent saving possible.\")\n","else:\n"," print(\"Google Drive saving disabled β output only temporary!\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Settings\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","FRAME_SIZE = 1024\n","BORDER_PX = 14\n","INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX\n","num_vertical_panels = 4 #@param {type:\"slider\", min:1, max:12}\n","NUM_SLICES = num_vertical_panels\n","SLICE_WIDTH = INNER_SIZE // NUM_SLICES\n","target_h = INNER_SIZE\n","target_w = SLICE_WIDTH\n","\n","BORDER_COLOR = (24, 24, 24)\n","\n","extract_root = \"/content/extracted_images\"\n","output_dir = \"/content/vertical_slice_frames\"\n","\n","os.makedirs(extract_root, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Helper β extract slices from single image\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","def extract_vertical_slices(photo, target_w, target_h, border_color):\n"," slices = []\n"," try:\n"," w, h = photo.size\n"," if h <= 0 or w <= 0:\n"," return slices\n","\n"," scale = target_h / h\n"," new_w = int(w * scale + 0.5)\n"," if new_w < 1:\n"," return slices\n","\n"," resized = photo.resize((new_w, target_h), Image.LANCZOS)\n","\n"," if new_w < target_w:\n"," sl = Image.new('RGB', (target_w, target_h), border_color)\n"," sl.paste(resized, ((target_w - new_w)//2, 0))\n"," slices.append(sl)\n"," else:\n"," num = max(1, new_w // target_w)\n"," used = num * target_w\n"," start = (new_w - used) // 2\n"," for i in range(num):\n"," left = start + i * target_w\n"," crop = resized.crop((left, 0, left + target_w, target_h))\n"," slices.append(crop)\n","\n"," del resized\n"," except Exception as e:\n"," print(f\"Error extracting slices: {e}\")\n"," return slices\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Load images β extract slices immediately (low memory)\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","all_slices = []\n","\n","print(\"Loading images and extracting slices...\\n\")\n","\n","if use_manual_upload:\n"," from google.colab import files\n"," print(\"Upload images (jpg/jpeg/png/webp)\")\n"," uploaded = files.upload()\n","\n"," for filename, filedata in uploaded.items():\n"," fname_lower = filename.lower()\n"," if fname_lower.startswith('._') or '__macosx' in fname_lower:\n"," continue\n"," if fname_lower.endswith(('.jpg','.jpeg','.png','.webp')):\n"," try:\n"," img = Image.open(io.BytesIO(filedata)).convert('RGB')\n"," temp_slices = extract_vertical_slices(img, target_w, target_h, BORDER_COLOR)\n"," all_slices.extend(temp_slices)\n"," del img, temp_slices\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Skip {filename}: {e}\")\n","\n","else:\n"," if not zip_file_path or not os.path.isfile(zip_file_path):\n"," print(\"Invalid or missing zip path.\")\n"," else:\n"," try:\n"," with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n"," print(\"Extraction finished.\")\n"," except Exception as e:\n"," print(f\"Zip extraction failed: {e}\")\n"," raise\n","\n"," valid_exts = ('.jpg', '.jpeg', '.png', '.webp')\n"," count = 0\n"," for root_dir, _, files in os.walk(extract_root):\n"," if '__MACOSX' in root_dir:\n"," continue\n"," for fname in files:\n"," if fname.startswith('._'):\n"," continue\n"," if fname.lower().endswith(valid_exts):\n"," path = os.path.join(root_dir, fname)\n"," try:\n"," # Quick verify\n"," with Image.open(path) as im:\n"," im.verify()\n"," img = Image.open(path).convert('RGB')\n"," temp_slices = extract_vertical_slices(img, target_w, target_h, BORDER_COLOR)\n"," all_slices.extend(temp_slices)\n"," del img, temp_slices\n"," count += 1\n"," if count % 20 == 0:\n"," print(f\"Processed {count} images...\")\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Skip {fname}: {str(e)}\")\n","\n","print(f\"\\nTotal vertical slices extracted: {len(all_slices)}\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Generate frames\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","if len(all_slices) == 0:\n"," print(\"No slices available β stopping.\")\n","else:\n"," print(f\"Generating {num_frames} frames...\")\n"," frame_idx = 0\n","\n"," while frame_idx < num_frames:\n"," k = min(NUM_SLICES, len(all_slices))\n"," group = random.sample(all_slices * 4, k)\n"," random.shuffle(group)\n","\n"," canvas = Image.new('RGB', (INNER_SIZE, INNER_SIZE), (0,0,0))\n"," for col in range(NUM_SLICES):\n"," crop = group[col % len(group)]\n"," canvas.paste(crop, (col * SLICE_WIDTH, 0))\n","\n"," final = Image.new('RGB', (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(canvas, (BORDER_PX, BORDER_PX))\n","\n"," fname = f\"frame_{frame_idx+1:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=82)\n","\n"," del canvas, final\n"," frame_idx += 1\n","\n"," if frame_idx % 50 == 0:\n"," print(f\"Saved {frame_idx}/{num_frames} frames...\")\n"," if frame_idx % 100 == 0:\n"," gc.collect()\n","\n"," print(f\"Finished β created {frame_idx} frames\")\n","\n"," # βββ Save fixed-name zip directly to Drive (overwrite) βββ\n"," if save_to_google_drive and drive_mounted:\n"," final_zip_name = \"vertical_slices.zip\"\n"," local_zip_path = f\"/content/{final_zip_name}\"\n"," drive_zip_path = os.path.join(drive_output_dir, final_zip_name)\n","\n"," print(\"Creating zip (flat structure)...\")\n","\n"," # Create zip with files at root level\n"," with zipfile.ZipFile(local_zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n"," for fname in sorted(os.listdir(output_dir)):\n"," if fname.endswith('.jpg'):\n"," full_path = os.path.join(output_dir, fname)\n"," zf.write(full_path, arcname=fname) # β flat: no subfolder\n","\n"," print(\"Copying to Google Drive (will overwrite previous version)...\")\n"," !cp -f \"{local_zip_path}\" \"{drive_zip_path}\"\n","\n"," print(f\"\\nSuccess! Overwritten file:\")\n"," print(f\"β {drive_zip_path}\")\n","\n"," # Optional cleanup (uncomment if you want to free Colab disk space)\n"," # !rm -rf \"{output_dir}\" \"{local_zip_path}\"\n"," print(\"Temporary files kept in /content β delete manually if needed.\")\n"," else:\n"," print(\"\\nNo Drive save β frames are only in /content/vertical_slice_frames\")"],"metadata":{"id":"qiXhuNfyhVtJ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# GOOGLE COLAB β FAST Voronoi Composite (color-replacement style)\n","# β’ All source images resized to height=1024 exactly β vertical always perfectly aligned\n","# β’ For wide sources (>1024 px): random horizontal window (fast slice)\n","# β’ For narrow sources: centered slice with gray padding on sides\n","# β’ Direct pixel replacement using integer label map β much faster than per-region masking\n","\n","import os\n","import random\n","import zipfile\n","import shutil\n","from google.colab import drive\n","from PIL import Image\n","import numpy as np\n","import gc\n","\n","print(\"Mounting Drive...\")\n","drive.mount('/content/drive', force_remount=False)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# SETTINGS\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","NUM_VORONOI_SETS = 20 #@param {type:\"slider\", min:5, max:500, step:5}\n","NUM_COMPOSITES = 10 #@param {type:\"slider\", min:10, max:1000, step:10}\n","NUM_COLORED_REGIONS = 4 #@param {type:\"slider\", min:2, max:10, step:1}\n","\n","SOURCE_ZIP_PATH = \"/content/drive/MyDrive/fetch.zip\" #@param {type:\"string\"}\n","DRIVE_ZIP_FOLDER = \"/content/drive/MyDrive/Fast_Voronoi_Composites\" #@param {type:\"string\"}\n","\n","JPEG_QUALITY = 88 #@param {type:\"slider\", min:70, max:95, step:1}\n","\n","# Fixed\n","FRAME_SIZE = 1024\n","BORDER_PX = 14\n","INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX\n","BORDER_COLOR = (24, 24, 24)\n","GRAY_PAD = np.array([24, 24, 24], dtype=np.uint8)\n","\n","COLOR_POOL = [\n"," (255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255), (0,255,255),\n"," (255,140,0), (60,179,113), (138,43,226), (255,105,180), (0,191,255),\n"," (255,215,0), (186,85,211), (154,205,50), (220,20,60)\n","]\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Folders\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","composites_dir = \"/content/composites\"\n","temp_extract = \"/content/temp_sources\"\n","\n","for d in [composites_dir, temp_extract]:\n"," os.makedirs(d, exist_ok=True)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# 1. Load & resize ALL sources to height=1024\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","source_resized = []\n","\n","print(\"Loading & resizing sources to height=1024...\\n\")\n","\n","if os.path.isfile(SOURCE_ZIP_PATH):\n"," with zipfile.ZipFile(SOURCE_ZIP_PATH, 'r') as z:\n"," z.extractall(temp_extract)\n","\n"," for root, _, files in os.walk(temp_extract):\n"," for fname in files:\n"," if not fname.lower().endswith(('.jpg','.jpeg','.png','.webp')): continue\n"," try:\n"," img = Image.open(os.path.join(root, fname)).convert('RGB')\n"," ratio = 1024.0 / img.height\n"," new_w = int(img.width * ratio + 0.5)\n"," resized = img.resize((new_w, 1024), Image.LANCZOS)\n"," source_resized.append(np.array(resized)) # keep as numpy β faster later\n"," except:\n"," pass\n","\n","print(f\"β Prepared {len(source_resized)} images (height=1024)\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# 2. Pre-generate label maps (integer regions, no color images needed)\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(f\"Generating {NUM_VORONOI_SETS} Voronoi label maps...\\n\")\n","\n","label_maps = []\n","\n","h = w = FRAME_SIZE\n","\n","for i in range(NUM_VORONOI_SETS):\n"," num_points = NUM_COLORED_REGIONS + 1 # +1 for background/gray\n"," points = np.random.randint(0, FRAME_SIZE, size=(num_points, 2))\n","\n"," yy, xx = np.mgrid[0:h, 0:w]\n"," dists = np.sqrt((xx[:,:,np.newaxis] - points[:,0])**2 + (yy[:,:,np.newaxis] - points[:,1])**2)\n"," labels = np.argmin(dists, axis=2).astype(np.uint8) # 0..N β region index\n","\n"," label_maps.append(labels)\n","\n"," if (i+1) % 5 == 0:\n"," print(f\" Generated {i+1}/{NUM_VORONOI_SETS}\")\n","\n","print(f\"\\n{len(label_maps)} label maps ready.\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# 3. Fast composite loop β direct replacement\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(f\"Creating {NUM_COMPOSITES} composites (fast pixel replacement)...\\n\")\n","\n","for idx in range(NUM_COMPOSITES):\n"," labels = random.choice(label_maps) # integer map (h,w)\n"," canvas = np.full((FRAME_SIZE, FRAME_SIZE, 3), GRAY_PAD, dtype=np.uint8)\n","\n"," # We only fill the colored regions (1..N); 0 stays gray\n"," used_regions = set(range(1, NUM_COLORED_REGIONS + 1))\n","\n"," for region_id in used_regions:\n"," mask = (labels == region_id)\n"," if not mask.any(): continue\n","\n"," src = random.choice(source_resized) # (1024, src_w, 3)\n"," src_w = src.shape[1]\n","\n"," if src_w >= FRAME_SIZE:\n"," # Random horizontal window\n"," offset = random.randint(0, src_w - FRAME_SIZE)\n"," patch = src[:, offset:offset+FRAME_SIZE] # (1024,1024,3)\n"," else:\n"," # Center narrow image + gray sides\n"," offset = (FRAME_SIZE - src_w) // 2\n"," patch = np.full((FRAME_SIZE, FRAME_SIZE, 3), GRAY_PAD, dtype=np.uint8)\n"," patch[:, offset:offset+src_w] = src\n","\n"," # Direct replacement β very fast vectorized op\n"," canvas[mask] = patch[mask]\n","\n"," # Apply border\n"," inner = canvas[BORDER_PX:BORDER_PX+INNER_SIZE, BORDER_PX:BORDER_PX+INNER_SIZE]\n"," final = np.full((FRAME_SIZE, FRAME_SIZE, 3), BORDER_COLOR, dtype=np.uint8)\n"," final[BORDER_PX:BORDER_PX+INNER_SIZE, BORDER_PX:BORDER_PX+INNER_SIZE] = inner\n","\n"," img = Image.fromarray(final)\n"," fname = f\"comp_{idx+1:05d}.jpg\"\n"," img.save(os.path.join(composites_dir, fname), quality=JPEG_QUALITY, optimize=True)\n","\n"," if (idx + 1) % 20 == 0:\n"," print(f\" β {idx+1}/{NUM_COMPOSITES} done\")\n"," if (idx + 1) % 50 == 0:\n"," gc.collect()\n","\n","print(f\"\\nAll {NUM_COMPOSITES} composites finished.\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# 4. ZIP β Drive\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"Zipping & copying to Drive...\\n\")\n","\n","zip_comps = \"/content/voronoi_composites_fast.zip\"\n","\n","with zipfile.ZipFile(zip_comps, 'w', zipfile.ZIP_DEFLATED) as z:\n"," for f in os.listdir(composites_dir):\n"," if f.endswith('.jpg'):\n"," z.write(os.path.join(composites_dir, f), f)\n","\n","os.makedirs(DRIVE_ZIP_FOLDER, exist_ok=True)\n","shutil.copy2(zip_comps, os.path.join(DRIVE_ZIP_FOLDER, \"voronoi_composites_fast.zip\"))\n","\n","print(\"β
DONE!\")\n","print(f\"π Composites ZIP β {DRIVE_ZIP_FOLDER}/voronoi_composites_fast.zip\")\n","print(\"\\nKey speed-ups:\")\n","print(\"β’ No per-region center_of_mass\")\n","print(\"β’ No repeated mask creation\")\n","print(\"β’ Direct array assignment canvas[mask] = patch[mask]\")\n","print(\"β’ Sources kept as numpy arrays\")"],"metadata":{"id":"TNvH912FkHV8"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1774284184476},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772924452907},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772923478843},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772831486007},{"file_id":"11rioWNojWzoPp-O4wZK97yjublkR9GtQ","timestamp":1772750616448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772741185417},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0} |