#!/usr/bin/env python3 """babelabc.cn crawler:下载全部剧集视频(mp4)和双语字幕(SRT)。 输出目录结构: download//.mp4 download//.srt (英中双语) download//cover.jpg download//info.json (剧集信息) 已存在的 mp4/srt 会跳过;失败记录写入 download/_failed.json。 视频分片通过 ThreadPoolExecutor 并发下载,ffmpeg concat 合并。 """ import json import os import shutil import subprocess import sys import tempfile import threading import time import urllib.error import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed BASE = "https://www.babelabc.cn" OUT_DIR = "download" FFMPEG = shutil.which("ffmpeg") or "/opt/homebrew/bin/ffmpeg" FFPROBE = shutil.which("ffprobe") or "/opt/homebrew/bin/ffprobe" UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) BabelabcCrawler/1.0" RETRIES = 4 RETRY_BACKOFF = 2.0 TIMEOUT = 30 SEG_WORKERS = 8 EP_DELAY = 0.3 MIN_VIDEO_SIZE = 64 * 1024 _print_lock = threading.Lock() _log_lock = threading.Lock() TAG_RE = __import__("re").compile(r"\[![^\]]*\]") def log(msg): with _print_lock: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def fetch(url): headers = {"User-Agent": UA} last = None for attempt in range(1, RETRIES + 1): try: req = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: return resp.read() except urllib.error.HTTPError as e: if e.code == 404: raise last = e except Exception as e: last = e if attempt < RETRIES: time.sleep(RETRY_BACKOFF * attempt) raise RuntimeError(f"fetch failed after {RETRIES} tries: {url} ({last})") def fetch_json(url): return json.loads(fetch(url)) def clean_text(text): return TAG_RE.sub("", text).strip() def srt_ts(seconds): ms = int(round(seconds * 1000)) h, rem = divmod(ms, 3600000) m, rem = divmod(rem, 60000) s, ms = divmod(rem, 1000) return "%02d:%02d:%02d,%03d" % (h, m, s, ms) def write_srt(dialogues, path): lines = [] for i, d in enumerate(dialogues, 1): en = clean_text(d["text"].get("en", "")) zh = clean_text(d["text"].get("zh", "")) lines.append(str(i)) lines.append(f"{srt_ts(d['start'])} --> {srt_ts(d['end'])}") if en: lines.append(en) if zh: lines.append(zh) lines.append("") with open(path, "w", encoding="utf-8") as f: f.write("\n".join(lines)) def ensure_dir(path): os.makedirs(path, exist_ok=True) def record_failure(drama, episode, kind, message): entry = {"drama": drama, "episode": episode, "kind": kind, "error": message} path = os.path.join(OUT_DIR, "_failed.json") with _log_lock: try: with open(path, encoding="utf-8") as f: failures = json.load(f) except Exception: failures = [] failures = [x for x in failures if not ( x.get("drama") == drama and x.get("episode") == episode and x.get("kind") == kind)] failures.append(entry) with open(path, "w", encoding="utf-8") as f: json.dump(failures, f, ensure_ascii=False, indent=1) def clear_failure(drama, episode, kind): path = os.path.join(OUT_DIR, "_failed.json") with _log_lock: try: with open(path, encoding="utf-8") as f: failures = json.load(f) except Exception: return kept = [x for x in failures if not ( x.get("drama") == drama and x.get("episode") == episode and x.get("kind") == kind)] if len(kept) != len(failures): with open(path, "w", encoding="utf-8") as f: json.dump(kept, f, ensure_ascii=False, indent=1) def crawl_subtitle(did, eid, srt_path): """返回 'ok' / 'skip' / 'fail'。""" if os.path.exists(srt_path) and os.path.getsize(srt_path) > 0: return "skip" url = f"{BASE}/_api/dramas/{did}/episodes/{eid}" try: ep = fetch_json(url) if not ep or "subtitle" not in ep: record_failure(did, eid, "subtitle", "no subtitle in response") return "fail" write_srt(ep["subtitle"]["dialogues"], srt_path) clear_failure(did, eid, "subtitle") return "ok" except Exception as ex: record_failure(did, eid, "subtitle", str(ex)) return "fail" def crawl_video(did, eid, mp4_path): """返回 'ok' / 'skip' / 'fail'。""" if os.path.exists(mp4_path) and os.path.getsize(mp4_path) >= MIN_VIDEO_SIZE: return "skip" url = f"{BASE}/babelabc-media/low/{did}/{eid}/index.m3u8?v=0" tmpdir = tempfile.mkdtemp(prefix="babelseg_", dir=OUT_DIR) try: try: playlist = fetch(url).decode() except urllib.error.HTTPError as e: if e.code == 404: record_failure(did, eid, "video", "index.m3u8 404") return "fail" raise segs = [ln.strip() for ln in playlist.splitlines() if ln.strip() and not ln.startswith("#")] if not segs: record_failure(did, eid, "video", "empty playlist") return "fail" def dl(seg, idx): seg_url = urllib.request.urljoin(url, seg) data = fetch(seg_url) p = os.path.join(tmpdir, f"seg{idx:04d}.ts") with open(p, "wb") as f: f.write(data) return idx failed = [] done = {} with ThreadPoolExecutor(max_workers=SEG_WORKERS) as ex: futs = {ex.submit(dl, seg, i): i for i, seg in enumerate(segs)} for fut in as_completed(futs): i = futs[fut] try: done[i] = fut.result() except Exception as ex2: failed.append(f"seg{i:04d}.ts: {ex2}") if failed: record_failure(did, eid, "video", f"{len(failed)}/{len(segs)} segments failed: " + failed[0]) return "fail" concat_file = os.path.join(tmpdir, "concat.txt") with open(concat_file, "w", encoding="utf-8") as f: for i in range(len(segs)): f.write(f"file 'seg{i:04d}.ts'\n") out_tmp = os.path.join(tmpdir, "out.mp4") r = subprocess.run( [FFMPEG, "-y", "-f", "concat", "-safe", "0", "-i", concat_file, "-c", "copy", out_tmp], capture_output=True) if r.returncode != 0 or not os.path.exists(out_tmp): record_failure(did, eid, "video", "ffmpeg failed: " + r.stderr.decode(errors="replace")[-300:]) return "fail" os.replace(out_tmp, mp4_path) clear_failure(did, eid, "video") return "ok" except Exception as ex: record_failure(did, eid, "video", str(ex)) return "fail" finally: shutil.rmtree(tmpdir, ignore_errors=True) def main(): ensure_dir(OUT_DIR) catalog = fetch_json(f"{BASE}/_api/dramas") dramas = catalog["dramas"] total = len(dramas) log(f"crawler 启动: 共 {total} 部剧集") counts = dict(video_ok=0, video_skip=0, video_fail=0, srt_ok=0, srt_skip=0, srt_fail=0) for di, d in enumerate(dramas, 1): did = d["id"] ddir = os.path.join(OUT_DIR, did) ensure_dir(ddir) info_path = os.path.join(ddir, "info.json") if not os.path.exists(info_path): info = {k: v for k, v in d.items() if k != "top"} with open(info_path, "w", encoding="utf-8") as f: json.dump(info, f, ensure_ascii=False, indent=1) cover_path = os.path.join(ddir, "cover.jpg") if not os.path.exists(cover_path): try: data = fetch(f"{BASE}/babelabc-data/dramas/{did}/cover.jpg") with open(cover_path, "wb") as f: f.write(data) except Exception as ex: record_failure(did, "-", "cover", str(ex)) try: det = fetch_json(f"{BASE}/_api/dramas/{did}") except Exception as ex: log(f"[{di}/{total}] {did} 详情获取失败: {ex}") record_failure(did, "-", "drama", str(ex)) continue for e in det["episodes"]: eid = e["id"] s_res = crawl_subtitle(did, eid, os.path.join(ddir, f"{eid}.srt")) v_res = crawl_video(did, eid, os.path.join(ddir, f"{eid}.mp4")) counts[f"srt_{s_res}"] += 1 counts[f"video_{v_res}"] += 1 if s_res == "fail" or v_res == "fail": log(f"[{di}/{total}] {did}/{eid}: srt={s_res} video={v_res}") time.sleep(EP_DELAY) log(f"[{di}/{total}] {did} done " f"(srt: ok={counts['srt_ok']} skip={counts['srt_skip']} " f"fail={counts['srt_fail']}; video: ok={counts['video_ok']} " f"skip={counts['video_skip']} fail={counts['video_fail']})") log(f"全部完成: {counts}; 失败记录见 {OUT_DIR}/_failed.json") if __name__ == "__main__": main()