""" scan_jsonl.py ============= Stream a JSONL corpus file and print analytics. Designed for axolotl-style 'completion' corpora where each line is a JSON object with at least a `text` field. Streams line-by-line so it handles 10+ GB files without OOM. Usage ----- # Default report (heuristic token estimate: chars / 4) python scan_jsonl.py corpus.jsonl # Machine-readable python scan_jsonl.py corpus.jsonl --json # Smoke-test on first N lines python scan_jsonl.py corpus.jsonl --sample 10000 # Different field name python scan_jsonl.py corpus.jsonl --field content # Accurate token count via a HF tokenizer (slow but precise) python scan_jsonl.py corpus.jsonl --tokenizer ibm-granite/granite-4.1-8b Output ------ Human-readable report by default. Covers: * File-level stats (size, lines, invalid) * Article-length stats (mean/median/std/min/max + p1..p99 percentiles) * Length-bucket histogram * Token estimate (heuristic or real) * Wall-clock throughput Stdlib only by default. `transformers` only required when --tokenizer is set. """ from __future__ import annotations import argparse import json import os import sys import time from collections import Counter # ----- Length buckets -------------------------------------------------------- # Picked to align with common article-size buckets for Wikipedia-style text. BUCKETS: list[tuple[int, int]] = [ (0, 500), (500, 1_500), (1_500, 2_000), (2_000, 5_000), (5_000, 10_000), (10_000, 50_000), (50_000, 100_000), (100_000, 10**9), # 100k+; cap to keep arithmetic simple ] def human_bytes(n: int) -> str: for unit in ("B", "KB", "MB", "GB", "TB"): if n < 1024 or unit == "TB": return f"{n:.1f} {unit}" n /= 1024 # type: ignore[assignment] return f"{n:.1f} TB" # ----- Main scan ------------------------------------------------------------- def scan(path: str, field: str, sample: int | None, tokenizer) -> dict: lengths: list[int] = [] total_chars = 0 total_bytes = 0 line_count = 0 invalid_json = 0 missing_field = 0 first_word_counts: Counter[str] = Counter() started = time.time() total_tokens = 0 batch_texts: list[str] = [] BATCH = 256 file_size = os.path.getsize(path) print(f"[info] Scanning {path} ({human_bytes(file_size)})...", file=sys.stderr) with open(path, "rb") as f: for raw in f: line_count += 1 try: ex = json.loads(raw) except json.JSONDecodeError: invalid_json += 1 continue text = ex.get(field) if isinstance(ex, dict) else None if not isinstance(text, str) or not text: missing_field += 1 continue n_chars = len(text) n_bytes = len(text.encode("utf-8")) lengths.append(n_chars) total_chars += n_chars total_bytes += n_bytes first_word = text.split(maxsplit=1)[0] if text.split() else "" if first_word: first_word_counts[first_word[:50]] += 1 if tokenizer is not None: batch_texts.append(text) if len(batch_texts) >= BATCH: enc = tokenizer(batch_texts, add_special_tokens=False, truncation=False) total_tokens += sum(len(ids) for ids in enc["input_ids"]) batch_texts.clear() if sample is not None and line_count >= sample: print(f"[info] Hit --sample {sample}, stopping.", file=sys.stderr) break if line_count % 500_000 == 0: elapsed = time.time() - started rate = line_count / elapsed if elapsed > 0 else 0.0 print(f"[progress] {line_count:>10,} lines | " f"{rate:>7,.0f} lines/s", file=sys.stderr) # Flush remaining tokenizer batch if tokenizer is not None and batch_texts: enc = tokenizer(batch_texts, add_special_tokens=False, truncation=False) total_tokens += sum(len(ids) for ids in enc["input_ids"]) elapsed = time.time() - started return _build_report( path=path, file_size=file_size, line_count=line_count, invalid_json=invalid_json, missing_field=missing_field, lengths=lengths, total_chars=total_chars, total_bytes=total_bytes, first_word_counts=first_word_counts, tokenizer_used=tokenizer, total_tokens=total_tokens, elapsed=elapsed, ) # ----- Reporting ------------------------------------------------------------- def _percentile(sorted_lengths: list[int], p: float) -> int: if not sorted_lengths: return 0 idx = int(p * len(sorted_lengths)) if idx >= len(sorted_lengths): idx = len(sorted_lengths) - 1 return sorted_lengths[idx] def _build_report(*, path, file_size, line_count, invalid_json, missing_field, lengths, total_chars, total_bytes, first_word_counts, tokenizer_used, total_tokens, elapsed) -> dict: if not lengths: return {"error": "no valid articles found"} lengths.sort() n = len(lengths) total = sum(lengths) mean = total / n # Sample-based variance for speed on huge lists if n > 100_000: # Use first/last/middle for std estimate isn't great; use sum-of-squares. sum_sq = sum(x * x for x in lengths) variance = sum_sq / n - mean * mean if variance < 0: variance = 0.0 std = variance ** 0.5 else: variance = sum((x - mean) ** 2 for x in lengths) / n std = variance ** 0.5 bucket_counts = [0] * len(BUCKETS) for L in lengths: for i, (lo, hi) in enumerate(BUCKETS): if lo <= L < hi: bucket_counts[i] += 1 break if tokenizer_used is not None: token_estimate = total_tokens token_method = f"transformers ({tokenizer_used.name_or_path})" else: token_estimate = total // 4 token_method = "chars/4 heuristic" report = { "file": { "path": path, "size_bytes": file_size, "size_human": human_bytes(file_size), }, "counts": { "lines": line_count, "valid_articles": n, "invalid_json": invalid_json, "missing_field": missing_field, }, "lengths": { "total_chars": total_chars, "total_bytes_utf8": total_bytes, "bytes_per_char": round(total_bytes / total_chars, 3), "min": lengths[0], "max": lengths[-1], "mean": round(mean, 1), "median": lengths[n // 2], "std": round(std, 1), }, "percentiles": { f"p{int(p*100):02d}": _percentile(lengths, p) for p in (0.01, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99) }, "buckets": [ { "label": f"{lo}-{hi if hi < 10**9 else 'inf'}", "count": c, "pct": round(100 * c / n, 2), } for (lo, hi), c in zip(BUCKETS, bucket_counts) ], "top_first_words": [ {"word": w, "count": c, "pct": round(100 * c / n, 2)} for w, c in first_word_counts.most_common(20) ], "tokens": { "estimate": token_estimate, "method": token_method, }, "timing": { "elapsed_s": round(elapsed, 1), "lines_per_s": round(line_count / elapsed if elapsed > 0 else 0, 0), }, } return report # ----- Pretty-print ---------------------------------------------------------- def print_report(r: dict, stream=sys.stdout) -> None: if "error" in r: print(f"[error] {r['error']}", file=stream) return f = r["file"]; c = r["counts"]; l = r["lengths"] p = r["percentiles"]; b = r["buckets"]; t = r["tokens"] ti = r["timing"]; top = r["top_first_words"] bar = "=" * 62 print(bar, file=stream) print(f" File : {f['path']}", file=stream) print(f" Size : {f['size_human']} ({f['size_bytes']:,} bytes)", file=stream) print(bar, file=stream) print(f" Lines scanned : {c['lines']:,}", file=stream) print(f" Valid articles : {c['valid_articles']:,}", file=stream) print(f" Invalid JSON : {c['invalid_json']:,}", file=stream) print(f" Missing field : {c['missing_field']:,}", file=stream) print(bar, file=stream) print(f" Total chars : {l['total_chars']:,}", file=stream) print(f" Total bytes : {l['total_bytes_utf8']:,} (UTF-8)", file=stream) print(f" Bytes / char : {l['bytes_per_char']:.3f}", file=stream) print(f" Min length : {l['min']:,} chars", file=stream) print(f" Max length : {l['max']:,} chars", file=stream) print(f" Mean length : {l['mean']:,} chars", file=stream) print(f" Median length : {l['median']:,} chars", file=stream) print(f" Std dev : {l['std']:,} chars", file=stream) print(bar, file=stream) print(" Length percentiles (chars):", file=stream) for k in sorted(p.keys(), key=lambda s: int(s[1:])): print(f" {k}: {p[k]:>9,}", file=stream) print(bar, file=stream) print(" Length buckets:", file=stream) max_bucket_pct = max(bb["pct"] for bb in b) or 1.0 for bb in b: bar_len = int(round(40 * bb["pct"] / max_bucket_pct)) bar_str = "#" * bar_len print(f" {bb['label']:>14} chars : {bb['count']:>9,} " f"({bb['pct']:>5.2f}%) {bar_str}", file=stream) print(bar, file=stream) print(f" Token estimate : {t['estimate']:,} tokens", file=stream) print(f" Token method : {t['method']}", file=stream) print(bar, file=stream) print(" Top 20 first-words:", file=stream) for entry in top: print(f" {entry['word']:>32} : {entry['count']:>9,} " f"({entry['pct']:.2f}%)", file=stream) print(bar, file=stream) print(f" Elapsed : {ti['elapsed_s']:.1f} s", file=stream) print(f" Throughput : {ti['lines_per_s']:,.0f} lines/s", file=stream) print(bar, file=stream) # ----- CLI ------------------------------------------------------------------- def main() -> None: p = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) p.add_argument("path", help="JSONL file to scan") p.add_argument("--field", default="text", help="JSON field to read (default: text)") p.add_argument("--sample", type=int, default=None, help="Only scan the first N lines (smoke-test)") p.add_argument("--json", action="store_true", help="Emit machine-readable JSON instead of pretty text") p.add_argument("--tokenizer", default=None, help="HF tokenizer name for exact token count " "(e.g. ibm-granite/granite-4.1-8b). " "Slow but precise; requires transformers.") args = p.parse_args() if not os.path.isfile(args.path): print(f"[error] File not found: {args.path}", file=sys.stderr) sys.exit(1) tokenizer = None if args.tokenizer: try: from transformers import AutoTokenizer # type: ignore print(f"[info] Loading tokenizer: {args.tokenizer}", file=sys.stderr) tokenizer = AutoTokenizer.from_pretrained(args.tokenizer) except Exception as exc: print(f"[error] Could not load tokenizer ({exc!r}). " f"Falling back to heuristic.", file=sys.stderr) sys.exit(1) report = scan(args.path, args.field, args.sample, tokenizer) if args.json: json.dump(report, sys.stdout, ensure_ascii=False, indent=2) sys.stdout.write("\n") else: print_report(report) if __name__ == "__main__": main()