POSA_Copyrighter/scripts/sweep_thresholds.py
changukyu c740c2e6ba feat: 캘리브레이션 측정 도구 + 스코어러 구조적 거동 첫 실측
SCORER_VERSION 이 v1 에서 v4 까지 갔는데 v3(제공자별 풀링)와 v4(신뢰 출처)는
밴드 분포를 한 번도 측정하지 않고 나갔다. 2026-08-08 평가가 쓴 224조합 하네스는
저장소에 남아 있지 않고, 그 문서의 두 수치(174/224=77.7% 와 82.6%)가 서로 맞지
않아 격자가 달랐음을 시사한다 — 과거 숫자와 비교 가능한 재현은 불가능하다.
그래서 격자를 스크립트에 명시적으로 고정해 새 기준선으로 삼는다.

  scripts/score_distribution.py   432조합 전수, 사람 없이 돈다
  scripts/sweep_thresholds.py     판정 시점 스냅샷 기준 임계 스윕
  docs/operations/calibration-corpus.md  코퍼스 절차

실측 결과(v4, 432조합):

                     신뢰출처 미등록   신뢰출처 등록
  high                      92%            63%
  100점 포화                80%            38%
  웹 신호만으로 high      13/24           0/24

두 가지가 드러났다.

1. v2 가 세운 "웹 존재만으로는 high 가 되지 않는다" 원칙이 이미 깨져 있다.
   presence 풀(최대 60)과 entity 풀(최대 20)이 각각 임계 아래로 캡되지만 합은
   캡되지 않아, full+partial + 엔티티 1개만으로 80/high 가 된다.

2. v3 의 제공자별 풀링이 그 경향을 키웠다. 독립 제공자가 하나 더 있으면 웹 전용
   조합의 high 가 4/12 -> 9/12, 전체 high 가 88% -> 97% 가 된다. 교차 확증이
   high 에 닿아야 한다는 v3 의 의도대로 동작한 결과지만 총량 통제가 없다.

대응 후보(웹 유래 점수 총합 상한)는 적용하지 않았다. 적용하면 또 한 번의
미측정 변경이 되고, 이번 실측이 바로 그 패턴을 지적한 것이기 때문이다.
결정 후 진행한다 — 적용 시 SCORER_VERSION 을 올리고 이 표를 다시 측정한다.

이 격자는 신호 축을 균등 샘플링하므로 실제 큐 분포가 아니다. 92% 는 "실제 큐의
92% 가 high"라는 뜻이 아니고 임계가 맞는지도 말해주지 않는다. 구조적 거동의
기준선일 뿐이다.

임계 검증은 실이미지 30~50장과 **사람의 판정**이 있어야 성립한다. 내가 판정을
만들면 도구의 밴드를 내 라벨과 대조하는 꼴이라 아무것도 검증되지 않는다.
sweep_thresholds.py 는 그때를 위한 도구이고, 지금은 usable pairs 0 을 정직하게
보고한다(가짜 판정 6건을 넣은 사본 DB 로 출력 동작은 확인했다).

검증: ruff clean, pytest 645 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BStHFrjQj2VypecSG9ex1V
2026-09-22 08:56:57 +09:00

144 lines
5.3 KiB
Python

"""운영자 판정과 대조해 밴드 임계(기본 70/30)가 맞는지 스윕한다.
**왜 decision_stats 가 아니라 이것인가**
`decision_stats` 의 교차표는 제출물의 **현재** riskBand 를 쓴다. 그런데
`_rescore_submission` 이 14개 지점에서 점수를 덮어쓰고 폴더 리로드마다 큐 전체를
리스코어하므로, 판정한 뒤 이미지를 더 넣으면 이미 판정된 케이스의 밴드가 바뀌어
교차표가 소급 변동한다. 판정 시점의 점수를 보존하는 것은 `decisionSnapshot` 뿐이다.
그래서 이 스크립트는 스냅샷에서 (판정 시점 점수, 판정) 쌍만 뽑아 임계를 스윕한다.
**제외되는 행** — 제외 사유를 반드시 함께 읽어야 한다:
unreviewed 아직 판정 안 함
no_snapshot 판정은 있으나 스냅샷이 없음 (스냅샷 도입 이전)
legacy_pre_stamp 스코어러 스탬프 도입 이전 행. 원점수를 복원할 수 없다
**읽는 법**
over = high 로 분류했는데 운영자가 승인한 건수 → 과탐. 많으면 high 임계가 낮다.
under = low 로 분류했는데 운영자가 반려한 건수 → 미탐. 0 이 아니면 medium 임계가 높다.
분모(high_n / low_n)가 5 미만인 줄은 해석하지 않는다. 특히 low_n 이 0 이면
under 는 언제나 0 이므로 "미탐 없음"이 아니라 "측정 불가"다 — 코퍼스에 저위험으로
떨어지는 이미지가 섞이지 않으면 이 열은 영원히 0 이다.
사용법:
python scripts/sweep_thresholds.py data/corpus.sqlite3
"""
from __future__ import annotations
import argparse
import json
import sqlite3
import sys
from collections import Counter
HIGH_CANDIDATES = (50, 60, 70, 80)
MEDIUM_CANDIDATES = (20, 30, 40)
MIN_DENOMINATOR = 5
def collect(db_path: str):
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
pairs = []
skipped = Counter()
try:
for row in conn.execute("select payload from submissions"):
submission = json.loads(row["payload"])
decision = submission.get("decisionStatus", "unreviewed")
if decision == "unreviewed":
skipped["unreviewed"] += 1
continue
snapshot = submission.get("decisionSnapshot")
if not snapshot:
skipped["no_snapshot"] += 1
continue
if snapshot.get("scorerVersion") == "legacy":
skipped["legacy_pre_stamp"] += 1
continue
score = snapshot.get("riskScore")
if score is None:
skipped["no_score_in_snapshot"] += 1
continue
pairs.append(
{
"id": str(submission.get("id", "")),
"score": int(score),
"band": snapshot.get("riskBand"),
"decision": decision,
"scorerVersion": snapshot.get("scorerVersion"),
}
)
finally:
conn.close()
return pairs, skipped
def sweep(pairs):
results = []
for high in HIGH_CANDIDATES:
for medium in MEDIUM_CANDIDATES:
if medium >= high:
continue
high_rows = [p for p in pairs if p["score"] >= high]
low_rows = [p for p in pairs if p["score"] < medium]
results.append(
{
"high": high,
"medium": medium,
"highN": len(high_rows),
"overDetection": sum(1 for p in high_rows if p["decision"] == "approved"),
"lowN": len(low_rows),
"underDetection": sum(1 for p in low_rows if p["decision"] == "rejected"),
}
)
return results
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("db", help="판정이 쌓인 SQLite 경로")
parser.add_argument("--json", action="store_true")
args = parser.parse_args()
pairs, skipped = collect(args.db)
results = sweep(pairs)
if args.json:
print(json.dumps({"pairs": pairs, "skipped": dict(skipped), "sweep": results}, ensure_ascii=False))
return 0
# 비ASCII 는 stdout 에 넣지 않는다 (콘솔이 cp949 라 죽은 이력).
print("usable pairs: %d skipped: %s" % (len(pairs), dict(skipped)))
if not pairs:
print("")
print("no decisions to sweep yet - see docs/operations/calibration-corpus.md")
return 0
versions = Counter(p["scorerVersion"] for p in pairs)
print("scorer versions in sample: %s" % dict(versions))
if len(versions) > 1:
print("WARNING: mixed scorer versions - scores are not comparable across them")
print("")
print("%-18s %6s %6s %6s %6s" % ("thresholds", "highN", "over", "lowN", "under"))
for item in results:
flag = "" if item["highN"] >= MIN_DENOMINATOR and item["lowN"] >= MIN_DENOMINATOR else " (n<%d)" % MIN_DENOMINATOR
print(
"high>=%-3d med>=%-3d %6d %6d %6d %6d%s"
% (
item["high"],
item["medium"],
item["highN"],
item["overDetection"],
item["lowN"],
item["underDetection"],
flag,
)
)
return 0
if __name__ == "__main__":
sys.exit(main())