"""Convert an Apify YouTube Transcripts or Videos JSON export to timed JSONL.""" import argparse from hashlib import sha256 import json import math from pathlib import Path import re import sys VIDEO_ID = re.compile(r"[A-Za-z0-9_-]{11}\Z") def seconds(value): if type(value) in (int, float) and 0 <= value <= sys.maxsize and math.isfinite(value): return float(value) return None def timed_segments(row): segments = row.get("transcript_segments") if not isinstance(segments, list): return [] valid = [] for segment in segments: if not isinstance(segment, dict) or not isinstance(segment.get("text"), str): continue start, duration = seconds(segment.get("start")), seconds(segment.get("duration")) text = " ".join(segment["text"].split()) if start is not None and duration is not None and text: valid.append((start, start + duration, text)) return sorted(dict.fromkeys(valid), key=lambda segment: segment[0]) def grouped_segments(segments, target_chars): group, length = [], 0 for segment in segments: new_chars = len(segment[2]) if group and length + 1 + new_chars > target_chars: yield group group, length = [], 0 length += new_chars + (1 if group else 0) group.append(segment) if group: yield group def transcript_chunks(rows, target_chars): """Return chunks from one export, rejecting conflicting rows for one track.""" if not isinstance(rows, list): raise ValueError("Expected a JSON array exported from Transcripts or Videos") if type(target_chars) is not int or target_chars <= 0: raise ValueError("Expected a positive character target") tracks = {} for row in rows: if not isinstance(row, dict) or row.get("transcript_available") is not True: continue if row.get("result_type") or row.get("type") not in (None, "transcript"): continue video_id = row.get("video_id") if not isinstance(video_id, str) or VIDEO_ID.fullmatch(video_id) is None: continue language = row.get("transcript_language") language = language if isinstance(language, str) else "" segments = timed_segments(row) if not segments: continue track = (video_id, language) if track in tracks and tracks[track] != segments: raise ValueError("Conflicting timed transcripts for one video and language") tracks[track] = segments for (video_id, language), segments in tracks.items(): for group in grouped_segments(segments, target_chars): start = group[0][0] end = max(segment[1] for segment in group) identity = json.dumps([video_id, language, group], ensure_ascii=True, separators=(",", ":")) yield { "chunk_id": sha256(identity.encode()).hexdigest(), "video_id": video_id, "transcript_language": language, "start_seconds": start, "end_seconds": end, "source_url": f"https://www.youtube.com/watch?v={video_id}&t={math.floor(start)}s", "text": " ".join(segment[2] for segment in group), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("export", type=Path, help="JSON array from a completed run") parser.add_argument("--target-chars", type=int, default=800, help="Approximate characters per chunk") args = parser.parse_args() try: rows = json.loads(args.export.read_text(encoding="utf-8-sig")) chunks = list(transcript_chunks(rows, args.target_chars)) except (OSError, ValueError) as error: parser.error(str(error)) if not chunks: print("No usable timed captions in the export.", file=sys.stderr) return 3 for chunk in chunks: print(json.dumps(chunk, ensure_ascii=True, allow_nan=False)) return 0 if __name__ == "__main__": sys.exit(main())