codeShare commited on
Commit
97e946a
·
verified ·
1 Parent(s): eebcae4

Upload dataset_builder.ipynb

Browse files
Files changed (1) hide show
  1. dataset_builder.ipynb +1 -1
dataset_builder.ipynb CHANGED
@@ -1 +1 @@
1
- {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1761731354034},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1761124521078},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760628088876},{"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":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"widgets":{"application/vnd.jupyter.widget-state+json":{"903f51f8340e4ee8ad4b2fdee19209c1":{"model_module":"@jupyter-widgets/controls","model_name":"IntSliderModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"IntSliderModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"IntSliderView","continuous_update":true,"description":"Border (px):","description_tooltip":null,"disabled":false,"layout":"IPY_MODEL_659aa3a9509946409fb36b31cb4297d1","max":100,"min":0,"orientation":"horizontal","readout":true,"readout_format":"d","step":1,"style":"IPY_MODEL_7b1c28abe8da4fa88b61b7b969670bdd","value":10}},"659aa3a9509946409fb36b31cb4297d1":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"7b1c28abe8da4fa88b61b7b969670bdd":{"model_module":"@jupyter-widgets/controls","model_name":"SliderStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"SliderStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":"initial","handle_color":null}},"c37b743019054467b7f291c232b795eb":{"model_module":"@jupyter-widgets/controls","model_name":"IntSliderModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"IntSliderModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"IntSliderView","continuous_update":true,"description":"Corner Radius (px):","description_tooltip":null,"disabled":false,"layout":"IPY_MODEL_82f7fc12560c45139e4913522b26c283","max":200,"min":0,"orientation":"horizontal","readout":true,"readout_format":"d","step":1,"style":"IPY_MODEL_08cf4eacb2024ffaa234b58363cd5a63","value":30}},"82f7fc12560c45139e4913522b26c283":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"08cf4eacb2024ffaa234b58363cd5a63":{"model_module":"@jupyter-widgets/controls","model_name":"SliderStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"SliderStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":"initial","handle_color":null}}}}},"cells":[{"cell_type":"code","source":["# Mount Google Drive\n","from google.colab import drive\n","drive.mount('/content/drive')\n","\n","#/content/drive/MyDrive/backgrounds_raw\n","import os\n","from PIL import Image\n","import zipfile\n","from pathlib import Path\n","\n","# === CONFIGURATION ===\n","input_folder = '/content/drive/MyDrive/backgrounds_raw'\n","output_folder = '/content/drive/MyDrive/backgrounds_cropped'\n","zip_path = '/content/drive/MyDrive/backgrounds_cropped_squares.zip'\n","\n","# Create output folder\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# Supported extensions\n","extensions = ('.jpg', '.jpeg', '.JPG', '.JPEG', '.webp', '.WEBP')\n","\n","# Initialize zip file\n","with zipfile.ZipFile(zip_path, 'w') as zipf:\n"," # Process each image\n"," for filename in os.listdir(input_folder):\n"," if filename.lower().endswith(extensions):\n"," img_path = os.path.join(input_folder, filename)\n","\n"," try:\n"," with Image.open(img_path) as img:\n"," width, height = img.size\n","\n"," # Determine square size: use the smaller dimension\n"," square_size = min(width, height)\n","\n"," # LEFT crop: from left edge\n"," left_crop = img.crop((0, 0, square_size, square_size))\n"," left_name = f\"{Path(filename).stem}_left_square.jpg\"\n"," left_save_path = os.path.join(output_folder, left_name)\n"," left_crop.save(left_save_path, \"JPEG\", quality=95)\n","\n"," # RIGHT crop: from right edge\n"," right_crop = img.crop((width - square_size, 0, width, square_size))\n"," right_name = f\"{Path(filename).stem}_right_square.jpg\"\n"," right_save_path = os.path.join(output_folder, right_name)\n"," right_crop.save(right_save_path, \"JPEG\", quality=95)\n","\n"," # Add both to zip\n"," zipf.write(left_save_path, arcname=left_name)\n"," zipf.write(right_save_path, arcname=right_name)\n","\n"," print(f\"Processed: {filename} → {left_name}, {right_name}\")\n","\n"," except Exception as e:\n"," print(f\"Error processing {filename}: {e}\")\n","\n","print(f\"\\nAll done! Cropped images saved in:\\n{output_folder}\")\n","print(f\"ZIP file created at:\\n{zip_path}\")"],"metadata":{"id":"v-XiNqlbZ7GQ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @title # Rounded Background Composer (1024x1024)\n","\n","from google.colab import drive\n","drive.mount('/content/drive')\n","\n","import os\n","from PIL import Image, ImageDraw\n","import zipfile\n","from pathlib import Path\n","import ipywidgets as widgets\n","from IPython.display import display\n","\n","# === CONFIGURATION ===\n","input_folder = '/content/drive/MyDrive/backgrounds_cropped' # from previous step\n","output_folder = '/content/drive/MyDrive/backgrounds_final_rounded'\n","zip_path = '/content/drive/MyDrive/backgrounds_final_rounded.zip'\n","\n","os.makedirs(output_folder, exist_ok=True)\n","\n","CANVAS_SIZE = 1024\n","BG_COLOR = (24, 24, 24) # #181818\n","\n","# === Interactive Sliders ===\n","print(\"Adjust settings below, then run the next cell:\")\n","\n","border_slider = widgets.IntSlider(\n"," value=10, min=0, max=100, step=1,\n"," description='Border (px):',\n"," style={'description_width': 'initial'}\n",")\n","\n","radius_slider = widgets.IntSlider(\n"," value=30, min=0, max=200, step=1,\n"," description='Corner Radius (px):',\n"," style={'description_width': 'initial'}\n",")\n","\n","display(border_slider, radius_slider)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":135,"referenced_widgets":["903f51f8340e4ee8ad4b2fdee19209c1","659aa3a9509946409fb36b31cb4297d1","7b1c28abe8da4fa88b61b7b969670bdd","c37b743019054467b7f291c232b795eb","82f7fc12560c45139e4913522b26c283","08cf4eacb2024ffaa234b58363cd5a63"]},"id":"ytb7bz9zYIJL","executionInfo":{"status":"ok","timestamp":1761732167157,"user_tz":-60,"elapsed":1229,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"79cfc196-6ddc-4038-e8bd-cb9a8a53d3a9"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","Adjust settings below, then run the next cell:\n"]},{"output_type":"display_data","data":{"text/plain":["IntSlider(value=10, description='Border (px):', style=SliderStyle(description_width='initial'))"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"903f51f8340e4ee8ad4b2fdee19209c1"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["IntSlider(value=30, description='Corner Radius (px):', max=200, style=SliderStyle(description_width='initial')…"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"c37b743019054467b7f291c232b795eb"}},"metadata":{}}]},{"cell_type":"code","source":["# @title Run Processing (after setting sliders)\n","\n","border_size = border_slider.value\n","corner_radius = radius_slider.value\n","\n","print(f\"Using: Border = {border_size}px | Corner Radius = {corner_radius}px\")\n","\n","# Helper: Create rounded mask\n","def create_rounded_mask(size, radius):\n"," mask = Image.new('L', size, 0)\n"," draw = ImageDraw.Draw(mask)\n"," draw.rounded_rectangle([(0,0), size], radius, fill=255)\n"," return mask\n","\n","# Supported extensions\n","extensions = ('.jpg', '.jpeg', '.png', '.webp')\n","\n","with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n"," processed = 0\n","\n"," for filename in os.listdir(input_folder):\n"," if filename.lower().endswith(extensions):\n"," img_path = os.path.join(input_folder, filename)\n","\n"," try:\n"," with Image.open(img_path).convert(\"RGB\") as img:\n"," # --- Create canvas ---\n"," canvas = Image.new(\"RGB\", (CANVAS_SIZE, CANVAS_SIZE), BG_COLOR)\n","\n"," # --- Inner area size ---\n"," inner_size = CANVAS_SIZE - 2 * border_size\n"," if inner_size <= 0:\n"," print(f\"Skip {filename}: border too large\")\n"," continue\n","\n"," # --- Resize image to fit inner area ---\n"," img_resized = img.resize((inner_size, inner_size), Image.LANCZOS)\n","\n"," # --- Apply rounded corners ---\n"," if corner_radius > 0:\n"," radius = min(corner_radius, inner_size // 2)\n"," mask = create_rounded_mask((inner_size, inner_size), radius)\n"," rounded_img = Image.new(\"RGBA\", (inner_size, inner_size), (0,0,0,0))\n"," rounded_img.paste(img_resized, (0,0))\n"," rounded_img.putalpha(mask)\n"," # Convert back to RGB by compositing on gray\n"," final_inner = Image.new(\"RGB\", (inner_size, inner_size), BG_COLOR)\n"," final_inner.paste(rounded_img, (0,0), rounded_img)\n"," else:\n"," final_inner = img_resized\n","\n"," # --- Paste in center ---\n"," paste_x = border_size\n"," paste_y = border_size\n"," canvas.paste(final_inner, (paste_x, paste_y))\n","\n"," # --- Save ---\n"," output_name = f\"{Path(filename).stem}_1024_border{border_size}_r{corner_radius}.png\"\n"," output_path = os.path.join(output_folder, output_name)\n"," canvas.save(output_path, \"PNG\", optimize=True)\n","\n"," # --- Add to ZIP ---\n"," zipf.write(output_path, arcname=output_name)\n","\n"," print(f\"Created: {output_name}\")\n"," processed += 1\n","\n"," except Exception as e:\n"," print(f\"Error with {filename}: {e}\")\n","\n","print(f\"\\nFinished! {processed} images processed.\")\n","print(f\"Folder: {output_folder}\")\n","print(f\"ZIP: {zip_path}\")"],"metadata":{"id":"jBdlKK8JYvj4"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["##Enable T4"],"metadata":{"id":"t5YMAVEdnPtr"}},{"cell_type":"code","source":["# @title 1. Setup & Install rm_anime_bg (Fixed CLI Usage)\n","\n","# Install rm_anime_bg (GPU version for Colab; use [cpu] if needed)\n","!pip install -U 'rm_anime_bg[gpu]' -q\n","\n","from google.colab import drive\n","drive.mount('/content/drive')\n","\n","import os, random, zipfile, shutil, subprocess\n","from pathlib import Path\n","from PIL import Image\n","import numpy as np\n","import glob\n","\n","# === CONFIG ===\n","MANGA_ZIP = '/content/drive/MyDrive/hellsing_aesthetic_sorted/hellsing_001.zip'\n","BG_FOLDER = '/content/drive/MyDrive/backgrounds_final_rounded' # From previous step\n","MANGA_TEMP = '/content/manga_original'\n","MANGA_NOBG = '/content/manga_nobg'\n","OUTPUT_FOLDER = '/content/manga_on_bg_rmanime'\n","ZIP_OUTPUT = '/content/drive/MyDrive/manga_on_hellsing_backgrounds_rmanime.zip'\n","\n","# Unzip manga\n","!unzip -q \"$MANGA_ZIP\" -d /content/\n","\n","# Copy manga files to temp dir (CLI expects inputs there)\n","os.makedirs(MANGA_TEMP, exist_ok=True)\n","os.makedirs(MANGA_NOBG, exist_ok=True)\n","\n","# Find and copy numbered manga files\n","manga_files = sorted([f for f in os.listdir('/content') if f.endswith(('.jpg', '.jpeg', '.png')) and f[0].isdigit()])\n","for f in manga_files:\n"," shutil.copy(os.path.join('/content', f), os.path.join(MANGA_TEMP, f))\n","\n","print(f\"Extracted & copied {len(manga_files)} manga images to {MANGA_TEMP}\")\n","print(f\"Backgrounds folder: {BG_FOLDER}\")\n","print(f\"Output will be saved to: {ZIP_OUTPUT}\")"],"metadata":{"id":"vmhF9-a0nNOc"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @title 2. Process: Remove Anime BG (CLI) → Place on Random Background\n","\n","# === 1. Batch remove backgrounds with rm_anime_bg CLI ===\n","print(\"Removing backgrounds with rm_anime_bg CLI...\")\n","input_files = ' '.join(glob.glob(os.path.join(MANGA_TEMP, '*')))\n","cmd = f\"rm_anime_bg -o {MANGA_NOBG} {input_files}\"\n","result = subprocess.run(cmd, shell=True, capture_output=True, text=True)\n","if result.returncode != 0:\n"," print(f\"CLI Error: {result.stderr}\")\n","else:\n"," print(\"Background removal complete!\")\n","\n","# Load processed no-bg images (CLI outputs .png with alpha)\n","manga_nobg_files = sorted(glob.glob(os.path.join(MANGA_NOBG, '*.png')))\n","print(f\"Processed {len(manga_nobg_files)} no-bg manga images\")\n","\n","# === 2. Load backgrounds & classify ===\n","left_bgs = [os.path.join(BG_FOLDER, f) for f in os.listdir(BG_FOLDER) if '_left_' in f and f.endswith(('.png', '.jpg', '.jpeg'))]\n","right_bgs = [os.path.join(BG_FOLDER, f) for f in os.listdir(BG_FOLDER) if '_right_' in f and f.endswith(('.png', '.jpg', '.jpeg'))]\n","\n","print(f\"Found {len(left_bgs)} left-cropped backgrounds\")\n","print(f\"Found {len(right_bgs)} right-cropped backgrounds\")\n","\n","# === 3. Composite on random backgrounds ===\n","with zipfile.ZipFile(ZIP_OUTPUT, 'w', zipfile.ZIP_DEFLATED) as zipf:\n"," for idx, nobg_path in enumerate(manga_nobg_files, 1):\n"," try:\n"," # Open no-bg manga (RGBA)\n"," manga_nobg = Image.open(nobg_path).convert(\"RGBA\")\n","\n"," # Pick random background based on alignment\n"," align_left = random.choice([True, False])\n"," if align_left and left_bgs:\n"," bg_path = random.choice(left_bgs)\n"," elif not align_left and right_bgs:\n"," bg_path = random.choice(right_bgs)\n"," else:\n"," bg_path = random.choice(left_bgs + right_bgs) # fallback\n","\n"," with Image.open(bg_path).convert(\"RGBA\") as bg_img:\n"," bg = bg_img.copy()\n","\n"," # Resize manga to fit height of background\n"," target_h = bg.height\n"," ratio = target_h / manga_nobg.height\n"," new_w = int(manga_nobg.width * ratio)\n"," manga_resized = manga_nobg.resize((new_w, target_h), Image.LANCZOS)\n","\n"," # Align left or right\n"," if align_left:\n"," paste_x = 0\n"," align_desc = \"left\"\n"," else:\n"," paste_x = bg.width - manga_resized.width\n"," align_desc = \"right\"\n","\n"," # Paste with alpha\n"," bg.paste(manga_resized, (paste_x, 0), manga_resized)\n","\n"," # Save\n"," result_name = f\"hellsing_{idx:03d}_{align_desc}_rmanime.png\"\n"," result_path = os.path.join(OUTPUT_FOLDER, result_name)\n"," bg.convert(\"RGB\").save(result_path, \"PNG\")\n","\n"," # Add to ZIP\n"," zipf.write(result_path, result_name)\n","\n"," print(f\"{idx}/{len(manga_nobg_files)} → {result_name}\")\n","\n"," except Exception as e:\n"," print(f\"Error with {nobg_path}: {e}\")\n","\n","# Clean temp dirs\n","shutil.rmtree(MANGA_TEMP, ignore_errors=True)\n","shutil.rmtree(MANGA_NOBG, ignore_errors=True)\n","\n","print(f\"\\nAll done! ZIP saved to:\\n{ZIP_OUTPUT}\")\n","print(f\"Individual files in:\\n{OUTPUT_FOLDER}\")"],"metadata":{"id":"i1vYA6lznbCq"},"execution_count":null,"outputs":[]}]}
 
1
+ {"cells":[{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true},"id":"xe6KWSqr3y2_"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')\n","\n","import os\n","from PIL import Image\n","import zipfile\n","from pathlib import Path\n","\n","# === CONFIGURATION ===\n","input_folder = '/content/drive/MyDrive/backgrounds_raw'\n","output_folder = '/content/drive/MyDrive/backgrounds_cropped'\n","zip_path = '/content/drive/MyDrive/backgrounds_cropped_squares.zip'\n","frame_size = 1024 # Size of each square frame\n","step_size = 512 # Step size for sliding window (controls overlap)\n","pad_color = (24, 24, 24) # RGB for #181818\n","\n","# Create output folder\n","os.makedirs(output_folder, exist_ok=True)\n","\n","# Supported extensions\n","extensions = ('.jpg', '.jpeg', '.JPG', '.JPEG', '.webp', '.WEBP')\n","\n","# Initialize zip file\n","with zipfile.ZipFile(zip_path, 'w') as zipf:\n"," # Process each image\n"," for filename in os.listdir(input_folder):\n"," if filename.lower().endswith(extensions):\n"," img_path = os.path.join(input_folder, filename)\n","\n"," try:\n"," with Image.open(img_path) as img:\n"," img = img.convert('RGB') # Ensure image is in RGB format\n"," width, height = img.size\n","\n"," # Pad image if smaller than frame_size\n"," if width < frame_size or height < frame_size:\n"," new_width = max(width, frame_size)\n"," new_height = max(height, frame_size)\n"," padded_img = Image.new('RGB', (new_width, new_height), pad_color)\n"," # Center the original image on the padded canvas\n"," paste_x = (new_width - width) // 2\n"," paste_y = (new_height - height) // 2\n"," padded_img.paste(img, (paste_x, paste_y))\n"," img = padded_img\n"," width, height = img.size\n","\n"," # Calculate number of possible frames in x and y directions\n"," num_x = max(1, (width - frame_size) // step_size + 1)\n"," num_y = max(1, (height - frame_size) // step_size + 1)\n","\n"," frame_count = 0\n"," # Slide window across image\n"," for y in range(0, max(height - frame_size + 1, 1), step_size):\n"," for x in range(0, max(width - frame_size + 1, 1), step_size):\n"," # Ensure we don't go beyond image boundaries\n"," if x + frame_size <= width and y + frame_size <= height:\n"," # Crop frame\n"," frame = img.crop((x, y, x + frame_size, y + frame_size))\n"," frame_name = f\"{Path(filename).stem}_frame_{frame_count}.jpg\"\n"," frame_save_path = os.path.join(output_folder, frame_name)\n"," frame.save(frame_save_path, \"JPEG\", quality=100)\n"," zipf.write(frame_save_path, arcname=frame_name)\n"," frame_count += 1\n","\n"," print(f\"Processed: {filename} → {frame_count} frames\")\n","\n"," except Exception as e:\n"," print(f\"Error processing {filename}: {e}\")\n","\n","print(f\"\\nAll done! Cropped images saved in:\\n{output_folder}\")\n","print(f\"ZIP file created at:\\n{zip_path}\")"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":135,"referenced_widgets":["903f51f8340e4ee8ad4b2fdee19209c1","659aa3a9509946409fb36b31cb4297d1","7b1c28abe8da4fa88b61b7b969670bdd","c37b743019054467b7f291c232b795eb","82f7fc12560c45139e4913522b26c283","08cf4eacb2024ffaa234b58363cd5a63"]},"executionInfo":{"elapsed":1229,"status":"ok","timestamp":1761732167157,"user":{"displayName":"No Name","userId":"10578412414437288386"},"user_tz":-60},"id":"ytb7bz9zYIJL","outputId":"79cfc196-6ddc-4038-e8bd-cb9a8a53d3a9"},"outputs":[{"name":"stdout","output_type":"stream","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","Adjust settings below, then run the next cell:\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"903f51f8340e4ee8ad4b2fdee19209c1","version_major":2,"version_minor":0},"text/plain":["IntSlider(value=10, description='Border (px):', style=SliderStyle(description_width='initial'))"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"c37b743019054467b7f291c232b795eb","version_major":2,"version_minor":0},"text/plain":["IntSlider(value=30, description='Corner Radius (px):', max=200, style=SliderStyle(description_width='initial')…"]},"metadata":{},"output_type":"display_data"}],"source":["# @title # Rounded Background Composer (1024x1024)\n","\n","from google.colab import drive\n","drive.mount('/content/drive')\n","\n","import os\n","from PIL import Image, ImageDraw\n","import zipfile\n","from pathlib import Path\n","import ipywidgets as widgets\n","from IPython.display import display\n","\n","# === CONFIGURATION ===\n","input_folder = '/content/drive/MyDrive/backgrounds_cropped' # from previous step\n","output_folder = '/content/drive/MyDrive/backgrounds_final_rounded'\n","zip_path = '/content/drive/MyDrive/backgrounds_final_rounded.zip'\n","\n","os.makedirs(output_folder, exist_ok=True)\n","\n","CANVAS_SIZE = 1024\n","BG_COLOR = (24, 24, 24) # #181818\n","\n","# === Interactive Sliders ===\n","print(\"Adjust settings below, then run the next cell:\")\n","\n","border_slider = widgets.IntSlider(\n"," value=10, min=0, max=100, step=1,\n"," description='Border (px):',\n"," style={'description_width': 'initial'}\n",")\n","\n","radius_slider = widgets.IntSlider(\n"," value=30, min=0, max=200, step=1,\n"," description='Corner Radius (px):',\n"," style={'description_width': 'initial'}\n",")\n","\n","display(border_slider, radius_slider)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"jBdlKK8JYvj4"},"outputs":[],"source":["# @title Run Processing (after setting sliders)\n","\n","border_size = border_slider.value\n","corner_radius = radius_slider.value\n","\n","print(f\"Using: Border = {border_size}px | Corner Radius = {corner_radius}px\")\n","\n","# Helper: Create rounded mask\n","def create_rounded_mask(size, radius):\n"," mask = Image.new('L', size, 0)\n"," draw = ImageDraw.Draw(mask)\n"," draw.rounded_rectangle([(0,0), size], radius, fill=255)\n"," return mask\n","\n","# Supported extensions\n","extensions = ('.jpg', '.jpeg', '.png', '.webp')\n","\n","with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n"," processed = 0\n","\n"," for filename in os.listdir(input_folder):\n"," if filename.lower().endswith(extensions):\n"," img_path = os.path.join(input_folder, filename)\n","\n"," try:\n"," with Image.open(img_path).convert(\"RGB\") as img:\n"," # --- Create canvas ---\n"," canvas = Image.new(\"RGB\", (CANVAS_SIZE, CANVAS_SIZE), BG_COLOR)\n","\n"," # --- Inner area size ---\n"," inner_size = CANVAS_SIZE - 2 * border_size\n"," if inner_size <= 0:\n"," print(f\"Skip {filename}: border too large\")\n"," continue\n","\n"," # --- Resize image to fit inner area ---\n"," img_resized = img.resize((inner_size, inner_size), Image.LANCZOS)\n","\n"," # --- Apply rounded corners ---\n"," if corner_radius > 0:\n"," radius = min(corner_radius, inner_size // 2)\n"," mask = create_rounded_mask((inner_size, inner_size), radius)\n"," rounded_img = Image.new(\"RGBA\", (inner_size, inner_size), (0,0,0,0))\n"," rounded_img.paste(img_resized, (0,0))\n"," rounded_img.putalpha(mask)\n"," # Convert back to RGB by compositing on gray\n"," final_inner = Image.new(\"RGB\", (inner_size, inner_size), BG_COLOR)\n"," final_inner.paste(rounded_img, (0,0), rounded_img)\n"," else:\n"," final_inner = img_resized\n","\n"," # --- Paste in center ---\n"," paste_x = border_size\n"," paste_y = border_size\n"," canvas.paste(final_inner, (paste_x, paste_y))\n","\n"," # --- Save ---\n"," output_name = f\"{Path(filename).stem}_1024_border{border_size}_r{corner_radius}.png\"\n"," output_path = os.path.join(output_folder, output_name)\n"," canvas.save(output_path, \"PNG\", optimize=True)\n","\n"," # --- Add to ZIP ---\n"," zipf.write(output_path, arcname=output_name)\n","\n"," print(f\"Created: {output_name}\")\n"," processed += 1\n","\n"," except Exception as e:\n"," print(f\"Error with {filename}: {e}\")\n","\n","print(f\"\\nFinished! {processed} images processed.\")\n","print(f\"Folder: {output_folder}\")\n","print(f\"ZIP: {zip_path}\")"]},{"cell_type":"markdown","metadata":{"id":"BEoxbD0jGdcT"},"source":["##Randomly add manga panels to the newly created backgrounds using rembg"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":19792,"status":"ok","timestamp":1761831052316,"user":{"displayName":"No Name","userId":"10578412414437288386"},"user_tz":-60},"id":"q7QyuDEqGXuZ","outputId":"764f2d02-3914-4d29-936a-71564972d4a4"},"outputs":[{"output_type":"stream","name":"stdout","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","Manga images extracted to /content/\n","Backgrounds folder: /content/drive/MyDrive/backgrounds_final_rounded\n","Output will be saved to: /content/drive/MyDrive/manga_on_backgrounds_67196.zip\n"]}],"source":["# @title 1. Setup & Unzip Manga Images\n","\n","!pip install rembg pillow numpy onnxruntime -q\n","\n","from google.colab import drive\n","drive.mount('/content/drive')\n","\n","import os, random, zipfile, shutil\n","from pathlib import Path\n","from PIL import Image\n","import numpy as np\n","from rembg import remove\n","\n","# === CONFIG ===\n","MANGA_ZIP = '/content/drive/MyDrive/mia_panels_part_004.zip' #@param {type:'string'}\n","BG_FOLDER = '/content/drive/MyDrive/backgrounds_final_rounded' # From previous step\n","OUTPUT_FOLDER = '/content/manga_on_bg'\n","\n","# Generate a random 5-digit number\n","random_suffix = random.randint(10000, 99999) # 5 digits\n","ZIP_OUTPUT = f'/content/drive/MyDrive/manga_on_backgrounds_{random_suffix}.zip'\n","\n","# Unzip manga\n","!unzip -q \"$MANGA_ZIP\" -d /content/\n","\n","# Clean & recreate output\n","if os.path.exists(OUTPUT_FOLDER):\n"," shutil.rmtree(OUTPUT_FOLDER)\n","os.makedirs(OUTPUT_FOLDER, exist_ok=True)\n","\n","print(\"Manga images extracted to /content/\")\n","print(f\"Backgrounds folder: {BG_FOLDER}\")\n","print(f\"Output will be saved to: {ZIP_OUTPUT}\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"4QjqS42xCzIO"},"outputs":[],"source":["# @title 2. Process: Remove BG → Place on Random Background\n","\n","import os, random, zipfile\n","import numpy as np\n","from PIL import Image\n","from rembg import remove\n","\n","# ------------------------------------------------------------------\n","# 1. Load *all* background images (no left/right split)\n","# ------------------------------------------------------------------\n","all_bgs = [\n"," os.path.join(BG_FOLDER, f)\n"," for f in os.listdir(BG_FOLDER)\n"," if f.lower().endswith(('.png', '.jpg', '.jpeg'))\n","]\n","print(f\"Found {len(all_bgs)} background images (any side)\")\n","\n","# ------------------------------------------------------------------\n","# 2. Find all manga panels\n","# ------------------------------------------------------------------\n","manga_files = sorted(\n"," [f for f in os.listdir('/content')\n"," if f.lower().endswith(('.jpg', '.jpeg', '.png')) and f[0].isdigit()]\n",")\n","print(f\"Processing {len(manga_files)} manga images...\")\n","\n","# ------------------------------------------------------------------\n","# 3. Output ZIP\n","# ------------------------------------------------------------------\n","os.makedirs(OUTPUT_FOLDER, exist_ok=True)\n","\n","with zipfile.ZipFile(ZIP_OUTPUT, 'w', zipfile.ZIP_DEFLATED) as zipf:\n"," for idx, manga_name in enumerate(manga_files, 1):\n"," manga_path = os.path.join('/content', manga_name)\n","\n"," try:\n"," # ---- 1. Open manga & remove background ----\n"," with Image.open(manga_path).convert(\"RGBA\") as manga_img:\n"," manga_np = np.array(manga_img)\n"," output = remove(manga_np) # rembg magic\n"," manga_nobg = Image.fromarray(output).convert(\"RGBA\")\n","\n"," # ---- 2. Pick a *random* background (any side) ----\n"," bg_path = random.choice(all_bgs)\n"," with Image.open(bg_path).convert(\"RGBA\") as bg_img:\n"," bg = bg_img.copy()\n","\n"," # ---- 3. Resize manga to the height of the background ----\n"," target_h = bg.height\n"," ratio = target_h / manga_nobg.height\n"," new_w = int(manga_nobg.width * ratio)\n"," manga_resized = manga_nobg.resize((new_w, target_h), Image.LANCZOS)\n","\n"," # ---- 4. Randomly place on LEFT or RIGHT ----\n"," place_left = random.choice([True, False])\n"," if place_left:\n"," paste_x = 0\n"," align_desc = \"left\"\n"," else:\n"," paste_x = bg.width - manga_resized.width\n"," align_desc = \"right\"\n","\n"," # Paste\n"," bg.paste(manga_resized, (paste_x, 0), manga_resized)\n","\n"," # ---- 5. Save & zip ----\n"," result_name = f\"{idx:03d}_{align_desc}.png\"\n"," result_path = os.path.join(OUTPUT_FOLDER, result_name)\n"," bg.convert(\"RGB\").save(result_path, \"PNG\")\n","\n"," zipf.write(result_path, result_name)\n","\n"," print(f\"{idx}/{len(manga_files)} → {result_name}\")\n","\n"," except Exception as e:\n"," print(f\"Error with {manga_name}: {e}\")\n","\n","print(f\"\\nAll done! ZIP saved to:\\n{ZIP_OUTPUT}\")\n","print(f\"Individual files in:\\n{OUTPUT_FOLDER}\")"]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/dataset_builder.ipynb","timestamp":1761823511544},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1761731354034},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1761124521078},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760628088876},{"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"},"widgets":{"application/vnd.jupyter.widget-state+json":{"08cf4eacb2024ffaa234b58363cd5a63":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"SliderStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"SliderStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":"initial","handle_color":null}},"659aa3a9509946409fb36b31cb4297d1":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"7b1c28abe8da4fa88b61b7b969670bdd":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"SliderStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"SliderStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":"initial","handle_color":null}},"82f7fc12560c45139e4913522b26c283":{"model_module":"@jupyter-widgets/base","model_module_version":"1.2.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"903f51f8340e4ee8ad4b2fdee19209c1":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"IntSliderModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"IntSliderModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"IntSliderView","continuous_update":true,"description":"Border (px):","description_tooltip":null,"disabled":false,"layout":"IPY_MODEL_659aa3a9509946409fb36b31cb4297d1","max":100,"min":0,"orientation":"horizontal","readout":true,"readout_format":"d","step":1,"style":"IPY_MODEL_7b1c28abe8da4fa88b61b7b969670bdd","value":10}},"c37b743019054467b7f291c232b795eb":{"model_module":"@jupyter-widgets/controls","model_module_version":"1.5.0","model_name":"IntSliderModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"IntSliderModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"IntSliderView","continuous_update":true,"description":"Corner Radius (px):","description_tooltip":null,"disabled":false,"layout":"IPY_MODEL_82f7fc12560c45139e4913522b26c283","max":200,"min":0,"orientation":"horizontal","readout":true,"readout_format":"d","step":1,"style":"IPY_MODEL_08cf4eacb2024ffaa234b58363cd5a63","value":30}}}}},"nbformat":4,"nbformat_minor":0}