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
@@ -59,10 +59,17 @@ ENV_MODEL_PATH = "AI_DETECTOR_MODEL_PATH"
|
||||
DEFAULT_MODEL_PATH = "./data/models/ai_detector.joblib"
|
||||
|
||||
#: 잠정 의심도 구간. 학습 시 target FPR 기준으로 재산출되어 아티팩트에 저장되며,
|
||||
#: 아티팩트 값이 있으면 그쪽이 우선한다. 아래는 모델이 없을 때의 자리표시자다.
|
||||
#: 아티팩트 값이 있으면 그쪽이 우선한다. 아래는 아무 근거 없는 자리표시자이므로,
|
||||
#: 휴리스틱 모드로 운영할 때는 scripts/calibrate_ai_detector_cuts.py 로 산출한
|
||||
#: 백분위 컷을 설정으로 주입할 것.
|
||||
DEFAULT_LOW_CUT = 0.40
|
||||
DEFAULT_HIGH_CUT = 0.70
|
||||
|
||||
#: 백분위 캘리브레이션 기본값. 등록 코퍼스(전부 인간 저작) 대비 상위 10%를
|
||||
#: medium, 상위 2%를 high 로 본다. "AI 확률"이 아니라 "인간 저작 대비 이례도"다.
|
||||
DEFAULT_LOW_PERCENTILE = 90.0
|
||||
DEFAULT_HIGH_PERCENTILE = 98.0
|
||||
|
||||
Provenance = Literal["human", "ai", "mixed", "edited", "unknown"]
|
||||
SuspicionLevel = Literal["low", "medium", "high"]
|
||||
|
||||
@@ -592,6 +599,57 @@ def _heuristic_score(feats: dict[str, float]) -> float:
|
||||
return max(0.0, min(1.0, sum(positions) / len(positions)))
|
||||
|
||||
|
||||
def percentile(values: Sequence[float], pct: float) -> float:
|
||||
"""선형 보간 백분위. numpy 없이도 동작하도록 직접 구현한다."""
|
||||
if not values:
|
||||
return 0.0
|
||||
ordered = sorted(values)
|
||||
if len(ordered) == 1:
|
||||
return float(ordered[0])
|
||||
pos = (len(ordered) - 1) * max(0.0, min(100.0, pct)) / 100.0
|
||||
low = int(math.floor(pos))
|
||||
high = int(math.ceil(pos))
|
||||
if low == high:
|
||||
return float(ordered[low])
|
||||
return float(ordered[low] + (ordered[high] - ordered[low]) * (pos - low))
|
||||
|
||||
|
||||
def calibrate_cuts(
|
||||
human_scores: Sequence[float],
|
||||
low_percentile: float = DEFAULT_LOW_PERCENTILE,
|
||||
high_percentile: float = DEFAULT_HIGH_PERCENTILE,
|
||||
) -> tuple[float, float]:
|
||||
"""인간 저작 코퍼스 점수 분포 → (low_cut, high_cut).
|
||||
|
||||
라벨이 전혀 필요 없다. "AI가 쓴 글의 점수는 얼마인가"가 아니라 "우리 코퍼스의
|
||||
인간 저작물 중 상위 몇 %인가"로 컷을 정의하기 때문이다. 그래서 정확도를
|
||||
측정하지 않고도 참인 진술("등록 자서전 대비 상위 2% 이례적 문체")이 되고,
|
||||
'high' 배지 비율이 정의상 고정되어 검토 부하도 예측 가능해진다.
|
||||
|
||||
두 백분위가 같은 값으로 뭉개지면(분포가 평평한 경우) high 를 살짝 올려
|
||||
medium 구간이 사라지지 않게 한다.
|
||||
"""
|
||||
if not human_scores:
|
||||
raise ValueError("점수 표본이 비어 있어 컷을 산출할 수 없습니다.")
|
||||
if not 0.0 <= low_percentile < high_percentile <= 100.0:
|
||||
raise ValueError(
|
||||
f"백분위는 0 <= low < high <= 100 이어야 합니다: {low_percentile}, {high_percentile}"
|
||||
)
|
||||
low = percentile(human_scores, low_percentile)
|
||||
high = percentile(human_scores, high_percentile)
|
||||
if high <= low:
|
||||
high = min(1.0, low + 0.01)
|
||||
return round(low, 4), round(high, 4)
|
||||
|
||||
|
||||
def score_text_heuristic(text: str, use_pos: bool = True) -> float | None:
|
||||
"""캘리브레이션용 단일 텍스트 점수. 너무 짧으면 None(표본에서 제외)."""
|
||||
norm = normalize_text(text)
|
||||
if len(norm) < HARD_MIN_CHARS:
|
||||
return None
|
||||
return _heuristic_score(extract_features(norm, use_pos=use_pos))
|
||||
|
||||
|
||||
def _heuristic_contributions(feats: dict[str, float]) -> list[tuple[str, float]]:
|
||||
"""휴리스틱에서 어느 특징이 점수를 끌어올렸는지."""
|
||||
out: list[tuple[str, float]] = []
|
||||
@@ -700,12 +758,17 @@ class AiGenerationDetector:
|
||||
model_path: str | Path | None = None,
|
||||
allow_heuristic: bool = False,
|
||||
use_pos: bool = True,
|
||||
low_cut: float | None = None,
|
||||
high_cut: float | None = None,
|
||||
):
|
||||
self.model_path = str(
|
||||
model_path or os.environ.get(ENV_MODEL_PATH) or DEFAULT_MODEL_PATH
|
||||
)
|
||||
self.allow_heuristic = allow_heuristic
|
||||
self.use_pos = use_pos
|
||||
# 휴리스틱 모드에서 쓸 백분위 컷. 둘 다 주어졌을 때만 적용한다.
|
||||
self.low_cut = low_cut
|
||||
self.high_cut = high_cut
|
||||
self.artifact = load_artifact(self.model_path)
|
||||
|
||||
# -- 모드 --------------------------------------------------------------
|
||||
@@ -720,11 +783,26 @@ class AiGenerationDetector:
|
||||
def model_version(self) -> str:
|
||||
if self.artifact is not None:
|
||||
return self.artifact.model_version
|
||||
return self.HEURISTIC_VERSION if self.allow_heuristic else "unavailable"
|
||||
if not self.allow_heuristic:
|
||||
return "unavailable"
|
||||
# 컷이 코퍼스로 캘리브레이션되었는지를 버전 문자열에 드러낸다.
|
||||
return (
|
||||
f"{self.HEURISTIC_VERSION}+corpus-percentile"
|
||||
if self.cuts_calibrated else self.HEURISTIC_VERSION
|
||||
)
|
||||
|
||||
@property
|
||||
def cuts_calibrated(self) -> bool:
|
||||
"""컷이 자리표시자가 아니라 실제 코퍼스 분포에서 나왔는지."""
|
||||
if self.artifact is not None:
|
||||
return True
|
||||
return self.low_cut is not None and self.high_cut is not None
|
||||
|
||||
def _cuts(self) -> tuple[float, float]:
|
||||
if self.artifact is not None:
|
||||
return self.artifact.low_cut, self.artifact.high_cut
|
||||
if self.low_cut is not None and self.high_cut is not None:
|
||||
return self.low_cut, self.high_cut
|
||||
return DEFAULT_LOW_CUT, DEFAULT_HIGH_CUT
|
||||
|
||||
def _level(self, score: float) -> SuspicionLevel:
|
||||
@@ -862,10 +940,17 @@ class AiGenerationDetector:
|
||||
segments = self._score_segments(norm) if with_segments else []
|
||||
provenance = self._infer_provenance(score, segments)
|
||||
|
||||
if self.artifact is None:
|
||||
if self.artifact is None and self.cuts_calibrated:
|
||||
note = (
|
||||
"⚠️ 미검증 휴리스틱 baseline 입니다. 학습된 모델이 아니며 "
|
||||
"판정 근거로 사용할 수 없습니다. 검토 우선순위 참고용."
|
||||
"학습 모델이 아니라 언어특징 규칙 점수입니다. 'AI일 확률'이 아니라 "
|
||||
"등록 코퍼스의 인간 저작물 대비 문체 이례도이며, 검토 우선순위 "
|
||||
"정렬용입니다. 판정 근거로 사용할 수 없습니다."
|
||||
)
|
||||
elif self.artifact is None:
|
||||
note = (
|
||||
"⚠️ 미검증 휴리스틱 baseline 입니다. 학습된 모델도 아니고 컷도 "
|
||||
"캘리브레이션되지 않았습니다(자리표시자). 판정 근거로 사용할 수 "
|
||||
"없습니다. scripts/calibrate_ai_detector_cuts.py 로 컷을 산출하세요."
|
||||
)
|
||||
else:
|
||||
note = (
|
||||
@@ -1008,21 +1093,26 @@ def get_ai_detector(
|
||||
model_path: str | Path | None = None,
|
||||
allow_heuristic: bool | None = None,
|
||||
use_pos: bool = True,
|
||||
low_cut: float | None = None,
|
||||
high_cut: float | None = None,
|
||||
) -> AiGenerationDetector:
|
||||
"""탐지기 인스턴스(프로세스 캐시).
|
||||
|
||||
allow_heuristic 을 생략하면 환경변수 AI_DETECTOR_ALLOW_HEURISTIC 을 따르고,
|
||||
그것도 없으면 False(= 모델 없으면 unavailable) 다. 기본값을 False 로 두는
|
||||
이유는, 미검증 점수가 조용히 운영에 노출되는 상황을 막기 위해서다.
|
||||
|
||||
low_cut/high_cut 은 휴리스틱 모드에서만 쓰이며, 둘 다 주어져야 적용된다.
|
||||
"""
|
||||
if allow_heuristic is None:
|
||||
allow_heuristic = os.environ.get(
|
||||
"AI_DETECTOR_ALLOW_HEURISTIC", ""
|
||||
).strip().lower() in {"1", "true", "yes"}
|
||||
key = (str(model_path or ""), bool(allow_heuristic), bool(use_pos))
|
||||
key = (str(model_path or ""), bool(allow_heuristic), bool(use_pos), low_cut, high_cut)
|
||||
if key not in _detector_cache:
|
||||
_detector_cache[key] = AiGenerationDetector(
|
||||
model_path=model_path, allow_heuristic=allow_heuristic, use_pos=use_pos
|
||||
model_path=model_path, allow_heuristic=allow_heuristic, use_pos=use_pos,
|
||||
low_cut=low_cut, high_cut=high_cut,
|
||||
)
|
||||
return _detector_cache[key]
|
||||
|
||||
|
||||
Reference in new issue
Block a user