Datasets:
Tags:
Not-For-All-Audiences
File size: 6,254 Bytes
061045d | 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyPvdDhUx76REln6krNGGNge"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"5r2jY7HTIaGk"},"outputs":[],"source":["# Cell 1: Mount Google Drive\n","from google.colab import drive\n","drive.mount('/content/drive')"]},{"cell_type":"code","source":["# Cell 2: Input Parameters (run this cell to show the text fields)\n","zip_path1 = '/content/drive/MyDrive/dataset1.zip' #@param {type:\"string\"}\n","zip_path2 = '/content/drive/MyDrive/poggers.zip' #@param {type:\"string\"}\n","zip_path3 = '' #@param {type:\"string\"}\n","output_zip_name = 'fetch_set.zip' #@param {type:\"string\"}"],"metadata":{"id":"lglLOquaJ-vQ","executionInfo":{"status":"ok","timestamp":1774965149730,"user_tz":-120,"elapsed":3,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":2,"outputs":[]},{"cell_type":"code","source":["# Cell 3: Imports and Setup\n","import os\n","import zipfile\n","import shutil\n","from PIL import Image\n","from pathlib import Path\n","\n","# Directories\n","temp_dir = Path('/content/temp_extracted')\n","output_dir = Path('/content/processed_pairs')\n","\n","# Clean any previous run\n","if temp_dir.exists():\n"," shutil.rmtree(temp_dir)\n","if output_dir.exists():\n"," shutil.rmtree(output_dir)\n","\n","temp_dir.mkdir(parents=True, exist_ok=True)\n","output_dir.mkdir(parents=True, exist_ok=True)\n","\n","print(\"β
Directories ready.\")"],"metadata":{"id":"pnPdQZayKBZx"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Cell 4: Unpack Zip Files (or skip if empty)\n","zip_paths = [zip_path1, zip_path2, zip_path3]\n","\n","for i, zip_p in enumerate(zip_paths, 1):\n"," if str(zip_p).strip():\n"," zip_path = Path(zip_p)\n"," if zip_path.exists() and zip_path.suffix.lower() == '.zip':\n"," sub_dir = temp_dir / f'zip_{i}'\n"," sub_dir.mkdir(exist_ok=True)\n"," with zipfile.ZipFile(zip_path, 'r') as zf:\n"," zf.extractall(sub_dir)\n"," print(f\"β
Unpacked {zip_path.name} β {sub_dir}\")\n"," else:\n"," print(f\"β οΈ Skipped (invalid/missing): {zip_p}\")\n"," else:\n"," print(f\"βοΈ Skipped empty path #{i}\")"],"metadata":{"id":"OynyRcBkKGvV"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Cell 5: Process Images (resize/pad + pairing) and Number Them\n","def process_image(img_path: Path, output_path: Path):\n"," \"\"\"Make shortest side exactly 1024 px:\n"," - If < 1024 px β pad with #181818 gray (no upscaling)\n"," - If >= 1024 px β resize down proportionally\"\"\"\n"," img = Image.open(img_path).convert('RGB')\n"," w, h = img.size\n"," short_side = min(w, h)\n"," gray = (24, 24, 24) # #181818\n","\n"," if short_side < 1024:\n"," # PAD (center original image on new canvas)\n"," new_w = max(w, 1024)\n"," new_h = max(h, 1024)\n"," canvas = Image.new('RGB', (new_w, new_h), gray)\n"," paste_x = (new_w - w) // 2\n"," paste_y = (new_h - h) // 2\n"," canvas.paste(img, (paste_x, paste_y))\n"," canvas.save(output_path, 'JPEG', quality=95)\n"," else:\n"," # RESIZE proportionally (shortest side becomes exactly 1024)\n"," scale = 1024 / short_side\n"," new_w = int(round(w * scale))\n"," new_h = int(round(h * scale))\n"," resized = img.resize((new_w, new_h), Image.LANCZOS)\n"," resized.save(output_path, 'JPEG', quality=95)\n","\n","# Supported image formats\n","image_exts = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff'}\n","\n","counter = 1\n","\n","for i in range(1, 4):\n"," sub_dir = temp_dir / f'zip_{i}'\n"," if sub_dir.exists():\n"," # Get all images in this zip (including subfolders)\n"," image_files = [p for p in sub_dir.rglob('*')\n"," if p.is_file() and p.suffix.lower() in image_exts]\n"," image_files.sort(key=lambda p: p.name.lower())\n","\n"," # Get all .txt files for pairing\n"," txt_files = [p for p in sub_dir.rglob('*')\n"," if p.is_file() and p.suffix.lower() == '.txt']\n","\n"," for img_path in image_files:\n"," stem = img_path.stem\n","\n"," # Match txt by stem (case-insensitive for robustness)\n"," matching_txts = [t for t in txt_files if t.stem.lower() == stem.lower()]\n"," is_pair = bool(matching_txts)\n"," txt_path = matching_txts[0] if matching_txts else None\n","\n"," num_str = f\"{counter:04d}\" # 0001, 0002... (sorts correctly)\n"," jpg_out = output_dir / f\"{num_str}.jpg\"\n","\n"," # Process & save image\n"," process_image(img_path, jpg_out)\n","\n"," if is_pair:\n"," txt_out = output_dir / f\"{num_str}.txt\"\n"," shutil.copy2(txt_path, txt_out)\n"," print(f\"β
Pair {num_str} β {img_path.name} + {txt_path.name}\")\n"," else:\n"," print(f\"β
Single image {num_str} β {img_path.name} (no txt)\")\n","\n"," counter += 1\n","\n","print(f\"\\nπ Processing finished β {counter-1} file(s) created in {output_dir}\")"],"metadata":{"id":"Lx3neitOKIkM"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Cell 6: Create final ZIP and save to Google Drive\n","final_zip = Path(f'/content/{output_zip_name}')\n","\n","with zipfile.ZipFile(final_zip, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for file in output_dir.iterdir():\n"," if file.is_file():\n"," zf.write(file, arcname=file.name) # flat zip\n","\n","print(f\"π¦ Final zip created: {final_zip}\")\n","\n","# Copy to Drive\n","drive_dest = Path(f'/content/drive/MyDrive/{output_zip_name}')\n","shutil.copy2(final_zip, drive_dest)\n","\n","print(f\"πΎ Saved to Google Drive β {drive_dest}\")\n","print(\"\\nβ
ALL DONE! Your numbered image/txt pairs are ready in the zip on Drive.\")"],"metadata":{"id":"1Ar0Le5dKQjJ"},"execution_count":null,"outputs":[]}]} |