Skip to content

Commit 2a75efe

Browse files
committed
Add document_ids as the grouping key for the multi-topic seam
1 parent 7a854b8 commit 2a75efe

2 files changed

Lines changed: 113 additions & 1 deletion

File tree

‎bertopic/_corpus.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ class Corpus:
4545
# For tracking ID mappings (e.g., during zero-shot)
4646
original_indices: np.ndarray = None
4747

48+
# Which document each row belongs to.
49+
document_ids: np.ndarray = None
50+
4851
# Zero-shot topic labels
4952
_zeroshot_labels: list[str] = field(default_factory=list)
5053

@@ -74,6 +77,10 @@ def __post_init__(self):
7477
if self.original_indices is None:
7578
self.original_indices = np.arange(nr_rows)
7679

80+
# A row is currently a document.
81+
if self.document_ids is None:
82+
self.document_ids = np.asarray(self.original_indices)
83+
7784
if isinstance(self.classes, list):
7885
self.classes = np.array(self.classes)
7986

@@ -212,6 +219,7 @@ def sort_by_timestamps(self) -> "Corpus":
212219
self.original_indices = (
213220
np.array(self.original_indices)[sort_order] if self.original_indices is not None else None
214221
)
222+
self.document_ids = np.array(self.document_ids)[sort_order]
215223

216224
return self
217225

@@ -235,6 +243,7 @@ def get_corpus_by_indices(self, indices: list[int]) -> "Corpus":
235243
topics=selected_topics,
236244
embeddings=selected_embeddings,
237245
original_indices=selected_original_indices,
246+
document_ids=[self.document_ids[index] for index in sorted_indices],
238247
_zeroshot_labels=self._zeroshot_labels,
239248
)
240249

@@ -268,6 +277,7 @@ def get_topic(self, topic_id: int, nr_samples: int | None = None) -> "Corpus":
268277
topics=[topic_id] * len(filtered_docs),
269278
embeddings=filtered_embeddings,
270279
original_indices=filtered_indices,
280+
document_ids=[self.document_ids[index] for index in filtered_indices],
271281
)
272282

273283
def __add__(self, other: "Corpus") -> "Corpus":
@@ -304,6 +314,7 @@ def __add__(self, other: "Corpus") -> "Corpus":
304314

305315
# Combine and reorder original_indices
306316
sorted_indices = [combined_indices[i] for i in sort_order]
317+
combined_document_ids = list(self.document_ids) + list(other.document_ids)
307318

308319
return Corpus(
309320
documents=sorted_documents,
@@ -312,9 +323,17 @@ def __add__(self, other: "Corpus") -> "Corpus":
312323
topics=sorted_topics,
313324
embeddings=sorted_embeddings,
314325
original_indices=sorted_indices,
326+
document_ids=[combined_document_ids[index] for index in sort_order],
315327
_zeroshot_labels=other._zeroshot_labels if other.has_zeroshot_labels else None,
316328
)
317329

330+
@property
331+
def nr_documents(self) -> int:
332+
"""How many distinct documents these rows came from, which equals the row count
333+
until something starts splitting documents into several rows.
334+
"""
335+
return len(np.unique(self.document_ids))
336+
318337
def __len__(self):
319338
return len(self.documents)
320339

@@ -327,7 +346,9 @@ def _validate_length(self, name: str, value) -> None:
327346

328347
def __setattr__(self, name: str, value) -> None:
329348
"""Whenever we update a per-row field after construction, validate its length."""
330-
if name in ("embeddings", "media", "modality", "topics") and getattr(self, "_initialized", False):
349+
if name in ("embeddings", "media", "modality", "topics", "document_ids") and getattr(
350+
self, "_initialized", False
351+
):
331352
self._validate_length(name, value)
332353
super().__setattr__(name, value)
333354

‎tests/test_corpus.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,3 +180,94 @@ def test_mismatched_media_is_rejected():
180180

181181
with pytest.raises(ValueError):
182182
corpus.media = ["only one"]
183+
184+
185+
def test_every_row_is_its_own_document_by_default():
186+
"""1.0 fits on whole documents, so the grouping key is the identity."""
187+
corpus = Corpus(documents=["first", "second", "third"])
188+
189+
assert list(corpus.document_ids) == [0, 1, 2]
190+
assert corpus.nr_documents == len(corpus)
191+
192+
193+
def test_rows_may_share_a_document():
194+
"""What a sentence splitter would produce: four rows from two documents.
195+
196+
Nothing generates this in 1.0. The key exists so that 1.1 can add a splitter without
197+
a second pass over the data layer.
198+
"""
199+
corpus = Corpus(
200+
documents=["first half", "second half", "another one", "and its tail"],
201+
document_ids=np.array([0, 0, 1, 1]),
202+
)
203+
204+
assert corpus.nr_documents == 2
205+
assert len(corpus) == 4
206+
207+
208+
def test_selecting_by_index_carries_document_ids():
209+
"""Slicing a corpus keeps each row pointing at the document it came from."""
210+
corpus = Corpus(documents=["a", "b", "c", "d"], document_ids=np.array([0, 0, 1, 1]))
211+
212+
selected = corpus.get_corpus_by_indices([1, 2])
213+
214+
assert list(selected.document_ids) == [0, 1]
215+
assert selected.nr_documents == 2
216+
217+
218+
def test_selecting_by_topic_carries_document_ids():
219+
corpus = Corpus(
220+
documents=["a", "b", "c"],
221+
document_ids=np.array([0, 0, 1]),
222+
topics=np.array([0, 1, 0]),
223+
)
224+
225+
selected = corpus.get_topic(0)
226+
227+
assert list(selected.document_ids) == [0, 1]
228+
229+
230+
def test_combining_corpora_carries_document_ids():
231+
"""Zero-shot splits a corpus and recombines it, which must not renumber the rows."""
232+
first = Corpus(
233+
documents=["first"], topics=np.array([0]), embeddings=np.zeros((1, 4)), original_indices=[0]
234+
)
235+
second = Corpus(
236+
documents=["second"], topics=np.array([1]), embeddings=np.ones((1, 4)), original_indices=[1]
237+
)
238+
239+
combined = first + second
240+
241+
assert len(combined.document_ids) == 2
242+
243+
244+
def test_mismatched_document_ids_are_rejected():
245+
"""A grouping key that is not one-per-row would silently misalign every later zip."""
246+
corpus = Corpus(documents=["first", "second"])
247+
248+
with pytest.raises(ValueError):
249+
corpus.document_ids = np.array([0])
250+
251+
252+
def test_recombining_a_split_corpus_keeps_documents_distinct():
253+
"""Zero-shot builds two corpora from one input and adds them back together.
254+
255+
Each defaults its own ids, so numbering them from scratch would make row 0 of each
256+
half look like the same document. `original_indices` is what keeps them apart.
257+
"""
258+
first = Corpus(
259+
documents=["a", "c", "e"],
260+
topics=np.array([0, 1, 0]),
261+
embeddings=np.zeros((3, 4)),
262+
original_indices=[0, 2, 4],
263+
)
264+
second = Corpus(
265+
documents=["b", "d", "f"],
266+
topics=np.array([1, 0, 1]),
267+
embeddings=np.ones((3, 4)),
268+
original_indices=[1, 3, 5],
269+
)
270+
271+
combined = first + second
272+
273+
assert combined.nr_documents == 6

0 commit comments

Comments
 (0)