Download scripts/update_danbooru.py from Jannchie/danbooru_metadata: direct link, hf CLI and curl.
- Browser
- Download file 8.77 kB
-
https://huggingface.co/datasets/Jannchie/danbooru_metadata/resolve/main/scripts/update_danbooru.py
- Command line
-
hf download hf://datasets/Jannchie/danbooru_metadata/scripts/update_danbooru.py
-
curl -L -o update_danbooru.py https://huggingface.co/datasets/Jannchie/danbooru_metadata/resolve/main/scripts/update_danbooru.py
8.77 kB
| import argparse | |
| import queue | |
| import threading | |
| import time | |
| from pathlib import Path | |
| from time import sleep | |
| 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, | |
| TextColumn, | |
| TimeElapsedColumn, | |
| TimeRemainingColumn, | |
| ) | |
| from sqlalchemy import text | |
| from db import get_engine, t_posts | |
| url_queue: queue.Queue[str | None] = queue.Queue(maxsize=64) | |
| data_queue: queue.Queue[list[dict[str, object]] | None] = queue.Queue(maxsize=64) | |
| # 彻底抓不到的页。list.append 在 CPython 下是原子的,worker 线程可以直接写。 | |
| failures: list[str] = [] | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--start_id", type=int, default=0) | |
| parser.add_argument("--api_key", type=str) | |
| parser.add_argument("--login", type=str) | |
| parser.add_argument("--workers", type=int, default=16) | |
| parser.add_argument( | |
| "--rate", | |
| type=float, | |
| default=DEFAULT_RATE, | |
| help=f"起步请求速率(req/s,默认 {DEFAULT_RATE},全部 worker 共享)。撞到 429 会自动减半再慢慢恢复。", | |
| ) | |
| parser.add_argument("--db_path", type=str, default=str(DANBOORU_DB_PATH)) | |
| parser.add_argument( | |
| "--follow", | |
| action="store_true", | |
| help="追平后不退出,每 2 秒轮询新帖。默认追平即退出 —— 定时任务链需要这个脚本会结束。", | |
| ) | |
| parser.add_argument( | |
| "--update", | |
| action="store_true", | |
| help="全量更新模式:从头遍历所有 id 刷新 score/fav_count 等变化的数值," | |
| "而非仅抓取新帖。已消失的条目会保留原值,不会从数据库删除。", | |
| ) | |
| args = parser.parse_args() | |
| API_KEY, LOGIN = credentials(args.api_key, args.login) | |
| # 一个发牌器管住所有 worker。限速是按账号算的,16 个线程各自限速等于超发 16 倍。 | |
| limiter = RateLimiter(args.rate) | |
| # 只回显 login。匿名和已认证的限流差一个数量级,跑之前得能一眼看出走的哪条路。 | |
| print(f"syncing posts -- {f'authenticated as {LOGIN}' if LOGIN else 'anonymous (heavier rate limiting)'}") | |
| BASE_API_URL = "https://danbooru.donmai.us/posts.json?page=a{}&limit=200{}" | |
| LATEST_ID_URL = "https://danbooru.donmai.us/posts.json?limit=1{}" | |
| latest_id = 1 | |
| def auth_query() -> str: | |
| # 仅在提供凭据时附加认证参数,否则匿名访问;拼接 api_key=None 会触发 401 | |
| if API_KEY and LOGIN: | |
| return f"&api_key={API_KEY}&login={LOGIN}" | |
| return "" | |
| def fetch_latest_id(session: requests.Session) -> None: | |
| global latest_id | |
| try: | |
| rows = get_json(session, LATEST_ID_URL.format(auth_query()), limiter=limiter) | |
| except RuntimeError as exc: | |
| # 只是进度条的上界,拿不到就沿用旧值继续跑,不值得为它中断同步。 | |
| print(f"\ncould not refresh the latest id ({exc}); keeping {latest_id}") | |
| return | |
| if rows and "id" in rows[0]: | |
| latest_id = int(rows[0]["id"]) | |
| def update_latest_id() -> None: | |
| session = requests.Session() | |
| while True: | |
| fetch_latest_id(session) | |
| time.sleep(60) | |
| def fetch_data() -> None: | |
| session = requests.Session() | |
| while True: | |
| url = url_queue.get() | |
| if url is None: | |
| url_queue.task_done() | |
| break | |
| try: | |
| data_queue.put(get_json(session, url, limiter=limiter)) | |
| except RuntimeError as exc: | |
| # 记下来,不要跳过就算了。这一页是 200 条投稿,少了在成品里完全看不出来, | |
| # 而增量模式下次从数据库最大 id 起跑,永远不会回头补这个洞。 | |
| failures.append(f"{url}: {exc}") | |
| print(f"\nGAVE UP on {url}: {exc}") | |
| url_queue.task_done() | |
| def save_data(engine_path: str, required_columns: list[str]) -> None: | |
| engine = get_engine(engine_path) | |
| while True: | |
| data = data_queue.get() | |
| if data is None: | |
| data_queue.task_done() | |
| break | |
| for column in required_columns: | |
| for row in data: | |
| if column not in row: | |
| row[column] = None | |
| with engine.connect() as conn: | |
| conn.execute(t_posts.insert().prefix_with("OR REPLACE"), data) | |
| conn.commit() | |
| data_queue.task_done() | |
| def drain(workers: list[threading.Thread]) -> None: | |
| """让在途的页真正落盘,再退出。 | |
| 这些线程是 daemon,进程一退就地消失。生产者停下时队列里通常还压着几十页 —— | |
| 直接返回等于把它们扔掉,而且扔得悄无声息:日志上看是一次干净的同步,数据库里 | |
| 少了几千条。所以按 抓取 -> 保存 的顺序逐级投毒丸,每级都等它自己排空。 | |
| """ | |
| for _ in workers: | |
| url_queue.put(None) | |
| for worker in workers: | |
| worker.join() | |
| data_queue.put(None) | |
| data_queue.join() | |
| def main() -> None: | |
| engine_path = Path(args.db_path) | |
| if engine_path.parent != Path("."): | |
| engine_path.parent.mkdir(parents=True, exist_ok=True) | |
| threads: list[threading.Thread] = [] | |
| for _ in range(args.workers): | |
| thread = threading.Thread(target=fetch_data, daemon=True) | |
| thread.start() | |
| threads.append(thread) | |
| # 先同步取一次,再决定要不要开轮询线程。latest_id 初值是 1,交给后台线程去填 | |
| # 就有竞态:非 follow 模式下 current_id(约 1190 万) >= 1 立刻成立,一条不抓就退出。 | |
| fetch_latest_id(requests.Session()) | |
| if args.follow: | |
| # 只有常驻模式才需要它。一次性同步对着固定快照跑,结果可复现。 | |
| threading.Thread(target=update_latest_id, daemon=True).start() | |
| required_columns = [col.name for col in t_posts.columns if not col.primary_key] | |
| danbooru_engine = get_engine(str(engine_path)) | |
| t_posts.metadata.create_all(danbooru_engine, tables=[t_posts]) | |
| with danbooru_engine.connect() as conn: | |
| res = conn.execute(text("SELECT MAX(id) FROM posts")) | |
| row = res.fetchone() | |
| latest_db_id = row[0] if row and row[0] else 1 | |
| # 起点优先级:显式 --start_id(续传) > --update(从头全量刷新) > 增量(数据库最大 id) | |
| if args.start_id != 0: | |
| start_id = args.start_id | |
| elif args.update: | |
| start_id = 1 | |
| else: | |
| start_id = latest_db_id | |
| print("mode:", "update" if args.update else "incremental") | |
| print("start_id:", start_id) | |
| save_thread = threading.Thread( | |
| target=save_data, | |
| args=(str(engine_path), required_columns), | |
| daemon=True, | |
| ) | |
| save_thread.start() | |
| try: | |
| with Progress( | |
| TextColumn("[progress.description]{task.description}"), | |
| BarColumn(), | |
| TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), | |
| TimeElapsedColumn(), | |
| TimeRemainingColumn(), | |
| TextColumn("[{task.completed} / {task.total}]"), | |
| ) as progress: | |
| total_items = max(latest_id - start_id + 1, 0) | |
| task = progress.add_task("Processing", start=True, total=total_items) | |
| current_id = start_id | |
| while True: | |
| if current_id >= latest_id: | |
| progress.update(task, completed=latest_id) | |
| if not args.follow: | |
| break | |
| sleep(2) | |
| continue | |
| url = BASE_API_URL.format(current_id, auth_query()) | |
| # 不在这里 sleep:队列 maxsize=64 已经是背压,真正的节奏由 limiter | |
| # 决定。producer 再睡一次只会和 limiter 叠加成一个谁也说不清的速率。 | |
| url_queue.put(url) | |
| current_id += 200 | |
| progress.update(task, completed=current_id, total=latest_id) | |
| except KeyboardInterrupt: | |
| print("Stopped by user") | |
| drain(threads) | |
| with danbooru_engine.connect() as conn: | |
| rows = conn.execute(text("SELECT COUNT(*) FROM posts")).scalar() | |
| newest = conn.execute(text("SELECT MAX(id) FROM posts")).scalar() | |
| print(f"posts: {rows:,} rows, max id {newest:,} (site was at {latest_id:,})") | |
| print(f"final rate: {limiter.rate:.2f} req/s (started at {args.rate:g})") | |
| if failures: | |
| # 非零退出码:定时任务链上游得知道这次存档是有洞的。 | |
| print(f"\n{len(failures)} page(s) were never fetched -- the archive has holes:") | |
| for failure in failures[:20]: | |
| print(f" {failure}") | |
| if len(failures) > 20: | |
| print(f" ... and {len(failures) - 20} more") | |
| print("Re-run with --start_id set below the lowest missing id to fill them.") | |
| raise SystemExit(1) | |
| raise SystemExit(0) | |
| if __name__ == "__main__": | |
| main() | |