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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "T4"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "markdown",
|
| 21 |
+
"source": [
|
| 22 |
+
"Using https://huggingface.co/datasets/lodestones/booru-essence"
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"id": "U-yf5jnY3gSd"
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"source": [
|
| 31 |
+
"from google.colab import drive\n",
|
| 32 |
+
"drive.mount('/content/drive')"
|
| 33 |
+
],
|
| 34 |
+
"metadata": {
|
| 35 |
+
"id": "HFy5aDxM3G7O"
|
| 36 |
+
},
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"source": [
|
| 43 |
+
"#@title Sort Parquet texts by Rating → T5 encode → KMeans clusters (up to 100)\n",
|
| 44 |
+
"# Loads the parquet, groups by the 'rating' column, builds one combined descriptive text per row,\n",
|
| 45 |
+
"# encodes with T5, then runs KMeans (max 100 clusters) and saves results to /content/output/ only.\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"!pip install -q transformers scikit-learn umap-learn matplotlib tqdm\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"import os\n",
|
| 50 |
+
"import re\n",
|
| 51 |
+
"import json\n",
|
| 52 |
+
"import numpy as np\n",
|
| 53 |
+
"import pandas as pd\n",
|
| 54 |
+
"import torch\n",
|
| 55 |
+
"from transformers import T5Tokenizer, T5Model\n",
|
| 56 |
+
"from sklearn.cluster import KMeans\n",
|
| 57 |
+
"from sklearn.metrics import silhouette_score\n",
|
| 58 |
+
"from umap import UMAP\n",
|
| 59 |
+
"import matplotlib.pyplot as plt\n",
|
| 60 |
+
"from tqdm.auto import tqdm\n",
|
| 61 |
+
"import warnings\n",
|
| 62 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"# ============================================================\n",
|
| 65 |
+
"# 0. Load the Parquet file\n",
|
| 66 |
+
"# ============================================================\n",
|
| 67 |
+
"file_path = \"/content/drive/MyDrive/booru_essence.parquet\" #@param {type:\"string\"}\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"print(f\"Loading parquet from: {file_path}\")\n",
|
| 70 |
+
"df = pd.read_parquet(file_path)\n",
|
| 71 |
+
"print(f\"Loaded dataframe shape: {df.shape}\")\n",
|
| 72 |
+
"print(f\"Columns: {df.columns.tolist()}\")\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"# ============================================================\n",
|
| 75 |
+
"# Configuration\n",
|
| 76 |
+
"# ============================================================\n",
|
| 77 |
+
"n_clusters = 100 #@param {type:\"slider\", min:2, max:100, step:1}\n",
|
| 78 |
+
"t5_model_name = \"t5-base\" #@param [\"t5-small\", \"t5-base\"]\n",
|
| 79 |
+
"max_length = 512 #@param {type:\"slider\", min:128, max:512, step:64}\n",
|
| 80 |
+
"batch_size = 16 #@param {type:\"slider\", min:4, max:32, step:4}\n",
|
| 81 |
+
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 82 |
+
"print(f\"Using device: {device}\")\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Which text columns to combine (in order of priority)\n",
|
| 85 |
+
"TEXT_COLS = [\n",
|
| 86 |
+
" \"brief_summary\",\n",
|
| 87 |
+
" \"midjourney_style_summary\",\n",
|
| 88 |
+
" \"tags\",\n",
|
| 89 |
+
" \"trigger_tag\",\n",
|
| 90 |
+
" # \"10_word_summary\", # currently all-null in your file\n",
|
| 91 |
+
"]\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"# ============================================================\n",
|
| 94 |
+
"# 1. Helper: clean & combine descriptive texts for one row\n",
|
| 95 |
+
"# ============================================================\n",
|
| 96 |
+
"def combine_texts(row):\n",
|
| 97 |
+
" parts = []\n",
|
| 98 |
+
" for col in TEXT_COLS:\n",
|
| 99 |
+
" val = row.get(col)\n",
|
| 100 |
+
" if pd.isna(val) or val is None:\n",
|
| 101 |
+
" continue\n",
|
| 102 |
+
" text = str(val).strip()\n",
|
| 103 |
+
" if text and text.lower() != \"none\":\n",
|
| 104 |
+
" # simple cleanup\n",
|
| 105 |
+
" text = re.sub(r'\\s+', ' ', text)\n",
|
| 106 |
+
" parts.append(text)\n",
|
| 107 |
+
" return \" | \".join(parts) if parts else \"\"\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"# ============================================================\n",
|
| 110 |
+
"# 2. Load T5 encoder\n",
|
| 111 |
+
"# ============================================================\n",
|
| 112 |
+
"print(f\"Loading {t5_model_name}...\")\n",
|
| 113 |
+
"tokenizer = T5Tokenizer.from_pretrained(t5_model_name)\n",
|
| 114 |
+
"model = T5Model.from_pretrained(t5_model_name).to(device)\n",
|
| 115 |
+
"model.eval()\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"def get_t5_embeddings(texts, batch_size=16):\n",
|
| 118 |
+
" \"\"\"Return mean-pooled encoder embeddings (N, hidden_size)\"\"\"\n",
|
| 119 |
+
" all_embs = []\n",
|
| 120 |
+
" for i in tqdm(range(0, len(texts), batch_size), desc=\"Encoding\"):\n",
|
| 121 |
+
" batch = texts[i:i+batch_size]\n",
|
| 122 |
+
" inputs = tokenizer(\n",
|
| 123 |
+
" batch,\n",
|
| 124 |
+
" return_tensors=\"pt\",\n",
|
| 125 |
+
" padding=True,\n",
|
| 126 |
+
" truncation=True,\n",
|
| 127 |
+
" max_length=max_length\n",
|
| 128 |
+
" ).to(device)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
" with torch.no_grad():\n",
|
| 131 |
+
" outputs = model.encoder(**inputs)\n",
|
| 132 |
+
" # mean pool over sequence length (ignore padding via attention mask)\n",
|
| 133 |
+
" last_hidden = outputs.last_hidden_state # (B, L, H)\n",
|
| 134 |
+
" mask = inputs.attention_mask.unsqueeze(-1).float()\n",
|
| 135 |
+
" summed = (last_hidden * mask).sum(dim=1)\n",
|
| 136 |
+
" counts = mask.sum(dim=1).clamp(min=1e-9)\n",
|
| 137 |
+
" mean_pooled = summed / counts # (B, H)\n",
|
| 138 |
+
" all_embs.append(mean_pooled.cpu().numpy())\n",
|
| 139 |
+
"\n",
|
| 140 |
+
" return np.vstack(all_embs)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"# ============================================================\n",
|
| 143 |
+
"# 3. Process each rating group separately\n",
|
| 144 |
+
"# ============================================================\n",
|
| 145 |
+
"assert \"rating\" in df.columns, \"Column 'rating' not found!\"\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"# All results go ONLY to /content/output/\n",
|
| 148 |
+
"output_base = \"/content/output\"\n",
|
| 149 |
+
"os.makedirs(output_base, exist_ok=True)\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"unique_ratings = df[\"rating\"].dropna().unique().tolist()\n",
|
| 152 |
+
"print(f\"Found ratings: {unique_ratings}\")\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"for rating in unique_ratings:\n",
|
| 155 |
+
" print(f\"\\n{'='*60}\")\n",
|
| 156 |
+
" print(f\"Processing rating = '{rating}'\")\n",
|
| 157 |
+
" print(f\"{'='*60}\")\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" # Filter\n",
|
| 160 |
+
" group = df[df[\"rating\"] == rating].copy().reset_index(drop=True)\n",
|
| 161 |
+
" print(f\" Rows: {len(group)}\")\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" # Build combined text\n",
|
| 164 |
+
" group[\"combined_text\"] = group.apply(combine_texts, axis=1)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" # Drop empty texts\n",
|
| 167 |
+
" group = group[group[\"combined_text\"].str.len() > 5].reset_index(drop=True)\n",
|
| 168 |
+
" print(f\" After dropping near-empty texts: {len(group)}\")\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" if len(group) < 2:\n",
|
| 171 |
+
" print(\" Skipping – not enough samples\")\n",
|
| 172 |
+
" continue\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" texts = group[\"combined_text\"].tolist()\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Encode with T5\n",
|
| 177 |
+
" embeddings = get_t5_embeddings(texts, batch_size=batch_size)\n",
|
| 178 |
+
" print(f\" Embeddings shape: {embeddings.shape}\")\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Decide number of clusters (never more than samples, never more than requested)\n",
|
| 181 |
+
" k = min(n_clusters, len(group) // 2, 100) # safety\n",
|
| 182 |
+
" k = max(k, 2)\n",
|
| 183 |
+
" print(f\" Using k = {k} clusters\")\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # KMeans\n",
|
| 186 |
+
" kmeans = KMeans(n_clusters=k, random_state=42, n_init=10, verbose=0)\n",
|
| 187 |
+
" labels = kmeans.fit_predict(embeddings)\n",
|
| 188 |
+
" group[\"cluster\"] = labels\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Silhouette (optional, can be slow on large sets)\n",
|
| 191 |
+
" try:\n",
|
| 192 |
+
" sil = silhouette_score(embeddings, labels, sample_size=min(5000, len(embeddings)))\n",
|
| 193 |
+
" print(f\" Silhouette score: {sil:.3f}\")\n",
|
| 194 |
+
" except Exception as e:\n",
|
| 195 |
+
" print(f\" Silhouette skipped: {e}\")\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Save full group with cluster labels\n",
|
| 198 |
+
" rating_safe = re.sub(r'[^a-zA-Z0-9_]', '_', str(rating))\n",
|
| 199 |
+
" out_dir = os.path.join(output_base, f\"rating_{rating_safe}\")\n",
|
| 200 |
+
" os.makedirs(out_dir, exist_ok=True)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # Save the whole dataframe for this rating\n",
|
| 203 |
+
" group.to_parquet(os.path.join(out_dir, f\"all_with_clusters.parquet\"), index=False)\n",
|
| 204 |
+
" group.to_csv(os.path.join(out_dir, f\"all_with_clusters.csv\"), index=False)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Also save one CSV per cluster (easy to inspect)\n",
|
| 207 |
+
" for c in range(k):\n",
|
| 208 |
+
" cluster_df = group[group[\"cluster\"] == c]\n",
|
| 209 |
+
" cluster_df.to_csv(\n",
|
| 210 |
+
" os.path.join(out_dir, f\"cluster_{c:03d}.csv\"),\n",
|
| 211 |
+
" index=False\n",
|
| 212 |
+
" )\n",
|
| 213 |
+
" # Optional: save only the combined text\n",
|
| 214 |
+
" with open(os.path.join(out_dir, f\"cluster_{c:03d}_texts.txt\"), \"w\", encoding=\"utf-8\") as f:\n",
|
| 215 |
+
" for t in cluster_df[\"combined_text\"]:\n",
|
| 216 |
+
" f.write(t + \"\\n\\n---\\n\\n\")\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" print(f\" Saved to: {out_dir}\")\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Optional 2-D UMAP plot\n",
|
| 221 |
+
" if len(embeddings) >= 10:\n",
|
| 222 |
+
" try:\n",
|
| 223 |
+
" reducer = UMAP(n_components=2, random_state=42, n_neighbors=15, min_dist=0.1)\n",
|
| 224 |
+
" emb_2d = reducer.fit_transform(embeddings)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" plt.figure(figsize=(10, 8))\n",
|
| 227 |
+
" scatter = plt.scatter(emb_2d[:, 0], emb_2d[:, 1],\n",
|
| 228 |
+
" c=labels, cmap=\"tab20\", s=20, alpha=0.7)\n",
|
| 229 |
+
" plt.colorbar(scatter, label=\"Cluster\")\n",
|
| 230 |
+
" plt.title(f\"T5 + KMeans – rating='{rating}' (k={k})\")\n",
|
| 231 |
+
" plt.xlabel(\"UMAP-1\")\n",
|
| 232 |
+
" plt.ylabel(\"UMAP-2\")\n",
|
| 233 |
+
" plt.tight_layout()\n",
|
| 234 |
+
" plt.savefig(os.path.join(out_dir, \"umap_plot.png\"), dpi=150)\n",
|
| 235 |
+
" plt.show()\n",
|
| 236 |
+
" except Exception as e:\n",
|
| 237 |
+
" print(f\" UMAP plot failed: {e}\")\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"print(\"\\n✅ Done!\")\n",
|
| 240 |
+
"print(f\"All results are under: {output_base}\")\n",
|
| 241 |
+
"print(\"Structure:\")\n",
|
| 242 |
+
"print(\" /content/output/\")\n",
|
| 243 |
+
"print(\" rating_explicit/\")\n",
|
| 244 |
+
"print(\" all_with_clusters.parquet / .csv\")\n",
|
| 245 |
+
"print(\" cluster_000.csv ... cluster_099.csv\")\n",
|
| 246 |
+
"print(\" cluster_000_texts.txt ...\")\n",
|
| 247 |
+
"print(\" umap_plot.png\")\n",
|
| 248 |
+
"print(\" rating_questionable/\")\n",
|
| 249 |
+
"print(\" rating_general/\")\n",
|
| 250 |
+
"print(\" ...\")"
|
| 251 |
+
],
|
| 252 |
+
"metadata": {
|
| 253 |
+
"id": "3WfqNYWD7V-h"
|
| 254 |
+
},
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"source": [
|
| 261 |
+
"#@title Generate text files from clustered prompts + create ZIP\n",
|
| 262 |
+
"# Creates one .txt file per cluster (sorted by rating → cluster number)\n",
|
| 263 |
+
"# Each file follows the exact //start ... format you provided.\n",
|
| 264 |
+
"# All .txt files are then zipped into /content/output/js_files.zip\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"import os\n",
|
| 267 |
+
"import re\n",
|
| 268 |
+
"import zipfile\n",
|
| 269 |
+
"from pathlib import Path\n",
|
| 270 |
+
"from tqdm.auto import tqdm\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"# ============================================================\n",
|
| 273 |
+
"# Configuration\n",
|
| 274 |
+
"# ============================================================\n",
|
| 275 |
+
"input_base = \"/content/output\" # where the previous cell saved results\n",
|
| 276 |
+
"output_dir = \"/content/output/js_files\" # final .txt files go here\n",
|
| 277 |
+
"os.makedirs(output_dir, exist_ok=True)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"name = \"booru_essence\" #@param {type:\"string\"}\n",
|
| 280 |
+
"emoji = \"🏖️\" #@param {type:\"string\"}\n",
|
| 281 |
+
"showComments = True\n",
|
| 282 |
+
"showDemo = True\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# Placeholder image (you can change later)\n",
|
| 285 |
+
"placeholder_image = \"https://www.iguides.ru/upload/iblock/ccf/ccf3e83b95a8b350d5089424687fc133.jpg\"\n",
|
| 286 |
+
"placeholder_description = \"a space ship , used as a placeholder\"\n",
|
| 287 |
+
"placeholder_caption = \"This is text\"\n",
|
| 288 |
+
"meta_image = \"https://i.imgur.com/TPHIzaa.jpeg\"\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"# ============================================================\n",
|
| 291 |
+
"# 1. Collect all cluster text files, sorted by rating then cluster number\n",
|
| 292 |
+
"# ============================================================\n",
|
| 293 |
+
"text_files = []\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"for rating_dir in sorted(Path(input_base).glob(\"rating_*\")):\n",
|
| 296 |
+
" if not rating_dir.is_dir():\n",
|
| 297 |
+
" continue\n",
|
| 298 |
+
" rating_name = rating_dir.name.replace(\"rating_\", \"\")\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" for txt_file in sorted(rating_dir.glob(\"cluster_*_texts.txt\")):\n",
|
| 301 |
+
" # extract cluster number for proper sorting\n",
|
| 302 |
+
" match = re.search(r\"cluster_(\\d+)_texts\\.txt\", txt_file.name)\n",
|
| 303 |
+
" if match:\n",
|
| 304 |
+
" cluster_num = int(match.group(1))\n",
|
| 305 |
+
" text_files.append({\n",
|
| 306 |
+
" \"path\": txt_file,\n",
|
| 307 |
+
" \"rating\": rating_name,\n",
|
| 308 |
+
" \"cluster\": cluster_num\n",
|
| 309 |
+
" })\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"# Final sort: rating name → cluster number\n",
|
| 312 |
+
"text_files = sorted(text_files, key=lambda x: (x[\"rating\"], x[\"cluster\"]))\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"print(f\"Found {len(text_files)} cluster text files\")\n",
|
| 315 |
+
"if len(text_files) == 0:\n",
|
| 316 |
+
" raise FileNotFoundError(\"No cluster_*_texts.txt files found under /content/output/\")\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# ============================================================\n",
|
| 319 |
+
"# 2. Helper: read prompts from a *_texts.txt file\n",
|
| 320 |
+
"# ============================================================\n",
|
| 321 |
+
"def load_prompts(txt_path):\n",
|
| 322 |
+
" content = Path(txt_path).read_text(encoding=\"utf-8\")\n",
|
| 323 |
+
" # Split on the separator used in the previous cell\n",
|
| 324 |
+
" raw_prompts = re.split(r'\\n\\s*---\\s*\\n', content)\n",
|
| 325 |
+
" prompts = []\n",
|
| 326 |
+
" for p in raw_prompts:\n",
|
| 327 |
+
" p = p.strip()\n",
|
| 328 |
+
" if p and len(p) > 5:\n",
|
| 329 |
+
" # clean newlines inside a single prompt → single space\n",
|
| 330 |
+
" p = re.sub(r'\\s+', ' ', p)\n",
|
| 331 |
+
" prompts.append(p)\n",
|
| 332 |
+
" return prompts\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# ============================================================\n",
|
| 335 |
+
"# 3. Generate one .txt file per cluster\n",
|
| 336 |
+
"# ============================================================\n",
|
| 337 |
+
"total = len(text_files)\n",
|
| 338 |
+
"generated_files = []\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"for idx, item in enumerate(tqdm(text_files, desc=\"Generating TXT files\"), start=1):\n",
|
| 341 |
+
" prompts = load_prompts(item[\"path\"])\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" if not prompts:\n",
|
| 344 |
+
" print(f\" Skipping empty cluster: {item['path']}\")\n",
|
| 345 |
+
" continue\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" # Join all prompts with single \"|\"\n",
|
| 348 |
+
" dataset_str = \"|\".join(prompts)\n",
|
| 349 |
+
"\n",
|
| 350 |
+
" # Build backward / forward links\n",
|
| 351 |
+
" if idx == 1:\n",
|
| 352 |
+
" backward = f'[\"fusion-t2i-{name}-1\"]'\n",
|
| 353 |
+
" else:\n",
|
| 354 |
+
" backward = f'[\"fusion-t2i-{name}-{idx-1}\"]'\n",
|
| 355 |
+
"\n",
|
| 356 |
+
" if idx == total:\n",
|
| 357 |
+
" forward = f'[\"fusion-t2i-{name}-{idx}\"]'\n",
|
| 358 |
+
" else:\n",
|
| 359 |
+
" forward = f'[\"fusion-t2i-{name}-{idx+1}\"]'\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" # Full content matching your template\n",
|
| 362 |
+
" content = f\"\"\"//start\n",
|
| 363 |
+
"index = {idx}\n",
|
| 364 |
+
"emoji = {emoji}\n",
|
| 365 |
+
"showComments = {str(showComments).lower()}\n",
|
| 366 |
+
"showDemo = {str(showDemo).lower()}\n",
|
| 367 |
+
"name = {name}\n",
|
| 368 |
+
"pageTitle = [emoji] fusion-t2i-[name]-[index]\n",
|
| 369 |
+
"pageDescription = captioned works by booru_parquet\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"tagBlackListRaw = [\"\"]\n",
|
| 372 |
+
"tagBlackList= [tagBlackListRaw.replaceText(' ' , ',')]\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"// Generator browse destinations\n",
|
| 375 |
+
"backward={backward}\n",
|
| 376 |
+
"forward={forward}\n",
|
| 377 |
+
"backward_em= {emoji}\n",
|
| 378 |
+
"forward_em= {emoji}\n",
|
| 379 |
+
"numItemsStart=1\n",
|
| 380 |
+
"//----//\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"image_url = [\"{placeholder_image}\"]\n",
|
| 384 |
+
"image_description= [\"{placeholder_description}\"]\n",
|
| 385 |
+
"optional_image_caption= [\"{placeholder_caption}\"]\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"$meta\n",
|
| 388 |
+
" title = [emoji] [name] [index] // <-- notice that this shows up in the browser tab - it overrides the <h1> text\n",
|
| 389 |
+
" description = This is subset [index] of [name] , which contains various descriptions of [name]\n",
|
| 390 |
+
" image = {meta_image}\n",
|
| 391 |
+
"$output\n",
|
| 392 |
+
" [dataset]\n",
|
| 393 |
+
"\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"data = [(($output.selectMany(document.numItems).join(\" \")+' '))]\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"dataset\n",
|
| 398 |
+
" [\"{dataset_str}\"]\n",
|
| 399 |
+
"//----//\n",
|
| 400 |
+
"\"\"\"\n",
|
| 401 |
+
"\n",
|
| 402 |
+
" # Save as .txt file\n",
|
| 403 |
+
" out_name = f\"fusion-t2i-{name}-{idx}.txt\"\n",
|
| 404 |
+
" out_path = os.path.join(output_dir, out_name)\n",
|
| 405 |
+
" with open(out_path, \"w\", encoding=\"utf-8\") as f:\n",
|
| 406 |
+
" f.write(content)\n",
|
| 407 |
+
"\n",
|
| 408 |
+
" generated_files.append(out_path)\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"print(f\"\\n✅ Generated {len(generated_files)} .txt files in: {output_dir}\")\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"# ============================================================\n",
|
| 413 |
+
"# 4. Create ZIP archive\n",
|
| 414 |
+
"# ============================================================\n",
|
| 415 |
+
"zip_path = \"/content/output/js_files.zip\"\n",
|
| 416 |
+
"\n",
|
| 417 |
+
"with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zipf:\n",
|
| 418 |
+
" for file_path in generated_files:\n",
|
| 419 |
+
" # store only the filename inside the zip (no folder structure)\n",
|
| 420 |
+
" zipf.write(file_path, arcname=os.path.basename(file_path))\n",
|
| 421 |
+
"\n",
|
| 422 |
+
"print(f\"✅ ZIP created: {zip_path}\")\n",
|
| 423 |
+
"print(f\" Contains {len(generated_files)} files\")\n",
|
| 424 |
+
"print(\"\\nYou can download it from the Colab file browser or with:\")\n",
|
| 425 |
+
"print(f\"!files.download('{zip_path}')\")"
|
| 426 |
+
],
|
| 427 |
+
"metadata": {
|
| 428 |
+
"id": "vJh25rT9_14a"
|
| 429 |
+
},
|
| 430 |
+
"execution_count": null,
|
| 431 |
+
"outputs": []
|
| 432 |
+
},
|
| 433 |
+
{
|
| 434 |
+
"cell_type": "code",
|
| 435 |
+
"source": [
|
| 436 |
+
"#@title Clean \"|\" before every \"by ...\" in the generated TXT files + re-zip\n",
|
| 437 |
+
"# Removes the \"|\" that appears immediately before artist credits like:\n",
|
| 438 |
+
"# \"white sweater | by hyde (tabakko)|1girl\" → \"white sweater by hyde (tabakko)|1girl\"\n",
|
| 439 |
+
"# \"eyebrows | by alexmaster|1girl\" → \"eyebrows by alexmaster|1girl\"\n",
|
| 440 |
+
"\n",
|
| 441 |
+
"import os\n",
|
| 442 |
+
"import re\n",
|
| 443 |
+
"import zipfile\n",
|
| 444 |
+
"from pathlib import Path\n",
|
| 445 |
+
"from tqdm.auto import tqdm\n",
|
| 446 |
+
"\n",
|
| 447 |
+
"# ============================================================\n",
|
| 448 |
+
"# Paths\n",
|
| 449 |
+
"# ============================================================\n",
|
| 450 |
+
"txt_dir = Path(\"/content/output/js_files\")\n",
|
| 451 |
+
"zip_path = \"/content/js_files.zip\" # ← final zip now saved directly to /content/\n",
|
| 452 |
+
"\n",
|
| 453 |
+
"if not txt_dir.exists():\n",
|
| 454 |
+
" raise FileNotFoundError(f\"Directory not found: {txt_dir}\")\n",
|
| 455 |
+
"\n",
|
| 456 |
+
"txt_files = sorted(txt_dir.glob(\"fusion-t2i-*.txt\"))\n",
|
| 457 |
+
"print(f\"Found {len(txt_files)} files to clean\")\n",
|
| 458 |
+
"\n",
|
| 459 |
+
"# ============================================================\n",
|
| 460 |
+
"# Cleaning function\n",
|
| 461 |
+
"# ============================================================\n",
|
| 462 |
+
"def clean_pipe_before_by(text: str) -> str:\n",
|
| 463 |
+
" \"\"\"\n",
|
| 464 |
+
" Remove the '|' that sits right before an artist credit starting with 'by '.\n",
|
| 465 |
+
" Examples:\n",
|
| 466 |
+
" \"... sweater | by hyde (tabakko)|1girl\"\n",
|
| 467 |
+
" → \"... sweater by hyde (tabakko)|1girl\"\n",
|
| 468 |
+
" \"\"\"\n",
|
| 469 |
+
" # Pattern: optional whitespace + | + optional whitespace + \"by \" (case-insensitive)\n",
|
| 470 |
+
" # We keep the \"by \" and just remove the preceding |\n",
|
| 471 |
+
" cleaned = re.sub(r'\\s*\\|\\s*(by\\s)', r' \\1', text, flags=re.IGNORECASE)\n",
|
| 472 |
+
"\n",
|
| 473 |
+
" # Also clean any double spaces that may have been created\n",
|
| 474 |
+
" cleaned = re.sub(r' {2,}', ' ', cleaned)\n",
|
| 475 |
+
"\n",
|
| 476 |
+
" return cleaned\n",
|
| 477 |
+
"\n",
|
| 478 |
+
"# ============================================================\n",
|
| 479 |
+
"# Process every file\n",
|
| 480 |
+
"# ============================================================\n",
|
| 481 |
+
"cleaned_count = 0\n",
|
| 482 |
+
"\n",
|
| 483 |
+
"for txt_path in tqdm(txt_files, desc=\"Cleaning files\"):\n",
|
| 484 |
+
" original = txt_path.read_text(encoding=\"utf-8\")\n",
|
| 485 |
+
" cleaned = clean_pipe_before_by(original)\n",
|
| 486 |
+
"\n",
|
| 487 |
+
" if cleaned != original:\n",
|
| 488 |
+
" txt_path.write_text(cleaned, encoding=\"utf-8\")\n",
|
| 489 |
+
" cleaned_count += 1\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"print(f\"\\n✅ Cleaned {cleaned_count} files (others already clean)\")\n",
|
| 492 |
+
"\n",
|
| 493 |
+
"# ============================================================\n",
|
| 494 |
+
"# Re-create the ZIP with the cleaned files → saved to /content/\n",
|
| 495 |
+
"# ============================================================\n",
|
| 496 |
+
"with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zipf:\n",
|
| 497 |
+
" for txt_path in sorted(txt_dir.glob(\"fusion-t2i-*.txt\")):\n",
|
| 498 |
+
" zipf.write(txt_path, arcname=txt_path.name)\n",
|
| 499 |
+
"\n",
|
| 500 |
+
"print(f\"✅ Updated ZIP created: {zip_path}\")\n",
|
| 501 |
+
"print(f\" Contains {len(list(txt_dir.glob('fusion-t2i-*.txt')))} files\")"
|
| 502 |
+
],
|
| 503 |
+
"metadata": {
|
| 504 |
+
"id": "gtoiWXwEBHP4"
|
| 505 |
+
},
|
| 506 |
+
"execution_count": null,
|
| 507 |
+
"outputs": []
|
| 508 |
+
}
|
| 509 |
+
]
|
| 510 |
+
}
|