Merge pull request #1 from o2ogit/exception_code

feat: return exception code F1 for unclassified matches
This commit is contained in:
jaehwang authored and GitHub committed 2026-10-30 08:54:01 +09:00
commit aaf88d0c1d
3 files changed
+108 -8

No files matched your search

+51 -6
View File
@@ -57,6 +57,11 @@ from app.engine.taxonomy import CaseDef, Taxonomy, load_taxonomy
logger = logging.getLogger(__name__)
#: 원고 점검 항목을 정하지 못한 매칭에 붙이는 예외 코드. 분류 체계의 항목이
#: 아니므로 /v1/taxonomy 에는 없고, 정하지 못한 이유는 후보의 reason 에 남긴다.
UNCLASSIFIED_CASE_ID = "F1"
UNCLASSIFIED_CASE_TITLE = "미분류"
class PlagiarismDetector:
#: 참조 특징 프로세스 캐시 상한. 초과하면 통째로 비운다(단순 LRU 대용).
@@ -629,14 +634,16 @@ class PlagiarismDetector:
)
for c in cases
]
if not candidates:
candidates = [self._unclassified_candidate(self.taxonomy, primary_tags, hit)]
return MatchResult(
source_doc=hit.doc_id,
source_title=hit.title,
similarity=round(hit.score, 4),
tags=tags,
case_id=cases[0].case_id if cases else None,
case_title=cases[0].title if cases else None,
case_id=candidates[0].case_id,
case_title=candidates[0].title,
case_candidates=candidates,
publication_verdict_status=("review_required" if any(
c.publication_verdict is not None for c in candidates
@@ -658,11 +665,8 @@ class PlagiarismDetector:
tie: tuple[CaseDef, ...]) -> str:
"""관리자 콘솔에 표시할 분류 사유. 엔진 신호 → 겹친 태그 → 항목 판단 기준 순."""
matched = "·".join(TAG_LABEL_KO[t] for t in primary_tags if t in case.primary_tags)
signal = (f"text={hit.text_sim:.2f} / lemma={hit.lemma_sim:.2f} / "
f"char={hit.element_sim.get('characters', 0.0):.2f} / "
f"motif={hit.element_sim.get('motifs', 0.0):.2f}")
reason = (f"엔진 주 태그 {matched}이(가) {case.case_id}({case.title})의 태그와 "
f"일치합니다 [{signal}].")
f"일치합니다 [{_score_signal(hit)}].")
if len(tie) > 1:
ids = ", ".join(c.case_id for c in tie)
reason += (f" 텍스트만으로는 {ids} 중 하나로 좁혀지지 않으므로 작성자 관계"
@@ -673,6 +677,37 @@ class PlagiarismDetector:
reason += " (이 항목의 태그 매핑은 추정치로, 컴북스 확인 전입니다.)"
return reason
@staticmethod
def _unclassified_candidate(taxonomy: Taxonomy | None, primary_tags: list[str],
hit: SimilarityHit) -> CaseCandidate:
"""항목을 정하지 못한 매칭의 F1 후보. 사유는 정하지 못한 지점마다 다르다.
- 분류 체계 미로드 → 설정 확인 필요
- 주 태그 없음(_assign_tags 의 마지막 분기) → 사람이 항목 지정
- 주 태그는 있으나 판별 대상 항목과 겹치지 않음 → 사람이 항목 지정
"""
signal = _score_signal(hit)
if taxonomy is None:
reason = (f"분류 체계를 불러오지 못해 원고 점검 항목을 매기지 못했습니다 "
f"[{signal}]. 서버의 TAXONOMY_DIR 설정을 확인해야 합니다.")
elif not primary_tags:
reason = (f"엔진이 주 태그를 내지 못해 원고 점검 항목 중 대응되는 항목이 "
f"없습니다 [{signal}]. 일치 구간과 원본 종류를 확인해 항목을 "
"사람이 지정해야 합니다.")
else:
matched = "·".join(TAG_LABEL_KO[t] for t in primary_tags)
targets = "·".join(c.case_id for c in taxonomy.cases if c.detectable_internal)
reason = (f"엔진 주 태그 {matched}이(가) 엔진 판별 대상 항목({targets})과 "
f"충분히 겹치지 않습니다 [{signal}]. 일치 구간과 원본 종류를 확인해 "
"항목을 사람이 지정해야 합니다.")
return CaseCandidate(
case_id=UNCLASSIFIED_CASE_ID,
title=UNCLASSIFIED_CASE_TITLE,
handling="terms_or_report",
precedent_note="분류 미확정이라 대표판례를 지정하지 않습니다.",
reason=reason,
)
def _assign_tags(self, hit: SimilarityHit, legacy: InfringementType,
exact_span: bool = False) -> list[InfringementTag]:
"""삼중 유사도 분포 → 10종 법령 태그(주/보조) 매핑.
@@ -768,6 +803,9 @@ class PlagiarismDetector:
ids = ", ".join(c.case_id for c in top.case_candidates)
case_part = (f" 추정 분류 후보 {ids} — 태그만으로는 구별되지 않으므로 "
f"작성자 관계와 원본 종류를 확인해 확정해야 합니다.")
elif top.case_id == UNCLASSIFIED_CASE_ID:
case_part = (f" 분류 미확정({UNCLASSIFIED_CASE_ID}) — 원본 종류와 일치 구간을 "
"확인해 항목을 지정해야 합니다.")
elif top.case_id:
case_part = f" 추정 분류 {top.case_id} ({top.case_title})."
else:
@@ -796,6 +834,13 @@ def _calibrate_similarity(raw: float, threshold: float) -> int:
return max(0, min(100, round(disp)))
def _score_signal(hit: SimilarityHit) -> str:
"""분류 사유에 붙이는 유사도 성분 요약."""
return (f"text={hit.text_sim:.2f} / lemma={hit.lemma_sim:.2f} / "
f"char={hit.element_sim.get('characters', 0.0):.2f} / "
f"motif={hit.element_sim.get('motifs', 0.0):.2f}")
def _classify_legacy(hit: SimilarityHit) -> InfringementType:
"""후방 호환 - 단일 enum 분류 (UI/기존 통합 코드용)."""
elem = hit.element_sim
+17 -2
View File
@@ -210,8 +210,8 @@ curl -X POST https://plagiarism.o2o.kr/v1/plagiarism/detect \
| `ai_generation` | object | AI 생성 의심도 상세. 현재 학습 모델 사용 시 `available=true`, `is_stub=false` |
| `matches[]` | array | 매칭된 원본별 상세 (표절 시). 태그·분류·근거 구간 포함 |
| `matches[].tags[]` | array | 법령 태그. `role`: `primary`(주)/`secondary`(보조), `label_ko` 한글 표기 |
| `matches[].case_id` | string\|null | 원고 점검 18항목 분류 코드(예: `M1`). `case_candidates[0]` 과 같다. 분류되지 않으면 null (§8) |
| `matches[].case_title` | string\|null | 분류명 (예: `남의 글을 옮겨 실었다`) |
| `matches[].case_id` | string | 원고 점검 18항목 분류 코드(예: `M1`). `case_candidates[0]` 과 같다. 항목을 정하지 못하면 예외 코드 `F1` (§8-4) |
| `matches[].case_title` | string | 분류명 (예: `남의 글을 옮겨 실었다`). `F1`이면 `미분류` |
| `matches[].case_candidates[]` | array | 태그 동점 분류 **전부**. 2개 이상이면 텍스트만으로 하나로 좁혀지지 않으므로 "이 중 하나"로 표시하고 사람이 확정한다 |
| `matches[].case_candidates[].handling` | string | `technical_detection`(엔진 판별 대상) / `terms_or_report`(사람 확인 대상) |
| `matches[].case_candidates[].publication_verdict` | string | 항목의 기본 출간 판정 (예: `조건부`). 이 원고의 최종 판정이 아니다 (§7-2) |
@@ -391,3 +391,18 @@ taxonomy 항목과 관리자용 case_candidates 각각에 `publication_verdict`
- 나머지 13항목(이미지·음원·편지·계약 등)은 텍스트로 판별하지 않으며 사람이 확인한다.
- 항목↔태그 매핑 중 7항목(M3a·M3b·M4·M5·M6·M10·R1)은 컴북스 확인 전이다
(`/v1/taxonomy`의 `tag_basis=추정`). 확인 후 값이 바뀌어도 응답 형식은 그대로다.
### 8-4. 예외 코드 F1 (미분류)
매칭은 있지만 18항목 중 어느 항목도 정하지 못하면 `case_id`를 null 대신 `F1`로 낸다.
`F1`은 18항목이 아닌 예외 코드라 `GET /v1/taxonomy`에는 없다. `case_candidates`에는
`F1` 후보 하나(`title=미분류`, `handling=terms_or_report`)가 들어가고, 정하지 못한 이유는
그 후보의 `reason`에 담긴다.
| 경우 | `reason` 요지 |
|---|---|
| 엔진이 주 태그를 내지 못함 | 일치 구간과 원본 종류를 확인해 사람이 항목 지정 |
| 주 태그가 엔진 판별 대상 항목과 충분히 겹치지 않음 | 일치 구간과 원본 종류를 확인해 사람이 항목 지정 |
| 서버가 분류 체계를 불러오지 못함 | 서버 설정(`TAXONOMY_DIR`) 확인 필요 |
매칭이 없는 응답(`matches=[]`)에는 분류 코드가 없다.
+40
View File
@@ -136,6 +136,46 @@ def test_case_reason_explains_tags_ties_and_draft_mapping():
assert '추정치' in PlagiarismDetector._case_reason(m10, ['reproduction'], hit, tie)
def test_unclassified_reason_differs_by_route():
from app.engine.detector import PlagiarismDetector
from app.engine.similarity import SimilarityHit
tax = load_taxonomy(Path('data/taxonomy'))
hit = SimilarityHit(doc_id='d', title='t', score=.4, text_sim=.2, lemma_sim=.2,
element_sim={'characters': .1, 'motifs': .1}, evidence=[])
no_taxonomy = PlagiarismDetector._unclassified_candidate(None, ['reproduction'], hit)
no_primary = PlagiarismDetector._unclassified_candidate(tax, [], hit)
no_overlap = PlagiarismDetector._unclassified_candidate(tax, ['integrity'], hit)
assert tax.find_cases(['integrity']) == ()
for c in (no_taxonomy, no_primary, no_overlap):
assert c.case_id == 'F1' and c.title == '미분류'
assert c.handling == 'terms_or_report' and c.matched_tags == []
assert c.precedent_note and 'text=0.20' in c.reason
assert 'TAXONOMY_DIR' in no_taxonomy.reason
assert no_primary.reason.startswith('엔진이 주 태그를 내지 못해')
assert '동일성유지권' in no_overlap.reason and 'M1·M2·M7·M10·P2' in no_overlap.reason
assert len({no_taxonomy.reason, no_primary.reason, no_overlap.reason}) == 3
def test_match_without_primary_tags_gets_f1():
"""주 태그가 없어 항목을 못 정한 매칭도 case_id 가 null 이 아니라 F1 이어야 한다."""
from app.engine.detector import PlagiarismDetector
from app.engine.similarity import SimilarityHit
hit = SimilarityHit(doc_id='d', title='t', score=.4, text_sim=.2, lemma_sim=.2,
element_sim={'characters': .1, 'motifs': .1}, evidence=[])
det = PlagiarismDetector.__new__(PlagiarismDetector)
det.taxonomy = load_taxonomy(Path('data/taxonomy'))
match = det._to_match(hit, True, None)
assert [t.role for t in match.tags] == ['secondary']
assert match.case_id == 'F1' and match.case_title == '미분류'
assert [c.case_id for c in match.case_candidates] == ['F1']
assert match.case_candidates[0].reason.startswith('엔진이 주 태그를 내지 못해')
assert match.publication_verdict_status == 'source_pending'
assert '분류 미확정(F1)' in det._build_ccl_basis([match])
det.taxonomy = None
match = det._to_match(hit, True, None)
assert match.case_id == 'F1' and 'TAXONOMY_DIR' in match.case_candidates[0].reason
def test_partial_verbatim_copy_gets_case_code(tmp_path):
"""원고 일부만 그대로 옮긴 경우 전체 유사도가 중간이라도 분류 코드가 비면 안 된다.