import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from typing import List, Dict, Tuple, Optional
def preprocess_text(text: str) -> str:
"""
Preprocess text: lowercase, remove punctuation, extra whitespace.
"""
text = text.lower()
text = re.sub(r'[^\w\s]', ' ', text) # Remove punctuation
text = re.sub(r'\s+', ' ', text).strip() # Normalize whitespace
return text
def detect_plagiarism(documents: List[str], threshold: float = 0.85, min_length: int = 50) -> Dict[str, Dict[str, float]]:
"""
Detect plagiarism across a list of text documents.
Args:
documents (List[str]): List of text documents (strings). Each string is a document.
threshold (float): Similarity threshold above which documents are considered plagiarized (0-1).
min_length (int): Minimum word count for a document to be considered.
Returns:
Dict[str, Dict[str, float]]: A dictionary where keys are document indices (as strings),
and values are dicts of similarities to other documents.
Entries > threshold indicate potential plagiarism.
Example:
docs = [
"This is the original text about machine learning.",
"This is the original text about machine learning.", # 100% plagiarized
"Machine learning is a subset of AI." # Partial similarity
]
results = detect_plagiarism(docs)
print(results)
"""
if len(documents) < 2:
return {}
# Preprocess documents
processed_docs = [preprocess_text(doc) for doc in documents]
# Filter short documents
valid_indices = [i for i, doc in enumerate(processed_docs) if len(doc.split()) >= min_length]
if len(valid_indices) < 2:
return {}
valid_docs = [processed_docs[i] for i in valid_indices]
# TF-IDF Vectorization
vectorizer = TfidfVectorizer(stop_words='english', min_df=1, max_df=0.95, ngram_range=(1, 2))
tfidf_matrix = vectorizer.fit_transform(valid_docs)
# Compute cosine similarity matrix
similarity_matrix = cosine_similarity(tfidf_matrix)
# Build results dict (using original indices)
results = {}
for i, orig_idx in enumerate(valid_indices):
results[str(orig_idx)] = {}
for j in range(len(valid_indices)):
if i != j:
sim = similarity_matrix[i][j]
other_idx = valid_indices[j]
results[str(orig_idx)][str(other_idx)] = float(sim)
return results
def find_plagiarized_pairs(results: Dict[str, Dict[str, float]], threshold: float) -> List[Tuple[str, str, float]]:
"""
Utility function to extract pairs of documents that exceed the plagiarism threshold.
Args:
results: Output from detect_plagiarism.
threshold: Similarity threshold.
Returns:
List of (doc1_idx, doc2_idx, similarity) tuples, sorted by similarity descending.
"""
pairs = []
for doc1, sims in results.items():
for doc2, sim in sims.items():
if sim > threshold:
pairs.append((doc1, doc2, sim))
return sorted(pairs, key=lambda x: x[2], reverse=True)
# Example usage
if __name__ == "__main__":
sample_docs = [
"Artificial intelligence is transforming the world by enabling machines to perform tasks that typically require human intelligence.",
"AI is changing the world through machines doing human-like tasks.",
"Machine learning, a subset of artificial intelligence, focuses on algorithms that improve through experience.",
"Artificial intelligence is transforming the world by enabling machines to perform tasks that typically require human intelligence." # Exact copy of first
]
results = detect_plagiarism(sample_docs, threshold=0.85)
plag_pairs = find_plagiarized_pairs(results, 0.85)
print("Plagiarism Results (similarity matrix):")
print(results)
print("\nPlagiarized Pairs (above 0.85):")
for pair in plag_pairs:
print(f"Docs {pair[0]} and {pair[1]}: {pair[2]:.3f}")
Key Features:
Preprocessing: Normalizes text (lowercase, removes punctuation, normalizes whitespace).
TF-IDF + Cosine Similarity: Industry-standard for plagiarism detection; handles word frequency and document length effectively.
Flexible Input: List of strings (documents); works with any number of texts.
Threshold-Based: Configurable similarity threshold (default 0.85 for strong matches).
Short Document Filter: Ignores very short texts to avoid false positives.
Output: Detailed similarity dict + utility for high-risk pairs.
Dependencies: scikit-learn, numpy (install via pip install scikit-learn numpy).
Extensible: Easily adapt for file inputs (e.g., read from PDFs/Word via PyPDF2 or docx).
This detects substantial copying (phrases/sentences), not just exact matches. For advanced needs (e.g., paraphrasing), integrate semantic embeddings like sentence-transformers.