#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Verify WordEmbedding outputs. Checks, in order: 1. files.json lists exactly the data files, with matching size and SHA-256; 2. every word list has as many lines as its matrix has rows (size / 384); 3. meta.json per-language counts and totals agree with the files; 4. README front matter lists exactly the languages present. With --sample it also prints cross-lingual cosine similarities for a few concepts (informational; a missing word is skipped, a low score is flagged). python tools/verify.py python tools/verify.py --sample """ from __future__ import annotations import argparse import gzip import hashlib import json import re import sys from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" DIM = 384 # concept -> {lang: word}; used only by --sample. CONCEPTS = { "apple": { "en": "apple", "zh": "苹果", "fr": "pomme", "de": "Apfel", "es": "manzana", "pt": "maçã", "it": "mela", "ru": "яблоко", "ja": "りんご", "ko": "사과", "ar": "تفاحة", }, "water": { "en": "water", "zh": "水", "fr": "eau", "de": "Wasser", "es": "agua", "pt": "água", "it": "acqua", "ru": "вода", "ja": "水", "ko": "물", "ar": "ماء", }, "book": { "en": "book", "zh": "书", "fr": "livre", "de": "Buch", "es": "libro", "pt": "livro", "it": "libro", "ru": "книга", "ja": "本", "ko": "책", "ar": "كتاب", }, } def sha256_file(path: Path, chunk: int = 1 << 20) -> str: """Streaming SHA-256.""" h = hashlib.sha256() with path.open("rb") as f: for block in iter(lambda: f.read(chunk), b""): h.update(block) return h.hexdigest() def read_words(path: Path) -> list[str]: """Read a one-word-per-line UTF-8 list.""" with path.open("r", encoding="utf-8") as f: return f.read().splitlines() def fail(msg: str, errors: list[str]) -> None: """Print and collect a verification error.""" print(f"FAIL {msg}") errors.append(msg) def check_files(meta: dict, errors: list[str]) -> None: """Check files.json against the data directory and re-hash every file.""" manifest = json.loads((ROOT / "files.json").read_text(encoding="utf-8")) listed = {entry["file"] for entry in manifest["files"]} actual = {p.relative_to(ROOT).as_posix() for p in DATA.iterdir() if p.is_file()} if listed != actual: fail(f"files.json mismatch: missing={sorted(actual - listed)} extra={sorted(listed - actual)}", errors) for entry in manifest["files"]: path = ROOT / entry["file"] if path.stat().st_size != entry["bytes"]: fail(f"{entry['file']}: size {path.stat().st_size} != {entry['bytes']}", errors) if sha256_file(path) != entry["sha256"]: fail(f"{entry['file']}: sha256 mismatch", errors) print(f"ok files.json: {len(manifest['files'])} files, sizes and SHA-256 verified") def check_layout(meta: dict, errors: list[str]) -> None: """Check words/matrix alignment, per-language counts and totals.""" total_words = 0 total_bytes = 0 for lang, entry in meta["languages"].items(): words_path = DATA / f"{lang}.words.txt" bin_path = DATA / f"{lang}.int8.vector" if not words_path.exists() or not bin_path.exists(): fail(f"{lang}: missing data file pair", errors) continue words = read_words(words_path) size = bin_path.stat().st_size if size % DIM: fail(f"{lang}: {size} bytes is not a multiple of {DIM}", errors) rows = size // DIM if len(words) != rows: fail(f"{lang}: {len(words)} words vs {rows} rows", errors) if entry["words"] != len(words): fail(f"{lang}: meta says {entry['words']} words, file has {len(words)}", errors) if entry["vectors_bytes"] != size: fail(f"{lang}: meta says {entry['vectors_bytes']} bytes, file has {size}", errors) total_words += len(words) total_bytes += size totals = meta["totals"] if totals["languages"] != len(meta["languages"]): fail("totals.languages does not match languages", errors) if totals["words"] != total_words: fail(f"totals.words {totals['words']} != {total_words}", errors) if totals["vectors_bytes"] != total_bytes: fail(f"totals.vectors_bytes {totals['vectors_bytes']} != {total_bytes}", errors) print(f"ok layout: {len(meta['languages'])} languages, {total_words:,} words, " f"{total_bytes / 2**20:.2f} MiB") def check_readme(meta: dict, errors: list[str]) -> None: """Check that the README front matter advertises exactly the built languages.""" text = (ROOT / "README.md").read_text(encoding="utf-8") head = text.split("---", 2)[1] # Front matter language list must be the one-line flow form used across the # published cards: language: [ar, bg, ...] flow = re.search(r"^language:\s*\[([^\]]*)\]\s*$", head, re.M) if not flow: fail("README front matter has no one-line language list " "(expected: language: [ar, bg, ...])", errors) return codes = {c.strip() for c in flow.group(1).split(",") if c.strip()} if codes != set(meta["languages"]): fail(f"README languages {sorted(codes)} != meta {sorted(meta['languages'])}", errors) else: print(f"ok README front matter: {len(codes)} languages") def sample(meta: dict) -> None: """Print cross-lingual similarities for a few concepts (informational).""" def row(lang: str, word: str): """Return the dequantized vector for one word, or None if absent.""" path = DATA / f"{lang}.words.txt" if not path.exists(): return None words = read_words(path) try: i = words.index(word) except ValueError: return None vec = np.memmap(DATA / f"{lang}.int8.vector", dtype=np.int8, mode="r").reshape(-1, DIM) return vec[i].astype(np.float32) / 127.0 print("\nCross-lingual sample (cosine vs en):") for concept, words in CONCEPTS.items(): base = row("en", words["en"]) if base is None: continue scores = [] for lang, word in words.items(): if lang == "en": continue v = row(lang, word) if v is not None: scores.append((float(base @ v), lang, word)) print(f" {concept}: " + ", ".join(f"{lang} {s:.3f}" for s, lang, _ in sorted(scores, reverse=True))) def main() -> int: """Run all checks; exit 1 when a hard check fails.""" ap = argparse.ArgumentParser() ap.add_argument("--sample", action="store_true", help="also print cross-lingual samples") args = ap.parse_args() meta = json.loads((ROOT / "meta.json").read_text(encoding="utf-8")) errors: list[str] = [] check_files(meta, errors) check_layout(meta, errors) check_readme(meta, errors) if args.sample: sample(meta) print(f"\n{'FAILED: ' + str(len(errors)) + ' error(s)' if errors else 'All checks passed.'}") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())