feat: add anonymized infringement batch reporting
This commit is contained in:
1 parent
d5e0f4346d
commit
c35c5aabfc
6 files changed
+573
-30
No files matched your search
+36
-23
@@ -204,6 +204,10 @@ class PlagiarismDetector:
|
||||
options: DetectOptions | None = None,
|
||||
include_ai_segments: bool = True,
|
||||
legal_context: LegalContext | None = None,
|
||||
*,
|
||||
exclude_document_ids: set[str] | None = None,
|
||||
exclude_source_groups: set[str] | None = None,
|
||||
include_ai_detection: bool = True,
|
||||
) -> DetectResponse:
|
||||
opts = options or DetectOptions()
|
||||
default_threshold = (
|
||||
@@ -242,6 +246,8 @@ class PlagiarismDetector:
|
||||
text,
|
||||
top_k=max(opts.top_k, self.settings.persistent_rerank_top_k),
|
||||
evidence_limit=self.settings.persistent_rerank_top_k,
|
||||
exclude_document_ids=exclude_document_ids,
|
||||
exclude_source_groups=exclude_source_groups,
|
||||
)
|
||||
persistent_hits = result.hits
|
||||
union_coverage = result.union_coverage
|
||||
@@ -341,29 +347,36 @@ class PlagiarismDetector:
|
||||
)
|
||||
|
||||
# AI 탐지는 전처리 전 raw text에서만 실행한다.
|
||||
ai_result = self._ai_detector.detect(text, with_segments=include_ai_segments)
|
||||
ai_signal = AiGenerationSignal(
|
||||
suspicion_level=ai_result.suspicion_level or "unknown",
|
||||
score=ai_result.score,
|
||||
available=ai_result.available,
|
||||
provenance=ai_result.provenance,
|
||||
is_stub=ai_result.is_stub,
|
||||
model_version=ai_result.model_version,
|
||||
feature_set_version=ai_result.feature_set_version,
|
||||
pos_available=ai_result.pos_available,
|
||||
warnings=ai_result.warnings,
|
||||
segments=[{
|
||||
"index": s.index, "start": s.start, "end": s.end,
|
||||
"char_count": s.char_count, "score": s.score,
|
||||
"suspicion_level": s.suspicion_level, "scored": s.scored,
|
||||
"note": s.note,
|
||||
} for s in ai_result.segments],
|
||||
top_contributions=[
|
||||
{"feature": name, "contribution": round(value, 4)}
|
||||
for name, value in ai_result.top_contributions
|
||||
],
|
||||
note=ai_result.note,
|
||||
)
|
||||
if include_ai_detection:
|
||||
ai_result = self._ai_detector.detect(text, with_segments=include_ai_segments)
|
||||
ai_signal = AiGenerationSignal(
|
||||
suspicion_level=ai_result.suspicion_level or "unknown",
|
||||
score=ai_result.score,
|
||||
available=ai_result.available,
|
||||
provenance=ai_result.provenance,
|
||||
is_stub=ai_result.is_stub,
|
||||
model_version=ai_result.model_version,
|
||||
feature_set_version=ai_result.feature_set_version,
|
||||
pos_available=ai_result.pos_available,
|
||||
warnings=ai_result.warnings,
|
||||
segments=[{
|
||||
"index": s.index, "start": s.start, "end": s.end,
|
||||
"char_count": s.char_count, "score": s.score,
|
||||
"suspicion_level": s.suspicion_level, "scored": s.scored,
|
||||
"note": s.note,
|
||||
} for s in ai_result.segments],
|
||||
top_contributions=[
|
||||
{"feature": name, "contribution": round(value, 4)}
|
||||
for name, value in ai_result.top_contributions
|
||||
],
|
||||
note=ai_result.note,
|
||||
)
|
||||
else:
|
||||
ai_signal = AiGenerationSignal(
|
||||
suspicion_level="unknown",
|
||||
available=False,
|
||||
note="침해 판별 배치에서는 AI 생성 의심도 채점을 생략했습니다.",
|
||||
)
|
||||
sim_pct = _calibrate_similarity(confidence, threshold)
|
||||
review = ReviewSummary(
|
||||
originality_percent=100 - sim_pct,
|
||||
|
||||
@@ -18,7 +18,9 @@ import numpy as np
|
||||
from app.engine.provenance import CorpusStore, SegmentRecord
|
||||
|
||||
|
||||
INDEX_VERSION = 1
|
||||
# v2: segment → document 및 문서 → 익명 작성자 그룹 메타를 함께 보관한다.
|
||||
# 배치에서 자기 문서/같은 작성자의 후보를 후보 순위 단계부터 제외하기 위함이다.
|
||||
INDEX_VERSION = 2
|
||||
VECTORIZER_CONFIG = {
|
||||
"analyzer": "char_wb",
|
||||
"ngram_range": [3, 4],
|
||||
@@ -158,7 +160,10 @@ class PersistentCorpusIndex:
|
||||
return False
|
||||
try:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
return self._matrix_path(meta).exists()
|
||||
return (
|
||||
meta.get("version") == INDEX_VERSION
|
||||
and self._matrix_path(meta).exists()
|
||||
)
|
||||
except (OSError, ValueError, json.JSONDecodeError):
|
||||
return False
|
||||
|
||||
@@ -214,6 +219,7 @@ class PersistentCorpusIndex:
|
||||
mode = "append"
|
||||
|
||||
by_id = {s.segment_id: s for s in segments}
|
||||
document_source_groups = self.store.document_source_groups()
|
||||
existing_set = set(existing_ids)
|
||||
new_ids = [s.segment_id for s in segments if s.segment_id not in existing_set]
|
||||
vectorizer = _vectorizer(n_features)
|
||||
@@ -238,6 +244,8 @@ class PersistentCorpusIndex:
|
||||
"n_features": n_features,
|
||||
"vectorizer_config": VECTORIZER_CONFIG,
|
||||
"segment_ids": ids,
|
||||
"segment_document_ids": [by_id[i].document_id for i in ids],
|
||||
"document_source_groups": document_source_groups,
|
||||
"text_hashes": {i: current[i] for i in ids},
|
||||
"document_count": self.store.document_count(),
|
||||
"matrix_file": matrix_file,
|
||||
@@ -251,10 +259,22 @@ class PersistentCorpusIndex:
|
||||
self._matrix, self._meta = matrix, meta
|
||||
return {"mode": mode, "total": len(ids), "added": len(new_ids)}
|
||||
|
||||
def query(self, text: str, top_k: int = 50, min_score: float = 0.0,
|
||||
evidence_limit: int | None = None) -> list[PersistentHit]:
|
||||
def query(
|
||||
self,
|
||||
text: str,
|
||||
top_k: int = 50,
|
||||
min_score: float = 0.0,
|
||||
evidence_limit: int | None = None,
|
||||
*,
|
||||
exclude_document_ids: set[str] | None = None,
|
||||
exclude_source_groups: set[str] | None = None,
|
||||
) -> list[PersistentHit]:
|
||||
"""후보만 필요할 때 쓰는 얇은 래퍼. union coverage 가 필요하면 search()."""
|
||||
return self.search(text, top_k, min_score, evidence_limit).hits
|
||||
return self.search(
|
||||
text, top_k, min_score, evidence_limit,
|
||||
exclude_document_ids=exclude_document_ids,
|
||||
exclude_source_groups=exclude_source_groups,
|
||||
).hits
|
||||
|
||||
def search(
|
||||
self,
|
||||
@@ -262,6 +282,9 @@ class PersistentCorpusIndex:
|
||||
top_k: int = 50,
|
||||
min_score: float = 0.0,
|
||||
evidence_limit: int | None = None,
|
||||
*,
|
||||
exclude_document_ids: set[str] | None = None,
|
||||
exclude_source_groups: set[str] | None = None,
|
||||
) -> PersistentQueryResult:
|
||||
"""후보 검색 + 상위 evidence_limit 개에 대해서만 정밀 비교.
|
||||
|
||||
@@ -296,8 +319,31 @@ class PersistentCorpusIndex:
|
||||
improved = local_scores > scores
|
||||
scores[improved] = local_scores[improved]
|
||||
best_chunk[improved] = batch_start + local_argmax[improved]
|
||||
k = min(max(1, top_k), len(scores))
|
||||
indexes = np.argpartition(scores, -k)[-k:]
|
||||
# 자기 문서와 같은 익명 작성자 그룹을 여기서 제외한다. 상위 K를 먼저
|
||||
# 뽑아 뒤늦게 제거하면 자기매칭이 실제 후보를 밀어내므로, 전량 점수에서
|
||||
# 허용 후보만 골라 순위를 만든다.
|
||||
excluded_documents = set(exclude_document_ids or ())
|
||||
excluded_groups = set(exclude_source_groups or ())
|
||||
document_ids = self._meta.get("segment_document_ids", [])
|
||||
if len(document_ids) != len(scores):
|
||||
raise ValueError("인덱스 문서 메타가 없어 재빌드가 필요합니다")
|
||||
source_groups = self._meta.get("document_source_groups", {})
|
||||
eligible = np.fromiter(
|
||||
(
|
||||
document_id not in excluded_documents
|
||||
and source_groups.get(document_id, "") not in excluded_groups
|
||||
for document_id in document_ids
|
||||
),
|
||||
dtype=bool,
|
||||
count=len(document_ids),
|
||||
)
|
||||
eligible_indexes = np.flatnonzero(eligible)
|
||||
if not len(eligible_indexes):
|
||||
return PersistentQueryResult([], 0.0, 0, len(text), evidence_limit or 0, False, {})
|
||||
k = min(max(1, top_k), len(eligible_indexes))
|
||||
eligible_scores = scores[eligible_indexes]
|
||||
selected = np.argpartition(eligible_scores, -k)[-k:]
|
||||
indexes = eligible_indexes[selected]
|
||||
indexes = indexes[np.argsort(scores[indexes])[::-1]]
|
||||
ids = [self._meta["segment_ids"][int(i)] for i in indexes if scores[int(i)] >= min_score]
|
||||
records = self.store.get_segments(ids)
|
||||
|
||||
@@ -315,6 +315,46 @@ class CorpusStore:
|
||||
).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def document_source_groups(self) -> dict[str, str]:
|
||||
"""문서별 익명 작성자 그룹을 반환한다.
|
||||
|
||||
``author_group`` 은 수령 XLSX 적재기의 기존 필드이고, ``source_group`` 은
|
||||
새 수집 원문·학습 데이터에서 쓰는 공통 필드다. 둘 다 가명 값만 허용한다.
|
||||
영속 인덱스가 자기 작성자의 후보를 검색 단계에서 제외할 때 사용한다.
|
||||
"""
|
||||
if not self.path.exists():
|
||||
return {}
|
||||
with self._connect() as con:
|
||||
rows = con.execute(
|
||||
"SELECT document_id, metadata_json FROM documents"
|
||||
).fetchall()
|
||||
groups: dict[str, str] = {}
|
||||
for row in rows:
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
group = str(
|
||||
metadata.get("source_group") or metadata.get("author_group") or ""
|
||||
).strip()
|
||||
if group:
|
||||
groups[str(row["document_id"])] = group
|
||||
return groups
|
||||
|
||||
def documents_with_metadata(self) -> list[DocumentRecord]:
|
||||
"""배치·감사용 문서 목록. 원문 세그먼트는 포함하지 않는다."""
|
||||
if not self.path.exists():
|
||||
return []
|
||||
with self._connect() as con:
|
||||
rows = con.execute(
|
||||
"""SELECT document_id, title, source_path, source_sha256, metadata_json
|
||||
FROM documents ORDER BY document_id"""
|
||||
).fetchall()
|
||||
return [DocumentRecord(
|
||||
document_id=str(row["document_id"]),
|
||||
title=str(row["title"]),
|
||||
source_path=row["source_path"],
|
||||
source_sha256=row["source_sha256"],
|
||||
metadata=json.loads(row["metadata_json"] or "{}"),
|
||||
) for row in rows]
|
||||
|
||||
def delete_document(self, document_id: str) -> bool:
|
||||
if not self.path.exists():
|
||||
return False
|
||||
|
||||
Reference in new issue
Block a user