AI 의심도 백분위 캘리브레이션 (학습·지표 없이 운영)
AI 생성 표본이 없어 정확도를 측정할 수 없는 상태에서, 규칙 기반 휴리스틱을 실제로 쓸 수 있게 만든다. 점수의 의미를 "AI일 확률"에서 "등록 코퍼스의 인간 저작물 대비 문체 이례도"로 재정의해, 라벨 없이도 참인 진술이 되도록 했다. 덤으로 high 배지 비율이 정의상 고정되어 검토 부하가 예측 가능해진다. - ai_detector: low_cut/high_cut 주입 지원. 둘 다 주어질 때만 적용하고, 적용되면 model_version 에 +corpus-percentile 을 붙여 컷 출처를 드러낸다. is_stub 은 여전히 true — 컷을 맞췄을 뿐 학습된 모델이 아니다. - calibrate_cuts/percentile/score_text_heuristic 순수 함수 추가. - scripts/calibrate_ai_detector_cuts.py: 코퍼스 표본의 점수 분포에서 백분위 컷을 산출하고 .env 두 줄을 출력한다. - 규칙 점수가 상단에서 clip 되어 p90=p98 이 되면 그 컷은 high 배지를 영원히 0건으로 만든다. 이 경우 .env 를 출력하지 않고 exit 3 으로 중단하며 saturated_share/distinct_scores 진단을 남긴다. 유효 표본 100건 미만은 exit 2. - kiwipiepy 유무가 점수를 바꾸므로 실제 사용 여부를 리포트에 기록하고 경고한다. 기본값은 그대로 비활성(AI_DETECTOR_ALLOW_HEURISTIC=false)이라 켜지 않으면 동작이 바뀌지 않는다. 컷 미설정 시에는 자리표시자임을 note 로 경고한다. 테스트 180건 통과 (신규 13건). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
f4461f39c7
commit
a530d2139f
7 files changed
+517
-7
No files matched your search
@@ -511,3 +511,147 @@ def test_valid_artifact_roundtrip(tmp_path):
|
||||
det = AiGenerationDetector(model_path=path, allow_heuristic=False)
|
||||
assert det.mode == "trained"
|
||||
assert det.detect(UNIFORM_TEXT, with_segments=False).score == pytest.approx(0.66)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 백분위 컷 캘리브레이션 (라벨 없이 인간 코퍼스만으로)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_percentile_matches_known_values():
|
||||
values = [0.0, 0.25, 0.5, 0.75, 1.0]
|
||||
assert ad.percentile(values, 0) == pytest.approx(0.0)
|
||||
assert ad.percentile(values, 50) == pytest.approx(0.5)
|
||||
assert ad.percentile(values, 100) == pytest.approx(1.0)
|
||||
assert ad.percentile([], 50) == 0.0
|
||||
assert ad.percentile([0.3], 90) == pytest.approx(0.3)
|
||||
|
||||
|
||||
def test_calibrate_cuts_from_human_scores():
|
||||
scores = [i / 1000 for i in range(1000)] # 0.000 ~ 0.999 균등
|
||||
low, high = ad.calibrate_cuts(scores, 90, 98)
|
||||
assert low == pytest.approx(0.899, abs=0.01)
|
||||
assert high == pytest.approx(0.979, abs=0.01)
|
||||
assert low < high
|
||||
|
||||
|
||||
def test_calibrate_cuts_keeps_medium_band_when_distribution_is_flat():
|
||||
low, high = ad.calibrate_cuts([0.5] * 200, 90, 98)
|
||||
assert high > low, "분포가 평평해도 medium 구간이 사라지면 안 된다"
|
||||
|
||||
|
||||
def test_calibrate_cuts_rejects_bad_input():
|
||||
with pytest.raises(ValueError):
|
||||
ad.calibrate_cuts([])
|
||||
with pytest.raises(ValueError):
|
||||
ad.calibrate_cuts([0.5], 98, 90) # low >= high
|
||||
with pytest.raises(ValueError):
|
||||
ad.calibrate_cuts([0.5], -1, 50)
|
||||
|
||||
|
||||
def test_calibrated_cuts_produce_expected_badge_rate():
|
||||
"""컷의 존재 이유 — 인간 코퍼스에서 high 비율이 설계값으로 고정된다."""
|
||||
scores = [i / 1000 for i in range(1000)]
|
||||
low, high = ad.calibrate_cuts(scores, 90, 98)
|
||||
high_rate = sum(1 for s in scores if s >= high) / len(scores)
|
||||
assert high_rate == pytest.approx(0.02, abs=0.005)
|
||||
|
||||
|
||||
def test_score_text_heuristic_skips_short_text():
|
||||
assert ad.score_text_heuristic("너무 짧다.") is None
|
||||
value = ad.score_text_heuristic(UNIFORM_TEXT)
|
||||
assert value is not None and 0.0 <= value <= 1.0
|
||||
|
||||
|
||||
def test_detector_uses_injected_cuts(tmp_path):
|
||||
det = AiGenerationDetector(
|
||||
model_path=tmp_path / "none.joblib", allow_heuristic=True,
|
||||
low_cut=0.10, high_cut=0.20,
|
||||
)
|
||||
assert det.cuts_calibrated is True
|
||||
assert det._cuts() == (0.10, 0.20)
|
||||
assert det.model_version == "heuristic-baseline-v1+corpus-percentile"
|
||||
assert det._level(0.05) == "low"
|
||||
assert det._level(0.15) == "medium"
|
||||
assert det._level(0.50) == "high"
|
||||
|
||||
|
||||
def test_partial_cuts_are_ignored(tmp_path):
|
||||
"""한쪽만 주면 자리표시자로 되돌아가야 한다 (반쪽 설정 방지)."""
|
||||
det = AiGenerationDetector(
|
||||
model_path=tmp_path / "none.joblib", allow_heuristic=True, low_cut=0.1,
|
||||
)
|
||||
assert det.cuts_calibrated is False
|
||||
assert det._cuts() == (ad.DEFAULT_LOW_CUT, ad.DEFAULT_HIGH_CUT)
|
||||
assert det.model_version == "heuristic-baseline-v1"
|
||||
|
||||
|
||||
def test_uncalibrated_heuristic_note_warns(tmp_path):
|
||||
det = AiGenerationDetector(model_path=tmp_path / "none.joblib", allow_heuristic=True)
|
||||
res = det.detect(UNIFORM_TEXT, with_segments=False)
|
||||
assert res.is_stub is True
|
||||
assert "캘리브레이션되지 않았습니다" in res.note
|
||||
|
||||
|
||||
def test_calibrated_heuristic_note_states_relative_meaning(tmp_path):
|
||||
det = AiGenerationDetector(
|
||||
model_path=tmp_path / "none.joblib", allow_heuristic=True,
|
||||
low_cut=0.3, high_cut=0.6,
|
||||
)
|
||||
res = det.detect(UNIFORM_TEXT, with_segments=False)
|
||||
assert res.is_stub is True, "캘리브레이션해도 학습 모델은 아니다"
|
||||
assert "문체 이례도" in res.note
|
||||
assert "확률" in res.note
|
||||
|
||||
|
||||
def test_artifact_cuts_win_over_injected_cuts():
|
||||
det = _stub_detector(0.5)
|
||||
det.low_cut, det.high_cut = 0.01, 0.02
|
||||
assert det._cuts() == (0.40, 0.70), "학습 아티팩트가 있으면 그쪽이 우선"
|
||||
|
||||
|
||||
def test_calibration_script_refuses_degenerate_corpus(tmp_path):
|
||||
"""포화된 코퍼스에서 'high 배지 0건' 설정을 출력하면 안 된다."""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ref = tmp_path / "ref"
|
||||
ref.mkdir()
|
||||
# 완전히 동일한 텍스트 200건 → 점수 전부 동률 = 포화
|
||||
for i in range(200):
|
||||
(ref / f"ref-{i:04d}__같은책.txt").write_text(UNIFORM_TEXT, encoding="utf-8")
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "scripts/calibrate_ai_detector_cuts.py",
|
||||
"--database", str(tmp_path / "absent.sqlite3"),
|
||||
"--reference-dir", str(ref), "--sample", "0",
|
||||
"--out", str(tmp_path / "cuts.json")],
|
||||
cwd=root, capture_output=True, text=True,
|
||||
)
|
||||
assert proc.returncode == 3, proc.stderr[-1500:]
|
||||
assert "AI_DETECTOR_LOW_CUT" not in proc.stdout, "죽은 설정을 출력하면 안 된다"
|
||||
assert "영원히 0건" in proc.stderr
|
||||
# 진단 리포트는 남아야 한다
|
||||
assert (tmp_path / "cuts.json").exists()
|
||||
|
||||
|
||||
def test_calibration_script_fails_on_tiny_sample(tmp_path):
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ref = tmp_path / "ref"
|
||||
ref.mkdir()
|
||||
for i in range(5):
|
||||
(ref / f"ref-{i}__책.txt").write_text(UNIFORM_TEXT, encoding="utf-8")
|
||||
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "scripts/calibrate_ai_detector_cuts.py",
|
||||
"--database", str(tmp_path / "absent.sqlite3"),
|
||||
"--reference-dir", str(ref), "--sample", "0",
|
||||
"--out", str(tmp_path / "cuts.json")],
|
||||
cwd=Path(__file__).resolve().parents[1], capture_output=True, text=True,
|
||||
)
|
||||
assert proc.returncode == 2
|
||||
assert "불안정" in proc.stderr
|
||||
Reference in new issue
Block a user