- data/taxonomy/cases_v3.0.json: 아카이빙DB v3.0 「2.원고점검체계18」 + 부록1-A 대표판례. 항목↔태그 매핑은 원문 표가 없어 tag_basis(명시/추정)로 구분 (추정 7항목은 컴북스 확인 대기) - 분류 후보를 엔진 판별 대상(M1·M2·M7·M10·P2)으로 한정 - admin detect 응답 case_candidates 에 matched_tags·reason·decision_steps·author_request 추가 (author 응답에서는 기존대로 제외) - /v1/taxonomy 에 항목별 판단 기준·판정 단계·문면·태그 근거 노출 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
137 lines
6.8 KiB
Python
137 lines
6.8 KiB
Python
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.api.schemas import (BatchStatusResponse, CaseCandidate, DetectResponse,
|
|
EvidenceSpan, ExtractedElements, LegalRiskSignal, MatchResult)
|
|
from app.engine.taxonomy import load_taxonomy
|
|
|
|
|
|
def response(audience):
|
|
return DetectResponse(
|
|
audience=audience, doc_id="test", is_infringement=True, confidence=.9,
|
|
extracted_elements=ExtractedElements(), engine_version="test-engine",
|
|
taxonomy_version="cases_1.3", analyzed_at=datetime.now(timezone.utc),
|
|
ccl_basis="A6 판례 2006나16757",
|
|
legal_risk=LegalRiskSignal(
|
|
status="review_required", similarity_evidence="A6",
|
|
protected_expression="not_reviewed", access_evidence="not_provided",
|
|
precedent_ids=["2006나16757"], judgment_summary="A6 2006나16757",
|
|
supporting_reasons=["A6 2006나16757"], disclaimer="검토 필요"),
|
|
matches=[MatchResult(source_doc="source", similarity=.9, case_id="A6",
|
|
case_title="case", evidence_spans=[EvidenceSpan(start=0,end=3,matched="일치문")],
|
|
case_candidates=[CaseCandidate(case_id="A6",title="case",
|
|
handling="technical_detection", representative_precedents=["2006나16757"])])],
|
|
)
|
|
|
|
|
|
def test_author_http_and_batch_serialization():
|
|
app = FastAPI()
|
|
@app.get('/detect', response_model=DetectResponse)
|
|
def detect():
|
|
return response('author')
|
|
@app.get('/batch', response_model=BatchStatusResponse)
|
|
def batch():
|
|
return BatchStatusResponse(job_id='job',status='completed',total=1,processed=1,
|
|
created_at=datetime.now(timezone.utc),results=[response('author')])
|
|
with TestClient(app) as client:
|
|
direct=client.get('/detect').json()
|
|
nested=client.get('/batch').json()['results'][0]
|
|
for body in (direct,nested):
|
|
assert 'A6' not in str(body) and '2006나16757' not in str(body)
|
|
assert 'case_id' not in body['matches'][0]
|
|
assert 'legal_risk' not in body
|
|
assert body['matches'][0]['evidence_spans'][0]['start']==0
|
|
assert body['request_id'] and body['taxonomy_version']=='cases_1.3'
|
|
assert body['ccl_basis']=='확인이 필요한 부분이 있습니다.'
|
|
|
|
|
|
def test_admin_preserves_candidates_and_unknown_verdict():
|
|
body=response('admin').model_dump()
|
|
assert body['matches'][0]['case_id']=='A6'
|
|
assert body['matches'][0]['case_candidates'][0]['representative_precedents']==['2006나16757']
|
|
assert body['matches'][0]['publication_verdict'] is None
|
|
assert body['matches'][0]['publication_verdict_status']=='source_pending'
|
|
assert response('admin').request_id != response('admin').request_id
|
|
|
|
|
|
def test_taxonomy_verdicts_come_from_v3_checklist():
|
|
tax=load_taxonomy(Path('data/taxonomy'))
|
|
assert len(tax.cases)==18
|
|
verdicts={c.case_id: c.publication_verdict for c in tax.cases}
|
|
assert verdicts['M1']=='조건부' and verdicts['M2']=='조건부(동의 확보)'
|
|
assert all(verdicts.values())
|
|
|
|
|
|
def test_real_detector_forwards_audience_for_direct_batch_and_review(tmp_path):
|
|
from app.main import app
|
|
text = Path('data/reference/ref-0001__어린왕자.txt').read_text()
|
|
from scripts.run_precision_eval import build_corpus
|
|
from app.engine.persistent_index import PersistentCorpusIndex
|
|
from app.engine.detector import PlagiarismDetector
|
|
from app.core.config import get_settings
|
|
db = tmp_path / 'corpus.sqlite3'
|
|
index = tmp_path / 'index'
|
|
build_corpus([{'author':'reference','segment_id':'ref-1','text':text}], db)
|
|
PersistentCorpusIndex(db, index).sync()
|
|
settings = get_settings().model_copy(update={
|
|
'use_persistent_index':True,'corpus_db_path':str(db),
|
|
'persistent_index_dir':str(index)})
|
|
with TestClient(app) as client:
|
|
app.state.detector = PlagiarismDetector(settings)
|
|
payload={'doc_id':'audience-test','text':text,'options':{'audience':'author','threshold':0}}
|
|
direct=client.post('/v1/plagiarism/detect',json=payload)
|
|
assert direct.status_code==200
|
|
body=direct.json()
|
|
assert body['audience']=='author' and body['matches']
|
|
assert all('case_candidates' not in m for m in body['matches'])
|
|
batch=client.post('/v1/plagiarism/batch',json={
|
|
'items':[{'doc_id':'batch-author','text':text}],
|
|
'options':{'audience':'author','threshold':0}})
|
|
result=client.get('/v1/plagiarism/batch/'+batch.json()['job_id']).json()
|
|
assert result['status']=='completed'
|
|
assert result['results'][0]['audience']=='author'
|
|
assert 'legal_risk' not in result['results'][0]
|
|
review=client.post('/v1/plagiarism/review',json=payload).json()
|
|
assert review['legal_judgment']['precedent_ids']==[]
|
|
assert review['legal_judgment']['label']=='확인이 필요한 부분'
|
|
admin=client.post('/v1/plagiarism/detect',json={
|
|
'doc_id':'admin-test','text':text,'options':{'threshold':0}}).json()
|
|
assert admin['audience']=='admin' and 'legal_risk' in admin
|
|
assert any(m['case_candidates'] for m in admin['matches'])
|
|
verdicts={c.case_id: c.publication_verdict
|
|
for c in load_taxonomy(Path('data/taxonomy')).cases}
|
|
for m in admin['matches']:
|
|
for c in m['case_candidates']:
|
|
assert c['publication_verdict']==verdicts[c['case_id']]
|
|
assert c['reason'].startswith('엔진 주 태그') and c['matched_tags']
|
|
assert all(m['publication_verdict_status']=='review_required'
|
|
for m in admin['matches'] if m['case_candidates'])
|
|
|
|
|
|
def test_author_no_match_message_and_invalid_audience():
|
|
import pytest
|
|
from pydantic import ValidationError
|
|
from app.api.schemas import DetectOptions
|
|
result = response('author').model_copy(update={'matches': []})
|
|
assert result.model_dump()['ccl_basis'] == '등록된 비교 자료에서 일치 구간을 찾지 못했습니다.'
|
|
with pytest.raises(ValidationError):
|
|
DetectOptions(audience='public')
|
|
|
|
|
|
def test_case_reason_explains_tags_ties_and_draft_mapping():
|
|
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=.9, text_sim=.45, lemma_sim=.3,
|
|
element_sim={'characters': .35}, evidence=[])
|
|
tie = tax.find_cases(['reproduction'])
|
|
m1, m10 = tie
|
|
reason = PlagiarismDetector._case_reason(m1, ['reproduction'], hit, tie)
|
|
assert '복제권' in reason and 'M1(남의 글을 옮겨 실었다)' in reason
|
|
assert 'text=0.45' in reason and 'M1, M10 중 하나로' in reason
|
|
assert '판단할 것: Q3' in reason and '추정치' not in reason
|
|
assert '추정치' in PlagiarismDetector._case_reason(m10, ['reproduction'], hit, tie)
|