File size: 9,370 Bytes
4437ddb | 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 | """Deterministic political discourse measurements and review provenance checks."""
from collections import Counter, defaultdict
from datetime import datetime, timezone
import hashlib
import json
import random
import re
VERSION = "doxa-measures-0.1.0"
LABELS = ("asserted", "attributed", "qualified", "insufficient_context")
FRAMES = ("causal_responsibility", "economic_consequence", "human_impact", "institutional_process", "public_safety")
ENGINEERING_PREVIEW = "engineering_preview"
HUMAN_REVIEWED = "human_reviewed"
def timestamp(value):
result = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
if result.strftime("%Y-%m-%dT%H:%M:%SZ") != value:
raise ValueError("Timestamp must use UTC and second precision")
return result
def match_exclusion(left, right):
"""Return the first ineligibility reason against the declared matching rule."""
for field in ("event_id", "genre", "source_cohort", "claim_type"):
if not left.get(field) or left[field] != right.get(field):
return f"different_{field}"
if left["claim_type"] not in {"budget", "capacity", "service_effect", "procedural_change"}:
return "not_a_factual_comparison"
if not left.get("actor") or not right.get("actor") or left["actor"] == right["actor"]:
return "actors_not_distinct"
if left.get("role") != "left" or right.get("role") != "right":
return "role_orientation_missing"
if any(side.get("evidence_status") != "uncorroborated" for side in (left, right)):
return "uncorroborated_evidence_required"
try:
for side in (left, right):
if timestamp(side["evidence_available_at"]) > timestamp(side["published_at"]):
return "evidence_unavailable_at_publication"
hours = abs((timestamp(left["published_at"]) - timestamp(right["published_at"])).total_seconds()) / 3600
except (ValueError, KeyError, TypeError):
return "timestamp_missing_or_invalid"
if hours > 48:
return "outside_48_hour_window"
return None
def label_bounds(numerator, unresolved, eligible):
if not eligible:
return None
return [numerator / eligible, (numerator + unresolved) / eligible]
def compare(pairs, bootstrap=1000, seed=1729):
"""Compare paired presentation rates using explicit unresolved bounds."""
by_event = defaultdict(list)
exclusions = Counter()
examples = []
used_ids = set()
used_units = set()
for pair in pairs:
ident = pair["pair_id"]
if ident in used_ids:
raise ValueError(f"Duplicate pair ID: {ident}")
used_ids.add(ident)
left, right = pair["left"], pair["right"]
units = {left["unit_id"], right["unit_id"]}
if len(units) != 2 or units & used_units:
raise ValueError("Each text unit can occur in only one audit pair")
used_units.update(units)
exclusion = match_exclusion(left, right)
if exclusion:
exclusions[exclusion] += 1
examples.append({"pair_id": ident, "eligible": False, "reason": exclusion})
continue
labels = (left["label"], right["label"])
if any(label not in LABELS for label in labels):
raise ValueError(f"Unknown evidence judgment in {ident}")
values = tuple(None if label == "insufficient_context" else int(label == "asserted") for label in labels)
by_event[left["event_id"]].append(values)
examples.append({"pair_id": ident, "eligible": True, "event_id": left["event_id"],
"left_label": labels[0], "right_label": labels[1]})
all_values = [value for group in by_event.values() for value in group]
eligible = len(all_values)
sides = []
for index in (0, 1):
numer = sum(value[index] == 1 for value in all_values)
unresolved = sum(value[index] is None for value in all_values)
sides.append({"presented_as_fact": numer, "unresolved": unresolved, "eligible": eligible,
"bounds": label_bounds(numer, unresolved, eligible)})
left, right = sides
coverage = [v for v in all_values if None not in v]
gap = (sum(a - b for a, b in coverage) / len(coverage)) if coverage else None
bounds = [left["bounds"][0] - right["bounds"][1], left["bounds"][1] - right["bounds"][0]] if eligible else None
# Event-level resampling preserves dependence among pairs in one event.
groups = [tuple((a,b) for a,b in group if None not in (a,b)) for group in by_event.values()]
interval = None
if sum(bool(group) for group in groups) >= 5 and bootstrap:
rng = random.Random(seed)
samples = []
for _ in range(bootstrap):
batch = [value for group in rng.choices(groups, k=len(groups)) for value in group]
if batch:
samples.append(sum(a-b for a,b in batch) / len(batch))
if samples:
samples.sort()
interval = [samples[int(.025*(len(samples)-1))], samples[int(.975*(len(samples)-1))]]
return {
"metric_version": VERSION, "eligible_pairs": eligible, "eligible_events": len(by_event),
"complete_pairs": len(coverage), "left": left, "right": right, "gap_bounds": bounds,
"complete_pair_gap": gap, "event_bootstrap_interval": interval,
"exclusions": dict(sorted(exclusions.items())), "pairs": examples,
}
def annotated_rates(rows):
eligible = [row for row in rows if row["eligible"]]
unreviewed = sum(row["status"] != "reviewed" for row in eligible)
reviewed = [row for row in eligible if row["status"] == "reviewed"]
loaded = sum(row["loaded_wording"] for row in reviewed)
counts = Counter(frame for row in reviewed for frame in set(row["frames"]))
if set(counts) - set(FRAMES):
raise ValueError("Unknown frame")
n = len(eligible)
return {
"eligible": n, "unresolved": unreviewed,
"loaded_wording_rate": label_bounds(loaded, unreviewed, n),
"frame_prevalence": {frame: label_bounds(counts[frame], unreviewed, n) for frame in FRAMES},
}
def canonical_sha(value):
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def review_gate(rows, approvals, artifact_sha):
"""Validate recorded review evidence. This is not identity attestation."""
missing = []
if not rows:
missing.append("no_reference_judgments")
for row in rows:
ident = row["unit_id"]
if (row.get("origin") != "authentic" or not str(row.get("source_url", "")).startswith("https://")
or not row.get("rights_basis") or not re.fullmatch("[a-f0-9]{64}", str(row.get("source_sha256", "")))):
missing.append(f"authentic_rights_and_source_required:{ident}")
if row.get("label") not in LABELS:
missing.append(f"invalid_label:{ident}")
span = row.get("reference_span")
if row.get("label") != "insufficient_context":
if not span or not valid_span(row, span):
missing.append(f"source_span_required:{ident}")
by_person = {x["reviewer_id"]: x for x in row.get("reviews", [])
if x["origin"] == "human" and x["independent"]}
if len(by_person) < 2:
missing.append(f"insufficient_human_reviews:{ident}")
elif row.get("origin") == "fictional":
missing.append(f"fictional_fixture:{ident}")
else:
decisions = {item["label"] for item in by_person.values()}
if len(decisions) == 1 and row.get("label") not in decisions:
missing.append(f"reference_disagrees_with_review:{ident}")
if len(decisions) > 1:
adjudication = row.get("adjudication", {})
if (adjudication.get("reviewer_id") in by_person or not adjudication.get("reviewer_id")
or adjudication.get("label") != row.get("label") or not adjudication.get("rationale")):
missing.append(f"adjudication_required:{ident}")
required = ("methods_reviewer", "independent_reproduction_engineer")
people = defaultdict(set)
for approval in approvals:
if (approval.get("artifact_sha256") == artifact_sha and approval.get("decision") == "approve"
and approval.get("origin") == "human" and approval.get("independent")
and approval.get("reviewer_id") and approval.get("recorded_at")):
people[approval["role"]].add(approval["reviewer_id"])
for role in required:
if not people[role]:
missing.append(f"approval_required:{role}")
if people[required[0]] and people[required[1]] and len(people[required[0]] | people[required[1]]) < 2:
missing.append("distinct_release_reviewers_required")
return {"ready_for_human_reviewed_release": not missing, "failures": missing,
"artifact_sha256": artifact_sha, "verification": "record_validation_only"}
def valid_span(row, span):
field = {"passage":"text", "context":"context"}.get(span.get("segment"))
source = row.get(field)
start, end = span.get("start"), span.get("end")
return (isinstance(source,str) and type(start) is int and type(end) is int
and 0 <= start < end <= len(source) and source[start:end] == span.get("quote"))
|