feat: OCR·조판 아티팩트 정규화와 백분위 컷 캘리브레이션
학습·캘리브레이션에 쓰는 79권 코퍼스는 OCR 후처리본이라 저자 문체가 아닌 스캔·조판 흔적이 남아 있다. AI 생성 표본에는 그 흔적이 없으므로, 그대로 두면 분류기가 문체가 아니라 "OCR 흔적이 있으면 human"을 배운다. 그러면 운영에서 들어오는 깨끗한 인간 원고가 AI로 오판된다. 규칙은 추측이 아니라 코퍼스 34,105건 실측에서 뽑았다. 표본 3,000건 기준 숫자+공백+단위 94.8%, 한자 병기 99.4%, 낫표 100% 제거. 정상 한국어인 `America라는`·`3년` 형태는 건드리지 않는다. 숫자-단위 규칙은 정규식으로 밀어넣으면 `3 번지`를 `3번지`로 잘못 붙이므로 단위·접미사 화이트리스트로 판정한다. 멱등성과 "깨끗한 입력에 무해" 두 불변식을 테스트로 고정했다. 후자가 깨지면 운영 원고가 학습 코퍼스와 다르게 처리되어 정규화 자체가 새 편향이 된다. calibrate_ai_detector_cuts.py 에 xlsx 입력과 OCR 정규화(기본 켜짐)를 추가했다. 79권 3,000건 실측 결과 low_cut 0.4286 / high_cut 0.5298, 인간 원고 기준 예상 high 비율 2.03%(설계 목표 2%)로 포화 없이 잡혔다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7f18206f36
commit
45355910fa
3 files changed
+369
-5
No files matched your search
@@ -11,7 +11,11 @@
|
||||
|
||||
이 값은 여전히 **AI 작성 판정이 아니다.** 검토 우선순위 정렬용이다.
|
||||
|
||||
입력: 영속 코퍼스 SQLite (기본) 또는 data/reference/*.txt
|
||||
입력: 영속 코퍼스 SQLite (기본) / data/reference/*.txt / 에피소드 xlsx
|
||||
|
||||
OCR 후처리 코퍼스가 입력이면 --ocr-normalize (기본 켜짐) 로 조판·스캔 흔적을
|
||||
먼저 지운다. 그러지 않으면 컷이 저자 문체가 아니라 그 책의 조판 관습 위에서
|
||||
잡히고, 다른 조판의 원고에는 맞지 않는다.
|
||||
출력: JSON 리포트 + 그대로 붙여넣을 .env 두 줄
|
||||
|
||||
사용:
|
||||
@@ -34,6 +38,10 @@ sys.path.insert(0, str(ROOT))
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
|
||||
logger = logging.getLogger("calibrate-cuts")
|
||||
|
||||
from app.engine.ocr_normalize import ( # noqa: E402
|
||||
normalize_ocr,
|
||||
ocr_artifact_stats,
|
||||
)
|
||||
from app.engine.ai_detector import ( # noqa: E402
|
||||
DEFAULT_HIGH_PERCENTILE,
|
||||
DEFAULT_LOW_PERCENTILE,
|
||||
@@ -49,11 +57,42 @@ def _stable_pick(key: str) -> int:
|
||||
return int(hashlib.sha1(key.encode("utf-8")).hexdigest()[:8], 16)
|
||||
|
||||
|
||||
def load_texts(database: Path | None, reference_dir: Path | None, sample: int) -> list[str]:
|
||||
def load_texts(
|
||||
database: Path | None,
|
||||
reference_dir: Path | None,
|
||||
sample: int,
|
||||
xlsx: Path | None = None,
|
||||
text_column: str = "에피소드",
|
||||
book_column: str = "book_name",
|
||||
) -> list[str]:
|
||||
"""코퍼스에서 텍스트를 표본 추출. 전량 처리는 느리므로 기본은 표본이다."""
|
||||
items: list[tuple[int, str]] = []
|
||||
|
||||
if database and database.exists():
|
||||
if xlsx and xlsx.exists():
|
||||
import pandas as pd
|
||||
|
||||
frame = pd.read_excel(xlsx, sheet_name=0)
|
||||
if text_column not in frame.columns:
|
||||
raise SystemExit(
|
||||
f"'{text_column}' 컬럼이 없습니다. 있는 컬럼: {list(frame.columns)}"
|
||||
)
|
||||
# 표본 키에 도서명을 섞어야 한 책이 표본을 독점하지 않는다.
|
||||
has_book = book_column in frame.columns
|
||||
seen: set[str] = set()
|
||||
for idx in range(len(frame)):
|
||||
text = frame[text_column].iloc[idx]
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
continue
|
||||
norm_key = " ".join(text.split())
|
||||
if norm_key in seen: # 완전 중복 에피소드 제거 (34,105 → 31,560)
|
||||
continue
|
||||
seen.add(norm_key)
|
||||
book = str(frame[book_column].iloc[idx]) if has_book else ""
|
||||
items.append((_stable_pick(f"{book}:{idx}"), text))
|
||||
logger.info(
|
||||
"xlsx 에피소드 %d건 로드(중복 제거 후): %s", len(items), xlsx.name
|
||||
)
|
||||
elif database and database.exists():
|
||||
from app.engine.provenance import CorpusStore
|
||||
|
||||
for seg in CorpusStore(database).iter_segments():
|
||||
@@ -79,6 +118,13 @@ def main() -> int:
|
||||
ap = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
ap.add_argument("--xlsx", type=Path, default=None,
|
||||
help="에피소드 xlsx (지정 시 최우선 입력)")
|
||||
ap.add_argument("--text-column", default="에피소드")
|
||||
ap.add_argument("--book-column", default="book_name",
|
||||
help="표본을 도서에 고르게 퍼뜨리는 데 쓰는 그룹 컬럼")
|
||||
ap.add_argument("--no-ocr-normalize", action="store_true",
|
||||
help="OCR·조판 아티팩트 정규화를 끈다(기본은 켜짐)")
|
||||
ap.add_argument("--database", type=Path, default=Path("data/runtime/corpus.sqlite3"))
|
||||
ap.add_argument("--reference-dir", type=Path, default=Path("data/reference"),
|
||||
help="SQLite 가 없을 때 쓰는 폴백")
|
||||
@@ -90,11 +136,32 @@ def main() -> int:
|
||||
ap.add_argument("--out", type=Path, default=Path("data/models/ai_cuts.json"))
|
||||
args = ap.parse_args()
|
||||
|
||||
texts = load_texts(args.database, args.reference_dir, args.sample)
|
||||
texts = load_texts(
|
||||
args.database, args.reference_dir, args.sample,
|
||||
xlsx=args.xlsx, text_column=args.text_column, book_column=args.book_column,
|
||||
)
|
||||
if not texts:
|
||||
logger.error("표본이 0건입니다.")
|
||||
return 2
|
||||
|
||||
# OCR·조판 흔적을 먼저 지운다. 이걸 건너뛰면 컷이 저자 문체가 아니라
|
||||
# 그 책의 조판 관습 위에서 잡힌다.
|
||||
ocr_before: dict[str, int] = {}
|
||||
ocr_after: dict[str, int] = {}
|
||||
if not args.no_ocr_normalize:
|
||||
for text in texts:
|
||||
for key, value in ocr_artifact_stats(text).items():
|
||||
ocr_before[key] = ocr_before.get(key, 0) + value
|
||||
texts = [normalize_ocr(text) for text in texts]
|
||||
for text in texts:
|
||||
for key, value in ocr_artifact_stats(text).items():
|
||||
ocr_after[key] = ocr_after.get(key, 0) + value
|
||||
removed = sum(ocr_before.values()) - sum(ocr_after.values())
|
||||
logger.info(
|
||||
"OCR 정규화: 아티팩트 %d건 → %d건 (%d건 제거)",
|
||||
sum(ocr_before.values()), sum(ocr_after.values()), removed,
|
||||
)
|
||||
|
||||
# 실제로 품사 특징이 쓰였는지 확인 (kiwipiepy 없으면 자동 폴백된다)
|
||||
from app.engine.ai_detector import extract_features
|
||||
|
||||
@@ -143,9 +210,16 @@ def main() -> int:
|
||||
target_high = (100.0 - args.high_percentile) / 100.0
|
||||
|
||||
report = {
|
||||
"source": str(args.database if args.database.exists() else args.reference_dir),
|
||||
"source": str(
|
||||
args.xlsx if args.xlsx and args.xlsx.exists()
|
||||
else args.database if args.database.exists()
|
||||
else args.reference_dir
|
||||
),
|
||||
"n_scored": len(scores),
|
||||
"n_skipped_short": skipped,
|
||||
"ocr_normalized": not args.no_ocr_normalize,
|
||||
"ocr_artifacts_before": ocr_before,
|
||||
"ocr_artifacts_after": ocr_after,
|
||||
"use_pos_requested": not args.no_pos,
|
||||
"pos_actually_used": pos_used,
|
||||
"low_percentile": args.low_percentile,
|
||||
|
||||
Reference in new issue
Block a user