diff --git "a/fetch_from_reddit.ipynb" "b/fetch_from_reddit.ipynb"
--- "a/fetch_from_reddit.ipynb"
+++ "b/fetch_from_reddit.ipynb"
@@ -1 +1,3088 @@
-{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"_gXEa0VE88VQ"},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"markdown","source":["# 🚀 Authenticate credentials for Reddit PRAW into Google colab Secrets"],"metadata":{"id":"gSErGKBctoAc"}},{"cell_type":"markdown","source":["\n","\n","**One-time setup** — after this, your notebook will automatically load Reddit credentials without prompts or hard-coded secrets.\n","\n","---\n","\n","### Step 1: Create Your Reddit “Script” App\n","1. Go to: **[https://www.reddit.com/prefs/apps](https://www.reddit.com/prefs/apps)** (log in first)\n","2. Scroll to the bottom → click **“create another app”** (or **“create app”**)\n","3. Fill the form:\n"," - **Name**: `Colab-PRAW-Script` (or any name you like)\n"," - **App type**: Select **script** ← very important\n"," - **Description**: (optional)\n"," - **Redirect URI**: `http://localhost:8080`\n","4. Click **Create app**\n","\n","You will now see:\n","- **personal use script** → 14-character string → **REDDIT_CLIENT_ID**\n","- **secret** → long string → **REDDIT_CLIENT_SECRET**\n","\n","Copy both values.\n","\n","---\n","\n","### Step 2: Choose Your User-Agent\n","Use this format (replace `yourusername` with your actual Reddit username):"],"metadata":{"id":"rst5O8t0tW7F"}},{"cell_type":"markdown","source":[""],"metadata":{"id":"rQPyne1Hr_CM"}},{"cell_type":"markdown","source":["This will be your **REDDIT_USER_AGENT**.\n","\n","---\n","\n","### Step 3: Add Secrets in Google Colab\n","1. Open your Colab notebook\n","2. In the left sidebar click the **🔑 Secrets** tab\n","3. Click **+ Add new secret** for each of these:\n","\n","| Secret Name | What to paste |\n","|------------------------|----------------------------------------------------|\n","| `REDDIT_CLIENT_ID` | 14-character string from Reddit |\n","| `REDDIT_CLIENT_SECRET` | The secret string from Reddit |\n","| `REDDIT_USER_AGENT` | `Colab-PRAW:v1.0 (by u/yourusername)` |\n","| `REDDIT_USERNAME` | Your Reddit username (no `u/`) |\n","| `REDDIT_PASSWORD` | Your Reddit account password |\n","\n","After each one, click **Add** and **Grant access** when prompted.\n","\n","---"],"metadata":{"id":"d4ikd1h7tbr5"}},{"cell_type":"code","source":["#@markdown **Reddit PRAW Authentication with Colab Secrets**\n","\n","# Install PRAW (run once)\n","!pip install praw -q\n","\n","import praw\n","from google.colab import userdata\n","import getpass\n","\n","# === AUTHENTICATION (uses secrets first, falls back to prompt if missing) ===\n","def get_secret_or_prompt(key, prompt_text):\n"," try:\n"," return userdata.get(key)\n"," except (KeyError, Exception):\n"," return getpass.getpass(prompt_text)\n","\n","reddit = praw.Reddit(\n"," client_id=get_secret_or_prompt(\"REDDIT_CLIENT_ID\", \"Enter your REDDIT_CLIENT_ID: \"),\n"," client_secret=get_secret_or_prompt(\"REDDIT_CLIENT_SECRET\", \"Enter your REDDIT_CLIENT_SECRET: \"),\n"," user_agent=get_secret_or_prompt(\"REDDIT_USER_AGENT\", \"Enter your REDDIT_USER_AGENT: \"),\n"," username=get_secret_or_prompt(\"REDDIT_USERNAME\", \"Enter your REDDIT_USERNAME: \"),\n"," password=get_secret_or_prompt(\"REDDIT_PASSWORD\", \"Enter your REDDIT_PASSWORD: \"),\n",")\n","\n","# Quick verification\n","print(\"✅ Successfully logged in as:\", reddit.user.me())\n","print(\"🔒 Read-only mode:\", reddit.read_only)"],"metadata":{"cellView":"form","id":"WLopd-NFtHwY","executionInfo":{"status":"ok","timestamp":1776537917357,"user_tz":-120,"elapsed":14324,"user":{"displayName":"","userId":""}},"outputId":"237c20c7-0aa3-41e8-ec14-7f8b843b55e0","colab":{"base_uri":"https://localhost:8080/"}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/189.3 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m189.3/189.3 kB\u001b[0m \u001b[31m12.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h"]},{"output_type":"stream","name":"stderr","text":["WARNING:praw:It appears that you are using PRAW in an asynchronous environment.\n","It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.\n","See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.\n","\n"]},{"output_type":"stream","name":"stdout","text":["✅ Successfully logged in as: MoreAd2538\n","🔒 Read-only mode: False\n"]}]},{"cell_type":"markdown","metadata":{"id":"V5i2-xwTGG4K"},"source":["#🚀 Fetch content from Reddit"]},{"cell_type":"markdown","source":["# Image crop left rigt"],"metadata":{"id":"WX17R9Yc6U1A"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"-ewlMjrTga21","cellView":"form"},"outputs":[],"source":["# === INTEGRATED REDDIT DOWNLOADER + MEDIA EXTRACTOR (Drive + Checkboxes + Sliders Edition) ===\n","# Replace BOTH of your previous cells with this single block and run it.\n","# All results (titles, links, images, frames, zips) are saved directly to your Google Drive.\n","# Images/frames are numbered sequentially (1.jpeg, 2.jpeg, ...) with optional paired .txt files.\n","\n","# @markdown ** Subreddit & Fetch Settings**\n","subreddit_name = \"celebnsfw\" # @param {type:\"string\"}\n","sort_method = \"new\" # @param [\"hot\", \"new\", \"top\"] {type:\"string\"}\n","num_posts_to_pull = 100 # @param {type:\"slider\", min:0, max:2000, step:100}\n","offset_index = 0 # @param {type:\"slider\", min:0, max:2000, step:100}\n","\n","# @markdown **✅ Functionality Checkboxes (select any combination)**\n","thumbnail_low_res = True # @param {type:\"boolean\"}\n","#1) Thumbnail download at low res\n","proper_image_download = False # @param {type:\"boolean\"}\n","#2) Proper image download including sub images in galleries\n","gif_frame_extraction = False # @param {type:\"boolean\"}\n","#3) GIF + RedGifs video → keyframe extraction (original files are NEVER saved)\n","combined_titles_txt = True # @param {type:\"boolean\"}\n","#4) Combined txt file of titles\n","pair_txt_with_media = False # @param {type:\"boolean\"}\n","#5) Adding txt files to saved images in zips as enumerated pairs (1.txt, 2.txt, ...)\n","debug_mode = False # @param {type:\"boolean\"}\n","#6) Enable detailed debug printouts during media processing\n","\n","import os\n","import shutil\n","import glob\n","import requests\n","import subprocess\n","from google.colab import files, drive\n","\n","if gif_frame_extraction:\n"," # Install yt-dlp if it's not already installed (moved outside conditional block)\n"," !pip install -q yt-dlp\n"," import yt_dlp\n","\n","\n","# ========================== DRIVE SETUP ==========================\n","print(\" Mounting Google Drive...\")\n","drive.mount('/content/drive', force_remount=False)\n","\n","drive_base_dir = f\"/content/drive/MyDrive/{subreddit_name}_reddit_downloads\"\n","os.makedirs(drive_base_dir, exist_ok=True)\n","\n","# Local temp media storage (Not on Drive)\n","local_media_dir = f\"/content/temp_output/{subreddit_name}_media\"\n","if os.path.exists(local_media_dir): shutil.rmtree(local_media_dir)\n","os.makedirs(local_media_dir, exist_ok=True)\n","\n","local_output_dir = \"/content/output\"\n","os.makedirs(local_output_dir, exist_ok=True)\n","\n","print(f\" Individual images stay local; only Zips/Txt go to: {drive_base_dir}\")\n","\n","# ========================== FETCH POSTS ==========================\n","print(f\" Fetching up to {num_posts_to_pull} posts from r/{subreddit_name} ({sort_method} sorting, offset {offset_index})...\")\n","\n","sub = reddit.subreddit(subreddit_name)\n","\n","if sort_method == \"hot\":\n"," iterator = sub.hot(limit=offset_index + num_posts_to_pull + 50)\n","elif sort_method == \"new\":\n"," iterator = sub.new(limit=offset_index + num_posts_to_pull + 50)\n","elif sort_method == \"top\":\n"," iterator = sub.top(limit=offset_index + num_posts_to_pull + 50)\n","else:\n"," iterator = sub.hot(limit=offset_index + num_posts_to_pull + 50)\n","\n","all_posts = list(iterator)\n","posts = all_posts[offset_index : offset_index + num_posts_to_pull]\n","\n","print(f\"✅ Successfully fetched {len(posts)} posts.\")\n","\n","# === NEW: Filename suffix with actual fetched count + offset ===\n","fetch_suffix = f\"_{len(posts)}posts_offset{offset_index}\"\n","\n","titles = []\n","external_links = []\n","\n","for submission in posts:\n"," cleaned_title = (submission.title\n"," .replace('^', '').replace('{', '').replace('}', '').replace('|', '')\n"," .replace('[','').replace(']','').replace('\"',''))\n"," titles.append(cleaned_title)\n","\n"," url = getattr(submission, 'url', None)\n"," if (url and url.startswith(('http://', 'https://')) and\n"," not any(domain in url for domain in ['reddit.com', 'redd.it'])):\n"," external_links.append(url)\n","\n","# ========================== OPTION 4: Combined Titles TXT ==========================\n","if combined_titles_txt:\n"," combined_content = '{' + '|'.join(titles) + '}'\n"," titles_file_drive = f\"{drive_base_dir}/{subreddit_name}_titles{fetch_suffix}.txt\"\n"," with open(titles_file_drive, \"w\", encoding=\"utf-8\") as f:\n"," f.write(combined_content)\n"," print(f\" Combined titles saved → {titles_file_drive}\")\n","\n","# ========================== External Links ==========================\n","if external_links:\n"," links_file = f\"{drive_base_dir}/{subreddit_name}_links{fetch_suffix}.txt\"\n"," with open(links_file, \"w\", encoding=\"utf-8\") as f:\n"," for link in external_links: f.write(link + \"\\n\")\n"," print(f\" External links saved → {links_file}\")\n"," print(f\" → {len(external_links)} links (mostly RedGifs)\")\n","\n","# ========================== MEDIA PROCESSING ==========================\n","any_media = thumbnail_low_res or proper_image_download or gif_frame_extraction\n","\n","if any_media:\n","\n"," temp_dir = \"/content/temp_download\"\n"," os.makedirs(temp_dir, exist_ok=True)\n","\n"," global_counter = 1\n","\n"," def save_media_and_txt(source, is_url=False, title=\"\"):\n"," global global_counter\n"," if is_url:\n"," clean_url = source.split('?')[0]\n"," ext = os.path.splitext(clean_url)[1].lower()\n"," if ext not in ['.jpg', '.jpeg', '.png']: ext = '.jpg'\n"," temp_file = f\"{temp_dir}/dl_{global_counter}{ext}\"\n"," try:\n"," r = requests.get(source, stream=True, timeout=60)\n"," r.raise_for_status()\n"," with open(temp_file, 'wb') as f:\n"," for chunk in r.iter_content(8192): f.write(chunk)\n"," except Exception:\n"," return\n"," else:\n"," temp_file = source\n"," ext = os.path.splitext(temp_file)[1].lower() or '.jpeg'\n","\n"," local_path = f\"{local_media_dir}/{global_counter}{ext}\"\n"," shutil.copy2(temp_file, local_path)\n","\n"," if pair_txt_with_media:\n"," with open(f\"{local_media_dir}/{global_counter}.txt\", \"w\", encoding=\"utf-8\") as f:\n"," f.write(title)\n","\n"," global_counter += 1\n"," print(f\" ✅ Saved locally #{global_counter-1} \", end=\"\\r\")\n"," if is_url and os.path.exists(temp_file): os.remove(temp_file)\n","\n"," for idx, submission in enumerate(posts, 1):\n"," cleaned_title = titles[idx-1]\n","\n"," if thumbnail_low_res:\n"," thumb_url = getattr(submission, 'thumbnail', None)\n"," if thumb_url and thumb_url.startswith('http'):\n"," save_media_and_txt(thumb_url, is_url=True, title=cleaned_title)\n","\n"," if proper_image_download:\n"," url = getattr(submission, 'url', None)\n"," if url and any(url.lower().endswith(e) for e in ['.jpg', '.jpeg', '.png']):\n"," save_media_and_txt(url, is_url=True, title=cleaned_title)\n","\n"," # === GIF + RedGifs keyframe extraction (debug toggleable) ===\n"," if gif_frame_extraction:\n"," url = getattr(submission, 'url', None)\n"," if url and url.startswith(('http://', 'https://')):\n"," if debug_mode:\n"," print(f\"\u001f DEBUG [{idx:03d}]: Checking URL → {url[:90]}...\")\n","\n"," if url.lower().endswith('.gif') or 'redgifs.com' in url.lower():\n"," if debug_mode:\n"," print(f\"✅ DEBUG: Eligible for keyframe extraction → {url[:90]}...\")\n"," temp_media = None\n"," try:\n"," # 1. Download\n"," if url.lower().endswith('.gif'):\n"," temp_media = f\"{temp_dir}/dl_gif_{idx}.gif\"\n"," r = requests.get(url, stream=True, timeout=60)\n"," r.raise_for_status()\n"," with open(temp_media, 'wb') as f:\n"," for chunk in r.iter_content(8192):\n"," f.write(chunk)\n"," if debug_mode:\n"," print(f\" ↓ Downloaded GIF ({os.path.getsize(temp_media)/1024/1024:.1f} MB)\")\n"," else:\n"," # RedGifs video\n"," temp_media = f\"{temp_dir}/dl_video_{idx}.mp4\"\n"," ydl_opts = {\n"," 'outtmpl': temp_media,\n"," 'quiet': True,\n"," 'no_warnings': True,\n"," 'format': 'bestvideo+bestaudio/best',\n"," 'merge_output_format': 'mp4',\n"," }\n"," with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n"," ydl.download([url])\n"," if debug_mode:\n"," print(f\" ↓ Downloaded RedGifs video ({os.path.getsize(temp_media)/1024/1024:.1f} MB)\")\n","\n"," # 2. Keyframe extraction\n"," output_pattern = f\"{temp_dir}/kf_{idx}_%04d.jpg\"\n"," cmd = [\n"," 'ffmpeg', '-y', '-i', temp_media,\n"," '-vf', \"select='gt(scene,0.15)',setpts=N/(FRAME_RATE*TB)\",\n"," '-vsync', 'vfr',\n"," '-q:v', '5',\n"," output_pattern\n"," ]\n"," subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)\n"," if debug_mode:\n"," print(f\" 🏆 ffmpeg keyframe extraction finished (scene threshold 0.15)\")\n","\n"," # 3. Save keyframes\n"," extracted_frames = sorted(glob.glob(f\"{temp_dir}/kf_{idx}_*.jpg\"))\n"," if debug_mode:\n"," print(f\" 📎 Extracted {len(extracted_frames)} keyframes → saving to ZIP\")\n","\n"," for frame_path in extracted_frames:\n"," save_media_and_txt(frame_path, is_url=False, title=cleaned_title)\n"," os.remove(frame_path)\n","\n"," # 4. Cleanup original\n"," if temp_media and os.path.exists(temp_media):\n"," os.remove(temp_media)\n"," if debug_mode:\n"," print(f\" 🗑️ Cleaned up original media file\")\n","\n"," except Exception as e:\n"," if debug_mode:\n"," print(f\" ⚠️ ERROR processing {url[:80]}... → {e}\")\n"," if temp_media and os.path.exists(temp_media):\n"," os.remove(temp_media)\n"," continue\n","\n"," print(f\"\\n\\n✅ MEDIA CACHED! Creating ZIP on Drive...\")\n"," zip_name = f\"{subreddit_name}_media{fetch_suffix}\"\n"," shutil.make_archive(f\"{drive_base_dir}/{zip_name}\", 'zip', local_media_dir)\n"," print(f\" ZIP created on Drive → {drive_base_dir}/{zip_name}.zip\")\n","\n","print(\"\\n✨ ALL DONE!\")"]},{"cell_type":"markdown","metadata":{"id":"3b94280b"},"source":["### 🖼️ Image Cropper: 1024x1024 Left and Right Aligned"]},{"cell_type":"code","metadata":{"id":"d3ca4317"},"source":["from google.colab import drive\n","from PIL import Image\n","import os\n","import shutil\n","import glob\n","import zipfile\n","\n","# @markdown **Configuration**\n","input_image_directory = \"/content\" # @param {type:\"string\"}\n","output_drive_folder = \"cropped_1024x1024_images\" # @param {type:\"string\"}\n","target_size = 1024 # @param {type:\"integer\"}\n","resize_smaller_images = True # @param {type:\"boolean\"}\n","\n","# Mount Google Drive\n","print(\"🔄 Mounting Google Drive...\")\n","drive.mount('/content/drive', force_remount=True)\n","\n","# Define output paths\n","drive_base_path = '/content/drive/MyDrive'\n","drive_output_folder_path = os.path.join(drive_base_path, output_drive_folder)\n","\n","# Create a temporary local directory for cropped images before zipping\n","local_temp_crop_dir = '/content/temp_cropped_images'\n","os.makedirs(local_temp_crop_dir, exist_ok=True)\n","\n","print(f\"\\n🔍 Scanning for images in {input_image_directory}...\")\n","image_files = []\n","for ext in ('*.png', '*.jpg', '*.jpeg', '*.webp'):\n"," image_files.extend(glob.glob(os.path.join(input_image_directory, ext)))\n","\n","if not image_files:\n"," print(f\"❌ No image files found in {input_image_directory}. Please ensure images are present or check the directory path.\")\n","else:\n"," print(f\"✅ Found {len(image_files)} image(s) to process.\")\n"," processed_count = 0\n"," skipped_count = 0\n","\n"," for file_path in image_files:\n"," filename = os.path.basename(file_path)\n"," print(f\"\\nProcessing {filename}...\")\n"," try:\n"," img = Image.open(file_path)\n","\n"," if img.mode != 'RGB':\n"," img = img.convert('RGB')\n","\n"," width, height = img.size\n","\n"," if width < target_size or height < target_size:\n"," if resize_smaller_images:\n"," print(f\"⚠️ Image dimensions ({width}x{height}) are smaller than target {target_size}x{target_size}. Resizing...\")\n"," if width < height:\n"," new_width = target_size\n"," new_height = int(height * (target_size / width))\n"," else:\n"," new_height = target_size\n"," new_width = int(width * (target_size / height))\n"," img = img.resize((new_width, new_height), Image.LANCZOS)\n"," width, height = img.size\n"," print(f\" Resized to {width}x{height}.\")\n"," else:\n"," print(f\"⚠️ Skipping {filename}: Image dimensions ({width}x{height}) are smaller than target {target_size}x{target_size}.\")\n"," skipped_count += 1\n"," continue\n","\n"," # --- Left-aligned crop ---\n"," left_crop_box = (0, 0, target_size, target_size)\n"," img_left_cropped = img.crop(left_crop_box)\n"," output_name_left = f\"{os.path.splitext(filename)[0]}_left_{target_size}x{target_size}.jpg\"\n"," img_left_cropped.save(os.path.join(local_temp_crop_dir, output_name_left))\n"," print(f\" ✅ Saved left-aligned crop to temp: {output_name_left}\")\n","\n"," # --- Right-aligned crop ---\n"," right_x_start = width - target_size\n"," right_crop_box = (right_x_start, 0, width, target_size)\n"," img_right_cropped = img.crop(right_crop_box)\n"," output_name_right = f\"{os.path.splitext(filename)[0]}_right_{target_size}x{target_size}.jpg\"\n"," img_right_cropped.save(os.path.join(local_temp_crop_dir, output_name_right))\n"," print(f\" ✅ Saved right-aligned crop to temp: {output_name_right}\")\n","\n"," processed_count += 1\n","\n"," except Exception as e:\n"," print(f\"❌ Error processing {filename}: {e}\")\n"," skipped_count += 1\n","\n"," print(f\"\\n✨ Processing complete! {processed_count} images processed, {skipped_count} skipped.\")\n","\n"," # Create ZIP file\n"," if processed_count > 0:\n"," os.makedirs(drive_output_folder_path, exist_ok=True)\n"," zip_filename = f\"{output_drive_folder}.zip\"\n"," zip_path_on_drive = os.path.join(drive_output_folder_path, zip_filename)\n","\n"," print(f\"\\n📦 Creating ZIP file '{zip_filename}' in Google Drive...\")\n"," shutil.make_archive(os.path.join(drive_output_folder_path, output_drive_folder), 'zip', local_temp_crop_dir)\n"," print(f\"✅ All cropped images zipped and saved to: {zip_path_on_drive}\")\n"," else:\n"," print(\"No images were processed to be zipped.\")\n","\n"," # Clean up local temporary directory\n"," shutil.rmtree(local_temp_crop_dir)\n"," print(\"🗑️ Cleaned up local temporary cropped images directory.\")\n"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"qisU9VeIyzX2"},"source":["# 🎮 itch.io (Indie Game Website) fetch"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"HDCueX6d3K00","cellView":"form"},"outputs":[],"source":["#@markdown # 🐙 itch.io Image-Text Dataset Creator\n","#@markdown **Fetch enumerated thumbnails + matching TXT files → ZIP → Google Drive**\n","\n","#@markdown ---\n","#@markdown ### 📋 Choose your settings below then **Run this cell**\n","\n","num_games = 1000 #@param {type:\"slider\", min:10, max:5000, step:10, description:\"How many games to fetch\"}\n","\n","sort_by = \"Most Recent\" #@param [\"Popular (default)\", \"New & Popular\", \"Top Sellers\", \"Top Rated\", \"Most Recent\"]\n","\n","subcategory = \"None (All Games)\" #@param [\"None (All Games)\", \"Genre: Action\", \"Genre: Adventure\", \"Genre: Arcade\", \"Genre: Card Game\", \"Genre: Educational\", \"Genre: Fighting\", \"Genre: Platformer\", \"Genre: Puzzle\", \"Genre: RPG\", \"Genre: Shooter\", \"Genre: Simulation\", \"Genre: Strategy\", \"Genre: Visual Novel\", \"Platform: Web\", \"Platform: Windows\", \"Platform: macOS\", \"Platform: Linux\", \"Platform: Android\", \"Tag: 2D\", \"Tag: Pixel Art\", \"Tag: Horror\", \"Tag: Multiplayer\", \"Tag: Roguelike\", \"Tag: Retro\"]\n","\n","#@markdown ---\n","\n","#@markdown **After changing the values above, just click the ▶️ Run button on this cell.**\n","\n","# ================================================\n","# ✅ READY-TO-RUN COLAB CELL (single cell version)\n","# ================================================\n","\n","import requests\n","from bs4 import BeautifulSoup\n","import os\n","import re\n","import json\n","import time\n","import shutil\n","import datetime\n","from urllib.parse import urljoin\n","from IPython.display import display, HTML, Image\n","from google.colab import drive\n","\n","print(\"✅ Starting itch.io scraper with your chosen settings...\")\n","\n","# ====================== MAP USER CHOICES TO URL SLUGS ======================\n","sort_map = {\n"," \"Popular (default)\": \"\",\n"," \"New & Popular\": \"new-and-popular\",\n"," \"Top Sellers\": \"top-sellers\",\n"," \"Top Rated\": \"top-rated\",\n"," \"Most Recent\": \"newest\"\n","}\n","\n","filter_map = {\n"," \"None (All Games)\": \"\",\n"," \"Genre: Action\": \"genre-action\",\n"," \"Genre: Adventure\": \"genre-adventure\",\n"," \"Genre: Arcade\": \"genre-arcade\",\n"," \"Genre: Card Game\": \"genre-card-game\",\n"," \"Genre: Educational\": \"genre-educational\",\n"," \"Genre: Fighting\": \"genre-fighting\",\n"," \"Genre: Platformer\": \"genre-platformer\",\n"," \"Genre: Puzzle\": \"genre-puzzle\",\n"," \"Genre: RPG\": \"genre-rpg\",\n"," \"Genre: Shooter\": \"genre-shooter\",\n"," \"Genre: Simulation\": \"genre-simulation\",\n"," \"Genre: Strategy\": \"genre-strategy\",\n"," \"Genre: Visual Novel\": \"genre-visual-novel\",\n"," \"Platform: Web\": \"platform-web\",\n"," \"Platform: Windows\": \"platform-windows\",\n"," \"Platform: macOS\": \"platform-macos\",\n"," \"Platform: Linux\": \"platform-linux\",\n"," \"Platform: Android\": \"platform-android\",\n"," \"Tag: 2D\": \"tag-2d\",\n"," \"Tag: Pixel Art\": \"tag-pixel-art\",\n"," \"Tag: Horror\": \"tag-horror\",\n"," \"Tag: Multiplayer\": \"tag-multiplayer\",\n"," \"Tag: Roguelike\": \"tag-roguelike\",\n"," \"Tag: Retro\": \"tag-retro\"\n","}\n","\n","sort_slug = sort_map[sort_by]\n","filter_slug = filter_map[subcategory]\n","\n","# ====================== CONFIG ======================\n","MAX_PAGES = 20\n","DELAY_BETWEEN_PAGES = 1.5\n","HEADERS = {\n"," \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n"," \"(KHTML, like Gecko) Chrome/134.0 Safari/537.36\"\n","}\n","\n","# Build the base URL according to user selections\n","base_url = \"https://itch.io/games\"\n","if sort_slug:\n"," base_url += f\"/{sort_slug}\"\n","if filter_slug:\n"," base_url += f\"/{filter_slug}\"\n","\n","print(f\"🌐 Target: {base_url} | Fetching up to {num_games} games\")\n","\n","# Mount Google Drive\n","print(\"🔄 Mounting Google Drive...\")\n","drive.mount('/content/drive', force_remount=True)\n","\n","# Create working folder\n","dataset_dir = \"/content/itch_dataset\"\n","os.makedirs(dataset_dir, exist_ok=True)\n","\n","# ====================== SCRAPE MULTIPLE PAGES ======================\n","pairs = []\n","page = 1\n","\n","while len(pairs) < num_games and page <= MAX_PAGES:\n"," url = f\"{base_url}?page={page}\" if page > 1 else base_url\n"," print(f\"📄 Scraping page {page} → {url}\")\n","\n"," try:\n"," response = requests.get(url, headers=HEADERS, timeout=20)\n"," if response.status_code != 200:\n"," print(f\"❌ Page {page} failed (HTTP {response.status_code})\")\n"," break\n","\n"," soup = BeautifulSoup(response.text, \"html.parser\")\n"," game_cells = soup.find_all(\"div\", class_=\"game_cell\")\n","\n"," if not game_cells:\n"," print(\"✅ No more games on this page.\")\n"," break\n","\n"," added = 0\n"," for cell in game_cells:\n"," if len(pairs) >= num_games:\n"," break\n","\n"," # Clean title (no price spam)\n"," title_tag = cell.find(\"div\", class_=\"game_title\")\n"," if not title_tag:\n"," continue\n"," title_link = title_tag.find(\"a\", class_=\"title\")\n"," title = title_link.get_text(strip=True) if title_link else title_tag.get_text(strip=True).split(\"$\")[0].strip()\n"," if not title:\n"," continue\n","\n"," # Extract thumbnail (robust for current itch.io layout)\n"," img_url = None\n"," img_tag = cell.find(\"img\")\n"," if img_tag:\n"," for attr in [\"data-lazy-src\", \"data-lazy_src\", \"data-src\", \"src\"]:\n"," img_url = img_tag.get(attr)\n"," if img_url:\n"," break\n"," if not img_url and img_tag.get(\"srcset\"):\n"," img_url = img_tag.get(\"srcset\").split(\",\")[0].strip().split(\" \")[0]\n","\n"," # Fallback: background-image\n"," if not img_url:\n"," for el in cell.find_all(lambda t: t.has_attr(\"style\") and \"background-image\" in t.get(\"style\", \"\").lower()):\n"," style = el.get(\"style\", \"\")\n"," match = re.search(r'background-image\\s*:\\s*url\\([\\'\\\"]?([^\\'\\\"]+)[\\'\\\"]?\\)', style, re.IGNORECASE)\n"," if match:\n"," img_url = match.group(1)\n"," break\n","\n"," if img_url:\n"," if img_url.startswith(\"//\"):\n"," img_url = \"https:\" + img_url\n"," elif not img_url.startswith((\"http://\", \"https://\")):\n"," img_url = urljoin(\"https://itch.io\", img_url)\n","\n"," pairs.append((title, img_url))\n"," added += 1\n","\n"," print(f\" → Added {added} games (total so far: {len(pairs)})\")\n","\n"," except Exception as e:\n"," print(f\"❌ Error on page {page}: {e}\")\n"," break\n","\n"," page += 1\n"," time.sleep(DELAY_BETWEEN_PAGES)\n","\n","if not pairs:\n"," print(\"❌ No games found with current filters. Try different settings.\")\n","else:\n"," print(f\"\\n✅ Collected {len(pairs)} games. Downloading images and creating TXT files...\")\n","\n"," # ====================== DOWNLOAD ENUMERATED FILES ======================\n"," downloaded = 0\n"," for idx, (title, img_url) in enumerate(pairs, start=1):\n"," num_str = f\"{idx:04d}\"\n"," img_path = f\"{dataset_dir}/{num_str}.jpg\"\n"," txt_path = f\"{dataset_dir}/{num_str}.txt\"\n","\n"," try:\n"," img_response = requests.get(img_url, headers=HEADERS, timeout=15)\n"," if img_response.status_code == 200:\n"," with open(img_path, \"wb\") as f:\n"," f.write(img_response.content)\n"," with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(title)\n"," downloaded += 1\n"," if downloaded % 10 == 0 or downloaded == len(pairs):\n"," print(f\" ✅ Saved {downloaded:04d}.jpg + {num_str}.txt\")\n"," else:\n"," print(f\"⚠️ Failed to download image {num_str}\")\n"," except Exception as e:\n"," print(f\"❌ Error downloading {num_str}: {e}\")\n","\n"," # ====================== CREATE ZIP & SAVE TO DRIVE ======================\n"," timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n"," zip_name = f\"itch_games_{timestamp}\"\n"," zip_path_local = f\"/content/{zip_name}.zip\"\n","\n"," print(f\"\\n🗜️ Creating ZIP file with {downloaded} image+txt pairs...\")\n"," shutil.make_archive(f\"/content/{zip_name}\", 'zip', dataset_dir)\n","\n"," # Copy to Google Drive\n"," drive_folder = \"/content/drive/MyDrive/itch_datasets\"\n"," os.makedirs(drive_folder, exist_ok=True)\n"," drive_zip_path = f\"{drive_folder}/{zip_name}.zip\"\n"," shutil.copy(zip_path_local, drive_zip_path)\n","\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"🎉 SUCCESS! Your dataset is ready\")\n"," print(f\"📦 ZIP file: {zip_name}.zip\")\n"," print(f\"📤 Saved to Google Drive → {drive_zip_path}\")\n"," print(f\" • Files inside: 0001.jpg + 0001.txt, 0002.jpg + 0002.txt, ...\")\n"," print(f\" • Total pairs: {downloaded}\")\n"," print(\"=\"*80)\n","\n"," # ====================== PREVIEW FIRST 3 PAIRS ======================\n"," print(\"\\n📸 Preview of first 3 pairs (click images to enlarge):\")\n"," for i in range(min(3, len(pairs))):\n"," num_str = f\"{i+1:04d}\"\n"," img_file = f\"{dataset_dir}/{num_str}.jpg\"\n"," display(HTML(f\"
{num_str}. {pairs[i][0]}
\"))\n"," display(Image(filename=img_file, width=400))\n"," print(\"─\" * 70)\n","\n"," print(f\"\\n✅ All files are also in: {dataset_dir} (you can download the folder manually if needed)\")"]},{"cell_type":"markdown","source":["# 📚 VNDB (Visual Novel Database) fetch"],"metadata":{"id":"0VlyEacYp7Pn"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"70mWljq0EJCT","cellView":"form"},"outputs":[],"source":["#@markdown # 🐙 VNDB Image-Text fetch\n","#@markdown **✅ Added offset slider + metadata in ZIP**\n","#@markdown Now you can fetch any batch (e.g. first 1000 → offset 0, next 1000 → offset 1000, etc.)\n","\n","#@markdown ---\n","#@markdown ### 📋 Choose your settings below then **Run this cell**\n","\n","num_vns = 1000 #@param {type:\"slider\", min:10, max:5000, step:10, description:\"How many visual novels to fetch in this batch\"}\n","\n","offset = 0 #@param {type:\"slider\", min:0, max:20000, step:100}\n","#description:\"Offset: skip this many VNs before starting (0 = first batch, 1000 = second batch, etc.)\"}\n","\n","sort_by = \"Most Recent (released desc)\" #@param [\"Most Recent (released desc)\", \"Highest Rated\", \"Most Voted\"]\n","\n","#@markdown **Tag ID** (from your link: https://vndb.org/g3560)\n","tag_id = \"g3560\" #@param {type:\"string\", description:\"VNDB tag ID (e.g. g3560 = 3D Graphics)\"}\n","\n","#@markdown ---\n","\n","#@markdown **After changing the values above, just click the ▶️ Run button on this cell.**\n","\n","# ================================================\n","# ✅ FULLY DEBUGGED + OFFSET + METADATA READY-TO-RUN COLAB CELL\n","# ================================================\n","\n","import requests\n","import os\n","import json\n","import time\n","import shutil\n","import datetime\n","from IPython.display import display, HTML, Image\n","from google.colab import drive\n","\n","print(\"✅ Starting VNDB scraper with OFFSET support...\")\n","\n","# ====================== CONFIG ======================\n","MAX_RESULTS_PER_PAGE = 100\n","DELAY_BETWEEN_PAGES = 0.5\n","HEADERS = {\n"," \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n"," \"(KHTML, like Gecko) Chrome/134.0 Safari/537.36\",\n"," \"Content-Type\": \"application/json\"\n","}\n","\n","API_URL = \"https://api.vndb.org/kana/vn\"\n","\n","# Sort mapping\n","sort_map = {\n"," \"Most Recent (released desc)\": {\"sort\": \"released\", \"reverse\": True},\n"," \"Highest Rated\": {\"sort\": \"rating\", \"reverse\": True},\n"," \"Most Voted\": {\"sort\": \"votecount\", \"reverse\": True}\n","}\n","\n","selected_sort = sort_map[sort_by]\n","\n","print(f\"🌐 Target: VNDB Tag {tag_id} | Offset: {offset} | Fetching up to {num_vns} VNs (sorted by {sort_by})\")\n","\n","# Mount Google Drive\n","print(\"🔄 Mounting Google Drive...\")\n","drive.mount('/content/drive', force_remount=True)\n","\n","# Create working folder\n","dataset_dir = \"/content/vndb_dataset\"\n","os.makedirs(dataset_dir, exist_ok=True)\n","\n","# ====================== CALCULATE PAGINATION WITH OFFSET ======================\n","start_page = (offset // MAX_RESULTS_PER_PAGE) + 1\n","skip_in_first_page = offset % MAX_RESULTS_PER_PAGE\n","\n","print(f\"📌 Calculated start_page = {start_page}, skip first {skip_in_first_page} items on that page\")\n","\n","# ====================== FETCH VIA VNDB KANA API ======================\n","pairs = []\n","page = start_page\n","items_collected = 0\n","\n","while len(pairs) < num_vns:\n"," payload = {\n"," \"filters\": [\"tag\", \"=\", tag_id],\n"," \"fields\": \"id, title, image.url\",\n"," \"sort\": selected_sort[\"sort\"],\n"," \"reverse\": selected_sort[\"reverse\"],\n"," \"results\": MAX_RESULTS_PER_PAGE,\n"," \"page\": page\n"," }\n","\n"," # ==================== FULL DEBUG PRINT ====================\n"," print(f\"\\n📄 === API REQUEST PAGE {page} (offset={offset}) ===\")\n"," print(\"Payload sent:\")\n"," print(json.dumps(payload, indent=2))\n"," # ========================================================\n","\n"," try:\n"," response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=30)\n","\n"," print(f\" 📡 Status code: {response.status_code}\")\n","\n"," if response.status_code != 200:\n"," print(\" ❌ ERROR RESPONSE BODY:\")\n"," try:\n"," error_json = response.json()\n"," print(json.dumps(error_json, indent=2))\n"," except:\n"," print(response.text[:1000])\n"," break\n","\n"," data = response.json()\n"," results = data.get(\"results\", [])\n","\n"," if not results:\n"," print(\"✅ No more results.\")\n"," break\n","\n"," # Handle offset skipping on the very first page we fetch\n"," if page == start_page and skip_in_first_page > 0:\n"," print(f\" ⏭️ Skipping first {skip_in_first_page} items due to offset\")\n"," results = results[skip_in_first_page:]\n"," skip_in_first_page = 0\n","\n"," added = 0\n"," for vn in results:\n"," if len(pairs) >= num_vns:\n"," break\n","\n"," title = vn.get(\"title\", \"\").strip()\n"," if not title:\n"," continue\n","\n"," img_url = vn.get(\"image\", {}).get(\"url\") if isinstance(vn.get(\"image\"), dict) else None\n","\n"," if img_url:\n"," pairs.append((title, img_url))\n"," added += 1\n"," items_collected += 1\n","\n"," print(f\" → Added {added} VNs (total so far: {len(pairs)})\")\n","\n"," if not data.get(\"more\", False):\n"," print(\"✅ Reached the end of results.\")\n"," break\n","\n"," except Exception as e:\n"," print(f\"❌ Exception on API page {page}: {e}\")\n"," break\n","\n"," page += 1\n"," time.sleep(DELAY_BETWEEN_PAGES)\n","\n","if not pairs:\n"," print(\"\\n❌ No visual novels found in this offset range. Check debug output above.\")\n","else:\n"," print(f\"\\n✅ Collected {len(pairs)} visual novels (offset {offset}). Downloading images and creating TXT files...\")\n","\n"," # ====================== DOWNLOAD ENUMERATED FILES ======================\n"," downloaded = 0\n"," for idx, (title, img_url) in enumerate(pairs, start=1):\n"," num_str = f\"{idx:04d}\"\n"," img_path = f\"{dataset_dir}/{num_str}.jpg\"\n"," txt_path = f\"{dataset_dir}/{num_str}.txt\"\n","\n"," try:\n"," img_response = requests.get(img_url, headers=HEADERS, timeout=15)\n"," if img_response.status_code == 200:\n"," with open(img_path, \"wb\") as f:\n"," f.write(img_response.content)\n"," with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(title)\n"," downloaded += 1\n"," if downloaded % 10 == 0 or downloaded == len(pairs):\n"," print(f\" ✅ Saved {num_str}.jpg + {num_str}.txt\")\n"," else:\n"," print(f\"⚠️ Failed to download image {num_str} (HTTP {img_response.status_code})\")\n"," except Exception as e:\n"," print(f\"❌ Error downloading {num_str}: {e}\")\n","\n"," # ====================== WRITE METADATA (index/offset/tag) ======================\n"," timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n"," with open(f\"{dataset_dir}/INFO.txt\", \"w\", encoding=\"utf-8\") as f:\n"," f.write(f\"VNDB Tag ID : {tag_id}\\n\")\n"," f.write(f\"Offset : {offset}\\n\")\n"," f.write(f\"Batch Size : {num_vns}\\n\")\n"," f.write(f\"Actual Downloaded: {downloaded}\\n\")\n"," f.write(f\"Sort Order : {sort_by}\\n\")\n"," f.write(f\"Start Page : {start_page}\\n\")\n"," f.write(f\"Collected on : {timestamp}\\n\")\n"," f.write(f\"File index 0001 = VN #{offset + 1} in the full tag list\\n\")\n","\n"," print(\"📝 Metadata INFO.txt written (contains index/offset/tag info)\")\n","\n"," # ====================== CREATE ZIP & SAVE TO DRIVE ======================\n"," zip_name = f\"vndb_{tag_id}_offset{offset:04d}_{num_vns}vns_{timestamp}\"\n"," zip_path_local = f\"/content/{zip_name}.zip\"\n","\n"," print(f\"\\n🗜️ Creating ZIP file with {downloaded} image+txt pairs + INFO.txt...\")\n"," shutil.make_archive(f\"/content/{zip_name}\", 'zip', dataset_dir)\n","\n"," drive_folder = \"/content/drive/MyDrive/vndb_datasets\"\n"," os.makedirs(drive_folder, exist_ok=True)\n"," drive_zip_path = f\"{drive_folder}/{zip_name}.zip\"\n"," shutil.copy(zip_path_local, drive_zip_path)\n","\n"," print(\"\\n\" + \"=\"*80)\n"," print(\"🎉 SUCCESS! Your dataset is ready\")\n"," print(f\"📦 ZIP file: {zip_name}.zip\")\n"," print(f\"📤 Saved to Google Drive → {drive_zip_path}\")\n"," print(f\" • Contains: 0001.jpg + 0001.txt ... + INFO.txt (with offset/tag/index)\")\n"," print(f\" • Total pairs: {downloaded}\")\n"," print(\"=\"*80)\n","\n"," # ====================== PREVIEW FIRST 3 PAIRS ======================\n"," print(\"\\n📸 Preview of first 3 pairs (click images to enlarge):\")\n"," for i in range(min(3, len(pairs))):\n"," num_str = f\"{i+1:04d}\"\n"," img_file = f\"{dataset_dir}/{num_str}.jpg\"\n"," display(HTML(f\"{num_str}. {pairs[i][0]}
\"))\n"," display(Image(filename=img_file, width=400))\n"," print(\"─\" * 70)\n","\n"," print(f\"\\n✅ All files are also in: {dataset_dir} (you can download the folder manually if needed)\")"]},{"cell_type":"markdown","source":["# 📌 Pinterest fetch"],"metadata":{"id":"JrtsI98cmAxB"}},{"cell_type":"markdown","metadata":{"id":"HO3NmF03QDpt"},"source":["Pinterest board downloader\n","\n","⚠️️ Use a throwaway account! Pinterest is a stupid website run by AI bots.\n","\n","1. Install the EditThisCookie (or \"Get cookies.txt LOCALLY\") Chrome extension.\n","2. Log into Pinterest in Chrome → open your board.\n","3. Click the extension icon → Export cookies for pinterest.com → save as cookies.txt (plain text / Netscape format).\n","4. In Colab, click the folder icon (left sidebar) → upload cookies.txt to your google drive."]},{"cell_type":"code","source":["# ==================== SINGLE CELL - FULL PINTEREST BOARD DOWNLOADER (Cookies from Google Drive) ====================\n","\n","# Install gallery-dl\n","!pip install -q gallery-dl\n","\n","import os\n","from google.colab import files\n","from google.colab import drive\n","import shutil # Import shutil for copying files\n","\n","# ====================== CONFIGURATION ======================\n","# 1. Paste your board URL here\n","board_url = \"\" #@param {type:\"string\"}\n","\n","# 2. Path to your cookies file on Google Drive (change only if it's in a subfolder)\n","cookies_file = \"/content/drive/MyDrive/pinterest_cookies.txt\" #@param {type:\"string\"}\n","\n","# Optional: custom board name (auto-detected from URL by default)\n","board_name = board_url.rstrip(\"/\").split(\"/\")[-1]\n","#or \"pinterest_board\" #@param {type:\"string\"}\n","\n","print(\"✅ Board URL:\", board_url)\n","print(\"📁 Board name:\", board_name)\n","print(\"🔑 Cookies path:\", cookies_file)\n","\n","# ====================== MOUNT GOOGLE DRIVE ======================\n","print(\"🚀 Mounting Google Drive...\")\n","drive.mount('/content/drive', force_remount=False)\n","\n","# Check if cookies file exists\n","if os.path.exists(cookies_file):\n"," print(\"✅ Cookies file found! Full board (700+ images) will be downloaded.\")\n","else:\n"," print(\"❌ Cookies file NOT found at the path above. Only ~200 images will download.\")\n","\n","# ====================== CREATE OUTPUT FOLDER ======================\n","output_dir = f\"/content/{board_name}\"\n","os.makedirs(output_dir, exist_ok=True)\n","\n","print(\"🚀 Starting download... (this can take a while for large boards)\")\n","\n","# ====================== BUILD & RUN GALLERY-DL COMMAND ======================\n","cmd = f'gallery-dl --dest \"{output_dir}\"'\n","if os.path.exists(cookies_file):\n"," cmd += f' --cookies \"{cookies_file}\"'\n","cmd += f' \"{board_url}\"'\n","\n","# Execute the download\n","!{cmd}\n","\n","# Count downloaded files\n","total_files = sum([len(files) for r, d, files in os.walk(output_dir)])\n","print(f\"✅ Download finished! {total_files} files saved in {output_dir}\")\n","\n","# ====================== ZIP & AUTO-DOWNLOAD ======================\n","zip_path = f\"/content/{board_name}.zip\"\n","print(\"📦 Zipping all images...\")\n","!zip -r -q \"{zip_path}\" \"{output_dir}\"\n","\n","print(f\"✅ Zipped everything → {zip_path}\")\n","\n","# Save to Google Drive\n","drive_zip_destination = f\"/content/drive/MyDrive/{board_name}.zip\"\n","shutil.copy2(zip_path, drive_zip_destination)\n","print(f\"✅ Copied '{zip_path}' to Google Drive at '{drive_zip_destination}'\")\n","\n","# Auto-download the zip to your computer\n","#files.download(zip_path)\n","\n","#print(\"🎉 All done! Your full Pinterest board is now downloaded, zipped, and available in your Google Drive and local downloads.\")"],"metadata":{"id":"E7vSr64JkWWa","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"id":"g0524iIvU1I_"},"outputs":[],"source":["# Auto-download the zip file\n","files.download(zip_path)"]},{"cell_type":"markdown","source":["# 🖼️ Fetch from Sankaku Complex"],"metadata":{"id":"s40baE0G_wn7"}},{"cell_type":"code","source":["from google.colab import drive, userdata\n","\n","# Mount your Google Drive\n","drive.mount('/content/drive')\n","\n","#@markdown Load Sankaku Complex secrets (set these in Colab's left sidebar → Secrets panel first!)\n","SANKAKU_USERNAME = userdata.get('SANKAKU_USERNAME')\n","SANKAKU_PASSWORD = userdata.get('SANKAKU_PASSWORD')\n","\n","print(\"✅ Google Drive mounted and Sankaku credentials loaded from secrets!\")"],"metadata":{"cellView":"form","id":"XmDavSOowJSJ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @title Sankaku Advanced Downloader + Pagination + Fullsize Processing\n","\n","search_phrase = \"\" # @param {type:\"string\"}\n","N = 291 # @param {type:\"slider\", min:0, max:2000, step:100}\n","offset = 0 # @param {type:\"slider\", min:0, max:20000, step:10}\n","\n","download_thumbnails = True # @param {type:\"boolean\"}\n","create_image_text_pairs = True # @param {type:\"boolean\"}\n","download_fullsize = True # @param {type:\"boolean\"}\n","list_animated_links = True # @param {type:\"boolean\"}\n","download_animated_and_extract_frames = False # @param {type:\"boolean\"}\n","\n","# ── NEW: Fullsize post-processing for training datasets ──\n","process_fullsize_for_training = False # @param {type:\"boolean\"}\n","target_shortest_side = 1024 # @param {type:\"slider\", min:512, max:2048, step:64}\n","output_drive_folder_name = \"sankaku_processed\" # @param {type:\"string\"}\n","output_zip_name = \"resized_image_text_pairs.zip\" # @param {type:\"string\"}\n","\n","import requests\n","import os\n","import shutil\n","from zipfile import ZipFile\n","import urllib.parse\n","import subprocess\n","import time\n","from http.cookiejar import MozillaCookieJar\n","from PIL import Image\n","from tqdm.notebook import tqdm\n","from pathlib import Path\n","import gc\n","\n","# ====================== LOGIN ======================\n","login_url = \"https://sankakuapi.com/auth/token\"\n","payload = {\"login\": SANKAKU_USERNAME, \"password\": SANKAKU_PASSWORD}\n","headers = {\n"," \"Accept\": \"application/vnd.sankaku.api+json;v=2\",\n"," \"Origin\": \"https://sankaku.app\",\n"," \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\",\n"," \"Content-Type\": \"application/json\"\n","}\n","\n","login_resp = requests.post(login_url, json=payload, headers=headers)\n","login_resp.raise_for_status()\n","access_token = login_resp.json()[\"access_token\"]\n","print(\"✅ Logged into Sankaku successfully!\")\n","\n","# ====================== SESSION + COOKIES ======================\n","session = requests.Session()\n","session.headers.update({\n"," \"Accept\": \"application/vnd.sankaku.api+json;v=2\",\n"," \"Origin\": \"https://sankaku.app\",\n"," \"User-Agent\": headers[\"User-Agent\"],\n"," \"Authorization\": f\"Bearer {access_token}\"\n","})\n","\n","cookies_path = \"/content/drive/MyDrive/sankaku_cookies.txt\"\n","if os.path.exists(cookies_path):\n"," try:\n"," cj = MozillaCookieJar()\n"," cj.load(cookies_path, ignore_discard=True, ignore_expires=True)\n"," session.cookies = cj\n"," print(\"✅ sankaku_cookies.txt loaded for faster downloads!\")\n"," except Exception as e:\n"," print(f\"⚠️ Cookie load issue: {e}\")\n","\n","# ====================== PAGINATED FETCH ======================\n","print(f\"🔄 Fetching up to {N} posts (offset {offset})...\")\n","posts_url = \"https://sankakuapi.com/posts\"\n","collected_posts = []\n","current_offset = offset\n","remaining = N\n","MAX_PER_REQUEST = 100\n","\n","while remaining > 0:\n"," batch_limit = min(MAX_PER_REQUEST, remaining)\n"," params = {\"tags\": search_phrase, \"limit\": batch_limit, \"offset\": current_offset}\n"," resp = session.get(posts_url, params=params)\n"," resp.raise_for_status()\n"," batch = resp.json()\n"," if not batch:\n"," break\n"," collected_posts.extend(batch)\n"," print(f\" ✅ Batch of {len(batch)} posts (total: {len(collected_posts)})\")\n"," current_offset += len(batch)\n"," remaining -= len(batch)\n"," if len(batch) < MAX_PER_REQUEST:\n"," break\n"," time.sleep(0.5)\n","\n","posts = collected_posts[:N]\n","print(f\"\\n✅ Fetched {len(posts)} posts total\")\n","\n","# ====================== STATS ======================\n","# (stats code unchanged – same as previous version)\n","image_count = animated_count = safe_count = questionable_count = explicit_count = 0\n","limited_visibility_count = ai_created_count = contentious_content_count = unlisted_count = 0\n","for post in posts:\n"," file_ext = post.get(\"file_ext\", \"\").lower()\n"," is_animated = (file_ext in [\"gif\", \"webm\", \"mp4\"]) or post.get(\"is_animated\", False)\n"," if is_animated:\n"," animated_count += 1\n"," else:\n"," image_count += 1\n"," rating = str(post.get(\"rating\", \"\")).lower().strip()\n"," if rating in [\"s\", \"safe\"]: safe_count += 1\n"," elif rating in [\"q\", \"questionable\"]: questionable_count += 1\n"," elif rating in [\"e\", \"explicit\"]: explicit_count += 1\n"," raw_tags = post.get(\"tags\", [])\n"," if isinstance(raw_tags, list) and raw_tags and isinstance(raw_tags[0], dict):\n"," tag_list = [t.get(\"name\", str(t)).lower() for t in raw_tags]\n"," else:\n"," tag_list = [str(t).lower() for t in raw_tags if t]\n"," if any(t == \"limited_visibility\" for t in tag_list): limited_visibility_count += 1\n"," if any(t in [\"ai-created\", \"ai_generated\"] for t in tag_list): ai_created_count += 1\n"," if any(t == \"contentious_content\" for t in tag_list): contentious_content_count += 1\n"," if any(t in [\"unlisted\", \"limited\", \"hidden\"] for t in tag_list): unlisted_count += 1\n","\n","print(\"\\n📊 Search stats:\")\n","print(f\" • Total fetched posts : {len(posts)}\")\n","print(f\" • Image results : {image_count}\")\n","print(f\" • Animated results : {animated_count}\")\n","print(f\" • Safe / Questionable / Explicit : {safe_count} / {questionable_count} / {explicit_count}\")\n","print(f\" • limited_visibility / AI-created / contentious_content / unlisted : {limited_visibility_count} / {ai_created_count} / {contentious_content_count} / {unlisted_count}\")\n","\n","# ====================== DOWNLOAD SECTION (unchanged) ======================\n","base_dir = \"/content/sankaku_downloads\"\n","thumbs_dir = os.path.join(base_dir, \"thumbnails\")\n","full_dir = os.path.join(base_dir, \"fullsize\")\n","frames_dir = os.path.join(base_dir, \"animated_frames\")\n","os.makedirs(thumbs_dir, exist_ok=True)\n","os.makedirs(full_dir, exist_ok=True)\n","os.makedirs(frames_dir, exist_ok=True)\n","\n","if download_animated_and_extract_frames:\n"," print(\"📦 Installing ffmpeg...\")\n"," subprocess.run([\"apt-get\", \"update\", \"-qq\"], check=True, capture_output=True)\n"," subprocess.run([\"apt-get\", \"install\", \"-y\", \"ffmpeg\", \"-qq\"], check=True, capture_output=True)\n","\n","animated_links = []\n","downloaded_count = 0\n","frames_extracted = 0\n","\n","for idx, post in enumerate(posts):\n"," post_id = post.get(\"id\", idx)\n"," file_url = post.get(\"file_url\")\n"," preview_url = post.get(\"preview_url\")\n"," file_ext = post.get(\"file_ext\", \"\").lower()\n"," is_animated = (file_ext in [\"gif\", \"webm\", \"mp4\"]) or post.get(\"is_animated\", False)\n","\n"," raw_tags = post.get(\"tags\", [])\n"," if isinstance(raw_tags, list) and raw_tags and isinstance(raw_tags[0], dict):\n"," tag_list = [t.get(\"name\", str(t)) for t in raw_tags]\n"," else:\n"," tag_list = [str(t) for t in raw_tags if t]\n"," tags_str = \", \".join(tag_list) if tag_list else \"no_tags\"\n","\n"," # Thumbnails\n"," if download_thumbnails and preview_url:\n"," try:\n"," resp = session.get(preview_url, timeout=15)\n"," resp.raise_for_status()\n"," ext = os.path.splitext(urllib.parse.urlparse(preview_url).path)[1].lower() or \".jpg\"\n"," fname = f\"thumb_{idx+1:04d}_id{post_id}{ext}\"\n"," with open(os.path.join(thumbs_dir, fname), \"wb\") as f: f.write(resp.content)\n"," if create_image_text_pairs:\n"," with open(os.path.join(thumbs_dir, fname.replace(ext, \".txt\")), \"w\", encoding=\"utf-8\") as f:\n"," f.write(tags_str)\n"," downloaded_count += 1\n"," except: pass\n","\n"," # Full-size\n"," if download_fullsize and file_url:\n"," try:\n"," resp = session.get(file_url, timeout=25)\n"," resp.raise_for_status()\n"," ext = os.path.splitext(urllib.parse.urlparse(file_url).path)[1].lower() or \".jpg\"\n"," fname = f\"full_{idx+1:04d}_id{post_id}{ext}\"\n"," with open(os.path.join(full_dir, fname), \"wb\") as f: f.write(resp.content)\n"," if create_image_text_pairs:\n"," with open(os.path.join(full_dir, fname.replace(ext, \".txt\")), \"w\", encoding=\"utf-8\") as f:\n"," f.write(tags_str)\n"," downloaded_count += 1\n"," except: pass\n","\n"," if list_animated_links and is_animated and file_url:\n"," animated_links.append(file_url)\n","\n"," if download_animated_and_extract_frames and is_animated and file_url:\n"," # (keyframe extraction code unchanged – same as before)\n"," try:\n"," resp = session.get(file_url, timeout=30)\n"," resp.raise_for_status()\n"," ext = os.path.splitext(urllib.parse.urlparse(file_url).path)[1].lower() or \".mp4\"\n"," anim_path = os.path.join(frames_dir, f\"anim_{idx+1:04d}_id{post_id}{ext}\")\n"," with open(anim_path, \"wb\") as f: f.write(resp.content)\n"," keyframe_dir = os.path.join(frames_dir, f\"keyframes_id{post_id}\")\n"," os.makedirs(keyframe_dir, exist_ok=True)\n"," output_pattern = os.path.join(keyframe_dir, f\"keyframe_{idx+1:04d}_%05d.jpg\")\n"," if ext == \".gif\":\n"," cmd = [\"ffmpeg\", \"-i\", anim_path, \"-vsync\", \"0\", \"-frame_pts\", \"1\", output_pattern.replace(\"%05d\", \"%04d\")]\n"," else:\n"," cmd = [\"ffmpeg\", \"-i\", anim_path, \"-vf\", \"select=eq(pict_type\\\\,I)\", \"-vsync\", \"vfr\", \"-frame_pts\", \"1\", output_pattern]\n"," subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)\n"," extracted = [f for f in os.listdir(keyframe_dir) if f.endswith(\".jpg\")]\n"," for jpg in extracted:\n"," with open(os.path.join(keyframe_dir, jpg.replace(\".jpg\",\".txt\")), \"w\", encoding=\"utf-8\") as f:\n"," f.write(tags_str)\n"," frames_extracted += 1\n"," except: pass\n","\n"," time.sleep(0.3)\n","\n","if list_animated_links and animated_links:\n"," with open(os.path.join(base_dir, \"animated_links.txt\"), \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"\\n\".join(animated_links))\n","\n","# ====================== RAW BACKUP ZIP ======================\n","zip_path = \"/content/sankaku_downloads.zip\"\n","with ZipFile(zip_path, \"w\") as zipf:\n"," for root, _, files in os.walk(base_dir):\n"," for file in files:\n"," zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), base_dir))\n","shutil.copy2(zip_path, \"/content/drive/MyDrive/sankaku_downloads.zip\")\n","print(f\"✅ Raw backup ZIP saved to Drive → /MyDrive/sankaku_downloads.zip\")\n","\n","# ====================== FULLSIZE PROCESSING (exactly as you asked) ======================\n","if process_fullsize_for_training and download_fullsize:\n"," print(\"\\n🔧 Starting fullsize post-processing (resize + rename + zip)...\")\n"," INPUT_IMAGES_DIR = os.path.join(base_dir, \"fullsize/\")\n"," TARGET_SHORTEST_SIDE = target_shortest_side\n"," OUTPUT_DRIVE_FOLDER_NAME = output_drive_folder_name\n"," OUTPUT_ZIP_FILE_NAME = output_zip_name\n","\n"," # Mount check (safe)\n"," try:\n"," from google.colab import drive\n"," drive.mount('/content/drive', force_remount=False)\n"," except: pass\n","\n"," drive_base = \"/content/drive/MyDrive\"\n"," drive_output_dir = os.path.join(drive_base, OUTPUT_DRIVE_FOLDER_NAME)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n","\n"," local_temp_output_dir = Path(\"/content/temp_processed_output\")\n"," shutil.rmtree(local_temp_output_dir, ignore_errors=True)\n"," local_temp_output_dir.mkdir(exist_ok=True, parents=True)\n","\n"," # Collect image-text pairs\n"," image_files = []\n"," valid_ext = ('.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff')\n"," print(f\"Scanning {INPUT_IMAGES_DIR}...\")\n"," for root, _, files in os.walk(INPUT_IMAGES_DIR):\n"," for fname in files:\n"," if fname.lower().endswith(valid_ext):\n"," img_path = Path(os.path.join(root, fname))\n"," txt_path = img_path.with_suffix('.txt')\n"," if txt_path.is_file():\n"," image_files.append((img_path, txt_path))\n","\n"," print(f\"Found {len(image_files)} image-text pairs.\")\n","\n"," processed_count = skipped_count = 0\n"," for original_img_path, original_txt_path in tqdm(image_files, desc=\"Resizing & renaming\"):\n"," try:\n"," with Image.open(original_img_path) as img:\n"," w, h = img.size\n"," if min(w, h) < TARGET_SHORTEST_SIDE:\n"," skipped_count += 1\n"," continue\n","\n"," if w < h:\n"," new_w = TARGET_SHORTEST_SIDE\n"," new_h = int(h * TARGET_SHORTEST_SIDE / w)\n"," else:\n"," new_h = TARGET_SHORTEST_SIDE\n"," new_w = int(w * TARGET_SHORTEST_SIDE / h)\n","\n"," resized = img.resize((new_w, new_h), Image.LANCZOS)\n"," if resized.mode != 'RGB':\n"," resized = resized.convert('RGB')\n","\n"," processed_count += 1\n"," new_base = str(processed_count)\n","\n"," output_img = local_temp_output_dir / f\"{new_base}.jpeg\"\n"," resized.save(output_img, \"JPEG\", quality=85)\n","\n"," output_txt = local_temp_output_dir / f\"{new_base}.txt\"\n"," shutil.copy2(original_txt_path, output_txt)\n","\n"," del img, resized\n"," if processed_count % 100 == 0:\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Error: {original_img_path.name} → {e}\")\n"," skipped_count += 1\n","\n"," print(f\"\\nProcessed {processed_count} images | Skipped {skipped_count}\")\n","\n"," # Create & save zip\n"," if processed_count > 0:\n"," local_zip_path = Path(\"/content\") / OUTPUT_ZIP_FILE_NAME\n"," with zipfile.ZipFile(local_zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n"," for item in tqdm(local_temp_output_dir.rglob(\"*\"), desc=\"Zipping\"):\n"," if item.is_file():\n"," zf.write(item, arcname=item.name)\n","\n"," drive_final_zip = Path(drive_output_dir) / OUTPUT_ZIP_FILE_NAME\n"," shutil.copy2(local_zip_path, drive_final_zip)\n"," size_mb = local_zip_path.stat().st_size / (1024 * 1024)\n"," print(f\"\\n🎉 PROCESSED ZIP SAVED!\")\n"," print(f\" Folder → {drive_output_dir}\")\n"," print(f\" Zip → {drive_final_zip}\")\n"," print(f\" Size → {size_mb:.1f} MiB\")\n","\n"," # Cleanup temp\n"," shutil.rmtree(local_temp_output_dir, ignore_errors=True)\n","\n","print(\"\\n🎉 ALL DONE! Check your Google Drive.\")"],"metadata":{"id":"P-4aeky_F2UN"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ✂️ Image slicer"],"metadata":{"id":"lUIEma9C-36K"}},{"cell_type":"code","source":["# ====================== IMAGE COLUMN SLICER (ZIP SUPPORT) ======================\n","\n","# ====================== SETTINGS ======================\n","N = 6 # @param {type:\"slider\", min:1, max:100, step:1}\n","M = 18 # @param {type:\"slider\", min:1, max:30, step:1}\n","\n","left_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n","right_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n","bottom_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n","\n","output_format = \"JPEG\" # @param [\"PNG\", \"JPEG\", \"WEBP\"]\n","image_quality = 90 # @param {type:\"slider\", min:10, max:100, step:1}\n","\n","upload_to_drive = False # @param {type:\"boolean\"}\n","drive_output_folder = \"sliced_images\" # @param {type:\"string\"}\n","\n","# ====================== IMPORTS ======================\n","import io\n","import os\n","import zipfile\n","from PIL import Image\n","from google.colab import files, drive\n","\n","# Install PyMuPDF for PDF processing\n","!pip install PyMuPDF -q\n","import fitz # PyMuPDF\n","\n","\n","print(f\"✅ Columns: {N}, Rows: {M}\")\n","print(f\"✅ Manual crops - L:{left_crop_percent}% R:{right_crop_percent}% B:{bottom_crop_percent}%\")\n","print(f\"✅ Output format: {output_format}, Quality: {image_quality}\")\n","print(f\"✅ Upload to Drive: {upload_to_drive}\")\n","\n","\n","# ====================== FILE FILTER ======================\n","def is_valid_image_file(filename):\n"," bad_patterns = [\"__MACOSX\", \".DS_Store\", \"Thumbs.db\", \".AppleDouble\", \"._\"]\n","\n"," if any(p in filename for p in bad_patterns):\n"," return False\n","\n"," if os.path.basename(filename).startswith(\".\"):\n"," return False\n","\n"," # Check for common image extensions\n"," return filename.lower().endswith((\".png\", \".jpg\", \".jpeg\", \".bmp\", \".tiff\", \".webp\"))\n","\n","\n","# ====================== EXTRACTOR ======================\n","def extract_files(uploaded_dict):\n"," \"\"\"\n"," Yield (filename, bytes) from:\n"," - direct image uploads\n"," - zip archives (including nested folders)\n"," - PDF files (each page converted to an image)\n"," \"\"\"\n"," for filename, file_content in uploaded_dict.items():\n","\n"," # ===== PDF FILE =====\n"," if filename.lower().endswith(\".pdf\"):\n"," print(f\"📄 Extracting PDF: {filename}\")\n"," try:\n"," pdf_doc = fitz.open(stream=file_content, filetype=\"pdf\")\n"," for page_num in range(len(pdf_doc)):\n"," page = pdf_doc.load_page(page_num)\n"," # Render page to a Pixmap (image buffer)\n"," pix = page.get_pixmap()\n"," # Convert Pixmap to PNG bytes\n"," img_bytes = pix.pil_tobytes(format=\"PNG\")\n"," # Yield a filename for the extracted page and its bytes\n"," yield f\"{os.path.splitext(filename)[0]}_page_{page_num + 1:03d}.png\", img_bytes\n"," pdf_doc.close()\n"," except Exception as e:\n"," print(f\"❌ Failed processing PDF {filename}: {e}\")\n","\n"," # ===== ZIP FILE =====\n"," elif filename.lower().endswith(\".zip\"):\n"," print(f\"📦 Extracting ZIP: {filename}\")\n","\n"," try:\n"," with zipfile.ZipFile(io.BytesIO(file_content)) as z:\n"," for member in z.namelist():\n"," # The is_valid_image_file check ensures we only process images from ZIPs\n"," if is_valid_image_file(member):\n"," try:\n"," yield member, z.read(member)\n"," except Exception as e:\n"," print(f\"❌ Failed reading {member}: {e}\")\n"," else:\n"," print(f\"⏭️ Skipping in ZIP: {member}\")\n","\n"," except Exception as e:\n"," print(f\"❌ Bad ZIP file: {filename} | {e}\")\n","\n"," # ===== DIRECT IMAGE =====\n"," else:\n"," # For non-zip/non-pdf, treat as a direct image. is_valid_image_file ensures it's an image.\n"," if is_valid_image_file(filename):\n"," yield filename, file_content\n"," else:\n"," print(f\"⏭️ Skipping unrecognized file: {filename}\")\n","\n","\n","# ====================== UPLOAD ======================\n","print(\"\\n📤 Upload images or ZIP files...\")\n","uploaded = files.upload()\n","\n","if not uploaded:\n"," print(\"❌ No files uploaded.\")\n","\n","else:\n","\n"," zip_buffer = io.BytesIO()\n","\n"," with zipfile.ZipFile(zip_buffer, \"w\", zipfile.ZIP_DEFLATED) as zip_file:\n","\n"," processed = 0\n","\n"," # ====================== PROCESS LOOP ======================\n"," for filename, file_content in extract_files(uploaded):\n","\n"," # This check is crucial here to ensure only actual image data (from PDFs, ZIPs, or direct) proceeds\n"," if not is_valid_image_file(filename):\n"," print(f\"⏭️ Skipping: {filename}\")\n"," continue\n","\n"," try:\n"," img = Image.open(io.BytesIO(file_content)).convert(\"RGB\")\n","\n"," # ====================== MANUAL CROPPING ======================\n"," w, h = img.size\n","\n"," left_px = int(w * left_crop_percent / 100)\n"," right_px = int(w * (1 - right_crop_percent / 100))\n"," bottom_px = int(h * (1 - bottom_crop_percent / 100))\n","\n"," if left_px >= right_px or bottom_px <= 1:\n"," print(f\"⚠️ Invalid crop: {filename}\")\n"," continue\n","\n"," img = img.crop((left_px, 0, right_px, bottom_px))\n"," w, h = img.size\n","\n"," if w < N:\n"," print(f\"⚠️ Too narrow for {N} columns: {filename}\")\n"," continue\n"," if h < M:\n"," print(f\"⚠️ Too short for {M} rows: {filename}\")\n"," continue\n","\n"," # ====================== SLICE ======================\n"," col_w = w // N\n"," row_h = h // M\n"," base = os.path.splitext(os.path.basename(filename))[0]\n","\n"," for i in range(N):\n"," col_l = i * col_w\n"," col_r = (i + 1) * col_w if i < N - 1 else w\n","\n"," # Crop the column first\n"," column_img = img.crop((col_l, 0, col_r, h))\n","\n"," for j in range(M):\n"," row_t = j * row_h\n"," row_b = (j + 1) * row_h if j < M - 1 else h\n","\n"," slice_img = column_img.crop((0, row_t, column_img.width, row_b))\n","\n"," # Determine output extension\n"," ext = \".\" + output_format.lower() if output_format != \"JPEG\" else \".jpg\"\n"," output_name = f\"{base}_col_{i+1:02d}_row_{j+1:02d}{ext}\"\n","\n"," buf = io.BytesIO()\n"," if output_format == \"PNG\":\n"," slice_img.save(buf, format=\"PNG\") # PIL defaults to good compression\n"," elif output_format == \"JPEG\":\n"," slice_img.save(buf, format=\"JPEG\", quality=image_quality)\n"," elif output_format == \"WEBP\":\n"," slice_img.save(buf, format=\"WEBP\", quality=image_quality)\n","\n"," zip_file.writestr(output_name, buf.getvalue())\n","\n"," processed += 1\n"," print(f\"✅ Processed: {filename}\")\n","\n"," except Exception as e:\n"," print(f\"❌ Error {filename}: {e}\")\n","\n","\n"," # ====================== DOWNLOAD / UPLOAD ======================\n"," if processed > 0:\n"," zip_path = \"/content/sliced_output.zip\"\n","\n"," with open(zip_path, \"wb\") as f:\n"," f.write(zip_buffer.getvalue())\n","\n"," print(f\"\\n🎉 Done! {processed} images processed.\")\n","\n"," if upload_to_drive:\n"," print(\"🚀 Mounting Google Drive...\")\n"," drive.mount('/content/drive', force_remount=True)\n"," drive_destination_folder = f\"/content/drive/MyDrive/{drive_output_folder}\"\n"," os.makedirs(drive_destination_folder, exist_ok=True)\n"," shutil.copy(zip_path, drive_destination_folder)\n"," print(f\"✅ Zip file saved to Google Drive: {drive_destination_folder}/sliced_output.zip\")\n"," else:\n"," files.download(zip_path)\n","\n"," else:\n"," print(\"❌ No valid images processed.\")"],"metadata":{"id":"0oxW9KL11lZ7"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# --- Upload ZIP ---\n","from google.colab import files\n","uploaded = files.upload()\n","\n","import zipfile\n","import os\n","import cv2\n","import numpy as np\n","\n","# --- Parameters ---\n","black_threshold = 40 # pixel intensity threshold (0–255); higher = more tolerant\n","tolerance_ratio = 0.95 # % of pixels in a row/col that must be \"black-like\"\n","\n","# --- Extract ZIP ---\n","zip_name = list(uploaded.keys())[0]\n","extract_dir = \"input_images\"\n","output_dir = \"cropped_images\"\n","\n","os.makedirs(extract_dir, exist_ok=True)\n","os.makedirs(output_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_name, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n","# --- Helper function ---\n","def is_mostly_black(line):\n"," # line shape: (N, 3)\n"," gray = np.mean(line, axis=1)\n"," black_pixels = np.sum(gray < black_threshold)\n"," return (black_pixels / len(gray)) >= tolerance_ratio\n","\n","# --- Process images ---\n","for root, _, files_in_dir in os.walk(extract_dir):\n"," for file in files_in_dir:\n"," if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):\n"," path = os.path.join(root, file)\n"," img = cv2.imread(path)\n","\n"," if img is None:\n"," continue\n","\n"," h, w, _ = img.shape\n","\n"," # --- Detect left crop ---\n"," left = 0\n"," for x in range(w):\n"," col = img[:, x, :]\n"," if is_mostly_black(col):\n"," left += 1\n"," else:\n"," break\n","\n"," # --- Detect right crop ---\n"," right = w\n"," for x in range(w - 1, -1, -1):\n"," col = img[:, x, :]\n"," if is_mostly_black(col):\n"," right -= 1\n"," else:\n"," break\n","\n"," # --- Detect bottom crop ---\n"," bottom = h\n"," for y in range(h - 1, -1, -1):\n"," row = img[y, :, :]\n"," if is_mostly_black(row):\n"," bottom -= 1\n"," else:\n"," break\n","\n"," # --- Crop ---\n"," cropped = img[0:bottom, left:right]\n","\n"," # --- Save ---\n"," out_path = os.path.join(output_dir, file)\n"," cv2.imwrite(out_path, cropped)\n","\n","# --- Zip results ---\n","output_zip = \"cropped_results.zip\"\n","with zipfile.ZipFile(output_zip, 'w') as zipf:\n"," for root, _, files_in_dir in os.walk(output_dir):\n"," for file in files_in_dir:\n"," file_path = os.path.join(root, file)\n"," zipf.write(file_path, arcname=file)\n","\n","# --- Download ---\n","files.download(output_zip)"],"metadata":{"id":"AmbYgH8LGtXI"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# 🎲 Fetch subset of zip file"],"metadata":{"id":"02aZcv2lB_hC"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"6edbf718","cellView":"form"},"outputs":[],"source":["#@markdown Randomly sample a selected zip file (with many images for example) , and download as smaller zip\n","import zipfile\n","import os\n","import random\n","import shutil\n","from glob import glob\n","from google.colab import files\n","\n","# --- Configuration ---\n","input_zip_file = '' #@param {type:'string'}\n","\n","extraction_dir = '/content/extracted_keyframes_temp'\n","output_zip_name = 'random_300_keyframes.zip'\n","num_images_to_pick = 180 #@param {type:'slider',min:0,step:5,max:1000}\n","\n","# --- Step 1: Unzip the input file ---\n","print(f\"🔄 Unzipping {input_zip_file}...\")\n","if os.path.exists(extraction_dir):\n"," shutil.rmtree(extraction_dir)\n","os.makedirs(extraction_dir, exist_ok=True)\n","\n","try:\n"," with zipfile.ZipFile(input_zip_file, 'r') as zip_ref:\n"," zip_ref.extractall(extraction_dir)\n"," print(\"✅ Unzip complete.\")\n","except Exception as e:\n"," print(f\"❌ Error unzipping file: {e}\")\n"," raise\n","\n","# --- Step 2: Find all images in the extracted directory ---\n","all_images = []\n","for ext in ('*.jpg', '*.jpeg', '*.png', '*.gif'): # Add more extensions if needed\n"," all_images.extend(glob(os.path.join(extraction_dir, '**', ext), recursive=True))\n","\n","if not all_images:\n"," print(\"⚠️ No images found in the extracted archive.\")\n"," raise FileNotFoundError(\"No images to process.\")\n","\n","print(f\"Found {len(all_images)} total images.\")\n","\n","# --- Step 3: Randomly select images ---\n","if len(all_images) <= num_images_to_pick:\n"," selected_images = all_images\n"," print(f\"Selecting all {len(all_images)} images (fewer than {num_images_to_pick} available).\")\n","else:\n"," selected_images = random.sample(all_images, num_images_to_pick)\n"," print(f\"✅ Randomly selected {len(selected_images)} images.\")\n","\n","# --- Step 4: Create a new zip file with selected images ---\n","output_zip_path = os.path.join('/content', output_zip_name)\n","\n","print(f\"🔄 Creating new zip file: {output_zip_name}...\")\n","with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as new_zip:\n"," for img_path in selected_images:\n"," # Add image to zip, preserving its relative path within the extracted folder\n"," arcname = os.path.relpath(img_path, extraction_dir)\n"," new_zip.write(img_path, arcname)\n","\n","print(f\"✅ New zip file created: {output_zip_path}\")\n","\n","# --- Step 5: Provide as widget output for download ---\n","print(\"📥 Initiating download of the new zip file...\")\n","files.download(output_zip_path)\n","\n","# --- Step 6: Cleanup temporary files ---\n","print(\"🗑️ Cleaning up temporary extraction directory...\")\n","shutil.rmtree(extraction_dir)\n","print(\"✅ Cleanup complete.\")\n","print(\"You can find the downloaded zip file in your local downloads.\")"]},{"cell_type":"markdown","source":["# 📝 Insert Titles Between Every Sentence"],"metadata":{"id":"U27drDtMB53n"}},{"cell_type":"code","source":["\n","# @markdown ---\n","# @markdown **How to use this Colab:**\n","# @markdown 1. Prepare two plain text files:\n","# @markdown - `titles.txt` → contains `{title1|title2|title3|...}` (or just `title1|title2|...`)\n","# @markdown - `texts.txt` → contains `{text1|text2|text3|...}` (or just `text1|text2|...`)\n","# @markdown 2. Upload both files using the widgets below.\n","# @markdown 3. Click **🚀 Process & Download Captions**.\n","# @markdown 4. You will get:\n","# @markdown - The full `{caption1|caption2|caption3|...}` string printed\n","# @markdown - A single `captions.txt` file automatically downloaded containing exactly that string\n","# @markdown ---\n","\n","import ipywidgets as widgets\n","from IPython.display import display, HTML\n","import re\n","import itertools\n","from google.colab import files\n","\n","# ====================== UPLOAD WIDGETS ======================\n","titles_upload = widgets.FileUpload(\n"," accept='.txt',\n"," multiple=False,\n"," description='📤 Upload titles.txt'\n",")\n","\n","texts_upload = widgets.FileUpload(\n"," accept='.txt',\n"," multiple=False,\n"," description='📤 Upload texts.txt'\n",")\n","\n","process_button = widgets.Button(\n"," description='🚀 Process & Download Captions',\n"," button_style='success',\n"," layout=widgets.Layout(width='100%', height='50px')\n",")\n","\n","output_area = widgets.Output()\n","\n","# ====================== PROCESSING LOGIC ======================\n","def process_captions(b):\n"," with output_area:\n"," output_area.clear_output()\n","\n"," if not titles_upload.value or not texts_upload.value:\n"," print(\"❌ ERROR: Please upload BOTH titles.txt and texts.txt files!\")\n"," return\n","\n"," # Read uploaded file contents\n"," titles_file = list(titles_upload.value.values())[0]\n"," texts_file = list(texts_upload.value.values())[0]\n","\n"," titles_str = titles_file['content'].decode('utf-8').strip()\n"," texts_str = texts_file['content'].decode('utf-8').strip()\n","\n"," # ====================== PARSE LISTS ======================\n"," def parse_list(s):\n"," s = s.strip()\n"," if s.startswith(\"{\") and s.endswith(\"}\"):\n"," items = [item.strip() for item in s[1:-1].split(\"|\") if item.strip()]\n"," else:\n"," items = [item.strip() for item in s.split(\"|\") if item.strip()]\n"," return items\n","\n"," titles_list = parse_list(titles_str)\n"," texts_list = parse_list(texts_str)\n","\n"," if not texts_list:\n"," print(\"❌ ERROR: texts.txt appears to be empty!\")\n"," return\n","\n"," # ====================== SENTENCE SPLITTER (preserves ALL punctuation) ======================\n"," def split_sentences(text):\n"," if not text or not text.strip():\n"," return []\n"," # Split after . ! ? followed by whitespace, punctuation STAYS attached to each sentence\n"," sentences = re.split(r'(?<=[.!?])\\s+', text.strip())\n"," return [s.strip() for s in sentences if s.strip()]\n","\n"," # ====================== BUILD CAPTIONS ======================\n"," captions = []\n"," title_cycle = itertools.cycle(titles_list) if titles_list else None\n","\n"," for text in texts_list:\n"," sentences = split_sentences(text)\n"," if not sentences:\n"," captions.append(\"\")\n"," continue\n","\n"," if not titles_list or len(sentences) <= 1:\n"," # No titles or only one sentence → no insertion\n"," caption = sentences[0]\n"," else:\n"," # Insert cycling titles BETWEEN sentences\n"," # Original punctuation remains on every sentence\n"," caption_parts = [sentences[0]]\n"," for sent in sentences[1:]:\n"," title = next(title_cycle)\n"," caption_parts.append(title)\n"," caption_parts.append(sent)\n"," caption = \" \".join(caption_parts)\n","\n"," captions.append(caption)\n","\n"," # ====================== CREATE SINGLE OUTPUT STRING ======================\n"," captions_str = \"{\" + \"|\".join(captions) + \"}\"\n","\n"," print(\"✅ SUCCESS! Generated Captions String:\")\n"," print(captions_str)\n","\n"," # ====================== SAVE & DOWNLOAD SINGLE captions.txt ======================\n"," output_path = \"/content/captions.txt\"\n"," with open(output_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(captions_str)\n","\n"," print(f\"\\n📄 Single file created: captions.txt\")\n"," print(\"⬇️ Downloading captions.txt now...\")\n"," files.download(output_path)\n","\n","# ====================== BUTTON CALLBACK ======================\n","process_button.on_click(process_captions)\n","\n","# ====================== DISPLAY UI ======================\n","ui = widgets.VBox([\n"," widgets.HTML(\"📄 Titles File
\"),\n"," titles_upload,\n"," widgets.HTML(\"📄 Texts File
\"),\n"," texts_upload,\n"," widgets.HTML(\"
Click the button below after uploading both files:\"),\n"," process_button,\n"," widgets.HTML(\"
\"),\n"," output_area\n","])\n","\n","display(ui)\n","print(\"👋 Ready! Upload your two .txt files and click the green button.\")"],"metadata":{"id":"smK4buMrqs9v"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"LaxF_cnIGNMh"},"source":["# ✍️ Convert a dataset into a combined text"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"trl0Eg8Xqy6B","executionInfo":{"status":"ok","timestamp":1777024555219,"user_tz":-120,"elapsed":99624,"user":{"displayName":"","userId":""}},"outputId":"ec757a1d-9949-42d3-ebc1-9feecbf65a3f","colab":{"base_uri":"https://localhost:8080/","height":287}},"outputs":[{"output_type":"stream","name":"stdout","text":["📤 Please upload your ZIP file (the one containing 1.txt, 2.txt, 3.txt, …)\n"]},{"output_type":"display_data","data":{"text/plain":[""],"text/html":["\n"," \n"," \n"," "]},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Saving TA-2026-04-24-11-51-46-988910702213220633.zip to TA-2026-04-24-11-51-46-988910702213220633.zip\n","✅ ZIP extracted to /content/extracted_txt_files\n","📄 Found 429 title files. Processing...\n","\n","✅ Done! Combined 429 titles into one line.\n","📁 Saved as: /content/combined_titles.txt\n"," (First 100 characters: {This is a digital cartoon illustration of a young woman with a stylized, exaggerated appearance. S...)\n"]},{"output_type":"display_data","data":{"text/plain":[""],"application/javascript":["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":[""],"application/javascript":["download(\"download_6e68886b-a05f-4a32-806c-ce844b817b2c\", \"combined_titles.txt\", 373035)"]},"metadata":{}},{"output_type":"stream","name":"stdout","text":["📥 Download started. You can now use this file wherever you need the {title1|title2|...} format.\n"]}],"source":["from google.colab import files\n","import zipfile\n","import os\n","from pathlib import Path\n","import shutil # Added for rmtree\n","\n","print(\"📤 Please upload your ZIP file (the one containing 1.txt, 2.txt, 3.txt, …)\")\n","\n","# Let the user upload the ZIP\n","uploaded = files.upload()\n","\n","# Find the uploaded ZIP file\n","zip_files = [f for f in uploaded.keys() if f.lower().endswith('.zip')]\n","if not zip_files:\n"," raise ValueError(\"❌ No .zip file was uploaded. Please try again.\")\n","\n","zip_filename = zip_files[0]\n","zip_path = f\"/content/{zip_filename}\"\n","\n","# Extract the ZIP to a temporary folder\n","extract_dir = \"/content/extracted_txt_files\"\n","\n","# --- Added: Clear the directory if it exists ---\n","if os.path.exists(extract_dir):\n"," shutil.rmtree(extract_dir)\n","# ---\n","os.makedirs(extract_dir, exist_ok=True)\n","\n","with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(extract_dir)\n","\n","print(f\"✅ ZIP extracted to {extract_dir}\")\n","\n","# Get all .txt files and sort them numerically (1.txt, 2.txt, 10.txt, etc.)\n","txt_paths = sorted(\n"," list(Path(extract_dir).glob(\"*.txt\")),\n"," key=lambda p: f\"{int(p.stem):05d}\" if p.stem.isdigit() else p.stem.lower()\n",")\n","\n","if not txt_paths:\n"," raise ValueError(\"❌ No .txt files found inside the ZIP!\")\n","\n","print(f\"📄 Found {len(txt_paths)} title files. Processing...\")\n","\n","# Read, clean, and combine titles\n","cleaned_titles = []\n","for txt_path in txt_paths:\n"," with open(txt_path, \"r\", encoding=\"utf-8\") as f:\n"," title = f.read().strip()\n","\n"," # Remove the forbidden characters: ^ { } | [] and newlines\n"," cleaned = (title\n"," .replace('^', '')\n"," .replace('{', '')\n"," .replace('}', '')\n"," .replace('|', '')\n"," .replace('\"','')\n"," .replace('>', '')\n"," .replace('<','')\n"," .replace('[','') # New: Remove opening bracket\n"," .replace(']','') # New: Remove closing bracket\n"," .replace('\\n', ' ')) # New: Replace newlines with spaces\n","\n"," cleaned_titles.append(cleaned)\n","\n","# Build the exact format you want: {text1|text2|text3|...}\n","combined_content = '{' + '|'.join(cleaned_titles) + '}'\n","\n","# Save to a single .txt file (no newlines)\n","output_file = \"/content/combined_titles.txt\"\n","with open(output_file, \"w\", encoding=\"utf-8\") as f:\n"," f.write(combined_content)\n","\n","# Confirmation\n","print(f\"\\n✅ Done! Combined {len(cleaned_titles)} titles into one line.\")\n","print(f\"📁 Saved as: {output_file}\")\n","print(f\" (First 100 characters: {combined_content[:100]}...)\")\n","\n","# Auto-download the combined file\n","files.download(output_file)\n","\n","print(\"📥 Download started. You can now use this file wherever you need the {title1|title2|...} format.\")"]},{"cell_type":"markdown","source":[],"metadata":{"id":"E82hTdUFaHZE"}},{"cell_type":"markdown","metadata":{"id":"tCD1B-_kaHuq"},"source":["# Extract image links from text and download them"]},{"cell_type":"code","source":["# ================================================\n","# 🌏 HTML Image Downloader + EXIF Metadata + Resize + Format Control\n","# ================================================\n","\n","#@title **🌏 HTML Image Downloader with EXIF Metadata**\n","\n","#@markdown ---\n","\n","#@markdown ### **Input**\n","use_file_upload = False #@param {type:\"boolean\"}\n","html_filepath = \"\" #@param {type:\"string\"}\n","#@markdown Try https://chromewebstore.google.com/detail/save-rendered-html/\"\n","\n","process_all_html_in_drive_folder = True #@param {type:\"boolean\"}\n","html_input_folder = \"/content/drive/MyDrive/html_grabs/\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","\n","#@markdown ### **Download & Processing Settings**\n","delay_seconds = 1.0 #@param {type:\"slider\", min:0, max:10, step:0.1}\n","max_longest_side_px = 2048 #@param {type:\"slider\", min:512, max:4096, step:64}\n","output_folder = \"fetched_from_html\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","\n","#@markdown ### **Image Output Settings**\n","output_format = \"JPEG\" #@param [\"JPEG\", \"PNG\", \"WEBP\"]\n","image_quality = 95 #@param {type:\"slider\", min:10, max:100, step:1}\n","extract_exif_metadata = False #@param {type:\"boolean\"}\n","\n","#@markdown ---\n","\n","#@markdown ### **Google Drive Options**\n","save_to_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"html_fetch\" #@param {type:\"string\"}\n","\n","encrypt_dataset = False #@param {type:\"boolean\"}\n","encryption_password = \"banana\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","#@markdown **Run this cell after uploading your HTML file (if enabled) or setting `html_filepath`**\n","\n","# ================================================\n","# ================== CODE START ==================\n","# ================================================\n","\n","!pip install beautifulsoup4 lxml pynacl -q\n","\n","import requests\n","from bs4 import BeautifulSoup\n","import os, time, hashlib, shutil, zipfile, glob\n","from urllib.parse import urljoin, urlparse\n","from PIL import Image, ExifTags\n","import io\n","from nacl.secret import SecretBox\n","from nacl.utils import random\n","from google.colab import drive, files\n","from datetime import datetime\n","\n","# ====================== UPLOAD HTML FILE / GET ALL HTML CONTENTS ======================\n","def get_all_html_contents():\n"," html_contents_list = []\n"," if process_all_html_in_drive_folder:\n"," print(f\"Processing all HTML files in: {html_input_folder}\")\n"," drive.mount('/content/drive', force_remount=False) # Ensure drive is mounted\n"," if not os.path.exists(html_input_folder):\n"," print(f\"❌ HTML input folder not found: {html_input_folder}\")\n"," return []\n"," for root, _, files_in_dir in os.walk(html_input_folder):\n"," for fname in files_in_dir:\n"," if fname.lower().endswith(('.html', '.htm')):\n"," full_path = os.path.join(root, fname)\n"," try:\n"," with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:\n"," content = f.read()\n"," # Sanitize content\n"," content = content.encode('utf-8', errors='replace').decode('utf-8')\n"," html_contents_list.append((fname, content))\n"," print(f\"✅ Loaded HTML file: {fname}\")\n"," except Exception as e:\n"," print(f\"❌ Error reading {fname}: {e}\")\n"," if not html_contents_list:\n"," print(f\"❌ No HTML files found in {html_input_folder}.\")\n"," return html_contents_list\n"," else:\n"," # Original logic for single file\n"," html_content = \"\"\n"," html_filename = \"single_input.html\" # Default name for single input case\n"," if use_file_upload:\n"," print(\"Please upload your HTML file:\")\n"," uploaded = files.upload()\n"," if not uploaded:\n"," print(\"❌ No HTML file uploaded!\")\n"," return []\n"," html_filename = list(uploaded.keys())[0]\n"," html_content = uploaded[html_filename].decode('utf-8', errors='ignore')\n"," else: # Use filepath from parameter\n"," if html_filepath and os.path.exists(html_filepath):\n"," print(f\"Reading HTML from file: {html_filepath}\")\n"," with open(html_filepath, 'r', encoding='utf-8', errors='ignore') as f:\n"," html_content = f.read()\n"," html_filename = os.path.basename(html_filepath)\n"," else:\n"," print(f\"❌ HTML filepath not found, empty, or 'use_file_upload' is True but no file was uploaded: {html_filepath}\")\n"," return []\n","\n"," html_content = html_content.encode('utf-8', errors='replace').decode('utf-8')\n"," return [(html_filename, html_content)]\n","\n","# ====================== EXTRACT IMAGE URLS ======================\n","def extract_image_urls(html_text):\n"," if not html_text.strip():\n"," return []\n"," soup = BeautifulSoup(html_text, 'html.parser')\n"," urls = []\n"," for img in soup.find_all('img'):\n"," src = img.get('src') or img.get('data-src') or img.get('data-original') or img.get('data-lazy-src')\n"," if src and src.startswith(('http://', 'https://')): # Only absolute URLs since base_url was removed\n"," urls.append(src)\n"," return list(dict.fromkeys(urls))\n","\n","# ====================== EXTRACT EXIF METADATA ======================\n","def save_exif_metadata(image_path, txt_path):\n"," try:\n"," with Image.open(image_path) as img:\n"," exif = img._getexif()\n"," if exif:\n"," with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"=== EXIF METADATA ===\\n\")\n"," f.write(f\"Extracted on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\")\n"," for tag_id, value in exif.items():\n"," tag_name = ExifTags.TAGS.get(tag_id, f\"Unknown_Tag_{tag_id}\")\n"," f.write(f\"{tag_name}: {value}\\n\")\n"," else:\n"," with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"No EXIF metadata found in this image.\")\n"," except Exception as e:\n"," with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(f\"Failed to read metadata: {e}\")\n","\n","# ====================== MAIN PROCESS ======================\n","print(\"\\u21ba Starting process...\\n\")\n","\n","all_html_inputs = get_all_html_contents()\n","\n","if not all_html_inputs:\n"," print(\"\\u274c No HTML content to process!\")\n","else:\n"," all_extracted_urls = []\n"," for html_filename, html_content in all_html_inputs:\n"," print(f\"Extracting URLs from: {html_filename}\")\n"," urls_from_this_html = extract_image_urls(html_content)\n"," print(f\" Found {len(urls_from_this_html)} URLs in {html_filename}.\")\n"," all_extracted_urls.extend(urls_from_this_html)\n","\n"," unique_urls = list(dict.fromkeys(all_extracted_urls)) # Remove duplicates\n"," print(f\"\\uD83D\\uDD0D Found {len(unique_urls)} unique images across all HTML files. Starting download...\\n\")\n","\n"," os.makedirs(output_folder, exist_ok=True)\n"," headers = {'User-Agent': 'Mozilla/5.0'}\n","\n"," downloaded_counter = 0\n"," for i, url in enumerate(unique_urls, 1):\n"," try:\n"," r = requests.get(url, headers=headers, timeout=15, stream=True)\n"," r.raise_for_status()\n","\n"," temp_path = os.path.join(output_folder, f\"temp_{i:04d}.tmp\")\n"," with open(temp_path, 'wb') as f:\n"," for chunk in r.iter_content(8192):\n"," f.write(chunk)\n","\n"," # Process image\n"," with Image.open(temp_path) as img:\n"," original_mode = img.mode\n"," if img.mode in ('RGBA', 'P'):\n"," img = img.convert('RGB')\n","\n"," was_resized = False\n"," w, h = img.size\n"," if max(w, h) > max_longest_side_px:\n"," scale = max_longest_side_px / max(w, h)\n"," new_size = (int(w * scale), int(h * scale))\n"," img = img.resize(new_size, Image.LANCZOS)\n"," was_resized = True\n","\n"," # Final filename\n"," ext = \".jpg\" if output_format == \"JPEG\" else \".png\" if output_format == \"PNG\" else \".webp\"\n"," final_name = f\"{i:04d}{ext}\"\n"," final_path = os.path.join(output_folder, final_name)\n","\n"," # Save with selected format & quality\n"," if output_format == \"JPEG\":\n"," img.save(final_path, quality=image_quality, optimize=True)\n"," elif output_format == \"PNG\":\n"," img.save(final_path, compress_level=6)\n"," else:\n"," img.save(final_path, quality=image_quality)\n","\n"," # Save EXIF metadata if requested\n"," if extract_exif_metadata:\n"," txt_path = os.path.join(output_folder, f\"{i:04d}.txt\")\n"," save_exif_metadata(final_path, txt_path)\n","\n"," # Clean temp file\n"," os.remove(temp_path)\n"," downloaded_counter += 1\n"," print(f\"\\u2705 {downloaded_counter:04d} saved\")\n","\n"," except Exception as e:\n"," print(f\"\\u274c Failed {i:04d}: {url[:70]}...\")\n","\n"," if i < len(unique_urls) and delay_seconds > 0:\n"," time.sleep(delay_seconds)\n","\n"," print(f\"\\n\\uD83C\\uDF89 All {downloaded_counter} images processed and renamed as 0001, 0002, 0003...\")\n","\n"," # ====================== SAVE TO DRIVE ======================\n"," if save_to_drive:\n"," drive.mount('/content/drive', force_remount=True)\n"," drive_path = f\"/content/drive/MyDrive/{drive_folder_name}\"\n"," os.makedirs(drive_path, exist_ok=True)\n","\n"," # Save html_filepath if it was used and not an upload\n"," # This logic needs adjustment if multiple HTML files were processed.\n"," # For now, we only record the html_filepath if a single file was processed via `html_filepath`.\n"," if not process_all_html_in_drive_folder and not use_file_upload and html_filepath and os.path.exists(html_filepath):\n"," filepath_record_path = os.path.join(drive_path, \"original_html_filepath.txt\")\n"," with open(filepath_record_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(html_filepath)\n"," print(f\"\\u2705 Original HTML filepath saved to Drive: {filepath_record_path}\")\n","\n"," # Save encryption password to password.txt\n"," if encryption_password:\n"," password_file_path = os.path.join(drive_path, \"password.txt\")\n"," with open(password_file_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(encryption_password)\n"," print(f\"\\u2705 Encryption password saved to Drive: {password_file_path}\")\n","\n"," if encrypt_dataset and encryption_password:\n"," print(\"\\uD83D\\uDD10 Encryption feature is available (can be expanded if needed)\")\n"," # Encryption code can be added later if you want it back\n"," else:\n"," zip_path = shutil.make_archive(f\"/content/{output_folder}\", 'zip', output_folder)\n"," final_zip_path = os.path.join(drive_path, f\"{output_folder}.zip\")\n"," shutil.move(zip_path, final_zip_path)\n"," print(f\"\\u2705 ZIP file saved to Google Drive:\\n\\uD83D\\uDCC1 {final_zip_path}\")\n","\n"," # Clear the local output folder after zipping and moving\n"," shutil.rmtree(output_folder, ignore_errors=True)\n"," print(f\"\\u2705 Local folder '{output_folder}' cleared.\")\n","\n"," # Delete the HTML file from Drive after processing if it was read from a file\n"," if not process_all_html_in_drive_folder and not use_file_upload and html_filepath and os.path.exists(html_filepath):\n"," try:\n"," os.remove(html_filepath)\n"," print(f\"\\u2705 Original HTML file deleted from Drive: {html_filepath}\")\n"," except Exception as e:\n"," print(f\"\\u274c Error deleting original HTML file from Drive: {e}\")\n","\n"," print(\"\\n\\u2705 Process Completed!\")"],"metadata":{"id":"amxSvxVfaZRA","cellView":"form"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777933895516},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777712335154},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777583462762},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777422091655},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777421006488},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777419764093},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777418751342},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777073558366},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777044746967},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777040498127},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1777025607471},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776618633334},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776539208168},{"file_id":"1i7MOC_zTC0p3ahKdqNnCMwI0bDgpSzuf","timestamp":1776174545773},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776174524210},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776099016608},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776047314806},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1776045909917},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775998668181},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775950117798},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775949817699},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775946246702},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775894617939},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775893490401},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/fetch_from_reddit.ipynb","timestamp":1775849356252},{"file_id":"1mdMfryfIudXrlN1MWsiNjoXQjondKOah","timestamp":1775845568290},{"file_id":"/v2/external/notebooks/intro.ipynb","timestamp":1775575177068}],"collapsed_sections":["gSErGKBctoAc","V5i2-xwTGG4K","WX17R9Yc6U1A","qisU9VeIyzX2","0VlyEacYp7Pn","JrtsI98cmAxB","s40baE0G_wn7","lUIEma9C-36K","02aZcv2lB_hC","U27drDtMB53n","LaxF_cnIGNMh"]},"kernelspec":{"display_name":"Python 3","name":"python3"}},"nbformat":4,"nbformat_minor":0}
\ No newline at end of file
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "_gXEa0VE88VQ"
+ },
+ "outputs": [],
+ "source": [
+ "from google.colab import drive\n",
+ "drive.mount('/content/drive')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 🚀 Authenticate credentials for Reddit PRAW into Google colab Secrets"
+ ],
+ "metadata": {
+ "id": "gSErGKBctoAc"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "\n",
+ "**One-time setup** — after this, your notebook will automatically load Reddit credentials without prompts or hard-coded secrets.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "### Step 1: Create Your Reddit “Script” App\n",
+ "1. Go to: **[https://www.reddit.com/prefs/apps](https://www.reddit.com/prefs/apps)** (log in first)\n",
+ "2. Scroll to the bottom → click **“create another app”** (or **“create app”**)\n",
+ "3. Fill the form:\n",
+ " - **Name**: `Colab-PRAW-Script` (or any name you like)\n",
+ " - **App type**: Select **script** ← very important\n",
+ " - **Description**: (optional)\n",
+ " - **Redirect URI**: `http://localhost:8080`\n",
+ "4. Click **Create app**\n",
+ "\n",
+ "You will now see:\n",
+ "- **personal use script** → 14-character string → **REDDIT_CLIENT_ID**\n",
+ "- **secret** → long string → **REDDIT_CLIENT_SECRET**\n",
+ "\n",
+ "Copy both values.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "### Step 2: Choose Your User-Agent\n",
+ "Use this format (replace `yourusername` with your actual Reddit username):"
+ ],
+ "metadata": {
+ "id": "rst5O8t0tW7F"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ ""
+ ],
+ "metadata": {
+ "id": "rQPyne1Hr_CM"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "This will be your **REDDIT_USER_AGENT**.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "### Step 3: Add Secrets in Google Colab\n",
+ "1. Open your Colab notebook\n",
+ "2. In the left sidebar click the **🔑 Secrets** tab\n",
+ "3. Click **+ Add new secret** for each of these:\n",
+ "\n",
+ "| Secret Name | What to paste |\n",
+ "|------------------------|----------------------------------------------------|\n",
+ "| `REDDIT_CLIENT_ID` | 14-character string from Reddit |\n",
+ "| `REDDIT_CLIENT_SECRET` | The secret string from Reddit |\n",
+ "| `REDDIT_USER_AGENT` | `Colab-PRAW:v1.0 (by u/yourusername)` |\n",
+ "| `REDDIT_USERNAME` | Your Reddit username (no `u/`) |\n",
+ "| `REDDIT_PASSWORD` | Your Reddit account password |\n",
+ "\n",
+ "After each one, click **Add** and **Grant access** when prompted.\n",
+ "\n",
+ "---"
+ ],
+ "metadata": {
+ "id": "d4ikd1h7tbr5"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "#@markdown **Reddit PRAW Authentication with Colab Secrets**\n",
+ "\n",
+ "# Install PRAW (run once)\n",
+ "!pip install praw -q\n",
+ "\n",
+ "import praw\n",
+ "from google.colab import userdata\n",
+ "import getpass\n",
+ "\n",
+ "# === AUTHENTICATION (uses secrets first, falls back to prompt if missing) ===\n",
+ "def get_secret_or_prompt(key, prompt_text):\n",
+ " try:\n",
+ " return userdata.get(key)\n",
+ " except (KeyError, Exception):\n",
+ " return getpass.getpass(prompt_text)\n",
+ "\n",
+ "reddit = praw.Reddit(\n",
+ " client_id=get_secret_or_prompt(\"REDDIT_CLIENT_ID\", \"Enter your REDDIT_CLIENT_ID: \"),\n",
+ " client_secret=get_secret_or_prompt(\"REDDIT_CLIENT_SECRET\", \"Enter your REDDIT_CLIENT_SECRET: \"),\n",
+ " user_agent=get_secret_or_prompt(\"REDDIT_USER_AGENT\", \"Enter your REDDIT_USER_AGENT: \"),\n",
+ " username=get_secret_or_prompt(\"REDDIT_USERNAME\", \"Enter your REDDIT_USERNAME: \"),\n",
+ " password=get_secret_or_prompt(\"REDDIT_PASSWORD\", \"Enter your REDDIT_PASSWORD: \"),\n",
+ ")\n",
+ "\n",
+ "# Quick verification\n",
+ "print(\"✅ Successfully logged in as:\", reddit.user.me())\n",
+ "print(\"🔒 Read-only mode:\", reddit.read_only)"
+ ],
+ "metadata": {
+ "cellView": "form",
+ "id": "WLopd-NFtHwY"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "V5i2-xwTGG4K"
+ },
+ "source": [
+ "#🚀 Fetch content from Reddit"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# Image crop left rigt"
+ ],
+ "metadata": {
+ "id": "WX17R9Yc6U1A"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "-ewlMjrTga21",
+ "cellView": "form"
+ },
+ "outputs": [],
+ "source": [
+ "# === INTEGRATED REDDIT DOWNLOADER + MEDIA EXTRACTOR (Drive + Checkboxes + Sliders Edition) ===\n",
+ "# Replace BOTH of your previous cells with this single block and run it.\n",
+ "# All results (titles, links, images, frames, zips) are saved directly to your Google Drive.\n",
+ "# Images/frames are numbered sequentially (1.jpeg, 2.jpeg, ...) with optional paired .txt files.\n",
+ "\n",
+ "# @markdown ** Subreddit & Fetch Settings**\n",
+ "subreddit_name = \"celebnsfw\" # @param {type:\"string\"}\n",
+ "sort_method = \"new\" # @param [\"hot\", \"new\", \"top\"] {type:\"string\"}\n",
+ "num_posts_to_pull = 100 # @param {type:\"slider\", min:0, max:2000, step:100}\n",
+ "offset_index = 0 # @param {type:\"slider\", min:0, max:2000, step:100}\n",
+ "\n",
+ "# @markdown **✅ Functionality Checkboxes (select any combination)**\n",
+ "thumbnail_low_res = True # @param {type:\"boolean\"}\n",
+ "#1) Thumbnail download at low res\n",
+ "proper_image_download = False # @param {type:\"boolean\"}\n",
+ "#2) Proper image download including sub images in galleries\n",
+ "gif_frame_extraction = False # @param {type:\"boolean\"}\n",
+ "#3) GIF + RedGifs video → keyframe extraction (original files are NEVER saved)\n",
+ "combined_titles_txt = True # @param {type:\"boolean\"}\n",
+ "#4) Combined txt file of titles\n",
+ "pair_txt_with_media = False # @param {type:\"boolean\"}\n",
+ "#5) Adding txt files to saved images in zips as enumerated pairs (1.txt, 2.txt, ...)\n",
+ "debug_mode = False # @param {type:\"boolean\"}\n",
+ "#6) Enable detailed debug printouts during media processing\n",
+ "\n",
+ "import os\n",
+ "import shutil\n",
+ "import glob\n",
+ "import requests\n",
+ "import subprocess\n",
+ "from google.colab import files, drive\n",
+ "\n",
+ "if gif_frame_extraction:\n",
+ " # Install yt-dlp if it's not already installed (moved outside conditional block)\n",
+ " !pip install -q yt-dlp\n",
+ " import yt_dlp\n",
+ "\n",
+ "\n",
+ "# ========================== DRIVE SETUP ==========================\n",
+ "print(\" Mounting Google Drive...\")\n",
+ "drive.mount('/content/drive', force_remount=False)\n",
+ "\n",
+ "drive_base_dir = f\"/content/drive/MyDrive/{subreddit_name}_reddit_downloads\"\n",
+ "os.makedirs(drive_base_dir, exist_ok=True)\n",
+ "\n",
+ "# Local temp media storage (Not on Drive)\n",
+ "local_media_dir = f\"/content/temp_output/{subreddit_name}_media\"\n",
+ "if os.path.exists(local_media_dir): shutil.rmtree(local_media_dir)\n",
+ "os.makedirs(local_media_dir, exist_ok=True)\n",
+ "\n",
+ "local_output_dir = \"/content/output\"\n",
+ "os.makedirs(local_output_dir, exist_ok=True)\n",
+ "\n",
+ "print(f\" Individual images stay local; only Zips/Txt go to: {drive_base_dir}\")\n",
+ "\n",
+ "# ========================== FETCH POSTS ==========================\n",
+ "print(f\" Fetching up to {num_posts_to_pull} posts from r/{subreddit_name} ({sort_method} sorting, offset {offset_index})...\")\n",
+ "\n",
+ "sub = reddit.subreddit(subreddit_name)\n",
+ "\n",
+ "if sort_method == \"hot\":\n",
+ " iterator = sub.hot(limit=offset_index + num_posts_to_pull + 50)\n",
+ "elif sort_method == \"new\":\n",
+ " iterator = sub.new(limit=offset_index + num_posts_to_pull + 50)\n",
+ "elif sort_method == \"top\":\n",
+ " iterator = sub.top(limit=offset_index + num_posts_to_pull + 50)\n",
+ "else:\n",
+ " iterator = sub.hot(limit=offset_index + num_posts_to_pull + 50)\n",
+ "\n",
+ "all_posts = list(iterator)\n",
+ "posts = all_posts[offset_index : offset_index + num_posts_to_pull]\n",
+ "\n",
+ "print(f\"✅ Successfully fetched {len(posts)} posts.\")\n",
+ "\n",
+ "# === NEW: Filename suffix with actual fetched count + offset ===\n",
+ "fetch_suffix = f\"_{len(posts)}posts_offset{offset_index}\"\n",
+ "\n",
+ "titles = []\n",
+ "external_links = []\n",
+ "\n",
+ "for submission in posts:\n",
+ " cleaned_title = (submission.title\n",
+ " .replace('^', '').replace('{', '').replace('}', '').replace('|', '')\n",
+ " .replace('[','').replace(']','').replace('\"',''))\n",
+ " titles.append(cleaned_title)\n",
+ "\n",
+ " url = getattr(submission, 'url', None)\n",
+ " if (url and url.startswith(('http://', 'https://')) and\n",
+ " not any(domain in url for domain in ['reddit.com', 'redd.it'])):\n",
+ " external_links.append(url)\n",
+ "\n",
+ "# ========================== OPTION 4: Combined Titles TXT ==========================\n",
+ "if combined_titles_txt:\n",
+ " combined_content = '{' + '|'.join(titles) + '}'\n",
+ " titles_file_drive = f\"{drive_base_dir}/{subreddit_name}_titles{fetch_suffix}.txt\"\n",
+ " with open(titles_file_drive, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(combined_content)\n",
+ " print(f\" Combined titles saved → {titles_file_drive}\")\n",
+ "\n",
+ "# ========================== External Links ==========================\n",
+ "if external_links:\n",
+ " links_file = f\"{drive_base_dir}/{subreddit_name}_links{fetch_suffix}.txt\"\n",
+ " with open(links_file, \"w\", encoding=\"utf-8\") as f:\n",
+ " for link in external_links: f.write(link + \"\\n\")\n",
+ " print(f\" External links saved → {links_file}\")\n",
+ " print(f\" → {len(external_links)} links (mostly RedGifs)\")\n",
+ "\n",
+ "# ========================== MEDIA PROCESSING ==========================\n",
+ "any_media = thumbnail_low_res or proper_image_download or gif_frame_extraction\n",
+ "\n",
+ "if any_media:\n",
+ "\n",
+ " temp_dir = \"/content/temp_download\"\n",
+ " os.makedirs(temp_dir, exist_ok=True)\n",
+ "\n",
+ " global_counter = 1\n",
+ "\n",
+ " def save_media_and_txt(source, is_url=False, title=\"\"):\n",
+ " global global_counter\n",
+ " if is_url:\n",
+ " clean_url = source.split('?')[0]\n",
+ " ext = os.path.splitext(clean_url)[1].lower()\n",
+ " if ext not in ['.jpg', '.jpeg', '.png']: ext = '.jpg'\n",
+ " temp_file = f\"{temp_dir}/dl_{global_counter}{ext}\"\n",
+ " try:\n",
+ " r = requests.get(source, stream=True, timeout=60)\n",
+ " r.raise_for_status()\n",
+ " with open(temp_file, 'wb') as f:\n",
+ " for chunk in r.iter_content(8192): f.write(chunk)\n",
+ " except Exception:\n",
+ " return\n",
+ " else:\n",
+ " temp_file = source\n",
+ " ext = os.path.splitext(temp_file)[1].lower() or '.jpeg'\n",
+ "\n",
+ " local_path = f\"{local_media_dir}/{global_counter}{ext}\"\n",
+ " shutil.copy2(temp_file, local_path)\n",
+ "\n",
+ " if pair_txt_with_media:\n",
+ " with open(f\"{local_media_dir}/{global_counter}.txt\", \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(title)\n",
+ "\n",
+ " global_counter += 1\n",
+ " print(f\" ✅ Saved locally #{global_counter-1} \", end=\"\\r\")\n",
+ " if is_url and os.path.exists(temp_file): os.remove(temp_file)\n",
+ "\n",
+ " for idx, submission in enumerate(posts, 1):\n",
+ " cleaned_title = titles[idx-1]\n",
+ "\n",
+ " if thumbnail_low_res:\n",
+ " thumb_url = getattr(submission, 'thumbnail', None)\n",
+ " if thumb_url and thumb_url.startswith('http'):\n",
+ " save_media_and_txt(thumb_url, is_url=True, title=cleaned_title)\n",
+ "\n",
+ " if proper_image_download:\n",
+ " url = getattr(submission, 'url', None)\n",
+ " if url and any(url.lower().endswith(e) for e in ['.jpg', '.jpeg', '.png']):\n",
+ " save_media_and_txt(url, is_url=True, title=cleaned_title)\n",
+ "\n",
+ " # === GIF + RedGifs keyframe extraction (debug toggleable) ===\n",
+ " if gif_frame_extraction:\n",
+ " url = getattr(submission, 'url', None)\n",
+ " if url and url.startswith(('http://', 'https://')):\n",
+ " if debug_mode:\n",
+ " print(f\"\u001f DEBUG [{idx:03d}]: Checking URL → {url[:90]}...\")\n",
+ "\n",
+ " if url.lower().endswith('.gif') or 'redgifs.com' in url.lower():\n",
+ " if debug_mode:\n",
+ " print(f\"✅ DEBUG: Eligible for keyframe extraction → {url[:90]}...\")\n",
+ " temp_media = None\n",
+ " try:\n",
+ " # 1. Download\n",
+ " if url.lower().endswith('.gif'):\n",
+ " temp_media = f\"{temp_dir}/dl_gif_{idx}.gif\"\n",
+ " r = requests.get(url, stream=True, timeout=60)\n",
+ " r.raise_for_status()\n",
+ " with open(temp_media, 'wb') as f:\n",
+ " for chunk in r.iter_content(8192):\n",
+ " f.write(chunk)\n",
+ " if debug_mode:\n",
+ " print(f\" ↓ Downloaded GIF ({os.path.getsize(temp_media)/1024/1024:.1f} MB)\")\n",
+ " else:\n",
+ " # RedGifs video\n",
+ " temp_media = f\"{temp_dir}/dl_video_{idx}.mp4\"\n",
+ " ydl_opts = {\n",
+ " 'outtmpl': temp_media,\n",
+ " 'quiet': True,\n",
+ " 'no_warnings': True,\n",
+ " 'format': 'bestvideo+bestaudio/best',\n",
+ " 'merge_output_format': 'mp4',\n",
+ " }\n",
+ " with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n",
+ " ydl.download([url])\n",
+ " if debug_mode:\n",
+ " print(f\" ↓ Downloaded RedGifs video ({os.path.getsize(temp_media)/1024/1024:.1f} MB)\")\n",
+ "\n",
+ " # 2. Keyframe extraction\n",
+ " output_pattern = f\"{temp_dir}/kf_{idx}_%04d.jpg\"\n",
+ " cmd = [\n",
+ " 'ffmpeg', '-y', '-i', temp_media,\n",
+ " '-vf', \"select='gt(scene,0.15)',setpts=N/(FRAME_RATE*TB)\",\n",
+ " '-vsync', 'vfr',\n",
+ " '-q:v', '5',\n",
+ " output_pattern\n",
+ " ]\n",
+ " subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)\n",
+ " if debug_mode:\n",
+ " print(f\" 🏆 ffmpeg keyframe extraction finished (scene threshold 0.15)\")\n",
+ "\n",
+ " # 3. Save keyframes\n",
+ " extracted_frames = sorted(glob.glob(f\"{temp_dir}/kf_{idx}_*.jpg\"))\n",
+ " if debug_mode:\n",
+ " print(f\" 📎 Extracted {len(extracted_frames)} keyframes → saving to ZIP\")\n",
+ "\n",
+ " for frame_path in extracted_frames:\n",
+ " save_media_and_txt(frame_path, is_url=False, title=cleaned_title)\n",
+ " os.remove(frame_path)\n",
+ "\n",
+ " # 4. Cleanup original\n",
+ " if temp_media and os.path.exists(temp_media):\n",
+ " os.remove(temp_media)\n",
+ " if debug_mode:\n",
+ " print(f\" 🗑️ Cleaned up original media file\")\n",
+ "\n",
+ " except Exception as e:\n",
+ " if debug_mode:\n",
+ " print(f\" ⚠️ ERROR processing {url[:80]}... → {e}\")\n",
+ " if temp_media and os.path.exists(temp_media):\n",
+ " os.remove(temp_media)\n",
+ " continue\n",
+ "\n",
+ " print(f\"\\n\\n✅ MEDIA CACHED! Creating ZIP on Drive...\")\n",
+ " zip_name = f\"{subreddit_name}_media{fetch_suffix}\"\n",
+ " shutil.make_archive(f\"{drive_base_dir}/{zip_name}\", 'zip', local_media_dir)\n",
+ " print(f\" ZIP created on Drive → {drive_base_dir}/{zip_name}.zip\")\n",
+ "\n",
+ "print(\"\\n✨ ALL DONE!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "3b94280b"
+ },
+ "source": [
+ "### 🖼️ Image Cropper: 1024x1024 Left and Right Aligned"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {
+ "id": "d3ca4317"
+ },
+ "source": [
+ "from google.colab import drive\n",
+ "from PIL import Image\n",
+ "import os\n",
+ "import shutil\n",
+ "import glob\n",
+ "import zipfile\n",
+ "\n",
+ "# @markdown **Configuration**\n",
+ "input_image_directory = \"/content\" # @param {type:\"string\"}\n",
+ "output_drive_folder = \"cropped_1024x1024_images\" # @param {type:\"string\"}\n",
+ "target_size = 1024 # @param {type:\"integer\"}\n",
+ "resize_smaller_images = True # @param {type:\"boolean\"}\n",
+ "\n",
+ "# Mount Google Drive\n",
+ "print(\"🔄 Mounting Google Drive...\")\n",
+ "drive.mount('/content/drive', force_remount=True)\n",
+ "\n",
+ "# Define output paths\n",
+ "drive_base_path = '/content/drive/MyDrive'\n",
+ "drive_output_folder_path = os.path.join(drive_base_path, output_drive_folder)\n",
+ "\n",
+ "# Create a temporary local directory for cropped images before zipping\n",
+ "local_temp_crop_dir = '/content/temp_cropped_images'\n",
+ "os.makedirs(local_temp_crop_dir, exist_ok=True)\n",
+ "\n",
+ "print(f\"\\n🔍 Scanning for images in {input_image_directory}...\")\n",
+ "image_files = []\n",
+ "for ext in ('*.png', '*.jpg', '*.jpeg', '*.webp'):\n",
+ " image_files.extend(glob.glob(os.path.join(input_image_directory, ext)))\n",
+ "\n",
+ "if not image_files:\n",
+ " print(f\"❌ No image files found in {input_image_directory}. Please ensure images are present or check the directory path.\")\n",
+ "else:\n",
+ " print(f\"✅ Found {len(image_files)} image(s) to process.\")\n",
+ " processed_count = 0\n",
+ " skipped_count = 0\n",
+ "\n",
+ " for file_path in image_files:\n",
+ " filename = os.path.basename(file_path)\n",
+ " print(f\"\\nProcessing {filename}...\")\n",
+ " try:\n",
+ " img = Image.open(file_path)\n",
+ "\n",
+ " if img.mode != 'RGB':\n",
+ " img = img.convert('RGB')\n",
+ "\n",
+ " width, height = img.size\n",
+ "\n",
+ " if width < target_size or height < target_size:\n",
+ " if resize_smaller_images:\n",
+ " print(f\"⚠️ Image dimensions ({width}x{height}) are smaller than target {target_size}x{target_size}. Resizing...\")\n",
+ " if width < height:\n",
+ " new_width = target_size\n",
+ " new_height = int(height * (target_size / width))\n",
+ " else:\n",
+ " new_height = target_size\n",
+ " new_width = int(width * (target_size / height))\n",
+ " img = img.resize((new_width, new_height), Image.LANCZOS)\n",
+ " width, height = img.size\n",
+ " print(f\" Resized to {width}x{height}.\")\n",
+ " else:\n",
+ " print(f\"⚠️ Skipping {filename}: Image dimensions ({width}x{height}) are smaller than target {target_size}x{target_size}.\")\n",
+ " skipped_count += 1\n",
+ " continue\n",
+ "\n",
+ " # --- Left-aligned crop ---\n",
+ " left_crop_box = (0, 0, target_size, target_size)\n",
+ " img_left_cropped = img.crop(left_crop_box)\n",
+ " output_name_left = f\"{os.path.splitext(filename)[0]}_left_{target_size}x{target_size}.jpg\"\n",
+ " img_left_cropped.save(os.path.join(local_temp_crop_dir, output_name_left))\n",
+ " print(f\" ✅ Saved left-aligned crop to temp: {output_name_left}\")\n",
+ "\n",
+ " # --- Right-aligned crop ---\n",
+ " right_x_start = width - target_size\n",
+ " right_crop_box = (right_x_start, 0, width, target_size)\n",
+ " img_right_cropped = img.crop(right_crop_box)\n",
+ " output_name_right = f\"{os.path.splitext(filename)[0]}_right_{target_size}x{target_size}.jpg\"\n",
+ " img_right_cropped.save(os.path.join(local_temp_crop_dir, output_name_right))\n",
+ " print(f\" ✅ Saved right-aligned crop to temp: {output_name_right}\")\n",
+ "\n",
+ " processed_count += 1\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error processing {filename}: {e}\")\n",
+ " skipped_count += 1\n",
+ "\n",
+ " print(f\"\\n✨ Processing complete! {processed_count} images processed, {skipped_count} skipped.\")\n",
+ "\n",
+ " # Create ZIP file\n",
+ " if processed_count > 0:\n",
+ " os.makedirs(drive_output_folder_path, exist_ok=True)\n",
+ " zip_filename = f\"{output_drive_folder}.zip\"\n",
+ " zip_path_on_drive = os.path.join(drive_output_folder_path, zip_filename)\n",
+ "\n",
+ " print(f\"\\n📦 Creating ZIP file '{zip_filename}' in Google Drive...\")\n",
+ " shutil.make_archive(os.path.join(drive_output_folder_path, output_drive_folder), 'zip', local_temp_crop_dir)\n",
+ " print(f\"✅ All cropped images zipped and saved to: {zip_path_on_drive}\")\n",
+ " else:\n",
+ " print(\"No images were processed to be zipped.\")\n",
+ "\n",
+ " # Clean up local temporary directory\n",
+ " shutil.rmtree(local_temp_crop_dir)\n",
+ " print(\"🗑️ Cleaned up local temporary cropped images directory.\")\n"
+ ],
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "qisU9VeIyzX2"
+ },
+ "source": [
+ "# 🎮 itch.io (Indie Game Website) fetch"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "HDCueX6d3K00",
+ "cellView": "form"
+ },
+ "outputs": [],
+ "source": [
+ "#@markdown # 🐙 itch.io Image-Text Dataset Creator\n",
+ "#@markdown **Fetch enumerated thumbnails + matching TXT files → ZIP → Google Drive**\n",
+ "\n",
+ "#@markdown ---\n",
+ "#@markdown ### 📋 Choose your settings below then **Run this cell**\n",
+ "\n",
+ "num_games = 1000 #@param {type:\"slider\", min:10, max:5000, step:10, description:\"How many games to fetch\"}\n",
+ "\n",
+ "sort_by = \"Most Recent\" #@param [\"Popular (default)\", \"New & Popular\", \"Top Sellers\", \"Top Rated\", \"Most Recent\"]\n",
+ "\n",
+ "subcategory = \"None (All Games)\" #@param [\"None (All Games)\", \"Genre: Action\", \"Genre: Adventure\", \"Genre: Arcade\", \"Genre: Card Game\", \"Genre: Educational\", \"Genre: Fighting\", \"Genre: Platformer\", \"Genre: Puzzle\", \"Genre: RPG\", \"Genre: Shooter\", \"Genre: Simulation\", \"Genre: Strategy\", \"Genre: Visual Novel\", \"Platform: Web\", \"Platform: Windows\", \"Platform: macOS\", \"Platform: Linux\", \"Platform: Android\", \"Tag: 2D\", \"Tag: Pixel Art\", \"Tag: Horror\", \"Tag: Multiplayer\", \"Tag: Roguelike\", \"Tag: Retro\"]\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown **After changing the values above, just click the ▶️ Run button on this cell.**\n",
+ "\n",
+ "# ================================================\n",
+ "# ✅ READY-TO-RUN COLAB CELL (single cell version)\n",
+ "# ================================================\n",
+ "\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "import os\n",
+ "import re\n",
+ "import json\n",
+ "import time\n",
+ "import shutil\n",
+ "import datetime\n",
+ "from urllib.parse import urljoin\n",
+ "from IPython.display import display, HTML, Image\n",
+ "from google.colab import drive\n",
+ "\n",
+ "print(\"✅ Starting itch.io scraper with your chosen settings...\")\n",
+ "\n",
+ "# ====================== MAP USER CHOICES TO URL SLUGS ======================\n",
+ "sort_map = {\n",
+ " \"Popular (default)\": \"\",\n",
+ " \"New & Popular\": \"new-and-popular\",\n",
+ " \"Top Sellers\": \"top-sellers\",\n",
+ " \"Top Rated\": \"top-rated\",\n",
+ " \"Most Recent\": \"newest\"\n",
+ "}\n",
+ "\n",
+ "filter_map = {\n",
+ " \"None (All Games)\": \"\",\n",
+ " \"Genre: Action\": \"genre-action\",\n",
+ " \"Genre: Adventure\": \"genre-adventure\",\n",
+ " \"Genre: Arcade\": \"genre-arcade\",\n",
+ " \"Genre: Card Game\": \"genre-card-game\",\n",
+ " \"Genre: Educational\": \"genre-educational\",\n",
+ " \"Genre: Fighting\": \"genre-fighting\",\n",
+ " \"Genre: Platformer\": \"genre-platformer\",\n",
+ " \"Genre: Puzzle\": \"genre-puzzle\",\n",
+ " \"Genre: RPG\": \"genre-rpg\",\n",
+ " \"Genre: Shooter\": \"genre-shooter\",\n",
+ " \"Genre: Simulation\": \"genre-simulation\",\n",
+ " \"Genre: Strategy\": \"genre-strategy\",\n",
+ " \"Genre: Visual Novel\": \"genre-visual-novel\",\n",
+ " \"Platform: Web\": \"platform-web\",\n",
+ " \"Platform: Windows\": \"platform-windows\",\n",
+ " \"Platform: macOS\": \"platform-macos\",\n",
+ " \"Platform: Linux\": \"platform-linux\",\n",
+ " \"Platform: Android\": \"platform-android\",\n",
+ " \"Tag: 2D\": \"tag-2d\",\n",
+ " \"Tag: Pixel Art\": \"tag-pixel-art\",\n",
+ " \"Tag: Horror\": \"tag-horror\",\n",
+ " \"Tag: Multiplayer\": \"tag-multiplayer\",\n",
+ " \"Tag: Roguelike\": \"tag-roguelike\",\n",
+ " \"Tag: Retro\": \"tag-retro\"\n",
+ "}\n",
+ "\n",
+ "sort_slug = sort_map[sort_by]\n",
+ "filter_slug = filter_map[subcategory]\n",
+ "\n",
+ "# ====================== CONFIG ======================\n",
+ "MAX_PAGES = 20\n",
+ "DELAY_BETWEEN_PAGES = 1.5\n",
+ "HEADERS = {\n",
+ " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n",
+ " \"(KHTML, like Gecko) Chrome/134.0 Safari/537.36\"\n",
+ "}\n",
+ "\n",
+ "# Build the base URL according to user selections\n",
+ "base_url = \"https://itch.io/games\"\n",
+ "if sort_slug:\n",
+ " base_url += f\"/{sort_slug}\"\n",
+ "if filter_slug:\n",
+ " base_url += f\"/{filter_slug}\"\n",
+ "\n",
+ "print(f\"🌐 Target: {base_url} | Fetching up to {num_games} games\")\n",
+ "\n",
+ "# Mount Google Drive\n",
+ "print(\"🔄 Mounting Google Drive...\")\n",
+ "drive.mount('/content/drive', force_remount=True)\n",
+ "\n",
+ "# Create working folder\n",
+ "dataset_dir = \"/content/itch_dataset\"\n",
+ "os.makedirs(dataset_dir, exist_ok=True)\n",
+ "\n",
+ "# ====================== SCRAPE MULTIPLE PAGES ======================\n",
+ "pairs = []\n",
+ "page = 1\n",
+ "\n",
+ "while len(pairs) < num_games and page <= MAX_PAGES:\n",
+ " url = f\"{base_url}?page={page}\" if page > 1 else base_url\n",
+ " print(f\"📄 Scraping page {page} → {url}\")\n",
+ "\n",
+ " try:\n",
+ " response = requests.get(url, headers=HEADERS, timeout=20)\n",
+ " if response.status_code != 200:\n",
+ " print(f\"❌ Page {page} failed (HTTP {response.status_code})\")\n",
+ " break\n",
+ "\n",
+ " soup = BeautifulSoup(response.text, \"html.parser\")\n",
+ " game_cells = soup.find_all(\"div\", class_=\"game_cell\")\n",
+ "\n",
+ " if not game_cells:\n",
+ " print(\"✅ No more games on this page.\")\n",
+ " break\n",
+ "\n",
+ " added = 0\n",
+ " for cell in game_cells:\n",
+ " if len(pairs) >= num_games:\n",
+ " break\n",
+ "\n",
+ " # Clean title (no price spam)\n",
+ " title_tag = cell.find(\"div\", class_=\"game_title\")\n",
+ " if not title_tag:\n",
+ " continue\n",
+ " title_link = title_tag.find(\"a\", class_=\"title\")\n",
+ " title = title_link.get_text(strip=True) if title_link else title_tag.get_text(strip=True).split(\"$\")[0].strip()\n",
+ " if not title:\n",
+ " continue\n",
+ "\n",
+ " # Extract thumbnail (robust for current itch.io layout)\n",
+ " img_url = None\n",
+ " img_tag = cell.find(\"img\")\n",
+ " if img_tag:\n",
+ " for attr in [\"data-lazy-src\", \"data-lazy_src\", \"data-src\", \"src\"]:\n",
+ " img_url = img_tag.get(attr)\n",
+ " if img_url:\n",
+ " break\n",
+ " if not img_url and img_tag.get(\"srcset\"):\n",
+ " img_url = img_tag.get(\"srcset\").split(\",\")[0].strip().split(\" \")[0]\n",
+ "\n",
+ " # Fallback: background-image\n",
+ " if not img_url:\n",
+ " for el in cell.find_all(lambda t: t.has_attr(\"style\") and \"background-image\" in t.get(\"style\", \"\").lower()):\n",
+ " style = el.get(\"style\", \"\")\n",
+ " match = re.search(r'background-image\\s*:\\s*url\\([\\'\\\"]?([^\\'\\\"]+)[\\'\\\"]?\\)', style, re.IGNORECASE)\n",
+ " if match:\n",
+ " img_url = match.group(1)\n",
+ " break\n",
+ "\n",
+ " if img_url:\n",
+ " if img_url.startswith(\"//\"):\n",
+ " img_url = \"https:\" + img_url\n",
+ " elif not img_url.startswith((\"http://\", \"https://\")):\n",
+ " img_url = urljoin(\"https://itch.io\", img_url)\n",
+ "\n",
+ " pairs.append((title, img_url))\n",
+ " added += 1\n",
+ "\n",
+ " print(f\" → Added {added} games (total so far: {len(pairs)})\")\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error on page {page}: {e}\")\n",
+ " break\n",
+ "\n",
+ " page += 1\n",
+ " time.sleep(DELAY_BETWEEN_PAGES)\n",
+ "\n",
+ "if not pairs:\n",
+ " print(\"❌ No games found with current filters. Try different settings.\")\n",
+ "else:\n",
+ " print(f\"\\n✅ Collected {len(pairs)} games. Downloading images and creating TXT files...\")\n",
+ "\n",
+ " # ====================== DOWNLOAD ENUMERATED FILES ======================\n",
+ " downloaded = 0\n",
+ " for idx, (title, img_url) in enumerate(pairs, start=1):\n",
+ " num_str = f\"{idx:04d}\"\n",
+ " img_path = f\"{dataset_dir}/{num_str}.jpg\"\n",
+ " txt_path = f\"{dataset_dir}/{num_str}.txt\"\n",
+ "\n",
+ " try:\n",
+ " img_response = requests.get(img_url, headers=HEADERS, timeout=15)\n",
+ " if img_response.status_code == 200:\n",
+ " with open(img_path, \"wb\") as f:\n",
+ " f.write(img_response.content)\n",
+ " with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(title)\n",
+ " downloaded += 1\n",
+ " if downloaded % 10 == 0 or downloaded == len(pairs):\n",
+ " print(f\" ✅ Saved {downloaded:04d}.jpg + {num_str}.txt\")\n",
+ " else:\n",
+ " print(f\"⚠️ Failed to download image {num_str}\")\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error downloading {num_str}: {e}\")\n",
+ "\n",
+ " # ====================== CREATE ZIP & SAVE TO DRIVE ======================\n",
+ " timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
+ " zip_name = f\"itch_games_{timestamp}\"\n",
+ " zip_path_local = f\"/content/{zip_name}.zip\"\n",
+ "\n",
+ " print(f\"\\n🗜️ Creating ZIP file with {downloaded} image+txt pairs...\")\n",
+ " shutil.make_archive(f\"/content/{zip_name}\", 'zip', dataset_dir)\n",
+ "\n",
+ " # Copy to Google Drive\n",
+ " drive_folder = \"/content/drive/MyDrive/itch_datasets\"\n",
+ " os.makedirs(drive_folder, exist_ok=True)\n",
+ " drive_zip_path = f\"{drive_folder}/{zip_name}.zip\"\n",
+ " shutil.copy(zip_path_local, drive_zip_path)\n",
+ "\n",
+ " print(\"\\n\" + \"=\"*80)\n",
+ " print(\"🎉 SUCCESS! Your dataset is ready\")\n",
+ " print(f\"📦 ZIP file: {zip_name}.zip\")\n",
+ " print(f\"📤 Saved to Google Drive → {drive_zip_path}\")\n",
+ " print(f\" • Files inside: 0001.jpg + 0001.txt, 0002.jpg + 0002.txt, ...\")\n",
+ " print(f\" • Total pairs: {downloaded}\")\n",
+ " print(\"=\"*80)\n",
+ "\n",
+ " # ====================== PREVIEW FIRST 3 PAIRS ======================\n",
+ " print(\"\\n📸 Preview of first 3 pairs (click images to enlarge):\")\n",
+ " for i in range(min(3, len(pairs))):\n",
+ " num_str = f\"{i+1:04d}\"\n",
+ " img_file = f\"{dataset_dir}/{num_str}.jpg\"\n",
+ " display(HTML(f\"{num_str}. {pairs[i][0]}
\"))\n",
+ " display(Image(filename=img_file, width=400))\n",
+ " print(\"─\" * 70)\n",
+ "\n",
+ " print(f\"\\n✅ All files are also in: {dataset_dir} (you can download the folder manually if needed)\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 📚 VNDB (Visual Novel Database) fetch"
+ ],
+ "metadata": {
+ "id": "0VlyEacYp7Pn"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "70mWljq0EJCT",
+ "cellView": "form"
+ },
+ "outputs": [],
+ "source": [
+ "#@markdown # 🐙 VNDB Image-Text fetch\n",
+ "#@markdown **✅ Added offset slider + metadata in ZIP**\n",
+ "#@markdown Now you can fetch any batch (e.g. first 1000 → offset 0, next 1000 → offset 1000, etc.)\n",
+ "\n",
+ "#@markdown ---\n",
+ "#@markdown ### 📋 Choose your settings below then **Run this cell**\n",
+ "\n",
+ "num_vns = 1000 #@param {type:\"slider\", min:10, max:5000, step:10, description:\"How many visual novels to fetch in this batch\"}\n",
+ "\n",
+ "offset = 0 #@param {type:\"slider\", min:0, max:20000, step:100}\n",
+ "#description:\"Offset: skip this many VNs before starting (0 = first batch, 1000 = second batch, etc.)\"}\n",
+ "\n",
+ "sort_by = \"Most Recent (released desc)\" #@param [\"Most Recent (released desc)\", \"Highest Rated\", \"Most Voted\"]\n",
+ "\n",
+ "#@markdown **Tag ID** (from your link: https://vndb.org/g3560)\n",
+ "tag_id = \"g3560\" #@param {type:\"string\", description:\"VNDB tag ID (e.g. g3560 = 3D Graphics)\"}\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown **After changing the values above, just click the ▶️ Run button on this cell.**\n",
+ "\n",
+ "# ================================================\n",
+ "# ✅ FULLY DEBUGGED + OFFSET + METADATA READY-TO-RUN COLAB CELL\n",
+ "# ================================================\n",
+ "\n",
+ "import requests\n",
+ "import os\n",
+ "import json\n",
+ "import time\n",
+ "import shutil\n",
+ "import datetime\n",
+ "from IPython.display import display, HTML, Image\n",
+ "from google.colab import drive\n",
+ "\n",
+ "print(\"✅ Starting VNDB scraper with OFFSET support...\")\n",
+ "\n",
+ "# ====================== CONFIG ======================\n",
+ "MAX_RESULTS_PER_PAGE = 100\n",
+ "DELAY_BETWEEN_PAGES = 0.5\n",
+ "HEADERS = {\n",
+ " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n",
+ " \"(KHTML, like Gecko) Chrome/134.0 Safari/537.36\",\n",
+ " \"Content-Type\": \"application/json\"\n",
+ "}\n",
+ "\n",
+ "API_URL = \"https://api.vndb.org/kana/vn\"\n",
+ "\n",
+ "# Sort mapping\n",
+ "sort_map = {\n",
+ " \"Most Recent (released desc)\": {\"sort\": \"released\", \"reverse\": True},\n",
+ " \"Highest Rated\": {\"sort\": \"rating\", \"reverse\": True},\n",
+ " \"Most Voted\": {\"sort\": \"votecount\", \"reverse\": True}\n",
+ "}\n",
+ "\n",
+ "selected_sort = sort_map[sort_by]\n",
+ "\n",
+ "print(f\"🌐 Target: VNDB Tag {tag_id} | Offset: {offset} | Fetching up to {num_vns} VNs (sorted by {sort_by})\")\n",
+ "\n",
+ "# Mount Google Drive\n",
+ "print(\"🔄 Mounting Google Drive...\")\n",
+ "drive.mount('/content/drive', force_remount=True)\n",
+ "\n",
+ "# Create working folder\n",
+ "dataset_dir = \"/content/vndb_dataset\"\n",
+ "os.makedirs(dataset_dir, exist_ok=True)\n",
+ "\n",
+ "# ====================== CALCULATE PAGINATION WITH OFFSET ======================\n",
+ "start_page = (offset // MAX_RESULTS_PER_PAGE) + 1\n",
+ "skip_in_first_page = offset % MAX_RESULTS_PER_PAGE\n",
+ "\n",
+ "print(f\"📌 Calculated start_page = {start_page}, skip first {skip_in_first_page} items on that page\")\n",
+ "\n",
+ "# ====================== FETCH VIA VNDB KANA API ======================\n",
+ "pairs = []\n",
+ "page = start_page\n",
+ "items_collected = 0\n",
+ "\n",
+ "while len(pairs) < num_vns:\n",
+ " payload = {\n",
+ " \"filters\": [\"tag\", \"=\", tag_id],\n",
+ " \"fields\": \"id, title, image.url\",\n",
+ " \"sort\": selected_sort[\"sort\"],\n",
+ " \"reverse\": selected_sort[\"reverse\"],\n",
+ " \"results\": MAX_RESULTS_PER_PAGE,\n",
+ " \"page\": page\n",
+ " }\n",
+ "\n",
+ " # ==================== FULL DEBUG PRINT ====================\n",
+ " print(f\"\\n📄 === API REQUEST PAGE {page} (offset={offset}) ===\")\n",
+ " print(\"Payload sent:\")\n",
+ " print(json.dumps(payload, indent=2))\n",
+ " # ========================================================\n",
+ "\n",
+ " try:\n",
+ " response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=30)\n",
+ "\n",
+ " print(f\" 📡 Status code: {response.status_code}\")\n",
+ "\n",
+ " if response.status_code != 200:\n",
+ " print(\" ❌ ERROR RESPONSE BODY:\")\n",
+ " try:\n",
+ " error_json = response.json()\n",
+ " print(json.dumps(error_json, indent=2))\n",
+ " except:\n",
+ " print(response.text[:1000])\n",
+ " break\n",
+ "\n",
+ " data = response.json()\n",
+ " results = data.get(\"results\", [])\n",
+ "\n",
+ " if not results:\n",
+ " print(\"✅ No more results.\")\n",
+ " break\n",
+ "\n",
+ " # Handle offset skipping on the very first page we fetch\n",
+ " if page == start_page and skip_in_first_page > 0:\n",
+ " print(f\" ⏭️ Skipping first {skip_in_first_page} items due to offset\")\n",
+ " results = results[skip_in_first_page:]\n",
+ " skip_in_first_page = 0\n",
+ "\n",
+ " added = 0\n",
+ " for vn in results:\n",
+ " if len(pairs) >= num_vns:\n",
+ " break\n",
+ "\n",
+ " title = vn.get(\"title\", \"\").strip()\n",
+ " if not title:\n",
+ " continue\n",
+ "\n",
+ " img_url = vn.get(\"image\", {}).get(\"url\") if isinstance(vn.get(\"image\"), dict) else None\n",
+ "\n",
+ " if img_url:\n",
+ " pairs.append((title, img_url))\n",
+ " added += 1\n",
+ " items_collected += 1\n",
+ "\n",
+ " print(f\" → Added {added} VNs (total so far: {len(pairs)})\")\n",
+ "\n",
+ " if not data.get(\"more\", False):\n",
+ " print(\"✅ Reached the end of results.\")\n",
+ " break\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Exception on API page {page}: {e}\")\n",
+ " break\n",
+ "\n",
+ " page += 1\n",
+ " time.sleep(DELAY_BETWEEN_PAGES)\n",
+ "\n",
+ "if not pairs:\n",
+ " print(\"\\n❌ No visual novels found in this offset range. Check debug output above.\")\n",
+ "else:\n",
+ " print(f\"\\n✅ Collected {len(pairs)} visual novels (offset {offset}). Downloading images and creating TXT files...\")\n",
+ "\n",
+ " # ====================== DOWNLOAD ENUMERATED FILES ======================\n",
+ " downloaded = 0\n",
+ " for idx, (title, img_url) in enumerate(pairs, start=1):\n",
+ " num_str = f\"{idx:04d}\"\n",
+ " img_path = f\"{dataset_dir}/{num_str}.jpg\"\n",
+ " txt_path = f\"{dataset_dir}/{num_str}.txt\"\n",
+ "\n",
+ " try:\n",
+ " img_response = requests.get(img_url, headers=HEADERS, timeout=15)\n",
+ " if img_response.status_code == 200:\n",
+ " with open(img_path, \"wb\") as f:\n",
+ " f.write(img_response.content)\n",
+ " with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(title)\n",
+ " downloaded += 1\n",
+ " if downloaded % 10 == 0 or downloaded == len(pairs):\n",
+ " print(f\" ✅ Saved {num_str}.jpg + {num_str}.txt\")\n",
+ " else:\n",
+ " print(f\"⚠️ Failed to download image {num_str} (HTTP {img_response.status_code})\")\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error downloading {num_str}: {e}\")\n",
+ "\n",
+ " # ====================== WRITE METADATA (index/offset/tag) ======================\n",
+ " timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
+ " with open(f\"{dataset_dir}/INFO.txt\", \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(f\"VNDB Tag ID : {tag_id}\\n\")\n",
+ " f.write(f\"Offset : {offset}\\n\")\n",
+ " f.write(f\"Batch Size : {num_vns}\\n\")\n",
+ " f.write(f\"Actual Downloaded: {downloaded}\\n\")\n",
+ " f.write(f\"Sort Order : {sort_by}\\n\")\n",
+ " f.write(f\"Start Page : {start_page}\\n\")\n",
+ " f.write(f\"Collected on : {timestamp}\\n\")\n",
+ " f.write(f\"File index 0001 = VN #{offset + 1} in the full tag list\\n\")\n",
+ "\n",
+ " print(\"📝 Metadata INFO.txt written (contains index/offset/tag info)\")\n",
+ "\n",
+ " # ====================== CREATE ZIP & SAVE TO DRIVE ======================\n",
+ " zip_name = f\"vndb_{tag_id}_offset{offset:04d}_{num_vns}vns_{timestamp}\"\n",
+ " zip_path_local = f\"/content/{zip_name}.zip\"\n",
+ "\n",
+ " print(f\"\\n🗜️ Creating ZIP file with {downloaded} image+txt pairs + INFO.txt...\")\n",
+ " shutil.make_archive(f\"/content/{zip_name}\", 'zip', dataset_dir)\n",
+ "\n",
+ " drive_folder = \"/content/drive/MyDrive/vndb_datasets\"\n",
+ " os.makedirs(drive_folder, exist_ok=True)\n",
+ " drive_zip_path = f\"{drive_folder}/{zip_name}.zip\"\n",
+ " shutil.copy(zip_path_local, drive_zip_path)\n",
+ "\n",
+ " print(\"\\n\" + \"=\"*80)\n",
+ " print(\"🎉 SUCCESS! Your dataset is ready\")\n",
+ " print(f\"📦 ZIP file: {zip_name}.zip\")\n",
+ " print(f\"📤 Saved to Google Drive → {drive_zip_path}\")\n",
+ " print(f\" • Contains: 0001.jpg + 0001.txt ... + INFO.txt (with offset/tag/index)\")\n",
+ " print(f\" • Total pairs: {downloaded}\")\n",
+ " print(\"=\"*80)\n",
+ "\n",
+ " # ====================== PREVIEW FIRST 3 PAIRS ======================\n",
+ " print(\"\\n📸 Preview of first 3 pairs (click images to enlarge):\")\n",
+ " for i in range(min(3, len(pairs))):\n",
+ " num_str = f\"{i+1:04d}\"\n",
+ " img_file = f\"{dataset_dir}/{num_str}.jpg\"\n",
+ " display(HTML(f\"{num_str}. {pairs[i][0]}
\"))\n",
+ " display(Image(filename=img_file, width=400))\n",
+ " print(\"─\" * 70)\n",
+ "\n",
+ " print(f\"\\n✅ All files are also in: {dataset_dir} (you can download the folder manually if needed)\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 📌 Pinterest fetch"
+ ],
+ "metadata": {
+ "id": "JrtsI98cmAxB"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "HO3NmF03QDpt"
+ },
+ "source": [
+ "Pinterest board downloader\n",
+ "\n",
+ "⚠️️ Use a throwaway account! Pinterest is a stupid website run by AI bots.\n",
+ "\n",
+ "1. Install the EditThisCookie (or \"Get cookies.txt LOCALLY\") Chrome extension.\n",
+ "2. Log into Pinterest in Chrome → open your board.\n",
+ "3. Click the extension icon → Export cookies for pinterest.com → save as cookies.txt (plain text / Netscape format).\n",
+ "4. In Colab, click the folder icon (left sidebar) → upload cookies.txt to your google drive."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# ==================== SINGLE CELL - FULL PINTEREST BOARD DOWNLOADER (Cookies from Google Drive) ====================\n",
+ "\n",
+ "# Install gallery-dl\n",
+ "!pip install -q gallery-dl\n",
+ "\n",
+ "import os\n",
+ "from google.colab import files\n",
+ "from google.colab import drive\n",
+ "import shutil # Import shutil for copying files\n",
+ "\n",
+ "# ====================== CONFIGURATION ======================\n",
+ "# 1. Paste your board URL here\n",
+ "board_url = \"\" #@param {type:\"string\"}\n",
+ "\n",
+ "# 2. Path to your cookies file on Google Drive (change only if it's in a subfolder)\n",
+ "cookies_file = \"/content/drive/MyDrive/pinterest_cookies.txt\" #@param {type:\"string\"}\n",
+ "\n",
+ "# Optional: custom board name (auto-detected from URL by default)\n",
+ "board_name = board_url.rstrip(\"/\").split(\"/\")[-1]\n",
+ "#or \"pinterest_board\" #@param {type:\"string\"}\n",
+ "\n",
+ "print(\"✅ Board URL:\", board_url)\n",
+ "print(\"📁 Board name:\", board_name)\n",
+ "print(\"🔑 Cookies path:\", cookies_file)\n",
+ "\n",
+ "# ====================== MOUNT GOOGLE DRIVE ======================\n",
+ "print(\"🚀 Mounting Google Drive...\")\n",
+ "drive.mount('/content/drive', force_remount=False)\n",
+ "\n",
+ "# Check if cookies file exists\n",
+ "if os.path.exists(cookies_file):\n",
+ " print(\"✅ Cookies file found! Full board (700+ images) will be downloaded.\")\n",
+ "else:\n",
+ " print(\"❌ Cookies file NOT found at the path above. Only ~200 images will download.\")\n",
+ "\n",
+ "# ====================== CREATE OUTPUT FOLDER ======================\n",
+ "output_dir = f\"/content/{board_name}\"\n",
+ "os.makedirs(output_dir, exist_ok=True)\n",
+ "\n",
+ "print(\"🚀 Starting download... (this can take a while for large boards)\")\n",
+ "\n",
+ "# ====================== BUILD & RUN GALLERY-DL COMMAND ======================\n",
+ "cmd = f'gallery-dl --dest \"{output_dir}\"'\n",
+ "if os.path.exists(cookies_file):\n",
+ " cmd += f' --cookies \"{cookies_file}\"'\n",
+ "cmd += f' \"{board_url}\"'\n",
+ "\n",
+ "# Execute the download\n",
+ "!{cmd}\n",
+ "\n",
+ "# Count downloaded files\n",
+ "total_files = sum([len(files) for r, d, files in os.walk(output_dir)])\n",
+ "print(f\"✅ Download finished! {total_files} files saved in {output_dir}\")\n",
+ "\n",
+ "# ====================== ZIP & AUTO-DOWNLOAD ======================\n",
+ "zip_path = f\"/content/{board_name}.zip\"\n",
+ "print(\"📦 Zipping all images...\")\n",
+ "!zip -r -q \"{zip_path}\" \"{output_dir}\"\n",
+ "\n",
+ "print(f\"✅ Zipped everything → {zip_path}\")\n",
+ "\n",
+ "# Save to Google Drive\n",
+ "drive_zip_destination = f\"/content/drive/MyDrive/{board_name}.zip\"\n",
+ "shutil.copy2(zip_path, drive_zip_destination)\n",
+ "print(f\"✅ Copied '{zip_path}' to Google Drive at '{drive_zip_destination}'\")\n",
+ "\n",
+ "# Auto-download the zip to your computer\n",
+ "#files.download(zip_path)\n",
+ "\n",
+ "#print(\"🎉 All done! Your full Pinterest board is now downloaded, zipped, and available in your Google Drive and local downloads.\")"
+ ],
+ "metadata": {
+ "id": "E7vSr64JkWWa",
+ "cellView": "form"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "g0524iIvU1I_"
+ },
+ "outputs": [],
+ "source": [
+ "# Auto-download the zip file\n",
+ "files.download(zip_path)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 🖼️ Fetch from Sankaku Complex"
+ ],
+ "metadata": {
+ "id": "s40baE0G_wn7"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "from google.colab import drive, userdata\n",
+ "\n",
+ "# Mount your Google Drive\n",
+ "drive.mount('/content/drive')\n",
+ "\n",
+ "#@markdown Load Sankaku Complex secrets (set these in Colab's left sidebar → Secrets panel first!)\n",
+ "SANKAKU_USERNAME = userdata.get('SANKAKU_USERNAME')\n",
+ "SANKAKU_PASSWORD = userdata.get('SANKAKU_PASSWORD')\n",
+ "\n",
+ "print(\"✅ Google Drive mounted and Sankaku credentials loaded from secrets!\")"
+ ],
+ "metadata": {
+ "cellView": "form",
+ "id": "XmDavSOowJSJ"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# @title Sankaku Advanced Downloader + Pagination + Fullsize Processing\n",
+ "\n",
+ "search_phrase = \"\" # @param {type:\"string\"}\n",
+ "N = 291 # @param {type:\"slider\", min:0, max:2000, step:100}\n",
+ "offset = 0 # @param {type:\"slider\", min:0, max:20000, step:10}\n",
+ "\n",
+ "download_thumbnails = True # @param {type:\"boolean\"}\n",
+ "create_image_text_pairs = True # @param {type:\"boolean\"}\n",
+ "download_fullsize = True # @param {type:\"boolean\"}\n",
+ "list_animated_links = True # @param {type:\"boolean\"}\n",
+ "download_animated_and_extract_frames = False # @param {type:\"boolean\"}\n",
+ "\n",
+ "# ── NEW: Fullsize post-processing for training datasets ──\n",
+ "process_fullsize_for_training = False # @param {type:\"boolean\"}\n",
+ "target_shortest_side = 1024 # @param {type:\"slider\", min:512, max:2048, step:64}\n",
+ "output_drive_folder_name = \"sankaku_processed\" # @param {type:\"string\"}\n",
+ "output_zip_name = \"resized_image_text_pairs.zip\" # @param {type:\"string\"}\n",
+ "\n",
+ "import requests\n",
+ "import os\n",
+ "import shutil\n",
+ "from zipfile import ZipFile\n",
+ "import urllib.parse\n",
+ "import subprocess\n",
+ "import time\n",
+ "from http.cookiejar import MozillaCookieJar\n",
+ "from PIL import Image\n",
+ "from tqdm.notebook import tqdm\n",
+ "from pathlib import Path\n",
+ "import gc\n",
+ "\n",
+ "# ====================== LOGIN ======================\n",
+ "login_url = \"https://sankakuapi.com/auth/token\"\n",
+ "payload = {\"login\": SANKAKU_USERNAME, \"password\": SANKAKU_PASSWORD}\n",
+ "headers = {\n",
+ " \"Accept\": \"application/vnd.sankaku.api+json;v=2\",\n",
+ " \"Origin\": \"https://sankaku.app\",\n",
+ " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\",\n",
+ " \"Content-Type\": \"application/json\"\n",
+ "}\n",
+ "\n",
+ "login_resp = requests.post(login_url, json=payload, headers=headers)\n",
+ "login_resp.raise_for_status()\n",
+ "access_token = login_resp.json()[\"access_token\"]\n",
+ "print(\"✅ Logged into Sankaku successfully!\")\n",
+ "\n",
+ "# ====================== SESSION + COOKIES ======================\n",
+ "session = requests.Session()\n",
+ "session.headers.update({\n",
+ " \"Accept\": \"application/vnd.sankaku.api+json;v=2\",\n",
+ " \"Origin\": \"https://sankaku.app\",\n",
+ " \"User-Agent\": headers[\"User-Agent\"],\n",
+ " \"Authorization\": f\"Bearer {access_token}\"\n",
+ "})\n",
+ "\n",
+ "cookies_path = \"/content/drive/MyDrive/sankaku_cookies.txt\"\n",
+ "if os.path.exists(cookies_path):\n",
+ " try:\n",
+ " cj = MozillaCookieJar()\n",
+ " cj.load(cookies_path, ignore_discard=True, ignore_expires=True)\n",
+ " session.cookies = cj\n",
+ " print(\"✅ sankaku_cookies.txt loaded for faster downloads!\")\n",
+ " except Exception as e:\n",
+ " print(f\"⚠️ Cookie load issue: {e}\")\n",
+ "\n",
+ "# ====================== PAGINATED FETCH ======================\n",
+ "print(f\"🔄 Fetching up to {N} posts (offset {offset})...\")\n",
+ "posts_url = \"https://sankakuapi.com/posts\"\n",
+ "collected_posts = []\n",
+ "current_offset = offset\n",
+ "remaining = N\n",
+ "MAX_PER_REQUEST = 100\n",
+ "\n",
+ "while remaining > 0:\n",
+ " batch_limit = min(MAX_PER_REQUEST, remaining)\n",
+ " params = {\"tags\": search_phrase, \"limit\": batch_limit, \"offset\": current_offset}\n",
+ " resp = session.get(posts_url, params=params)\n",
+ " resp.raise_for_status()\n",
+ " batch = resp.json()\n",
+ " if not batch:\n",
+ " break\n",
+ " collected_posts.extend(batch)\n",
+ " print(f\" ✅ Batch of {len(batch)} posts (total: {len(collected_posts)})\")\n",
+ " current_offset += len(batch)\n",
+ " remaining -= len(batch)\n",
+ " if len(batch) < MAX_PER_REQUEST:\n",
+ " break\n",
+ " time.sleep(0.5)\n",
+ "\n",
+ "posts = collected_posts[:N]\n",
+ "print(f\"\\n✅ Fetched {len(posts)} posts total\")\n",
+ "\n",
+ "# ====================== STATS ======================\n",
+ "# (stats code unchanged – same as previous version)\n",
+ "image_count = animated_count = safe_count = questionable_count = explicit_count = 0\n",
+ "limited_visibility_count = ai_created_count = contentious_content_count = unlisted_count = 0\n",
+ "for post in posts:\n",
+ " file_ext = post.get(\"file_ext\", \"\").lower()\n",
+ " is_animated = (file_ext in [\"gif\", \"webm\", \"mp4\"]) or post.get(\"is_animated\", False)\n",
+ " if is_animated:\n",
+ " animated_count += 1\n",
+ " else:\n",
+ " image_count += 1\n",
+ " rating = str(post.get(\"rating\", \"\")).lower().strip()\n",
+ " if rating in [\"s\", \"safe\"]: safe_count += 1\n",
+ " elif rating in [\"q\", \"questionable\"]: questionable_count += 1\n",
+ " elif rating in [\"e\", \"explicit\"]: explicit_count += 1\n",
+ " raw_tags = post.get(\"tags\", [])\n",
+ " if isinstance(raw_tags, list) and raw_tags and isinstance(raw_tags[0], dict):\n",
+ " tag_list = [t.get(\"name\", str(t)).lower() for t in raw_tags]\n",
+ " else:\n",
+ " tag_list = [str(t).lower() for t in raw_tags if t]\n",
+ " if any(t == \"limited_visibility\" for t in tag_list): limited_visibility_count += 1\n",
+ " if any(t in [\"ai-created\", \"ai_generated\"] for t in tag_list): ai_created_count += 1\n",
+ " if any(t == \"contentious_content\" for t in tag_list): contentious_content_count += 1\n",
+ " if any(t in [\"unlisted\", \"limited\", \"hidden\"] for t in tag_list): unlisted_count += 1\n",
+ "\n",
+ "print(\"\\n📊 Search stats:\")\n",
+ "print(f\" • Total fetched posts : {len(posts)}\")\n",
+ "print(f\" • Image results : {image_count}\")\n",
+ "print(f\" • Animated results : {animated_count}\")\n",
+ "print(f\" • Safe / Questionable / Explicit : {safe_count} / {questionable_count} / {explicit_count}\")\n",
+ "print(f\" • limited_visibility / AI-created / contentious_content / unlisted : {limited_visibility_count} / {ai_created_count} / {contentious_content_count} / {unlisted_count}\")\n",
+ "\n",
+ "# ====================== DOWNLOAD SECTION (unchanged) ======================\n",
+ "base_dir = \"/content/sankaku_downloads\"\n",
+ "thumbs_dir = os.path.join(base_dir, \"thumbnails\")\n",
+ "full_dir = os.path.join(base_dir, \"fullsize\")\n",
+ "frames_dir = os.path.join(base_dir, \"animated_frames\")\n",
+ "os.makedirs(thumbs_dir, exist_ok=True)\n",
+ "os.makedirs(full_dir, exist_ok=True)\n",
+ "os.makedirs(frames_dir, exist_ok=True)\n",
+ "\n",
+ "if download_animated_and_extract_frames:\n",
+ " print(\"📦 Installing ffmpeg...\")\n",
+ " subprocess.run([\"apt-get\", \"update\", \"-qq\"], check=True, capture_output=True)\n",
+ " subprocess.run([\"apt-get\", \"install\", \"-y\", \"ffmpeg\", \"-qq\"], check=True, capture_output=True)\n",
+ "\n",
+ "animated_links = []\n",
+ "downloaded_count = 0\n",
+ "frames_extracted = 0\n",
+ "\n",
+ "for idx, post in enumerate(posts):\n",
+ " post_id = post.get(\"id\", idx)\n",
+ " file_url = post.get(\"file_url\")\n",
+ " preview_url = post.get(\"preview_url\")\n",
+ " file_ext = post.get(\"file_ext\", \"\").lower()\n",
+ " is_animated = (file_ext in [\"gif\", \"webm\", \"mp4\"]) or post.get(\"is_animated\", False)\n",
+ "\n",
+ " raw_tags = post.get(\"tags\", [])\n",
+ " if isinstance(raw_tags, list) and raw_tags and isinstance(raw_tags[0], dict):\n",
+ " tag_list = [t.get(\"name\", str(t)) for t in raw_tags]\n",
+ " else:\n",
+ " tag_list = [str(t) for t in raw_tags if t]\n",
+ " tags_str = \", \".join(tag_list) if tag_list else \"no_tags\"\n",
+ "\n",
+ " # Thumbnails\n",
+ " if download_thumbnails and preview_url:\n",
+ " try:\n",
+ " resp = session.get(preview_url, timeout=15)\n",
+ " resp.raise_for_status()\n",
+ " ext = os.path.splitext(urllib.parse.urlparse(preview_url).path)[1].lower() or \".jpg\"\n",
+ " fname = f\"thumb_{idx+1:04d}_id{post_id}{ext}\"\n",
+ " with open(os.path.join(thumbs_dir, fname), \"wb\") as f: f.write(resp.content)\n",
+ " if create_image_text_pairs:\n",
+ " with open(os.path.join(thumbs_dir, fname.replace(ext, \".txt\")), \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(tags_str)\n",
+ " downloaded_count += 1\n",
+ " except: pass\n",
+ "\n",
+ " # Full-size\n",
+ " if download_fullsize and file_url:\n",
+ " try:\n",
+ " resp = session.get(file_url, timeout=25)\n",
+ " resp.raise_for_status()\n",
+ " ext = os.path.splitext(urllib.parse.urlparse(file_url).path)[1].lower() or \".jpg\"\n",
+ " fname = f\"full_{idx+1:04d}_id{post_id}{ext}\"\n",
+ " with open(os.path.join(full_dir, fname), \"wb\") as f: f.write(resp.content)\n",
+ " if create_image_text_pairs:\n",
+ " with open(os.path.join(full_dir, fname.replace(ext, \".txt\")), \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(tags_str)\n",
+ " downloaded_count += 1\n",
+ " except: pass\n",
+ "\n",
+ " if list_animated_links and is_animated and file_url:\n",
+ " animated_links.append(file_url)\n",
+ "\n",
+ " if download_animated_and_extract_frames and is_animated and file_url:\n",
+ " # (keyframe extraction code unchanged – same as before)\n",
+ " try:\n",
+ " resp = session.get(file_url, timeout=30)\n",
+ " resp.raise_for_status()\n",
+ " ext = os.path.splitext(urllib.parse.urlparse(file_url).path)[1].lower() or \".mp4\"\n",
+ " anim_path = os.path.join(frames_dir, f\"anim_{idx+1:04d}_id{post_id}{ext}\")\n",
+ " with open(anim_path, \"wb\") as f: f.write(resp.content)\n",
+ " keyframe_dir = os.path.join(frames_dir, f\"keyframes_id{post_id}\")\n",
+ " os.makedirs(keyframe_dir, exist_ok=True)\n",
+ " output_pattern = os.path.join(keyframe_dir, f\"keyframe_{idx+1:04d}_%05d.jpg\")\n",
+ " if ext == \".gif\":\n",
+ " cmd = [\"ffmpeg\", \"-i\", anim_path, \"-vsync\", \"0\", \"-frame_pts\", \"1\", output_pattern.replace(\"%05d\", \"%04d\")]\n",
+ " else:\n",
+ " cmd = [\"ffmpeg\", \"-i\", anim_path, \"-vf\", \"select=eq(pict_type\\\\,I)\", \"-vsync\", \"vfr\", \"-frame_pts\", \"1\", output_pattern]\n",
+ " subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)\n",
+ " extracted = [f for f in os.listdir(keyframe_dir) if f.endswith(\".jpg\")]\n",
+ " for jpg in extracted:\n",
+ " with open(os.path.join(keyframe_dir, jpg.replace(\".jpg\",\".txt\")), \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(tags_str)\n",
+ " frames_extracted += 1\n",
+ " except: pass\n",
+ "\n",
+ " time.sleep(0.3)\n",
+ "\n",
+ "if list_animated_links and animated_links:\n",
+ " with open(os.path.join(base_dir, \"animated_links.txt\"), \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(\"\\n\".join(animated_links))\n",
+ "\n",
+ "# ====================== RAW BACKUP ZIP ======================\n",
+ "zip_path = \"/content/sankaku_downloads.zip\"\n",
+ "with ZipFile(zip_path, \"w\") as zipf:\n",
+ " for root, _, files in os.walk(base_dir):\n",
+ " for file in files:\n",
+ " zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), base_dir))\n",
+ "shutil.copy2(zip_path, \"/content/drive/MyDrive/sankaku_downloads.zip\")\n",
+ "print(f\"✅ Raw backup ZIP saved to Drive → /MyDrive/sankaku_downloads.zip\")\n",
+ "\n",
+ "# ====================== FULLSIZE PROCESSING (exactly as you asked) ======================\n",
+ "if process_fullsize_for_training and download_fullsize:\n",
+ " print(\"\\n🔧 Starting fullsize post-processing (resize + rename + zip)...\")\n",
+ " INPUT_IMAGES_DIR = os.path.join(base_dir, \"fullsize/\")\n",
+ " TARGET_SHORTEST_SIDE = target_shortest_side\n",
+ " OUTPUT_DRIVE_FOLDER_NAME = output_drive_folder_name\n",
+ " OUTPUT_ZIP_FILE_NAME = output_zip_name\n",
+ "\n",
+ " # Mount check (safe)\n",
+ " try:\n",
+ " from google.colab import drive\n",
+ " drive.mount('/content/drive', force_remount=False)\n",
+ " except: pass\n",
+ "\n",
+ " drive_base = \"/content/drive/MyDrive\"\n",
+ " drive_output_dir = os.path.join(drive_base, OUTPUT_DRIVE_FOLDER_NAME)\n",
+ " os.makedirs(drive_output_dir, exist_ok=True)\n",
+ "\n",
+ " local_temp_output_dir = Path(\"/content/temp_processed_output\")\n",
+ " shutil.rmtree(local_temp_output_dir, ignore_errors=True)\n",
+ " local_temp_output_dir.mkdir(exist_ok=True, parents=True)\n",
+ "\n",
+ " # Collect image-text pairs\n",
+ " image_files = []\n",
+ " valid_ext = ('.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff')\n",
+ " print(f\"Scanning {INPUT_IMAGES_DIR}...\")\n",
+ " for root, _, files in os.walk(INPUT_IMAGES_DIR):\n",
+ " for fname in files:\n",
+ " if fname.lower().endswith(valid_ext):\n",
+ " img_path = Path(os.path.join(root, fname))\n",
+ " txt_path = img_path.with_suffix('.txt')\n",
+ " if txt_path.is_file():\n",
+ " image_files.append((img_path, txt_path))\n",
+ "\n",
+ " print(f\"Found {len(image_files)} image-text pairs.\")\n",
+ "\n",
+ " processed_count = skipped_count = 0\n",
+ " for original_img_path, original_txt_path in tqdm(image_files, desc=\"Resizing & renaming\"):\n",
+ " try:\n",
+ " with Image.open(original_img_path) as img:\n",
+ " w, h = img.size\n",
+ " if min(w, h) < TARGET_SHORTEST_SIDE:\n",
+ " skipped_count += 1\n",
+ " continue\n",
+ "\n",
+ " if w < h:\n",
+ " new_w = TARGET_SHORTEST_SIDE\n",
+ " new_h = int(h * TARGET_SHORTEST_SIDE / w)\n",
+ " else:\n",
+ " new_h = TARGET_SHORTEST_SIDE\n",
+ " new_w = int(w * TARGET_SHORTEST_SIDE / h)\n",
+ "\n",
+ " resized = img.resize((new_w, new_h), Image.LANCZOS)\n",
+ " if resized.mode != 'RGB':\n",
+ " resized = resized.convert('RGB')\n",
+ "\n",
+ " processed_count += 1\n",
+ " new_base = str(processed_count)\n",
+ "\n",
+ " output_img = local_temp_output_dir / f\"{new_base}.jpeg\"\n",
+ " resized.save(output_img, \"JPEG\", quality=85)\n",
+ "\n",
+ " output_txt = local_temp_output_dir / f\"{new_base}.txt\"\n",
+ " shutil.copy2(original_txt_path, output_txt)\n",
+ "\n",
+ " del img, resized\n",
+ " if processed_count % 100 == 0:\n",
+ " gc.collect()\n",
+ " except Exception as e:\n",
+ " print(f\"Error: {original_img_path.name} → {e}\")\n",
+ " skipped_count += 1\n",
+ "\n",
+ " print(f\"\\nProcessed {processed_count} images | Skipped {skipped_count}\")\n",
+ "\n",
+ " # Create & save zip\n",
+ " if processed_count > 0:\n",
+ " local_zip_path = Path(\"/content\") / OUTPUT_ZIP_FILE_NAME\n",
+ " with zipfile.ZipFile(local_zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:\n",
+ " for item in tqdm(local_temp_output_dir.rglob(\"*\"), desc=\"Zipping\"):\n",
+ " if item.is_file():\n",
+ " zf.write(item, arcname=item.name)\n",
+ "\n",
+ " drive_final_zip = Path(drive_output_dir) / OUTPUT_ZIP_FILE_NAME\n",
+ " shutil.copy2(local_zip_path, drive_final_zip)\n",
+ " size_mb = local_zip_path.stat().st_size / (1024 * 1024)\n",
+ " print(f\"\\n🎉 PROCESSED ZIP SAVED!\")\n",
+ " print(f\" Folder → {drive_output_dir}\")\n",
+ " print(f\" Zip → {drive_final_zip}\")\n",
+ " print(f\" Size → {size_mb:.1f} MiB\")\n",
+ "\n",
+ " # Cleanup temp\n",
+ " shutil.rmtree(local_temp_output_dir, ignore_errors=True)\n",
+ "\n",
+ "print(\"\\n🎉 ALL DONE! Check your Google Drive.\")"
+ ],
+ "metadata": {
+ "id": "P-4aeky_F2UN"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# ✂️ Image slicer"
+ ],
+ "metadata": {
+ "id": "lUIEma9C-36K"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# ====================== IMAGE COLUMN SLICER (ZIP SUPPORT) ======================\n",
+ "\n",
+ "# ====================== SETTINGS ======================\n",
+ "N = 6 # @param {type:\"slider\", min:1, max:100, step:1}\n",
+ "M = 18 # @param {type:\"slider\", min:1, max:30, step:1}\n",
+ "\n",
+ "left_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n",
+ "right_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n",
+ "bottom_crop_percent = 0 # @param {type:\"slider\", min:0, max:50, step:1}\n",
+ "\n",
+ "output_format = \"JPEG\" # @param [\"PNG\", \"JPEG\", \"WEBP\"]\n",
+ "image_quality = 90 # @param {type:\"slider\", min:10, max:100, step:1}\n",
+ "\n",
+ "upload_to_drive = False # @param {type:\"boolean\"}\n",
+ "drive_output_folder = \"sliced_images\" # @param {type:\"string\"}\n",
+ "\n",
+ "# ====================== IMPORTS ======================\n",
+ "import io\n",
+ "import os\n",
+ "import zipfile\n",
+ "from PIL import Image\n",
+ "from google.colab import files, drive\n",
+ "\n",
+ "# Install PyMuPDF for PDF processing\n",
+ "!pip install PyMuPDF -q\n",
+ "import fitz # PyMuPDF\n",
+ "\n",
+ "\n",
+ "print(f\"✅ Columns: {N}, Rows: {M}\")\n",
+ "print(f\"✅ Manual crops - L:{left_crop_percent}% R:{right_crop_percent}% B:{bottom_crop_percent}%\")\n",
+ "print(f\"✅ Output format: {output_format}, Quality: {image_quality}\")\n",
+ "print(f\"✅ Upload to Drive: {upload_to_drive}\")\n",
+ "\n",
+ "\n",
+ "# ====================== FILE FILTER ======================\n",
+ "def is_valid_image_file(filename):\n",
+ " bad_patterns = [\"__MACOSX\", \".DS_Store\", \"Thumbs.db\", \".AppleDouble\", \"._\"]\n",
+ "\n",
+ " if any(p in filename for p in bad_patterns):\n",
+ " return False\n",
+ "\n",
+ " if os.path.basename(filename).startswith(\".\"):\n",
+ " return False\n",
+ "\n",
+ " # Check for common image extensions\n",
+ " return filename.lower().endswith((\".png\", \".jpg\", \".jpeg\", \".bmp\", \".tiff\", \".webp\"))\n",
+ "\n",
+ "\n",
+ "# ====================== EXTRACTOR ======================\n",
+ "def extract_files(uploaded_dict):\n",
+ " \"\"\"\n",
+ " Yield (filename, bytes) from:\n",
+ " - direct image uploads\n",
+ " - zip archives (including nested folders)\n",
+ " - PDF files (each page converted to an image)\n",
+ " \"\"\"\n",
+ " for filename, file_content in uploaded_dict.items():\n",
+ "\n",
+ " # ===== PDF FILE =====\n",
+ " if filename.lower().endswith(\".pdf\"):\n",
+ " print(f\"📄 Extracting PDF: {filename}\")\n",
+ " try:\n",
+ " pdf_doc = fitz.open(stream=file_content, filetype=\"pdf\")\n",
+ " for page_num in range(len(pdf_doc)):\n",
+ " page = pdf_doc.load_page(page_num)\n",
+ " # Render page to a Pixmap (image buffer)\n",
+ " pix = page.get_pixmap()\n",
+ " # Convert Pixmap to PNG bytes\n",
+ " img_bytes = pix.pil_tobytes(format=\"PNG\")\n",
+ " # Yield a filename for the extracted page and its bytes\n",
+ " yield f\"{os.path.splitext(filename)[0]}_page_{page_num + 1:03d}.png\", img_bytes\n",
+ " pdf_doc.close()\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Failed processing PDF {filename}: {e}\")\n",
+ "\n",
+ " # ===== ZIP FILE =====\n",
+ " elif filename.lower().endswith(\".zip\"):\n",
+ " print(f\"📦 Extracting ZIP: {filename}\")\n",
+ "\n",
+ " try:\n",
+ " with zipfile.ZipFile(io.BytesIO(file_content)) as z:\n",
+ " for member in z.namelist():\n",
+ " # The is_valid_image_file check ensures we only process images from ZIPs\n",
+ " if is_valid_image_file(member):\n",
+ " try:\n",
+ " yield member, z.read(member)\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Failed reading {member}: {e}\")\n",
+ " else:\n",
+ " print(f\"⏭️ Skipping in ZIP: {member}\")\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Bad ZIP file: {filename} | {e}\")\n",
+ "\n",
+ " # ===== DIRECT IMAGE =====\n",
+ " else:\n",
+ " # For non-zip/non-pdf, treat as a direct image. is_valid_image_file ensures it's an image.\n",
+ " if is_valid_image_file(filename):\n",
+ " yield filename, file_content\n",
+ " else:\n",
+ " print(f\"⏭️ Skipping unrecognized file: {filename}\")\n",
+ "\n",
+ "\n",
+ "# ====================== UPLOAD ======================\n",
+ "print(\"\\n📤 Upload images or ZIP files...\")\n",
+ "uploaded = files.upload()\n",
+ "\n",
+ "if not uploaded:\n",
+ " print(\"❌ No files uploaded.\")\n",
+ "\n",
+ "else:\n",
+ "\n",
+ " zip_buffer = io.BytesIO()\n",
+ "\n",
+ " with zipfile.ZipFile(zip_buffer, \"w\", zipfile.ZIP_DEFLATED) as zip_file:\n",
+ "\n",
+ " processed = 0\n",
+ "\n",
+ " # ====================== PROCESS LOOP ======================\n",
+ " for filename, file_content in extract_files(uploaded):\n",
+ "\n",
+ " # This check is crucial here to ensure only actual image data (from PDFs, ZIPs, or direct) proceeds\n",
+ " if not is_valid_image_file(filename):\n",
+ " print(f\"⏭️ Skipping: {filename}\")\n",
+ " continue\n",
+ "\n",
+ " try:\n",
+ " img = Image.open(io.BytesIO(file_content)).convert(\"RGB\")\n",
+ "\n",
+ " # ====================== MANUAL CROPPING ======================\n",
+ " w, h = img.size\n",
+ "\n",
+ " left_px = int(w * left_crop_percent / 100)\n",
+ " right_px = int(w * (1 - right_crop_percent / 100))\n",
+ " bottom_px = int(h * (1 - bottom_crop_percent / 100))\n",
+ "\n",
+ " if left_px >= right_px or bottom_px <= 1:\n",
+ " print(f\"⚠️ Invalid crop: {filename}\")\n",
+ " continue\n",
+ "\n",
+ " img = img.crop((left_px, 0, right_px, bottom_px))\n",
+ " w, h = img.size\n",
+ "\n",
+ " if w < N:\n",
+ " print(f\"⚠️ Too narrow for {N} columns: {filename}\")\n",
+ " continue\n",
+ " if h < M:\n",
+ " print(f\"⚠️ Too short for {M} rows: {filename}\")\n",
+ " continue\n",
+ "\n",
+ " # ====================== SLICE ======================\n",
+ " col_w = w // N\n",
+ " row_h = h // M\n",
+ " base = os.path.splitext(os.path.basename(filename))[0]\n",
+ "\n",
+ " for i in range(N):\n",
+ " col_l = i * col_w\n",
+ " col_r = (i + 1) * col_w if i < N - 1 else w\n",
+ "\n",
+ " # Crop the column first\n",
+ " column_img = img.crop((col_l, 0, col_r, h))\n",
+ "\n",
+ " for j in range(M):\n",
+ " row_t = j * row_h\n",
+ " row_b = (j + 1) * row_h if j < M - 1 else h\n",
+ "\n",
+ " slice_img = column_img.crop((0, row_t, column_img.width, row_b))\n",
+ "\n",
+ " # Determine output extension\n",
+ " ext = \".\" + output_format.lower() if output_format != \"JPEG\" else \".jpg\"\n",
+ " output_name = f\"{base}_col_{i+1:02d}_row_{j+1:02d}{ext}\"\n",
+ "\n",
+ " buf = io.BytesIO()\n",
+ " if output_format == \"PNG\":\n",
+ " slice_img.save(buf, format=\"PNG\") # PIL defaults to good compression\n",
+ " elif output_format == \"JPEG\":\n",
+ " slice_img.save(buf, format=\"JPEG\", quality=image_quality)\n",
+ " elif output_format == \"WEBP\":\n",
+ " slice_img.save(buf, format=\"WEBP\", quality=image_quality)\n",
+ "\n",
+ " zip_file.writestr(output_name, buf.getvalue())\n",
+ "\n",
+ " processed += 1\n",
+ " print(f\"✅ Processed: {filename}\")\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error {filename}: {e}\")\n",
+ "\n",
+ "\n",
+ " # ====================== DOWNLOAD / UPLOAD ======================\n",
+ " if processed > 0:\n",
+ " zip_path = \"/content/sliced_output.zip\"\n",
+ "\n",
+ " with open(zip_path, \"wb\") as f:\n",
+ " f.write(zip_buffer.getvalue())\n",
+ "\n",
+ " print(f\"\\n🎉 Done! {processed} images processed.\")\n",
+ "\n",
+ " if upload_to_drive:\n",
+ " print(\"🚀 Mounting Google Drive...\")\n",
+ " drive.mount('/content/drive', force_remount=True)\n",
+ " drive_destination_folder = f\"/content/drive/MyDrive/{drive_output_folder}\"\n",
+ " os.makedirs(drive_destination_folder, exist_ok=True)\n",
+ " shutil.copy(zip_path, drive_destination_folder)\n",
+ " print(f\"✅ Zip file saved to Google Drive: {drive_destination_folder}/sliced_output.zip\")\n",
+ " else:\n",
+ " files.download(zip_path)\n",
+ "\n",
+ " else:\n",
+ " print(\"❌ No valid images processed.\")"
+ ],
+ "metadata": {
+ "id": "0oxW9KL11lZ7"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# --- Upload ZIP ---\n",
+ "from google.colab import files\n",
+ "uploaded = files.upload()\n",
+ "\n",
+ "import zipfile\n",
+ "import os\n",
+ "import cv2\n",
+ "import numpy as np\n",
+ "\n",
+ "# --- Parameters ---\n",
+ "black_threshold = 40 # pixel intensity threshold (0–255); higher = more tolerant\n",
+ "tolerance_ratio = 0.95 # % of pixels in a row/col that must be \"black-like\"\n",
+ "\n",
+ "# --- Extract ZIP ---\n",
+ "zip_name = list(uploaded.keys())[0]\n",
+ "extract_dir = \"input_images\"\n",
+ "output_dir = \"cropped_images\"\n",
+ "\n",
+ "os.makedirs(extract_dir, exist_ok=True)\n",
+ "os.makedirs(output_dir, exist_ok=True)\n",
+ "\n",
+ "with zipfile.ZipFile(zip_name, 'r') as zip_ref:\n",
+ " zip_ref.extractall(extract_dir)\n",
+ "\n",
+ "# --- Helper function ---\n",
+ "def is_mostly_black(line):\n",
+ " # line shape: (N, 3)\n",
+ " gray = np.mean(line, axis=1)\n",
+ " black_pixels = np.sum(gray < black_threshold)\n",
+ " return (black_pixels / len(gray)) >= tolerance_ratio\n",
+ "\n",
+ "# --- Process images ---\n",
+ "for root, _, files_in_dir in os.walk(extract_dir):\n",
+ " for file in files_in_dir:\n",
+ " if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):\n",
+ " path = os.path.join(root, file)\n",
+ " img = cv2.imread(path)\n",
+ "\n",
+ " if img is None:\n",
+ " continue\n",
+ "\n",
+ " h, w, _ = img.shape\n",
+ "\n",
+ " # --- Detect left crop ---\n",
+ " left = 0\n",
+ " for x in range(w):\n",
+ " col = img[:, x, :]\n",
+ " if is_mostly_black(col):\n",
+ " left += 1\n",
+ " else:\n",
+ " break\n",
+ "\n",
+ " # --- Detect right crop ---\n",
+ " right = w\n",
+ " for x in range(w - 1, -1, -1):\n",
+ " col = img[:, x, :]\n",
+ " if is_mostly_black(col):\n",
+ " right -= 1\n",
+ " else:\n",
+ " break\n",
+ "\n",
+ " # --- Detect bottom crop ---\n",
+ " bottom = h\n",
+ " for y in range(h - 1, -1, -1):\n",
+ " row = img[y, :, :]\n",
+ " if is_mostly_black(row):\n",
+ " bottom -= 1\n",
+ " else:\n",
+ " break\n",
+ "\n",
+ " # --- Crop ---\n",
+ " cropped = img[0:bottom, left:right]\n",
+ "\n",
+ " # --- Save ---\n",
+ " out_path = os.path.join(output_dir, file)\n",
+ " cv2.imwrite(out_path, cropped)\n",
+ "\n",
+ "# --- Zip results ---\n",
+ "output_zip = \"cropped_results.zip\"\n",
+ "with zipfile.ZipFile(output_zip, 'w') as zipf:\n",
+ " for root, _, files_in_dir in os.walk(output_dir):\n",
+ " for file in files_in_dir:\n",
+ " file_path = os.path.join(root, file)\n",
+ " zipf.write(file_path, arcname=file)\n",
+ "\n",
+ "# --- Download ---\n",
+ "files.download(output_zip)"
+ ],
+ "metadata": {
+ "id": "AmbYgH8LGtXI"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 🎲 Fetch subset of zip file"
+ ],
+ "metadata": {
+ "id": "02aZcv2lB_hC"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "6edbf718",
+ "cellView": "form"
+ },
+ "outputs": [],
+ "source": [
+ "#@markdown Randomly sample a selected zip file (with many images for example) , and download as smaller zip\n",
+ "import zipfile\n",
+ "import os\n",
+ "import random\n",
+ "import shutil\n",
+ "from glob import glob\n",
+ "from google.colab import files\n",
+ "\n",
+ "# --- Configuration ---\n",
+ "input_zip_file = '' #@param {type:'string'}\n",
+ "\n",
+ "extraction_dir = '/content/extracted_keyframes_temp'\n",
+ "output_zip_name = 'random_300_keyframes.zip'\n",
+ "num_images_to_pick = 180 #@param {type:'slider',min:0,step:5,max:1000}\n",
+ "\n",
+ "# --- Step 1: Unzip the input file ---\n",
+ "print(f\"🔄 Unzipping {input_zip_file}...\")\n",
+ "if os.path.exists(extraction_dir):\n",
+ " shutil.rmtree(extraction_dir)\n",
+ "os.makedirs(extraction_dir, exist_ok=True)\n",
+ "\n",
+ "try:\n",
+ " with zipfile.ZipFile(input_zip_file, 'r') as zip_ref:\n",
+ " zip_ref.extractall(extraction_dir)\n",
+ " print(\"✅ Unzip complete.\")\n",
+ "except Exception as e:\n",
+ " print(f\"❌ Error unzipping file: {e}\")\n",
+ " raise\n",
+ "\n",
+ "# --- Step 2: Find all images in the extracted directory ---\n",
+ "all_images = []\n",
+ "for ext in ('*.jpg', '*.jpeg', '*.png', '*.gif'): # Add more extensions if needed\n",
+ " all_images.extend(glob(os.path.join(extraction_dir, '**', ext), recursive=True))\n",
+ "\n",
+ "if not all_images:\n",
+ " print(\"⚠️ No images found in the extracted archive.\")\n",
+ " raise FileNotFoundError(\"No images to process.\")\n",
+ "\n",
+ "print(f\"Found {len(all_images)} total images.\")\n",
+ "\n",
+ "# --- Step 3: Randomly select images ---\n",
+ "if len(all_images) <= num_images_to_pick:\n",
+ " selected_images = all_images\n",
+ " print(f\"Selecting all {len(all_images)} images (fewer than {num_images_to_pick} available).\")\n",
+ "else:\n",
+ " selected_images = random.sample(all_images, num_images_to_pick)\n",
+ " print(f\"✅ Randomly selected {len(selected_images)} images.\")\n",
+ "\n",
+ "# --- Step 4: Create a new zip file with selected images ---\n",
+ "output_zip_path = os.path.join('/content', output_zip_name)\n",
+ "\n",
+ "print(f\"🔄 Creating new zip file: {output_zip_name}...\")\n",
+ "with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as new_zip:\n",
+ " for img_path in selected_images:\n",
+ " # Add image to zip, preserving its relative path within the extracted folder\n",
+ " arcname = os.path.relpath(img_path, extraction_dir)\n",
+ " new_zip.write(img_path, arcname)\n",
+ "\n",
+ "print(f\"✅ New zip file created: {output_zip_path}\")\n",
+ "\n",
+ "# --- Step 5: Provide as widget output for download ---\n",
+ "print(\"📥 Initiating download of the new zip file...\")\n",
+ "files.download(output_zip_path)\n",
+ "\n",
+ "# --- Step 6: Cleanup temporary files ---\n",
+ "print(\"🗑️ Cleaning up temporary extraction directory...\")\n",
+ "shutil.rmtree(extraction_dir)\n",
+ "print(\"✅ Cleanup complete.\")\n",
+ "print(\"You can find the downloaded zip file in your local downloads.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 📝 Insert Titles Between Every Sentence"
+ ],
+ "metadata": {
+ "id": "U27drDtMB53n"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "\n",
+ "# @markdown ---\n",
+ "# @markdown **How to use this Colab:**\n",
+ "# @markdown 1. Prepare two plain text files:\n",
+ "# @markdown - `titles.txt` → contains `{title1|title2|title3|...}` (or just `title1|title2|...`)\n",
+ "# @markdown - `texts.txt` → contains `{text1|text2|text3|...}` (or just `text1|text2|...`)\n",
+ "# @markdown 2. Upload both files using the widgets below.\n",
+ "# @markdown 3. Click **🚀 Process & Download Captions**.\n",
+ "# @markdown 4. You will get:\n",
+ "# @markdown - The full `{caption1|caption2|caption3|...}` string printed\n",
+ "# @markdown - A single `captions.txt` file automatically downloaded containing exactly that string\n",
+ "# @markdown ---\n",
+ "\n",
+ "import ipywidgets as widgets\n",
+ "from IPython.display import display, HTML\n",
+ "import re\n",
+ "import itertools\n",
+ "from google.colab import files\n",
+ "\n",
+ "# ====================== UPLOAD WIDGETS ======================\n",
+ "titles_upload = widgets.FileUpload(\n",
+ " accept='.txt',\n",
+ " multiple=False,\n",
+ " description='📤 Upload titles.txt'\n",
+ ")\n",
+ "\n",
+ "texts_upload = widgets.FileUpload(\n",
+ " accept='.txt',\n",
+ " multiple=False,\n",
+ " description='📤 Upload texts.txt'\n",
+ ")\n",
+ "\n",
+ "process_button = widgets.Button(\n",
+ " description='🚀 Process & Download Captions',\n",
+ " button_style='success',\n",
+ " layout=widgets.Layout(width='100%', height='50px')\n",
+ ")\n",
+ "\n",
+ "output_area = widgets.Output()\n",
+ "\n",
+ "# ====================== PROCESSING LOGIC ======================\n",
+ "def process_captions(b):\n",
+ " with output_area:\n",
+ " output_area.clear_output()\n",
+ "\n",
+ " if not titles_upload.value or not texts_upload.value:\n",
+ " print(\"❌ ERROR: Please upload BOTH titles.txt and texts.txt files!\")\n",
+ " return\n",
+ "\n",
+ " # Read uploaded file contents\n",
+ " titles_file = list(titles_upload.value.values())[0]\n",
+ " texts_file = list(texts_upload.value.values())[0]\n",
+ "\n",
+ " titles_str = titles_file['content'].decode('utf-8').strip()\n",
+ " texts_str = texts_file['content'].decode('utf-8').strip()\n",
+ "\n",
+ " # ====================== PARSE LISTS ======================\n",
+ " def parse_list(s):\n",
+ " s = s.strip()\n",
+ " if s.startswith(\"{\") and s.endswith(\"}\"):\n",
+ " items = [item.strip() for item in s[1:-1].split(\"|\") if item.strip()]\n",
+ " else:\n",
+ " items = [item.strip() for item in s.split(\"|\") if item.strip()]\n",
+ " return items\n",
+ "\n",
+ " titles_list = parse_list(titles_str)\n",
+ " texts_list = parse_list(texts_str)\n",
+ "\n",
+ " if not texts_list:\n",
+ " print(\"❌ ERROR: texts.txt appears to be empty!\")\n",
+ " return\n",
+ "\n",
+ " # ====================== SENTENCE SPLITTER (preserves ALL punctuation) ======================\n",
+ " def split_sentences(text):\n",
+ " if not text or not text.strip():\n",
+ " return []\n",
+ " # Split after . ! ? followed by whitespace, punctuation STAYS attached to each sentence\n",
+ " sentences = re.split(r'(?<=[.!?])\\s+', text.strip())\n",
+ " return [s.strip() for s in sentences if s.strip()]\n",
+ "\n",
+ " # ====================== BUILD CAPTIONS ======================\n",
+ " captions = []\n",
+ " title_cycle = itertools.cycle(titles_list) if titles_list else None\n",
+ "\n",
+ " for text in texts_list:\n",
+ " sentences = split_sentences(text)\n",
+ " if not sentences:\n",
+ " captions.append(\"\")\n",
+ " continue\n",
+ "\n",
+ " if not titles_list or len(sentences) <= 1:\n",
+ " # No titles or only one sentence → no insertion\n",
+ " caption = sentences[0]\n",
+ " else:\n",
+ " # Insert cycling titles BETWEEN sentences\n",
+ " # Original punctuation remains on every sentence\n",
+ " caption_parts = [sentences[0]]\n",
+ " for sent in sentences[1:]:\n",
+ " title = next(title_cycle)\n",
+ " caption_parts.append(title)\n",
+ " caption_parts.append(sent)\n",
+ " caption = \" \".join(caption_parts)\n",
+ "\n",
+ " captions.append(caption)\n",
+ "\n",
+ " # ====================== CREATE SINGLE OUTPUT STRING ======================\n",
+ " captions_str = \"{\" + \"|\".join(captions) + \"}\"\n",
+ "\n",
+ " print(\"✅ SUCCESS! Generated Captions String:\")\n",
+ " print(captions_str)\n",
+ "\n",
+ " # ====================== SAVE & DOWNLOAD SINGLE captions.txt ======================\n",
+ " output_path = \"/content/captions.txt\"\n",
+ " with open(output_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(captions_str)\n",
+ "\n",
+ " print(f\"\\n📄 Single file created: captions.txt\")\n",
+ " print(\"⬇️ Downloading captions.txt now...\")\n",
+ " files.download(output_path)\n",
+ "\n",
+ "# ====================== BUTTON CALLBACK ======================\n",
+ "process_button.on_click(process_captions)\n",
+ "\n",
+ "# ====================== DISPLAY UI ======================\n",
+ "ui = widgets.VBox([\n",
+ " widgets.HTML(\"📄 Titles File
\"),\n",
+ " titles_upload,\n",
+ " widgets.HTML(\"📄 Texts File
\"),\n",
+ " texts_upload,\n",
+ " widgets.HTML(\"
Click the button below after uploading both files:\"),\n",
+ " process_button,\n",
+ " widgets.HTML(\"
\"),\n",
+ " output_area\n",
+ "])\n",
+ "\n",
+ "display(ui)\n",
+ "print(\"👋 Ready! Upload your two .txt files and click the green button.\")"
+ ],
+ "metadata": {
+ "id": "smK4buMrqs9v"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "LaxF_cnIGNMh"
+ },
+ "source": [
+ "# ✍️ Convert a dataset into a combined text"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "trl0Eg8Xqy6B",
+ "outputId": "ec757a1d-9949-42d3-ebc1-9feecbf65a3f",
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 287
+ }
+ },
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "📤 Please upload your ZIP file (the one containing 1.txt, 2.txt, 3.txt, …)\n"
+ ]
+ },
+ {
+ "output_type": "display_data",
+ "data": {
+ "text/plain": [
+ ""
+ ],
+ "text/html": [
+ "\n",
+ " \n",
+ " \n",
+ " "
+ ]
+ },
+ "metadata": {}
+ },
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Saving TA-2026-04-24-11-51-46-988910702213220633.zip to TA-2026-04-24-11-51-46-988910702213220633.zip\n",
+ "✅ ZIP extracted to /content/extracted_txt_files\n",
+ "📄 Found 429 title files. Processing...\n",
+ "\n",
+ "✅ Done! Combined 429 titles into one line.\n",
+ "📁 Saved as: /content/combined_titles.txt\n",
+ " (First 100 characters: {This is a digital cartoon illustration of a young woman with a stylized, exaggerated appearance. S...)\n"
+ ]
+ },
+ {
+ "output_type": "display_data",
+ "data": {
+ "text/plain": [
+ ""
+ ],
+ "application/javascript": [
+ "\n",
+ " async function download(id, filename, size) {\n",
+ " if (!google.colab.kernel.accessAllowed) {\n",
+ " return;\n",
+ " }\n",
+ " const div = document.createElement('div');\n",
+ " const label = document.createElement('label');\n",
+ " label.textContent = `Downloading \"${filename}\": `;\n",
+ " div.appendChild(label);\n",
+ " const progress = document.createElement('progress');\n",
+ " progress.max = size;\n",
+ " div.appendChild(progress);\n",
+ " document.body.appendChild(div);\n",
+ "\n",
+ " const buffers = [];\n",
+ " let downloaded = 0;\n",
+ "\n",
+ " const channel = await google.colab.kernel.comms.open(id);\n",
+ " // Send a message to notify the kernel that we're ready.\n",
+ " channel.send({})\n",
+ "\n",
+ " for await (const message of channel.messages) {\n",
+ " // Send a message to notify the kernel that we're ready.\n",
+ " channel.send({})\n",
+ " if (message.buffers) {\n",
+ " for (const buffer of message.buffers) {\n",
+ " buffers.push(buffer);\n",
+ " downloaded += buffer.byteLength;\n",
+ " progress.value = downloaded;\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " const blob = new Blob(buffers, {type: 'application/binary'});\n",
+ " const a = document.createElement('a');\n",
+ " a.href = window.URL.createObjectURL(blob);\n",
+ " a.download = filename;\n",
+ " div.appendChild(a);\n",
+ " a.click();\n",
+ " div.remove();\n",
+ " }\n",
+ " "
+ ]
+ },
+ "metadata": {}
+ },
+ {
+ "output_type": "display_data",
+ "data": {
+ "text/plain": [
+ ""
+ ],
+ "application/javascript": [
+ "download(\"download_6e68886b-a05f-4a32-806c-ce844b817b2c\", \"combined_titles.txt\", 373035)"
+ ]
+ },
+ "metadata": {}
+ },
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "📥 Download started. You can now use this file wherever you need the {title1|title2|...} format.\n"
+ ]
+ }
+ ],
+ "source": [
+ "from google.colab import files\n",
+ "import zipfile\n",
+ "import os\n",
+ "from pathlib import Path\n",
+ "import shutil # Added for rmtree\n",
+ "\n",
+ "print(\"📤 Please upload your ZIP file (the one containing 1.txt, 2.txt, 3.txt, …)\")\n",
+ "\n",
+ "# Let the user upload the ZIP\n",
+ "uploaded = files.upload()\n",
+ "\n",
+ "# Find the uploaded ZIP file\n",
+ "zip_files = [f for f in uploaded.keys() if f.lower().endswith('.zip')]\n",
+ "if not zip_files:\n",
+ " raise ValueError(\"❌ No .zip file was uploaded. Please try again.\")\n",
+ "\n",
+ "zip_filename = zip_files[0]\n",
+ "zip_path = f\"/content/{zip_filename}\"\n",
+ "\n",
+ "# Extract the ZIP to a temporary folder\n",
+ "extract_dir = \"/content/extracted_txt_files\"\n",
+ "\n",
+ "# --- Added: Clear the directory if it exists ---\n",
+ "if os.path.exists(extract_dir):\n",
+ " shutil.rmtree(extract_dir)\n",
+ "# ---\n",
+ "os.makedirs(extract_dir, exist_ok=True)\n",
+ "\n",
+ "with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n",
+ " zip_ref.extractall(extract_dir)\n",
+ "\n",
+ "print(f\"✅ ZIP extracted to {extract_dir}\")\n",
+ "\n",
+ "# Get all .txt files and sort them numerically (1.txt, 2.txt, 10.txt, etc.)\n",
+ "txt_paths = sorted(\n",
+ " list(Path(extract_dir).glob(\"*.txt\")),\n",
+ " key=lambda p: f\"{int(p.stem):05d}\" if p.stem.isdigit() else p.stem.lower()\n",
+ ")\n",
+ "\n",
+ "if not txt_paths:\n",
+ " raise ValueError(\"❌ No .txt files found inside the ZIP!\")\n",
+ "\n",
+ "print(f\"📄 Found {len(txt_paths)} title files. Processing...\")\n",
+ "\n",
+ "# Read, clean, and combine titles\n",
+ "cleaned_titles = []\n",
+ "for txt_path in txt_paths:\n",
+ " with open(txt_path, \"r\", encoding=\"utf-8\") as f:\n",
+ " title = f.read().strip()\n",
+ "\n",
+ " # Remove the forbidden characters: ^ { } | [] and newlines\n",
+ " cleaned = (title\n",
+ " .replace('^', '')\n",
+ " .replace('{', '')\n",
+ " .replace('}', '')\n",
+ " .replace('|', '')\n",
+ " .replace('\"','')\n",
+ " .replace('>', '')\n",
+ " .replace('<','')\n",
+ " .replace('[','') # New: Remove opening bracket\n",
+ " .replace(']','') # New: Remove closing bracket\n",
+ " .replace('\\n', ' ')) # New: Replace newlines with spaces\n",
+ "\n",
+ " cleaned_titles.append(cleaned)\n",
+ "\n",
+ "# Build the exact format you want: {text1|text2|text3|...}\n",
+ "combined_content = '{' + '|'.join(cleaned_titles) + '}'\n",
+ "\n",
+ "# Save to a single .txt file (no newlines)\n",
+ "output_file = \"/content/combined_titles.txt\"\n",
+ "with open(output_file, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(combined_content)\n",
+ "\n",
+ "# Confirmation\n",
+ "print(f\"\\n✅ Done! Combined {len(cleaned_titles)} titles into one line.\")\n",
+ "print(f\"📁 Saved as: {output_file}\")\n",
+ "print(f\" (First 100 characters: {combined_content[:100]}...)\")\n",
+ "\n",
+ "# Auto-download the combined file\n",
+ "files.download(output_file)\n",
+ "\n",
+ "print(\"📥 Download started. You can now use this file wherever you need the {title1|title2|...} format.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [],
+ "metadata": {
+ "id": "E82hTdUFaHZE"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "tCD1B-_kaHuq"
+ },
+ "source": [
+ "# Extract image links from text and download them"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "# ================================================\n",
+ "# 🌏 HTML Image Downloader + EXIF Metadata + Resize + Format Control\n",
+ "# ================================================\n",
+ "\n",
+ "#@title **🌏 HTML Image Downloader with EXIF Metadata**\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown ### **Input**\n",
+ "use_file_upload = False #@param {type:\"boolean\"}\n",
+ "html_filepath = \"\" #@param {type:\"string\"}\n",
+ "#@markdown Try https://chromewebstore.google.com/detail/save-rendered-html/\"\n",
+ "\n",
+ "process_all_html_in_drive_folder = True #@param {type:\"boolean\"}\n",
+ "html_input_folder = \"/content/drive/MyDrive/html_grabs/\" #@param {type:\"string\"}\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown ### **Download & Processing Settings**\n",
+ "delay_seconds = 1.0 #@param {type:\"slider\", min:0, max:10, step:0.1}\n",
+ "max_longest_side_px = 2048 #@param {type:\"slider\", min:512, max:4096, step:64}\n",
+ "output_folder = \"fetched_from_html\" #@param {type:\"string\"}\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown ### **Image Output Settings**\n",
+ "output_format = \"JPEG\" #@param [\"JPEG\", \"PNG\", \"WEBP\"]\n",
+ "image_quality = 95 #@param {type:\"slider\", min:10, max:100, step:1}\n",
+ "extract_exif_metadata = False #@param {type:\"boolean\"}\n",
+ "\n",
+ "#@markdown ---\n",
+ "\n",
+ "#@markdown ### **Google Drive Options**\n",
+ "save_to_drive = True #@param {type:\"boolean\"}\n",
+ "drive_folder_name = \"html_fetch\" #@param {type:\"string\"}\n",
+ "\n",
+ "encrypt_dataset = False #@param {type:\"boolean\"}\n",
+ "encryption_password = \"banana\" #@param {type:\"string\"}\n",
+ "\n",
+ "#@markdown ---\n",
+ "#@markdown **Run this cell after uploading your HTML file (if enabled) or setting `html_filepath`**\n",
+ "\n",
+ "# ================================================\n",
+ "# ================== CODE START ==================\n",
+ "# ================================================\n",
+ "\n",
+ "!pip install beautifulsoup4 lxml pynacl -q\n",
+ "\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "import os, time, hashlib, shutil, zipfile, glob\n",
+ "from urllib.parse import urljoin, urlparse\n",
+ "from PIL import Image, ExifTags\n",
+ "import io\n",
+ "from nacl.secret import SecretBox\n",
+ "from nacl.utils import random\n",
+ "from google.colab import drive, files\n",
+ "from datetime import datetime\n",
+ "\n",
+ "# ====================== UPLOAD HTML FILE / GET ALL HTML CONTENTS ======================\n",
+ "def get_all_html_contents():\n",
+ " html_contents_list = []\n",
+ " if process_all_html_in_drive_folder:\n",
+ " print(f\"Processing all HTML files in: {html_input_folder}\")\n",
+ " drive.mount('/content/drive', force_remount=False) # Ensure drive is mounted\n",
+ " if not os.path.exists(html_input_folder):\n",
+ " print(f\"❌ HTML input folder not found: {html_input_folder}\")\n",
+ " return []\n",
+ " for root, _, files_in_dir in os.walk(html_input_folder):\n",
+ " for fname in files_in_dir:\n",
+ " if fname.lower().endswith(('.html', '.htm')):\n",
+ " full_path = os.path.join(root, fname)\n",
+ " try:\n",
+ " with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:\n",
+ " content = f.read()\n",
+ " # Sanitize content\n",
+ " content = content.encode('utf-8', errors='replace').decode('utf-8')\n",
+ " html_contents_list.append((fname, content))\n",
+ " print(f\"✅ Loaded HTML file: {fname}\")\n",
+ " except Exception as e:\n",
+ " print(f\"❌ Error reading {fname}: {e}\")\n",
+ " if not html_contents_list:\n",
+ " print(f\"❌ No HTML files found in {html_input_folder}.\")\n",
+ " return html_contents_list\n",
+ " else:\n",
+ " # Original logic for single file\n",
+ " html_content = \"\"\n",
+ " html_filename = \"single_input.html\" # Default name for single input case\n",
+ " if use_file_upload:\n",
+ " print(\"Please upload your HTML file:\")\n",
+ " uploaded = files.upload()\n",
+ " if not uploaded:\n",
+ " print(\"❌ No HTML file uploaded!\")\n",
+ " return []\n",
+ " html_filename = list(uploaded.keys())[0]\n",
+ " html_content = uploaded[html_filename].decode('utf-8', errors='ignore')\n",
+ " else: # Use filepath from parameter\n",
+ " if html_filepath and os.path.exists(html_filepath):\n",
+ " print(f\"Reading HTML from file: {html_filepath}\")\n",
+ " with open(html_filepath, 'r', encoding='utf-8', errors='ignore') as f:\n",
+ " html_content = f.read()\n",
+ " html_filename = os.path.basename(html_filepath)\n",
+ " else:\n",
+ " print(f\"❌ HTML filepath not found, empty, or 'use_file_upload' is True but no file was uploaded: {html_filepath}\")\n",
+ " return []\n",
+ "\n",
+ " html_content = html_content.encode('utf-8', errors='replace').decode('utf-8')\n",
+ " return [(html_filename, html_content)]\n",
+ "\n",
+ "# ====================== EXTRACT IMAGE URLS ======================\n",
+ "def extract_image_urls(html_text):\n",
+ " if not html_text.strip():\n",
+ " return []\n",
+ " soup = BeautifulSoup(html_text, 'html.parser')\n",
+ " urls = []\n",
+ " for img in soup.find_all('img'):\n",
+ " src = img.get('src') or img.get('data-src') or img.get('data-original') or img.get('data-lazy-src')\n",
+ " if src and src.startswith(('http://', 'https://')): # Only absolute URLs since base_url was removed\n",
+ " urls.append(src)\n",
+ " return list(dict.fromkeys(urls))\n",
+ "\n",
+ "# ====================== EXTRACT EXIF METADATA ======================\n",
+ "def save_exif_metadata(image_path, txt_path):\n",
+ " try:\n",
+ " with Image.open(image_path) as img:\n",
+ " exif = img._getexif()\n",
+ " if exif:\n",
+ " with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(\"=== EXIF METADATA ===\\n\")\n",
+ " f.write(f\"Extracted on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\")\n",
+ " for tag_id, value in exif.items():\n",
+ " tag_name = ExifTags.TAGS.get(tag_id, f\"Unknown_Tag_{tag_id}\")\n",
+ " f.write(f\"{tag_name}: {value}\\n\")\n",
+ " else:\n",
+ " with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(\"No EXIF metadata found in this image.\")\n",
+ " except Exception as e:\n",
+ " with open(txt_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(f\"Failed to read metadata: {e}\")\n",
+ "\n",
+ "# ====================== MAIN PROCESS ======================\n",
+ "print(\"\\u21ba Starting process...\\n\")\n",
+ "\n",
+ "all_html_inputs = get_all_html_contents()\n",
+ "\n",
+ "if not all_html_inputs:\n",
+ " print(\"\\u274c No HTML content to process!\")\n",
+ "else:\n",
+ " all_extracted_urls = []\n",
+ " for html_filename, html_content in all_html_inputs:\n",
+ " print(f\"Extracting URLs from: {html_filename}\")\n",
+ " urls_from_this_html = extract_image_urls(html_content)\n",
+ " print(f\" Found {len(urls_from_this_html)} URLs in {html_filename}.\")\n",
+ " all_extracted_urls.extend(urls_from_this_html)\n",
+ "\n",
+ " unique_urls = list(dict.fromkeys(all_extracted_urls)) # Remove duplicates\n",
+ " print(f\"\\uD83D\\uDD0D Found {len(unique_urls)} unique images across all HTML files. Starting download...\\n\")\n",
+ "\n",
+ " os.makedirs(output_folder, exist_ok=True)\n",
+ " headers = {'User-Agent': 'Mozilla/5.0'}\n",
+ "\n",
+ " downloaded_counter = 0\n",
+ " for i, url in enumerate(unique_urls, 1):\n",
+ " try:\n",
+ " r = requests.get(url, headers=headers, timeout=15, stream=True)\n",
+ " r.raise_for_status()\n",
+ "\n",
+ " temp_path = os.path.join(output_folder, f\"temp_{i:04d}.tmp\")\n",
+ " with open(temp_path, 'wb') as f:\n",
+ " for chunk in r.iter_content(8192):\n",
+ " f.write(chunk)\n",
+ "\n",
+ " # Process image\n",
+ " with Image.open(temp_path) as img:\n",
+ " original_mode = img.mode\n",
+ " if img.mode in ('RGBA', 'P'):\n",
+ " img = img.convert('RGB')\n",
+ "\n",
+ " was_resized = False\n",
+ " w, h = img.size\n",
+ " if max(w, h) > max_longest_side_px:\n",
+ " scale = max_longest_side_px / max(w, h)\n",
+ " new_size = (int(w * scale), int(h * scale))\n",
+ " img = img.resize(new_size, Image.LANCZOS)\n",
+ " was_resized = True\n",
+ "\n",
+ " # Final filename\n",
+ " ext = \".jpg\" if output_format == \"JPEG\" else \".png\" if output_format == \"PNG\" else \".webp\"\n",
+ " final_name = f\"{i:04d}{ext}\"\n",
+ " final_path = os.path.join(output_folder, final_name)\n",
+ "\n",
+ " # Save with selected format & quality\n",
+ " if output_format == \"JPEG\":\n",
+ " img.save(final_path, quality=image_quality, optimize=True)\n",
+ " elif output_format == \"PNG\":\n",
+ " img.save(final_path, compress_level=6)\n",
+ " else:\n",
+ " img.save(final_path, quality=image_quality)\n",
+ "\n",
+ " # Save EXIF metadata if requested\n",
+ " if extract_exif_metadata:\n",
+ " txt_path = os.path.join(output_folder, f\"{i:04d}.txt\")\n",
+ " save_exif_metadata(final_path, txt_path)\n",
+ "\n",
+ " # Clean temp file\n",
+ " os.remove(temp_path)\n",
+ " downloaded_counter += 1\n",
+ " print(f\"\\u2705 {downloaded_counter:04d} saved\")\n",
+ "\n",
+ " except Exception as e:\n",
+ " print(f\"\\u274c Failed {i:04d}: {url[:70]}...\")\n",
+ "\n",
+ " if i < len(unique_urls) and delay_seconds > 0:\n",
+ " time.sleep(delay_seconds)\n",
+ "\n",
+ " print(f\"\\n\\uD83C\\uDF89 All {downloaded_counter} images processed and renamed as 0001, 0002, 0003...\")\n",
+ "\n",
+ " # ====================== SAVE TO DRIVE ======================\n",
+ " if save_to_drive:\n",
+ " drive.mount('/content/drive', force_remount=True)\n",
+ " drive_path = f\"/content/drive/MyDrive/{drive_folder_name}\"\n",
+ " os.makedirs(drive_path, exist_ok=True)\n",
+ "\n",
+ " # Save html_filepath if it was used and not an upload\n",
+ " # This logic needs adjustment if multiple HTML files were processed.\n",
+ " # For now, we only record the html_filepath if a single file was processed via `html_filepath`.\n",
+ " if not process_all_html_in_drive_folder and not use_file_upload and html_filepath and os.path.exists(html_filepath):\n",
+ " filepath_record_path = os.path.join(drive_path, \"original_html_filepath.txt\")\n",
+ " with open(filepath_record_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(html_filepath)\n",
+ " print(f\"\\u2705 Original HTML filepath saved to Drive: {filepath_record_path}\")\n",
+ "\n",
+ " # Save encryption password to password.txt\n",
+ " if encryption_password:\n",
+ " password_file_path = os.path.join(drive_path, \"password.txt\")\n",
+ " with open(password_file_path, \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(encryption_password)\n",
+ " print(f\"\\u2705 Encryption password saved to Drive: {password_file_path}\")\n",
+ "\n",
+ " if encrypt_dataset and encryption_password:\n",
+ " print(\"\\uD83D\\uDD10 Encryption feature is available (can be expanded if needed)\")\n",
+ " # Encryption code can be added later if you want it back\n",
+ " else:\n",
+ " zip_path = shutil.make_archive(f\"/content/{output_folder}\", 'zip', output_folder)\n",
+ " final_zip_path = os.path.join(drive_path, f\"{output_folder}.zip\")\n",
+ " shutil.move(zip_path, final_zip_path)\n",
+ " print(f\"\\u2705 ZIP file saved to Google Drive:\\n\\uD83D\\uDCC1 {final_zip_path}\")\n",
+ "\n",
+ " # Clear the local output folder after zipping and moving\n",
+ " shutil.rmtree(output_folder, ignore_errors=True)\n",
+ " print(f\"\\u2705 Local folder '{output_folder}' cleared.\")\n",
+ "\n",
+ " # Delete the HTML file from Drive after processing if it was read from a file\n",
+ " if not process_all_html_in_drive_folder and not use_file_upload and html_filepath and os.path.exists(html_filepath):\n",
+ " try:\n",
+ " os.remove(html_filepath)\n",
+ " print(f\"\\u2705 Original HTML file deleted from Drive: {html_filepath}\")\n",
+ " except Exception as e:\n",
+ " print(f\"\\u274c Error deleting original HTML file from Drive: {e}\")\n",
+ "\n",
+ " print(\"\\n\\u2705 Process Completed!\")"
+ ],
+ "metadata": {
+ "id": "amxSvxVfaZRA",
+ "cellView": "form",
+ "outputId": "dab242c0-bf6b-429e-f413-0ba130b9b929",
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ }
+ },
+ "execution_count": null,
+ "outputs": [
+ {
+ "metadata": {
+ "tags": null
+ },
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/1.4 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m1.4/1.4 MB\u001b[0m \u001b[31m53.8 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.4/1.4 MB\u001b[0m \u001b[31m21.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
+ "\u001b[?25h↺ Starting process...\n",
+ "\n",
+ "Processing all HTML files in: /content/drive/MyDrive/html_grabs/\n",
+ "Mounted at /content/drive\n",
+ "✅ Loaded HTML file: posts.html\n",
+ "Extracting URLs from: posts.html\n"
+ ]
+ },
+ {
+ "metadata": {
+ "tags": null
+ },
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "ERROR:tornado.application:Exception in callback functools.partial(>)\n",
+ "Traceback (most recent call last):\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/jupyter_client/session.py\", line 104, in json_packer\n",
+ " ).encode(\"utf8\", errors=\"surrogateescape\")\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ "UnicodeEncodeError: 'utf-8' codec can't encode characters in position 61-62: surrogates not allowed\n",
+ "\n",
+ "During handling of the above exception, another exception occurred:\n",
+ "\n",
+ "Traceback (most recent call last):\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/tornado/ioloop.py\", line 758, in _run_callback\n",
+ " ret = callback()\n",
+ " ^^^^^^^^^^\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/ipykernel/iostream.py\", line 518, in _flush\n",
+ " self.session.send(\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/jupyter_client/session.py\", line 848, in send\n",
+ " to_send = self.serialize(msg, ident)\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/jupyter_client/session.py\", line 718, in serialize\n",
+ " content = self.pack(content)\n",
+ " ^^^^^^^^^^^^^^^^^^\n",
+ " File \"/usr/local/lib/python3.12/dist-packages/jupyter_client/session.py\", line 112, in json_packer\n",
+ " ).encode(\"utf8\", errors=\"surrogateescape\")\n",
+ " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
+ "UnicodeEncodeError: 'utf-8' codec can't encode characters in position 61-62: surrogates not allowed\n"
+ ]
+ },
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "❌ Failed 0001: https://image.tensorartassets.com/cdn-cgi/image/anim=false,plain=false...\n",
+ "❌ Failed 0002: https://image.tensorartassets.com/cdn-cgi/image/anim=false,plain=false...\n",
+ "❌ Failed 0003: https://image.tensorartassets.com/cdn-cgi/image/anim=false,plain=false...\n",
+ "❌ Failed 0004: https://image.tensorartassets.com/cdn-cgi/image/anim=false,plain=false...\n",
+ "✅ 0001 saved\n",
+ "❌ Failed 0006: https://image.tensorartassets.com/frontend/155caa5deb0c97aeb01c08df6d9...\n",
+ "✅ 0002 saved\n",
+ "✅ 0003 saved\n",
+ "❌ Failed 0009: https://image.tensorartassets.com/frontend/c6861894832c3e885197f53356c...\n",
+ "❌ Failed 0010: https://image.tensorartassets.com/frontend/aa5ca485c3cb18b679e6a970f65...\n",
+ "❌ Failed 0011: https://image.tensorartassets.com/frontend/72ddcdd1808cbb025680c677dad...\n",
+ "❌ Failed 0012: https://image.tensorartassets.com/frontend/91556d1e7a4903d20c0da65eedf...\n",
+ "❌ Failed 0013: https://image.tensorartassets.com/frontend/a0f33b3f654cacfe9b75a13843f...\n",
+ "❌ Failed 0014: https://image.tensorartassets.com/frontend/f284f65126389e1b552c0db0ac5...\n",
+ "❌ Failed 0015: https://image.tensorartassets.com/frontend/2e74fd848fad692dd269ce69abe...\n",
+ "❌ Failed 0016: https://image.tensorartassets.com/frontend/25ca640da8fae681beaeb8204b1...\n",
+ "❌ Failed 0017: https://image.tensorartassets.com/frontend/45244bad5a768dfcbdc9cda8aa0...\n",
+ "❌ Failed 0018: https://image.tensorartassets.com/frontend/f0a4fc1b05b4a824f407752733a...\n",
+ "❌ Failed 0019: https://image.tensorartassets.com/frontend/520983bf4f804141978802b268c...\n",
+ "❌ Failed 0020: https://image.tensorartassets.com/frontend/aa3246e20e3dffba223a25fa101...\n",
+ "❌ Failed 0021: https://image.tensorartassets.com/frontend/f148b5b7efabf78e9733a6d026f...\n",
+ "❌ Failed 0022: https://image.tensorartassets.com/frontend/4ccd8ed648a0bb92fd246ad539c...\n",
+ "❌ Failed 0023: https://image.tensorartassets.com/frontend/fe00964ef90dbd3e7415143e05f...\n",
+ "✅ 0004 saved\n",
+ "✅ 0005 saved\n",
+ "✅ 0006 saved\n",
+ "✅ 0007 saved\n",
+ "✅ 0008 saved\n",
+ "✅ 0009 saved\n",
+ "✅ 0010 saved\n",
+ "✅ 0011 saved\n",
+ "✅ 0012 saved\n",
+ "✅ 0013 saved\n",
+ "✅ 0014 saved\n",
+ "✅ 0015 saved\n",
+ "✅ 0016 saved\n",
+ "✅ 0017 saved\n",
+ "✅ 0018 saved\n",
+ "✅ 0019 saved\n",
+ "✅ 0020 saved\n",
+ "✅ 0021 saved\n",
+ "✅ 0022 saved\n",
+ "✅ 0023 saved\n",
+ "✅ 0024 saved\n",
+ "✅ 0025 saved\n",
+ "✅ 0026 saved\n",
+ "✅ 0027 saved\n",
+ "✅ 0028 saved\n",
+ "✅ 0029 saved\n",
+ "✅ 0030 saved\n",
+ "✅ 0031 saved\n",
+ "✅ 0032 saved\n",
+ "✅ 0033 saved\n",
+ "✅ 0034 saved\n",
+ "✅ 0035 saved\n",
+ "✅ 0036 saved\n",
+ "✅ 0037 saved\n",
+ "✅ 0038 saved\n",
+ "✅ 0039 saved\n",
+ "✅ 0040 saved\n",
+ "✅ 0041 saved\n",
+ "✅ 0042 saved\n",
+ "✅ 0043 saved\n",
+ "✅ 0044 saved\n",
+ "✅ 0045 saved\n",
+ "✅ 0046 saved\n",
+ "✅ 0047 saved\n",
+ "✅ 0048 saved\n",
+ "✅ 0049 saved\n",
+ "✅ 0050 saved\n",
+ "✅ 0051 saved\n",
+ "✅ 0052 saved\n",
+ "✅ 0053 saved\n",
+ "✅ 0054 saved\n",
+ "✅ 0055 saved\n",
+ "✅ 0056 saved\n",
+ "✅ 0057 saved\n",
+ "✅ 0058 saved\n",
+ "✅ 0059 saved\n",
+ "✅ 0060 saved\n",
+ "✅ 0061 saved\n",
+ "✅ 0062 saved\n",
+ "✅ 0063 saved\n",
+ "✅ 0064 saved\n",
+ "✅ 0065 saved\n",
+ "✅ 0066 saved\n",
+ "✅ 0067 saved\n",
+ "✅ 0068 saved\n",
+ "✅ 0069 saved\n",
+ "✅ 0070 saved\n",
+ "✅ 0071 saved\n",
+ "✅ 0072 saved\n",
+ "✅ 0073 saved\n",
+ "✅ 0074 saved\n",
+ "✅ 0075 saved\n",
+ "✅ 0076 saved\n",
+ "✅ 0077 saved\n",
+ "✅ 0078 saved\n",
+ "✅ 0079 saved\n",
+ "✅ 0080 saved\n",
+ "✅ 0081 saved\n",
+ "✅ 0082 saved\n",
+ "✅ 0083 saved\n",
+ "✅ 0084 saved\n",
+ "✅ 0085 saved\n",
+ "✅ 0086 saved\n",
+ "✅ 0087 saved\n",
+ "✅ 0088 saved\n",
+ "✅ 0089 saved\n",
+ "✅ 0090 saved\n",
+ "✅ 0091 saved\n",
+ "✅ 0092 saved\n",
+ "✅ 0093 saved\n",
+ "✅ 0094 saved\n",
+ "✅ 0095 saved\n",
+ "✅ 0096 saved\n",
+ "✅ 0097 saved\n",
+ "✅ 0098 saved\n",
+ "✅ 0099 saved\n",
+ "✅ 0100 saved\n",
+ "✅ 0101 saved\n",
+ "✅ 0102 saved\n",
+ "✅ 0103 saved\n",
+ "✅ 0104 saved\n",
+ "✅ 0105 saved\n",
+ "✅ 0106 saved\n",
+ "✅ 0107 saved\n",
+ "✅ 0108 saved\n",
+ "✅ 0109 saved\n",
+ "✅ 0110 saved\n",
+ "✅ 0111 saved\n",
+ "✅ 0112 saved\n",
+ "✅ 0113 saved\n",
+ "✅ 0114 saved\n",
+ "✅ 0115 saved\n",
+ "✅ 0116 saved\n",
+ "✅ 0117 saved\n",
+ "✅ 0118 saved\n",
+ "✅ 0119 saved\n",
+ "✅ 0120 saved\n",
+ "✅ 0121 saved\n",
+ "✅ 0122 saved\n",
+ "✅ 0123 saved\n",
+ "✅ 0124 saved\n",
+ "✅ 0125 saved\n",
+ "✅ 0126 saved\n",
+ "✅ 0127 saved\n",
+ "✅ 0128 saved\n",
+ "✅ 0129 saved\n",
+ "✅ 0130 saved\n",
+ "✅ 0131 saved\n",
+ "✅ 0132 saved\n",
+ "✅ 0133 saved\n",
+ "✅ 0134 saved\n",
+ "✅ 0135 saved\n",
+ "✅ 0136 saved\n",
+ "✅ 0137 saved\n",
+ "✅ 0138 saved\n",
+ "✅ 0139 saved\n",
+ "✅ 0140 saved\n",
+ "✅ 0141 saved\n",
+ "✅ 0142 saved\n",
+ "✅ 0143 saved\n",
+ "✅ 0144 saved\n",
+ "✅ 0145 saved\n",
+ "✅ 0146 saved\n",
+ "✅ 0147 saved\n",
+ "✅ 0148 saved\n",
+ "✅ 0149 saved\n",
+ "✅ 0150 saved\n",
+ "✅ 0151 saved\n",
+ "✅ 0152 saved\n",
+ "✅ 0153 saved\n",
+ "✅ 0154 saved\n",
+ "✅ 0155 saved\n",
+ "✅ 0156 saved\n",
+ "✅ 0157 saved\n",
+ "✅ 0158 saved\n",
+ "✅ 0159 saved\n",
+ "✅ 0160 saved\n",
+ "✅ 0161 saved\n",
+ "✅ 0162 saved\n",
+ "✅ 0163 saved\n",
+ "✅ 0164 saved\n",
+ "✅ 0165 saved\n",
+ "✅ 0166 saved\n",
+ "✅ 0167 saved\n",
+ "✅ 0168 saved\n",
+ "✅ 0169 saved\n",
+ "✅ 0170 saved\n",
+ "✅ 0171 saved\n",
+ "✅ 0172 saved\n",
+ "✅ 0173 saved\n",
+ "✅ 0174 saved\n",
+ "✅ 0175 saved\n",
+ "✅ 0176 saved\n",
+ "✅ 0177 saved\n",
+ "✅ 0178 saved\n",
+ "✅ 0179 saved\n",
+ "✅ 0180 saved\n",
+ "✅ 0181 saved\n",
+ "✅ 0182 saved\n",
+ "✅ 0183 saved\n",
+ "✅ 0184 saved\n",
+ "✅ 0185 saved\n",
+ "✅ 0186 saved\n",
+ "✅ 0187 saved\n",
+ "✅ 0188 saved\n",
+ "✅ 0189 saved\n",
+ "✅ 0190 saved\n",
+ "✅ 0191 saved\n",
+ "✅ 0192 saved\n",
+ "✅ 0193 saved\n",
+ "✅ 0194 saved\n",
+ "✅ 0195 saved\n",
+ "✅ 0196 saved\n",
+ "✅ 0197 saved\n",
+ "✅ 0198 saved\n",
+ "✅ 0199 saved\n",
+ "✅ 0200 saved\n",
+ "✅ 0201 saved\n",
+ "✅ 0202 saved\n",
+ "✅ 0203 saved\n",
+ "✅ 0204 saved\n",
+ "✅ 0205 saved\n",
+ "✅ 0206 saved\n",
+ "✅ 0207 saved\n",
+ "✅ 0208 saved\n",
+ "✅ 0209 saved\n",
+ "✅ 0210 saved\n",
+ "✅ 0211 saved\n",
+ "✅ 0212 saved\n",
+ "✅ 0213 saved\n",
+ "✅ 0214 saved\n",
+ "✅ 0215 saved\n",
+ "✅ 0216 saved\n",
+ "✅ 0217 saved\n",
+ "✅ 0218 saved\n",
+ "✅ 0219 saved\n",
+ "✅ 0220 saved\n",
+ "✅ 0221 saved\n",
+ "✅ 0222 saved\n",
+ "✅ 0223 saved\n",
+ "✅ 0224 saved\n",
+ "✅ 0225 saved\n",
+ "✅ 0226 saved\n",
+ "✅ 0227 saved\n",
+ "✅ 0228 saved\n",
+ "✅ 0229 saved\n",
+ "✅ 0230 saved\n",
+ "✅ 0231 saved\n",
+ "✅ 0232 saved\n",
+ "✅ 0233 saved\n",
+ "✅ 0234 saved\n",
+ "✅ 0235 saved\n",
+ "✅ 0236 saved\n",
+ "✅ 0237 saved\n",
+ "✅ 0238 saved\n",
+ "✅ 0239 saved\n",
+ "✅ 0240 saved\n",
+ "✅ 0241 saved\n",
+ "✅ 0242 saved\n"
+ ]
+ }
+ ]
+ }
+ ],
+ "metadata": {
+ "colab": {
+ "provenance": [],
+ "collapsed_sections": [
+ "gSErGKBctoAc",
+ "V5i2-xwTGG4K",
+ "WX17R9Yc6U1A",
+ "qisU9VeIyzX2",
+ "0VlyEacYp7Pn",
+ "JrtsI98cmAxB",
+ "s40baE0G_wn7",
+ "lUIEma9C-36K",
+ "02aZcv2lB_hC",
+ "U27drDtMB53n",
+ "LaxF_cnIGNMh"
+ ]
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "name": "python3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
\ No newline at end of file