Now I'm adding some advanced features to handle batch document processing. A DocumentCorpus class manages multiple documents through the detector, storing duplicate pairs found during analysis. The add_from_file method reads documents from disk and registers them with the detector using a unique identifier.
For finding duplicates across the entire corpus, I iterate through all document pairs while tracking which ones have already been processed to avoid redundant comparisons. The method uses LSH for efficiency and returns results sorted by similarity score, allowing callers to optionally override the similarity threshold.
When exporting results, I generate a formatted report that includes the total document count and number of duplicate pairs discovered, then lists each pair with both the LSH-estimated similarity and the actual Jaccard similarity for comparison.
Now I'm defining a SimilarityMatrix class to compute pairwise document similarities. The compute method builds an n×n matrix where diagonal entries are 1.0, and for the upper triangle I calculate similarities between document pairs, with an option to use either the approximate or true similarity metric. I need to complete the partial thought and then summarize the next thinking.
The current rewritten thinking shows the end of a similarity matrix computation and printing method. Looking at the next thinking, I can see it's starting a new function for corpus analysis.
Here's the completed and rewritten thinking:
def example_corpus_analysis():
"""Analyze document corpus."""
print("\n" + "=" * 60)
print("CORPUS ANALYSIS EXAMPLE")
print("=" * 60)
detector = PlagiarismDetector(k=5, num_hashes=128, similarity_threshold=0.4)
docs = {
"student1": "The theory of evolution explains biodiversity through natural selection",
"student2": "Evolution theory accounts for species diversity via natural selection",
"student3": "Quantum mechanics studies atomic and subatomic phenomena",
"student4": "Python is useful for data science and machine learning",
"student5": "Programming in Python helps with data science tasks",
}
for doc_id, text in docs.items():
detector.add_document(doc_id, text)
I'm setting up a demonstration function that initializes a plagiarism detector with specific parameters and loads a set of sample documents representing different topics—two pairs with similar content about evolution and Python, plus one unrelated quantum mechanics document.</think>
# Plagiarism Detection Using Shingling and MinHash
I'll implement a complete plagiarism detection system using shingling, MinHash, and LSH for efficient near-duplicate detection.
```python
import hashlib
import numpy as np
from typing import Set, Tuple, List, Dict, Optional
from collections import defaultdict
import time
from dataclasses import dataclass
# ============================================================================
# 1. SHINGLE GENERATION
# ============================================================================
class ShingleGenerator:
"""Generate k-gram shingles from text."""
def __init__(self, k: int = 5):
"""
Args:
k: Shingle size (number of characters or words)
"""
self.k = k
def generate_char_shingles(self, text: str, as_hashes: bool = False) -> Set:
"""Generate character-level shingles."""
text = text.lower().strip()
shingles = set()
if len(text) < self.k:
shingles = {text} if text else set()
else:
shingles = {text[i:i+self.k] for i in range(len(text) - self.k + 1)}
if as_hashes:
return {self._hash_shingle(s) for s in shingles}
return shingles
def generate_word_shingles(self, text: str, as_hashes: bool = False) -> Set:
"""Generate word-level shingles."""
words = text.lower().split()
shingles = set()
if len(words) < self.k:
shingles = {tuple(words)} if words else set()
else:
shingles = {tuple(words[i:i+self.k]) for i in range(len(words) - self.k + 1)}
if as_hashes:
return {self._hash_shingle(str(s)) for s in shingles}
return shingles
@staticmethod
def _hash_shingle(shingle: str) -> int:
"""Hash shingle to 64-bit integer."""
return int(hashlib.md5(shingle.encode()).hexdigest(), 16)
# ============================================================================
# 2. MINHASH SIGNATURE COMPUTATION
# ============================================================================
class MinHashSignature:
"""Generate MinHash signatures for approximate set comparison."""
def __init__(self, num_hashes: int = 128, seed: int = 42):
"""
Args:
num_hashes: Number of hash functions
seed: Random seed for reproducibility
"""
self.num_hashes = num_hashes
self.seed = seed
np.random.seed(seed)
# Generate random coefficients for hash functions
self.a = np.random.randint(1, 2**31, num_hashes)
self.b = np.random.randint(0, 2**31, num_hashes)
self.max_value = 2**32 - 1
def generate_signature(self, shingles: Set[int]) -> np.ndarray:
"""
Generate MinHash signature for a set of shingles.
Args:
shingles: Set of hashed shingle values
Returns:
MinHash signature (array of min hash values)
"""
signature = np.full(self.num_hashes, self.max_value, dtype=np.uint32)
for shingle in shingles:
# Apply each hash function: h(x) = (a*x + b) mod p
for i in range(self.num_hashes):
hashed = ((self.a[i] * shingle + self.b[i]) % (2**31 - 1))
signature[i] = min(signature[i], hashed)
return signature
def jaccard_similarity(self, sig1: np.ndarray, sig2: np.ndarray) -> float:
"""
Estimate Jaccard similarity from MinHash signatures.
J(A,B) ≈ (# of matching rows) / (total # of rows)
Args:
sig1: First signature
sig2: Second signature
Returns:
Estimated Jaccard similarity [0, 1]
"""
matches = np.sum(sig1 == sig2)
return matches / self.num_hashes
def get_error_bounds(self) -> Tuple[float, float]:
"""
Calculate confidence bounds for MinHash estimation.
Returns:
(error_probability, max_error) - with 95% confidence
"""
# Standard error ≈ sqrt(1/num_hashes)
std_error = 1.0 / np.sqrt(self.num_hashes)
# 95% confidence interval ≈ 1.96 * std_error
max_error = 1.96 * std_error
error_prob = 0.05
return error_prob, max_error
# ============================================================================
# 3. LOCALITY-SENSITIVE HASHING (LSH) FOR EFFICIENT RETRIEVAL
# ============================================================================
class LSHBands:
"""Locality-Sensitive Hashing with banding for efficient candidate finding."""
def __init__(self, num_hashes: int = 128, num_bands: int = 8):
"""
Args:
num_hashes: Total number of hash functions
num_bands: Number of bands to split signature
Band strategy: Split signature into bands to increase collision probability
for similar documents while reducing false positives.
"""
if num_hashes % num_bands != 0:
raise ValueError("num_hashes must be divisible by num_bands")
self.num_hashes = num_hashes
self.num_bands = num_bands
self.rows_per_band = num_hashes // num_bands
# Hash tables: band_id -> {band_hash -> [doc_ids]}
self.hash_tables: List[Dict[str, List[str]]] = [
defaultdict(list) for _ in range(num_bands)
]
self.document_sigs: Dict[str, np.ndarray] = {}
def add_document(self, doc_id: str, signature: np.ndarray):
"""Add document signature to LSH structure."""
self.document_sigs[doc_id] = signature
# Split signature into bands and hash each
for band_id in range(self.num_bands):
start_idx = band_id * self.rows_per_band
end_idx = start_idx + self.rows_per_band
band = signature[start_idx:end_idx]
# Hash band and add to hash table
band_hash = hashlib.md5(band.tobytes()).hexdigest()
self.hash_tables[band_id][band_hash].append(doc_id)
def query_candidates(self, query_sig: np.ndarray) -> Set[str]:
"""
Find candidate near-duplicates using LSH banding.
A document is a candidate if it hashes to the same bucket
in at least one band.
Args:
query_sig: Query MinHash signature
Returns:
Set of candidate document IDs
"""
candidates = set()
for band_id in range(self.num_bands):
start_idx = band_id * self.rows_per_band
end_idx = start_idx + self.rows_per_band
band = query_sig[start_idx:end_idx]
band_hash = hashlib.md5(band.tobytes()).hexdigest()
candidates.update(self.hash_tables[band_id][band_hash])
return candidates
def get_false_positive_rate(self, similarity: float) -> float:
"""
Calculate false positive rate for LSH banding.
For similarity threshold t, false positive rate is the probability
that two documents with similarity < t are retrieved as candidates.
P(false positive) = 1 - (1 - t^r)^b
where r = rows_per_band, b = num_bands
"""
term = 1.0 - (similarity ** self.rows_per_band)
return 1.0 - (term ** self.num_bands)
# ============================================================================
# 4. PLAGIARISM DETECTOR (MAIN CLASS)
# ============================================================================
@dataclass
class SimilarityMatch:
"""Stores information about a similarity match."""
document_id: str
minhash_similarity: float
true_similarity: Optional[float] = None
def __repr__(self):
if self.true_similarity is not None:
error = abs(self.minhash_similarity - self.true_similarity)
return (f"Match({self.document_id}, MinHash={self.minhash_similarity:.4f}, "
f"True={self.true_similarity:.4f}, Error={error:.4f})")
return f"Match({self.document_id}, {self.minhash_similarity:.4f})"
class PlagiarismDetector:
"""Complete plagiarism detection system using MinHash and LSH."""
def __init__(self, k: int = 5, num_hashes: int = 128,
num_bands: int = 8, similarity_threshold: float = 0.5,
use_words: bool = False):
"""
Args:
k: Shingle size
num_hashes: Number of MinHash functions
num_bands: Number of LSH bands
similarity_threshold: Minimum similarity to report match
use_words: Use word-level shingles instead of character-level
"""
self.shingle_gen = ShingleGenerator(k)
self.minhash = MinHashSignature(num_hashes)
self.lsh = LSHBands(num_hashes, num_bands)
self.similarity_threshold = similarity_threshold
self.use_words = use_words
self.documents: Dict[str, str] = {}
self.signatures: Dict[str, np.ndarray] = {}
self.shingles: Dict[str, Set] = {}
def add_document(self, doc_id: str, text: str):
"""Add document to detection system."""
if doc_id in self.documents:
raise ValueError(f"Document {doc_id} already exists")
self.documents[doc_id] = text
# Generate shingles
if self.use_words:
shingles_set = self.shingle_gen.generate_word_shingles(text, as_hashes=True)
else:
shingles_set = self.shingle_gen.generate_char_shingles(text, as_hashes=True)
self.shingles[doc_id] = shingles_set
# Generate MinHash signature
signature = self.minhash.generate_signature(shingles_set)
self.signatures[doc_id] = signature
# Add to LSH structure
self.lsh.add_document(doc_id, signature)
def get_true_jaccard_similarity(self, doc_id1: str, doc_id2: str) -> float:
"""
Compute exact Jaccard similarity.
J(A,B) = |A ∩ B| / |A ∪ B|
"""
set1 = self.shingles[doc_id1]
set2 = self.shingles[doc_id2]
intersection = len(set1 & set2)
union = len(set1 | set2)
if union == 0:
return 0.0
return intersection / union
def find_duplicates(self, doc_id: str, use_lsh: bool = True,
return_true_similarity: bool = False) -> List[SimilarityMatch]:
"""
Find duplicate/similar documents.
Args:
doc_id: Query document ID
use_lsh: Use LSH for faster candidate finding
return_true_similarity: Also compute true Jaccard similarity
Returns:
List of SimilarityMatch objects, sorted by similarity
"""
if doc_id not in self.signatures:
raise ValueError(f"Document {doc_id} not found")
query_sig = self.signatures[doc_id]
# Find candidates using LSH or brute force
if use_lsh:
candidates = self.lsh.query_candidates(query_sig)
candidates.discard(doc_id) # Remove query document
else:
candidates = set(self.signatures.keys()) - {doc_id}
# Compute similarities for candidates
results = []
for candidate_id in candidates:
candidate_sig = self.signatures[candidate_id]
minhash_sim = self.minhash.jaccard_similarity(query_sig, candidate_sig)
if minhash_sim >= self.similarity_threshold:
true_sim = None
if return_true_similarity:
true_sim = self.get_true_jaccard_similarity(doc_id, candidate_id)
results.append(SimilarityMatch(
document_id=candidate_id,
minhash_similarity=minhash_sim,
true_similarity=true_sim
))
# Sort by similarity
results.sort(key=lambda x: x.minhash_similarity, reverse=True)
return results
def find_all_near_duplicates(self, use_lsh: bool = True) -> List[Tuple[str, str, float]]:
"""
Find all near-duplicate document pairs efficiently.
Returns:
List of (doc_id1, doc_id2, similarity) tuples
"""
pairs = []
processed = set()
for doc_id in self.documents:
if doc_id not in processed:
duplicates = self.find_duplicates(doc_id, use_lsh)
for match in duplicates:
pair = tuple(sorted([doc_id, match.document_id]))
pairs.append((*pair, match.minhash_similarity))
processed.add(match.document_id)
pairs.sort(key=lambda x: x[2], reverse=True)
return pairs
def generate_report(self, doc_id: str, detailed: bool = True) -> Dict:
"""Generate detailed plagiarism report."""
matches = self.find_duplicates(doc_id, use_lsh=True,
return_true_similarity=detailed)
report = {
'query_document': doc_id,
'total_duplicates': len(matches),
'matches': []
}
for match in matches:
match_info = {
'document_id': match.document_id,
'minhash_similarity': round(match.minhash_similarity, 4),
}
if match.true_similarity is not None:
match_info['true_similarity'] = round(match.true_similarity, 4)
match_info['estimation_error'] = round(
abs(match.minhash_similarity - match.true_similarity), 4
)
report['matches'].append(match_info)
return report
def get_statistics(self) -> Dict:
"""Get corpus statistics."""
total_shingles = sum(len(shingles) for shingles in self.shingles.values())
avg_shingles = total_shingles / len(self.documents) if self.documents else 0
return {
'num_documents': len(self.documents),
'total_shingles': total_shingles,
'avg_shingles_per_doc': round(avg_shingles, 2),
'num_hashes': self.minhash.num_hashes,
'num_bands': self.lsh.num_bands,
'error_probability': round(self.minhash.get_error_bounds()[0], 4),
'estimated_max_error': round(self.minhash.get_error_bounds()[1], 4),
}
# ============================================================================
# 5. SIMILARITY MATRIX AND ANALYSIS
# ============================================================================
class SimilarityAnalyzer:
"""Analyze similarity between documents."""
def __init__(self, detector: PlagiarismDetector):
self.detector = detector
def compute_similarity_matrix(self, use_true_similarity: bool = False) -> np.ndarray:
"""Compute pairwise similarity matrix."""
doc_ids = list(self.detector.documents.keys())
n = len(doc_ids)
matrix = np.zeros((n, n))
for i, doc_id1 in enumerate(doc_ids):
for j, doc_id2 in enumerate(doc_ids):
if i == j:
matrix[i][j] = 1.0
elif i < j:
if use_true_similarity:
sim = self.detector.get_true_jaccard_similarity(doc_id1, doc_id2)
else:
sig1 = self.detector.signatures[doc_id1]
sig2 = self.detector.signatures[doc_id2]
sim = self.detector.minhash.jaccard_similarity(sig1, sig2)
matrix[i][j] = sim
matrix[j][i] = sim
return matrix, doc_ids
def print_similarity_matrix(self, use_true_similarity: bool = False):
"""Print formatted similarity matrix."""
matrix, doc_ids = self.compute_similarity_matrix(use_true_similarity)
label = "True Similarity" if use_true_similarity else "Est. Similarity (MinHash)"
print(f"\n{label} Matrix:")
print(" " * 15 + "".join(f"{did:>10}" for did in doc_ids))
print("-" * (15 + 10 * len(doc_ids)))
for i, doc_id1 in enumerate(doc_ids):
print(f"{doc_id1:>14}", end=" ")
for j in range(len(doc_ids)):
print(f"{matrix[i][j]:>10.4f}", end=" ")
print()
# ============================================================================
# 6. COMPREHENSIVE EXAMPLES
# ============================================================================
def example_basic_plagiarism_detection():
"""Basic plagiarism detection example."""
print("\n" + "="*70)
print("EXAMPLE 1: BASIC PLAGIARISM DETECTION")
print("="*70)
# Create detector
detector = PlagiarismDetector(
k=5,
num_hashes=128,
num_bands=8,
similarity_threshold=0.3
)
# Add documents
doc1 = "The quick brown fox jumps over the lazy dog"
doc2 = "The quick brown fox jumps over the lazy dog" # Exact duplicate
doc3 = "A fast brown fox jumps over a sleepy dog" # Similar
doc4 = "Python is an excellent programming language" # Different
detector.add_document("doc1", doc1)
detector.add_document("doc2", doc2)
detector.add_document("doc3", doc3)
detector.add_document("doc4", doc4)
# Find duplicates
print("\n✓ Searching for documents similar to 'doc1'...")
results = detector.find_duplicates("doc1", use_lsh=True,
return_true_similarity=True)
for match in results:
print(f" • {match}")
# Generate report
print("\n✓ Detailed Report for doc1:")
report = detector.generate_report("doc1")
print(f" Total duplicates found: {report['total_duplicates']}")
for match in report['matches']:
print(f" - {match['document_id']}: "
f"MinHash={match['minhash_similarity']}, "
f"True={match.get('true_similarity', 'N/A')}")
def example_academic_plagiarism():
"""Academic paper plagiarism detection."""
print("\n" + "="*70)
print("EXAMPLE 2: ACADEMIC PAPER PLAGIARISM DETECTION")
print("="*70)
detector = PlagiarismDetector(
k=4,
num_hashes=256,
num_bands=16,
similarity_threshold=0.3,
use_words=True
)
papers = {
"paper_A": """
Machine learning is a subset of artificial intelligence that focuses on
the development of algorithms and statistical models that enable computers
to improve their performance on tasks through experience.
""",
"paper_B": """
Machine learning, a division of AI, concentrates on creating algorithms and
statistical models allowing computers to enhance task performance through experience.
""",
"paper_C": """
Deep learning uses neural networks with multiple layers to process data.
It has revolutionized the fields of computer vision and natural language processing.
""",
"paper_D": """
Climate change is caused by increased greenhouse gases in the atmosphere.
This leads to global warming and disruption of weather patterns.
""",
}
for doc_id, text in papers.items():
detector.add_document(doc_id, text)
# Find all near-duplicates
print("\n✓ Near-Duplicate Pairs Found:")
pairs = detector.find_all_near_duplicates(use_lsh=True)
if pairs:
for doc1, doc2, sim in pairs:
print(f" • {doc1} <-> {doc2}: {sim:.4f}")
else:
print(" No near-duplicates detected above threshold")
# Similarity matrix
print("\n✓ Similarity Matrix (MinHash Estimation):")
analyzer = SimilarityAnalyzer(detector)
analyzer.print_similarity_matrix(use_true_similarity=False)
def example_lsh_efficiency():
"""Compare LSH vs Brute Force efficiency."""
print("\n" + "="*70)
print("EXAMPLE 3: LSH VS BRUTE FORCE EFFICIENCY")
print("="*70)
num_docs = 1000
base_text = " ".join([f"word{i}" for i in range(500)])
# Create detector with LSH
detector_lsh = PlagiarismDetector(k=5, num_hashes=128, num_bands=8)
# Create detector without LSH (brute force)
detector_brute = PlagiarismDetector(k=5, num_hashes=128, num_bands=1)
print(f"\n✓ Adding {num_docs} documents...")
for i in range(num_docs):
doc_text = base_text if i == 0 else base_text.replace("word0", f"word0_{i}")
detector_lsh.add_document(f"doc_{i}", doc_text)
detector_brute.add_document(f"doc_{i}", doc_text)
# Benchmark LSH
start = time.time()
results_lsh = detector_lsh.find_duplicates("doc_0", use_lsh=True)
time_lsh = time.time() - start
# Benchmark brute force
start = time.time()
results_brute = detector_brute.find_duplicates("doc_0", use_lsh=False)
time_brute = time.time() - start
print(f"\n✓ Query Performance on {num_docs} documents:")
print(f" • LSH: {time_lsh*1000:>8.2f} ms "
f"({len(results_lsh)} candidates)")
print(f" • Brute Force: {time_brute*1000:>8.2f} ms "
f"({len(results_brute)} candidates)")
print(f" • Speedup: {time_brute/time_lsh:>8.1f}x")
def example_minHash_accuracy():
"""Analyze MinHash accuracy vs true Jaccard similarity."""
print("\n" + "="*70)
print("EXAMPLE 4: MINHASH ESTIMATION ACCURACY")
print("="*70)
from random import Random, shuffle
def create_modified_text(base: str, modification_rate: float) -> str:
"""Create modified text with controlled modification rate."""
words = base.split()
rng = Random(42)
num_changes = max(1, int(len(words) * modification_rate))
indices = rng.sample(range(len(words)), num_changes)
for idx in indices:
words[idx] = f"MODIFIED_{idx}"
return " ".join(words)
base_text = " ".join([f"word{i}" for i in range(200)])
modification_rates = [0.0, 0.1, 0.2, 0.3, 0.5, 0.7]
results = []
for mod_rate in modification_rates:
detector = PlagiarismDetector(k=5, num_hashes=256, use_words=True)
detector.add_document("base", base_text)
modified = create_modified_text(base_text, mod_rate)
detector.add_document("modified", modified)
# Get signatures
sig_base = detector.signatures["base"]
sig_mod = detector.signatures["modified"]
# Compute similarities
minhash_sim = detector.minhash.jaccard_similarity(sig_base, sig_mod)
true_sim = detector.get_true_jaccard_similarity("base", "modified")
error = abs(minhash_sim - true_sim)
results.append({
'modification_rate': mod_rate,
'minhash_sim': minhash_sim,
'true_sim': true_sim,
'error': error
})
print("\n✓ MinHash Accuracy Analysis:")
print(f"{'Mod Rate':<12} {'MinHash':<12} {'True':<12} {'Error':<12} {'Rel Error %':<12}")
print("-" * 60)
for r in results:
rel_error = (r['error'] / (r['true_sim'] + 1e-10)) * 100
print(f"{r['modification_rate']*100:>10.0f}% "
f"{r['minhash_sim']:>10.4f} "
f"{r['true_sim']:>10.4f} "
f"{r['error']:>10.4f} "
f"{rel_error:>10.1f}%")
def example_shingle_analysis():
"""Analyze shingle generation and statistics."""
print("\n" + "="*70)
print("EXAMPLE 5: SHINGLE ANALYSIS")
print("="*70)
text = "The quick brown fox jumps over the lazy dog"
print(f"\nText: '{text}'")
# Character-level shingles
print("\n✓ Character-Level Shingles:")
for k in [2, 3, 4, 5]:
gen = ShingleGenerator(k=k)
shingles = gen.generate_char_shingles(text)
print(f" k={k}: {len(shingles)} shingles")
if k == 3:
print(f" Examples: {sorted(list(shingles))[:8]}")
# Word-level shingles
print("\n✓ Word-Level Shingles:")
for k in [1, 2, 3]:
gen = ShingleGenerator(k=k)
shingles = gen.generate_word_shingles(text)
print(f" k={k}: {len(shingles)} shingles")
if k == 2:
print(f" Examples: {list(shingles)[:3]}")
def example_corpus_statistics():
"""Show corpus statistics and error bounds."""
print("\n" + "="*70)
print("EXAMPLE 6: CORPUS STATISTICS AND ERROR BOUNDS")
print("="*70)
detector = PlagiarismDetector(k=5, num_hashes=256, num_bands=16)
docs = {
"doc1": "Python is a powerful programming language for data science",
"doc2": "Java is an object-oriented programming language",
"doc3": "JavaScript runs in web browsers",
}
for doc_id, text in docs.items():
detector.add_document(doc_id, text, use_words=True)
stats = detector.get_statistics()
print("\n✓ Corpus Statistics:")
for key, value in stats.items():
print(f" • {key}: {value}")
print("\n✓ MinHash Error Bounds (95% confidence):")
error_prob, max_error = detector.minhash.get_error_bounds()
print(f" • Error Probability: {error_prob:.4f}")
print(f" • Max Estimation Error: ±{max_error:.4f}")
# ============================================================================
# 7. MAIN EXECUTION
# ============================================================================
if __name__ == "__main__":
print("\n" + "█"*70)
print("█" + " "*68 + "█")
print("█" + " PLAGIARISM DETECTION USING SHINGLING AND MINHASH".center(68) + "█")
print("█" + " "*68 + "█")
print("█"*70)
# Run all examples
example_basic_plagiarism_detection()
example_shingle_analysis()
example_minHash_accuracy()
example_academic_plagiarism()
example_lsh_efficiency()
example_corpus_statistics()
print("\n" + "█"*70)
print("✓ All examples completed successfully!")
print("█"*70 + "\n")