File size: 17,568 Bytes
7829f38 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | #!/usr/bin/env python3
"""HuggingFace Danbooru metadata -> normalized SQLite3 builder."""
from __future__ import annotations
import argparse
import json
import shutil
import sqlite3
from pathlib import Path
import pyarrow.parquet as pq
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
DEFAULT_REPO_ID = "trojblue/danbooru2025-metadata"
DEFAULT_CACHE_DIR = Path.home() / "Downloads" / "pixiv_spider_hf_probe"
POST_COLS = [
"id", "pixiv_id", "source", "rating", "score", "fav_count",
"image_width", "image_height", "file_size", "file_ext",
"md5", "file_url", "created_at", "updated_at", "uploader_id", "parent_id",
]
TAG_COLS = {
"tag_string_artist": "artist",
"tag_string_character": "character",
"tag_string_copyright": "copyright",
"tag_string_general": "general",
"tag_string_meta": "meta",
}
REQUIRED_COLS = POST_COLS + list(TAG_COLS.keys())
ALLOWED_RATINGS = {"g", "s", "q", "e"}
DROP_POLICY = {
"tag_string": "redundant with typed tag_string_* columns",
"tag_count*": "derivable from normalized post_tags",
"up_score/down_score": "single score column is enough for core ranking",
"large_file_url/preview_file_url/has_large": "variant URLs omitted in minimal schema",
"approver_id": "moderation detail omitted in minimal schema",
"has_*children": "not needed for core queries",
"is_pending/is_flagged/is_deleted/is_banned": "status flags omitted in minimal schema",
"last_*": "comment/note activity timestamps omitted in minimal schema",
"bit_flags": "bitmask omitted in minimal schema",
"media_asset_*": "media internals omitted in minimal schema",
}
PROJECT_ROOT = Path(__file__).resolve().parent
PROTECTED_DB = (PROJECT_ROOT / "danbooru.db").resolve()
class ConverterError(RuntimeError):
pass
def parse_tags(value: object) -> list[str]:
if value is None:
return []
return [x for x in str(value).strip().split() if x]
def to_nullable_int(value: object) -> int | None:
if value is None:
return None
if isinstance(value, float):
if value != value:
return None
return int(value)
if isinstance(value, int):
return value
text = str(value).strip()
if not text:
return None
return int(float(text))
def init_db(conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=OFF")
conn.execute("PRAGMA cache_size=-1048576")
conn.execute(
"""
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
pixiv_id INTEGER,
source TEXT,
rating TEXT,
score INTEGER,
fav_count INTEGER,
image_width INTEGER,
image_height INTEGER,
file_size INTEGER,
file_ext TEXT,
md5 TEXT,
file_url TEXT,
created_at TEXT,
updated_at TEXT,
uploader_id INTEGER,
parent_id INTEGER
)
"""
)
conn.execute(
"""
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT,
type TEXT,
UNIQUE(name, type)
)
"""
)
conn.execute(
"""
CREATE TABLE post_tags (
post_id INTEGER REFERENCES posts(id),
tag_id INTEGER REFERENCES tags(id),
PRIMARY KEY (post_id, tag_id)
) WITHOUT ROWID
"""
)
def build_indexes(conn: sqlite3.Connection) -> None:
conn.execute("CREATE INDEX idx_posts_pixiv_id ON posts(pixiv_id)")
conn.execute("CREATE INDEX idx_posts_source ON posts(source)")
conn.execute("CREATE INDEX idx_posts_rating ON posts(rating)")
conn.execute("CREATE INDEX idx_posts_score ON posts(score)")
conn.execute("CREATE INDEX idx_posts_created_at ON posts(created_at)")
conn.execute("CREATE INDEX idx_posts_md5 ON posts(md5)")
conn.execute("CREATE INDEX idx_posts_parent_id ON posts(parent_id)")
conn.execute("CREATE INDEX idx_tags_name_type ON tags(name, type)")
conn.execute("CREATE INDEX idx_tags_type ON tags(type)")
conn.execute("CREATE INDEX idx_post_tags_tag_id ON post_tags(tag_id)")
conn.commit()
def validate_output_path(output_db: Path, overwrite: bool) -> None:
output_db = output_db.resolve()
if output_db == PROTECTED_DB:
raise ConverterError(
f"Refusing to write protected DB path: {output_db}"
)
if output_db.exists() and not overwrite:
raise ConverterError(
f"Output DB already exists: {output_db} (pass --overwrite-candidate to replace)"
)
def list_repo_parquet_files(repo_id: str) -> tuple[dict, list[str]]:
api = HfApi()
info = api.dataset_info(repo_id=repo_id, files_metadata=True)
files = []
for sibling in info.siblings or []:
name = sibling.rfilename
if name.endswith(".parquet") and name.startswith("data/"):
files.append(name)
if not files:
raise ConverterError(f"No Parquet files under data/ in dataset {repo_id}")
card_data = getattr(info, "card_data", None) or getattr(info, "cardData", None) or {}
last_modified = getattr(info, "last_modified", None) or getattr(info, "lastModified", None)
meta = {
"repo_id": repo_id,
"private": bool(getattr(info, "private", False)),
"gated": getattr(info, "gated", None),
"sha": getattr(info, "sha", None),
"last_modified": str(last_modified) if last_modified is not None else None,
"card_license": card_data.get("license"),
"parquet_file_count": len(files),
}
return meta, sorted(files)
def download_sample_parquet(repo_id: str, parquet_files: list[str], cache_dir: Path, sample_count: int = 2) -> list[Path]:
cache_dir.mkdir(parents=True, exist_ok=True)
out = []
for name in parquet_files[:sample_count]:
local = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=name,
local_dir=str(cache_dir),
)
out.append(Path(local))
return out
def inspect_parquet_schema(parquet_file: Path) -> list[dict[str, str]]:
schema = pq.ParquetFile(parquet_file).schema_arrow
return [{"name": field.name, "type": str(field.type)} for field in schema]
def validate_required_columns(parquet_file: Path) -> tuple[list[str], list[str]]:
schema_names = set(pq.ParquetFile(parquet_file).schema_arrow.names)
missing = [c for c in REQUIRED_COLS if c not in schema_names]
return sorted(schema_names), missing
def inspect_sample_stats(parquet_file: Path, max_rows: int = 5000) -> dict:
table = pq.read_table(parquet_file, columns=[
"id", "pixiv_id", "parent_id", "source", "rating", "file_url", "md5",
"tag_string_artist", "tag_string_character", "tag_string_copyright",
"tag_string_general", "tag_string_meta",
])
if table.num_rows > max_rows:
table = table.slice(0, max_rows)
data = table.to_pydict()
n = len(data["id"])
rating_counts: dict[str, int] = {}
invalid_ratings = 0
pixiv_non_null = 0
parent_non_null = 0
source_non_null = 0
file_url_non_null = 0
md5_non_null = 0
tag_non_empty = {k: 0 for k in TAG_COLS}
for i in range(n):
r = data["rating"][i]
if r is not None:
rating_counts[str(r)] = rating_counts.get(str(r), 0) + 1
if str(r) not in ALLOWED_RATINGS:
invalid_ratings += 1
if data["pixiv_id"][i] is not None:
pixiv_non_null += 1
if data["parent_id"][i] is not None:
parent_non_null += 1
if data["source"][i]:
source_non_null += 1
if data["file_url"][i]:
file_url_non_null += 1
if data["md5"][i]:
md5_non_null += 1
for col in TAG_COLS:
if parse_tags(data[col][i]):
tag_non_empty[col] += 1
return {
"sample_rows": n,
"rating_counts": rating_counts,
"invalid_rating_rows": invalid_ratings,
"pixiv_non_null": pixiv_non_null,
"parent_non_null": parent_non_null,
"source_non_null": source_non_null,
"file_url_non_null": file_url_non_null,
"md5_non_null": md5_non_null,
"tag_non_empty_rows": tag_non_empty,
}
def snapshot_parquet_paths(repo_id: str, cache_dir: Path) -> list[Path]:
cache_dir.mkdir(parents=True, exist_ok=True)
local_dir = snapshot_download(
repo_id=repo_id,
repo_type="dataset",
local_dir=str(cache_dir),
allow_patterns=["data/*.parquet", "README.md", "*.json"],
)
data_dir = Path(local_dir) / "data"
files = sorted(data_dir.glob("*.parquet"))
if not files:
raise ConverterError(f"No parquet files found after snapshot_download at {data_dir}")
return files
def iter_local_parquet(local_parquet_dir: Path) -> list[Path]:
files = sorted(local_parquet_dir.glob("train-*.parquet"))
if not files:
files = sorted(local_parquet_dir.glob("*.parquet"))
if not files:
raise ConverterError(f"No parquet files found in {local_parquet_dir}")
return files
def build_db(parquet_files: list[Path], output_db: Path, batch_size: int) -> dict:
building_path = output_db.with_suffix(output_db.suffix + ".building")
if building_path.exists():
building_path.unlink()
conn = sqlite3.connect(building_path)
init_db(conn)
insert_posts_sql = (
"INSERT OR IGNORE INTO posts VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insert_tags_sql = "INSERT OR IGNORE INTO tags VALUES (?,?,?)"
insert_post_tags_sql = "INSERT OR IGNORE INTO post_tags VALUES (?,?)"
tag_cache: dict[tuple[str, str], int] = {}
next_tag_id = 1
posts_total = 0
post_tags_total = 0
for idx, file in enumerate(parquet_files, start=1):
pf = pq.ParquetFile(file)
file_posts = 0
for batch in pf.iter_batches(batch_size=batch_size, columns=REQUIRED_COLS):
data = batch.to_pydict()
nrows = len(data["id"])
post_rows = []
for i in range(nrows):
row = []
for col in POST_COLS:
value = data[col][i]
if col in {"pixiv_id", "parent_id"}:
value = to_nullable_int(value)
row.append(value)
post_rows.append(tuple(row))
conn.executemany(insert_posts_sql, post_rows)
tag_rows = []
post_tag_rows = []
for i in range(nrows):
post_id = data["id"][i]
for col, ttype in TAG_COLS.items():
for tag_name in parse_tags(data[col][i]):
key = (tag_name, ttype)
tag_id = tag_cache.get(key)
if tag_id is None:
tag_id = next_tag_id
next_tag_id += 1
tag_cache[key] = tag_id
tag_rows.append((tag_id, tag_name, ttype))
post_tag_rows.append((post_id, tag_id))
if tag_rows:
conn.executemany(insert_tags_sql, tag_rows)
if post_tag_rows:
conn.executemany(insert_post_tags_sql, post_tag_rows)
conn.commit()
posts_total += nrows
file_posts += nrows
post_tags_total += len(post_tag_rows)
print(f"[{idx}/{len(parquet_files)}] {file.name}: {file_posts:,} rows")
build_indexes(conn)
tag_count = conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0]
post_count = conn.execute("SELECT COUNT(*) FROM posts").fetchone()[0]
post_tag_count = conn.execute("SELECT COUNT(*) FROM post_tags").fetchone()[0]
conn.close()
if output_db.exists():
output_db.unlink()
building_path.rename(output_db)
return {
"posts_inserted_rows": posts_total,
"post_tags_inserted_rows": post_tags_total,
"posts_count": post_count,
"tags_count": tag_count,
"post_tags_count": post_tag_count,
"output_db": str(output_db),
}
def validate_built_db(output_db: Path) -> dict:
conn = sqlite3.connect(output_db)
posts = conn.execute("SELECT COUNT(*) FROM posts").fetchone()[0]
tags = conn.execute("SELECT COUNT(*) FROM tags").fetchone()[0]
post_tags = conn.execute("SELECT COUNT(*) FROM post_tags").fetchone()[0]
rating_rows = conn.execute(
"SELECT rating, COUNT(*) FROM posts GROUP BY rating ORDER BY rating"
).fetchall()
rating_dist = {str(r): c for r, c in rating_rows}
pixiv_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE pixiv_id IS NOT NULL"
).fetchone()[0]
source_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE source IS NOT NULL AND source <> ''"
).fetchone()[0]
md5_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE md5 IS NOT NULL AND md5 <> ''"
).fetchone()[0]
parent_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE parent_id IS NOT NULL"
).fetchone()[0]
broken_pt_post = conn.execute(
"SELECT COUNT(*) FROM post_tags pt LEFT JOIN posts p ON p.id = pt.post_id WHERE p.id IS NULL"
).fetchone()[0]
broken_pt_tag = conn.execute(
"SELECT COUNT(*) FROM post_tags pt LEFT JOIN tags t ON t.id = pt.tag_id WHERE t.id IS NULL"
).fetchone()[0]
conn.close()
return {
"posts": posts,
"tags": tags,
"post_tags": post_tags,
"rating_distribution": rating_dist,
"pixiv_non_null": pixiv_non_null,
"source_non_null": source_non_null,
"md5_non_null": md5_non_null,
"parent_non_null": parent_non_null,
"broken_post_tags_post_ref": broken_pt_post,
"broken_post_tags_tag_ref": broken_pt_tag,
}
def ensure_disk_space(target_path: Path, required_gb: int = 20) -> None:
usage = shutil.disk_usage(target_path.parent)
free_gb = usage.free / (1024 ** 3)
if free_gb < required_gb:
raise ConverterError(
f"Insufficient free space in {target_path.parent}: {free_gb:.2f}GB < required {required_gb}GB"
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-id", default=DEFAULT_REPO_ID)
parser.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE_DIR)
parser.add_argument("--output-db", type=Path, default=PROJECT_ROOT / "danbooru2025_candidate.db")
parser.add_argument("--inspect-only", action="store_true")
parser.add_argument("--limit-files", type=int, default=0)
parser.add_argument("--overwrite-candidate", action="store_true")
parser.add_argument("--local-parquet-dir", type=Path)
parser.add_argument("--batch-size", type=int, default=50000)
parser.add_argument("--json", action="store_true", help="print machine-readable JSON summary")
return parser.parse_args()
def main() -> None:
args = parse_args()
meta, repo_parquet_files = list_repo_parquet_files(args.repo_id)
sample_files = download_sample_parquet(
repo_id=args.repo_id,
parquet_files=repo_parquet_files,
cache_dir=args.cache_dir,
sample_count=2,
)
sample_schema = inspect_parquet_schema(sample_files[0])
schema_names, missing = validate_required_columns(sample_files[0])
sample_stats = inspect_sample_stats(sample_files[0])
summary = {
"dataset": meta,
"sample_file": str(sample_files[0]),
"sample_schema_column_count": len(schema_names),
"sample_schema": sample_schema,
"kept_post_columns": POST_COLS,
"normalized_tag_columns": list(TAG_COLS.keys()),
"drop_policy": DROP_POLICY,
"sample_missing_required_columns": missing,
"sample_stats": sample_stats,
}
if missing:
raise ConverterError(f"Missing required columns: {missing}")
if args.inspect_only:
if args.json:
print(json.dumps(summary, ensure_ascii=False, indent=2))
else:
print("Inspection summary:")
print(json.dumps(summary, ensure_ascii=False, indent=2))
return
output_db = args.output_db.resolve()
validate_output_path(output_db, overwrite=args.overwrite_candidate)
ensure_disk_space(output_db, required_gb=20)
if args.local_parquet_dir:
parquet_files = iter_local_parquet(args.local_parquet_dir.resolve())
else:
parquet_files = snapshot_parquet_paths(args.repo_id, args.cache_dir)
if args.limit_files > 0:
parquet_files = parquet_files[: args.limit_files]
if not parquet_files:
raise ConverterError("No parquet files selected for conversion")
build_summary = build_db(parquet_files, output_db=output_db, batch_size=args.batch_size)
db_summary = validate_built_db(output_db)
summary["build"] = build_summary
summary["candidate_db_validation"] = db_summary
if args.json:
print(json.dumps(summary, ensure_ascii=False, indent=2))
else:
print("Build summary:")
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
try:
main()
except ConverterError as exc:
raise SystemExit(f"error: {exc}")
|