Spaces:
Sleeping

script / kappa_calculator.py
Lara Monteagudo Tubau
Fix 5 bugs: f-string crash, broken streaming, pending rules filter, chunk dedup, silent discard
ab719c7
Raw History Blame Contribute Delete
35.7 kB
"""
kappa_calculator.py
-------------------
Inter-rater reliability for CollabCode.
PRIMARY METRIC : Gwet's AC1 (Gwet 2008)
SECONDARY METRIC: Cohen's Kappa (Cohen 1960) β€” retained for journal compatibility
GATE THRESHOLD : AC1 β‰₯ 0.70
Why AC1 over Cohen's ΞΊ?
-----------------------
Cohen's ΞΊ has a well-documented prevalence-bias problem: when one or more categories
dominate the distribution (common in CSCL coding β€” D3 and D9 typically appear far
more often than D6 or D7), ΞΊ is systematically depressed below the actual level of
agreement. Two coders can genuinely agree 80% of the time but produce ΞΊ < 0.50
purely because of category imbalance. This makes sessions appear to fail the
reliability gate when coders are actually working well.
Gwet's AC1 corrects for this by computing chance agreement as a function of the
*average* marginal proportions (not their product), which is bounded away from 1
even when one category dominates β€” preventing artificial depression of the metric.
Byrt, Bishop & Carlin (1993) demonstrated the mathematical basis for this artifact
in ΞΊ. Gwet (2008) proposed AC1 as the correction. Wongpakaran et al. (2013)
validated AC1 clinically across imbalanced coding schemes.
Key references
--------------
Gwet, K. L. (2008). Computing inter-rater reliability and its variance in the
presence of high agreement. British Journal of Mathematical and Statistical
Psychology, 61(1), 29–48.
Byrt, T., Bishop, J., & Carlin, J. B. (1993). Bias, prevalence and kappa.
Journal of Clinical Epidemiology, 46(5), 423–429.
Cohen, J. (1960). A coefficient of agreement for nominal scales.
Educational and Psychological Measurement, 20(1), 37–46.
Wongpakaran, N., Wongpakaran, T., Wedding, D., & Gwet, K. L. (2013).
A comparison of Cohen's kappa and Gwet's AC1 when calculating inter-rater
reliability coefficients. BMC Medical Research Methodology, 13(1), 61.
Landis, J. R., & Koch, G. G. (1977). The measurement of observer agreement
for categorical data. Biometrics, 33(1), 159–174.
β€” Verbal interpretation benchmarks (same numeric thresholds used for both ΞΊ and AC1).
Bujang, M. A., & Baharum, N. (2017). Guidelines of the minimum sample size
requirements for Cohen's Kappa. Epidemiology, Biostatistics and Public Health, 14(2).
β€” Sample size guidance applies equally to AC1 given equivalent statistical power.
Confidence intervals
--------------------
95% percentile bootstrap CIs (B=1000 resamples, seed=42 for reproducibility).
The bootstrap is preferred over analytical SEs for small samples (N<100) and
non-normal coefficient distributions, as is common with AC1 near 0 or 1.
Efron, B., & Tibshirani, R. J. (1994). An Introduction to the Bootstrap.
Chapman & Hall. β€” Bootstrap CI methodology.
Per-dimension reliability
-------------------------
Computed as a binary one-vs-rest AC1: for each dimension D, labels are recoded as
{D, not-D} and AC1 is computed on these binary labels. This correctly answers
"how reliably can coders identify episodes of dimension D?" without the distributional
distortion introduced by the subsetting approach used for Cohen's ΞΊ.
Gate note
---------
AC1 β‰₯ 0.70 is retained as the same numeric threshold as the prior ΞΊ gate. In
balanced distributions AC1 β‰ˆ ΞΊ; in imbalanced distributions AC1 > ΞΊ, so the gate
is slightly more lenient than ΞΊ β‰₯ 0.70 would have been. This is intentional:
the gate should reflect actual agreement, not measurement artefact.
"""
from __future__ import annotations
import json
import random
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
AC1_GATE_THRESHOLD = 0.70 # primary gate (Gwet's AC1)
KAPPA_THRESHOLD = 0.70 # secondary reference (Cohen's ΞΊ)
DIMENSIONS = ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "NS", "NA"]
N_BOOTSTRAP = 1000 # resamples for confidence intervals
CI_LEVEL = 0.95 # 95% CI
BOOTSTRAP_SEED = 42 # fixed seed β†’ reproducible CIs across runs
# Prevalence warning: flag if any single category accounts for more than this
# proportion of all codings, as κ–AC1 divergence becomes large above ~40%.
PREVALENCE_WARNING_THRESHOLD = 0.40
# ---------------------------------------------------------------------------
# Data loaders (unchanged API)
# ---------------------------------------------------------------------------
def load_coding(filepath: Path) -> dict:
data = json.loads(filepath.read_text(encoding="utf-8"))
if "codings" not in data:
raise ValueError(f"Coding file missing 'codings' key: {filepath}")
if "researcher_id" not in data:
raise ValueError(f"Coding file missing 'researcher_id': {filepath}")
return data
def load_proposed_segments(filepath: Path) -> dict:
data = json.loads(filepath.read_text(encoding="utf-8"))
if "segments" not in data:
raise ValueError(f"Segments file missing 'segments' key: {filepath}")
return {seg["segment_id"]: seg for seg in data["segments"]}
# ---------------------------------------------------------------------------
# Validation (unchanged)
# ---------------------------------------------------------------------------
def validate_codings(
coding_r1: dict,
coding_r2: dict,
proposed_segments: dict,
) -> list[str]:
errors = []
ids_r1 = {c["segment_id"] for c in coding_r1["codings"]}
ids_r2 = {c["segment_id"] for c in coding_r2["codings"]}
ids_all = set(proposed_segments.keys())
missing_r1 = ids_all - ids_r1
missing_r2 = ids_all - ids_r2
extra_r1 = ids_r1 - ids_all
extra_r2 = ids_r2 - ids_all
if missing_r1:
errors.append(f"{coding_r1['researcher_id']} has not coded: {sorted(missing_r1)}")
if missing_r2:
errors.append(f"{coding_r2['researcher_id']} has not coded: {sorted(missing_r2)}")
if extra_r1:
errors.append(f"{coding_r1['researcher_id']} coded unknown segments: {sorted(extra_r1)}")
if extra_r2:
errors.append(f"{coding_r2['researcher_id']} coded unknown segments: {sorted(extra_r2)}")
for coding in [coding_r1, coding_r2]:
for c in coding["codings"]:
if c["dimension_id"] not in DIMENSIONS:
errors.append(
f"{coding['researcher_id']} used unknown dimension "
f"'{c['dimension_id']}' for {c['segment_id']}"
)
# secondary_dimension_id is optional; only validate if present and non-null
sec = c.get("secondary_dimension_id")
if sec is not None and sec not in DIMENSIONS:
errors.append(
f"{coding['researcher_id']} used unknown secondary dimension "
f"'{sec}' for {c['segment_id']}"
)
if sec is not None and sec == c.get("dimension_id"):
errors.append(
f"{coding['researcher_id']} set secondary == primary "
f"('{sec}') for {c['segment_id']} β€” secondary must differ"
)
return errors
# ---------------------------------------------------------------------------
# Alignment helper
# ---------------------------------------------------------------------------
def _build_aligned_labels(
coding_r1: dict,
coding_r2: dict,
) -> tuple[list[str], list[str], list[str]]:
map_r1 = {c["segment_id"]: c["dimension_id"] for c in coding_r1["codings"]}
map_r2 = {c["segment_id"]: c["dimension_id"] for c in coding_r2["codings"]}
shared = sorted(set(map_r1) & set(map_r2))
return shared, [map_r1[s] for s in shared], [map_r2[s] for s in shared]
# ---------------------------------------------------------------------------
# Core agreement functions
# ---------------------------------------------------------------------------
def _observed_agreement(labels_a: list[str], labels_b: list[str]) -> float:
n = len(labels_a)
return sum(a == b for a, b in zip(labels_a, labels_b)) / n if n else 0.0
def _cohen_kappa(labels_a: list[str], labels_b: list[str]) -> float:
"""
Cohen's ΞΊ (Cohen 1960).
Preserved for journal compatibility; AC1 is the primary metric.
Known limitation: depressed by prevalence imbalance β€” do not use alone as
the gate metric (Byrt, Bishop & Carlin 1993).
"""
n = len(labels_a)
if n == 0:
return 0.0
p_o = _observed_agreement(labels_a, labels_b)
cats = set(labels_a) | set(labels_b)
p_e = sum((labels_a.count(c) / n) * (labels_b.count(c) / n) for c in cats)
if p_e >= 1.0:
return 1.0 if p_o >= 1.0 else 0.0
return (p_o - p_e) / (1.0 - p_e)
def _gwet_ac1(labels_a: list[str], labels_b: list[str]) -> float:
"""
Gwet's AC1 (Gwet 2008).
Chance agreement formula:
P_e = [1 / (K-1)] * Ξ£_k Ο€_k * (1 - Ο€_k)
where Ο€_k = average marginal proportion for category k,
K = number of distinct categories used by either rater.
This P_e is bounded away from 1 even when one category dominates,
preventing the prevalence-induced depression of ΞΊ.
"""
n = len(labels_a)
if n == 0:
return 0.0
p_o = _observed_agreement(labels_a, labels_b)
cats = set(labels_a) | set(labels_b)
K = len(cats)
if K <= 1:
return 1.0 if p_o >= 1.0 else 0.0
p_e = sum(
((labels_a.count(c) / n + labels_b.count(c) / n) / 2)
* (1 - (labels_a.count(c) / n + labels_b.count(c) / n) / 2)
for c in cats
) / (K - 1)
if p_e >= 1.0:
return 1.0 if p_o >= 1.0 else 0.0
return (p_o - p_e) / (1.0 - p_e)
def _bootstrap_ci(
labels_a: list[str],
labels_b: list[str],
fn,
n_boot: int = N_BOOTSTRAP,
ci: float = CI_LEVEL,
seed: int = BOOTSTRAP_SEED,
) -> tuple[float, float]:
"""
Percentile bootstrap CI for any reliability function fn(a, b) β†’ float.
(Efron & Tibshirani 1994)
Critical implementation detail: indices are shared across both raters so
that (label_a_i, label_b_i) pairs are resampled together. Independent
resampling would break the pairing and produce nonsensical reliability
estimates on shuffled data.
Preferred over analytical SEs for small N and non-normal coefficient
distributions, as is common with AC1 near 0 or 1.
"""
rng = random.Random(seed)
n = len(labels_a)
boots: list[float] = []
for _ in range(n_boot):
# One set of indices used for BOTH raters β€” paired resampling
idxs = [rng.randrange(n) for _ in range(n)]
ba = [labels_a[i] for i in idxs]
bb = [labels_b[i] for i in idxs]
boots.append(fn(ba, bb))
boots.sort()
lo_idx = int(n_boot * (1 - ci) / 2)
hi_idx = min(int(n_boot * (1 + ci) / 2), n_boot - 1)
return round(boots[lo_idx], 4), round(boots[hi_idx], 4)
# ---------------------------------------------------------------------------
# Interpretation (Landis & Koch 1977 benchmarks β€” apply to both ΞΊ and AC1)
# ---------------------------------------------------------------------------
def _interpret(value: float) -> str:
if value < 0:
return "poor β€” worse than chance"
elif value < 0.20:
return "slight"
elif value < 0.40:
return "fair"
elif value < 0.60:
return "moderate"
elif value < 0.70:
return "substantial β€” below gate"
elif value < 0.80:
return "substantial β€” gate passed"
elif value < 0.90:
return "strong"
else:
return "near-perfect"
# Keep old name for any external callers
def interpret_kappa(kappa: float) -> str:
return _interpret(kappa)
# ---------------------------------------------------------------------------
# Per-dimension reliability
# ---------------------------------------------------------------------------
def _binary_labels(labels: list[str], target_dim: str) -> list[str]:
"""Recode to binary: target_dim vs. 'other'. One-vs-rest for per-dim AC1."""
return [target_dim if l == target_dim else "_other_" for l in labels]
def calculate_per_dimension_kappa(
segment_ids: list[str],
labels_r1: list[str],
labels_r2: list[str],
) -> dict[str, Optional[float]]:
"""
Cohen's ΞΊ per dimension β€” subsetting approach (retained for backwards compatibility).
Subset = segments where at least one rater used that dimension.
"""
per_dim = {}
for dim in DIMENSIONS:
idxs = [i for i, (a, b) in enumerate(zip(labels_r1, labels_r2))
if a == dim or b == dim]
if len(idxs) < 2:
per_dim[dim] = None
continue
sub_r1 = [labels_r1[i] for i in idxs]
sub_r2 = [labels_r2[i] for i in idxs]
per_dim[dim] = round(_cohen_kappa(sub_r1, sub_r2), 4)
return per_dim
def calculate_per_dimension_ac1(
segment_ids: list[str],
labels_r1: list[str],
labels_r2: list[str],
) -> dict[str, Optional[float]]:
"""
Gwet's AC1 per dimension β€” binary one-vs-rest approach.
For each dimension D:
Recode all labels as {D, "_other_"} and compute AC1.
Answers: "how reliably can raters identify episodes of dimension D?"
This avoids the distributional distortion of the subsetting approach and
gives a reliability estimate that is directly interpretable for each dimension.
Requires β‰₯ 2 instances of the target dimension (summed across both raters).
"""
per_dim: dict[str, Optional[float]] = {}
for dim in DIMENSIONS:
n_instances = sum(1 for l in labels_r1 + labels_r2 if l == dim)
if n_instances < 2:
per_dim[dim] = None
continue
bin_r1 = _binary_labels(labels_r1, dim)
bin_r2 = _binary_labels(labels_r2, dim)
per_dim[dim] = round(_gwet_ac1(bin_r1, bin_r2), 4)
return per_dim
# ---------------------------------------------------------------------------
# Category distribution / prevalence diagnostics
# ---------------------------------------------------------------------------
def _compute_category_distribution(
labels_r1: list[str],
labels_r2: list[str],
) -> dict[str, dict]:
"""
Compute per-category counts and prevalence for both raters.
Prevalence = average proportion across both raters.
High prevalence (> PREVALENCE_WARNING_THRESHOLD) indicates potential
κ–AC1 divergence: AC1 will be notably higher than ΞΊ in these cases.
"""
n = len(labels_r1)
if n == 0:
return {}
dist: dict[str, dict] = {}
for dim in DIMENSIONS:
c1 = labels_r1.count(dim)
c2 = labels_r2.count(dim)
prev = ((c1 / n) + (c2 / n)) / 2
if c1 > 0 or c2 > 0:
dist[dim] = {
"r1_count": c1,
"r2_count": c2,
"prevalence": round(prev, 4),
}
return dist
def _prevalence_warning(dist: dict[str, dict]) -> bool:
"""True if any category's prevalence exceeds the warning threshold."""
return any(
v["prevalence"] > PREVALENCE_WARNING_THRESHOLD
for v in dist.values()
)
# ---------------------------------------------------------------------------
# Secondary dimension analysis
# ---------------------------------------------------------------------------
_NO_SECONDARY = "NONE" # sentinel label used when secondary_dimension_id is null
def _extract_secondary_labels(
coding_r1: dict,
coding_r2: dict,
segment_ids: list[str],
) -> tuple[list[str], list[str]]:
"""
Build paired secondary-label lists aligned by segment_id.
Segments with no secondary are labelled _NO_SECONDARY.
This treats "no secondary dimension" as a valid, explicit category β€”
which is correct, since most segments are single-dimensional and both
raters marking no secondary is a genuine agreement.
"""
map_r1 = {c["segment_id"]: c.get("secondary_dimension_id") or _NO_SECONDARY
for c in coding_r1["codings"]}
map_r2 = {c["segment_id"]: c.get("secondary_dimension_id") or _NO_SECONDARY
for c in coding_r2["codings"]}
sec_r1 = [map_r1.get(sid, _NO_SECONDARY) for sid in segment_ids]
sec_r2 = [map_r2.get(sid, _NO_SECONDARY) for sid in segment_ids]
return sec_r1, sec_r2
def _compute_secondary_agreement(
coding_r1: dict,
coding_r2: dict,
segment_ids: list[str],
) -> dict:
"""
Compute Gwet's AC1 for secondary dimension labels.
High prevalence of _NO_SECONDARY is expected and correct β€” AC1 handles
this naturally without the prevalence bias that would afflict Cohen's ΞΊ
in the same situation (Byrt, Bishop & Carlin 1993).
Returns a dict with:
n_with_secondary_r1 : segments where R1 marked a secondary
n_with_secondary_r2 : segments where R2 marked a secondary
n_with_secondary_both : segments where BOTH marked a secondary
secondary_agreement_ac1 : AC1 on secondary labels (NONE treated as valid category)
secondary_ci_95 : bootstrap CI for secondary AC1
secondary_interpretation : verbal label
"""
sec_r1, sec_r2 = _extract_secondary_labels(coding_r1, coding_r2, segment_ids)
n_r1 = sum(1 for l in sec_r1 if l != _NO_SECONDARY)
n_r2 = sum(1 for l in sec_r2 if l != _NO_SECONDARY)
n_both = sum(1 for a, b in zip(sec_r1, sec_r2)
if a != _NO_SECONDARY and b != _NO_SECONDARY)
if n_r1 == 0 and n_r2 == 0:
return {
"n_with_secondary_r1": 0,
"n_with_secondary_r2": 0,
"n_with_secondary_both": 0,
"secondary_agreement_ac1":None,
"secondary_ci_95": None,
"secondary_interpretation":"no secondary dimensions used",
}
ac1 = round(_gwet_ac1(sec_r1, sec_r2), 4)
ci = _bootstrap_ci(sec_r1, sec_r2, _gwet_ac1)
return {
"n_with_secondary_r1": n_r1,
"n_with_secondary_r2": n_r2,
"n_with_secondary_both": n_both,
"secondary_agreement_ac1":ac1,
"secondary_ci_95": list(ci),
"secondary_interpretation":_interpret(ac1),
}
def _compute_codimension_frequency(
coding_r1: dict,
coding_r2: dict,
segment_ids: list[str],
) -> dict[str, int]:
"""
Count how often each (primary + secondary) dimension pair occurs
across both raters' codings.
Segments without a secondary are recorded as "{primary}" only.
Segments with a secondary are recorded as "{primary}+{secondary}".
This reveals which dimension combinations co-occur in the corpus β€”
useful for theory refinement and for identifying where the single-code
assumption is most strained (Strijbos et al. 2006; Suthers & Rosen 2011).
"""
counts: dict[str, int] = {}
for coding in [coding_r1, coding_r2]:
for c in coding["codings"]:
if c["segment_id"] not in segment_ids:
continue
prim = c.get("dimension_id", "?")
sec = c.get("secondary_dimension_id")
key = f"{prim}+{sec}" if sec else prim
counts[key] = counts.get(key, 0) + 1
# Sort by frequency descending
return dict(sorted(counts.items(), key=lambda x: -x[1]))
# ---------------------------------------------------------------------------
# Disagreement analysis (unchanged)
# ---------------------------------------------------------------------------
def identify_disagreements(
segment_ids: list[str],
labels_r1: list[str],
labels_r2: list[str],
coding_r1: dict,
coding_r2: dict,
proposed_segments: dict,
) -> list[dict]:
map_comments_r1 = {c["segment_id"]: c.get("comment", "") for c in coding_r1["codings"]}
map_comments_r2 = {c["segment_id"]: c.get("comment", "") for c in coding_r2["codings"]}
disagreements = []
for sid, d1, d2 in zip(segment_ids, labels_r1, labels_r2):
if d1 != d2:
seg = proposed_segments.get(sid, {})
# Backwards-compatible field names use researcher_id prefix
r1id = coding_r1["researcher_id"]
r2id = coding_r2["researcher_id"]
disagreements.append({
"segment_id": sid,
"start_time": seg.get("start_time"),
"end_time": seg.get("end_time"),
"agent_dimension": seg.get("dimension_id"),
"agent1_dimension": seg.get("dimension_id"), # legacy key
"agent1_rationale": seg.get("rationale"),
"r1_dimension": d1,
"r2_dimension": d2,
f"{r1id}_dimension": d1,
f"{r1id}_comment": map_comments_r1.get(sid, ""),
f"{r2id}_dimension": d2,
f"{r2id}_comment": map_comments_r2.get(sid, ""),
"resolution_status": "pending",
"resolved_dimension": None,
"resolution_note": "",
})
return disagreements
# ---------------------------------------------------------------------------
# Main report builder
# ---------------------------------------------------------------------------
def calculate_kappa_report(
session_id: str,
coding_r1_path: Path,
coding_r2_path: Path,
proposed_segments_path: Path,
output_path: Optional[Path] = None,
) -> dict:
"""
Full inter-rater reliability report for a session.
Returns a dict with both AC1 (primary) and ΞΊ (secondary), per-dimension
breakdowns for both metrics, bootstrap CIs, prevalence diagnostics,
and the full disagreement list with resolution tracking.
The report is backwards-compatible: all fields present in the prior
kappa-only report are retained. New fields are additive.
"""
coding_r1 = load_coding(coding_r1_path)
coding_r2 = load_coding(coding_r2_path)
proposed_segments = load_proposed_segments(proposed_segments_path)
errors = validate_codings(coding_r1, coding_r2, proposed_segments)
if errors:
raise ValueError(
"Coding validation failed:\n" + "\n".join(f" - {e}" for e in errors)
)
segment_ids, labels_r1, labels_r2 = _build_aligned_labels(coding_r1, coding_r2)
n = len(segment_ids)
n_agree = sum(a == b for a, b in zip(labels_r1, labels_r2))
n_dis = n - n_agree
# ── Primary metric: Gwet's AC1 ──────────────────────────────────────────
ac1 = round(_gwet_ac1(labels_r1, labels_r2), 4)
ac1_ci = _bootstrap_ci(labels_r1, labels_r2, _gwet_ac1)
ac1_dim = calculate_per_dimension_ac1(segment_ids, labels_r1, labels_r2)
# ── Secondary metric: Cohen's ΞΊ ─────────────────────────────────────────
kappa = round(_cohen_kappa(labels_r1, labels_r2), 4)
kappa_ci = _bootstrap_ci(labels_r1, labels_r2, _cohen_kappa)
kappa_dim = calculate_per_dimension_kappa(segment_ids, labels_r1, labels_r2)
# ── Prevalence diagnostics ───────────────────────────────────────────────
cat_dist = _compute_category_distribution(labels_r1, labels_r2)
prev_warning = _prevalence_warning(cat_dist)
divergence = round(abs(ac1 - kappa), 4)
divergence_flag = divergence > 0.05 # notable divergence: ΞΊ is biased
# ── Gate ────────────────────────────────────────────────────────────────
gate_passed = ac1 >= AC1_GATE_THRESHOLD
# ── Secondary dimension analysis ─────────────────────────────────────────
secondary_analysis = _compute_secondary_agreement(coding_r1, coding_r2, segment_ids)
codimension_freq = _compute_codimension_frequency(coding_r1, coding_r2, segment_ids)
# ── Disagreements ────────────────────────────────────────────────────────
disagreements = identify_disagreements(
segment_ids, labels_r1, labels_r2,
coding_r1, coding_r2, proposed_segments,
)
report = {
# ── Session metadata ────────────────────────────────────────────────
"session_id": session_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
"researcher_1": coding_r1["researcher_id"],
"researcher_2": coding_r2["researcher_id"],
"n_segments_total": n,
"n_segments_agreed": n_agree,
"n_segments_disagreed": n_dis,
# ── PRIMARY: Gwet's AC1 ─────────────────────────────────────────────
"overall_ac1": ac1,
"ac1_ci_95": list(ac1_ci),
"ac1_interpretation": _interpret(ac1),
"ac1_per_dimension": ac1_dim,
# ── SECONDARY: Cohen's ΞΊ (kept for journal compatibility) ───────────
"overall_kappa": kappa, # legacy key preserved
"kappa_ci_95": list(kappa_ci),
"kappa_interpretation": _interpret(kappa),
"kappa_per_dimension": kappa_dim,
# ── Gate ────────────────────────────────────────────────────────────
"gate_metric": "gwet_ac1",
"gate_threshold": AC1_GATE_THRESHOLD,
"gate_passed": gate_passed,
# ── Prevalence diagnostics ──────────────────────────────────────────
"category_distribution": cat_dist,
"prevalence_warning": prev_warning,
"kappa_ac1_divergence": divergence,
"kappa_ac1_divergence_flag": divergence_flag,
# ── Secondary dimension analysis ──────────────────────────────────────
"secondary_dimension_analysis": secondary_analysis,
"codimension_frequency": codimension_freq,
# ── Disagreements ────────────────────────────────────────────────────
"segments_in_disagreement": [d["segment_id"] for d in disagreements],
"disagreements": disagreements,
# ── Status ───────────────────────────────────────────────────────────
"status": (
"ready_for_agent2"
if gate_passed and not disagreements
else "pending_disagreement_review"
if gate_passed
else "below_threshold_review_required"
),
}
if output_path:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8"
)
print(f"[Reliability] Report saved to {output_path}")
_print_summary(report)
return report
# ---------------------------------------------------------------------------
# Disagreement resolution (unchanged API)
# ---------------------------------------------------------------------------
def resolve_disagreement(
report_path: Path,
segment_id: str,
resolved_dimension: str,
resolution_note: str,
) -> dict:
report = json.loads(report_path.read_text(encoding="utf-8"))
found = False
for d in report["disagreements"]:
if d["segment_id"] == segment_id:
d["resolution_status"] = "resolved"
d["resolved_dimension"] = resolved_dimension
d["resolution_note"] = resolution_note
found = True
if not found:
raise ValueError(f"Segment '{segment_id}' not found in disagreements.")
if all(d["resolution_status"] in ("resolved", "discarded")
for d in report["disagreements"]) and report["gate_passed"]:
report["status"] = "ready_for_agent2"
report_path.write_text(
json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8"
)
print(f"[Reliability] Resolved {segment_id} β†’ {resolved_dimension}")
return report
def discard_disagreement(
report_path: Path,
segment_id: str,
discard_note: str,
) -> dict:
report = json.loads(report_path.read_text(encoding="utf-8"))
found = False
for d in report["disagreements"]:
if d["segment_id"] == segment_id:
d["resolution_status"] = "discarded"
d["resolved_dimension"] = None
d["resolution_note"] = discard_note
found = True
if not found:
raise ValueError(f"Segment '{segment_id}' not found in disagreements.")
if all(d["resolution_status"] in ("resolved", "discarded")
for d in report["disagreements"]) and report["gate_passed"]:
report["status"] = "ready_for_agent2"
report_path.write_text(
json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8"
)
print(f"[Reliability] Discarded {segment_id}")
return report
# ---------------------------------------------------------------------------
# Console summary
# ---------------------------------------------------------------------------
def _print_summary(report: dict) -> None:
print("\n" + "═" * 60)
print(f" RELIABILITY REPORT β€” {report['session_id']}")
print("═" * 60)
print(f" Raters : {report['researcher_1']} vs {report['researcher_2']}")
print(f" Segments : {report['n_segments_total']} total, "
f"{report['n_segments_agreed']} agreed, "
f"{report['n_segments_disagreed']} disagreed")
print()
print(f" PRIMARY β€” Gwet's AC1 (Gwet 2008):")
ac1_lo, ac1_hi = report['ac1_ci_95']
print(f" AC1 = {report['overall_ac1']:.4f} "
f"95% CI [{ac1_lo:.4f}, {ac1_hi:.4f}]")
print(f" Interpretation: {report['ac1_interpretation']}")
print(f" Gate (AC1 β‰₯ {report['gate_threshold']:.2f}): "
f"{'βœ“ PASSED' if report['gate_passed'] else 'βœ— FAILED'}")
print()
print(f" SECONDARY β€” Cohen's ΞΊ (Cohen 1960) [for reference only]:")
k_lo, k_hi = report['kappa_ci_95']
print(f" ΞΊ = {report['overall_kappa']:.4f} "
f"95% CI [{k_lo:.4f}, {k_hi:.4f}]")
print(f" |AC1 - ΞΊ| = {report['kappa_ac1_divergence']:.4f}"
+ (" ← notable divergence (prevalence bias in ΞΊ)"
if report['kappa_ac1_divergence_flag'] else ""))
if report.get("prevalence_warning"):
dom = max(report["category_distribution"].items(),
key=lambda x: x[1]["prevalence"])
print(f"\n ⚠ Prevalence warning: '{dom[0]}' accounts for "
f"{dom[1]['prevalence']:.0%} of all codings. "
f"AC1 is the appropriate metric here.")
print("\n Per-dimension AC1 (one-vs-rest):")
for dim in DIMENSIONS:
v = report["ac1_per_dimension"].get(dim)
if v is not None:
bar = "β–“" * int(v * 20)
gate_flag = " βœ“" if v >= AC1_GATE_THRESHOLD else " Β·"
print(f" {dim} {v:.3f} {bar}{gate_flag}")
else:
print(f" {dim} β€” (insufficient data)")
# Secondary dimension summary
sec = report.get("secondary_dimension_analysis", {})
if sec.get("n_with_secondary_r1", 0) > 0 or sec.get("n_with_secondary_r2", 0) > 0:
print(f"\n Secondary dimensions:")
print(f" R1 used secondary in {sec.get('n_with_secondary_r1',0)} segments")
print(f" R2 used secondary in {sec.get('n_with_secondary_r2',0)} segments")
print(f" Both used secondary in {sec.get('n_with_secondary_both',0)} segments")
ac1s = sec.get("secondary_agreement_ac1")
if ac1s is not None:
print(f" Secondary AC1: {ac1s:.4f} ({sec.get('secondary_interpretation','')})")
cdf = report.get("codimension_frequency", {})
multi_pairs = {k: v for k, v in cdf.items() if "+" in k}
if multi_pairs:
print(f" Co-occurring pairs:")
for pair, count in list(multi_pairs.items())[:5]:
print(f" {pair}: {count}x")
else:
print("\n Secondary dimensions: none used in this session")
print(f"\n Status: {report['status']}")
print("═" * 60 + "\n")
# ---------------------------------------------------------------------------
# Coding template generator (unchanged)
# ---------------------------------------------------------------------------
def generate_coding_template(
proposed_segments_path: Path,
researcher_id: str,
session_id: str,
output_path: Path,
) -> None:
proposed = json.loads(proposed_segments_path.read_text(encoding="utf-8"))
template = {
"researcher_id": researcher_id,
"session_id": session_id,
"instructions": (
"Fill in dimension_id (D1–D9, NS=Not Sure, NA=Not Applicable). "
"Use comment for boundary concerns or ambiguity notes."
),
"codings": [
{
"segment_id": seg["segment_id"],
"start_time": seg.get("start_time"),
"end_time": seg.get("end_time"),
"agent1_label": seg.get("dimension_id"),
"agent1_rationale": seg.get("rationale"),
"dimension_id": "",
"comment": "",
}
for seg in proposed["segments"]
],
}
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(template, indent=2, ensure_ascii=False), encoding="utf-8"
)
print(f"[Reliability] Template for {researcher_id} saved to {output_path}")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage:")
print(" python kappa_calculator.py calc <session_id> <r1.json> <r2.json> <segments.json> [report.json]")
print(" python kappa_calculator.py template <segments.json> <researcher_id> <session_id> <output.json>")
sys.exit(1)
command = sys.argv[1]
if command == "calc":
calculate_kappa_report(
sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4]), Path(sys.argv[5]),
Path(sys.argv[6]) if len(sys.argv) > 6 else None,
)
elif command == "template":
generate_coding_template(
Path(sys.argv[2]), sys.argv[3], sys.argv[4], Path(sys.argv[5])
)
else:
print(f"Unknown command: {command}")
sys.exit(1)