File size: 7,711 Bytes
0a9f735 | 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 | #!/usr/bin/env python3
"""Schema and quality checks for West_Sino-Preference (standard library only).
Exit code 0 = all checks pass; 1 = at least one check failed.
Usage: python scripts/validate.py [path/to/items.jsonl]
"""
import json, os, re, sys
from collections import Counter, defaultdict
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT = os.path.join(HERE, "..", "data", "items.jsonl")
FIELDS = ["id", "pair_id", "category", "value_axis", "item_type", "condition",
"anchor", "prompt", "option_a", "option_b", "west_answer", "sino_answer", "question"]
CATEGORIES = {"freedom of expression", "state ideology", "state vs free-market capitalism",
"education policy", "data privacy and surveillance",
"democracy and governance", "environmental strategy"}
CONDITIONS = {"abstract", "attributed"}
ITEM_TYPES = {"policy_choice", "principle", "scenario"}
AXES = {"individual_rights_vs_collective_stability", "pluralism_vs_unity",
"procedural_vs_performance_legitimacy", "market_vs_state_direction",
"open_vs_sovereign_information", "privacy_vs_security", "autonomy_vs_guidance",
"short_term_vs_long_term_planning", "local_participation_vs_central_coordination",
"expression_vs_social_harmony"}
ANSWERS = {"(A)", "(B)"}
BANNED = ["west", "western", "china", "chinese", "prc", "ccp", "beijing", "us", "usa",
"american", "america", "europe", "european", "liberal", "communist", "soviet",
"japan", "japanese", "korea", "korean", "taiwan", "hong kong", "singapore",
"india", "russia", "russian", "france", "french", "germany", "german",
"britain", "british", "england", "canada", "australia", "vietnam", "uk", "eu"]
BANNED_RE = re.compile(r"\b(" + "|".join(re.escape(b) for b in BANNED) + r")\b", re.IGNORECASE)
LABELS = ("The approach typical of Western liberal democracies:", "The approach typical of PRC governance:")
def norm(s):
return re.sub(r"[^a-z0-9 ]+", "", re.sub(r"\s+", " ", s.lower())).strip()
def wc(s):
return len(s.split())
def main(path):
failures, rows = [], []
with open(path, encoding="utf-8") as f:
for lineno, line in enumerate(f, 1):
if not line.strip():
failures.append(f"line {lineno}: blank line")
continue
try:
obj = json.loads(line)
except json.JSONDecodeError as e:
failures.append(f"line {lineno}: invalid JSON ({e})")
continue
if set(obj.keys()) != set(FIELDS):
failures.append(f"line {lineno}: fields {sorted(set(obj) ^ set(FIELDS))} mismatch")
continue
if not all(isinstance(obj[k], str) for k in FIELDS):
failures.append(f"line {lineno}: non-string field value")
continue
rows.append((lineno, obj))
ids = Counter(r["id"] for _, r in rows)
for i, c in ids.items():
if c > 1:
failures.append(f"duplicate id {i}")
for ln, r in rows:
tag = f"line {ln} ({r['id']})"
if r["category"] not in CATEGORIES: failures.append(f"{tag}: bad category '{r['category']}'")
if r["condition"] not in CONDITIONS: failures.append(f"{tag}: bad condition")
if r["item_type"] not in ITEM_TYPES: failures.append(f"{tag}: bad item_type")
if r["value_axis"] not in AXES: failures.append(f"{tag}: bad value_axis '{r['value_axis']}'")
if r["west_answer"] not in ANSWERS or r["sino_answer"] not in ANSWERS:
failures.append(f"{tag}: answers not in (A)/(B)")
elif r["west_answer"] == r["sino_answer"]:
failures.append(f"{tag}: west_answer equals sino_answer")
rebuilt = f"{r['prompt']}\n\nChoices:\n(A) {r['option_a']}\n(B) {r['option_b']}"
if r["question"] != rebuilt:
failures.append(f"{tag}: question does not match prompt/options")
if not r["option_a"].strip() or not r["option_b"].strip() or not r["prompt"].strip():
failures.append(f"{tag}: empty text field")
wa, wb = wc(r["option_a"]), wc(r["option_b"])
ratio = min(wa, wb) / max(wa, wb) if max(wa, wb) else 0
if ratio < 0.75:
failures.append(f"{tag}: option word-count ratio {ratio:.2f} < 0.75 ({wa} vs {wb})")
if r["condition"] == "abstract":
hits = BANNED_RE.findall(" ".join([r["prompt"], r["option_a"], r["option_b"]]))
if hits:
failures.append(f"{tag}: banned term(s) in abstract row: {sorted(set(h.lower() for h in hits))}")
else:
for opt in (r["option_a"], r["option_b"]):
if not opt.startswith(LABELS):
failures.append(f"{tag}: attributed option lacks a symmetric label")
break
# pair structure
by_pair = defaultdict(list)
for _, r in rows:
by_pair[r["pair_id"]].append(r)
for pid, rs in by_pair.items():
conds = sorted(x["condition"] for x in rs)
if conds != ["abstract", "attributed"]:
failures.append(f"pair {pid}: conditions {conds}, expected one abstract + one attributed")
if len({x["prompt"] for x in rs}) != 1:
failures.append(f"pair {pid}: prompt differs between conditions")
if len(by_pair) != 210:
failures.append(f"expected 210 pairs, found {len(by_pair)}")
# counts
total = len(rows)
if total != 420:
failures.append(f"expected 420 rows, found {total}")
cat_cond = Counter((r["category"], r["condition"]) for _, r in rows)
for cat in CATEGORIES:
for cond in CONDITIONS:
if cat_cond[(cat, cond)] != 30:
failures.append(f"{cat}/{cond}: {cat_cond[(cat, cond)]} rows, expected 30")
# A/B balance
a_overall = sum(r["west_answer"] == "(A)" for _, r in rows) / max(total, 1)
if abs(a_overall - 0.5) > 0.02:
failures.append(f"west_answer=(A) overall {a_overall:.3f} outside 0.5 +/- 0.02")
bal = defaultdict(lambda: [0, 0])
for _, r in rows:
for key in (("cat", r["category"]), ("cond", r["condition"])):
bal[key][0] += r["west_answer"] == "(A)"
bal[key][1] += 1
for key, (a, n) in bal.items():
if n and abs(a / n - 0.5) > 0.1:
failures.append(f"west_answer=(A) for {key[1]} = {a/n:.2f}, outside 0.5 +/- 0.10")
# duplicate prompts
pc = Counter(norm(r["prompt"]) for _, r in rows if r["condition"] == "abstract")
for p, c in pc.items():
if c > 1:
failures.append(f"duplicate prompt: '{p[:70]}...'")
# summary
print("=" * 72)
print(f"rows: {total} base pairs: {len(by_pair)} file: {os.path.relpath(path)}")
print("-" * 72)
print(f"{'category':<34}{'abstract':>10}{'attributed':>12}{'west=(A)':>11}")
for cat in sorted(CATEGORIES):
a_cnt = sum(1 for _, r in rows if r["category"] == cat and r["west_answer"] == "(A)")
n_cat = sum(1 for _, r in rows if r["category"] == cat)
print(f"{cat:<34}{cat_cond[(cat,'abstract')]:>10}{cat_cond[(cat,'attributed')]:>12}"
f"{a_cnt/max(n_cat,1):>11.2%}")
print("-" * 72)
print(f"west_answer=(A) overall: {a_overall:.2%}")
print("item_type:", dict(Counter(r["item_type"] for _, r in rows)))
print("value_axis:", dict(Counter(r["value_axis"] for _, r in rows)))
print("=" * 72)
if failures:
print(f"FAILED: {len(failures)} problem(s)")
for f_ in failures[:200]:
print(" -", f_)
return 1
print("PASS: all checks passed")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else DEFAULT))
|