File size: 7,352 Bytes
0ca5fab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | #!/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())
|