clusterizer 0.7.1__py3-none-any.whl

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 (38) hide show
  1. aladeen_clusterizer/ClusteringPipeline.py +712 -0
  2. aladeen_clusterizer/DailyClusteringPipeline.py +106 -0
  3. aladeen_clusterizer/MultiSentClusteringPipeline.py +49 -0
  4. aladeen_clusterizer/__init__.py +49 -0
  5. aladeen_clusterizer/abstract/ClusterScorer.py +10 -0
  6. aladeen_clusterizer/abstract/ClusteringAlgorithm.py +8 -0
  7. aladeen_clusterizer/abstract/DataPreprocessor.py +7 -0
  8. aladeen_clusterizer/abstract/DimensionalityReducer.py +35 -0
  9. aladeen_clusterizer/abstract/EmbeddingGenerator.py +9 -0
  10. aladeen_clusterizer/abstract/OutlierDetector.py +17 -0
  11. aladeen_clusterizer/abstract/__init__.py +0 -0
  12. aladeen_clusterizer/cluster_scorers/CosineSimililarityClusterScorer.py +31 -0
  13. aladeen_clusterizer/cluster_scorers/SilhouetteClusterScorer.py +16 -0
  14. aladeen_clusterizer/cluster_scorers/__init__.py +0 -0
  15. aladeen_clusterizer/clustering_algorithms/HDBSCANClustering.py +300 -0
  16. aladeen_clusterizer/clustering_algorithms/KMeansClustering.py +15 -0
  17. aladeen_clusterizer/clustering_algorithms/__init__.py +0 -0
  18. aladeen_clusterizer/embedding_generators/DirectModelEmbeddingGenerator.py +17 -0
  19. aladeen_clusterizer/embedding_generators/SentenceTransformerEmbeddingGenerator.py +27 -0
  20. aladeen_clusterizer/embedding_generators/__init__.py +8 -0
  21. aladeen_clusterizer/factory.py +146 -0
  22. aladeen_clusterizer/misc/BenchmarkUtils.py +124 -0
  23. aladeen_clusterizer/misc/EmbeddingTimestamper.py +21 -0
  24. aladeen_clusterizer/misc/TextPreprocessor.py +20 -0
  25. aladeen_clusterizer/misc/__init__.py +0 -0
  26. aladeen_clusterizer/outlier_detectors/DynamicZScoreOutlierDetector.py +53 -0
  27. aladeen_clusterizer/outlier_detectors/IQROutlierDetector.py +60 -0
  28. aladeen_clusterizer/outlier_detectors/LOFOutlierDetector.py +47 -0
  29. aladeen_clusterizer/outlier_detectors/StandardDeviationOutlierDetector.py +27 -0
  30. aladeen_clusterizer/outlier_detectors/ZScoreOutlierDetector.py +37 -0
  31. aladeen_clusterizer/outlier_detectors/__init__.py +0 -0
  32. aladeen_clusterizer/result_visualizers/MultiResultVisualizer.py +65 -0
  33. aladeen_clusterizer/result_visualizers/ResultVisualizer.py +179 -0
  34. aladeen_clusterizer/result_visualizers/__init__.py +0 -0
  35. clusterizer-0.7.1.dist-info/METADATA +144 -0
  36. clusterizer-0.7.1.dist-info/RECORD +38 -0
  37. clusterizer-0.7.1.dist-info/WHEEL +5 -0
  38. clusterizer-0.7.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,712 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Union, List, Dict, Any, Tuple
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+
8
+ from aladeen_clusterizer.abstract.ClusterScorer import ClusterScorer
9
+ from aladeen_clusterizer.abstract.OutlierDetector import OutlierDetector
10
+ from aladeen_clusterizer.abstract.EmbeddingGenerator import EmbeddingGenerator
11
+ from aladeen_clusterizer.abstract.ClusteringAlgorithm import ClusteringAlgorithm
12
+ from aladeen_clusterizer.abstract.DimensionalityReducer import DimensionalityReducer
13
+
14
+ from aladeen_clusterizer.embedding_generators.SentenceTransformerEmbeddingGenerator import (
15
+ SentenceTransformerEmbeddingGenerator,
16
+ )
17
+
18
+ # from aladeen_clusterizer.cluster_scorers.SilhouetteClusterScorer import SilhouetteClusterScorer
19
+ from aladeen_clusterizer.cluster_scorers.CosineSimililarityClusterScorer import (
20
+ CosineSimililarityClusterScorer,
21
+ )
22
+ from aladeen_clusterizer.clustering_algorithms.HDBSCANClustering import (
23
+ HDBSCANClustering,
24
+ )
25
+ # from aladeen_clusterizer.misc.EmbeddingTimestamper import EmbeddingTimestamper
26
+
27
+ # Setup logging
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ @dataclass
32
+ class ClusteringConfig:
33
+ """Configuration class for clustering algorithm parameters."""
34
+
35
+ # HDBSCAN specific parameters
36
+ min_samples: int = 6
37
+ min_cluster_size: int = 2
38
+ metric: str = "euclidean"
39
+ cluster_selection_method: str = "eom"
40
+ cluster_selection_epsilon: float = 0.1
41
+ alpha: float = 0.6
42
+ algorithm: str = "prims_kdtree"
43
+
44
+ # Pipeline parameters
45
+ model_name: str = "BAAI/bge-m3" # Default embedding model
46
+ outlier_threshold: float = 0.7
47
+
48
+ def to_dict(self) -> Dict[str, Any]:
49
+ """Convert the configuration to a dictionary format."""
50
+ return {k: v for k, v in self.__dict__.items()}
51
+
52
+ @classmethod
53
+ def from_dict(cls, config_dict: Dict[str, Any]) -> "ClusteringConfig":
54
+ """Create a configuration object from a dictionary."""
55
+ return cls(**{k: v for k, v in config_dict.items() if k in cls.__annotations__})
56
+
57
+
58
+ class PipelineStage(ABC):
59
+ """Abstract base class for pipeline stages."""
60
+
61
+ @abstractmethod
62
+ def process(self, data: Any, context: Dict[str, Any]) -> Any:
63
+ """Process the data and return the result."""
64
+ pass
65
+
66
+
67
+ class EmbeddingStage(PipelineStage):
68
+ """Stage for generating embeddings from text data."""
69
+
70
+ def __init__(self, embedding_generator: EmbeddingGenerator):
71
+ self.embedding_generator = embedding_generator
72
+
73
+ def process(self, data: pd.DataFrame, context: Dict[str, Any]) -> np.ndarray:
74
+ """Generate embeddings from the text data."""
75
+ text_col = context.get("text_col")
76
+ if text_col is None:
77
+ raise ValueError("'text_col' must be provided in the context")
78
+
79
+ texts = data[text_col].tolist()
80
+ embeddings = self.embedding_generator.generate_embeddings(texts)
81
+ logger.info(f"Generated embeddings with shape: {embeddings.shape}")
82
+ return embeddings
83
+
84
+
85
+ class DimensionalityReductionStage(PipelineStage):
86
+ """Stage for reducing dimensionality of embeddings."""
87
+
88
+ def __init__(self, dimensionality_reducer: Optional[DimensionalityReducer] = None):
89
+ self.dimensionality_reducer = dimensionality_reducer
90
+
91
+ def process(self, embeddings: np.ndarray, context: Dict[str, Any]) -> np.ndarray:
92
+ """Reduce dimensionality of embeddings if a reducer is provided."""
93
+ if self.dimensionality_reducer is None:
94
+ logger.info("No dimensionality reduction applied")
95
+ return embeddings
96
+
97
+ reduced_embeddings = self.dimensionality_reducer.fit_transform(embeddings)
98
+ logger.info(
99
+ f"Reduced embeddings from {embeddings.shape} to {reduced_embeddings.shape}"
100
+ )
101
+ return reduced_embeddings
102
+
103
+
104
+ class ClusteringStage(PipelineStage):
105
+ """Stage for clustering embeddings."""
106
+
107
+ def __init__(self, clustering_algorithm: ClusteringAlgorithm):
108
+ self.clustering_algorithm = clustering_algorithm
109
+
110
+ def process(self, embeddings: np.ndarray, context: Dict[str, Any]) -> np.ndarray:
111
+ """Cluster the embeddings."""
112
+ labels = self.clustering_algorithm.cluster(embeddings)
113
+ logger.info(f"Generated {len(np.unique(labels))} clusters")
114
+ return np.array(labels)
115
+
116
+
117
+ class OutlierDetectionStage(PipelineStage):
118
+ """Stage for detecting outliers."""
119
+
120
+ def __init__(
121
+ self, outlier_detector: OutlierDetector, outlier_scorer: ClusterScorer
122
+ ):
123
+ self.outlier_detector = outlier_detector
124
+ self.outlier_scorer = outlier_scorer
125
+
126
+ def process(
127
+ self, data: Tuple[np.ndarray, np.ndarray], context: Dict[str, Any]
128
+ ) -> Tuple[np.ndarray, np.ndarray, Dict[int, List[float]]]:
129
+ """Detect outliers in the clusters."""
130
+ embeddings, labels = data
131
+
132
+ if self.outlier_detector is not None:
133
+ outlier_mask, item_scores = self.outlier_detector.detect_outliers(
134
+ embeddings, labels
135
+ )
136
+ else:
137
+ item_scores = self.outlier_scorer.calculate_scores(embeddings, labels)
138
+ outlier_mask = np.full(len(labels), False)
139
+
140
+ # apply outlier mask to labels
141
+ modified_labels = labels.copy()
142
+ modified_labels[outlier_mask] = -1
143
+
144
+ logger.info(f"Detected {np.sum(outlier_mask)} outliers")
145
+ return modified_labels, outlier_mask, item_scores
146
+
147
+
148
+ class ClusterScoringStage(PipelineStage):
149
+ """Stage for scoring clusters."""
150
+
151
+ def __init__(self, scorer: ClusterScorer):
152
+ self.scorer = scorer
153
+
154
+ def process(
155
+ self, data: Tuple[np.ndarray, np.ndarray], context: Dict[str, Any]
156
+ ) -> Dict[int, float]:
157
+ """Score the clusters."""
158
+ embeddings, labels = data
159
+ scores = self.scorer.calculate_scores(embeddings, labels)
160
+
161
+ # calculate average score per cluster
162
+ cluster_scores = {}
163
+ unique_labels = np.unique(labels)
164
+ for label in unique_labels:
165
+ if label in scores:
166
+ cluster_scores[label] = np.mean(scores[label])
167
+
168
+ # sort clusters by score
169
+ sorted_scores = dict(
170
+ sorted(cluster_scores.items(), key=lambda x: x[1], reverse=True)
171
+ )
172
+ logger.info(f"Scored {len(sorted_scores)} clusters")
173
+ return sorted_scores
174
+
175
+
176
+ class ClusteringPipelineBuilder:
177
+ """Builder for creating and configuring a clustering pipeline."""
178
+
179
+ def __init__(self):
180
+ self.config = ClusteringConfig()
181
+ self.embedding_generator = None
182
+ self.clustering_algorithm = None
183
+ self.dimensionality_reducer = None
184
+ self.outlier_detector = None
185
+ self.outlier_scorer = None
186
+ self.cluster_scorer = None
187
+
188
+ def with_config(
189
+ self, config: Union[Dict[str, Any], ClusteringConfig]
190
+ ) -> "ClusteringPipelineBuilder":
191
+ """Set the configuration for the pipeline."""
192
+ if isinstance(config, dict):
193
+ self.config = ClusteringConfig.from_dict(config)
194
+ else:
195
+ self.config = config
196
+ return self
197
+
198
+ def with_embedding_generator(
199
+ self, generator: EmbeddingGenerator
200
+ ) -> "ClusteringPipelineBuilder":
201
+ """Set the embedding generator."""
202
+ self.embedding_generator = generator
203
+ return self
204
+
205
+ def with_clustering_algorithm(
206
+ self, algorithm: ClusteringAlgorithm
207
+ ) -> "ClusteringPipelineBuilder":
208
+ """Set the clustering algorithm."""
209
+ self.clustering_algorithm = algorithm
210
+ return self
211
+
212
+ def with_dimensionality_reducer(
213
+ self, reducer: DimensionalityReducer
214
+ ) -> "ClusteringPipelineBuilder":
215
+ """Set the dimensionality reducer."""
216
+ self.dimensionality_reducer = reducer
217
+ return self
218
+
219
+ def with_outlier_detector(
220
+ self, detector: OutlierDetector
221
+ ) -> "ClusteringPipelineBuilder":
222
+ """Set the outlier detector."""
223
+ self.outlier_detector = detector
224
+ return self
225
+
226
+ def with_outlier_scorer(self, scorer: ClusterScorer) -> "ClusteringPipelineBuilder":
227
+ """Set the outlier scorer."""
228
+ self.outlier_scorer = scorer
229
+ return self
230
+
231
+ def with_cluster_scorer(self, scorer: ClusterScorer) -> "ClusteringPipelineBuilder":
232
+ """Set the cluster scorer."""
233
+ self.cluster_scorer = scorer
234
+ return self
235
+
236
+ def build(self) -> "ClusteringPipeline":
237
+ """Build the clustering pipeline."""
238
+ # create default components if not specified
239
+ config_dict = self.config.to_dict()
240
+
241
+ if self.embedding_generator is None:
242
+ self.embedding_generator = SentenceTransformerEmbeddingGenerator(
243
+ config_dict, self.config.model_name
244
+ )
245
+
246
+ if self.clustering_algorithm is None:
247
+ self.clustering_algorithm = HDBSCANClustering(config_dict)
248
+
249
+ if self.outlier_scorer is None:
250
+ self.outlier_scorer = CosineSimililarityClusterScorer()
251
+
252
+ if self.cluster_scorer is None:
253
+ self.cluster_scorer = CosineSimililarityClusterScorer()
254
+
255
+ return ClusteringPipeline(
256
+ config=self.config,
257
+ embedding_generator=self.embedding_generator,
258
+ clustering_algorithm=self.clustering_algorithm,
259
+ dimensionality_reducer=self.dimensionality_reducer,
260
+ outlier_detector=self.outlier_detector,
261
+ outlier_scorer=self.outlier_scorer,
262
+ cluster_scorer=self.cluster_scorer,
263
+ )
264
+
265
+
266
+ class ClusteringPipeline:
267
+ """Pipeline for clustering text data using embeddings.
268
+
269
+ This pipeline handles the entire process from converting text to embeddings,
270
+ clustering the embeddings, detecting outliers, and scoring clusters.
271
+ """
272
+
273
+ def __init__(
274
+ self,
275
+ config: ClusteringConfig,
276
+ embedding_generator: EmbeddingGenerator,
277
+ clustering_algorithm: ClusteringAlgorithm,
278
+ dimensionality_reducer: Optional[DimensionalityReducer] = None,
279
+ outlier_detector: Optional[OutlierDetector] = None,
280
+ outlier_scorer: Optional[ClusterScorer] = None,
281
+ cluster_scorer: Optional[ClusterScorer] = None,
282
+ ):
283
+ self.config = config
284
+
285
+ # initialize pipeline stages
286
+ self.stages = []
287
+ self.stages.append(EmbeddingStage(embedding_generator))
288
+
289
+ if dimensionality_reducer is not None:
290
+ self.stages.append(DimensionalityReductionStage(dimensionality_reducer))
291
+
292
+ self.stages.append(ClusteringStage(clustering_algorithm))
293
+
294
+ if outlier_detector is not None or outlier_scorer is not None:
295
+ self.stages.append(
296
+ OutlierDetectionStage(
297
+ outlier_detector,
298
+ outlier_scorer or CosineSimililarityClusterScorer(),
299
+ )
300
+ )
301
+
302
+ self.stages.append(
303
+ ClusterScoringStage(cluster_scorer or CosineSimililarityClusterScorer())
304
+ )
305
+
306
+ # pipeline state
307
+ self.raw_embeddings = None
308
+ self.processed_embeddings = None
309
+ self.data = None
310
+ self.labels = None
311
+ self.cluster_scores = None
312
+ self.outlier_mask = None
313
+ self.item_scores = None
314
+ self.context = None
315
+
316
+ logger.info("Clustering pipeline initialized")
317
+
318
+ def run(
319
+ self,
320
+ data: pd.DataFrame,
321
+ text_col: str,
322
+ uuid_col: str,
323
+ datetime_col: Optional[str] = None,
324
+ title_col: Optional[str] = None,
325
+ content_col: Optional[str] = None,
326
+ embeddings: Optional[np.ndarray] = None,
327
+ ) -> Dict[str, Any]:
328
+ """Run the complete clustering pipeline on the provided data.
329
+
330
+ Args:
331
+ data: DataFrame containing the text data
332
+ text_col: Column name containing the text to cluster
333
+ uuid_col: Column name containing unique identifiers
334
+ datetime_col: Column name containing datetime information (optional)
335
+ title_col: Column name containing title information (optional)
336
+ content_col: Column name containing content information (optional)
337
+ embeddings: Pre-computed embeddings (optional)
338
+
339
+ Returns:
340
+ Dictionary containing all clustering results
341
+ """
342
+ # Validate inputs
343
+ if text_col not in data.columns and embeddings is None:
344
+ raise ValueError(
345
+ f"Text column '{text_col}' not found in data and no embeddings provided"
346
+ )
347
+
348
+ if uuid_col not in data.columns:
349
+ raise ValueError(f"UUID column '{uuid_col}' not found in data")
350
+
351
+ if datetime_col is not None and datetime_col not in data.columns:
352
+ logger.warning(f"Datetime column '{datetime_col}' not found in data")
353
+ datetime_col = None
354
+
355
+ if title_col is not None and title_col not in data.columns:
356
+ logger.warning(f"Title column '{title_col}' not found in data")
357
+ title_col = None
358
+
359
+ if content_col is not None and content_col not in data.columns:
360
+ logger.warning(f"Content column '{content_col}' not found in data")
361
+ content_col = None
362
+
363
+ # initialize context
364
+ context = {
365
+ "text_col": text_col,
366
+ "uuid_col": uuid_col,
367
+ "datetime_col": datetime_col,
368
+ "title_col": title_col,
369
+ "content_col": content_col,
370
+ }
371
+
372
+ # store the context
373
+ self.context = context
374
+
375
+ # store the original data
376
+ self.data = data
377
+
378
+ # run the pipeline stages
379
+ current_data = data
380
+ stage_results = {}
381
+
382
+ for i, stage in enumerate(self.stages):
383
+ stage_name = stage.__class__.__name__
384
+ logger.info(f"Running stage {i + 1}/{len(self.stages)}: {stage_name}")
385
+
386
+ if isinstance(stage, EmbeddingStage) and embeddings is not None:
387
+ # skip embedding generation if embeddings are provided
388
+ current_data = embeddings
389
+ logger.info("Using provided embeddings")
390
+ else:
391
+ current_data = stage.process(current_data, context)
392
+
393
+ stage_results[stage_name] = current_data
394
+
395
+ # update context with stage results
396
+ if isinstance(stage, EmbeddingStage):
397
+ self.raw_embeddings = current_data
398
+ context["embeddings"] = current_data
399
+ elif isinstance(stage, DimensionalityReductionStage):
400
+ self.processed_embeddings = current_data
401
+ context["processed_embeddings"] = current_data
402
+ elif isinstance(stage, ClusteringStage):
403
+ self.labels = current_data
404
+ context["labels"] = current_data
405
+ current_data = (self.raw_embeddings, current_data)
406
+ elif isinstance(stage, OutlierDetectionStage):
407
+ self.labels, self.outlier_mask, self.item_scores = current_data
408
+ context["labels"] = self.labels
409
+ context["outlier_mask"] = self.outlier_mask
410
+ context["item_scores"] = self.item_scores
411
+ current_data = (self.raw_embeddings, self.labels)
412
+ elif isinstance(stage, ClusterScoringStage):
413
+ self.cluster_scores = current_data
414
+ context["cluster_scores"] = current_data
415
+
416
+ # generate the final result
417
+ result = self.get_clusters(threshold=self.config.outlier_threshold)
418
+ # print(self.labels)
419
+ return {
420
+ "clusters": result,
421
+ "labels": self.labels,
422
+ "raw_embeddings": self.raw_embeddings,
423
+ "processed_embeddings": self.processed_embeddings,
424
+ "cluster_scores": self.cluster_scores,
425
+ "item_scores": self.item_scores,
426
+ }
427
+
428
+ def _validate_pipeline_state(self) -> None:
429
+ """Validate that the pipeline has been run before getting clusters."""
430
+ if self.labels is None:
431
+ raise ValueError("Pipeline must be run before getting clusters")
432
+
433
+ if self.context is None:
434
+ raise ValueError("Pipeline must be run before getting clusters")
435
+
436
+ def _create_item_dictionaries(self, threshold: float = 0.7) -> List[Dict[str, Any]]:
437
+ """Create dictionaries for each item with their cluster label and score.
438
+
439
+ Args:
440
+ threshold: Score threshold for including items in clusters
441
+
442
+ Returns:
443
+ List of item dictionaries with labels and scores
444
+ """
445
+ item_dicts = []
446
+
447
+ # Outlier detection can change membership. Recompute against final labels,
448
+ # as the previous pipeline did, and consume each cluster's scores in order.
449
+ scorer = CosineSimililarityClusterScorer()
450
+ scored_samples = scorer.calculate_scores(self.raw_embeddings, self.labels)
451
+ score_positions = {label: 0 for label in scored_samples}
452
+
453
+ logger.info(
454
+ f"Score dictionary contains scores for clusters: {list(scored_samples.keys())}"
455
+ )
456
+
457
+ # create item dictionaries with scores
458
+ for i, label in enumerate(self.labels):
459
+ if label == -1:
460
+ score = -1
461
+ else:
462
+ position = score_positions[label]
463
+ score = scored_samples[label][position]
464
+ score_positions[label] = position + 1
465
+
466
+ if threshold and score < threshold:
467
+ logger.debug(
468
+ f"Item {i} score {score} below threshold {threshold}, marking as outlier"
469
+ )
470
+ label = -1
471
+
472
+ item_dicts.append(
473
+ {
474
+ "uuid": self.data.iloc[i][self.context["uuid_col"]],
475
+ "label": int(label),
476
+ "score": float(score),
477
+ }
478
+ )
479
+
480
+ logger.info(f"Created {len(item_dicts)} item dictionaries")
481
+ return item_dicts
482
+
483
+ def _group_items_into_clusters(
484
+ self, item_dicts: List[Dict[str, Any]], include_outliers: bool = False
485
+ ) -> List[Dict[str, Any]]:
486
+ """Group items into clusters and format the result.
487
+
488
+ Args:
489
+ item_dicts: List of item dictionaries with labels and scores
490
+ include_outliers: Whether to include outlier cluster (-1) in results
491
+
492
+ Returns:
493
+ List of cluster dictionaries with items and scores
494
+ """
495
+ # group items by cluster
496
+ clusters = {}
497
+ for item in item_dicts:
498
+ label = item["label"]
499
+
500
+ if label not in clusters:
501
+ clusters[label] = {"score": item["score"], "items": [item]}
502
+ else:
503
+ clusters[label]["items"].append(item)
504
+ # update cluster score to be the mean of all item scores
505
+ clusters[label]["score"] = np.mean(
506
+ [i["score"] for i in clusters[label]["items"]]
507
+ )
508
+
509
+ logger.info(f"Grouped items into {len(clusters)} clusters")
510
+
511
+ # format the final result
512
+ result = [{"label": label, **clusters[label]} for label in clusters]
513
+ result = sorted(result, key=lambda x: x["score"], reverse=True)
514
+ logger.info(f"After sorting: {len(result)} clusters")
515
+
516
+ result = [x for x in result if len(x["items"]) > 1]
517
+ logger.info(
518
+ f"After filtering clusters with less than 2 items: {len(result)} clusters"
519
+ )
520
+
521
+ if not include_outliers:
522
+ result = [x for x in result if x["label"] != -1]
523
+ logger.info(f"After removing outliers: {len(result)} clusters")
524
+
525
+ return result
526
+
527
+ def _enrich_clusters_with_metadata(
528
+ self,
529
+ clusters: List[Dict[str, Any]],
530
+ include_title: bool = True,
531
+ include_content: bool = True,
532
+ ) -> List[Dict[str, Any]]:
533
+ """Add title and content information to cluster items if requested.
534
+
535
+ Args:
536
+ clusters: List of cluster dictionaries
537
+ include_title: Whether to include title information
538
+ include_content: Whether to include content information
539
+
540
+ Returns:
541
+ Enriched cluster dictionaries
542
+ """
543
+ if not (include_title or include_content):
544
+ return clusters
545
+
546
+ for cluster in clusters:
547
+ # get the UUIDs from the cluster items
548
+ cluster_uuids = [item["uuid"] for item in cluster["items"]]
549
+
550
+ # find the corresponding rows in the original data
551
+ _cluster_data = self.data[
552
+ self.data[self.context["uuid_col"]].isin(cluster_uuids)
553
+ ]
554
+
555
+ # add title and content information to each item in the cluster
556
+ for item in cluster["items"]:
557
+ item_uuid = item["uuid"]
558
+ # find the matching row in the original data
559
+ matching_row = self.data[
560
+ self.data[self.context["uuid_col"]] == item_uuid
561
+ ]
562
+ if not matching_row.empty:
563
+ # add title if requested and available
564
+ if (
565
+ include_title
566
+ and "title_col" in self.context
567
+ and self.context["title_col"] in matching_row.columns
568
+ ):
569
+ item["title"] = matching_row[self.context["title_col"]].values[
570
+ 0
571
+ ]
572
+ # add content if requested and available
573
+ if (
574
+ include_content
575
+ and "content_col" in self.context
576
+ and self.context["content_col"] in matching_row.columns
577
+ ):
578
+ item["content"] = matching_row[
579
+ self.context["content_col"]
580
+ ].values[0]
581
+
582
+ return clusters
583
+
584
+ def get_clusters(
585
+ self,
586
+ threshold: float = 0.7,
587
+ include_outliers: bool = False,
588
+ include_title: bool = True,
589
+ include_content: bool = True,
590
+ ) -> List[Dict[str, Any]]:
591
+ """Get the final cluster results.
592
+
593
+ Args:
594
+ threshold: Score threshold for including items in clusters
595
+ include_outliers: Whether to include outlier cluster (-1) in results
596
+ include_title: Whether to include title information in cluster items
597
+ include_content: Whether to include content information in cluster items
598
+
599
+ Returns:
600
+ List of cluster dictionaries with items and scores
601
+ """
602
+ self._validate_pipeline_state()
603
+
604
+ logger.info(
605
+ f"Starting get_clusters with {len(self.labels)} labels. Unique labels: {np.unique(self.labels)}"
606
+ )
607
+
608
+ # create item dictionaries with scores
609
+ item_dicts = self._create_item_dictionaries(threshold)
610
+
611
+ # group items into clusters
612
+ result = self._group_items_into_clusters(item_dicts, include_outliers)
613
+
614
+ # optionally enrich clusters with metadata
615
+ if include_title or include_content:
616
+ result = self._enrich_clusters_with_metadata(
617
+ result, include_title, include_content
618
+ )
619
+
620
+ return result
621
+
622
+ def print_clusters(
623
+ self,
624
+ clusters: Optional[List[Dict[str, Any]]] = None,
625
+ show_fields: Optional[List[str]] = None,
626
+ ) -> None:
627
+ """Print clusters in a readable format.
628
+
629
+ Args:
630
+ clusters: List of cluster dictionaries. If None, will use the last computed clusters.
631
+ show_fields: List of additional fields from the data to display for each item.
632
+ If None, will only show the text field used for clustering.
633
+ """
634
+ if clusters is None:
635
+ clusters = self.get_clusters()
636
+
637
+ if not clusters:
638
+ print("No clusters found.")
639
+ return
640
+
641
+ if self.context is None:
642
+ raise ValueError("Pipeline must be run before printing clusters")
643
+
644
+ text_col = self.context["text_col"]
645
+
646
+ print(f"\nFound {len(clusters)} clusters:")
647
+ print("-" * 80)
648
+
649
+ for cluster in clusters:
650
+ print(
651
+ f"CLUSTER {cluster['label']} - SCORE: {cluster['score']:.3f} - ITEMS: {len(cluster['items'])}"
652
+ )
653
+
654
+ for item_dict in cluster["items"]:
655
+ uuid = item_dict["uuid"]
656
+ item = self.data[self.data[self.context["uuid_col"]] == uuid]
657
+
658
+ # Format the item text
659
+ text = item[text_col].values[0]
660
+ score = round(item_dict["score"], 3)
661
+
662
+ # Build additional fields string if requested
663
+ additional_info = ""
664
+ if show_fields:
665
+ field_values = []
666
+ for field in show_fields:
667
+ if field in item.columns:
668
+ field_values.append(f"{field}: {item[field].values[0]}")
669
+ if field_values:
670
+ additional_info = f" ({', '.join(field_values)})"
671
+
672
+ print(f"--[{score}] {text}{additional_info}")
673
+ print()
674
+
675
+ def hyperparameter_tuning(
676
+ self,
677
+ data: pd.DataFrame,
678
+ text_col: str,
679
+ uuid_col: str,
680
+ expected_labels: List[int],
681
+ n_iter_search: int = 20,
682
+ ) -> Dict[str, Any]:
683
+ """Tune hyperparameters for the clustering algorithm.
684
+
685
+ Args:
686
+ data: DataFrame containing the text data
687
+ text_col: Column name containing the text
688
+ uuid_col: Column name containing unique identifiers
689
+ expected_labels: Expected cluster labels for evaluation
690
+ n_iter_search: Number of iterations for hyperparameter search
691
+
692
+ Returns:
693
+ Dictionary of best hyperparameters
694
+ """
695
+ # generate embeddings if not already available
696
+ if self.raw_embeddings is None:
697
+ embedding_stage = self.stages[0]
698
+ self.raw_embeddings = embedding_stage.process(data, {"text_col": text_col})
699
+
700
+ uuids = data[uuid_col].tolist()
701
+
702
+ # tune hyperparameters
703
+ best_params = self.stages[2].clustering_algorithm.hyperparameter_tuning(
704
+ self.raw_embeddings,
705
+ uuids,
706
+ expected_labels,
707
+ self.stages[3].outlier_detector if len(self.stages) > 3 else None,
708
+ n_iter_search,
709
+ )
710
+
711
+ logger.info(f"Best hyperparameters found: {best_params}")
712
+ return best_params