Download scripts/update_wiki.py from Jannchie/danbooru_metadata: direct link, hf CLI and curl.
- Browser
- Download file 5.87 kB
-
https://huggingface.co/datasets/Jannchie/danbooru_metadata/resolve/main/scripts/update_wiki.py
- Command line
-
hf download hf://datasets/Jannchie/danbooru_metadata/scripts/update_wiki.py
-
curl -L -o update_wiki.py https://huggingface.co/datasets/Jannchie/danbooru_metadata/resolve/main/scripts/update_wiki.py
5.87 kB
| import argparse | |
| import json | |
| from typing import Any | |
| import requests | |
| from _danbooru import DEFAULT_RATE, RateLimiter, get_json | |
| from _env import credentials | |
| from _paths import DANBOORU_DB_PATH | |
| from rich.progress import ( | |
| BarColumn, | |
| Progress, | |
| TaskProgressColumn, | |
| TextColumn, | |
| TimeElapsedColumn, | |
| ) | |
| from sqlalchemy import Table, text | |
| from sqlalchemy.engine import Engine | |
| from db import get_engine, metadata, t_artists, t_tag_aliases, t_tag_implications, t_tags, t_wiki_pages | |
| BASE_URL = "https://danbooru.donmai.us" | |
| PAGE_LIMIT = 1000 | |
| ENDPOINTS: list[tuple[str, Table]] = [ | |
| ("wiki_pages", t_wiki_pages), | |
| ("tags", t_tags), | |
| ("tag_aliases", t_tag_aliases), | |
| ("tag_implications", t_tag_implications), | |
| ("artists", t_artists), | |
| ] | |
| def auth_params(api_key: str | None, login: str | None) -> dict[str, str]: | |
| # 仅在提供凭据时附加认证参数,否则匿名访问 | |
| if api_key and login: | |
| return {"api_key": api_key, "login": login} | |
| return {} | |
| def describe(auth: dict[str, str]) -> str: | |
| # 只回显 login。匿名和已认证的限流差一个数量级,跑之前得能一眼看出走的哪条路。 | |
| return f"authenticated as {auth['login']}" if auth else "anonymous (heavier rate limiting)" | |
| def normalize_row(row: dict[str, Any], columns: list[str]) -> dict[str, Any]: | |
| out: dict[str, Any] = {column: row.get(column) for column in columns} | |
| if isinstance(out.get("other_names"), list): | |
| out["other_names"] = json.dumps(out["other_names"], ensure_ascii=False) | |
| return out | |
| def fetch_page( | |
| session: requests.Session, | |
| endpoint: str, | |
| params: dict[str, Any], | |
| limiter: RateLimiter, | |
| ) -> list[dict[str, Any]]: | |
| return get_json(session, f"{BASE_URL}/{endpoint}.json", params, limiter) | |
| def fetch_max_id(session: requests.Session, endpoint: str, auth: dict[str, str], limiter: RateLimiter) -> int: | |
| # page=b{很大的 id} 返回现存最大 id 的一行(id 降序),对所有 endpoint 通用 | |
| rows = fetch_page(session, endpoint, {"limit": 1, "page": "b1000000000", **auth}, limiter) | |
| return int(rows[0]["id"]) if rows else 0 | |
| def sync_endpoint( | |
| session: requests.Session, | |
| engine: Engine, | |
| endpoint: str, | |
| table: Table, | |
| auth: dict[str, str], | |
| progress: Progress, | |
| limiter: RateLimiter, | |
| ) -> int: | |
| columns = [column.name for column in table.columns] | |
| max_id = fetch_max_id(session, endpoint, auth, limiter) | |
| task = progress.add_task(endpoint, total=max_id) | |
| cursor = 0 | |
| total_rows = 0 | |
| while True: | |
| # 节奏由 limiter 统一控制,这里不再自己 sleep —— 两处限速会互相叠加, | |
| # 而且撞到 429 时只有 limiter 那份会退避。 | |
| rows = fetch_page(session, endpoint, {"limit": PAGE_LIMIT, "page": f"a{cursor}", **auth}, limiter) | |
| if not rows: | |
| break | |
| payload = [normalize_row(row, columns) for row in rows] | |
| with engine.connect() as conn: | |
| conn.execute(table.insert().prefix_with("OR REPLACE"), payload) | |
| conn.commit() | |
| cursor = max(int(row["id"]) for row in rows) | |
| total_rows += len(rows) | |
| progress.update(task, completed=min(cursor, max_id)) | |
| progress.update(task, completed=max_id) | |
| return total_rows | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Archive Danbooru wiki pages and tag metadata into SQLite." | |
| ) | |
| parser.add_argument("--api_key", type=str) | |
| parser.add_argument("--login", type=str) | |
| parser.add_argument("--db_path", type=str, default=str(DANBOORU_DB_PATH)) | |
| parser.add_argument( | |
| "--only", | |
| type=str, | |
| default=None, | |
| help="只同步指定 endpoint(逗号分隔),如 --only artists 或 --only wiki_pages,tags", | |
| ) | |
| parser.add_argument( | |
| "--rate", | |
| type=float, | |
| default=DEFAULT_RATE, | |
| help=f"起步请求速率(req/s,默认 {DEFAULT_RATE})。撞到 429 会自动减半再慢慢恢复。", | |
| ) | |
| return parser.parse_args() | |
| def select_endpoints(only: str | None) -> list[tuple[str, Table]]: | |
| if only is None: | |
| return ENDPOINTS | |
| wanted = {name.strip() for name in only.split(",") if name.strip()} | |
| known = {name for name, _ in ENDPOINTS} | |
| unknown = wanted - known | |
| if unknown: | |
| raise SystemExit(f"unknown endpoint(s): {', '.join(sorted(unknown))}; available: {', '.join(sorted(known))}") | |
| return [(name, table) for name, table in ENDPOINTS if name in wanted] | |
| def main() -> None: | |
| args = parse_args() | |
| auth = auth_params(*credentials(args.api_key, args.login)) | |
| endpoints = select_endpoints(args.only) | |
| limiter = RateLimiter(args.rate) | |
| print(f"syncing {', '.join(name for name, _ in endpoints)} -- {describe(auth)} at {args.rate:g} req/s") | |
| engine = get_engine(args.db_path) | |
| metadata.create_all(engine, tables=[table for _, table in endpoints]) | |
| session = requests.Session() | |
| counts: dict[str, int] = {} | |
| with Progress( | |
| TextColumn("[progress.description]{task.description}"), | |
| BarColumn(), | |
| TaskProgressColumn(), | |
| TimeElapsedColumn(), | |
| ) as progress: | |
| for endpoint, table in endpoints: | |
| counts[endpoint] = sync_endpoint(session, engine, endpoint, table, auth, progress, limiter) | |
| with engine.connect() as conn: | |
| for endpoint, table in endpoints: | |
| row_count = conn.execute(text(f"SELECT COUNT(*) FROM {table.name}")).scalar() | |
| print(f"{table.name}: fetched {counts[endpoint]}, table now has {row_count} rows") | |
| # 收尾时的速率就是这次实际能跑到的配额。明显低于起步值说明撞过 429,下次可以 | |
| # 直接用 --rate 从那个数字起步,省掉一路试探。 | |
| print(f"final rate: {limiter.rate:.2f} req/s (started at {args.rate:g})") | |
| if __name__ == "__main__": | |
| main() | |