Datasets:
Tags:
Not-For-All-Audiences
Upload trim_dataset_duplicates.ipynb
Browse files
trim_dataset_duplicates.ipynb
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"gpuType":"T4","mount_file_id":"1qLYFQ4JFbsA9dvr5Zn068JGB9HVZjDEa","authorship_tag":"ABX9TyOByX/+abwHOtQ0+kZ19Wwj"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"code","source":["# Step 1: Mount Google Drive\n","from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"AEA3l5bSLSo1"},"execution_count":null,"outputs":[]},{"cell_type":"code","metadata":{"id":"69c32694"},"source":["from google.colab import userdata\n","from huggingface_hub import login\n","\n","# Retrieve HF_TOKEN from Colab secrets\n","HF_TOKEN = userdata.get('HF_TOKEN')\n","\n","if HF_TOKEN:\n"," login(token=HF_TOKEN)\n"," print(\"Successfully logged into Hugging Face.\")\n","else:\n"," print(\"HF_TOKEN not found in Colab secrets. Please add it to proceed with gated models.\")"],"execution_count":null,"outputs":[]},{"cell_type":"code","execution_count":null,"metadata":{"cellView":"form","id":"zpNn5C3fjXC_"},"outputs":[],"source":["#@title Zip Upload + CLIP Clustering with Enumeration\n","import os\n","import zipfile\n","import shutil\n","import numpy as np\n","import torch\n","from PIL import Image\n","import matplotlib.pyplot as plt\n","from sklearn.cluster import KMeans\n","from sklearn.metrics import silhouette_score, pairwise_distances\n","import warnings\n","warnings.filterwarnings('ignore')\n","\n","# ========================== CONFIG ==========================\n","#@markdown ### 1. Zip File Path\n","zip_path = '/content/drive/MyDrive/Saved from Chrome/2994538_training_data.zip' #@param {type:\"string\"}\n","\n","#@markdown ### 2. Number of Clusters\n","n_clusters = 50 #@param {type:\"slider\", min:5, max:200, step:1}\n","\n","#@markdown ### 3. Output Settings\n","output_base = '/content/clustered_images' #@param {type:\"string\"}\n","move_files = False #@param {type:\"boolean\"}\n","output_format = \"JPEG\" #@param [\"JPEG\", \"PNG\", \"WEBP\"]\n","quality = 95 #@param {type:\"slider\", min:50, max:100, step:1}\n","\n","# Force GPU (T4)\n","device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n","print(f\"Using device: {device}\")\n","# ========================================================\n","\n","# --------------------- Unzip ---------------------\n","print(\"Unzipping...\")\n","os.makedirs('/content/data', exist_ok=True)\n","with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall('/content/data')\n","\n","# --------------------- Find Image-Text Pairs ---------------------\n","image_dir = '/content/data'\n","pairs = {}\n","image_extensions = ('.png', '.jpg', '.jpeg', '.webp', '.bmp')\n","\n","for root, _, files in os.walk(image_dir):\n"," for f in files:\n"," if f.lower().endswith(image_extensions):\n"," base = os.path.splitext(f)[0]\n"," txt_path = os.path.join(root, base + '.txt')\n"," if os.path.exists(txt_path):\n"," pairs[base] = {\n"," 'image': os.path.join(root, f),\n"," 'text': txt_path\n"," }\n","\n","print(f\"Found {len(pairs)} image-text pairs.\")\n","\n","# --------------------- Enumerate Pairs ---------------------\n","enumerated_pairs = []\n","for idx, (base, paths) in enumerate(pairs.items(), 1):\n"," enumerated_pairs.append({\n"," 'number': idx,\n"," 'base': base,\n"," 'image_path': paths['image'],\n"," 'text_path': paths['text']\n"," })\n","\n","print(\"\\nFirst 5 enumerated pairs:\")\n","for p in enumerated_pairs[:5]:\n"," print(f\"{p['number']}: {p['base']}\")\n","\n","# --------------------- CLIP Setup ---------------------\n","!pip install -q open_clip_torch ftfy regex tqdm\n","\n","import open_clip\n","\n","model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion400m_e32')\n","model = model.to(device)\n","model.eval()\n","\n","print(\"CLIP model loaded on\", device)\n","\n","# --------------------- Extract Embeddings ---------------------\n","embeddings = []\n","image_paths = [] # full paths\n","image_numbers = [] # 1-based enumeration\n","bases = []\n","\n","print(\"Encoding images with CLIP...\")\n","\n","for pair in enumerated_pairs:\n"," try:\n"," img = Image.open(pair['image_path']).convert('RGB')\n"," img_tensor = preprocess(img).unsqueeze(0).to(device)\n","\n"," with torch.no_grad():\n"," emb = model.encode_image(img_tensor)\n"," emb = emb.cpu().numpy().flatten()\n","\n"," embeddings.append(emb)\n"," image_paths.append(pair['image_path'])\n"," image_numbers.append(pair['number'])\n"," bases.append(pair['base'])\n","\n"," except Exception as e:\n"," print(f\"Error processing {pair['base']}: {e}\")\n","\n","embeddings = np.array(embeddings)\n","print(f\"Extracted {len(embeddings)} embeddings of shape {embeddings.shape}\")"]},{"cell_type":"markdown","source":["# Inference"],"metadata":{"id":"o30zirstlCXr"}},{"cell_type":"code","source":["#@title Perform Clustering + Create Folders with Similarity Info\n","# KMeans\n","kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)\n","cluster_labels = kmeans.fit_predict(embeddings)\n","\n","# Silhouette\n","sil_score = silhouette_score(embeddings, cluster_labels)\n","print(f\"Silhouette Score: {sil_score:.4f}\")\n","\n","# --------------------- Per-Cluster Similarity Stats ---------------------\n","cluster_info = {}\n","\n","for c in range(n_clusters):\n"," idxs = np.where(cluster_labels == c)[0]\n"," if len(idxs) < 2:\n"," cluster_info[c] = {\"max_sim\": 100.0, \"min_sim\": 100.0, \"size\": len(idxs)}\n"," continue\n","\n"," cluster_embs = embeddings[idxs]\n"," # Compute cosine similarity matrix\n"," norms = np.linalg.norm(cluster_embs, axis=1, keepdims=True)\n"," sim_matrix = (cluster_embs @ cluster_embs.T) / (norms * norms.T)\n"," np.fill_diagonal(sim_matrix, 0) # ignore self-similarity\n","\n"," max_sim = float(sim_matrix.max() * 100)\n"," min_sim = float(sim_matrix.min() * 100)\n","\n"," cluster_info[c] = {\n"," \"max_sim\": round(max_sim, 2),\n"," \"min_sim\": round(min_sim, 2),\n"," \"size\": len(idxs)\n"," }\n","\n","# --------------------- Create Cluster Folders ---------------------\n","os.makedirs(output_base, exist_ok=True)\n","\n","for c in range(n_clusters):\n"," info = cluster_info[c]\n"," folder_name = f\"cluster_{c:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n"," os.makedirs(os.path.join(output_base, folder_name), exist_ok=True)\n","\n","print(f\"Created {n_clusters} cluster folders with similarity ranges.\")\n","\n","# --------------------- Copy/Move Files ---------------------\n","for idx, label in enumerate(cluster_labels):\n"," src_img = image_paths[idx]\n"," base_name = bases[idx]\n"," num = image_numbers[idx]\n","\n"," info = cluster_info[label]\n"," folder_name = f\"cluster_{label:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n"," dst_dir = os.path.join(output_base, folder_name)\n","\n"," # Image\n"," ext = f\".{output_format.lower()}\"\n"," dst_img = os.path.join(dst_dir, f\"{num:04d}_{base_name}{ext}\")\n","\n"," with Image.open(src_img).convert('RGB') as img:\n"," if output_format == \"JPEG\":\n"," img.save(dst_img, \"JPEG\", quality=quality, optimize=True)\n"," elif output_format == \"PNG\":\n"," comp = int(9 * (100 - quality) / 100)\n"," img.save(dst_img, \"PNG\", compress_level=comp)\n"," else: # WEBP\n"," img.save(dst_img, \"WEBP\", quality=quality)\n","\n"," # Text file\n"," src_txt = enumerated_pairs[idx]['text_path'] # using original index\n"," dst_txt = os.path.join(dst_dir, f\"{num:04d}_{base_name}.txt\")\n"," shutil.copy(src_txt, dst_txt)\n","\n"," if move_files and os.path.exists(src_img):\n"," os.remove(src_img)\n","\n","print(f\"\\n✅ Done! Images + text files sorted into: {output_base}\")"],"metadata":{"id":"VsrSI_Nbls1Y"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Optional: Preview First Few Clusters\n","def show_cluster_samples(cluster_idx, n=4):\n"," info = cluster_info[cluster_idx]\n"," folder_name = f\"cluster_{cluster_idx:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n"," cluster_dir = os.path.join(output_base, folder_name)\n","\n"," images = [f for f in os.listdir(cluster_dir) if f.lower().endswith(('.jpg','.jpeg','.png','.webp'))][:n]\n","\n"," if not images:\n"," print(\"No images found\")\n"," return\n","\n"," fig, axs = plt.subplots(1, len(images), figsize=(4*len(images), 4))\n"," if len(images) == 1: axs = [axs]\n","\n"," for ax, fname in zip(axs, images):\n"," img = Image.open(os.path.join(cluster_dir, fname))\n"," ax.imshow(img)\n"," ax.set_title(fname[:20] + '...' if len(fname)>20 else fname)\n"," ax.axis('off')\n"," plt.suptitle(f\"Cluster {cluster_idx} | Similarity: {info['max_sim']}% – {info['min_sim']}%\")\n"," plt.show()\n","\n","# Show first 5 clusters\n","for c in range(min(5, n_clusters)):\n"," show_cluster_samples(c)"],"metadata":{"id":"M8bj_J5NlvZ0"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Perform Clustering + Deduplication + Folder Creation\n","\n","import numpy as np\n","from sklearn.cluster import KMeans\n","from sklearn.metrics import silhouette_score\n","import shutil\n","\n","# --------------------- Clustering ---------------------\n","kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)\n","cluster_labels = kmeans.fit_predict(embeddings)\n","\n","sil_score = silhouette_score(embeddings, cluster_labels)\n","print(f\"Silhouette Score: {sil_score:.4f}\")\n","\n","# --------------------- Deduplication Settings ---------------------\n","#@markdown ### Deduplication Settings\n","dedup_threshold = 0.9 #@param {type:\"slider\", min:0.85, max:0.995, step:0.005}\n","dedup_enabled = True #@param {type:\"boolean\"}\n","\n","print(f\"Deduplication enabled: {dedup_enabled} | Threshold: {dedup_threshold}\")\n","\n","# --------------------- Per-Cluster Deduplication ---------------------\n","to_keep = set() # indices in the embeddings list that we will keep\n","\n","for c in range(n_clusters):\n"," idxs = np.where(cluster_labels == c)[0]\n"," if len(idxs) == 0:\n"," continue\n","\n"," cluster_embs = embeddings[idxs]\n","\n"," # Compute cosine similarity matrix\n"," norms = np.linalg.norm(cluster_embs, axis=1, keepdims=True)\n"," sim_matrix = (cluster_embs @ cluster_embs.T) / (norms * norms.T)\n"," np.fill_diagonal(sim_matrix, 0)\n","\n"," # Find duplicates\n"," keep_in_cluster = []\n"," processed = set()\n","\n"," for i in range(len(idxs)):\n"," if i in processed:\n"," continue\n"," keep_in_cluster.append(idxs[i])\n"," processed.add(i)\n","\n"," # Find all very similar images\n"," similar = np.where(sim_matrix[i] > dedup_threshold)[0]\n"," for j in similar:\n"," if j not in processed:\n"," processed.add(j)\n","\n"," to_keep.update(keep_in_cluster)\n","\n","to_keep = sorted(list(to_keep))\n","print(f\"After deduplication: Keeping {len(to_keep)} / {len(embeddings)} images\")\n","\n","# --------------------- Per-Cluster Similarity Stats (on kept images) ---------------------\n","cluster_info = {}\n","kept_labels = cluster_labels[np.array(to_keep)]\n","kept_embeddings = embeddings[np.array(to_keep)]\n","\n","for c in range(n_clusters):\n"," idxs = np.where(kept_labels == c)[0]\n"," if len(idxs) == 0:\n"," cluster_info[c] = {\"max_sim\": 0.0, \"min_sim\": 0.0, \"size\": 0}\n"," continue\n"," if len(idxs) == 1:\n"," cluster_info[c] = {\"max_sim\": 100.0, \"min_sim\": 100.0, \"size\": 1}\n"," continue\n","\n"," cluster_embs = kept_embeddings[idxs]\n"," norms = np.linalg.norm(cluster_embs, axis=1, keepdims=True)\n"," sim_matrix = (cluster_embs @ cluster_embs.T) / (norms * norms.T)\n"," np.fill_diagonal(sim_matrix, 0)\n","\n"," max_sim = float(sim_matrix.max() * 100)\n"," min_sim = float(sim_matrix.min() * 100)\n","\n"," cluster_info[c] = {\n"," \"max_sim\": round(max_sim, 2),\n"," \"min_sim\": round(min_sim, 2),\n"," \"size\": len(idxs)\n"," }\n","\n","# --------------------- Create Cluster Folders ---------------------\n","os.makedirs(output_base, exist_ok=True)\n","\n","for c in range(n_clusters):\n"," info = cluster_info[c]\n"," if info[\"size\"] == 0:\n"," continue\n"," folder_name = f\"cluster_{c:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n"," os.makedirs(os.path.join(output_base, folder_name), exist_ok=True)\n","\n","print(f\"Created {len([c for c in cluster_info if cluster_info[c]['size'] > 0])} non-empty cluster folders.\")\n","\n","# --------------------- Copy/Move Files (Only Kept Images) ---------------------\n","kept_set = set(to_keep)\n","\n","for orig_idx in to_keep:\n"," label = cluster_labels[orig_idx]\n"," info = cluster_info[label]\n"," if info[\"size\"] == 0:\n"," continue\n","\n"," folder_name = f\"cluster_{label:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n"," dst_dir = os.path.join(output_base, folder_name)\n","\n"," src_img = image_paths[orig_idx]\n"," base_name = bases[orig_idx]\n"," num = image_numbers[orig_idx]\n","\n"," # Image\n"," ext = f\".{output_format.lower()}\"\n"," dst_img = os.path.join(dst_dir, f\"{num:04d}_{base_name}{ext}\")\n","\n"," with Image.open(src_img).convert('RGB') as img:\n"," if output_format == \"JPEG\":\n"," img.save(dst_img, \"JPEG\", quality=quality, optimize=True)\n"," elif output_format == \"PNG\":\n"," comp = int(9 * (100 - quality) / 100)\n"," img.save(dst_img, \"PNG\", compress_level=comp)\n"," else:\n"," img.save(dst_img, \"WEBP\", quality=quality)\n","\n"," # Text file\n"," src_txt = enumerated_pairs[orig_idx]['text_path']\n"," dst_txt = os.path.join(dst_dir, f\"{num:04d}_{base_name}.txt\")\n"," shutil.copy(src_txt, dst_txt)\n","\n"," if move_files and os.path.exists(src_img):\n"," os.remove(src_img)\n","\n","print(f\"\\n✅ Deduplication + Sorting completed!\")\n","print(f\"Final images kept: {len(to_keep)}\")"],"metadata":{"id":"GLHA5t8LlZM6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Full Dataset Visualization + Cluster Map (2D Projection)\n","\n","import numpy as np\n","import matplotlib.pyplot as plt\n","from umap import UMAP\n","from sklearn.manifold import TSNE\n","import math\n","from PIL import Image\n","\n","#@markdown ### Visualization Settings\n","use_umap = True #@param {type:\"boolean\"}\n","n_samples_per_cluster = 6 #@param {type:\"slider\", min:1, max:12, step:1}\n","max_clusters_to_show = 50 #@param {type:\"slider\", min:5, max:100, step:5}\n","\n","print(\"Generating full dataset visualizations...\")\n","\n","# Use only kept images after deduplication\n","kept_idx = np.array(to_keep)\n","kept_embeddings = embeddings[kept_idx]\n","kept_labels = cluster_labels[kept_idx]\n","kept_image_paths = [image_paths[i] for i in kept_idx]\n","kept_numbers = [image_numbers[i] for i in kept_idx]\n","kept_bases = [bases[i] for i in kept_idx]\n","\n","# ====================== 1. 2D Cluster Map ======================\n","print(\"Creating 2D projection...\")\n","\n","if use_umap:\n"," reducer = UMAP(n_components=2, random_state=42, n_neighbors=15, min_dist=0.1)\n"," projection = reducer.fit_transform(kept_embeddings)\n"," method_name = \"UMAP\"\n","else:\n"," reducer = TSNE(n_components=2, random_state=42, perplexity=min(30, len(kept_embeddings)-1))\n"," projection = reducer.fit_transform(kept_embeddings)\n"," method_name = \"t-SNE\"\n","\n","plt.figure(figsize=(14, 10))\n","scatter = plt.scatter(projection[:, 0], projection[:, 1],\n"," c=kept_labels, cmap='tab20', s=40, alpha=0.8)\n","\n","plt.colorbar(scatter, label='Cluster ID')\n","plt.title(f'{method_name} Projection of CLIP Image Embeddings\\nColored by K-Means Clusters', fontsize=16)\n","plt.xlabel(f'{method_name} 1')\n","plt.ylabel(f'{method_name} 2')\n","plt.grid(True, alpha=0.3)\n","\n","# Add cluster centers annotation (optional)\n","centers = []\n","for c in range(n_clusters):\n"," mask = kept_labels == c\n"," if np.sum(mask) > 0:\n"," center = projection[mask].mean(axis=0)\n"," centers.append((center, c))\n","\n","for center, c in centers[:30]: # limit annotations\n"," plt.annotate(str(c), center, xytext=(3,3), textcoords='offset points',\n"," fontsize=9, bbox=dict(boxstyle=\"round,pad=0.3\", fc=\"white\", alpha=0.7))\n","\n","plt.tight_layout()\n","plt.show()\n","\n","# ====================== 2. Grid of Images per Cluster ======================\n","print(f\"\\nDisplaying up to {max_clusters_to_show} clusters with sample images...\")\n","\n","num_cols = 4\n","num_rows = math.ceil(min(max_clusters_to_show, n_clusters) / num_cols)\n","\n","fig = plt.figure(figsize=(20, 5 * num_rows))\n","\n","plot_idx = 0\n","for c in range(n_clusters):\n"," if plot_idx >= max_clusters_to_show * n_samples_per_cluster:\n"," break\n","\n"," cluster_mask = kept_labels == c\n"," cluster_indices = np.where(cluster_mask)[0]\n","\n"," if len(cluster_indices) == 0:\n"," continue\n","\n"," info = cluster_info[c]\n"," folder_name = f\"cluster_{c:03d}_size{info['size']}_{info['max_sim']:.0f}-{info['min_sim']:.0f}pct\"\n","\n"," # Take first N samples\n"," samples = cluster_indices[:n_samples_per_cluster]\n","\n"," for i, sample_idx in enumerate(samples):\n"," plot_idx += 1\n"," ax = plt.subplot(num_rows * n_samples_per_cluster, num_cols, plot_idx)\n","\n"," img_path = kept_image_paths[sample_idx]\n"," try:\n"," img = Image.open(img_path).convert('RGB')\n"," # Resize for faster display\n"," img = img.resize((256, 256), Image.Resampling.LANCZOS)\n"," ax.imshow(img)\n"," except:\n"," ax.text(0.5, 0.5, \"Error loading image\", ha='center', va='center')\n","\n"," title = f\"#{kept_numbers[sample_idx]}\"\n"," if i == 0:\n"," title = f\"Cluster {c}\\n{title} | Size: {info['size']}\"\n","\n"," ax.set_title(title, fontsize=10)\n"," ax.axis('off')\n","\n"," # Add separator line between clusters\n"," if (c + 1) % num_cols == 0 and plot_idx < max_clusters_to_show * n_samples_per_cluster:\n"," plot_idx += (num_cols - (plot_idx % num_cols)) # fill row if needed\n","\n","plt.suptitle(\"Sample Images from Each Cluster (After Deduplication)\", fontsize=18, y=0.98)\n","plt.tight_layout()\n","plt.show()\n","\n","# ====================== 3. Cluster Summary Table ======================\n","print(\"\\n=== Cluster Summary ===\")\n","print(f\"{'Cluster':<8} {'Size':<8} {'Max Sim':<10} {'Min Sim':<10} {'Images Kept'}\")\n","print(\"-\" * 55)\n","\n","for c in range(n_clusters):\n"," info = cluster_info.get(c, {\"size\":0, \"max_sim\":0, \"min_sim\":0})\n"," if info[\"size\"] > 0:\n"," print(f\"Cluster {c:<3} {info['size']:<8} {info['max_sim']:>6.1f}% {info['min_sim']:>6.1f}% \"\n"," f\"{len(np.where(kept_labels == c)[0])}\")"],"metadata":{"id":"U7IP78tumXrI"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Create Final Flat Zip with Enumerated Image-Text Pairs\n","\n","import shutil\n","import zipfile\n","import os\n","from pathlib import Path\n","\n","#@markdown ### Final Export Settings\n","final_zip_name = \"deduplicated_training_dataset\" #@param {type:\"string\"}\n","include_cluster_in_filename = True #@param {type:\"boolean\"}\n","pad_cluster = 3 #@param {type:\"slider\", min:2, max:5, step:1}\n","pad_index = 5 #@param {type:\"slider\", min:3, max:6, step:1}\n","\n","output_flat_dir = '/content/final_flat_dataset'\n","os.makedirs(output_flat_dir, exist_ok=True)\n","\n","print(\"Creating flat structure for final zip...\")\n","\n","kept_idx = np.array(to_keep)\n","kept_labels = cluster_labels[kept_idx]\n","\n","# Sort by cluster then by original number for consistent ordering\n","sorted_order = sorted(range(len(kept_idx)), key=lambda i: (kept_labels[i], image_numbers[kept_idx[i]]))\n","\n","final_count = 0\n","\n","for pos, orig_pos in enumerate(sorted_order):\n"," global_idx = kept_idx[orig_pos]\n","\n"," cluster_id = kept_labels[orig_pos]\n"," original_num = image_numbers[global_idx]\n"," base_name = bases[global_idx]\n","\n"," # New filename format: clusterXXX_NNNNN\n"," if include_cluster_in_filename:\n"," prefix = f\"cluster{cluster_id:0{pad_cluster}d}\"\n"," filename = f\"{prefix}_{original_num:0{pad_index}d}_{base_name}\"\n"," else:\n"," filename = f\"{original_num:0{pad_index}d}_{base_name}\"\n","\n"," src_img = image_paths[global_idx]\n"," src_txt = enumerated_pairs[global_idx]['text_path']\n","\n"," dst_img = os.path.join(output_flat_dir, f\"{filename}.jpg\")\n"," dst_txt = os.path.join(output_flat_dir, f\"{filename}.txt\")\n","\n"," # Save image as JPEG (clean and standardized)\n"," with Image.open(src_img).convert('RGB') as img:\n"," img.save(dst_img, \"JPEG\", quality=quality, optimize=True)\n","\n"," # Copy text file\n"," shutil.copy(src_txt, dst_txt)\n","\n"," final_count += 1\n","\n"," if final_count % 500 == 0:\n"," print(f\"Processed {final_count} pairs...\")\n","\n","print(f\"\\n✅ Final flat dataset created with {final_count} image-text pairs.\")\n","\n","# ====================== Create Zip ======================\n","zip_path = f\"/content/{final_zip_name}.zip\"\n","\n","print(f\"Compressing to {final_zip_name}.zip ...\")\n","with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:\n"," for file in os.listdir(output_flat_dir):\n"," if file.endswith(('.jpg', '.jpeg', '.txt')):\n"," zf.write(os.path.join(output_flat_dir, file), file)\n","\n","print(f\"Zip created successfully: {zip_path}\")\n","\n","# ====================== Copy to Drive ======================\n","drive_zip_path = f\"/content/drive/MyDrive/{final_zip_name}.zip\"\n","shutil.copy(zip_path, drive_zip_path)\n","print(f\"✅ Copied to Google Drive: {drive_zip_path}\")\n","\n","# Optional: Show first 10 files in the zip\n","print(\"\\nFirst 10 files in the final zip:\")\n","for i, f in enumerate(sorted(os.listdir(output_flat_dir))[:10]):\n"," print(f\" {f}\")"],"metadata":{"id":"4ypnekjmnztE"},"execution_count":null,"outputs":[]}]}
|