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
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user