kalam-speech-corpus / scripts /verify_all_transcripts.py
sanjeevafk's picture
Upload folder using huggingface_hub
6112973 verified
Raw
History Blame Contribute Delete
5.01 kB
#!/usr/bin/env python3
"""
Agnostic Deep Transcript & Corpus Verification Script.
Audits:
- Word counts & character lengths
- SHA-256 hash match against transcript content
- Residual HTML tags, CSS blocks, or web scraper artifacts
- Date, Year, Location, Period, and Event Type validation
- Duplicate detection & provenance consistency
"""
from __future__ import annotations
import argparse
import json
import re
import hashlib
from pathlib import Path
from collections import defaultdict
def parse_args():
parser = argparse.ArgumentParser(description="Verify transcript quality, formatting, and cryptographic hashes.")
parser.add_argument(
"--corpus-dir",
type=Path,
default=Path(__file__).resolve().parent.parent,
help="Path to the dataset directory."
)
parser.add_argument(
"--min-words",
type=int,
default=50,
help="Minimum transcript word count threshold for non-stub speeches."
)
return parser.parse_args()
def verify_corpus():
args = parse_args()
data_dir = args.corpus_dir.resolve() / "data"
speeches_file = data_dir / "speeches.jsonl"
sources_file = data_dir / "sources.jsonl"
if not speeches_file.exists():
print(f"[ERROR] Speeches file does not exist: {speeches_file}")
return 1
print("=== Starting Deep Transcript Verification ===")
print(f"Data Directory: {data_dir}")
total_speeches = 0
clean_speeches = 0
empty_speeches = 0
short_speeches = 0
html_residue_issues = 0
hash_mismatches = 0
year_issues = 0
period_issues = 0
stats = {
"word_counts": [],
"char_counts": [],
"by_period": defaultdict(int),
"by_year": defaultdict(int),
"by_rights": defaultdict(int),
"by_status": defaultdict(int),
}
html_tag_pattern = re.compile(r"<(div|span|p|a\s|script|style|table|tr|td|body|html)[^>]*>", re.IGNORECASE)
with speeches_file.open("r", encoding="utf-8") as f:
for idx, line in enumerate(f, 1):
total_speeches += 1
rec = json.loads(line.strip())
transcript = rec.get("transcript", "")
title = rec.get("title", "")
date_str = rec.get("date", "")
year = rec.get("year")
period = rec.get("period", "")
rights = rec.get("rights_status", "")
status = rec.get("transcript_status", "")
sha = rec.get("sha256", "")
stats["by_period"][period] += 1
stats["by_year"][year or 0] += 1
stats["by_rights"][rights] += 1
stats["by_status"][status] += 1
# Length & Word count
words = len(transcript.split())
chars = len(transcript)
stats["word_counts"].append(words)
stats["char_counts"].append(chars)
if not transcript.strip():
empty_speeches += 1
continue
elif words < args.min_words and status not in ("stub_placeholder", "video_only"):
short_speeches += 1
# SHA-256 Check
computed_sha = hashlib.sha256(transcript.encode("utf-8")).hexdigest()
if sha and sha != computed_sha:
hash_mismatches += 1
# HTML Residue Check
if html_tag_pattern.search(transcript):
html_residue_issues += 1
# Year Check
if not year or year < 1900 or year > 2100:
year_issues += 1
# Period check
if not period:
period_issues += 1
clean_speeches += 1
print(f"\nVerification Results:")
print(f" Total Canonical Speeches Audited: {total_speeches}")
print(f" Verified High-Quality / Clean: {clean_speeches}")
print(f" Empty Transcripts (Stubs/Video): {empty_speeches}")
print(f" Suspiciously Short (<{args.min_words} words): {short_speeches}")
print(f" HTML Residue / Tag Issues: {html_residue_issues}")
print(f" Hash Mismatches: {hash_mismatches}")
print(f" Year Anomaly Count: {year_issues}")
print(f" Period Anomaly Count: {period_issues}")
total_words = sum(stats["word_counts"])
avg_words = total_words / total_speeches if total_speeches else 0
print(f"\nCorpus Text Statistics:")
print(f" Total Words in Transcripts: {total_words:,}")
print(f" Average Words per Speech: {avg_words:,.1f}")
print(f" Max Words in Single Speech: {max(stats['word_counts']) if stats['word_counts'] else 0:,}")
print("\nPeriod Distribution:")
for p, cnt in sorted(stats["by_period"].items()):
print(f" - {p}: {cnt} speeches")
print("\nRights Status Breakdown:")
for r, cnt in sorted(stats["by_rights"].items()):
print(f" - {r}: {cnt} records")
return 0
if __name__ == "__main__":
raise SystemExit(verify_corpus())