"""Dependency-free exact and near-duplicate detection."""
from __future__ import annotations
import re
import unicodedata
from difflib import SequenceMatcher
from ..models import ParsedDocument
from .models import DuplicateGroup, DuplicateReport
def _canonical(text: str) -> str:
normalized = unicodedata.normalize("NFKC", text).casefold()
return re.sub(r"\s+", " ", normalized).strip()
[docs]
def detect_duplicates(
document: ParsedDocument,
*,
threshold: float = 0.92,
min_chars: int = 20,
) -> DuplicateReport:
"""Group duplicate document elements using exact or similarity matching.
This intentionally uses a standard-library matcher and is best suited to
modest document element counts. Similarity matching is quadratic in the
number of eligible elements; use a dedicated index for very large corpora.
"""
if not 0 < threshold <= 1:
raise ValueError("threshold must be greater than 0 and at most 1")
if min_chars < 1:
raise ValueError("min_chars must be at least 1")
texts = [element.text for element in document.elements]
if not texts:
texts = [document.content]
eligible = [
(index, _canonical(text))
for index, text in enumerate(texts)
if len(_canonical(text)) >= min_chars
]
parent = {index: index for index, _ in eligible}
members = {index: [index] for index, _ in eligible}
group_similarity: dict[int, float] = {}
group_exact: dict[int, bool] = {}
def find(index: int) -> int:
while parent[index] != index:
parent[index] = parent[parent[index]]
index = parent[index]
return index
for position, (left_index, left_text) in enumerate(eligible):
for right_index, right_text in eligible[position + 1 :]:
if left_text == right_text:
similarity, exact = 1.0, True
else:
similarity = SequenceMatcher(
None, left_text, right_text, autojunk=False
).ratio()
exact = False
if similarity < threshold:
continue
left_root, right_root = find(left_index), find(right_index)
if left_root == right_root:
continue
parent[right_root] = left_root
members[left_root].extend(members.pop(right_root))
group_similarity[left_root] = min(
similarity,
group_similarity.get(left_root, 1.0),
group_similarity.pop(right_root, 1.0),
)
group_exact[left_root] = (
group_exact.get(left_root, True)
and group_exact.pop(right_root, True)
and exact
)
groups = []
for root, indices in members.items():
if len(indices) < 2:
continue
indices.sort()
groups.append(
DuplicateGroup(
representative_index=indices[0],
duplicate_indices=tuple(indices[1:]),
similarity=group_similarity.get(root, 1.0),
exact=group_exact.get(root, True),
)
)
groups.sort(key=lambda group: group.representative_index)
return DuplicateReport(tuple(groups), len(eligible), threshold)