youtube-shorts-dataset / scripts /yt_scrapper.py
mxmprhd's picture
Upload folder using huggingface_hub
155a87f verified
Raw
History Blame Contribute Delete
9.53 kB
#!/usr/bin/env python3
"""Download YouTube Shorts as cover-video candidates (raw MP4 + metadata) for StegoReels.
Usage:
python yt_scrapper.py --source "ytsearch50:cats" --output-dir ../raw
python yt_scrapper.py --input-file sources.txt --max-videos 1000
Output: <output-dir>/<id>.mp4 + <output-dir>/<id>.meta.json.
"""
from __future__ import annotations
import argparse
import json
import logging
from dataclasses import dataclass
from pathlib import Path
import yt_dlp
from yt_dlp.postprocessor.common import PostProcessor
LOGGER = logging.getLogger("yt_scrapper")
DEFAULT_MIN_DURATION_S = 3
DEFAULT_MAX_DURATION_S = 60 # YouTube Shorts cutoff
@dataclass
class ScrapeConfig:
output_dir: Path
archive_file: Path
max_videos: int | None
min_duration: int
max_duration: int
require_vertical: bool
sleep_interval: float
max_sleep_interval: float
cookies_from_browser: str | None
verbose: bool
dry_run: bool
def build_match_filter(cfg: ScrapeConfig):
"""Pre-download filter; only duration is reliably known at this stage."""
def _match_filter(info_dict, *, incomplete: bool = False):
duration = info_dict.get("duration")
if duration is None:
return None
if duration < cfg.min_duration:
return f"duration {duration}s below --min-duration {cfg.min_duration}s"
if duration > cfg.max_duration:
return f"duration {duration}s above --max-duration {cfg.max_duration}s"
return None
return _match_filter
def extract_compact_metadata(info: dict, source: str, extra: dict | None = None) -> dict:
"""Stable metadata schema written as the .meta.json sidecar."""
meta = {
"id": info.get("id"),
"title": info.get("title"),
"webpage_url": info.get("webpage_url"),
"source_query": source,
"uploader": info.get("uploader"),
"channel_id": info.get("channel_id"),
"upload_date": info.get("upload_date"),
"duration_s": info.get("duration"),
"width": info.get("width"),
"height": info.get("height"),
"fps": info.get("fps"),
"view_count": info.get("view_count"),
"like_count": info.get("like_count"),
"license": info.get("license"),
"tags": info.get("tags"),
"ext": info.get("ext"),
}
if extra:
meta.update(extra)
return meta
class ShortsFilterPostProcessor(PostProcessor):
"""Post-download gate: enforce final duration/aspect ratio, write metadata, delete rejects."""
def __init__(self, cfg: ScrapeConfig, source: str, extra_meta: dict | None = None):
super().__init__()
self._cfg = cfg
self._source = source
self._extra_meta = extra_meta
def run(self, info):
filepath = info.get("filepath") or info.get("_filename")
duration = info.get("duration")
width, height = info.get("width"), info.get("height")
reasons = []
if duration is not None and not (
self._cfg.min_duration <= duration <= self._cfg.max_duration
):
reasons.append(f"duration={duration}s outside range")
if self._cfg.require_vertical and width and height and height < width:
reasons.append(f"not vertical ({width}x{height})")
if reasons:
LOGGER.info("Rejecting %s: %s", info.get("id"), "; ".join(reasons))
if filepath and Path(filepath).exists():
Path(filepath).unlink()
return [], info
meta = extract_compact_metadata(info, self._source, self._extra_meta)
if filepath:
Path(filepath).with_suffix(".meta.json").write_text(
json.dumps(meta, indent=2, ensure_ascii=False)
)
LOGGER.info("Kept %s -> %s", info.get("id"), filepath)
return [], info
def load_sources(source_args: list[str] | None, input_file: str | None) -> list[str]:
sources: list[str] = list(source_args or [])
if input_file:
for line in Path(input_file).read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#"):
sources.append(line)
if not sources:
raise SystemExit("No sources given. Use --source and/or --input-file.")
return sources
def build_ydl_opts(cfg: ScrapeConfig) -> dict:
cfg.output_dir.mkdir(parents=True, exist_ok=True)
cfg.archive_file.parent.mkdir(parents=True, exist_ok=True)
opts = {
# Force H.264/AAC: cover videos must play in any standard player,
# and YouTube serves AV1 (undecodable in QuickTime on many Macs)
# for its highest-res mp4 formats.
"format": "bv*[ext=mp4][vcodec^=avc1]+ba[ext=m4a]/b[ext=mp4][vcodec^=avc1]/bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/best", # noqa: E501
"merge_output_format": "mp4",
"outtmpl": str(cfg.output_dir / "%(id)s.%(ext)s"),
"download_archive": str(cfg.archive_file),
"match_filter": build_match_filter(cfg),
"sleep_interval": cfg.sleep_interval,
"max_sleep_interval": cfg.max_sleep_interval,
# Throttles per-video metadata/API requests too, not just downloads --
# channel-listing pagination is what actually triggers YouTube's
# "rate-limited for up to an hour" block on long multi-channel runs.
"sleep_interval_requests": cfg.sleep_interval,
"ignoreerrors": True,
"noprogress": not cfg.verbose,
"quiet": not cfg.verbose,
"no_warnings": not cfg.verbose,
"retries": 3,
"simulate": cfg.dry_run,
}
if cfg.max_videos:
opts["max_downloads"] = cfg.max_videos
if cfg.cookies_from_browser:
opts["cookiesfrombrowser"] = (cfg.cookies_from_browser,)
return opts
def run(cfg: ScrapeConfig, sources: list[str], extra_meta: dict | None = None) -> None:
ydl_opts = build_ydl_opts(cfg)
for source in sources:
LOGGER.info("Scraping source: %s", source)
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
if not cfg.dry_run:
ydl.add_post_processor(
ShortsFilterPostProcessor(cfg, source, extra_meta), when="after_move"
)
try:
ydl.download([source])
except yt_dlp.utils.MaxDownloadsReached:
LOGGER.info("Reached --max-videos limit (%s); stopping.", cfg.max_videos)
return
except yt_dlp.utils.DownloadError as exc:
LOGGER.warning("Source %s failed: %s", source, exc)
continue
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Download YouTube Shorts as cover-video candidates via yt-dlp.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--source",
action="append",
help="Channel/Shorts-tab URL, playlist URL, video URL, or yt-dlp search "
"pseudo-URL (e.g. 'ytsearch50:cats'). Repeatable.",
)
parser.add_argument("--input-file", help="File with one source per line (# comments allowed).")
parser.add_argument(
"--output-dir",
type=Path,
default=Path(__file__).resolve().parent.parent / "raw",
help="Where to write clips + metadata sidecars.",
)
parser.add_argument(
"--archive-file",
type=Path,
default=Path(__file__).resolve().parent.parent / "raw" / ".yt_dlp_archive.txt",
help="yt-dlp download-archive file, to skip already-seen video ids.",
)
parser.add_argument("--max-videos", type=int, default=None, help="Cap on download attempts.")
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",
help="Disable the post-download vertical-aspect-ratio filter.",
)
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,
help="Browser to read cookies from (e.g. 'chrome'), for age-restricted videos.",
)
parser.add_argument(
"--dry-run", action="store_true", help="Simulate only; no downloads or writes."
)
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",
)
cfg = ScrapeConfig(
output_dir=args.output_dir,
archive_file=args.archive_file,
max_videos=args.max_videos,
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,
)
sources = load_sources(args.source, args.input_file)
run(cfg, sources)
if __name__ == "__main__":
main()