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| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"# Install required packages if needed\n",
|
| 15 |
+
"!pip install -q huggingface_hub pandas pyarrow\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"from google.colab import userdata, drive\n",
|
| 18 |
+
"from huggingface_hub import hf_hub_download, list_repo_files\n",
|
| 19 |
+
"import tarfile\n",
|
| 20 |
+
"import json\n",
|
| 21 |
+
"import pandas as pd\n",
|
| 22 |
+
"import os\n",
|
| 23 |
+
"from pathlib import Path\n",
|
| 24 |
+
"from tqdm.auto import tqdm\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"# Mount Google Drive\n",
|
| 27 |
+
"drive.mount('/content/drive')\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"# Get HF token from Colab secrets\n",
|
| 30 |
+
"HF_TOKEN = userdata.get('HF_TOKEN')\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"# Dataset info\n",
|
| 33 |
+
"REPO_ID = \"thisnick/nsfw-video-still-caption\"\n",
|
| 34 |
+
"REPO_TYPE = \"dataset\"\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# List all tar files in the train/ folder\n",
|
| 37 |
+
"print(\"Listing files in the repository...\")\n",
|
| 38 |
+
"all_files = list_repo_files(REPO_ID, repo_type=REPO_TYPE, token=HF_TOKEN)\n",
|
| 39 |
+
"tar_files = sorted([f for f in all_files if f.startswith(\"train/\") and f.endswith(\".tar\")])\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"print(f\"Found {len(tar_files)} tar files:\")\n",
|
| 42 |
+
"for f in tar_files:\n",
|
| 43 |
+
" print(f\" - {f}\")\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Helper to build the description string\n",
|
| 46 |
+
"def build_description(data: dict) -> str:\n",
|
| 47 |
+
" \"\"\"\n",
|
| 48 |
+
" Combine relevant fields into:\n",
|
| 49 |
+
" \"title, categories by cast, tags\"\n",
|
| 50 |
+
" Missing fields are skipped gracefully.\n",
|
| 51 |
+
" \"\"\"\n",
|
| 52 |
+
" title = str(data.get(\"title\", \"\")).strip()\n",
|
| 53 |
+
" categories = data.get(\"categories\", [])\n",
|
| 54 |
+
" if isinstance(categories, list):\n",
|
| 55 |
+
" categories_str = \", \".join(str(c).strip() for c in categories if c)\n",
|
| 56 |
+
" else:\n",
|
| 57 |
+
" categories_str = str(categories).strip() if categories else \"\"\n",
|
| 58 |
+
"\n",
|
| 59 |
+
" # \"by cast\" – try common keys\n",
|
| 60 |
+
" cast = data.get(\"cast\") or data.get(\"actors\") or data.get(\"performers\") or []\n",
|
| 61 |
+
" if isinstance(cast, list):\n",
|
| 62 |
+
" cast_str = \", \".join(str(c).strip() for c in cast if c)\n",
|
| 63 |
+
" else:\n",
|
| 64 |
+
" cast_str = str(cast).strip() if cast else \"\"\n",
|
| 65 |
+
"\n",
|
| 66 |
+
" tags = data.get(\"tags\", [])\n",
|
| 67 |
+
" if isinstance(tags, list):\n",
|
| 68 |
+
" tags_str = \", \".join(str(t).strip() for t in tags if t)\n",
|
| 69 |
+
" else:\n",
|
| 70 |
+
" tags_str = str(tags).strip() if tags else \"\"\n",
|
| 71 |
+
"\n",
|
| 72 |
+
" parts = []\n",
|
| 73 |
+
" if title:\n",
|
| 74 |
+
" parts.append(title)\n",
|
| 75 |
+
" if categories_str:\n",
|
| 76 |
+
" parts.append(categories_str)\n",
|
| 77 |
+
" if cast_str:\n",
|
| 78 |
+
" parts.append(f\"by {cast_str}\")\n",
|
| 79 |
+
" if tags_str:\n",
|
| 80 |
+
" parts.append(tags_str)\n",
|
| 81 |
+
"\n",
|
| 82 |
+
" return \", \".join(parts)\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Process every tar file\n",
|
| 85 |
+
"all_rows = []\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"for tar_filename in tqdm(tar_files, desc=\"Processing tar files\"):\n",
|
| 88 |
+
" print(f\"\\nDownloading {tar_filename} ...\")\n",
|
| 89 |
+
" tar_path = hf_hub_download(\n",
|
| 90 |
+
" repo_id=REPO_ID,\n",
|
| 91 |
+
" filename=tar_filename,\n",
|
| 92 |
+
" repo_type=REPO_TYPE,\n",
|
| 93 |
+
" token=HF_TOKEN,\n",
|
| 94 |
+
" local_dir=\"/content\",\n",
|
| 95 |
+
" local_dir_use_symlinks=False\n",
|
| 96 |
+
" )\n",
|
| 97 |
+
"\n",
|
| 98 |
+
" with tarfile.open(tar_path, \"r\") as tar:\n",
|
| 99 |
+
" for member in tar.getmembers():\n",
|
| 100 |
+
" if member.name.endswith(\".json\"):\n",
|
| 101 |
+
" f = tar.extractfile(member)\n",
|
| 102 |
+
" if f is not None:\n",
|
| 103 |
+
" try:\n",
|
| 104 |
+
" data = json.load(f)\n",
|
| 105 |
+
" description = build_description(data)\n",
|
| 106 |
+
" if description: # skip completely empty descriptions\n",
|
| 107 |
+
" all_rows.append({\n",
|
| 108 |
+
" \"__key__\": Path(member.name).stem,\n",
|
| 109 |
+
" \"source_tar\": tar_filename,\n",
|
| 110 |
+
" \"description\": description\n",
|
| 111 |
+
" })\n",
|
| 112 |
+
" except Exception as e:\n",
|
| 113 |
+
" print(f\" Skipping {member.name}: {e}\")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
" # Free disk space after each tar (optional but recommended)\n",
|
| 116 |
+
" try:\n",
|
| 117 |
+
" os.remove(tar_path)\n",
|
| 118 |
+
" except OSError:\n",
|
| 119 |
+
" pass\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"print(f\"\\nTotal records extracted: {len(all_rows)}\")\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Create DataFrame\n",
|
| 124 |
+
"df = pd.DataFrame(all_rows)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# Remove duplicate descriptions (keep first occurrence)\n",
|
| 127 |
+
"before = len(df)\n",
|
| 128 |
+
"df = df.drop_duplicates(subset=[\"description\"], keep=\"first\").reset_index(drop=True)\n",
|
| 129 |
+
"after = len(df)\n",
|
| 130 |
+
"print(f\"Removed {before - after} duplicate descriptions. Remaining: {after}\")\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"# Save to Drive\n",
|
| 133 |
+
"output_dir = \"/content/drive/MyDrive/nsfw_video_still_caption\"\n",
|
| 134 |
+
"os.makedirs(output_dir, exist_ok=True)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"parquet_path = os.path.join(output_dir, \"all_train_descriptions.parquet\")\n",
|
| 137 |
+
"df.to_parquet(parquet_path, index=False)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"print(f\"\\nSaved parquet with {len(df)} unique descriptions to:\")\n",
|
| 140 |
+
"print(parquet_path)\n",
|
| 141 |
+
"print(\"\\nColumns:\", list(df.columns))\n",
|
| 142 |
+
"print(df.head(10))"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"source": [
|
| 148 |
+
"#@title Adapted Pipeline – Your parquet → clean → T5 → KMeans → JS TXT → ZIP\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"!pip install -q transformers scikit-learn tqdm\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"from google.colab import drive\n",
|
| 153 |
+
"drive.mount('/content/drive')\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"import os\n",
|
| 156 |
+
"import re\n",
|
| 157 |
+
"import zipfile\n",
|
| 158 |
+
"import numpy as np\n",
|
| 159 |
+
"import pandas as pd\n",
|
| 160 |
+
"import torch\n",
|
| 161 |
+
"from pathlib import Path\n",
|
| 162 |
+
"from transformers import T5Tokenizer, T5Model\n",
|
| 163 |
+
"from sklearn.cluster import KMeans\n",
|
| 164 |
+
"from tqdm.auto import tqdm\n",
|
| 165 |
+
"import warnings\n",
|
| 166 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# ============================================================\n",
|
| 169 |
+
"# Configuration\n",
|
| 170 |
+
"# ============================================================\n",
|
| 171 |
+
"parquet_path = \"/content/drive/MyDrive/nsfw_video_still_caption/all_train_descriptions.parquet\"\n",
|
| 172 |
+
"t5_model_name = \"t5-base\" #@param [\"t5-small\", \"t5-base\"]\n",
|
| 173 |
+
"max_tokens = 500 #@param {type:\"slider\", min:128, max:512, step:32}\n",
|
| 174 |
+
"batch_size = 1 # keep 1 for safety on Colab\n",
|
| 175 |
+
"max_clusters = 100 # Goal 9 – maximum folders\n",
|
| 176 |
+
"max_texts_per_file = 1000\n",
|
| 177 |
+
"min_texts_per_file = 300 # merge small clusters\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 180 |
+
"print(f\"Device: {device}\")\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"output_base = Path(\"/content/output\")\n",
|
| 183 |
+
"js_root = output_base / \"js_files\"\n",
|
| 184 |
+
"os.makedirs(js_root, exist_ok=True)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"# ============================================================\n",
|
| 187 |
+
"# 0. Load your parquet\n",
|
| 188 |
+
"# ============================================================\n",
|
| 189 |
+
"print(f\"Loading: {parquet_path}\")\n",
|
| 190 |
+
"df = pd.read_parquet(parquet_path)\n",
|
| 191 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 192 |
+
"print(f\"Columns: {df.columns.tolist()}\")\n",
|
| 193 |
+
"print(df.head(3))\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"assert \"description\" in df.columns, \"Column 'description' not found!\"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"# ============================================================\n",
|
| 198 |
+
"# Helper: Text cleaning (Goals 3 → 6)\n",
|
| 199 |
+
"# ============================================================\n",
|
| 200 |
+
"def clean_text(text: str) -> str:\n",
|
| 201 |
+
" if not isinstance(text, str) or not text.strip():\n",
|
| 202 |
+
" return \"\"\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" text = text.strip()\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # 4) Replace double quotes with single quotes\n",
|
| 207 |
+
" text = text.replace('\"', \"'\")\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # 5) Ensure commas have one space before and after\n",
|
| 210 |
+
" text = re.sub(r'\\s*,\\s*', ' , ', text)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # 5) Remove forbidden symbols: { } [ ] | ^ / \\\n",
|
| 213 |
+
" text = re.sub(r'[{}\\[\\]\\|\\^/\\\\]', '', text)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Normalize whitespace\n",
|
| 216 |
+
" text = re.sub(r'\\s+', ' ', text).strip()\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # 6) Lowercase everything except start of sentence / start of quote\n",
|
| 219 |
+
" def smart_case(s):\n",
|
| 220 |
+
" parts = re.split(r'([.!?]\\s+)', s)\n",
|
| 221 |
+
" result = []\n",
|
| 222 |
+
" capitalize_next = True\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" for part in parts:\n",
|
| 225 |
+
" if not part:\n",
|
| 226 |
+
" continue\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" if capitalize_next and part and part[0].isalpha():\n",
|
| 229 |
+
" part = part[0].upper() + part[1:].lower()\n",
|
| 230 |
+
" else:\n",
|
| 231 |
+
" part = part.lower()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Capitalize letter after a single quote (e.g. 'Tree)\n",
|
| 234 |
+
" part = re.sub(\n",
|
| 235 |
+
" r\"(['‘’])([a-z])\",\n",
|
| 236 |
+
" lambda m: m.group(1) + m.group(2).upper(),\n",
|
| 237 |
+
" part\n",
|
| 238 |
+
" )\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" result.append(part)\n",
|
| 241 |
+
" capitalize_next = part.endswith(('.', '!', '?')) or bool(re.search(r'[.!?]\\s*$', part))\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" return ''.join(result)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" return smart_case(text)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"def prepare_text(row) -> str:\n",
|
| 249 |
+
" # Only one text column in your parquet\n",
|
| 250 |
+
" return clean_text(str(row.get(\"description\", \"\")))\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"# ============================================================\n",
|
| 253 |
+
"# Prepare cleaned texts\n",
|
| 254 |
+
"# ============================================================\n",
|
| 255 |
+
"print(\"\\nCleaning texts...\")\n",
|
| 256 |
+
"df = df.copy()\n",
|
| 257 |
+
"df[\"cleaned_text\"] = df.apply(prepare_text, axis=1)\n",
|
| 258 |
+
"df = df[df[\"cleaned_text\"].str.len() > 10].reset_index(drop=True)\n",
|
| 259 |
+
"print(f\"Usable rows after cleaning: {len(df)}\")\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"if len(df) < 2:\n",
|
| 262 |
+
" raise ValueError(\"Not enough usable texts to continue.\")\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"texts = df[\"cleaned_text\"].tolist()\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"# ============================================================\n",
|
| 267 |
+
"# Load T5 encoder\n",
|
| 268 |
+
"# ============================================================\n",
|
| 269 |
+
"print(f\"\\nLoading {t5_model_name}...\")\n",
|
| 270 |
+
"tokenizer = T5Tokenizer.from_pretrained(t5_model_name)\n",
|
| 271 |
+
"model = T5Model.from_pretrained(t5_model_name).to(device)\n",
|
| 272 |
+
"model.eval()\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"def get_t5_embeddings(texts):\n",
|
| 275 |
+
" all_embs = []\n",
|
| 276 |
+
" for i in tqdm(range(0, len(texts), batch_size), desc=\"Encoding with T5\"):\n",
|
| 277 |
+
" batch = texts[i : i + batch_size]\n",
|
| 278 |
+
" inputs = tokenizer(\n",
|
| 279 |
+
" batch,\n",
|
| 280 |
+
" return_tensors=\"pt\",\n",
|
| 281 |
+
" padding=True,\n",
|
| 282 |
+
" truncation=True,\n",
|
| 283 |
+
" max_length=max_tokens,\n",
|
| 284 |
+
" ).to(device)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" with torch.no_grad():\n",
|
| 287 |
+
" outputs = model.encoder(**inputs)\n",
|
| 288 |
+
" last_hidden = outputs.last_hidden_state\n",
|
| 289 |
+
" mask = inputs.attention_mask.unsqueeze(-1).float()\n",
|
| 290 |
+
" summed = (last_hidden * mask).sum(dim=1)\n",
|
| 291 |
+
" counts = mask.sum(dim=1).clamp(min=1e-9)\n",
|
| 292 |
+
" mean_pooled = summed / counts\n",
|
| 293 |
+
" all_embs.append(mean_pooled.cpu().numpy())\n",
|
| 294 |
+
" return np.vstack(all_embs)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# ============================================================\n",
|
| 297 |
+
"# Goal 8: Encode\n",
|
| 298 |
+
"# ============================================================\n",
|
| 299 |
+
"print(\"\\nEncoding texts...\")\n",
|
| 300 |
+
"embeddings = get_t5_embeddings(texts)\n",
|
| 301 |
+
"print(f\"Embeddings shape: {embeddings.shape}\")\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"# ============================================================\n",
|
| 304 |
+
"# Goal 9: K-Means (max 100 folders)\n",
|
| 305 |
+
"# ============================================================\n",
|
| 306 |
+
"k = min(max_clusters, max(2, len(texts) // 8))\n",
|
| 307 |
+
"k = min(k, len(texts))\n",
|
| 308 |
+
"print(f\"Using k = {k} clusters\")\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)\n",
|
| 311 |
+
"labels = kmeans.fit_predict(embeddings)\n",
|
| 312 |
+
"df[\"cluster\"] = labels\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Collect texts per cluster\n",
|
| 315 |
+
"cluster_texts_list = []\n",
|
| 316 |
+
"for c in range(k):\n",
|
| 317 |
+
" cluster_texts = df.loc[df[\"cluster\"] == c, \"cleaned_text\"].tolist()\n",
|
| 318 |
+
" if cluster_texts:\n",
|
| 319 |
+
" cluster_texts_list.append(cluster_texts)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"print(f\"Raw clusters created: {len(cluster_texts_list)}\")\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"# ============================================================\n",
|
| 324 |
+
"# Merge small clusters (< 300 items)\n",
|
| 325 |
+
"# ============================================================\n",
|
| 326 |
+
"large_clusters = []\n",
|
| 327 |
+
"small_pool = []\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"for texts_list in cluster_texts_list:\n",
|
| 330 |
+
" if len(texts_list) >= min_texts_per_file:\n",
|
| 331 |
+
" large_clusters.append(texts_list)\n",
|
| 332 |
+
" else:\n",
|
| 333 |
+
" small_pool.extend(texts_list)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"print(f\"Large clusters (≥{min_texts_per_file}): {len(large_clusters)}\")\n",
|
| 336 |
+
"print(f\"Texts moved to small pool: {len(small_pool)}\")\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"merged_small_clusters = []\n",
|
| 339 |
+
"if small_pool:\n",
|
| 340 |
+
" for start in range(0, len(small_pool), max_texts_per_file):\n",
|
| 341 |
+
" chunk = small_pool[start : start + max_texts_per_file]\n",
|
| 342 |
+
" if (len(chunk) < min_texts_per_file and merged_small_clusters\n",
|
| 343 |
+
" and len(merged_small_clusters[-1]) + len(chunk) <= max_texts_per_file):\n",
|
| 344 |
+
" merged_small_clusters[-1].extend(chunk)\n",
|
| 345 |
+
" else:\n",
|
| 346 |
+
" merged_small_clusters.append(chunk)\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"final_folders = large_clusters + merged_small_clusters\n",
|
| 349 |
+
"print(f\"Final folders after merging: {len(final_folders)}\")\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"# ============================================================\n",
|
| 352 |
+
"# Helper: write one JS file\n",
|
| 353 |
+
"# ============================================================\n",
|
| 354 |
+
"def write_js_file(cluster_dir, gname, folder_id, part_idx, chunk):\n",
|
| 355 |
+
" dataset_str = \"{\" + \"|\".join(chunk) + \"}\"\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" content = f\"\"\"//start\n",
|
| 358 |
+
"group = \"{gname}\"\n",
|
| 359 |
+
"folder_id = \"{folder_id}\"\n",
|
| 360 |
+
"file_index = {part_idx + 1}\n",
|
| 361 |
+
"name = \"nsfw_video_still_caption\"\n",
|
| 362 |
+
"emoji = \"🎬\"\n",
|
| 363 |
+
"showComments = true\n",
|
| 364 |
+
"showDemo = true\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"pageTitle = [emoji] fusion-t2i-[name]-[group]-[folder_id]-[file_index]\n",
|
| 367 |
+
"pageDescription = Captioned works from nsfw_video_still_caption parquet – {gname} – {folder_id}\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"tagBlackListRaw = [\"\"]\n",
|
| 370 |
+
"tagBlackList = [tagBlackListRaw.replaceText(' ' , ',')]\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"// Generator browse destinations\n",
|
| 373 |
+
"backward = []\n",
|
| 374 |
+
"forward = []\n",
|
| 375 |
+
"backward_em = {{emoji}}\n",
|
| 376 |
+
"forward_em = {{emoji}}\n",
|
| 377 |
+
"numItemsStart = 1\n",
|
| 378 |
+
"//----//\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"image_url = [\"https://www.iguides.ru/upload/iblock/ccf/ccf3e83b95a8b350d5089424687fc133.jpg\"]\n",
|
| 381 |
+
"image_description = [\"placeholder\"]\n",
|
| 382 |
+
"optional_image_caption = [\"placeholder\"]\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"$meta\n",
|
| 385 |
+
" title = [emoji] [name] [group] [folder_id] [file_index]\n",
|
| 386 |
+
" description = Subset of {gname} – {folder_id} – part {part_idx+1}\n",
|
| 387 |
+
" image = https://i.imgur.com/TPHIzaa.jpeg\n",
|
| 388 |
+
"$output\n",
|
| 389 |
+
" [dataset]\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"data = [(($output.selectMany(document.numItems).join(\" \")+' '))]\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"dataset\n",
|
| 394 |
+
" [\"{dataset_str}\"]\n",
|
| 395 |
+
"//----//\n",
|
| 396 |
+
"\"\"\"\n",
|
| 397 |
+
"\n",
|
| 398 |
+
" filename = f\"fusion-t2i-nsfw_video_still_caption-{gname}-{folder_id}-part{part_idx+1:02d}.txt\"\n",
|
| 399 |
+
" with open(cluster_dir / filename, \"w\", encoding=\"utf-8\") as f:\n",
|
| 400 |
+
" f.write(content)\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"# ============================================================\n",
|
| 403 |
+
"# Write the files (single group because we have no rating/solo columns)\n",
|
| 404 |
+
"# ============================================================\n",
|
| 405 |
+
"gname = \"all_descriptions\"\n",
|
| 406 |
+
"group_dir = js_root / gname\n",
|
| 407 |
+
"os.makedirs(group_dir, exist_ok=True)\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"for folder_idx, folder_texts in enumerate(final_folders):\n",
|
| 410 |
+
" folder_id = f\"cluster_{folder_idx:03d}\"\n",
|
| 411 |
+
" cluster_dir = group_dir / folder_id\n",
|
| 412 |
+
" os.makedirs(cluster_dir, exist_ok=True)\n",
|
| 413 |
+
"\n",
|
| 414 |
+
" for part_idx, start in enumerate(range(0, len(folder_texts), max_texts_per_file)):\n",
|
| 415 |
+
" chunk = folder_texts[start : start + max_texts_per_file]\n",
|
| 416 |
+
" write_js_file(cluster_dir, gname, folder_id, part_idx, chunk)\n",
|
| 417 |
+
"\n",
|
| 418 |
+
"print(f\"\\n→ Saved under {group_dir}\")\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"# ============================================================\n",
|
| 421 |
+
"# Goal 11: Create ZIP\n",
|
| 422 |
+
"# ============================================================\n",
|
| 423 |
+
"zip_path = \"/content/output/nsfw_video_still_caption_js_files.zip\"\n",
|
| 424 |
+
"\n",
|
| 425 |
+
"with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zipf:\n",
|
| 426 |
+
" for root, dirs, files in os.walk(js_root):\n",
|
| 427 |
+
" for file in files:\n",
|
| 428 |
+
" if file.endswith(\".txt\"):\n",
|
| 429 |
+
" full = os.path.join(root, file)\n",
|
| 430 |
+
" arcname = os.path.relpath(full, js_root)\n",
|
| 431 |
+
" zipf.write(full, arcname=arcname)\n",
|
| 432 |
+
"\n",
|
| 433 |
+
"print(\"\\n\" + \"=\"*70)\n",
|
| 434 |
+
"print(\"✅ ALL DONE\")\n",
|
| 435 |
+
"print(f\"ZIP file: {zip_path}\")\n",
|
| 436 |
+
"print(\"Structure inside ZIP:\")\n",
|
| 437 |
+
"print(\" all_descriptions/\")\n",
|
| 438 |
+
"print(\" cluster_000/\")\n",
|
| 439 |
+
"print(\" fusion-t2i-....txt\")\n",
|
| 440 |
+
"print(\" cluster_001/\")\n",
|
| 441 |
+
"print(\" ...\")\n",
|
| 442 |
+
"print(\"=\"*70)\n",
|
| 443 |
+
"print(\"Download the ZIP from the Colab file browser (left panel) or copy it to Drive.\")"
|
| 444 |
+
],
|
| 445 |
+
"metadata": {
|
| 446 |
+
"id": "FGBfwwUTBcJY"
|
| 447 |
+
},
|
| 448 |
+
"execution_count": null,
|
| 449 |
+
"outputs": []
|
| 450 |
+
}
|
| 451 |
+
],
|
| 452 |
+
"metadata": {
|
| 453 |
+
"colab": {
|
| 454 |
+
"provenance": []
|
| 455 |
+
},
|
| 456 |
+
"kernelspec": {
|
| 457 |
+
"display_name": "Python 3",
|
| 458 |
+
"name": "python3"
|
| 459 |
+
},
|
| 460 |
+
"language_info": {
|
| 461 |
+
"name": "python"
|
| 462 |
+
}
|
| 463 |
+
},
|
| 464 |
+
"nbformat": 4,
|
| 465 |
+
"nbformat_minor": 0
|
| 466 |
+
}
|