semhash 0.2.0__tar.gz → 0.2.1__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 (35) hide show
  1. {semhash-0.2.0 → semhash-0.2.1}/PKG-INFO +62 -8
  2. {semhash-0.2.0 → semhash-0.2.1}/README.md +61 -7
  3. {semhash-0.2.0 → semhash-0.2.1}/semhash/index.py +0 -4
  4. {semhash-0.2.0 → semhash-0.2.1}/semhash/records.py +5 -0
  5. {semhash-0.2.0 → semhash-0.2.1}/semhash/semhash.py +33 -14
  6. {semhash-0.2.0 → semhash-0.2.1}/semhash/utils.py +1 -1
  7. {semhash-0.2.0 → semhash-0.2.1}/semhash/version.py +1 -1
  8. {semhash-0.2.0 → semhash-0.2.1}/semhash.egg-info/PKG-INFO +62 -8
  9. {semhash-0.2.0 → semhash-0.2.1}/uv.lock +3 -3
  10. {semhash-0.2.0 → semhash-0.2.1}/.github/workflows/ci.yaml +0 -0
  11. {semhash-0.2.0 → semhash-0.2.1}/.gitignore +0 -0
  12. {semhash-0.2.0 → semhash-0.2.1}/.pre-commit-config.yaml +0 -0
  13. {semhash-0.2.0 → semhash-0.2.1}/LICENSE +0 -0
  14. {semhash-0.2.0 → semhash-0.2.1}/Makefile +0 -0
  15. {semhash-0.2.0 → semhash-0.2.1}/assets/images/semhash_logo.png +0 -0
  16. {semhash-0.2.0 → semhash-0.2.1}/benchmarks/__init__.py +0 -0
  17. {semhash-0.2.0 → semhash-0.2.1}/benchmarks/data.py +0 -0
  18. {semhash-0.2.0 → semhash-0.2.1}/benchmarks/results/train_benchmark_results.json +0 -0
  19. {semhash-0.2.0 → semhash-0.2.1}/benchmarks/results/train_test_benchmark_results.json +0 -0
  20. {semhash-0.2.0 → semhash-0.2.1}/benchmarks/run_benchmarks.py +0 -0
  21. {semhash-0.2.0 → semhash-0.2.1}/pyproject.toml +0 -0
  22. {semhash-0.2.0 → semhash-0.2.1}/semhash/__init__.py +0 -0
  23. {semhash-0.2.0 → semhash-0.2.1}/semhash/datamodels.py +0 -0
  24. {semhash-0.2.0 → semhash-0.2.1}/semhash.egg-info/SOURCES.txt +0 -0
  25. {semhash-0.2.0 → semhash-0.2.1}/semhash.egg-info/dependency_links.txt +0 -0
  26. {semhash-0.2.0 → semhash-0.2.1}/semhash.egg-info/requires.txt +0 -0
  27. {semhash-0.2.0 → semhash-0.2.1}/semhash.egg-info/top_level.txt +0 -0
  28. {semhash-0.2.0 → semhash-0.2.1}/setup.cfg +0 -0
  29. {semhash-0.2.0 → semhash-0.2.1}/tests/conftest.py +0 -0
  30. {semhash-0.2.0 → semhash-0.2.1}/tests/data/test_model/README.md +0 -0
  31. {semhash-0.2.0 → semhash-0.2.1}/tests/data/test_model/config.json +0 -0
  32. {semhash-0.2.0 → semhash-0.2.1}/tests/data/test_model/model.safetensors +0 -0
  33. {semhash-0.2.0 → semhash-0.2.1}/tests/data/test_model/tokenizer.json +0 -0
  34. {semhash-0.2.0 → semhash-0.2.1}/tests/test_datamodels.py +0 -0
  35. {semhash-0.2.0 → semhash-0.2.1}/tests/test_semhash.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: semhash
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Fast Semantic Text Deduplication
5
5
  Author-email: Thomas van Dongen <thomas123@live.nl>, Stéphan Tulkens <stephantul@gmail.com>
6
6
  License: MIT License
@@ -69,14 +69,20 @@ Requires-Dist: ruff; extra == "dev"
69
69
  # Fast Semantic Text Deduplication
70
70
 
71
71
 
72
- <h2>
72
+ <h2>
73
73
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/v/semhash?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
74
74
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/pyversions/semhash" alt="Supported Python versions"></a>
75
75
  <a href="https://app.codecov.io/gh/MinishLab/semhash">
76
- <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
76
+ <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
77
77
  </a>
78
- <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
79
- </h2>
78
+ <a href="https://discord.gg/4BDPR5nmtK">
79
+ <img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
80
+ </a>
81
+ <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE">
82
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
83
+ </a>
84
+ </h2>
85
+
80
86
 
81
87
 
82
88
  [Quickstart](#quickstart) •
@@ -127,8 +133,8 @@ test_texts = load_dataset("ag_news", split="test")["text"]
127
133
  # Initialize a SemHash instance with the training data
128
134
  semhash = SemHash.from_records(records=train_texts)
129
135
 
130
- # Deduplicate the test data against the training data
131
- deduplicated_test_texts = semhash.deduplicate(records=test_texts).deduplicated
136
+ # 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
132
138
  ```
133
139
 
134
140
  Or, deduplicate multi-column datasets with the following code (e.g., deduplicating a QA dataset):
@@ -150,7 +156,7 @@ semhash = SemHash.from_records(records=records, columns=["question", "context"])
150
156
  deduplicated_records = semhash.self_deduplicate().deduplicated
151
157
  ```
152
158
 
153
- The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/prepare-release/semhash/datamodels.py#L35). This object stores the deduplicated corpus, a set of duplicate objec (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.
159
+ 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.
154
160
 
155
161
  ## Main Features
156
162
 
@@ -158,6 +164,7 @@ The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult
158
164
  - **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
159
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).
160
166
  - **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
167
+ - **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.
161
168
 
162
169
  ## Usage
163
170
 
@@ -318,12 +325,43 @@ deduplicated_texts = semhash.self_deduplicate()
318
325
 
319
326
  </details>
320
327
 
328
+ <details>
329
+ <summary> Using Pandas DataFrames </summary>
330
+ <br>
331
+
332
+ You can easily use Pandas DataFrames with SemHash. The following code snippet shows how to deduplicate a Pandas DataFrame:
333
+
334
+ ```python
335
+ import pandas as pd
336
+ from datasets import load_dataset
337
+ from semhash import SemHash
338
+
339
+ # Load a dataset as a pandas dataframe
340
+ dataframe = load_dataset("ag_news", split="train").to_pandas()
341
+
342
+ # Convert the dataframe to a list of dictionaries
343
+ dataframe = dataframe.to_dict(orient="records")
344
+
345
+ # Initialize a SemHash instance with the columns to deduplicate
346
+ semhash = SemHash.from_records(records=dataframe, columns=["text"])
347
+
348
+ # Deduplicate the texts
349
+ deduplicated_records = semhash.self_deduplicate().deduplicated
350
+
351
+ # Convert the deduplicated records back to a pandas dataframe
352
+ deduplicated_dataframe = pd.DataFrame(deduplicated_records)
353
+ ```
354
+
355
+ </details>
356
+
321
357
  NOTE: By default, we use the ANN (approximate-nearest neighbors) backend for deduplication. We recommend keeping this since the recall for smaller datasets is ~100%, and it's needed for larger datasets (>1M samples) since these will take too long to deduplicate without ANN. If you want to use the flat/exact-matching backend, you can set `use_ann=False` in the SemHash constructor:
322
358
 
323
359
  ```python
324
360
  semhash = SemHash.from_records(records=texts, use_ann=False)
325
361
  ```
326
362
 
363
+
364
+
327
365
  ## Benchmarks
328
366
 
329
367
  We've benchmarked SemHash on a variety of datasets to measure the deduplication performance and speed. The benchmarks were run with the following setup:
@@ -387,3 +425,19 @@ To run the benchmarks yourself, you can use the following command (assuming you
387
425
  python -m benchmarks.run_benchmarks
388
426
  ```
389
427
  Optionally, the datasets can be updated in the [datasets.py](https://github.com/MinishLab/semhash/blob/main/benchmarks/datasets.py) file.
428
+
429
+ ## License
430
+
431
+ MIT
432
+
433
+ ## Citing
434
+
435
+ If you use SemHash in your research, please cite the following:
436
+ ```bibtex
437
+ @software{minishlab2025semhash,
438
+ author = {Thomas van Dongen and Stephan Tulkens},
439
+ title = {SemHash: Fast Semantic Text Deduplication},
440
+ year = {2025},
441
+ url = {https://github.com/MinishLab/semhash}
442
+ }
443
+ ```
@@ -12,14 +12,20 @@
12
12
  # Fast Semantic Text Deduplication
13
13
 
14
14
 
15
- <h2>
15
+ <h2>
16
16
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/v/semhash?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
17
17
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/pyversions/semhash" alt="Supported Python versions"></a>
18
18
  <a href="https://app.codecov.io/gh/MinishLab/semhash">
19
- <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
19
+ <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
20
20
  </a>
21
- <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
22
- </h2>
21
+ <a href="https://discord.gg/4BDPR5nmtK">
22
+ <img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
23
+ </a>
24
+ <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE">
25
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
26
+ </a>
27
+ </h2>
28
+
23
29
 
24
30
 
25
31
  [Quickstart](#quickstart) •
@@ -70,8 +76,8 @@ test_texts = load_dataset("ag_news", split="test")["text"]
70
76
  # Initialize a SemHash instance with the training data
71
77
  semhash = SemHash.from_records(records=train_texts)
72
78
 
73
- # Deduplicate the test data against the training data
74
- deduplicated_test_texts = semhash.deduplicate(records=test_texts).deduplicated
79
+ # 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
75
81
  ```
76
82
 
77
83
  Or, deduplicate multi-column datasets with the following code (e.g., deduplicating a QA dataset):
@@ -93,7 +99,7 @@ semhash = SemHash.from_records(records=records, columns=["question", "context"])
93
99
  deduplicated_records = semhash.self_deduplicate().deduplicated
94
100
  ```
95
101
 
96
- The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/prepare-release/semhash/datamodels.py#L35). This object stores the deduplicated corpus, a set of duplicate objec (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.
102
+ 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.
97
103
 
98
104
  ## Main Features
99
105
 
@@ -101,6 +107,7 @@ The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult
101
107
  - **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
102
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).
103
109
  - **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
110
+ - **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.
104
111
 
105
112
  ## Usage
106
113
 
@@ -261,12 +268,43 @@ deduplicated_texts = semhash.self_deduplicate()
261
268
 
262
269
  </details>
263
270
 
271
+ <details>
272
+ <summary> Using Pandas DataFrames </summary>
273
+ <br>
274
+
275
+ You can easily use Pandas DataFrames with SemHash. The following code snippet shows how to deduplicate a Pandas DataFrame:
276
+
277
+ ```python
278
+ import pandas as pd
279
+ from datasets import load_dataset
280
+ from semhash import SemHash
281
+
282
+ # Load a dataset as a pandas dataframe
283
+ dataframe = load_dataset("ag_news", split="train").to_pandas()
284
+
285
+ # Convert the dataframe to a list of dictionaries
286
+ dataframe = dataframe.to_dict(orient="records")
287
+
288
+ # Initialize a SemHash instance with the columns to deduplicate
289
+ semhash = SemHash.from_records(records=dataframe, columns=["text"])
290
+
291
+ # Deduplicate the texts
292
+ deduplicated_records = semhash.self_deduplicate().deduplicated
293
+
294
+ # Convert the deduplicated records back to a pandas dataframe
295
+ deduplicated_dataframe = pd.DataFrame(deduplicated_records)
296
+ ```
297
+
298
+ </details>
299
+
264
300
  NOTE: By default, we use the ANN (approximate-nearest neighbors) backend for deduplication. We recommend keeping this since the recall for smaller datasets is ~100%, and it's needed for larger datasets (>1M samples) since these will take too long to deduplicate without ANN. If you want to use the flat/exact-matching backend, you can set `use_ann=False` in the SemHash constructor:
265
301
 
266
302
  ```python
267
303
  semhash = SemHash.from_records(records=texts, use_ann=False)
268
304
  ```
269
305
 
306
+
307
+
270
308
  ## Benchmarks
271
309
 
272
310
  We've benchmarked SemHash on a variety of datasets to measure the deduplication performance and speed. The benchmarks were run with the following setup:
@@ -330,3 +368,19 @@ To run the benchmarks yourself, you can use the following command (assuming you
330
368
  python -m benchmarks.run_benchmarks
331
369
  ```
332
370
  Optionally, the datasets can be updated in the [datasets.py](https://github.com/MinishLab/semhash/blob/main/benchmarks/datasets.py) file.
371
+
372
+ ## License
373
+
374
+ MIT
375
+
376
+ ## Citing
377
+
378
+ If you use SemHash in your research, please cite the following:
379
+ ```bibtex
380
+ @software{minishlab2025semhash,
381
+ author = {Thomas van Dongen and Stephan Tulkens},
382
+ title = {SemHash: Fast Semantic Text Deduplication},
383
+ year = {2025},
384
+ url = {https://github.com/MinishLab/semhash}
385
+ }
386
+ ```
@@ -25,10 +25,6 @@ class Index:
25
25
  self.backend = backend
26
26
  self.vectors = vectors
27
27
 
28
- def items_as_sequence(self) -> list[dict[str, str]]:
29
- """Return all items as a single sequence."""
30
- return [item[0] for item in self.items]
31
-
32
28
  @classmethod
33
29
  def from_vectors_and_items(cls, vectors: np.ndarray, items: list[DictItem], backend_type: Backend) -> Index:
34
30
  """
@@ -39,3 +39,8 @@ def map_deduplication_result_to_strings(result: DeduplicationResult, columns: Se
39
39
  )
40
40
  )
41
41
  return DeduplicationResult(deduplicated=deduplicated_str, duplicates=mapped, threshold=result.threshold)
42
+
43
+
44
+ def add_scores_to_records(records: list[dict[str, str]]) -> list[tuple[dict[str, str], float]]:
45
+ """Add scores to records and return a DeduplicationResult."""
46
+ return [(record, 1.0) for record in records]
@@ -10,7 +10,7 @@ from vicinity import Backend
10
10
 
11
11
  from semhash.datamodels import DeduplicationResult, DuplicateRecord, Record
12
12
  from semhash.index import Index
13
- from semhash.records import map_deduplication_result_to_strings, to_frozendict
13
+ from semhash.records import add_scores_to_records, map_deduplication_result_to_strings, to_frozendict
14
14
  from semhash.utils import Encoder
15
15
 
16
16
 
@@ -57,8 +57,8 @@ class SemHash(Generic[Record]):
57
57
  cls,
58
58
  records: Sequence[dict[str, str]],
59
59
  columns: Sequence[str],
60
- reference_records: list[dict[str, str]] | None = None,
61
- ) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
60
+ reference_records: list[list[dict[str, str]]] | None = None,
61
+ ) -> tuple[list[dict[str, str]], list[tuple[dict[str, str], list[dict[str, str]]]]]:
62
62
  """
63
63
  Remove exact duplicates based on the unpacked string representation of each record.
64
64
 
@@ -74,18 +74,22 @@ class SemHash(Generic[Record]):
74
74
 
75
75
  column_set = set(columns)
76
76
  # Build a seen set from reference_records if provided
77
- seen = {to_frozendict(x, column_set) for x in reference_records} if reference_records else set()
77
+ seen: defaultdict[frozendict[str, str], list[dict[str, str]]] = defaultdict(list)
78
+ if reference_records is not None:
79
+ for record_set in reference_records:
80
+ key = to_frozendict(record_set[0], column_set)
81
+ seen[key] = list(record_set)
78
82
  in_one_set = reference_records is None
79
83
 
80
84
  for record in records:
81
85
  frozen_record = frozendict({k: v for k, v in record.items() if k in column_set})
82
- if frozen_record not in seen:
86
+ if duplicated_records := seen.get(frozen_record):
87
+ duplicates.append((record, duplicated_records))
88
+ else:
83
89
  deduplicated.append(record)
84
90
  # Only add current documents to seen if no reference set is used
85
91
  if in_one_set:
86
- seen.add(frozen_record)
87
- else:
88
- duplicates.append(record)
92
+ seen[frozen_record].append(record)
89
93
 
90
94
  return deduplicated, duplicates
91
95
 
@@ -128,9 +132,10 @@ class SemHash(Generic[Record]):
128
132
  # Remove exact duplicates
129
133
  deduplicated_records, duplicates = cls._remove_exact_duplicates(dict_records, columns)
130
134
 
135
+ col_set = set(columns)
131
136
  duplicate_map = defaultdict(list)
132
- for x in duplicates:
133
- frozen_record = to_frozendict(x, set(columns))
137
+ for x, _ in duplicates:
138
+ frozen_record = to_frozendict(x, col_set)
134
139
  duplicate_map[frozen_record].append(x)
135
140
 
136
141
  items: list[list[dict[str, str]]] = []
@@ -180,9 +185,13 @@ class SemHash(Generic[Record]):
180
185
 
181
186
  # Remove exact duplicates before embedding
182
187
  dict_records, exact_duplicates = self._remove_exact_duplicates(
183
- records=dict_records, columns=self.columns, reference_records=self.index.items_as_sequence()
188
+ records=dict_records, columns=self.columns, reference_records=self.index.items
184
189
  )
185
- duplicate_records = [DuplicateRecord(record=record, duplicates=[], exact=True) for record in exact_duplicates]
190
+ duplicate_records = []
191
+ for record, duplicates in exact_duplicates:
192
+ duplicated_with_score = add_scores_to_records(duplicates)
193
+ duplicate_record = DuplicateRecord(record=record, duplicates=duplicated_with_score, exact=True)
194
+ duplicate_records.append(duplicate_record)
186
195
 
187
196
  # If no records are left after removing exact duplicates, return early
188
197
  if not dict_records:
@@ -240,8 +249,18 @@ class SemHash(Generic[Record]):
240
249
  # So if the an item has more than one record, it is an exact duplicate
241
250
  # Crucially, we should count each instance separately.
242
251
  record, *duplicates = item
243
- for record in duplicates:
244
- duplicate_records.append(DuplicateRecord(record=record, duplicates=[], exact=True))
252
+ # We need to compare all duplicates to all _items_.
253
+ # The first item in a list of duplicate is not duplicated, because otherwise
254
+ # we would remove the whole cluster. But it is a duplicate for the other items.
255
+
256
+ # Iterate from index 1.
257
+ for index, curr_record in enumerate(duplicates, 1):
258
+ # The use of indexing is intentional here, we want to check if the object is the same
259
+ # not if they have the same values. If we did != or is we would probably ignore lots
260
+ # of items.
261
+ items_to_keep = item[:index] + item[index + 1 :]
262
+ items_with_score = add_scores_to_records(items_to_keep)
263
+ duplicate_records.append(DuplicateRecord(record=curr_record, duplicates=items_with_score, exact=True))
245
264
 
246
265
  # If we don't see any similar_items, we know the record is not a duplicate.
247
266
  # in rare cases, the item itself might not be a duplicate of itself.
@@ -18,4 +18,4 @@ class Encoder(Protocol):
18
18
  :param **kwargs: Additional keyword arguments.
19
19
  :return: The embeddings of the sentences.
20
20
  """
21
- ...
21
+ ... # pragma: no cover
@@ -1,2 +1,2 @@
1
- __version_triple__ = (0, 2, 0)
1
+ __version_triple__ = (0, 2, 1)
2
2
  __version__ = ".".join(map(str, __version_triple__))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: semhash
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Fast Semantic Text Deduplication
5
5
  Author-email: Thomas van Dongen <thomas123@live.nl>, Stéphan Tulkens <stephantul@gmail.com>
6
6
  License: MIT License
@@ -69,14 +69,20 @@ Requires-Dist: ruff; extra == "dev"
69
69
  # Fast Semantic Text Deduplication
70
70
 
71
71
 
72
- <h2>
72
+ <h2>
73
73
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/v/semhash?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
74
74
  <a href="https://pypi.org/project/semhash/"><img src="https://img.shields.io/pypi/pyversions/semhash" alt="Supported Python versions"></a>
75
75
  <a href="https://app.codecov.io/gh/MinishLab/semhash">
76
- <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
76
+ <img src="https://codecov.io/gh/MinishLab/semhash/graph/badge.svg?token=YPOD6HD0MG" alt="Codecov">
77
77
  </a>
78
- <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
79
- </h2>
78
+ <a href="https://discord.gg/4BDPR5nmtK">
79
+ <img src="https://img.shields.io/badge/Join-Discord-5865F2?logo=discord&logoColor=white" alt="Join Discord">
80
+ </a>
81
+ <a href="https://github.com/MinishLab/semhash/blob/main/LICENSE">
82
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT">
83
+ </a>
84
+ </h2>
85
+
80
86
 
81
87
 
82
88
  [Quickstart](#quickstart) •
@@ -127,8 +133,8 @@ test_texts = load_dataset("ag_news", split="test")["text"]
127
133
  # Initialize a SemHash instance with the training data
128
134
  semhash = SemHash.from_records(records=train_texts)
129
135
 
130
- # Deduplicate the test data against the training data
131
- deduplicated_test_texts = semhash.deduplicate(records=test_texts).deduplicated
136
+ # 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
132
138
  ```
133
139
 
134
140
  Or, deduplicate multi-column datasets with the following code (e.g., deduplicating a QA dataset):
@@ -150,7 +156,7 @@ semhash = SemHash.from_records(records=records, columns=["question", "context"])
150
156
  deduplicated_records = semhash.self_deduplicate().deduplicated
151
157
  ```
152
158
 
153
- The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult](https://github.com/MinishLab/semhash/blob/prepare-release/semhash/datamodels.py#L35). This object stores the deduplicated corpus, a set of duplicate objec (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.
159
+ 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.
154
160
 
155
161
  ## Main Features
156
162
 
@@ -158,6 +164,7 @@ The `deduplicate` and `self_deduplicate` functions return a [DeduplicationResult
158
164
  - **Scalable**: SemHash can deduplicate large datasets with millions of records thanks to the ANN backends in Vicinity.
159
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).
160
166
  - **Lightweight**: SemHash is a lightweight package with minimal dependencies, making it easy to install and use.
167
+ - **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.
161
168
 
162
169
  ## Usage
163
170
 
@@ -318,12 +325,43 @@ deduplicated_texts = semhash.self_deduplicate()
318
325
 
319
326
  </details>
320
327
 
328
+ <details>
329
+ <summary> Using Pandas DataFrames </summary>
330
+ <br>
331
+
332
+ You can easily use Pandas DataFrames with SemHash. The following code snippet shows how to deduplicate a Pandas DataFrame:
333
+
334
+ ```python
335
+ import pandas as pd
336
+ from datasets import load_dataset
337
+ from semhash import SemHash
338
+
339
+ # Load a dataset as a pandas dataframe
340
+ dataframe = load_dataset("ag_news", split="train").to_pandas()
341
+
342
+ # Convert the dataframe to a list of dictionaries
343
+ dataframe = dataframe.to_dict(orient="records")
344
+
345
+ # Initialize a SemHash instance with the columns to deduplicate
346
+ semhash = SemHash.from_records(records=dataframe, columns=["text"])
347
+
348
+ # Deduplicate the texts
349
+ deduplicated_records = semhash.self_deduplicate().deduplicated
350
+
351
+ # Convert the deduplicated records back to a pandas dataframe
352
+ deduplicated_dataframe = pd.DataFrame(deduplicated_records)
353
+ ```
354
+
355
+ </details>
356
+
321
357
  NOTE: By default, we use the ANN (approximate-nearest neighbors) backend for deduplication. We recommend keeping this since the recall for smaller datasets is ~100%, and it's needed for larger datasets (>1M samples) since these will take too long to deduplicate without ANN. If you want to use the flat/exact-matching backend, you can set `use_ann=False` in the SemHash constructor:
322
358
 
323
359
  ```python
324
360
  semhash = SemHash.from_records(records=texts, use_ann=False)
325
361
  ```
326
362
 
363
+
364
+
327
365
  ## Benchmarks
328
366
 
329
367
  We've benchmarked SemHash on a variety of datasets to measure the deduplication performance and speed. The benchmarks were run with the following setup:
@@ -387,3 +425,19 @@ To run the benchmarks yourself, you can use the following command (assuming you
387
425
  python -m benchmarks.run_benchmarks
388
426
  ```
389
427
  Optionally, the datasets can be updated in the [datasets.py](https://github.com/MinishLab/semhash/blob/main/benchmarks/datasets.py) file.
428
+
429
+ ## License
430
+
431
+ MIT
432
+
433
+ ## Citing
434
+
435
+ If you use SemHash in your research, please cite the following:
436
+ ```bibtex
437
+ @software{minishlab2025semhash,
438
+ author = {Thomas van Dongen and Stephan Tulkens},
439
+ title = {SemHash: Fast Semantic Text Deduplication},
440
+ year = {2025},
441
+ url = {https://github.com/MinishLab/semhash}
442
+ }
443
+ ```
@@ -163,7 +163,7 @@ name = "click"
163
163
  version = "8.1.7"
164
164
  source = { registry = "https://pypi.org/simple" }
165
165
  dependencies = [
166
- { name = "colorama", marker = "platform_system == 'Windows'" },
166
+ { name = "colorama", marker = "sys_platform == 'win32'" },
167
167
  ]
168
168
  sdist = { url = "https://files.pythonhosted.org/packages/96/d3/f04c7bfcf5c1862a2a5b845c6b2b360488cf47af55dfa79c98f6a6bf98b5/click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de", size = 336121 }
169
169
  wheels = [
@@ -1068,7 +1068,7 @@ wheels = [
1068
1068
 
1069
1069
  [[package]]
1070
1070
  name = "semhash"
1071
- version = "0.1.0"
1071
+ version = "0.2.0"
1072
1072
  source = { editable = "." }
1073
1073
  dependencies = [
1074
1074
  { name = "frozendict" },
@@ -1313,7 +1313,7 @@ name = "tqdm"
1313
1313
  version = "4.66.5"
1314
1314
  source = { registry = "https://pypi.org/simple" }
1315
1315
  dependencies = [
1316
- { name = "colorama", marker = "platform_system == 'Windows'" },
1316
+ { name = "colorama", marker = "sys_platform == 'win32'" },
1317
1317
  ]
1318
1318
  sdist = { url = "https://files.pythonhosted.org/packages/58/83/6ba9844a41128c62e810fddddd72473201f3eacde02046066142a2d96cc5/tqdm-4.66.5.tar.gz", hash = "sha256:e1020aef2e5096702d8a025ac7d16b1577279c9d63f8375b63083e9a5f0fcbad", size = 169504 }
1319
1319
  wheels = [
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes