File size: 4,850 Bytes
155a87f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | #!/usr/bin/env python3
"""Scrape a diverse multi-channel cover-video corpus for StegoReels.
Reads a channel list (--channels-file, see dataset/config/channels.csv),
scrapes each channel's Shorts tab up to a per-channel cap, and tags every
clip's .meta.json with that channel's category/split. Wraps yt_scrapper.py
for the actual download/filter logic. Verify channel handles before a large
run -- creator @handles change and are not guaranteed current.
Usage:
python scrape_dataset.py --target-total 1000
"""
from __future__ import annotations
import argparse
import csv
import json
import logging
import math
from pathlib import Path
from yt_scrapper import DEFAULT_MAX_DURATION_S, DEFAULT_MIN_DURATION_S, ScrapeConfig, run
LOGGER = logging.getLogger("scrape_dataset")
SCRIPT_DIR = Path(__file__).resolve().parent
DATASET_DIR = SCRIPT_DIR.parent
def load_channels(path: Path) -> list[dict]:
with path.open(encoding="utf-8") as f:
rows = [row for row in csv.DictReader(f) if row.get("channel_url", "").strip()]
if not rows:
raise SystemExit(f"No channels found in {path}")
return rows
def build_manifest(output_dir: Path, manifest_path: Path) -> int:
"""Aggregate every *.meta.json under output_dir into one manifest.jsonl."""
count = 0
with manifest_path.open("w", encoding="utf-8") as out:
for meta_file in sorted(output_dir.glob("*.meta.json")):
meta = json.loads(meta_file.read_text(encoding="utf-8"))
out.write(json.dumps(meta, ensure_ascii=False) + "\n")
count += 1
return count
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--channels-file", type=Path, default=DATASET_DIR / "config" / "channels.csv"
)
parser.add_argument("--output-dir", type=Path, default=DATASET_DIR / "raw")
parser.add_argument("--archive-file", type=Path, default=None)
parser.add_argument("--target-total", type=int, default=1000)
parser.add_argument(
"--per-channel-max", type=int, default=None, help="Overrides target-total / #channels."
)
parser.add_argument(
"--val-test-fraction",
type=float,
default=0.35,
help="Per-channel clip cap for val/test channels, as a fraction of the train cap "
"(val/test only need enough clips to evaluate on, not train-level volume).",
)
parser.add_argument("--min-duration", type=int, default=DEFAULT_MIN_DURATION_S)
parser.add_argument("--max-duration", type=int, default=DEFAULT_MAX_DURATION_S)
parser.add_argument("--no-require-vertical", dest="require_vertical", action="store_false")
parser.add_argument("--sleep-interval", type=float, default=1.0)
parser.add_argument("--max-sleep-interval", type=float, default=3.0)
parser.add_argument("--cookies-from-browser", default=None)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("-v", "--verbose", action="store_true")
parser.set_defaults(require_vertical=True)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> None:
args = parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
channels = load_channels(args.channels_file)
per_channel_max = args.per_channel_max or math.ceil(args.target_total / len(channels))
archive_file = args.archive_file or (args.output_dir / ".yt_dlp_archive.txt")
LOGGER.info(
"%d channels, cap %d clips/channel (target ~%d total)",
len(channels),
per_channel_max,
args.target_total,
)
for row in channels:
cap = (
per_channel_max
if row["split"] == "train"
else max(1, round(per_channel_max * args.val_test_fraction))
)
cfg = ScrapeConfig(
output_dir=args.output_dir,
archive_file=archive_file,
max_videos=cap,
min_duration=args.min_duration,
max_duration=args.max_duration,
require_vertical=args.require_vertical,
sleep_interval=args.sleep_interval,
max_sleep_interval=args.max_sleep_interval,
cookies_from_browser=args.cookies_from_browser,
verbose=args.verbose,
dry_run=args.dry_run,
)
extra_meta = {"category": row["category"], "split": row["split"]}
run(cfg, [row["channel_url"]], extra_meta=extra_meta)
if not args.dry_run:
manifest_path = args.output_dir / "manifest.jsonl"
n = build_manifest(args.output_dir, manifest_path)
LOGGER.info("Wrote manifest with %d clips -> %s", n, manifest_path)
if __name__ == "__main__":
main()
|