write a snippet of code which deduplicates documents (list of texts) and only returns the texts without duplicates using python
Assistant
python
def deduplicate_documents(documents):
"""Deduplicates a list of text documents.
Args:
documents: A list of strings, where each string represents a document.
Returns:
A list of unique documents, preserving the order of the first occurrence.
"""
seen_documents = set()
unique_documents = []
for document in documents:
if document not in seen_documents:
seen_documents.add(document)
unique_documents.append(document)
return unique_documents
# Example usage:
documents = [
"This is the first document.",
"This is the second document.",
"This is the first document.",
"This is the third document."
]
unique_documents = deduplicate_documents(documents)
print(unique_documents)
Explanation:
deduplicate_documents(documents) function:
Takes a list of documents as input.
Initializes an empty set called seen_documents to keep track of unique documents encountered.
Initializes an empty list called unique_documents to store the deduplicated documents.
Iterating through documents:
The code iterates through each document in the input documents list.
Checking for duplicates:
For each document, it checks if the document is already present in the seen_documents set.
If the document is not in the set (meaning it's unique), the following happens:
The document is added to the seen_documents set to mark it as seen.
The document is appended to the unique_documents list.
Returning unique documents:
User
can I use minhash for that, for near deduplication
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
After processing all documents, the function returns the unique_documents list, which now contains only the unique documents in the order they first appeared in the input list.
Key points:
Sets for efficient duplicate checking: Using a set (seen_documents) allows for fast membership checking (checking if a document is already seen) because sets have constant-time lookup complexity.
Preserving order: The code preserves the order of the first occurrence of each unique document.
Let me know if you have any other questions or would like to explore different deduplication techniques!
Yes, you can use MinHash for near-duplicate detection, which is particularly useful when dealing with large datasets or when you want to find documents that are similar but not exactly the same. MinHash is a probabilistic data structure that allows you to estimate the similarity between two sets by comparing their hash values. Here's an example of how you can use the minhash library in Python to find near-duplicate documents:
First, install the minhash library if you haven't already:
bash
pip install minhash
Now, here's a snippet of code that uses MinHash for near-duplicate detection:
python
from minhash import MinHash, MinHashLSH
def find_near_duplicates(documents, similarity_threshold=0.7):
"""Finds near-duplicate documents using MinHash.
Args:
documents: A list of strings, where each string represents a document.
similarity_threshold: The minimum similarity score required for documents to be considered near-duplicates (default is 0.7).
Returns:
A list of tuples, where each tuple contains a document and its near-duplicates with a similarity score above the threshold.
"""
minhash = MinHash(num_perm=128) # You can adjust the number of permutations (num_perm) for better accuracy or performance
minhash_lsh = MinHashLSH(threshold=similarity_threshold, num_perm=128)
document_to_minhash = {}
near_duplicates = []
for i, document in enumerate(documents):
document_hash = minhash.hash document
document_to_minhash[i] = document_hash
minhash_lsh.insert(document_hash, i)
for i, document_hash in document_to_minhash.items():
similar_documents = minhash_lsh.query(document_hash)
if len(similar_documents) > 1: # Skip documents with no near-duplicates
near_duplicates.append((documents[i], [(documents[j], minhash.jaccard_similarity(document_to_minhash[i], document_to_minhash[j])) for j in similar_documents]))
return near_duplicates
# Example usage:
documents = [
"This is the first document.",
"This is a slightly modified version of the first document.",
"This is the second document.",
"This is another slightly modified version of the first document.",
"This is the third document."
]
near_duplicates = find_near_duplicates(documents)
for doc, similar_docs in near_duplicates:
print(f"Document: '{doc}'")
for similar_doc, similarity_score in similar_docs:
print(f"- Similar document: '{similar_doc}' (Similarity: {similarity_score:.4f})")
print()
Explanation:
Initialization:
Create a MinHash object with a specified number of permutations (num_perm).
Create a MinHashLSH object with a similarity threshold and the same number of permutations as the MinHash object.
Initialize an empty dictionary (document_to_minhash) to store the mapping between document indices and their MinHash values.
Initialize an empty list (near_duplicates) to store the near-duplicate documents along with their similarity scores.
Hashing documents:
Iterate through each document in the input documents list.
Hash the document using the MinHash object and store the hash value in the document_to_minhash dictionary.
Insert the document hash and its index into the MinHashLSH object.
Finding near-duplicates:
Iterate through the document_to_minhash dictionary.
For each document hash, query the MinHashLSH object to find similar documents with a similarity score above the threshold.
If the document has near-duplicates, append the document and its near-duplicates (along with their similarity scores) to the near_duplicates list.
Returning near-duplicates:
After processing all documents, the function returns the near_duplicates list, which now contains documents along with their near-duplicates and similarity scores.
Key points:
MinHash for near-duplicate detection: MinHash allows you to efficiently find near-duplicate documents by comparing their hash values and estimating the Jaccard similarity between the sets of n-grams (contiguous sequences of n items) in the documents.
Adjusting the similarity threshold: You can adjust the similarity_threshold parameter to change the minimum similarity score required for documents to be considered near-duplicates.
Choosing the number of permutations: The number of permutations (num_perm) affects the accuracy and performance of MinHash. A higher number of permutations generally results in better accuracy but slower performance. You can adjust this value depending on your specific use case.
Using MinHash for near-duplicate detection can be particularly useful when dealing with large datasets or when you want to find documents that are similar but not exactly the same. However, keep in mind that MinHash is a probabilistic data structure, and there might be false positives or false negatives in the results. You can fine-tune the parameters and adjust the similarity threshold to achieve better results for your specific use case.