booru-quality-80-union-db / scripts /convert_gelbooru.py
LeeMirror013's picture
Super-squash dataset history to drop stale LFS objects
7829f38
#!/usr/bin/env python3
"""HuggingFace Gelbooru metadata parquet -> 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
DEFAULT_REPO_ID = "AngelBottomless/Booru-Parquets"
DEFAULT_PARQUET_FILE = "gelbooru.parquet"
PROJECT_ROOT = Path(__file__).resolve().parent
DEFAULT_DOWNLOAD_DIR = PROJECT_ROOT / "gelbooru_meta"
DEFAULT_OUTPUT_DB = PROJECT_ROOT / "gelbooru.db"
SOURCE_POST_COLS = [
"id",
"created_at",
"score",
"width",
"height",
"md5",
"directory",
"image",
"rating",
"source",
"change",
"owner",
"creator_id",
"parent_id",
"sample",
"preview_height",
"preview_width",
"tags",
"title",
"has_notes",
"has_comments",
"file_url",
"preview_url",
"sample_url",
"sample_height",
"sample_width",
"status",
"post_locked",
"has_children",
"@attributes.limit",
"@attributes.offset",
"@attributes.count",
]
DB_POST_COLS = [
"id",
"created_at",
"score",
"width",
"height",
"md5",
"directory",
"image",
"rating",
"source",
"change",
"owner",
"creator_id",
"parent_id",
"sample",
"preview_height",
"preview_width",
"tags",
"title",
"has_notes",
"has_comments",
"file_url",
"preview_url",
"sample_url",
"sample_height",
"sample_width",
"status",
"post_locked",
"has_children",
"attr_limit",
"attr_offset",
"attr_count",
]
SOURCE_TO_DB_COL = dict(zip(SOURCE_POST_COLS, DB_POST_COLS, strict=True))
class ConverterError(RuntimeError):
pass
def parse_tags(value: object) -> list[str]:
if value is None:
return []
seen = set()
tags = []
for tag in str(value).strip().split():
if tag and tag not in seen:
seen.add(tag)
tags.append(tag)
return tags
def to_nullable_int(value: object, *, zero_is_null: bool = False) -> int | None:
if value is None:
return None
if isinstance(value, float):
if value != value:
return None
out = int(value)
elif isinstance(value, int):
out = value
else:
text = str(value).strip()
if not text:
return None
out = int(float(text))
if zero_is_null and out == 0:
return None
return out
def to_nullable_text(value: object) -> str | None:
if value is None:
return None
text = str(value)
return text if text else None
def to_bool_int(value: object) -> int | None:
if value is None:
return None
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
if isinstance(value, float) and value != value:
return None
return int(bool(value))
text = str(value).strip().lower()
if not text:
return None
if text in {"true", "1", "yes"}:
return 1
if text in {"false", "0", "no"}:
return 0
raise ConverterError(f"Cannot coerce boolean value: {value!r}")
def normalize_post_row(data: dict[str, list], index: int) -> tuple:
row = []
for source_col in SOURCE_POST_COLS:
value = data[source_col][index]
db_col = SOURCE_TO_DB_COL[source_col]
if db_col in {
"id",
"score",
"width",
"height",
"change",
"creator_id",
"sample",
"preview_height",
"preview_width",
"sample_height",
"sample_width",
"post_locked",
"attr_limit",
"attr_offset",
"attr_count",
}:
value = to_nullable_int(value)
elif db_col == "parent_id":
value = to_nullable_int(value, zero_is_null=True)
elif db_col in {"has_notes", "has_comments", "has_children"}:
value = to_bool_int(value)
else:
value = to_nullable_text(value)
row.append(value)
return tuple(row)
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,
created_at TEXT,
score INTEGER,
width INTEGER,
height INTEGER,
md5 TEXT,
directory TEXT,
image TEXT,
rating TEXT,
source TEXT,
change INTEGER,
owner TEXT,
creator_id INTEGER,
parent_id INTEGER,
sample INTEGER,
preview_height INTEGER,
preview_width INTEGER,
tags TEXT,
title TEXT,
has_notes INTEGER,
has_comments INTEGER,
file_url TEXT,
preview_url TEXT,
sample_url TEXT,
sample_height INTEGER,
sample_width INTEGER,
status TEXT,
post_locked INTEGER,
has_children INTEGER,
attr_limit INTEGER,
attr_offset INTEGER,
attr_count INTEGER
)
"""
)
conn.execute(
"""
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE
)
"""
)
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_md5 ON posts(md5)")
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_parent_id ON posts(parent_id)")
conn.execute("CREATE INDEX idx_posts_creator_id ON posts(creator_id)")
conn.execute("CREATE INDEX idx_posts_status ON posts(status)")
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.exists() and not overwrite:
raise ConverterError(f"Output DB already exists: {output_db} (pass --overwrite to replace)")
def ensure_disk_space(target_path: Path, required_gb: int = 30) -> 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 dataset_meta(repo_id: str, parquet_file: str) -> dict:
info = HfApi().dataset_info(repo_id=repo_id, files_metadata=True)
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)
siblings = getattr(info, "siblings", None) or []
file_info = next((s for s in siblings if getattr(s, "rfilename", None) == parquet_file), None)
if file_info is None:
raise ConverterError(f"Cannot find {parquet_file} in dataset {repo_id}")
return {
"repo_id": repo_id,
"parquet_file": parquet_file,
"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_size": getattr(file_info, "size", None),
}
def download_parquet(repo_id: str, parquet_file: str, download_dir: Path) -> Path:
download_dir.mkdir(parents=True, exist_ok=True)
local = hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
filename=parquet_file,
local_dir=str(download_dir),
)
return Path(local)
def inspect_parquet(parquet_file: Path) -> dict:
pf = pq.ParquetFile(parquet_file)
schema = pf.schema_arrow
return {
"rows": pf.metadata.num_rows,
"row_groups": pf.metadata.num_row_groups,
"schema_column_count": len(schema.names),
"schema": [{"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 = [col for col in SOURCE_POST_COLS if col not in schema_names]
return sorted(schema_names), missing
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 = f"INSERT OR IGNORE INTO posts VALUES ({','.join(['?'] * len(DB_POST_COLS))})"
insert_tags_sql = "INSERT OR IGNORE INTO tags VALUES (?,?)"
insert_post_tags_sql = "INSERT OR IGNORE INTO post_tags VALUES (?,?)"
tag_cache: dict[str, int] = {}
next_tag_id = 1
source_rows = 0
valid_source_rows = 0
skipped_missing_id_rows = 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=SOURCE_POST_COLS):
data = batch.to_pydict()
nrows = len(data["id"])
valid_indexes = [i for i in range(nrows) if data["id"][i] is not None]
skipped_missing_id_rows += nrows - len(valid_indexes)
post_rows = [normalize_post_row(data, i) for i in valid_indexes]
conn.executemany(insert_posts_sql, post_rows)
tag_rows = []
post_tag_rows = []
for i in valid_indexes:
post_id = to_nullable_int(data["id"][i])
for tag_name in parse_tags(data["tags"][i]):
tag_id = tag_cache.get(tag_name)
if tag_id is None:
tag_id = next_tag_id
next_tag_id += 1
tag_cache[tag_name] = tag_id
tag_rows.append((tag_id, tag_name))
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()
source_rows += nrows
valid_source_rows += len(valid_indexes)
file_posts += len(valid_indexes)
post_tags_total += len(post_tag_rows)
print(f"[{idx}/{len(parquet_files)}] {file.name}: {file_posts:,} valid rows")
build_indexes(conn)
post_count = conn.execute("SELECT COUNT(*) FROM posts").fetchone()[0]
tag_count = conn.execute("SELECT COUNT(*) FROM tags").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 {
"source_rows": source_rows,
"valid_source_rows": valid_source_rows,
"skipped_missing_id_rows": skipped_missing_id_rows,
"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, expected_posts: int | None = None, *, check_references: bool = False
) -> 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]
columns = [row[1] for row in conn.execute("PRAGMA table_info(posts)").fetchall()]
missing_columns = [col for col in DB_POST_COLS if col not in columns]
broken_pt_post = None
broken_pt_tag = None
if check_references:
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]
md5_non_null = conn.execute("SELECT COUNT(*) FROM posts WHERE md5 IS NOT NULL AND md5 <> ''").fetchone()[0]
source_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE source IS NOT NULL AND source <> ''"
).fetchone()[0]
file_url_non_null = conn.execute(
"SELECT COUNT(*) FROM posts WHERE file_url IS NOT NULL AND file_url <> ''"
).fetchone()[0]
tag_text_non_null = conn.execute("SELECT COUNT(*) FROM posts WHERE tags IS NOT NULL AND tags <> ''").fetchone()[0]
sample_rows = conn.execute(
"SELECT id, rating, md5, source FROM posts ORDER BY id DESC LIMIT 5"
).fetchall()
conn.close()
if expected_posts is not None and posts != expected_posts:
raise ConverterError(f"posts count mismatch: db={posts} expected={expected_posts}")
if missing_columns:
raise ConverterError(f"missing DB columns: {missing_columns}")
if check_references and (broken_pt_post or broken_pt_tag):
raise ConverterError(
f"broken post_tags refs: posts={broken_pt_post}, tags={broken_pt_tag}"
)
return {
"posts": posts,
"tags": tags,
"post_tags": post_tags,
"missing_columns": missing_columns,
"broken_post_tags_post_ref": broken_pt_post,
"broken_post_tags_tag_ref": broken_pt_tag,
"md5_non_null": md5_non_null,
"source_non_null": source_non_null,
"file_url_non_null": file_url_non_null,
"tag_text_non_null": tag_text_non_null,
"sample_rows": sample_rows,
}
def cleanup_parquet(parquet_path: Path, download_dir: Path) -> None:
if parquet_path.exists():
parquet_path.unlink()
try:
download_dir.rmdir()
except OSError:
pass
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-id", default=DEFAULT_REPO_ID)
parser.add_argument("--parquet-file", default=DEFAULT_PARQUET_FILE)
parser.add_argument("--download-dir", type=Path, default=DEFAULT_DOWNLOAD_DIR)
parser.add_argument("--output-db", type=Path, default=DEFAULT_OUTPUT_DB)
parser.add_argument("--inspect-only", action="store_true")
parser.add_argument("--download-only", action="store_true")
parser.add_argument("--keep-parquet", action="store_true")
parser.add_argument("--check-references", action="store_true")
parser.add_argument("--overwrite", action="store_true")
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 = dataset_meta(args.repo_id, args.parquet_file)
parquet_path = download_parquet(args.repo_id, args.parquet_file, args.download_dir)
parquet_info = inspect_parquet(parquet_path)
schema_names, missing = validate_required_columns(parquet_path)
summary = {
"dataset": meta,
"local_parquet": str(parquet_path),
"parquet": parquet_info,
"required_columns": SOURCE_POST_COLS,
"db_columns": DB_POST_COLS,
"missing_required_columns": missing,
}
if missing:
raise ConverterError(f"Missing required columns: {missing}")
if args.inspect_only or args.download_only:
if args.json:
print(json.dumps(summary, ensure_ascii=False, indent=2))
else:
print(json.dumps(summary, ensure_ascii=False, indent=2))
return
output_db = args.output_db.resolve()
validate_output_path(output_db, overwrite=args.overwrite)
ensure_disk_space(output_db, required_gb=30)
build_summary = build_db([parquet_path], output_db=output_db, batch_size=args.batch_size)
db_summary = validate_built_db(
output_db,
expected_posts=build_summary["valid_source_rows"],
check_references=args.check_references,
)
summary["build"] = build_summary
summary["db_validation"] = db_summary
if not args.keep_parquet:
cleanup_parquet(parquet_path, args.download_dir)
summary["parquet_removed"] = not parquet_path.exists()
if args.json:
print(json.dumps(summary, ensure_ascii=False, indent=2))
else:
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
try:
main()
except ConverterError as exc:
raise SystemExit(f"error: {exc}")