| |
| """Build a de-duplicated 80th-percentile quality image union DB.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| from collections import Counter |
| import json |
| import sqlite3 |
| from pathlib import Path |
|
|
|
|
| PROJECT_ROOT = Path(__file__).resolve().parent |
| DEFAULT_GELBOORU_DB = PROJECT_ROOT / "gelbooru.db" |
| DEFAULT_DANBOORU_DB = PROJECT_ROOT / "danbooru2025_candidate.db" |
| DEFAULT_OUTPUT_DB = PROJECT_ROOT / "quality_80_union.db" |
|
|
| GEL_THRESHOLDS = { |
| "sensitive": 17, |
| "explicit": 125, |
| "general": 6, |
| "questionable": 61, |
| "safe": 22, |
| } |
| DAN_THRESHOLDS = { |
| "s": 31, |
| "g": 16, |
| "q": 70, |
| "e": 110, |
| } |
| RATING_RANK = { |
| "safe": 0, |
| "general": 0, |
| "sensitive": 1, |
| "questionable": 2, |
| "explicit": 3, |
| } |
|
|
|
|
| class BuildError(RuntimeError): |
| pass |
|
|
|
|
| def dan_rating_name(value: str | None) -> str | None: |
| return {"g": "general", "s": "sensitive", "q": "questionable", "e": "explicit"}.get(value, value) |
|
|
|
|
| def stricter_rating(left: str | None, right: str | None) -> str | None: |
| if left is None: |
| return right |
| if right is None: |
| return left |
| return left if RATING_RANK.get(left, -1) >= RATING_RANK.get(right, -1) else right |
|
|
|
|
| def validate_output_path(output_db: Path, overwrite: bool) -> None: |
| if output_db.exists() and not overwrite: |
| raise BuildError(f"Output DB already exists: {output_db} (pass --overwrite to replace)") |
|
|
|
|
| def register_functions(conn: sqlite3.Connection) -> None: |
| conn.create_function("dan_rating_name", 1, dan_rating_name) |
| conn.create_function("stricter_rating", 2, stricter_rating) |
|
|
|
|
| def create_schema(conn: sqlite3.Connection) -> None: |
| conn.executescript( |
| """ |
| PRAGMA journal_mode=WAL; |
| PRAGMA synchronous=OFF; |
| PRAGMA cache_size=-1048576; |
| |
| CREATE TABLE selected_md5 ( |
| md5 TEXT PRIMARY KEY, |
| selected_by_gelbooru80 INTEGER NOT NULL DEFAULT 0, |
| selected_by_danbooru80 INTEGER NOT NULL DEFAULT 0 |
| ); |
| |
| CREATE TABLE selected_gelbooru_posts ( |
| post_id INTEGER PRIMARY KEY, |
| md5 TEXT NOT NULL |
| ); |
| |
| CREATE TABLE selected_danbooru_posts ( |
| post_id INTEGER PRIMARY KEY, |
| md5 TEXT NOT NULL |
| ); |
| |
| CREATE TABLE images ( |
| md5 TEXT PRIMARY KEY, |
| canonical_rating TEXT, |
| canonical_file_url TEXT, |
| canonical_preview_url TEXT, |
| canonical_sample_url TEXT, |
| canonical_source TEXT, |
| canonical_width INTEGER, |
| canonical_height INTEGER, |
| present_in_gelbooru INTEGER NOT NULL, |
| present_in_danbooru INTEGER NOT NULL, |
| selected_by_gelbooru80 INTEGER NOT NULL, |
| selected_by_danbooru80 INTEGER NOT NULL, |
| quality_score REAL, |
| quality_tier TEXT NOT NULL, |
| gelbooru_id INTEGER, |
| gelbooru_rating TEXT, |
| gelbooru_score INTEGER, |
| gelbooru_score_pct REAL, |
| gelbooru_file_url TEXT, |
| gelbooru_preview_url TEXT, |
| gelbooru_sample_url TEXT, |
| gelbooru_source TEXT, |
| gelbooru_tags_text TEXT, |
| gelbooru_status TEXT, |
| danbooru_id INTEGER, |
| danbooru_rating TEXT, |
| danbooru_score INTEGER, |
| danbooru_score_pct REAL, |
| danbooru_file_url TEXT, |
| danbooru_source TEXT, |
| danbooru_pixiv_id INTEGER, |
| danbooru_fav_count INTEGER, |
| danbooru_file_size INTEGER, |
| danbooru_file_ext TEXT, |
| image_parquet_file TEXT |
| ); |
| |
| CREATE TABLE gelbooru_image_tags ( |
| md5 TEXT NOT NULL REFERENCES images(md5), |
| tag_name TEXT NOT NULL, |
| PRIMARY KEY (md5, tag_name) |
| ) WITHOUT ROWID; |
| |
| CREATE TABLE danbooru_image_tags ( |
| md5 TEXT NOT NULL REFERENCES images(md5), |
| tag_name TEXT NOT NULL, |
| tag_type TEXT NOT NULL, |
| PRIMARY KEY (md5, tag_name, tag_type) |
| ) WITHOUT ROWID; |
| |
| CREATE TABLE build_metadata ( |
| key TEXT PRIMARY KEY, |
| value TEXT |
| ); |
| |
| CREATE TABLE gel_score_percentiles ( |
| rating TEXT NOT NULL, |
| score INTEGER NOT NULL, |
| pct REAL NOT NULL, |
| PRIMARY KEY (rating, score) |
| ) WITHOUT ROWID; |
| |
| CREATE TABLE dan_score_percentiles ( |
| rating TEXT NOT NULL, |
| score INTEGER NOT NULL, |
| pct REAL NOT NULL, |
| PRIMARY KEY (rating, score) |
| ) WITHOUT ROWID; |
| """ |
| ) |
|
|
|
|
| TAG_BATCH_SIZE = 50000 |
| PERCENTILE_INSERT_BATCH_SIZE = 5000 |
|
|
|
|
| def _identity_rating(value: str | None) -> str | None: |
| return value |
|
|
|
|
| def _score_percentile_rows(histogram: dict[str, Counter[int]]) -> list[tuple[str, int, float]]: |
| rows: list[tuple[str, int, float]] = [] |
| for rating, counts in histogram.items(): |
| total = sum(counts.values()) |
| cumulative = 0 |
| for score in sorted(counts): |
| cumulative += counts[score] |
| rows.append((rating, score, cumulative / total)) |
| return rows |
|
|
|
|
| def _populate_score_percentiles( |
| conn: sqlite3.Connection, |
| source_db_alias: str, |
| dest_table: str, |
| normalize_rating, |
| ) -> int: |
| """Build cume_dist score lookup with O(unique scores) memory.""" |
| histogram: dict[str, Counter[int]] = {} |
| cursor = conn.execute( |
| f""" |
| SELECT rating, score |
| FROM {source_db_alias}.posts |
| WHERE md5 IS NOT NULL AND md5 <> '' |
| AND score IS NOT NULL |
| """ |
| ) |
| for raw_rating, score in cursor: |
| rating = normalize_rating(raw_rating) |
| if rating is None: |
| continue |
| histogram.setdefault(rating, Counter())[int(score)] += 1 |
|
|
| rows = _score_percentile_rows(histogram) |
| conn.executemany( |
| f"INSERT INTO {dest_table}(rating, score, pct) VALUES (?, ?, ?)", |
| rows, |
| ) |
| conn.commit() |
| return len(rows) |
|
|
|
|
| def _batch_insert_tags( |
| conn: sqlite3.Connection, |
| src_posts_table: str, |
| dest_table: str, |
| dest_cols: str, |
| src_db_alias: str, |
| ) -> int: |
| """Insert tags for selected posts in batches, committing per batch.""" |
| post_count = conn.execute( |
| f"SELECT COUNT(*) FROM {src_posts_table}" |
| ).fetchone()[0] |
| total = 0 |
| offset = 0 |
| batch = 0 |
| tag_type_col = ", t.type" if ", tag_type" in dest_cols else "" |
| while offset < post_count: |
| batch += 1 |
| before_changes = conn.total_changes |
| conn.execute( |
| f""" |
| INSERT OR IGNORE INTO {dest_table}({dest_cols}) |
| SELECT p.md5, t.name{tag_type_col} |
| FROM ( |
| SELECT post_id, md5 FROM {src_posts_table} |
| LIMIT {TAG_BATCH_SIZE} OFFSET {offset} |
| ) p |
| CROSS JOIN {src_db_alias}.post_tags pt ON pt.post_id = p.post_id |
| JOIN {src_db_alias}.tags t ON t.id = pt.tag_id |
| """ |
| ) |
| conn.commit() |
| total += conn.total_changes - before_changes |
| offset += TAG_BATCH_SIZE |
| if batch % 10 == 0 or offset >= post_count: |
| pct = min(100, offset * 100 // post_count) |
| print(f" [{src_db_alias}] tags batch {batch}: {offset:,}/{post_count:,} posts ({pct}%)") |
| return total |
|
|
|
|
| def build_quality_db(gelbooru_db: Path, danbooru_db: Path, output_db: Path, overwrite: bool) -> dict: |
| output_db = output_db.resolve() |
| validate_output_path(output_db, overwrite) |
| building_path = output_db.with_suffix(output_db.suffix + ".building") |
| if building_path.exists(): |
| building_path.unlink() |
| conn = sqlite3.connect(building_path) |
| register_functions(conn) |
| create_schema(conn) |
| conn.execute("ATTACH DATABASE ? AS g", (str(gelbooru_db),)) |
| conn.execute("ATTACH DATABASE ? AS d", (str(danbooru_db),)) |
|
|
| print("[1/7] Building rating-bucket score percentiles...") |
| gel_pct_rows = _populate_score_percentiles(conn, "g", "gel_score_percentiles", _identity_rating) |
| dan_pct_rows = _populate_score_percentiles(conn, "d", "dan_score_percentiles", dan_rating_name) |
| print(f" Gelbooru: {gel_pct_rows:,} score buckets, Danbooru: {dan_pct_rows:,} score buckets") |
|
|
| print("[2/7] Selecting md5 by 80th percentile thresholds...") |
| gel_count = conn.execute( |
| """ |
| INSERT INTO selected_md5(md5, selected_by_gelbooru80, selected_by_danbooru80) |
| SELECT md5, 1, 0 |
| FROM g.posts |
| WHERE md5 IS NOT NULL AND md5 <> '' |
| AND score >= CASE rating |
| WHEN 'sensitive' THEN 17 |
| WHEN 'explicit' THEN 125 |
| WHEN 'general' THEN 6 |
| WHEN 'questionable' THEN 61 |
| WHEN 'safe' THEN 22 |
| ELSE 999999999 |
| END |
| """ |
| ).rowcount |
| print(f" Gelbooru 80th: {gel_count:,} md5") |
|
|
| dan_count = conn.execute( |
| """ |
| INSERT INTO selected_md5(md5, selected_by_gelbooru80, selected_by_danbooru80) |
| SELECT md5, 0, 1 |
| FROM d.posts |
| WHERE md5 IS NOT NULL AND md5 <> '' |
| AND score >= CASE rating |
| WHEN 's' THEN 31 |
| WHEN 'g' THEN 16 |
| WHEN 'q' THEN 70 |
| WHEN 'e' THEN 110 |
| ELSE 999999999 |
| END |
| ON CONFLICT(md5) DO UPDATE SET selected_by_danbooru80 = 1 |
| """ |
| ).rowcount |
| union = conn.execute("SELECT COUNT(*) FROM selected_md5").fetchone()[0] |
| both = conn.execute( |
| "SELECT COUNT(*) FROM selected_md5 WHERE selected_by_gelbooru80=1 AND selected_by_danbooru80=1" |
| ).fetchone()[0] |
| print(f" Danbooru 80th: {dan_count:,} md5") |
| print(f" Union: {union:,} unique md5 ({both:,} in both)") |
| conn.commit() |
|
|
| print("[3/7] Mapping selected posts...") |
| gel_posts = conn.execute( |
| """ |
| INSERT INTO selected_gelbooru_posts(post_id, md5) |
| SELECT gp.id, gp.md5 |
| FROM selected_md5 s |
| JOIN g.posts gp ON gp.md5 = s.md5 |
| """ |
| ).rowcount |
| dan_posts = conn.execute( |
| """ |
| INSERT INTO selected_danbooru_posts(post_id, md5) |
| SELECT dp.id, dp.md5 |
| FROM selected_md5 s |
| JOIN d.posts dp ON dp.md5 = s.md5 |
| """ |
| ).rowcount |
| print(f" Gelbooru: {gel_posts:,} posts, Danbooru: {dan_posts:,} posts") |
| conn.commit() |
|
|
| print("[4/7] Merging into images table...") |
| img_count = conn.execute( |
| """ |
| INSERT INTO images ( |
| md5, canonical_rating, canonical_file_url, canonical_preview_url, canonical_sample_url, |
| canonical_source, canonical_width, canonical_height, |
| present_in_gelbooru, present_in_danbooru, |
| selected_by_gelbooru80, selected_by_danbooru80, |
| quality_score, quality_tier, |
| gelbooru_id, gelbooru_rating, gelbooru_score, gelbooru_score_pct, |
| gelbooru_file_url, gelbooru_preview_url, gelbooru_sample_url, |
| gelbooru_source, gelbooru_tags_text, gelbooru_status, |
| danbooru_id, danbooru_rating, danbooru_score, danbooru_score_pct, |
| danbooru_file_url, danbooru_source, danbooru_pixiv_id, |
| danbooru_fav_count, danbooru_file_size, danbooru_file_ext |
| ) |
| SELECT |
| s.md5, |
| stricter_rating(gp.rating, dan_rating_name(dp.rating)), |
| COALESCE(gp.file_url, dp.file_url), |
| gp.preview_url, |
| gp.sample_url, |
| COALESCE(gp.source, dp.source), |
| COALESCE(gp.width, dp.image_width), |
| COALESCE(gp.height, dp.image_height), |
| CASE WHEN gp.id IS NULL THEN 0 ELSE 1 END, |
| CASE WHEN dp.id IS NULL THEN 0 ELSE 1 END, |
| s.selected_by_gelbooru80, |
| s.selected_by_danbooru80, |
| max(COALESCE(gsp.pct, 0), COALESCE(dsp.pct, 0)), |
| 'p80', |
| gp.id, gp.rating, gp.score, gsp.pct, |
| gp.file_url, gp.preview_url, gp.sample_url, gp.source, gp.tags, gp.status, |
| dp.id, dan_rating_name(dp.rating), dp.score, dsp.pct, |
| dp.file_url, dp.source, dp.pixiv_id, dp.fav_count, dp.file_size, dp.file_ext |
| FROM selected_md5 s |
| LEFT JOIN g.posts gp ON gp.md5 = s.md5 |
| LEFT JOIN d.posts dp ON dp.md5 = s.md5 |
| LEFT JOIN gel_score_percentiles gsp ON gsp.rating = gp.rating AND gsp.score = gp.score |
| LEFT JOIN dan_score_percentiles dsp ON dsp.rating = dan_rating_name(dp.rating) AND dsp.score = dp.score |
| """ |
| ).rowcount |
| print(f" {img_count:,} images written") |
| conn.commit() |
|
|
| print("[5/7] Inserting Gelbooru tags (batched)...") |
| gel_tag_count = _batch_insert_tags( |
| conn, |
| src_posts_table="selected_gelbooru_posts", |
| dest_table="gelbooru_image_tags", |
| dest_cols="md5, tag_name", |
| src_db_alias="g", |
| ) |
| print(f" {gel_tag_count:,} gelbooru tag associations") |
|
|
| print("[6/7] Inserting Danbooru tags (batched)...") |
| dan_tag_count = _batch_insert_tags( |
| conn, |
| src_posts_table="selected_danbooru_posts", |
| dest_table="danbooru_image_tags", |
| dest_cols="md5, tag_name, tag_type", |
| src_db_alias="d", |
| ) |
| print(f" {dan_tag_count:,} danbooru tag associations") |
|
|
| print("[7/7] Creating indexes and finalizing...") |
| create_indexes(conn) |
| summary = validate_built_db(conn) |
| metadata = { |
| "gelbooru_db": str(gelbooru_db), |
| "danbooru_db": str(danbooru_db), |
| "gel_thresholds": json.dumps(GEL_THRESHOLDS, sort_keys=True), |
| "dan_thresholds": json.dumps(DAN_THRESHOLDS, sort_keys=True), |
| "quality_score_method": "rating_bucket_cume_dist_v1", |
| "quality_score_scale": "0..1", |
| **{k: str(v) for k, v in summary.items()}, |
| } |
| conn.executemany("INSERT INTO build_metadata(key, value) VALUES (?, ?)", metadata.items()) |
| conn.commit() |
| conn.close() |
| if output_db.exists(): |
| output_db.unlink() |
| building_path.rename(output_db) |
| return summary |
|
|
|
|
| def create_indexes(conn: sqlite3.Connection) -> None: |
| conn.executescript( |
| """ |
| CREATE INDEX idx_images_canonical_rating ON images(canonical_rating); |
| CREATE INDEX idx_images_quality_score ON images(quality_score); |
| CREATE INDEX idx_images_present_sources ON images(present_in_gelbooru, present_in_danbooru); |
| CREATE INDEX idx_images_selected_sources ON images(selected_by_gelbooru80, selected_by_danbooru80); |
| CREATE INDEX idx_gelbooru_image_tags_tag ON gelbooru_image_tags(tag_name); |
| CREATE INDEX idx_danbooru_image_tags_tag_type ON danbooru_image_tags(tag_name, tag_type); |
| """ |
| ) |
| conn.commit() |
|
|
|
|
| def validate_built_db(conn: sqlite3.Connection) -> dict: |
| images = conn.execute("SELECT COUNT(*) FROM images").fetchone()[0] |
| distinct_md5 = conn.execute("SELECT COUNT(DISTINCT md5) FROM images").fetchone()[0] |
| if images != distinct_md5: |
| raise BuildError(f"md5 de-duplication failed: images={images}, distinct_md5={distinct_md5}") |
| selected_by_gel = conn.execute("SELECT COUNT(*) FROM images WHERE selected_by_gelbooru80 = 1").fetchone()[0] |
| selected_by_dan = conn.execute("SELECT COUNT(*) FROM images WHERE selected_by_danbooru80 = 1").fetchone()[0] |
| selected_by_both = conn.execute( |
| "SELECT COUNT(*) FROM images WHERE selected_by_gelbooru80 = 1 AND selected_by_danbooru80 = 1" |
| ).fetchone()[0] |
| return { |
| "images": images, |
| "selected_by_gelbooru80": selected_by_gel, |
| "selected_by_danbooru80": selected_by_dan, |
| "selected_by_both": selected_by_both, |
| "gelbooru_image_tags": conn.execute("SELECT COUNT(*) FROM gelbooru_image_tags").fetchone()[0], |
| "danbooru_image_tags": conn.execute("SELECT COUNT(*) FROM danbooru_image_tags").fetchone()[0], |
| } |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--gelbooru-db", type=Path, default=DEFAULT_GELBOORU_DB) |
| parser.add_argument("--danbooru-db", type=Path, default=DEFAULT_DANBOORU_DB) |
| parser.add_argument("--output-db", type=Path, default=DEFAULT_OUTPUT_DB) |
| parser.add_argument("--overwrite", action="store_true") |
| parser.add_argument("--json", action="store_true") |
| return parser.parse_args() |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| summary = build_quality_db(args.gelbooru_db, args.danbooru_db, args.output_db, args.overwrite) |
| if args.json: |
| print(json.dumps(summary, ensure_ascii=False, indent=2)) |
| else: |
| print(f"\nDone. {summary['images']:,} images, " |
| f"{summary['gelbooru_image_tags']:,} gel tags, " |
| f"{summary['danbooru_image_tags']:,} dan tags") |
|
|
|
|
| if __name__ == "__main__": |
| try: |
| main() |
| except BuildError as exc: |
| raise SystemExit(f"error: {exc}") |
|
|