semhash 0.2.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {semhash-0.2.1 → semhash-0.3.0}/.gitignore +2 -0
  2. {semhash-0.2.1 → semhash-0.3.0}/PKG-INFO +72 -29
  3. {semhash-0.2.1 → semhash-0.3.0}/README.md +69 -25
  4. {semhash-0.2.1 → semhash-0.3.0}/benchmarks/run_benchmarks.py +2 -2
  5. {semhash-0.2.1 → semhash-0.3.0}/pyproject.toml +2 -1
  6. semhash-0.3.0/semhash/datamodels.py +135 -0
  7. {semhash-0.2.1 → semhash-0.3.0}/semhash/index.py +20 -0
  8. {semhash-0.2.1 → semhash-0.3.0}/semhash/records.py +2 -2
  9. semhash-0.3.0/semhash/semhash.py +584 -0
  10. semhash-0.3.0/semhash/utils.py +49 -0
  11. {semhash-0.2.1 → semhash-0.3.0}/semhash/version.py +1 -1
  12. {semhash-0.2.1 → semhash-0.3.0}/semhash.egg-info/PKG-INFO +72 -29
  13. {semhash-0.2.1 → semhash-0.3.0}/semhash.egg-info/SOURCES.txt +1 -0
  14. semhash-0.3.0/tests/conftest.py +57 -0
  15. semhash-0.3.0/tests/data/test_model/README.md +97 -0
  16. semhash-0.3.0/tests/data/test_model/config.json +12 -0
  17. semhash-0.3.0/tests/data/test_model/model.safetensors +0 -0
  18. semhash-0.3.0/tests/data/test_model/modules.json +14 -0
  19. {semhash-0.2.1 → semhash-0.3.0}/tests/data/test_model/tokenizer.json +2 -2
  20. {semhash-0.2.1 → semhash-0.3.0}/tests/test_datamodels.py +25 -2
  21. {semhash-0.2.1 → semhash-0.3.0}/tests/test_semhash.py +89 -9
  22. {semhash-0.2.1 → semhash-0.3.0}/uv.lock +5 -4
  23. semhash-0.2.1/semhash/datamodels.py +0 -80
  24. semhash-0.2.1/semhash/semhash.py +0 -296
  25. semhash-0.2.1/semhash/utils.py +0 -21
  26. semhash-0.2.1/tests/conftest.py +0 -14
  27. semhash-0.2.1/tests/data/test_model/README.md +0 -78
  28. semhash-0.2.1/tests/data/test_model/config.json +0 -1
  29. semhash-0.2.1/tests/data/test_model/model.safetensors +0 -0
  30. {semhash-0.2.1 → semhash-0.3.0}/.github/workflows/ci.yaml +0 -0
  31. {semhash-0.2.1 → semhash-0.3.0}/.pre-commit-config.yaml +0 -0
  32. {semhash-0.2.1 → semhash-0.3.0}/LICENSE +0 -0
  33. {semhash-0.2.1 → semhash-0.3.0}/Makefile +0 -0
  34. {semhash-0.2.1 → semhash-0.3.0}/assets/images/semhash_logo.png +0 -0
  35. {semhash-0.2.1 → semhash-0.3.0}/benchmarks/__init__.py +0 -0
  36. {semhash-0.2.1 → semhash-0.3.0}/benchmarks/data.py +0 -0
  37. {semhash-0.2.1 → semhash-0.3.0}/benchmarks/results/train_benchmark_results.json +0 -0
  38. {semhash-0.2.1 → semhash-0.3.0}/benchmarks/results/train_test_benchmark_results.json +0 -0
  39. {semhash-0.2.1 → semhash-0.3.0}/semhash/__init__.py +0 -0
  40. {semhash-0.2.1 → semhash-0.3.0}/semhash.egg-info/dependency_links.txt +0 -0
  41. {semhash-0.2.1 → semhash-0.3.0}/semhash.egg-info/requires.txt +0 -0
  42. {semhash-0.2.1 → semhash-0.3.0}/semhash.egg-info/top_level.txt +0 -0
  43. {semhash-0.2.1 → semhash-0.3.0}/setup.cfg +0 -0
@@ -163,3 +163,5 @@ cython_debug/
163
163
  # and can be added to the global gitignore or merged into this file. For a more nuclear
164
164
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
165
165
  #.idea/
166
+
167
+ .DS_Store
@@ -1,7 +1,7 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: semhash
3
- Version: 0.2.1
4
- Summary: Fast Semantic Text Deduplication
3
+ Version: 0.3.0
4
+ Summary: Fast Semantic Text Deduplication & Filtering
5
5
  Author-email: Thomas van Dongen <thomas123@live.nl>, Stéphan Tulkens <stephantul@gmail.com>
6
6
  License: MIT License
7
7
 
@@ -42,7 +42,6 @@ Classifier: Programming Language :: Python :: 3.12
42
42
  Classifier: Natural Language :: English
43
43
  Requires-Python: >=3.9
44
44
  Description-Content-Type: text/markdown
45
- License-File: LICENSE
46
45
  Requires-Dist: model2vec>=0.3.4
47
46
  Requires-Dist: vicinity[usearch]>=0.4.0
48
47
  Requires-Dist: frozendict
@@ -66,7 +65,7 @@ Requires-Dist: ruff; extra == "dev"
66
65
 
67
66
  <div align="center">
68
67
 
69
- # Fast Semantic Text Deduplication
68
+ # Fast Semantic Text Deduplication & Filtering
70
69
 
71
70
 
72
71
  <h2>
@@ -93,9 +92,9 @@ Requires-Dist: ruff; extra == "dev"
93
92
  </div>
94
93
 
95
94
 
96
- SemHash is a lightweight and flexible tool for deduplicating datasets using semantic similarity. It combines fast embedding generation from [Model2Vec](https://github.com/MinishLab/model2vec) with efficient ANN-based similarity search through [Vicinity](https://github.com/MinishLab/vicinity).
95
+ SemHash is a lightweight and flexible tool for deduplicating datasets, filtering outliers, and finding representative samples using semantic similarity. It combines fast embedding generation from [Model2Vec](https://github.com/MinishLab/model2vec) with efficient ANN-based similarity search through [Vicinity](https://github.com/MinishLab/vicinity).
97
96
 
98
- SemHash supports both single-dataset deduplication (e.g., cleaning up a train set) and multi-dataset deduplication (e.g., ensuring no overlap between a test set and a train set). It works with simple datasets, such as text lists, and more complex ones, like multi-column QA datasets. Additionally, it includes functions to inspect deduplication results, making it easier to understand and refine your data cleaning process.
97
+ SemHash supports both single-dataset deduplication & filtering (e.g., cleaning up a train set by removing duplicates and outliers) and multi-dataset deduplication & filtering (e.g., ensuring no overlap between a test set and a train set). It works with simple datasets, such as text lists, and more complex ones, like multi-column QA datasets. Additionally, it includes functions to inspect deduplication results, making it easier to understand and refine your data cleaning process.
99
98
 
100
99
  ## Quickstart
101
100
 
@@ -104,7 +103,7 @@ Install the package with:
104
103
  pip install semhash
105
104
  ```
106
105
 
107
- Deduplicate a single dataset with the following code (note: the examples assume you have `datasets` installed, which you can install with `pip install datasets`):
106
+ Deduplicate a single dataset, filter outliers, and find representative samples with the following code (note: the examples assume you have `datasets` installed, which you can install with `pip install datasets`):
108
107
 
109
108
  ```python
110
109
  from datasets import load_dataset
@@ -117,10 +116,16 @@ texts = load_dataset("ag_news", split="train")["text"]
117
116
  semhash = SemHash.from_records(records=texts)
118
117
 
119
118
  # Deduplicate the texts
120
- deduplicated_texts = semhash.self_deduplicate().deduplicated
119
+ deduplicated_texts = semhash.self_deduplicate().selected
120
+
121
+ # Filter outliers
122
+ filtered_texts = semhash.self_filter_outliers().selected
123
+
124
+ # Find representative texts
125
+ representative_texts = semhash.self_find_representative().selected
121
126
  ```
122
127
 
123
- Or, deduplicate across two datasets with the following code (e.g., eliminating train/test leakage):
128
+ Or, deduplicate across two datasets, filter outliers, and find representative samples with the following code (e.g., eliminating train/test leakage):
124
129
 
125
130
  ```python
126
131
  from datasets import load_dataset
@@ -134,10 +139,21 @@ test_texts = load_dataset("ag_news", split="test")["text"]
134
139
  semhash = SemHash.from_records(records=train_texts)
135
140
 
136
141
  # Deduplicate the test data against the training data, optionally with a specific threshold
137
- deduplicated_test_texts = semhash.deduplicate(records=test_texts, threshold=0.9).deduplicated
142
+ deduplicated_test_texts = semhash.deduplicate(records=test_texts, threshold=0.9).selected
143
+
144
+ # Filter outliers from the test data against the training data,
145
+ # optionally with a specific percentage
146
+ filtered_test_texts = semhash.filter_outliers(records=test_texts, outlier_percentage=0.1).selected
147
+
148
+ # Find representative texts in the test data against the training data,
149
+ # optionally with a specific selection size
150
+ representative_test_texts = semhash.find_representative(
151
+ records=test_texts, selection_size=10).selected
152
+
153
+
138
154
  ```
139
155
 
140
- Or, deduplicate multi-column datasets with the following code (e.g., deduplicating a QA dataset):
156
+ Or, deduplicate multi-column dataset, filter outliers, and find representative samples with the following code (e.g., deduplicating a QA dataset):
141
157
 
142
158
  ```python
143
159
  from datasets import load_dataset
@@ -153,28 +169,37 @@ records = [dict(row) for row in dataset]
153
169
  semhash = SemHash.from_records(records=records, columns=["question", "context"])
154
170
 
155
171
  # Deduplicate the records
156
- deduplicated_records = semhash.self_deduplicate().deduplicated
172
+ deduplicated_records = semhash.self_deduplicate().selected
173
+
174
+ # Filter outliers from the records
175
+ filtered_texts = semhash.self_filter_outliers().selected
176
+
177
+ # Find representative texts in the records
178
+ representative_texts = semhash.self_find_representative().selected
157
179
  ```
158
180
 
159
181
  The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#L30). This object stores the deduplicated corpus, a set of duplicate object (along with the objects that caused duplication), and several useful functions to further inspect the deduplication result. Examples of how these functions can be used can be found in the [usage](#usage) section.
160
182
 
183
+ The `filter_outliers`, `self_filter_outliers`, `find_representative`, and `self_find_representative` functions return a [FilterResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#106). This object stores the found outliers/representative samples.
184
+
185
+ For both the `DeduplicationResult` and `FilterResult` objects, you can easily view the filtered records with the `selected` attribute (e.g. to view outliers: `outliers = semhash.self_filter_outliers().filtered`)
161
186
  ## Main Features
162
187
 
163
188
  - **Fast**: SemHash uses [model2vec](https://github.com/MinishLab/model2vec) to embed texts and [vicinity](https://github.com/MinishLab/vicinity) to perform similarity search, making it extremely fast.
164
- - **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
165
- - **Flexible**: SemHash can be used to deduplicate a single dataset or across two datasets, and can also be used to deduplicate multi-column datasets (such as QA datasets).
189
+ - **Scalable**: SemHash can deduplicate & filter large datasets with millions of records thanks to the ANN backends in Vicinity.
190
+ - **Flexible**: SemHash can be used to deduplicate & filter a single dataset or across two datasets, and can also be used to deduplicate & filter multi-column datasets (such as QA datasets).
166
191
  - **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
167
192
  - **Explainable**: Easily inspect the duplicates and what caused them with the `DeduplicationResult` object. You can also view the lowest similarity duplicates to find the right threshold for deduplication for your dataset.
168
193
 
169
194
  ## Usage
170
195
 
171
- The following examples show the various ways you can use SemHash to deduplicate datasets. These examples assume you have the `datasets` library installed, which you can install with `pip install datasets`.
196
+ The following examples show the various ways you can use SemHash to deduplicate datasets, filter outliers, and find representative samples. These examples assume you have the `datasets` library installed, which you can install with `pip install datasets`.
172
197
 
173
198
  <details>
174
- <summary> Deduplicate a single dataset </summary>
199
+ <summary> Deduplicate, filter outliers, and find representative samples on a single dataset </summary>
175
200
  <br>
176
201
 
177
- The following code snippet shows how to deduplicate a single dataset using SemHash (in this example, the train split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
202
+ The following code snippet shows how to deduplicate a single dataset, filter outliers, and find representative samples using SemHash (in this example, the train split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
178
203
 
179
204
  ```python
180
205
  from datasets import load_dataset
@@ -187,15 +212,21 @@ texts = load_dataset("ag_news", split="train")["text"]
187
212
  semhash = SemHash.from_records(records=texts)
188
213
 
189
214
  # Deduplicate the texts
190
- deduplicated_texts = semhash.self_deduplicate()
215
+ deduplicated_texts = semhash.self_deduplicate().selected
216
+
217
+ # Filter outliers
218
+ filtered_texts = semhash.self_filter_outliers().selected
219
+
220
+ # Find representative texts
221
+ representative_texts = semhash.self_find_representative().selected
191
222
  ```
192
223
  </details>
193
224
 
194
225
  <details>
195
- <summary> Deduplicate across two datasets </summary>
226
+ <summary> Deduplicate, filter outliers, and find representative samples across two datasets </summary>
196
227
  <br>
197
228
 
198
- The following code snippet shows how to deduplicate across two datasets using SemHash (in this example, the train/test split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
229
+ The following code snippet shows how to deduplicate across two datasets, filter outliers, and find representative samples using SemHash (in this example, the train/test split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
199
230
 
200
231
  ```python
201
232
  from datasets import load_dataset
@@ -212,16 +243,22 @@ test_texts = load_dataset("ag_news", split="test")["text"]
212
243
  semhash = SemHash.from_records(records=train_texts)
213
244
 
214
245
  # Deduplicate the test data against the training data
215
- deduplicated_test_texts = semhash.deduplicate(records=test_texts)
246
+ deduplicated_test_texts = semhash.deduplicate(records=test_texts).selected
247
+
248
+ # Filter outliers from the test data
249
+ filtered_test_texts = semhash.filter_outliers(records=test_texts).selected
250
+
251
+ # Find representative texts in the test data
252
+ representative_test_texts = semhash.find_representative(records=test_texts).selected
216
253
  ```
217
254
 
218
255
  </details>
219
256
 
220
257
  <details>
221
- <summary> Deduplicate multi-column datasets </summary>
258
+ <summary> Deduplicate, filter outliers, and find representative samples on multi-column datasets </summary>
222
259
  <br>
223
260
 
224
- The following code snippet shows how to deduplicate multi-column datasets using SemHash (in this example, the train split of the QA dataset [SQuAD 2.0](https://huggingface.co/datasets/rajpurkar/squad_v2), which consists of questions, contexts, and answers):
261
+ The following code snippet shows how to deduplicate multi-column datasets, filter outliers, and find representative samples using SemHash (in this example, the train split of the QA dataset [SQuAD 2.0](https://huggingface.co/datasets/rajpurkar/squad_v2), which consists of questions, contexts, and answers):
225
262
 
226
263
  ```python
227
264
  from datasets import load_dataset
@@ -237,7 +274,13 @@ records = [dict(row) for row in dataset]
237
274
  semhash = SemHash.from_records(records=records, columns=["question", "context"])
238
275
 
239
276
  # Deduplicate the records
240
- deduplicated_records = semhash.self_deduplicate().deduplicated
277
+ deduplicated_records = semhash.self_deduplicate().selected
278
+
279
+ # Filter outliers from the records
280
+ filtered_records = semhash.self_filter_outliers().selected
281
+
282
+ # Find representative samples in the records
283
+ representative_records = semhash.self_find_representative().selected
241
284
  ```
242
285
 
243
286
  </details>
@@ -262,9 +305,9 @@ semhash = SemHash.from_records(records=texts)
262
305
  deduplication_result = semhash.self_deduplicate()
263
306
 
264
307
  # Check the deduplicated texts
265
- deduplication_result.deduplicated
308
+ deduplication_result.selected
266
309
  # Check the duplicates
267
- deduplication_result.duplicates
310
+ deduplication_result.filtered
268
311
  # See what percentage of the texts were duplicates
269
312
  deduplication_result.duplicate_ratio
270
313
  # See what percentage of the texts were exact duplicates
@@ -346,7 +389,7 @@ dataframe = dataframe.to_dict(orient="records")
346
389
  semhash = SemHash.from_records(records=dataframe, columns=["text"])
347
390
 
348
391
  # Deduplicate the texts
349
- deduplicated_records = semhash.self_deduplicate().deduplicated
392
+ deduplicated_records = semhash.self_deduplicate().selected
350
393
 
351
394
  # Convert the deduplicated records back to a pandas dataframe
352
395
  deduplicated_dataframe = pd.DataFrame(deduplicated_records)
@@ -436,7 +479,7 @@ If you use SemHash in your research, please cite the following:
436
479
  ```bibtex
437
480
  @software{minishlab2025semhash,
438
481
  author = {Thomas van Dongen and Stephan Tulkens},
439
- title = {SemHash: Fast Semantic Text Deduplication},
482
+ title = {SemHash: Fast Semantic Text Deduplication & Filtering},
440
483
  year = {2025},
441
484
  url = {https://github.com/MinishLab/semhash}
442
485
  }
@@ -9,7 +9,7 @@
9
9
 
10
10
  <div align="center">
11
11
 
12
- # Fast Semantic Text Deduplication
12
+ # Fast Semantic Text Deduplication & Filtering
13
13
 
14
14
 
15
15
  <h2>
@@ -36,9 +36,9 @@
36
36
  </div>
37
37
 
38
38
 
39
- SemHash is a lightweight and flexible tool for deduplicating datasets using semantic similarity. It combines fast embedding generation from [Model2Vec](https://github.com/MinishLab/model2vec) with efficient ANN-based similarity search through [Vicinity](https://github.com/MinishLab/vicinity).
39
+ SemHash is a lightweight and flexible tool for deduplicating datasets, filtering outliers, and finding representative samples using semantic similarity. It combines fast embedding generation from [Model2Vec](https://github.com/MinishLab/model2vec) with efficient ANN-based similarity search through [Vicinity](https://github.com/MinishLab/vicinity).
40
40
 
41
- SemHash supports both single-dataset deduplication (e.g., cleaning up a train set) and multi-dataset deduplication (e.g., ensuring no overlap between a test set and a train set). It works with simple datasets, such as text lists, and more complex ones, like multi-column QA datasets. Additionally, it includes functions to inspect deduplication results, making it easier to understand and refine your data cleaning process.
41
+ SemHash supports both single-dataset deduplication & filtering (e.g., cleaning up a train set by removing duplicates and outliers) and multi-dataset deduplication & filtering (e.g., ensuring no overlap between a test set and a train set). It works with simple datasets, such as text lists, and more complex ones, like multi-column QA datasets. Additionally, it includes functions to inspect deduplication results, making it easier to understand and refine your data cleaning process.
42
42
 
43
43
  ## Quickstart
44
44
 
@@ -47,7 +47,7 @@ Install the package with:
47
47
  pip install semhash
48
48
  ```
49
49
 
50
- Deduplicate a single dataset with the following code (note: the examples assume you have `datasets` installed, which you can install with `pip install datasets`):
50
+ Deduplicate a single dataset, filter outliers, and find representative samples with the following code (note: the examples assume you have `datasets` installed, which you can install with `pip install datasets`):
51
51
 
52
52
  ```python
53
53
  from datasets import load_dataset
@@ -60,10 +60,16 @@ texts = load_dataset("ag_news", split="train")["text"]
60
60
  semhash = SemHash.from_records(records=texts)
61
61
 
62
62
  # Deduplicate the texts
63
- deduplicated_texts = semhash.self_deduplicate().deduplicated
63
+ deduplicated_texts = semhash.self_deduplicate().selected
64
+
65
+ # Filter outliers
66
+ filtered_texts = semhash.self_filter_outliers().selected
67
+
68
+ # Find representative texts
69
+ representative_texts = semhash.self_find_representative().selected
64
70
  ```
65
71
 
66
- Or, deduplicate across two datasets with the following code (e.g., eliminating train/test leakage):
72
+ Or, deduplicate across two datasets, filter outliers, and find representative samples with the following code (e.g., eliminating train/test leakage):
67
73
 
68
74
  ```python
69
75
  from datasets import load_dataset
@@ -77,10 +83,21 @@ test_texts = load_dataset("ag_news", split="test")["text"]
77
83
  semhash = SemHash.from_records(records=train_texts)
78
84
 
79
85
  # Deduplicate the test data against the training data, optionally with a specific threshold
80
- deduplicated_test_texts = semhash.deduplicate(records=test_texts, threshold=0.9).deduplicated
86
+ deduplicated_test_texts = semhash.deduplicate(records=test_texts, threshold=0.9).selected
87
+
88
+ # Filter outliers from the test data against the training data,
89
+ # optionally with a specific percentage
90
+ filtered_test_texts = semhash.filter_outliers(records=test_texts, outlier_percentage=0.1).selected
91
+
92
+ # Find representative texts in the test data against the training data,
93
+ # optionally with a specific selection size
94
+ representative_test_texts = semhash.find_representative(
95
+ records=test_texts, selection_size=10).selected
96
+
97
+
81
98
  ```
82
99
 
83
- Or, deduplicate multi-column datasets with the following code (e.g., deduplicating a QA dataset):
100
+ Or, deduplicate multi-column dataset, filter outliers, and find representative samples with the following code (e.g., deduplicating a QA dataset):
84
101
 
85
102
  ```python
86
103
  from datasets import load_dataset
@@ -96,28 +113,37 @@ records = [dict(row) for row in dataset]
96
113
  semhash = SemHash.from_records(records=records, columns=["question", "context"])
97
114
 
98
115
  # Deduplicate the records
99
- deduplicated_records = semhash.self_deduplicate().deduplicated
116
+ deduplicated_records = semhash.self_deduplicate().selected
117
+
118
+ # Filter outliers from the records
119
+ filtered_texts = semhash.self_filter_outliers().selected
120
+
121
+ # Find representative texts in the records
122
+ representative_texts = semhash.self_find_representative().selected
100
123
  ```
101
124
 
102
125
  The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#L30). This object stores the deduplicated corpus, a set of duplicate object (along with the objects that caused duplication), and several useful functions to further inspect the deduplication result. Examples of how these functions can be used can be found in the [usage](#usage) section.
103
126
 
127
+ The `filter_outliers`, `self_filter_outliers`, `find_representative`, and `self_find_representative` functions return a [FilterResult](https://github.com/MinishLab/semhash/blob/main/semhash/datamodels.py#106). This object stores the found outliers/representative samples.
128
+
129
+ For both the `DeduplicationResult` and `FilterResult` objects, you can easily view the filtered records with the `selected` attribute (e.g. to view outliers: `outliers = semhash.self_filter_outliers().filtered`)
104
130
  ## Main Features
105
131
 
106
132
  - **Fast**: SemHash uses [model2vec](https://github.com/MinishLab/model2vec) to embed texts and [vicinity](https://github.com/MinishLab/vicinity) to perform similarity search, making it extremely fast.
107
- - **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
108
- - **Flexible**: SemHash can be used to deduplicate a single dataset or across two datasets, and can also be used to deduplicate multi-column datasets (such as QA datasets).
133
+ - **Scalable**: SemHash can deduplicate & filter large datasets with millions of records thanks to the ANN backends in Vicinity.
134
+ - **Flexible**: SemHash can be used to deduplicate & filter a single dataset or across two datasets, and can also be used to deduplicate & filter multi-column datasets (such as QA datasets).
109
135
  - **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
110
136
  - **Explainable**: Easily inspect the duplicates and what caused them with the `DeduplicationResult` object. You can also view the lowest similarity duplicates to find the right threshold for deduplication for your dataset.
111
137
 
112
138
  ## Usage
113
139
 
114
- The following examples show the various ways you can use SemHash to deduplicate datasets. These examples assume you have the `datasets` library installed, which you can install with `pip install datasets`.
140
+ The following examples show the various ways you can use SemHash to deduplicate datasets, filter outliers, and find representative samples. These examples assume you have the `datasets` library installed, which you can install with `pip install datasets`.
115
141
 
116
142
  <details>
117
- <summary> Deduplicate a single dataset </summary>
143
+ <summary> Deduplicate, filter outliers, and find representative samples on a single dataset </summary>
118
144
  <br>
119
145
 
120
- The following code snippet shows how to deduplicate a single dataset using SemHash (in this example, the train split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
146
+ The following code snippet shows how to deduplicate a single dataset, filter outliers, and find representative samples using SemHash (in this example, the train split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
121
147
 
122
148
  ```python
123
149
  from datasets import load_dataset
@@ -130,15 +156,21 @@ texts = load_dataset("ag_news", split="train")["text"]
130
156
  semhash = SemHash.from_records(records=texts)
131
157
 
132
158
  # Deduplicate the texts
133
- deduplicated_texts = semhash.self_deduplicate()
159
+ deduplicated_texts = semhash.self_deduplicate().selected
160
+
161
+ # Filter outliers
162
+ filtered_texts = semhash.self_filter_outliers().selected
163
+
164
+ # Find representative texts
165
+ representative_texts = semhash.self_find_representative().selected
134
166
  ```
135
167
  </details>
136
168
 
137
169
  <details>
138
- <summary> Deduplicate across two datasets </summary>
170
+ <summary> Deduplicate, filter outliers, and find representative samples across two datasets </summary>
139
171
  <br>
140
172
 
141
- The following code snippet shows how to deduplicate across two datasets using SemHash (in this example, the train/test split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
173
+ The following code snippet shows how to deduplicate across two datasets, filter outliers, and find representative samples using SemHash (in this example, the train/test split of the [AG News dataset](https://huggingface.co/datasets/fancyzhx/ag_news)):
142
174
 
143
175
  ```python
144
176
  from datasets import load_dataset
@@ -155,16 +187,22 @@ test_texts = load_dataset("ag_news", split="test")["text"]
155
187
  semhash = SemHash.from_records(records=train_texts)
156
188
 
157
189
  # Deduplicate the test data against the training data
158
- deduplicated_test_texts = semhash.deduplicate(records=test_texts)
190
+ deduplicated_test_texts = semhash.deduplicate(records=test_texts).selected
191
+
192
+ # Filter outliers from the test data
193
+ filtered_test_texts = semhash.filter_outliers(records=test_texts).selected
194
+
195
+ # Find representative texts in the test data
196
+ representative_test_texts = semhash.find_representative(records=test_texts).selected
159
197
  ```
160
198
 
161
199
  </details>
162
200
 
163
201
  <details>
164
- <summary> Deduplicate multi-column datasets </summary>
202
+ <summary> Deduplicate, filter outliers, and find representative samples on multi-column datasets </summary>
165
203
  <br>
166
204
 
167
- The following code snippet shows how to deduplicate multi-column datasets using SemHash (in this example, the train split of the QA dataset [SQuAD 2.0](https://huggingface.co/datasets/rajpurkar/squad_v2), which consists of questions, contexts, and answers):
205
+ The following code snippet shows how to deduplicate multi-column datasets, filter outliers, and find representative samples using SemHash (in this example, the train split of the QA dataset [SQuAD 2.0](https://huggingface.co/datasets/rajpurkar/squad_v2), which consists of questions, contexts, and answers):
168
206
 
169
207
  ```python
170
208
  from datasets import load_dataset
@@ -180,7 +218,13 @@ records = [dict(row) for row in dataset]
180
218
  semhash = SemHash.from_records(records=records, columns=["question", "context"])
181
219
 
182
220
  # Deduplicate the records
183
- deduplicated_records = semhash.self_deduplicate().deduplicated
221
+ deduplicated_records = semhash.self_deduplicate().selected
222
+
223
+ # Filter outliers from the records
224
+ filtered_records = semhash.self_filter_outliers().selected
225
+
226
+ # Find representative samples in the records
227
+ representative_records = semhash.self_find_representative().selected
184
228
  ```
185
229
 
186
230
  </details>
@@ -205,9 +249,9 @@ semhash = SemHash.from_records(records=texts)
205
249
  deduplication_result = semhash.self_deduplicate()
206
250
 
207
251
  # Check the deduplicated texts
208
- deduplication_result.deduplicated
252
+ deduplication_result.selected
209
253
  # Check the duplicates
210
- deduplication_result.duplicates
254
+ deduplication_result.filtered
211
255
  # See what percentage of the texts were duplicates
212
256
  deduplication_result.duplicate_ratio
213
257
  # See what percentage of the texts were exact duplicates
@@ -289,7 +333,7 @@ dataframe = dataframe.to_dict(orient="records")
289
333
  semhash = SemHash.from_records(records=dataframe, columns=["text"])
290
334
 
291
335
  # Deduplicate the texts
292
- deduplicated_records = semhash.self_deduplicate().deduplicated
336
+ deduplicated_records = semhash.self_deduplicate().selected
293
337
 
294
338
  # Convert the deduplicated records back to a pandas dataframe
295
339
  deduplicated_dataframe = pd.DataFrame(deduplicated_records)
@@ -379,7 +423,7 @@ If you use SemHash in your research, please cite the following:
379
423
  ```bibtex
380
424
  @software{minishlab2025semhash,
381
425
  author = {Thomas van Dongen and Stephan Tulkens},
382
- title = {SemHash: Fast Semantic Text Deduplication},
426
+ title = {SemHash: Fast Semantic Text Deduplication & Filtering},
383
427
  year = {2025},
384
428
  url = {https://github.com/MinishLab/semhash}
385
429
  }
@@ -55,7 +55,7 @@ def main() -> None: # noqa: C901
55
55
 
56
56
  train_only_dedup_time = train_only_end - train_only_start
57
57
  original_train_size = len(train_records)
58
- dedup_train_size = len(deduplicated_train.deduplicated)
58
+ dedup_train_size = len(deduplicated_train.selected)
59
59
 
60
60
  percent_removed_train = deduplicated_train.duplicate_ratio * 100
61
61
  train_dedup_results.append(
@@ -88,7 +88,7 @@ def main() -> None: # noqa: C901
88
88
  train_test_end = perf_counter()
89
89
  train_test_dedup_time = train_test_end - train_test_start
90
90
  original_test_size = len(test_records)
91
- deduped_test_size = len(deduplicated_test.deduplicated)
91
+ deduped_test_size = len(deduplicated_test.selected)
92
92
  percent_removed_test = deduplicated_test.duplicate_ratio * 100
93
93
 
94
94
  train_test_dedup_results.append(
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "semhash"
3
- description = "Fast Semantic Text Deduplication"
3
+ description = "Fast Semantic Text Deduplication & Filtering"
4
4
  authors = [{name = "Thomas van Dongen", email = "thomas123@live.nl"}, { name = "Stéphan Tulkens", email = "stephantul@gmail.com"}]
5
5
  readme = { file = "README.md", content-type = "text/markdown" }
6
6
  dynamic = ["version"]
@@ -92,6 +92,7 @@ ignore_missing_imports = true
92
92
 
93
93
  [tool.setuptools]
94
94
  packages = ["semhash"]
95
+ license-files = []
95
96
 
96
97
  [tool.setuptools_scm]
97
98
  # can be empty if no extra settings are needed, presence enables setuptools_scm
@@ -0,0 +1,135 @@
1
+ import warnings
2
+ from dataclasses import dataclass, field
3
+ from typing import Generic, TypeVar
4
+
5
+ Record = TypeVar("Record", str, dict[str, str])
6
+
7
+
8
+ @dataclass
9
+ class DuplicateRecord(Generic[Record]):
10
+ """
11
+ A single record with its duplicates.
12
+
13
+ Attributes
14
+ ----------
15
+ record: The original record being deduplicated.
16
+ exact: Whether the record was identified as an exact match.
17
+ duplicates: List of tuples consisting of duplicate records and their associated scores.
18
+
19
+ """
20
+
21
+ record: Record
22
+ exact: bool
23
+ duplicates: list[tuple[Record, float]] = field(default_factory=list)
24
+
25
+ def _rethreshold(self, threshold: float) -> None:
26
+ """Rethreshold the duplicates."""
27
+ self.duplicates = [(d, score) for d, score in self.duplicates if score >= threshold]
28
+
29
+
30
+ @dataclass
31
+ class DeduplicationResult(Generic[Record]):
32
+ """
33
+ Deduplication result.
34
+
35
+ Attributes
36
+ ----------
37
+ selected: List of deduplicated records after removing duplicates.
38
+ filtered: List of DuplicateRecord objects containing details about duplicates of an original record.
39
+ threshold: The similarity threshold used for deduplication.
40
+ deduplicated: Deprecated, use selected instead.
41
+ duplicates: Deprecated, use filtered instead.
42
+
43
+ """
44
+
45
+ selected: list[Record] = field(default_factory=list)
46
+ filtered: list[DuplicateRecord] = field(default_factory=list)
47
+ threshold: float = field(default=0.9)
48
+ deduplicated: list[Record] = field(default_factory=list) # Deprecated
49
+ duplicates: list[DuplicateRecord] = field(default_factory=list) # Deprecated
50
+
51
+ def __post_init__(self) -> None:
52
+ """Initialize deprecated fields and warn about deprecation."""
53
+ if self.deduplicated or self.duplicates:
54
+ warnings.warn(
55
+ "'deduplicated' and 'duplicates' fields are deprecated and will be removed in a future release. Use 'selected' and 'filtered' instead.",
56
+ DeprecationWarning,
57
+ stacklevel=2,
58
+ )
59
+
60
+ if not self.selected and self.deduplicated:
61
+ self.selected = self.deduplicated
62
+ if not self.filtered and self.duplicates:
63
+ self.filtered = self.duplicates
64
+ if not self.deduplicated:
65
+ self.deduplicated = self.selected
66
+ if not self.duplicates:
67
+ self.duplicates = self.filtered
68
+
69
+ @property
70
+ def duplicate_ratio(self) -> float:
71
+ """Return the percentage of records dropped."""
72
+ if denom := len(self.selected) + len(self.filtered):
73
+ return 1.0 - len(self.selected) / denom
74
+ return 0.0
75
+
76
+ @property
77
+ def exact_duplicate_ratio(self) -> float:
78
+ """Return the percentage of records dropped due to an exact match."""
79
+ if denom := len(self.selected) + len(self.filtered):
80
+ return len([dup for dup in self.filtered if dup.exact]) / denom
81
+ return 0.0
82
+
83
+ def get_least_similar_from_duplicates(self, n: int = 1) -> list[tuple[Record, Record, float]]:
84
+ """
85
+ Return the N least similar duplicate pairs.
86
+
87
+ :param n: The number of least similar pairs to return.
88
+ :return: A list of tuples consisting of (original_record, duplicate_record, score).
89
+ """
90
+ all_pairs = [(dup.record, d, score) for dup in self.filtered for d, score in dup.duplicates]
91
+ sorted_pairs = sorted(all_pairs, key=lambda x: x[2]) # Sort by score
92
+ return sorted_pairs[:n]
93
+
94
+ def rethreshold(self, threshold: float) -> None:
95
+ """Rethreshold the duplicates."""
96
+ if self.threshold > threshold:
97
+ raise ValueError("Threshold is smaller than the given value.")
98
+ for dup in self.filtered:
99
+ dup._rethreshold(threshold)
100
+ if not dup.duplicates:
101
+ self.filtered.remove(dup)
102
+ self.selected.append(dup.record)
103
+ self.threshold = threshold
104
+
105
+
106
+ @dataclass
107
+ class FilterResult(Generic[Record]):
108
+ """
109
+ Result of filtering operations.
110
+
111
+ Attributes
112
+ ----------
113
+ selected: List of records that passed the filter criteria.
114
+ filtered: List of records that were filtered out.
115
+ scores_selected: List of scores for the selected records.
116
+ scores_filtered: List of scores for the filtered records.
117
+
118
+ """
119
+
120
+ selected: list[Record]
121
+ filtered: list[Record]
122
+ scores_selected: list[float] = field(default_factory=list)
123
+ scores_filtered: list[float] = field(default_factory=list)
124
+
125
+ @property
126
+ def filter_ratio(self) -> float:
127
+ """Return the percentage of records filtered out."""
128
+ if denom := len(self.selected) + len(self.filtered):
129
+ return len(self.filtered) / denom
130
+ return 0.0
131
+
132
+ @property
133
+ def selected_ratio(self) -> float:
134
+ """Return the percentage of records selected."""
135
+ return 1 - self.filter_ratio
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import numpy as np
4
4
  from vicinity import Backend
5
5
  from vicinity.backends import AbstractBackend, get_backend_class
6
+ from vicinity.datatypes import SingleQueryResult
6
7
 
7
8
  DocScore = tuple[dict[str, str], float]
8
9
  DocScores = list[DocScore]
@@ -61,3 +62,22 @@ class Index:
61
62
  out.append(intermediate)
62
63
 
63
64
  return out
65
+
66
+ def query_top_k(self, vectors: np.ndarray, k: int, vectors_are_in_index: bool) -> list[SingleQueryResult]:
67
+ """
68
+ Query the index with a top-k.
69
+
70
+ :param vectors: The vectors to query.
71
+ :param k: Maximum number of top-k records to keep.
72
+ :param vectors_are_in_index: Whether the vectors are in the index. If this is set to True, we retrieve k + 1
73
+ records, and do not consider the first one, as it is the query vector itself.
74
+ :return: The query results. Each result is a tuple where the first element is the list of neighbor records,
75
+ and the second element is a NumPy array of cosine similarity scores.
76
+ """
77
+ results = []
78
+ offset = int(vectors_are_in_index)
79
+ for x, y in self.backend.query(vectors=vectors, k=k + offset):
80
+ # Convert returned distances to cosine similarities.
81
+ similarities = 1 - y[offset:]
82
+ results.append((x[offset:], similarities))
83
+ return results