diff --git "a/fetch_from_reddit.ipynb" "b/fetch_from_reddit.ipynb"
--- "a/fetch_from_reddit.ipynb"
+++ "b/fetch_from_reddit.ipynb"
@@ -1 +1 @@
-{"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":"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":"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":{"cellView":"form","id":"P-4aeky_F2UN"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ✂️ Image slicer"],"metadata":{"id":"OHPBxduU0aMa"}},{"cell_type":"code","source":["# @title Image Column Slicer + Left/Right/Bottom Crop (Upload → Crop Left/Right/Bottom % → Slice into N Columns → Download ZIP)\n","\n","N = 20 #@param {type:\"slider\", min:1, max:100, step:1}\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","import io\n","import os\n","from PIL import Image\n","import zipfile\n","from google.colab import files\n","\n","print(f\"✅ Number of columns per image set to: **{N}**\")\n","print(f\"✅ Left crop percentage set to: **{left_crop_percent}%**\")\n","print(f\"✅ Right crop percentage set to: **{right_crop_percent}%**\")\n","print(f\"✅ Bottom crop percentage set to: **{bottom_crop_percent}%**\")\n","\n","# ====================== UPLOAD IMAGES ======================\n","print(\"\\n📤 Please select and upload your images (you can select multiple)...\")\n","uploaded = files.upload()\n","\n","if not uploaded:\n"," print(\"❌ No files were uploaded.\")\n","else:\n"," print(f\"📸 Found {len(uploaded)} file(s). Processing images...\")\n","\n"," # ====================== CREATE ZIP IN MEMORY ======================\n"," zip_buffer = io.BytesIO()\n"," with zipfile.ZipFile(zip_buffer, \"w\", zipfile.ZIP_DEFLATED) as zip_file:\n"," processed_count = 0\n","\n"," for filename, file_content in uploaded.items():\n"," # Only process common image formats\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')):\n"," try:\n"," # Open the image\n"," image = Image.open(io.BytesIO(file_content))\n"," width, height = image.size\n","\n"," # ====================== APPLY LEFT, RIGHT & BOTTOM CROPS ======================\n"," left_px = int(width * left_crop_percent / 100.0)\n"," right_px = int(width * (1 - right_crop_percent / 100.0))\n"," bottom_px = int(height * (1 - bottom_crop_percent / 100.0))\n","\n"," if left_px >= right_px or bottom_px < 1:\n"," print(f\"⚠️ {filename} would have zero width or height after crops. Skipping.\")\n"," continue\n","\n"," image = image.crop((left_px, 0, right_px, bottom_px))\n"," width, height = image.size\n","\n"," if left_crop_percent > 0 or right_crop_percent > 0 or bottom_crop_percent > 0:\n"," print(f\" 📏 Cropped left {left_crop_percent}% , right {right_crop_percent}% , bottom {bottom_crop_percent}% of {filename} → new size: {width}x{height}px\")\n","\n"," # ====================== SLICE INTO N COLUMNS ======================\n"," if width < N:\n"," print(f\"⚠️ {filename} is too narrow ({width}px) for {N} columns. Skipping.\")\n"," continue\n","\n"," col_width = width // N\n"," base_name = os.path.splitext(filename)[0]\n","\n"," # Slice into N vertical columns\n"," for i in range(N):\n"," left = i * col_width\n"," right = (i + 1) * col_width if i < N - 1 else width\n","\n"," cropped = image.crop((left, 0, right, height))\n","\n"," # Name each slice nicely (1-based indexing with leading zeros)\n"," slice_name = f\"{base_name}_col_{i+1:02d}.png\"\n","\n"," # Save slice as PNG (lossless) into the zip\n"," slice_buffer = io.BytesIO()\n"," cropped.save(slice_buffer, format=\"PNG\")\n"," slice_buffer.seek(0)\n","\n"," zip_file.writestr(slice_name, slice_buffer.getvalue())\n","\n"," processed_count += 1\n"," print(f\"✅ Sliced {filename} → {N} columns\")\n","\n"," except Exception as e:\n"," print(f\"❌ Error processing {filename}: {e}\")\n"," else:\n"," print(f\"⏭️ Skipping non-image file: {filename}\")\n","\n"," # ====================== SAVE & DOWNLOAD ZIP ======================\n"," if processed_count > 0:\n"," zip_buffer.seek(0)\n"," zip_path = \"/content/sliced_columns.zip\"\n","\n"," with open(zip_path, \"wb\") as f:\n"," f.write(zip_buffer.getvalue())\n","\n"," print(f\"\\n🎉 Finished! Created ZIP with slices from {processed_count} image(s).\")\n"," print(\" (Left, Right & Bottom crops were applied before slicing)\")\n"," print(\"📥 Downloading 'sliced_columns.zip' now...\")\n"," files.download(zip_path)\n"," else:\n"," print(\"\\n❌ No images were successfully processed.\")"],"metadata":{"id":"_7e5md75xJuI","cellView":"form"},"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":1775998096400,"user_tz":-120,"elapsed":13528,"user":{"displayName":"","userId":""}},"outputId":"655efe02-6df2-4936-c593-60b481c88e10","colab":{"base_uri":"https://localhost:8080/","height":253}},"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 Archive.zip to Archive.zip\n","✅ ZIP extracted to /content/extracted_txt_files\n","📄 Found 340 title files. Processing...\n","\n","✅ Done! Combined 340 titles into one line.\n","📁 Saved as: /content/combined_titles.txt\n"," (First 100 characters: {The image depicts a person with long, dark hair, wearing a red and black checkered jacket, and p...)\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_6856ff8e-4e27-412d-9c7b-169baff4784e\", \"combined_titles.txt\", 477304)"]},"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.\")"]}],"metadata":{"colab":{"provenance":[{"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","qisU9VeIyzX2","0VlyEacYp7Pn","JrtsI98cmAxB","s40baE0G_wn7","OHPBxduU0aMa","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","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":"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":"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":{"cellView":"form","id":"P-4aeky_F2UN"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# ✂️ Image slicer"],"metadata":{"id":"OHPBxduU0aMa"}},{"cell_type":"code","source":["# @title Image Column Slicer + Left/Right/Bottom Crop (Upload → Crop Left/Right/Bottom % → Slice into N Columns → Download ZIP)\n","\n","N = 20 #@param {type:\"slider\", min:1, max:100, step:1}\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","import io\n","import os\n","from PIL import Image\n","import zipfile\n","from google.colab import files\n","\n","print(f\"✅ Number of columns per image set to: **{N}**\")\n","print(f\"✅ Left crop percentage set to: **{left_crop_percent}%**\")\n","print(f\"✅ Right crop percentage set to: **{right_crop_percent}%**\")\n","print(f\"✅ Bottom crop percentage set to: **{bottom_crop_percent}%**\")\n","\n","# ====================== UPLOAD IMAGES ======================\n","print(\"\\n📤 Please select and upload your images (you can select multiple)...\")\n","uploaded = files.upload()\n","\n","if not uploaded:\n"," print(\"❌ No files were uploaded.\")\n","else:\n"," print(f\"📸 Found {len(uploaded)} file(s). Processing images...\")\n","\n"," # ====================== CREATE ZIP IN MEMORY ======================\n"," zip_buffer = io.BytesIO()\n"," with zipfile.ZipFile(zip_buffer, \"w\", zipfile.ZIP_DEFLATED) as zip_file:\n"," processed_count = 0\n","\n"," for filename, file_content in uploaded.items():\n"," # Only process common image formats\n"," if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')):\n"," try:\n"," # Open the image\n"," image = Image.open(io.BytesIO(file_content))\n"," width, height = image.size\n","\n"," # ====================== APPLY LEFT, RIGHT & BOTTOM CROPS ======================\n"," left_px = int(width * left_crop_percent / 100.0)\n"," right_px = int(width * (1 - right_crop_percent / 100.0))\n"," bottom_px = int(height * (1 - bottom_crop_percent / 100.0))\n","\n"," if left_px >= right_px or bottom_px < 1:\n"," print(f\"⚠️ {filename} would have zero width or height after crops. Skipping.\")\n"," continue\n","\n"," image = image.crop((left_px, 0, right_px, bottom_px))\n"," width, height = image.size\n","\n"," if left_crop_percent > 0 or right_crop_percent > 0 or bottom_crop_percent > 0:\n"," print(f\" 📏 Cropped left {left_crop_percent}% , right {right_crop_percent}% , bottom {bottom_crop_percent}% of {filename} → new size: {width}x{height}px\")\n","\n"," # ====================== SLICE INTO N COLUMNS ======================\n"," if width < N:\n"," print(f\"⚠️ {filename} is too narrow ({width}px) for {N} columns. Skipping.\")\n"," continue\n","\n"," col_width = width // N\n"," base_name = os.path.splitext(filename)[0]\n","\n"," # Slice into N vertical columns\n"," for i in range(N):\n"," left = i * col_width\n"," right = (i + 1) * col_width if i < N - 1 else width\n","\n"," cropped = image.crop((left, 0, right, height))\n","\n"," # Name each slice nicely (1-based indexing with leading zeros)\n"," slice_name = f\"{base_name}_col_{i+1:02d}.png\"\n","\n"," # Save slice as PNG (lossless) into the zip\n"," slice_buffer = io.BytesIO()\n"," cropped.save(slice_buffer, format=\"PNG\")\n"," slice_buffer.seek(0)\n","\n"," zip_file.writestr(slice_name, slice_buffer.getvalue())\n","\n"," processed_count += 1\n"," print(f\"✅ Sliced {filename} → {N} columns\")\n","\n"," except Exception as e:\n"," print(f\"❌ Error processing {filename}: {e}\")\n"," else:\n"," print(f\"⏭️ Skipping non-image file: {filename}\")\n","\n"," # ====================== SAVE & DOWNLOAD ZIP ======================\n"," if processed_count > 0:\n"," zip_buffer.seek(0)\n"," zip_path = \"/content/sliced_columns.zip\"\n","\n"," with open(zip_path, \"wb\") as f:\n"," f.write(zip_buffer.getvalue())\n","\n"," print(f\"\\n🎉 Finished! Created ZIP with slices from {processed_count} image(s).\")\n"," print(\" (Left, Right & Bottom crops were applied before slicing)\")\n"," print(\"📥 Downloading 'sliced_columns.zip' now...\")\n"," files.download(zip_path)\n"," else:\n"," print(\"\\n❌ No images were successfully processed.\")"],"metadata":{"id":"_7e5md75xJuI","cellView":"form"},"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"},"outputs":[],"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":"code","source":["# @title Thumbnail Fetcher + Save to Drive (ZIP + Titles) - FIXED v5.6 (undetected-chromedriver + chromium-chromedriver)\n","# ✅ FIXED v5.6:\n","# • Added `chromium-chromedriver` to apt install (this was the missing piece)\n","# • Robust version detection: tries chromium-browser → falls back to chromedriver --version\n","# • This fixes \"Command returned non-zero exit status 1\" and \"cannot connect to chrome\"\n","# • Matches exactly what Colab expects in 2026 for undetected-chromedriver\n","# • Kept clean options + full stealth + lazy-load scrolling\n","\n","!apt-get update -qq\n","!apt-get install -y chromium-browser chromium-chromedriver \\\n"," libnss3 libgconf-2-4 libxss1 libasound2 libxtst6 libx11-xcb1 \\\n"," fonts-liberation libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libdbus-1-3 \\\n"," libexpat1 libfontconfig1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 \\\n"," libpangocairo-1.0-0 libstdc++6 libx11-6 libxcb1 libxcomposite1 libxcursor1 \\\n"," libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxtst6 \\\n"," xdg-utils -qq > /dev/null\n","\n","!pip install beautifulsoup4 lxml selenium undetected-chromedriver --upgrade -q\n","\n","import requests\n","from bs4 import BeautifulSoup\n","from IPython.display import display, Image\n","import time\n","import os\n","import zipfile\n","import re\n","import io\n","import subprocess\n","from google.colab import drive\n","\n","# Selenium imports\n","import undetected_chromedriver as uc\n","from selenium.webdriver.support.ui import WebDriverWait\n","from selenium.webdriver.support import expected_conditions as EC\n","from selenium.webdriver.common.by import By\n","\n","# =============================================================================\n","# Colab form parameters\n","# =============================================================================\n","\n","N = 100 #@param {type:\"slider\", min:1, max:200, step:1, label:\"Number of thumbnails (N)\"}\n","offset = 0 #@param {type:\"slider\", min:0, max:1000, step:10, label:\"Offset (skip first X items)\"}\n","sleep_time = 0.5 #@param {type:\"slider\", min:0, max:2, step:0.1, label:\"Sleep time between pages (seconds)\"}\n","debug = True #@param {type:\"boolean\", label:\"Debug mode (prints useful info)\"}\n","\n","# Sort-by dropdown\n","sort_by = \"Trending\" #@param [\"New\", \"Top\", \"Popular\", \"Trending\"] {type:\"string\", label:\"Sort by\"}\n","\n","# Save options\n","save_to_drive = True #@param {type:\"boolean\", label:\"✅ Save ZIP + titles to Google Drive\"}\n","\n","# =============================================================================\n","# Main script\n","# =============================================================================\n","\n","sort_paths = {\n"," \"New\": \"\",\n"," \"Top\": \"top/\",\n"," \"Popular\": \"popular/\",\n"," \"Trending\": \"trending/\",\n","}\n","\n","base_url = f\"https://www.girlsreleased.com/{sort_paths[sort_by]}\".rstrip(\"/\") + \"/\"\n","\n","if debug:\n"," print(\"=== DEBUG: Configuration ===\")\n"," print(f\"Sort by (category): {sort_by}\")\n"," print(f\"Base URL: {base_url}\")\n"," print(f\"N = {N}, Offset = {offset}, Sleep = {sleep_time}s\")\n"," print(f\"Save to Drive: {save_to_drive}\")\n"," print(\"============================\\n\")\n","\n","print(\"🚀 Setting up undetected-chromedriver (chromium-chromedriver + robust version detection)...\\n\")\n","\n","# =============================================================================\n","# CRITICAL FIX: Install + detect version using both binaries\n","# =============================================================================\n","chrome_bin = \"/usr/bin/chromium-browser\"\n","chromedriver_bin = \"/usr/bin/chromedriver\"\n","version_main = None\n","\n","print(\"Detecting Chromium version...\")\n","\n","# Try browser first\n","try:\n"," version_output = subprocess.check_output(\n"," [chrome_bin, \"--version\"], stderr=subprocess.STDOUT\n"," ).decode(\"utf-8\").strip()\n"," print(f\"✅ Detected via browser: {version_output}\")\n"," version_main = int(version_output.split()[1].split(\".\")[0])\n","except Exception:\n"," print(\"⚠️ Browser --version failed → trying chromedriver (more reliable in Colab)\")\n","\n","# Fallback to chromedriver (this almost always works after installing chromium-chromedriver)\n","try:\n"," version_output = subprocess.check_output(\n"," [chromedriver_bin, \"--version\"], stderr=subprocess.STDOUT\n"," ).decode(\"utf-8\").strip()\n"," print(f\"✅ Detected via chromedriver: {version_output}\")\n"," version_main = int(version_output.split()[1].split(\".\")[0])\n","except Exception as e:\n"," print(f\"⚠️ Could not detect version: {e}\")\n"," version_main = None # uc will auto-detect if possible\n","\n","if version_main:\n"," print(f\" → Using version_main={version_main} for perfect driver match\")\n","\n","options = uc.ChromeOptions()\n","options.add_argument(\"--headless=new\")\n","options.add_argument(\"--no-sandbox\")\n","options.add_argument(\"--disable-dev-shm-usage\")\n","options.add_argument(\"--disable-gpu\")\n","options.add_argument(\"--window-size=1920,1080\")\n","options.add_argument(\"--disable-setuid-sandbox\")\n","options.add_argument(\"--remote-debugging-port=9222\")\n","options.add_argument(\"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\")\n","\n","# =============================================================================\n","# Create driver with explicit binary + version (this fixes the connection error)\n","# =============================================================================\n","driver = uc.Chrome(\n"," options=options,\n"," browser_executable_path=chrome_bin,\n"," version_main=version_main,\n",")\n","\n","print(\"✅ undetected-chromedriver ready (Cloudflare bypass + version-matched)\\n\")\n","\n","collected_items = []\n","page = 1\n","max_pages = 30\n","\n","print(f\"Fetching thumbnails sorted by '{sort_by}' (skipping first {offset}, taking next {N})...\\n\")\n","\n","headers = {\n"," \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n"," \"(KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\",\n","}\n","\n","while len(collected_items) < offset + N and page <= max_pages:\n"," if page == 1:\n"," url = base_url\n"," else:\n"," url = base_url.rstrip(\"/\") + f\"/page/{page}/\"\n","\n"," if debug:\n"," print(f\"Fetching page {page}: {url}\")\n","\n"," try:\n"," driver.get(url)\n","\n"," # Extra long wait for Cloudflare + page render\n"," WebDriverWait(driver, 40).until(\n"," EC.presence_of_element_located((By.TAG_NAME, \"img\"))\n"," )\n","\n"," # Force lazy-loading and any JS challenges\n"," time.sleep(3)\n"," driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n"," time.sleep(2)\n"," driver.execute_script(\"window.scrollTo(0, 0);\")\n"," time.sleep(1.5)\n","\n"," html = driver.page_source\n"," soup = BeautifulSoup(html, \"html.parser\")\n","\n"," page_items = []\n"," seen_srcs = set()\n","\n"," # === 1. Extract from tags ===\n"," for img in soup.find_all(\"img\"):\n"," src = (img.get(\"data-src\") or img.get(\"data-lazy-src\") or\n"," img.get(\"data-original\") or img.get(\"src\") or \"\").strip()\n"," if not src:\n"," continue\n"," lower_src = src.lower()\n"," if not any(lower_src.endswith(ext) for ext in [\".jpg\", \".jpeg\", \".png\", \".webp\"]):\n"," continue\n"," if any(word in lower_src for word in [\"logo\", \"icon\", \"banner\", \"avatar\", \"button\", \"header\", \"footer\"]):\n"," continue\n","\n"," title = img.get(\"alt\", \"\").strip() or img.get(\"title\", \"\").strip()\n"," if not title:\n"," a_tag = img.find_parent(\"a\")\n"," if a_tag:\n"," title = a_tag.get(\"title\", \"\").strip()\n"," if not title:\n"," for tag_name in [\"h1\",\"h2\",\"h3\",\"h4\",\"span\",\"div\"]:\n"," h = a_tag.find(tag_name, class_=lambda x: x and (\"title\" in str(x).lower() or \"caption\" in str(x).lower()))\n"," if h:\n"," title = h.get_text(strip=True)\n"," break\n"," if not title:\n"," title = f\"Untitled_{len(collected_items) + len(page_items) + 1}\"\n","\n"," if not src.startswith((\"http://\", \"https://\")):\n"," src = \"https://www.girlsreleased.com\" + (src if src.startswith(\"/\") else \"/\" + src)\n","\n"," if src not in seen_srcs:\n"," seen_srcs.add(src)\n"," page_items.append((src, title))\n","\n"," # === 2. Extract from CSS background-image ===\n"," for element in soup.find_all([\"div\", \"a\", \"article\", \"span\"], style=True):\n"," style = element.get(\"style\", \"\")\n"," if \"background-image\" not in style.lower():\n"," continue\n"," match = re.search(r'url\\([\\'\"]?([^\\'\")]+)[\\'\"]?\\)', style)\n"," if not match:\n"," continue\n"," src = match.group(1).strip()\n"," lower_src = src.lower()\n"," if not any(lower_src.endswith(ext) for ext in [\".jpg\", \".jpeg\", \".png\", \".webp\"]):\n"," continue\n"," if any(word in lower_src for word in [\"logo\", \"icon\", \"banner\", \"avatar\", \"button\", \"header\", \"footer\"]):\n"," continue\n","\n"," title = element.get(\"alt\", \"\").strip() or element.get(\"title\", \"\").strip()\n"," if not title:\n"," a_tag = element.find_parent(\"a\") or element\n"," title = a_tag.get(\"title\", \"\").strip()\n"," if not title:\n"," for tag_name in [\"h1\",\"h2\",\"h3\",\"h4\",\"span\",\"div\"]:\n"," h = a_tag.find(tag_name, class_=lambda x: x and (\"title\" in str(x).lower() or \"caption\" in str(x).lower()))\n"," if h:\n"," title = h.get_text(strip=True)\n"," break\n"," if not title:\n"," title = f\"Untitled_{len(collected_items) + len(page_items) + 1}\"\n","\n"," if not src.startswith((\"http://\", \"https://\")):\n"," src = \"https://www.girlsreleased.com\" + (src if src.startswith(\"/\") else \"/\" + src)\n","\n"," if src not in seen_srcs:\n"," seen_srcs.add(src)\n"," page_items.append((src, title))\n","\n"," if debug:\n"," total_imgs = len(soup.find_all(\"img\"))\n"," bg_count = len([e for e in soup.find_all([\"div\",\"a\",\"article\",\"span\"], style=True)\n"," if \"background-image\" in e.get(\"style\",\"\").lower()])\n"," print(f\" → Total tags AFTER JS: {total_imgs} | Backgrounds: {bg_count}\")\n"," print(f\" → Found {len(page_items)} thumbnails on page {page}\")\n","\n"," collected_items.extend(page_items)\n","\n"," except Exception as e:\n"," if debug:\n"," print(f\" → Error on page {page}: {type(e).__name__} - {e}\")\n"," break\n","\n"," page += 1\n"," time.sleep(sleep_time)\n","\n","driver.quit()\n","\n","selected_items = collected_items[offset:offset + N]\n","\n","if debug:\n"," print(\"\\n=== DEBUG: Final Summary ===\")\n"," print(f\"Total collected: {len(collected_items)} | Selected: {len(selected_items)}\")\n"," print(\"===========================\\n\")\n","\n","# =============================================================================\n","# SAVE TO GOOGLE DRIVE (Direct ZIP + Custom filenames - NO images folder)\n","# =============================================================================\n","if save_to_drive and selected_items:\n"," print(\"Mounting Google Drive...\")\n"," drive.mount('/content/drive', force_remount=False)\n","\n"," drive_folder = \"/content/drive/MyDrive/girlsreleased\"\n"," os.makedirs(drive_folder, exist_ok=True)\n"," print(f\"✅ Drive folder ready: {drive_folder}\")\n","\n"," # Custom filenames with category, N, offset\n"," category = sort_by\n"," zip_filename = f\"girlsreleased_{category}_N{N}_offset{offset}.zip\"\n"," titles_filename = f\"girlsreleased_{category}_N{N}_offset{offset}_titles.txt\"\n","\n"," # === 1. Save titles ===\n"," titles_list = [title for _, title in selected_items]\n"," titles_str = \"|\".join(titles_list)\n"," titles_path = os.path.join(drive_folder, titles_filename)\n"," with open(titles_path, \"w\", encoding=\"utf-8\") as f:\n"," f.write(titles_str)\n"," print(f\"✅ Titles saved → {titles_filename} ({len(titles_list)} titles)\")\n","\n"," # === 2. Create ZIP directly in memory (no images folder at all) ===\n"," print(f\"Downloading {len(selected_items)} images directly into ZIP → {zip_filename}\")\n"," zip_buffer = io.BytesIO()\n"," downloaded_count = 0\n","\n"," with zipfile.ZipFile(zip_buffer, \"w\", zipfile.ZIP_DEFLATED) as z:\n"," for i, (url, title) in enumerate(selected_items, 1):\n"," try:\n"," r = requests.get(url, headers=headers, stream=True, timeout=15)\n"," r.raise_for_status()\n","\n"," ext = url.split(\".\")[-1].split(\"?\")[0].lower()\n"," ext = ext if ext in [\"jpg\", \"jpeg\", \"png\", \"webp\"] else \"jpg\"\n"," filename_in_zip = f\"{i:03d}.{ext}\"\n","\n"," z.writestr(filename_in_zip, r.content)\n"," downloaded_count += 1\n"," if debug:\n"," print(f\" Added {filename_in_zip}\")\n"," except Exception as e:\n"," if debug:\n"," print(f\" Failed {i}: {e}\")\n"," continue\n","\n"," # Write buffer to Drive\n"," zip_path = os.path.join(drive_folder, zip_filename)\n"," with open(zip_path, \"wb\") as f:\n"," f.write(zip_buffer.getvalue())\n","\n"," print(f\"✅ ZIP created → {zip_filename} ({downloaded_count} images)\")\n","\n","# =============================================================================\n","# Display results\n","# =============================================================================\n","print(f\"\\n✅ Fetched {len(selected_items)} thumbnail(s) sorted by '{sort_by}'\")\n","if save_to_drive:\n"," print(f\" Saved to Google Drive: {drive_folder}\")\n","\n","if not selected_items:\n"," print(\"No thumbnails found.\")\n","else:\n"," for i, (thumb_url, title) in enumerate(selected_items, 1):\n"," print(f\"{i:2d}. {title}\")\n"," print(f\" {thumb_url}\")\n"," display(Image(url=thumb_url, width=280, height=280))\n"," print(\"─\" * 90)\n","\n","print(\"\\nAll done! v5.6 — Fixed with chromium-chromedriver + robust version detection\")\n","print(\"Just change the form values (sort_by, N, offset) and re-run — filenames will update automatically.\")"],"metadata":{"id":"uS9gO9DG4aeR"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"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","qisU9VeIyzX2","0VlyEacYp7Pn","JrtsI98cmAxB","s40baE0G_wn7","OHPBxduU0aMa","02aZcv2lB_hC","U27drDtMB53n"]},"kernelspec":{"display_name":"Python 3","name":"python3"}},"nbformat":4,"nbformat_minor":0}
\ No newline at end of file