> built 2026-11-22 22:20 UTC from 3368ccc (main) · imbed 0.0.28. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# imbed

Tools to work with embeddings, easily an flexibily.

To install:	`pip install imbed`

# Introduction

As we all know, though RAG (Retrieval Augumented Generation) is hyper-popular at the moment, the R part, though around for decades
(mainly under the names “information retrieval” (IR), “search”, “indexing”,…), has a lot to contribute towards the success, or failure, of the effort.
The [many characteristics of the retrieval part](https://arxiv.org/abs/2312.10997) need to be tuned to align with the final generation and business objectives.
There’s still a lot of science to do.

So the last thing we want is to be slowed down by pedestrian aspects of the process.
We want to be agile in getting data prepared and analyzed, so we spend more time doign science, and iterate our models quickly.

There are two major aspects the `imbed` wishes to contribute two that.

* search: getting from raw data to an iterface where we can search the information effectively
* visualize: exploring the data visually (which requires yet another kind of embedding, to 2D or 3D vectors)

What we’re looking for here is a setup where with minimal **configuration** (not code), we can make pipelines where we can point to the original data, enter a few parameters,
wait, and get a “search controller” (that is, an object that has all the methods we need to do retrieval stuff). Here’s an example of the kind of interface we’d like to target.

```python
raw_docs = mk_text_store(
    doc_src_uri
)  # the store used will depend on the source and format of where the docs are stored
segments = mk_segments_store(
    raw_docs, ...
)  # will not copy any data over, but will give a key-value view of chunked (split) docs
search_ctrl = mk_search_controller(vectorDB, embedder, ...)
search_ctrl.fit(segments, doc_src_uri, ...)
search_ctrl.save(...)
```

# Basic Usage

## Text Segmentation

```python
from imbed.segmentation_util import fixed_step_chunker

# Create chunks of text with a specific size
text = "This is a sample text that will be divided into smaller chunks for processing."
chunks = list(fixed_step_chunker(text.split(), chk_size=3))
print(chunks)
# Output: [['This', 'is', 'a'], ['sample', 'text', 'that'], ['will', 'be', 'divided'], ['into', 'smaller', 'chunks'], ['for', 'processing.']]

# Create overlapping chunks with a step size
overlapping_chunks = list(fixed_step_chunker(text.split(), chk_size=4, chk_step=2))
print(overlapping_chunks)
# Output: [['This', 'is', 'a', 'sample'], ['a', 'sample', 'text', 'that'], ...]
```

## Working with Embeddings

```python
import numpy as np
from imbed.util import cosine_similarity, planar_embeddings, transpose_iterable

# Create some example embeddings
embeddings = {
    "doc1": np.array([0.1, 0.2, 0.3]),
    "doc2": np.array([0.2, 0.3, 0.4]),
    "doc3": np.array([0.9, 0.8, 0.7]),
}

# Calculate cosine similarity between embeddings
similarity = cosine_similarity(embeddings["doc1"], embeddings["doc2"])
print(f"Similarity between doc1 and doc2: {similarity:.3f}")

# Project embeddings to 2D for visualization
planar_coords = planar_embeddings(embeddings)
print("2D coordinates for visualization:")
for doc_id, coords in planar_coords.items():
    print(f"  {doc_id}: {coords}")

# Get x, y coordinates separately for plotting
x_values, y_values = transpose_iterable(planar_coords.values())
```

## Creating a Search System

```python
from imbed.segmentation_util import SegmentStore

# Example document store
docs = {
    "doc1": "This is the first document about artificial intelligence.",
    "doc2": "The second document discusses neural networks and deep learning.",
    "doc3": "Document three covers natural language processing.",
}

# Create segment keys (doc_id, start_position, end_position)
segment_keys = [
    ("doc1", 0, len(docs["doc1"])),
    ("doc2", 0, 27),  # First half
    ("doc2", 28, len(docs["doc2"])),  # Second half
    ("doc3", 0, len(docs["doc3"])),
]

# Create a segment store
segment_store = SegmentStore(docs, segment_keys)

# Get a segment
print(segment_store[("doc2", 28, len(docs["doc2"]))])
# Output: "neural networks and deep learning."

# Iterate over all segments
for key in segment_store:
    segment = segment_store[key]
    print(f"{key}: {segment[:20]}...")
```

## Storage Utilities

```python
import os
from imbed.util import extension_based_wrap
from dol import Files

# Create a directory for storing data
os.makedirs("./data_store", exist_ok=True)

# Create a store that handles encoding/decoding based on file extensions
store = extension_based_wrap(Files("./data_store"))

# Store different types of data with appropriate extensions
store["config.json"] = {"model": "text-embedding-3-small", "batch_size": 32}
store["embeddings.npy"] = np.random.random((10, 128))

# The data is automatically encoded/decoded based on file extension
config = store["config.json"]  # Decoded from JSON automatically
embeddings = store["embeddings.npy"]  # Loaded as numpy array automatically

# Check available codec mappings
from imbed.util import get_codec_mappings

print("Available codecs:", list(get_codec_mappings()[0].keys()))
```

# Advanced Pipeline

For more complex use cases, imbed enables a configuration-driven pipeline approach:

```py
# Example of the configuration-driven pipeline (conceptual)
raw_docs = mk_text_store("s3://my-bucket/documents/")
segments = mk_segments_store(raw_docs, chunk_size=512, overlap=128)
search_ctrl = mk_search_controller(vector_db="faiss", embedder="text-embedding-3-small")
search_ctrl.fit(segments)
search_ctrl.save("./search_model")

# Search using the controller
results = search_ctrl.search("How does machine learning work?")
```

# Working with Embeddings and Visualization in imbed

The imbed package provides powerful tools for working with embeddings, particularly for visualizing high-dimensional data and identifying meaningful clusters. Here are examples showing how to use the planarization and clusterization modules.

## Planarization for Embedding Visualization

Embedding models typically produce high-dimensional vectors (e.g., 384 or 1536 dimensions) that can’t be directly visualized. The planarization module helps project these vectors to 2D space for visualization purposes.

```py
import numpy as np
import matplotlib.pyplot as plt
from imbed.components.planarization import planarizers, umap_planarizer

# Create some sample high-dimensional embeddings
np.random.seed(42)
embeddings = np.random.randn(100, 128)  # 100 documents with 128-dimensional embeddings

# Project embeddings to 2D using UMAP (great for preserving local relationships)
planar_points = umap_planarizer(
    embeddings, n_neighbors=15, min_dist=0.1, random_state=42
)

# Convert to separate x and y coordinates for plotting
x_coords, y_coords = zip(*planar_points)

# Create a simple scatter plot
plt.figure(figsize=(10, 8))
plt.scatter(x_coords, y_coords, alpha=0.7)
plt.title("Document Embeddings Visualization using UMAP")
plt.xlabel("Dimension 1")
plt.ylabel("Dimension 2")
plt.grid(alpha=0.3)
plt.show()

# Available planarization algorithms
print(f"Available planarization methods: {list(planarizers.keys())}")
```

The planarization module offers multiple techniques for dimensionality reduction:

* `umap_planarizer`: Great for preserving both local and global relationships
* `tsne_planarizer`: Good for preserving local neighborhood relationships
* `pca_planarizer`: Linear projection that preserves global variance
* `force_directed_planarizer`: Physics-based approach for visualization

Each algorithm has different strengths - UMAP is generally excellent for embedding visualization, while t-SNE is better for highlighting local clusters.

## Clusterization for Content Organization

After projecting embeddings to 2D, you can cluster them to identify groups of related documents:

```py
import numpy as np
import matplotlib.pyplot as plt
from imbed.components.planarization import umap_planarizer
from imbed.components.clusterization import (
    kmeans_clusterer,
    hierarchical_clusterer,
    clusterers,
)

# Create some sample embeddings
np.random.seed(42)
# Create 3 distinct groups of embeddings
group1 = np.random.randn(30, 128) + np.array([2.0] * 128)
group2 = np.random.randn(40, 128) - np.array([2.0] * 128)
group3 = np.random.randn(30, 128) + np.array([0.0] * 128)
embeddings = np.vstack([group1, group2, group3])

# First project to 2D for visualization
planar_points = umap_planarizer(embeddings, random_state=42)
x_coords, y_coords = zip(*planar_points)

# Apply clustering to the original high-dimensional embeddings
cluster_ids = kmeans_clusterer(embeddings, n_clusters=3)

# Visualize the clusters
plt.figure(figsize=(10, 8))
scatter = plt.scatter(x_coords, y_coords, c=cluster_ids, cmap="viridis", alpha=0.7)
plt.colorbar(scatter, label="Cluster ID")
plt.title("Document Clusters Visualization")
plt.xlabel("Dimension 1")
plt.ylabel("Dimension 2")
plt.grid(alpha=0.3)
plt.show()

# Try a different clustering algorithm
hierarchical_clusters = hierarchical_clusterer(embeddings, n_clusters=3, linkage="ward")

# Compare clustering results
agreement = sum(1 for a, b in zip(cluster_ids, hierarchical_clusters) if a == b) / len(
    cluster_ids
)
print(f"Agreement between kmeans and hierarchical clustering: {agreement:.2%}")

# Available clustering algorithms
print(f"Available clustering methods: {list(clusterers.keys())}")
```

## Labeling clusters

A useful AI-based tool to label clusters.

```py
from imbed import cluster_labeler

import pandas as pd
import numpy as np
from typing import Callable, Union

# Sample data with text segments and cluster indices
data = {
    "segment": [
        "Machine learning models can be trained on large datasets to identify patterns.",
        "Neural networks are a subset of machine learning algorithms inspired by the human brain.",
        "Deep learning is a type of neural network with multiple hidden layers.",
        "Python is a versatile programming language used in data science and web development.",
        "JavaScript is primarily used for web development and creating interactive websites.",
        "HTML and CSS are markup languages used to structure and style web pages.",
        "SQL is a query language designed for managing and manipulating databases.",
        "NoSQL databases like MongoDB store data in flexible, JSON-like documents.",
    ],
    "cluster_idx": [0, 0, 0, 1, 1, 1, 2, 2],  # 3 clusters
}

# Create the dataframe
df = pd.DataFrame(data)

# You can test with:
labels = cluster_labeler(df, context="Technical documentation")
labels
```

```none
{0: 'Neural Networks Overview',
1: 'Web Development Language Comparisons',
2: 'Database Management Comparisons'}
```

## Why This Matters for Embedding Visualization

Both planarization and clusterization are essential for making sense of embeddings:

Dimensionality Reduction: High-dimensional embeddings can’t be directly visualized. Planarization techniques reduce them to 2D or 3D for plotting while preserving meaningful relationships.

Pattern Discovery: Clustering helps identify natural groupings within your data, revealing thematic structures that might not be obvious.

Content Organization: You can use clusters to automatically organize documents by topic, identify outliers, or create faceted navigation systems.

Relevance Evaluation: Visualizing embeddings lets you assess whether your embedding model is capturing meaningful semantic relationships.

Iterative Refinement: Visual inspection of embeddings and clusters helps you iterate on your data preparation, segmentation, and model selection strategies.

The imbed package makes these powerful techniques accessible through a simple, unified interface, allowing you to focus on the analysis rather than implementation details.

<p class="epythet-aggregates">This documentation as a single file: <a href="imbed.md">imbed.md</a> (Markdown, for agents).</p>


# _autosummary/imbed.base.html.md

# imbed.base

Base functionality of imbded.

### Functions

| `add_token_info_to_df`(df, segments_col, \*[, ...])                           |                                                    |
|-------------------------------------------------------------------------------|----------------------------------------------------|
| [`batches`](_autosummary/imbed.base.html.md#imbed.base.batches)(df[, chk_size])      | Yield batches of rows from a DataFrame.            |
| `compute_and_save_embeddings`(df[, ...])                                      |                                                    |
| `compute_and_save_planar_embeddings`(...[, ...])                              |                                                    |
| [`get_empty_temporary_folder`](_autosummary/imbed.base.html.md#imbed.base.get_empty_temporary_folder)() | Returns the path of a new, empty temporary folder. |
| `identity`(x)                                                                 |                                                    |
| `mk_local_store`(rootdir)                                                     |                                                    |

### Classes

| [`ComputedValuesMapping`](_autosummary/imbed.base.html.md#imbed.base.ComputedValuesMapping)(keys_factory[, ...])    | A mapping that returns empty values for all keys.   |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------|
| [`HugfaceDaccBase`](_autosummary/imbed.base.html.md#imbed.base.HugfaceDaccBase)(huggingface_data_stub[, ...]) |                                                     |
| `ImbedDaccBase`()                                                                              |                                                     |
| `LocalSavesMixin`()                                                                            |                                                     |

### *class* imbed.base.ComputedValuesMapping(keys_factory, value_of_key=functools.partial(<function identity>, None))

Bases: `KvReader`, [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

A mapping that returns empty values for all keys.

Example usage:

```pycon
>>> m = ComputedValuesMapping(('apple', 'crumble'), value_of_key=len)
>>> list(m)
['apple', 'crumble']
>>> m['apple']
5
```

### *class* imbed.base.HugfaceDaccBase(huggingface_data_stub, name=None, , saves_dir=None, root_saves_dir='/home/runner/.config/imbed/saves', verbose=1)

Bases: `LocalSavesMixin`

### imbed.base.batches(df, chk_size=1000)

Yield batches of rows from a DataFrame.

The yielded batches are lists of (index, row) tuples.

If chk_size is None, yield the whole DataFrame as a single batch.

### imbed.base.get_empty_temporary_folder()

Returns the path of a new, empty temporary folder.


# _autosummary/imbed.components.clusterization.html.md

# imbed.components.clusterization

Clusterization module for imbed.

### Functions

| [`affinity_propagation_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.affinity_propagation_clusterer)(vectors[, ...])    | Affinity Propagation clustering using scikit-learn.                            |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| [`birch_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.birch_clusterer)(vectors[, n_clusters, ...])       | Birch clustering using scikit-learn.                                           |
| [`bisecting_kmeans_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.bisecting_kmeans_clusterer)(vectors[, ...])        | Bisecting K-means clustering implementation.                                   |
| [`constant_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.constant_clusterer)(vectors)                       | Returns alternating [0, 1, 0, 1, ...] cluster IDs regardless of input vectors. |
| [`dbscan_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.dbscan_clusterer)(vectors[, eps, ...])             | DBSCAN clustering using scikit-learn.                                          |
| [`fit_kmeans`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.fit_kmeans)(vectors[, n_clusters, normalize])      | Fit a KMeans model and return it for inference on new vectors.                 |
| [`get_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.get_clusterer)(name)                               | Get a clusterer by name.                                                       |
| [`gmm_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.gmm_clusterer)(vectors[, n_components, ...])       | Gaussian Mixture Model clustering using scikit-learn.                          |
| [`hierarchical_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.hierarchical_clusterer)(vectors[, ...])            | Hierarchical clustering using scikit-learn.                                    |
| [`kmeans_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.kmeans_clusterer)(vectors[, n_clusters, ...])      | K-means clustering using scikit-learn.                                         |
| [`kmeans_lite_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.kmeans_lite_clusterer)(vectors[, n_clusters, ...]) | K-means clustering implementation.                                             |
| [`list_available_clusterers`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.list_available_clusterers)()                       | Return a list of names of all available clusterers.                            |
| [`meanshift_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.meanshift_clusterer)(vectors[, quantile, ...])     | Mean-shift clustering using scikit-learn.                                      |
| [`minibatch_kmeans_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.minibatch_kmeans_clusterer)(vectors[, ...])        | Mini-batch K-means clustering using scikit-learn.                              |
| [`nearest_neighbor_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.nearest_neighbor_clusterer)(vectors[, ...])        | Clustering based on nearest neighbors.                                         |
| [`optics_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.optics_clusterer)(vectors[, min_samples, xi, ...]) | OPTICS clustering using scikit-learn.                                          |
| [`random_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.random_clusterer)(vectors[, n_clusters])           | Randomly assigns cluster IDs to vectors.                                       |
| [`scan_for_clusterers`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.scan_for_clusterers)()                             | Scan the module for all registered clusterers.                                 |
| [`spectral_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.spectral_clusterer)(vectors[, n_clusters, ...])    | Spectral clustering using scikit-learn.                                        |
| [`threshold_clusterer`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.threshold_clusterer)(vectors[, threshold, ...])    | Clusters vectors based on a simple distance threshold.                         |

### imbed.components.clusterization.affinity_propagation_clusterer(vectors, damping=0.5, max_iter=200)

Affinity Propagation clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **damping** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Damping factor
  * **max_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of iterations
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.birch_clusterer(vectors, n_clusters=3, threshold=0.5, branching_factor=50)

Birch clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters
  * **threshold** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – The radius of the subcluster for a sample to be added
  * **branching_factor** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of CF subclusters in each node
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.bisecting_kmeans_clusterer(vectors, n_clusters=3, max_iter=100)

Bisecting K-means clustering implementation.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters to form
  * **max_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of iterations per bisection
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.constant_clusterer(vectors)

Returns alternating [0, 1, 0, 1, …] cluster IDs regardless of input vectors.
This is just for testing purposes.

* **Parameters:**
  **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  A sequence of cluster IDs (alternating 0 and 1)

```pycon
>>> constant_clusterer([[1, 2], [3, 4], [5, 6], [7, 8]])
[0, 1, 0, 1]
>>> constant_clusterer([[1, 2], [3, 4], [5, 6]])
[0, 1, 0]
```

### imbed.components.clusterization.dbscan_clusterer(vectors, eps=0.5, min_samples=5, metric='cosine')

DBSCAN clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **eps** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – The maximum distance between two samples for them to be considered neighbors
  * **min_samples** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – The number of samples in a neighborhood for a point to be considered a core point
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The distance metric to use (default: ‘cosine’ for semantic embeddings)
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster IDs with -1 representing noise points

### imbed.components.clusterization.fit_kmeans(vectors, n_clusters=8, , normalize=True, \*\*kmeans_kwargs)

Fit a KMeans model and return it for inference on new vectors.

Unlike [`kmeans_clusterer()`](_autosummary/imbed.components.clusterization.html.md#imbed.components.clusterization.kmeans_clusterer), which throws the model away after
labeling the input, this returns the fitted model so the same cluster
codebook can label *new* vectors later (key for inference pipelines).

The returned object exposes:

- `.labels_`: cluster IDs for the input vectors.
- `.cluster_centers_`: centroid matrix.
- `.predict(new_vectors) -> list[int]`: classify new vectors against
  the fitted centroids.
- Direct call: `model(vectors) -> list[int]` (so it matches the
  `Clusterer = Callable[[Vectors], ClusterIDs]` protocol exactly).

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – Training vectors.
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Cluster count.
  * **normalize** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True (default), L2-normalize vectors first so Euclidean
    distance approximates cosine distance — appropriate for semantic
    embeddings.
  * **\*\*kmeans_kwargs** – Passed to `sklearn.cluster.KMeans`.
* **Returns:**
  `_FittedKMeans` instance.

### imbed.components.clusterization.get_clusterer(name)

Get a clusterer by name.

* **Parameters:**
  **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Name of the clusterer
* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]] | [`None`](https://docs.python.org/3/builtins/constants.html#None)
* **Returns:**
  The clusterer function if found, None otherwise

```pycon
>>> get_clusterer('constant_clusterer') == constant_clusterer
True
>>> get_clusterer('nonexistent_clusterer') is None
True
```

### imbed.components.clusterization.gmm_clusterer(vectors, n_components=2, covariance_type='full', random_state=42)

Gaussian Mixture Model clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_components** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of mixture components
  * **covariance_type** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Covariance parameter type
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random state for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.hierarchical_clusterer(vectors, n_clusters=2, linkage='average', affinity='cosine')

Hierarchical clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters to form
  * **linkage** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Linkage criterion [‘ward’, ‘complete’, ‘average’, ‘single’]
    (Note: ‘ward’ requires affinity=’euclidean’)
  * **affinity** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Distance metric to use (default: ‘cosine’ for semantic embeddings)
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.kmeans_clusterer(vectors, n_clusters=8, , init='k-means++', n_init='auto', max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')

K-means clustering using scikit-learn.

#### NOTE
KMeans uses Euclidean distance internally. For semantic embeddings based on
cosine similarity, it’s recommended to L2-normalize your input vectors before passing
them to this function. When vectors are L2-normalized, Euclidean distance becomes
equivalent to cosine distance.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors (L2-normalize for cosine-like behavior)
  * **n_clusters** – Number of clusters to form
  * **random_state** – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.kmeans_lite_clusterer(vectors, n_clusters=3, max_iter=100, tol=0.0001, seed=None)

K-means clustering implementation.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters to form
  * **max_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of iterations
  * **tol** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Tolerance for convergence
  * **seed** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.list_available_clusterers()

Return a list of names of all available clusterers.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of clusterer names

```pycon
>>> 'constant_clusterer' in list_available_clusterers()
True
```

### imbed.components.clusterization.meanshift_clusterer(vectors, quantile=0.3, n_samples=None)

Mean-shift clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **quantile** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Quantile for bandwidth estimation
  * **n_samples** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Number of samples to use for bandwidth estimation
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.minibatch_kmeans_clusterer(vectors, n_clusters=3, batch_size=100, max_iter=100)

Mini-batch K-means clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters
  * **batch_size** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Size of mini-batches
  * **max_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of iterations
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.nearest_neighbor_clusterer(vectors, threshold=1.0, n_neighbors=5)

Clustering based on nearest neighbors.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **threshold** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Distance threshold for neighbors
  * **n_neighbors** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of neighbors to consider
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.optics_clusterer(vectors, min_samples=5, xi=0.05, min_cluster_size=0.05)

OPTICS clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **min_samples** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of samples in a neighborhood
  * **xi** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Determines the minimum steepness on the reachability plot
  * **min_cluster_size** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum cluster size as a fraction of total samples
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.random_clusterer(vectors, n_clusters=2)

Randomly assigns cluster IDs to vectors.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters to create (default: 2)
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Randomly assigned cluster IDs

```pycon
>>> random.seed(42)
>>> random_clusterer([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], n_clusters=3)
[2, 1, 0, 2, 2]
```

### imbed.components.clusterization.scan_for_clusterers()

Scan the module for all registered clusterers.
This function simply returns the global clusterers dictionary.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]]
* **Returns:**
  Dictionary of registered clusterers

### imbed.components.clusterization.spectral_clusterer(vectors, n_clusters=2, affinity='cosine')

Spectral clustering using scikit-learn.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_clusters** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of clusters to form
  * **affinity** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Affinity type [‘nearest_neighbors’, ‘rbf’, ‘precomputed’, ‘cosine’]
    (default: ‘cosine’ for semantic embeddings)
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster assignments for each input vector

### imbed.components.clusterization.threshold_clusterer(vectors, threshold=1.0, distance_func=<function \_cosine_distance>)

Clusters vectors based on a simple distance threshold.
Vectors within threshold distance are put in the same cluster.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **threshold** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Distance threshold for cluster assignment
  * **distance_func** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)], [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]], [`float`](https://docs.python.org/3/builtins/functions.html#float)]) – Function to calculate distance between two vectors
    (default: cosine distance for semantic embeddings)
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]
* **Returns:**
  Cluster IDs for each input vector


# _autosummary/imbed.components.components_util.html.md

# imbed.components.components_util

Utils for components

### Functions

| [`add_default_key`](_autosummary/imbed.components.components_util.html.md#imbed.components.components_util.add_default_key)(d, default_key[, ...])   | Add a 'default' key to a registry pointing to a specified component.   |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------------|
| [`get_component_store`](_autosummary/imbed.components.components_util.html.md#imbed.components.components_util.get_component_store)(component)           | Get the store for a specific component type                            |
| [`get_standard_components`](_autosummary/imbed.components.components_util.html.md#imbed.components.components_util.get_standard_components)([refresh])       | Get the standard components for the project.                           |

### Classes

| [`ComponentRegistry`](_autosummary/imbed.components.components_util.html.md#imbed.components.components_util.ComponentRegistry)(name, \*[, factory])   | A dict-based registry with decorator support for registration.   |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------|

### *class* imbed.components.components_util.ComponentRegistry(name, , factory=None)

Bases: [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

A dict-based registry with decorator support for registration.

This registry provides:

- Decorator-based registration with @registry.register()
- Custom key support with @registry.register(‘custom_key’)
- Direct registration via registry.register_item(key, item)
- Optional factory functions to wrap registered items
- Full dict compatibility for backward compatibility

### Examples

```pycon
>>> registry = ComponentRegistry('my_components')
>>> @registry.register()
... def my_function(x):
...     return x * 2
>>> registry['my_function'](5)
10
>>> @registry.register('custom_name')
... def another_function(x):
...     return x + 1
>>> registry['custom_name'](5)
6
```

#### register(key=None, \*\*config)

Decorator to register a component.

* **Parameters:**
  * **key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Registration key (defaults to function/class name)
  * **\*\*config** – Additional configuration passed to factory if present
* **Return type:**
  [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`T`], `T`]
* **Returns:**
  Decorator function that registers and returns the component

### Examples

```pycon
>>> registry = ComponentRegistry('test')
>>> @registry.register()
... def my_func():
...     return 42
>>> registry['my_func']()
42
>>> @registry.register('custom')
... def other_func():
...     return 99
>>> registry['custom']()
99
```

#### register_item(key, item, \*\*config)

Register an item directly (non-decorator usage).

* **Parameters:**
  * **key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Registration key
  * **item** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Item to register
  * **\*\*config** – Additional configuration passed to factory if present

### Examples

```pycon
>>> registry = ComponentRegistry('test')
>>> def my_func():
...     return 42
>>> registry.register_item('my_key', my_func)
>>> registry['my_key']()
42
```

### imbed.components.components_util.add_default_key(d, default_key, enviornment_var=None)

Add a ‘default’ key to a registry pointing to a specified component.

* **Parameters:**
  * **d** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – The registry dict to add default to
  * **default_key** – Either a string key or a callable (uses \_\_name_\_ as key)
  * **enviornment_var** – Optional environment variable to override default_key
* **Returns:**
  The modified dict
* **Raises:**
  [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the default_key is not found in the registry

### imbed.components.components_util.get_component_store(component)

Get the store for a specific component type

### imbed.components.components_util.get_standard_components(refresh=False)

Get the standard components for the project.

* **Returns:**
  A dictionary of standard components, each containing registered processing functions


# _autosummary/imbed.components.html.md

# imbed.components

Components for imbed applications.

This module provides lazy-loading access to component registries:

- segmenters: Text segmentation functions
- embedders: Vectorization/embedding functions
- planarizers: 2D projection functions for visualization
- clusterers: Clustering algorithms

Components are loaded on first access to minimize import time.

### Examples

```pycon
>>> from imbed.components import segmenters
>>> list(segmenters.keys())[:3]
['string_lines', 'jdict_to_segments', 'field_values']
```

```pycon
>>> from imbed.components import components
>>> embedders = components.embedders  # Lazy load via attribute
>>> planarizers = components['planarizers']  # Lazy load via dict access
>>> 'constant_vectorizer' in embedders
True
>>> 'segmenters' in components  # Check if component type exists
True
>>> list(components)  # Iterate over component names
['segmenters', 'embedders', 'planarizers', 'clusterers']
```

### Modules

| [`clusterization`](_autosummary/imbed.components.clusterization.html.md#module-imbed.components.clusterization)   | Clusterization module for imbed.                          |
|----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|
| [`components_util`](_autosummary/imbed.components.components_util.html.md#module-imbed.components.components_util) | Utils for components                                      |
| [`planarization`](_autosummary/imbed.components.planarization.html.md#module-imbed.components.planarization)     | Planarization functions for embedding visualization.      |
| [`segmentation`](_autosummary/imbed.components.segmentation.html.md#module-imbed.components.segmentation)       | Segmentation functions to get text segments.              |
| [`vectorization`](_autosummary/imbed.components.vectorization.html.md#module-imbed.components.vectorization)     | Vectorization functions for converting text to embeddings |


# _autosummary/imbed.components.planarization.html.md

# imbed.components.planarization

Planarization functions for embedding visualization.

### Functions

| [`circular_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.circular_planarizer)(vectors)                     | Places vectors in a circle with similar vectors closer together.        |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|
| [`constant_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.constant_planarizer)(embeddings)                  | Generate basic 2D projections from embeddings                           |
| [`factor_analysis_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.factor_analysis_planarizer)(vectors[, ...])       | Factor Analysis for 2D projection.                                      |
| [`fast_ica_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.fast_ica_planarizer)(vectors[, random_state])     | Fast Independent Component Analysis (FastICA) for 2D projection.        |
| [`gaussian_random_projection_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.gaussian_random_projection_planarizer)(vectors)   | Gaussian Random Projection for 2D projection.                           |
| [`grid_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.grid_planarizer)(vectors)                         | Places vectors in a grid pattern.                                       |
| [`identity_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.identity_planarizer)(vectors)                     | Returns the first two dimensions of each vector.                        |
| [`isomap_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.isomap_planarizer)(vectors[, n_neighbors])        | Isomap for 2D projection.                                               |
| [`kernel_pca_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.kernel_pca_planarizer)(vectors[, kernel, ...])    | Kernel PCA for 2D projection.                                           |
| [`lle_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.lle_planarizer)(vectors[, n_neighbors, ...])      | Locally Linear Embedding (LLE) for 2D projection.                       |
| [`mds_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.mds_planarizer)(vectors[, metric, n_init, ...])   | Multidimensional Scaling (MDS) for 2D projection.                       |
| [`nmf_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.nmf_planarizer)(vectors[, init, random_state])    | Non-negative Matrix Factorization (NMF) for 2D projection.              |
| [`random_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.random_planarizer)(vectors[, scale])              | Randomly projects vectors into 2D space.                                |
| [`robust_pca_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.robust_pca_planarizer)(vectors[, random_state])   | Robust PCA for 2D projection, using a robust scaler before PCA.         |
| [`semantic_pca_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.semantic_pca_planarizer)(vectors[, random_state]) | PCA for 2D projection optimized for L2-normalized semantic embeddings.  |
| [`simple_pca_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.simple_pca_planarizer)(vectors[, random_state])   | Principal Component Analysis (PCA) for 2D projection.                   |
| [`sparse_random_projection_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.sparse_random_projection_planarizer)(vectors)     | Sparse Random Projection for 2D projection.                             |
| [`spectral_embedding_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.spectral_embedding_planarizer)(vectors[, ...])    | Spectral Embedding for 2D projection.                                   |
| [`truncated_svd_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.truncated_svd_planarizer)(vectors[, ...])         | Truncated Singular Value Decomposition (SVD) for 2D projection.         |
| [`tsne_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.tsne_planarizer)(vectors[, perplexity, ...])      | t-SNE (t-Distributed Stochastic Neighbor Embedding) for 2D projection.  |
| [`umap_planarizer`](_autosummary/imbed.components.planarization.html.md#imbed.components.planarization.umap_planarizer)(vectors[, n_neighbors, ...])     | UMAP (Uniform Manifold Approximation and Projection) for 2D projection. |

### imbed.components.planarization.circular_planarizer(vectors)

Places vectors in a circle with similar vectors closer together.

* **Parameters:**
  **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points arranged in a circle

### imbed.components.planarization.constant_planarizer(embeddings)

Generate basic 2D projections from embeddings

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]

### imbed.components.planarization.factor_analysis_planarizer(vectors, random_state=42)

Factor Analysis for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Factor Analysis

### imbed.components.planarization.fast_ica_planarizer(vectors, random_state=42)

Fast Independent Component Analysis (FastICA) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from FastICA projection

### imbed.components.planarization.gaussian_random_projection_planarizer(vectors, random_state=42)

Gaussian Random Projection for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Gaussian Random Projection

### imbed.components.planarization.grid_planarizer(vectors)

Places vectors in a grid pattern.

* **Parameters:**
  **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points arranged in a grid

### imbed.components.planarization.identity_planarizer(vectors)

Returns the first two dimensions of each vector.
If vectors have fewer than 2 dimensions, pads with zeros.

* **Parameters:**
  **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points

```pycon
>>> identity_planarizer([[1, 2, 3], [4, 5, 6]])
[(1.0, 2.0), (4.0, 5.0)]
>>> identity_planarizer([[1], [2]])
[(1.0, 0.0), (2.0, 0.0)]
```

### imbed.components.planarization.isomap_planarizer(vectors, n_neighbors=5)

Isomap for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_neighbors** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of neighbors to consider for each point
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Isomap projection

### imbed.components.planarization.kernel_pca_planarizer(vectors, kernel='rbf', gamma=None, random_state=42)

Kernel PCA for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **kernel** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Kernel type (‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘cosine’)
  * **gamma** ([`float`](https://docs.python.org/3/builtins/functions.html#float) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’ kernels
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Kernel PCA projection

### imbed.components.planarization.lle_planarizer(vectors, n_neighbors=5, method='standard', random_state=42)

Locally Linear Embedding (LLE) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_neighbors** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of neighbors to consider for each point
  * **method** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – LLE algorithm to use (‘standard’, ‘hessian’, ‘modified’, or ‘ltsa’)
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from LLE projection

### imbed.components.planarization.mds_planarizer(vectors, metric=True, n_init=4, max_iter=300, random_state=42)

Multidimensional Scaling (MDS) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **metric** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, perform metric MDS; otherwise, perform nonmetric MDS
  * **n_init** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of times the SMACOF algorithm will be run with different initializations
  * **max_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Maximum number of iterations of the SMACOF algorithm
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from MDS projection

### imbed.components.planarization.nmf_planarizer(vectors, init='nndsvd', random_state=42)

Non-negative Matrix Factorization (NMF) for 2D projection.
Works only for non-negative data.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of non-negative vectors
  * **init** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Method used to initialize the procedure (‘random’, ‘nndsvd’)
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from NMF projection

### imbed.components.planarization.random_planarizer(vectors, scale=1.0)

Randomly projects vectors into 2D space.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **scale** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Scale factor for the random projections
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of random 2D points

```pycon
>>> random_planarizer([[1, 2, 3], [4, 5, 6]], scale=0.5)
[(0.37454011796069593, 0.4590583266505292), (0.32919921068172773, 0.7365648894035036)]
```

### imbed.components.planarization.robust_pca_planarizer(vectors, random_state=42)

Robust PCA for 2D projection, using a robust scaler before PCA.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Robust PCA projection

### imbed.components.planarization.semantic_pca_planarizer(vectors, random_state=None)

PCA for 2D projection optimized for L2-normalized semantic embeddings.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]

### imbed.components.planarization.simple_pca_planarizer(vectors, random_state=None)

Principal Component Analysis (PCA) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points representing the top 2 principal components

### imbed.components.planarization.sparse_random_projection_planarizer(vectors, density='auto', random_state=42)

Sparse Random Projection for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **density** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Density of the random projection matrix
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Sparse Random Projection

### imbed.components.planarization.spectral_embedding_planarizer(vectors, n_neighbors=10, affinity='nearest_neighbors', random_state=42)

Spectral Embedding for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_neighbors** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of neighbors to consider for each point (when affinity=’nearest_neighbors’)
  * **affinity** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – How to construct the affinity matrix (‘nearest_neighbors’, ‘rbf’, or ‘precomputed’)
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Spectral Embedding

### imbed.components.planarization.truncated_svd_planarizer(vectors, algorithm='randomized', n_iter=5, random_state=42)

Truncated Singular Value Decomposition (SVD) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **algorithm** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – SVD solver algorithm (‘arpack’ or ‘randomized’)
  * **n_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of iterations for randomized SVD solver
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from Truncated SVD projection

### imbed.components.planarization.tsne_planarizer(vectors, perplexity=30.0, learning_rate=200.0, n_iter=1000, metric='cosine', norm='l2', init='pca', random_state=42)

t-SNE (t-Distributed Stochastic Neighbor Embedding) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **perplexity** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – The perplexity parameter for t-SNE
  * **learning_rate** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – The learning rate for t-SNE
  * **n_iter** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of iterations
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Distance metric to use
  * **init** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Initialization method for t-SNE
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from t-SNE projection

### imbed.components.planarization.umap_planarizer(vectors, n_neighbors=15, min_dist=0.1, metric='euclidean', random_state=42)

UMAP (Uniform Manifold Approximation and Projection) for 2D projection.

* **Parameters:**
  * **vectors** ([`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – A sequence of vectors
  * **n_neighbors** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Number of neighbors to consider for each point
  * **min_dist** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum distance between points in the embedding
  * **metric** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Distance metric to use
  * **random_state** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Random seed for reproducibility
* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  A sequence of 2D points from UMAP projection


# _autosummary/imbed.components.segmentation.html.md

# imbed.components.segmentation

Segmentation functions to get text segments.

This includes tools to extract segments from text data, but also transform standard
segments sources into a format ready to be used with the imbed library.

### Functions

| [`field_values`](_autosummary/imbed.components.segmentation.html.md#imbed.components.segmentation.field_values)(segments_src, field)                  | Extract values from a dictionary of segments based on a specific field.   |
|-----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`jdict_to_segments`](_autosummary/imbed.components.segmentation.html.md#imbed.components.segmentation.jdict_to_segments)(segments_src, \*[, str_handler]) | Convert various JSON-friendly formats to segments.                        |
| [`string_lines`](_autosummary/imbed.components.segmentation.html.md#imbed.components.segmentation.string_lines)(text)                                 | Split a string into lines, removing leading and trailing whitespace.      |

### imbed.components.segmentation.field_values(segments_src, field)

Extract values from a dictionary of segments based on a specific field.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### imbed.components.segmentation.jdict_to_segments(segments_src, \*, str_handler=<function string_lines>)

Convert various JSON-friendly formats to segments.

JSON-friendly formats we handle here are:

- str (a single string)
- list (and and iterable, of strings)
- dict (whose values are strings)

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### imbed.components.segmentation.string_lines(text)

Split a string into lines, removing leading and trailing whitespace.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/imbed.components.vectorization.html.md

# imbed.components.vectorization

Vectorization functions for converting text to embeddings

### Functions

| [`constant_vectorizer`](_autosummary/imbed.components.vectorization.html.md#imbed.components.vectorization.constant_vectorizer)(segments, \*[, sleep_s])   | Generate basic constant vector for each segment                                         |
|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`simple_text_embedder`](_autosummary/imbed.components.vectorization.html.md#imbed.components.vectorization.simple_text_embedder)(texts[, stopwords])       | Extracts a set of lightweight, linguistically significant features from a text segment. |
| [`three_text_features`](_autosummary/imbed.components.vectorization.html.md#imbed.components.vectorization.three_text_features)(text)                      | Calculate simple (pseudo-)semantic features of the text.                                |

### imbed.components.vectorization.constant_vectorizer(segments, , sleep_s=0)

Generate basic constant vector for each segment

### imbed.components.vectorization.simple_text_embedder(texts, stopwords=None)

Extracts a set of lightweight, linguistically significant features from a text segment.

The function computes several features based on the input text including:

> - Total number of words.
> - Mean and median word lengths.
> - Number and ratio of stopwords.
> - Number of punctuation characters.
> - Total number of characters.
> - Number of sentences and average words per sentence.
> - Lexical diversity (ratio of unique words to total words).
> - Number of numeric tokens.
> - Number of capitalized words.
* **Parameters:**
  * **text** ([*str*](https://docs.python.org/3/builtins/stdtypes.html#str)) – The text segment to analyze.
  * **stopwords** ([*set*](https://docs.python.org/3/builtins/stdtypes.html#set) *,* *optional*) – A set of stopwords for counting. Defaults to an empty set.
* **Returns:**
  A list of numerical features representing the text, in the following order:
  : [num_words, mean_word_length, median_word_length, num_stopwords, stopword_ratio,
    num_punctuation, num_characters, num_sentences, avg_words_per_sentence,
    lexical_diversity, num_numeric_tokens, num_capitalized_words]
* **Return type:**
  [*list*](https://docs.python.org/3/builtins/stdtypes.html#list)

### Example

```pycon
>>> sample_text = "Hello, world! This is an example text, with 123 numbers and various punctuation marks."
>>> sample_stopwords = {'this', 'is', 'an', 'with', 'and'}
>>> simple_text_embedder(sample_text, sample_stopwords)
[14, 5.21..., 6, 5, 0.35..., 4, 86, 2, 7.0, 1.0, 1, 2]
```

### imbed.components.vectorization.three_text_features(text)

Calculate simple (pseudo-)semantic features of the text.
This is meant to be used as a placeholder vectorizer (a.k.a. embedding function) for
text segments, for testing mainly.

```pycon
>>> three_text_features("Hello, world!")
(2, 12, 2)
```

* **Return type:**
  [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]


# _autosummary/imbed.data_prep.html.md

# imbed.data_prep

Data preparation

### Functions

| [`clusters_df`](_autosummary/imbed.data_prep.html.md#imbed.data_prep.clusters_df)(embeddings[, n_clusters])          | Convenience function to get a table with cluster indices for different cluster sizes.   |
|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`kmeans_cluster_indices`](_autosummary/imbed.data_prep.html.md#imbed.data_prep.kmeans_cluster_indices)(data_src[, n_clusters]) | Cluster data using KMeans or MiniBatchKMeans depending on the input type.               |
| [`re_clusters`](_autosummary/imbed.data_prep.html.md#imbed.data_prep.re_clusters)(X, labels, k)                      | Re-cluster the dataset X to have exactly k clusters.                                    |

### Classes

| `ImbedArtifactsMixin`()   |    |
|---------------------------|----|

### imbed.data_prep.clusters_df(embeddings, n_clusters=[5, 8, 13, 21, 34])

Convenience function to get a table with cluster indices for different cluster sizes.

### imbed.data_prep.kmeans_cluster_indices(data_src, n_clusters=8, \*\*learner_kwargs)

Cluster data using KMeans or MiniBatchKMeans depending on the input type.

If `data_src` is a numpy array, uses `KMeans`. If `data_src` is an iterable
of numpy arrays, uses `MiniBatchKMeans` and processes the batches iteratively.

### Parameters

- data_src: A numpy array, an iterable of numpy arrays (batches), or a factory thereof.
- n_clusters: Number of clusters for KMeans.
- learner_kwargs: Additional arguments for KMeans or MiniBatchKMeans.

### Returns

- ```
  labels_
  ```

  : Cluster labels for the data.

### Example

```pycon
>>> np.random.seed(0)  # Set seed for reproducibility
>>> data = np.array([[1, 2], [1, 4], [1, 0], [1, 1], [10, 4], [10, 0]])
>>> labels = kmeans_cluster_indices(data, n_clusters=2, random_state=42)
>>> [sorted(data[labels == i].tolist()) for i in np.unique(labels)]
[[[1, 0], [1, 1], [1, 2], [1, 4]], [[10, 0], [10, 4]]]
```

For MiniBatchKMeans case:

```pycon
>>> np.random.seed(0)  # Set seed for reproducibility
>>> get_data_batches = lambda: (data[i:i+2] for i in range(0, len(data), 2))
>>> labels = kmeans_cluster_indices(get_data_batches, n_clusters=2, random_state=42)
>>> [sorted(data[labels == i].tolist()) for i in np.unique(labels)]
[[[1, 0], [1, 1], [1, 2], [1, 4]], [[10, 0], [10, 4]]]
```

### imbed.data_prep.re_clusters(X, labels, k)

Re-cluster the dataset X to have exactly k clusters.

### Parameters

- X: array-like of shape (n_samples, n_features)
  : The input data.
- labels: array-like of shape (n_samples,)
  : Cluster labels for each point in the dataset.
- k: int
  : The desired number of clusters.

### Returns

- new_labels: array-like of shape (n_samples,)
  : The new cluster labels for the dataset.

* Handling Cases:
  : * Equal Clusters: If the current number of clusters equals k, the function
      returns the original labels.
    * More Clusters: If the current number of clusters is more than k, it merges
      clusters using hierarchical clustering (AgglomerativeClustering).
    * Fewer Clusters: If the current number of clusters is fewer than k, it splits
      the largest cluster iteratively until the desired number of clusters is reached.
* Merging Clusters:
  : * Uses hierarchical clustering on the centroids of the current clusters to
      merge them down to k clusters.
* Splitting Clusters:
  : * Iteratively splits the largest cluster using AgglomerativeClustering until
      the number of clusters reaches k.


# _autosummary/imbed.html.md

# imbed

Tools for imbeddings

### Modules

| [`base`](_autosummary/imbed.base.html.md#module-imbed.base)                               | Base functionality of imbded.                                                   |
|-------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`components`](_autosummary/imbed.components.html.md#module-imbed.components)                   | Components for imbed applications.                                              |
| [`data_prep`](_autosummary/imbed.data_prep.html.md#module-imbed.data_prep)                     | Data preparation                                                                |
| [`imbed_project`](_autosummary/imbed.imbed_project.html.md#module-imbed.imbed_project)             | Project interface for text embedding system.                                    |
| [`imbed_types`](_autosummary/imbed.imbed_types.html.md#module-imbed.imbed_types)                 | Types for imbed                                                                 |
| [`mdat`](_autosummary/imbed.mdat.html.md#module-imbed.mdat)                               | Data access and preparation modules                                             |
| [`oa_batch_embeddings`](_autosummary/imbed.oa_batch_embeddings.html.md#module-imbed.oa_batch_embeddings) | Simplified interface for computing embeddings in bulk using OpenAI's batch API. |
| [`segmentation_util`](_autosummary/imbed.segmentation_util.html.md#module-imbed.segmentation_util)     | Tools for segmentation, batching, chunking...                                   |
| [`stores_util`](_autosummary/imbed.stores_util.html.md#module-imbed.stores_util)                 | Utils for stores                                                                |
| [`tools`](_autosummary/imbed.tools.html.md#module-imbed.tools)                             | Tools around imbeddings tasks                                                   |
| [`util`](_autosummary/imbed.util.html.md#module-imbed.util)                               | Utils for imbed package.                                                        |
| [`vector_db`](_autosummary/imbed.vector_db.html.md#module-imbed.vector_db)                     | Facades for vector databases                                                    |


# _autosummary/imbed.imbed_project.html.md

# imbed.imbed_project

Project interface for text embedding system.

This module provides the core Project class that manages segments, embeddings,
planarizations, and clusterings with automatic invalidation and async computation
support via the au framework.

### Module Attributes

| [`COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.COMPONENT_KINDS)                | The component kinds [`Project.compute()`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project.compute) knows how to dispatch.                                                                                            |
|---------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`ASYNC_CAPABLE_COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.ASYNC_CAPABLE_COMPONENT_KINDS)  | The subset of [`COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.COMPONENT_KINDS) whose work can be handed to the async (`au`) backend.                                                                     |
| [`RESULT_STORE_BY_COMPONENT_KIND`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.RESULT_STORE_BY_COMPONENT_KIND) | Which [`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project) store each component kind's results are filed in, under the caller's `save_key`.                                                          |
| [`MissingEmbeddingsPolicy`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MissingEmbeddingsPolicy)        | What [`Project.compute()`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project.compute) may do when the default planarizer/clusterer input it assembles is missing some segments (their embeddings have not landed yet). |
| [`MISSING_EMBEDDINGS_POLICIES`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MISSING_EMBEDDINGS_POLICIES)    | [`MissingEmbeddingsPolicy`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MissingEmbeddingsPolicy)'s members, for runtime validation and messages.                                                                                 |
| [`DFLT_ON_MISSING_EMBEDDINGS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.DFLT_ON_MISSING_EMBEDDINGS)     | Default reaction to a partial default input.                                                                                                                                                             |
| [`MAX_MISSING_KEYS_SHOWN`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MAX_MISSING_KEYS_SHOWN)         | How many missing segment keys an error/warning names before eliding the rest.                                                                                                                            |

### Functions

| `DFLT_GET_PROJECT_MALL`([project_id])                                                          |                                                         |
|------------------------------------------------------------------------------------------------|---------------------------------------------------------|
| [`clear_store`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.clear_store)(store)                            | Clear all items in a store                              |
| [`get_local_mall`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.get_local_mall)([project_id, mall_keys, ...])  | Get the user stores for the package.                    |
| [`get_mall`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.get_mall)([project_id, get_project_mall, ...]) | Get the registry mall containing all function stores    |
| `get_ram_project_mall`([project_id])                                                           |                                                         |
| `named_partial`(func, \*args[, \_\_name_\_])                                                   |                                                         |
| [`validate_component_kind_tables`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.validate_component_kind_tables)()              | Assert the component-kind tables agree with each other. |
| `validate_mall_keys`(mall)                                                                     |                                                         |
| `validate_mall_kinds`()                                                                        |                                                         |

### Classes

| [`PartializedFuncs`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.PartializedFuncs)(store)              | A mapping that allows retrieval of functions with optional partial application.   |
|---------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| [`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project)([segments, embeddings, ...]) | Central project interface - facade for all operations.                            |
| [`Projects`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Projects)([store_factory])            | Container for projects with MutableMapping interface.                             |

### imbed.imbed_project.ASYNC_CAPABLE_COMPONENT_KINDS *= frozenset({'embedder'})*

The subset of [`COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.COMPONENT_KINDS) whose work can be handed to the async (`au`)
backend. Single source of truth on purpose: [`Project.compute()`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project.compute) both *resolves*
and *validates* `async_mode` against this one name, so the two cannot drift — and
drift between them is exactly how `async_mode=True` came to be silently downgraded
to a synchronous run for the kinds the async branch did not cover.

### imbed.imbed_project.COMPONENT_KINDS *= ('embedder', 'planarizer', 'clusterer')*

The component kinds [`Project.compute()`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project.compute) knows how to dispatch. Each name
`kind` needs a `Project.{kind}s` registry attribute to resolve components from,
and a way to store its results (see [`RESULT_STORE_BY_COMPONENT_KIND`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.RESULT_STORE_BY_COMPONENT_KIND)).

### imbed.imbed_project.DFLT_ON_MISSING_EMBEDDINGS *: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal)['raise', 'warn', 'ignore']* *= 'warn'*

Default reaction to a partial default input. `"warn"` rather than `"raise"`
because “process what is ready” is a legitimate thing to want — pending embeddings
are the normal state of an async project — but it must never be what a caller gets
*without knowing*, since a result covering part of the project is indistinguishable
from one covering all of it. `"raise"` is one keyword away for all-or-nothing
callers, `"ignore"` for those who already know the input is partial.

### imbed.imbed_project.MAX_MISSING_KEYS_SHOWN *= 5*

How many missing segment keys an error/warning names before eliding the rest.

### imbed.imbed_project.MISSING_EMBEDDINGS_POLICIES *= ('raise', 'warn', 'ignore')*

[`MissingEmbeddingsPolicy`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MissingEmbeddingsPolicy)’s members, for runtime validation and messages.

### imbed.imbed_project.MissingEmbeddingsPolicy

What [`Project.compute()`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project.compute) may do when the default planarizer/clusterer input it
assembles is missing some segments (their embeddings have not landed yet).

alias of [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[‘raise’, ‘warn’, ‘ignore’]

### *class* imbed.imbed_project.PartializedFuncs(store)

Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)]

A mapping that allows retrieval of functions with optional partial application.

```pycon
>>> store = {'add': lambda x, y: x + y, 'subtract': lambda x, y: x - y}
>>> partialized_ops = PartializedFuncs(store)
```

When using a non-dict key, it will return the function directly:

```pycon
>>> func1 = partialized_ops['add']
>>> func1(2, 3)
5
```

If the key is a dictionary with one item, it will return a partial function:

```pycon
>>> func2 = partialized_ops[{'add': {'y': 3}}]
>>> func2(2)
5
```

### *class* imbed.imbed_project.Project(segments=dict(), embeddings=dict(), planar_coords=dict(), cluster_indices=dict(), embedders=<factory>, planarizers=<factory>, clusterers=<factory>, default_embedder='default', \_active_computations=dict(), \_invalidation_cascade=True, \_auto_compute_embeddings=True, \_async_embeddings=False, \_async_base_path=None, \_id=None, \_async_backend=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Central project interface - facade for all operations.

Manages segments, embeddings, planarizations, and clusterings with
automatic computation and invalidation cascade. Supports both synchronous
and asynchronous embedding computation via the au framework.

#### add_segments(segments)

Add segments and trigger embedding computation.

* **Parameters:**
  **segments** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`SegmentKey` (`KT`), `Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))]) – Mapping of segment keys to segment text
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`SegmentKey` (`KT`)]
* **Returns:**
  List of segment keys that were added

#### cleanup_async_storage()

Clean up expired async computation results.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

#### compute(component_kind, component_key, data=None, , save_key=None, async_mode=None, on_missing_embeddings='warn')

Generic computation dispatcher.

Runs the component the caller named, on the data the caller gave, in the mode
the caller asked for — or raises saying why it cannot. It never quietly
substitutes a different component, a different mode, or a different input:
every path here returns the same kind of save key, so a silent substitution
would be indistinguishable from success.

* **Parameters:**
  * **component_kind** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Type of component; one of [`COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.COMPONENT_KINDS).
  * **component_key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Key of the component in the corresponding registry.
  * **data** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping) | [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Input data. If None, an appropriate default is used (see below).
    For an embedder it must be a `Mapping` of segment key -> segment,
    since embeddings are stored per segment key and a bare sequence carries
    no keys to store them under.
  * **save_key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Key to file the results under. Generated (uniquely) if not given.
    An explicitly given key is honoured as given, and so overwrites any
    previous result stored under it.
  * **async_mode** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Whether to run asynchronously. `None` (the default) uses the
    project’s `_async_embeddings` setting, which applies only to kinds in
    [`ASYNC_CAPABLE_COMPONENT_KINDS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.ASYNC_CAPABLE_COMPONENT_KINDS). Passing `True` for any other
    kind raises: those kinds have no async path, and running them
    synchronously would silently contradict an explicit request.
  * **on_missing_embeddings** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'raise'`, `'warn'`, `'ignore'`]) – What to do when the *default* input for a
    planarizer/clusterer is incomplete because some segments have no
    embedding yet — one of [`MISSING_EMBEDDINGS_POLICIES`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.MISSING_EMBEDDINGS_POLICIES), default
    [`DFLT_ON_MISSING_EMBEDDINGS`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.DFLT_ON_MISSING_EMBEDDINGS). Only consulted when `data` is
    None; when you supply `data`, its completeness is yours to decide.
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)
* **Returns:**
  The save key. For a planarizer or clusterer this is the key its results are
  stored under, in `planar_coords` / `cluster_indices` respectively. For
  an embedder it identifies the *computation*: embedding results are merged
  into `embeddings` under their own segment keys, sync or async alike.

Default input by kind:

> - embedder: all of `segments`.
> - planarizer, clusterer: the embeddings of every segment that has one, in
>   segment order (see `on_missing_embeddings` for the ones that do not).

How results are attributed to segments:
: A component returning a mapping is taken at its word. A component returning
  a plain sequence is matched to its input by position — which requires
  knowing the input’s keys, so the sequence case is supported when `data`
  was defaulted or given as a mapping, and refused (rather than guessed) when
  `data` was given as a bare sequence.

* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – unknown `component_kind`, unknown `component_key`, async
        requested for a kind that cannot do it, an unknown
        `on_missing_embeddings`, or results that cannot be attributed to
        segments.
  * [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError) – embedder `data` that is not a Mapping.
* **Return type:**
  [*str*](https://docs.python.org/3/builtins/stdtypes.html#str)

#### *property* embedding_status *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [int](https://docs.python.org/3/builtins/functions.html#int)]*

Get counts of embedding statuses.

Returns counts of: present, missing, computing

#### get_computation_status(computation_id)

Get status of a tracked async computation.

* **Return type:**
  `ComputationStatus` | [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### get_embeddings(segment_keys=None)

Get embeddings for specified segments (or all if None)

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]

#### list_active_computations()

List IDs of active async computations.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### set_async_mode(enabled)

Enable or disable async embedding computation.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### *property* valid_embeddings *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[KT, [Sequence](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[float](https://docs.python.org/3/builtins/functions.html#float)]]*

Get all available computed embeddings

#### wait_for_embeddings(segment_keys=None, timeout=10.0, poll_interval=0.1)

Wait for embeddings to be available.

This works for both sync and async modes - in sync mode, embeddings
are immediately available; in async mode, we poll until they appear.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### *class* imbed.imbed_project.Projects(store_factory=<class 'dict'>)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project)]

Container for projects with MutableMapping interface.

```pycon
>>> projects = Projects()
>>> p = Project(_id='test', segments={}, embeddings={},
...             planar_coords={}, cluster_indices={},
...             embedders={}, planarizers={}, clusterers={})
>>> projects["test"] = p
>>> list(projects)
['test']
>>> projects["test"]._id
'test'
```

#### append(project)

Append a project to the collection.

* **Parameters:**
  **project** ([`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project)) – Project instance to add
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### create_project(\*, project_id=None, segments_store_factory=<class 'dict'>, embeddings_store_factory=<class 'dict'>, planar_store_factory=<class 'dict'>, cluster_store_factory=<class 'dict'>, embedders=None, planarizers=None, clusterers=None, async_embeddings=True, async_base_path=None, async_backend=None, overwrite=False)

Create and add a new project.

* **Parameters:**
  * **project_id** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – ID for the new project (optional)
  * **\*_store_factory** – Factory functions for various stores
  * **embedders** ([`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Component registry for embedders
  * **planarizers** ([`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Component registry for planarizers
  * **clusterers** ([`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Component registry for clusterers
  * **async_embeddings** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether to use async embedding computation
  * **async_base_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Base path for au async computation storage
  * **async_backend** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Backend for async computation (StdLibQueueBackend, RQ, etc)
  * **overwrite** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, replace any existing project with the same id
* **Return type:**
  [`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project)
* **Returns:**
  The created Project instance

### imbed.imbed_project.RESULT_STORE_BY_COMPONENT_KIND *= {'clusterer': 'cluster_indices', 'planarizer': 'planar_coords'}*

Which [`Project`](_autosummary/imbed.imbed_project.html.md#imbed.imbed_project.Project) store each component kind’s results are filed in, under the
caller’s `save_key`. `"embedder"` is deliberately absent: embeddings are merged
into `Project.embeddings` under their *segment* keys, so an embedder’s
`save_key` names the computation rather than a stored value.

### imbed.imbed_project.clear_store(store)

Clear all items in a store

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### imbed.imbed_project.get_local_mall(project_id='default_project', \*, mall_keys=('misc', 'segments', 'embeddings', 'clusters', 'planar_embeddings', 'statuses', 'cluster_labels'), default_store_maker=functools.partial(<function mk_blob_store_for_path>, path_to_bytes_store=<class 'dol.filesys.Files'>, base_store_wrap=functools.partial(<function extension_based_wrap>, extension_to_decoder={'csv': functools.partial(<function read_from_bytes>, functools.partial(<function read_csv>, index_col=None), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'txt': <method 'decode' of 'bytes' objects>, 'tsv': functools.partial(<function read_from_bytes>, functools.partial(<function read_csv>, sep='\\t', index_col=None), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'parquet': functools.partial(<function read_from_bytes>, <function read_parquet>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'json': <function loads>, 'html': functools.partial(<function read_from_bytes>, functools.partial(<function read_html>, index_col=0), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'p': functools.partial(<function read_from_bytes>, <built-in function load>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'pickle': functools.partial(<function read_from_bytes>, <built-in function load>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'pkl': <built-in function loads>, 'xml': functools.partial(<function read_from_bytes>, <function read_xml>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'sql': functools.partial(<function read_from_bytes>, <function read_sql>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'sqlite': functools.partial(<function read_from_bytes>, <function read_sql>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'feather': functools.partial(<function read_from_bytes>, <function read_feather>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'stata': functools.partial(<function read_from_bytes>, functools.partial(<function read_stata>, index_col=0), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'dta': functools.partial(<function read_from_bytes>, functools.partial(<function read_stata>, index_col=0), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'sas': functools.partial(<function read_from_bytes>, <function read_sas>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'h5': functools.partial(<function read_from_bytes>, <function read_hdf>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'hdf5': functools.partial(<function read_from_bytes>, <function read_hdf>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'xls': functools.partial(<function read_from_bytes>, functools.partial(<function read_excel>, index_col=0), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'xlsx': functools.partial(<function read_from_bytes>, functools.partial(<function read_excel>, index_col=0), buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'orc': functools.partial(<function read_from_bytes>, <function read_orc>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'sav': functools.partial(<function read_from_bytes>, <function read_spss>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'mat': functools.partial(<function read_from_bytes>, <function mat_bytes_to_dataframe>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), 'arrow': functools.partial(<function read_from_bytes>, <function arrow_bytes_to_dataframe>, buffer_arg_position=0, buffer_arg_name=None, io_buffer_cls=<class '_io.BytesIO'>), '': <function loads>, 'dill': <function loads>}, extension_to_encoder={'csv': functools.partial(<function written_bytes>, functools.partial(<function NDFrame.to_csv>, index=False), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'txt': <method 'encode' of 'str' objects>, 'tsv': functools.partial(<function written_bytes>, functools.partial(<function NDFrame.to_csv>, index=False, sep='\\t', escapechar='\\\\', quotechar='"'), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'json': <dol.util.Pipe object>, 'html': functools.partial(<function written_bytes>, functools.partial(<function DataFrame.to_html>, index=True), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'p': functools.partial(<function written_bytes>, <function NDFrame.to_pickle>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'pickle': functools.partial(<function written_bytes>, <function NDFrame.to_pickle>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'pkl': <built-in function dumps>, 'npy': functools.partial(<function written_bytes>, <function save>, obj_arg_position_in_writer=1, io_buffer_cls=<class '_io.BytesIO'>), 'zip': <function save_df_to_zipped_tsv>, 'h5': functools.partial(<function written_bytes>, <function NDFrame.to_hdf>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'hdf5': functools.partial(<function written_bytes>, <function NDFrame.to_hdf>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'stata': functools.partial(<function written_bytes>, functools.partial(<function DataFrame.to_stata>, write_index=True), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'dta': functools.partial(<function written_bytes>, functools.partial(<function DataFrame.to_stata>, write_index=True), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'sql': functools.partial(<function written_bytes>, <function NDFrame.to_sql>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'sqlite': functools.partial(<function written_bytes>, <function NDFrame.to_sql>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'gbq': functools.partial(<function written_bytes>, <function \_to_gbq_unavailable>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'xls': functools.partial(<function written_bytes>, functools.partial(<function NDFrame.to_excel>, index=True), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'xlsx': functools.partial(<function written_bytes>, functools.partial(<function NDFrame.to_excel>, index=True), obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'xml': functools.partial(<function written_bytes>, <function DataFrame.to_xml>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'parquet': functools.partial(<function written_bytes>, <function cast_to_parquet>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'feather': functools.partial(<function written_bytes>, <function DataFrame.to_feather>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'orc': functools.partial(<function written_bytes>, <function DataFrame.to_orc>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'mat': functools.partial(<function written_bytes>, <function dataframe_to_mat_bytes>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), 'arrow': functools.partial(<function written_bytes>, <function dataframe_to_arrow_bytes>, obj_arg_position_in_writer=0, io_buffer_cls=<class '_io.BytesIO'>), '': <function dumps>, 'dill': <function dumps>}), filename_suffix='.dill'))

Get the user stores for the package.

* **Returns:**
  A dictionary containing paths to various user stores.
* **Return type:**
  [*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)

### imbed.imbed_project.get_mall(project_id='default_project', \*, get_project_mall=<function get_ram_project_mall>, include_signature_stores=True)

Get the registry mall containing all function stores

* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)]]
* **Returns:**
  A dictionary of stores, each containing registered processing functions

### imbed.imbed_project.validate_component_kind_tables()

Assert the component-kind tables agree with each other.

They are read in different places — registry lookup, async gating, result storage —
and a kind present in one but absent from another is precisely the failure mode
this module keeps hitting: a request that resolves fine and is then dropped.


# _autosummary/imbed.imbed_types.html.md

# imbed.imbed_types

Types for imbed

### Classes

| [`Embed`](_autosummary/imbed.imbed_types.html.md#imbed.imbed_types.Embed)(\*args, \*\*kwargs)   | A callable that embeds text.   |
|------------------------------------------------------------------------------|--------------------------------|

### *class* imbed.imbed_types.Embed(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

A callable that embeds text.


# _autosummary/imbed.mdat.html.md

# imbed.mdat

Data access and preparation modules

Forwards to the imbed_data_prep package.


# _autosummary/imbed.oa_batch_embeddings.html.md

# imbed.oa_batch_embeddings

Simplified interface for computing embeddings in bulk using OpenAI’s batch API.

This module provides a clean, reusable interface for generating embeddings from
text segments using OpenAI’s batch API, handling the async nature of the API
and providing status monitoring, error handling, and result aggregation.


# _autosummary/imbed.segmentation_util.html.md

# imbed.segmentation_util

Tools for segmentation, batching, chunking…

The words segmentation, batching, chunking, along with slicing, partitioning, etc.
are often used interchangeably in the context of data processing.
Here we will try to clarify the meaning of these terms in the context of our package

We will use the term “segmentation” when the process is about producing (smaller)
segments of text from a (larger) input text.

We will use the term “batching” when the process is about producing batches of
data from a data input stream (for example, an iterable of text segments that need
to be embedded, but we need to batch them to avoid resource limitation issues).

We will use the term “chunking” to denote a more general process of dividing a
sequence of items into chunks, usually of a fixed size.

### Functions

| [`chunk_mapping`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.chunk_mapping)(mapping[, chunker])                 | Use the chunker to chunk the items of mapping, yielding sub-mappings                                                                                                            |
|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ensure_chunker`(chunker)                                                                          |                                                                                                                                                                                 |
| [`fixed_step_chunker`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.fixed_step_chunker)(it, chk_size[, chk_step, ...]) | a function to get (an iterator of) segments (bt, tt) of chunks from an iterator (or list) of the for [it_1, it_2...], given a chk_size, chk_step, and a start_at and a stop_at. |
| [`rechunker`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.rechunker)(chks, chk_size[, chk_step, ...])        | Takes an iterable of chks and produces another iterable of chunks.                                                                                                              |
| [`wrapped_chunker`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.wrapped_chunker)(src, chunker, \*[, ingress, ...]) | A function to extend chunking functionality to any source of iterables, with the ability to wrap the chunks in a function before yielding them.                                 |
| [`yield_from`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.yield_from)(it)                                    | A function to do `yield from it`.                                                                                                                                               |

### Classes

| [`SegmentStore`](_autosummary/imbed.segmentation_util.html.md#imbed.segmentation_util.SegmentStore)(docs, segment_keys)   | A class to represent a mapping between segments and documents.   |
|-------------------------------------------------------------------------------------|------------------------------------------------------------------|

### *class* imbed.segmentation_util.SegmentStore(docs, segment_keys)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A class to represent a mapping between segments and documents.

### imbed.segmentation_util.chunk_dataframe(src, chunker, \*, ingress=operator.methodcaller('iterrows'), egress=<function identity>)

Yield chunks of rows from a DataFrame.
The yielded chunks are lists of (index, row) tuples.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`ChunkBasedObj`]

### imbed.segmentation_util.chunk_mapping(mapping, chunker=None)

Use the chunker to chunk the items of mapping, yielding sub-mappings

* **Parameters:**
  * **chunker** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`IterableToChunk`], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`Chunk`]], [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – a chunker function
  * **mapping** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`KT`, `T`]) – a mapping of items
* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`KT`, `T`]]
* **Returns:**
  an iterator of sub-mappings in the form of dictionaries

### Examples

```pycon
>>> from functools import partial
>>> chunker = partial(fixed_step_chunker, chk_size=2)
>>> mapping = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
>>> list(chunk_mapping(mapping, chunker))
[{1: 'a', 2: 'b'}, {3: 'c', 4: 'd'}, {5: 'e'}]
```

### imbed.segmentation_util.fixed_step_chunker(it, chk_size, chk_step=None, \*, start_at=None, stop_at=None, return_tail=True, chunk_egress=<class 'list'>)

a function to get (an iterator of) segments (bt, tt) of chunks from an iterator
(or list) of the for [it_1, it_2…], given a chk_size, chk_step, and a start_at
and a stop_at.
The start_at, stop_at act like slices indices for a list: start_at is included
and stop_at is excluded

* **Parameters:**
  * **it** ([`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`T`]) – iterator of elements of any type
  * **chk_size** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – length of the chunks
  * **chk_step** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – step between chunks
  * **start_at** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – index of the first term of the iterator at which we begin building
    the chunks (inclusive)
  * **stop_at** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – index of the last term from the iterator included in the chunks
  * **return_tail** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – if set to false, only the chunks with max element with index
    less than stop_at are yielded
    if set to true, any chunks with minimum index value no more than stop_at are
    returned but they contain term with index no more than stop_at
* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[`T`]]
* **Returns:**
  an iterator of the chunks

1. If stop_at is not None and return_tail is False:
   : will return all full chunks with maximum element index less than stop_at
     or until the iterator is exhausted. Only full chunks are returned here.
2. If stop_at is not None and return_tail is True:
   : will return all full chunks as above along with possibly cut off chunks
     containing one term whose index is stop_at-1 or one (last) term which is the
     last element of it
3. If stop_at is None and return_tail is False:
   : will return all full chunks with maximum element index less or equal to the last
     element of it
4. If stop_at is None and return_tail is True:
   : will return all full chunks with maximum element index less or equal to the last
     element of it plus cut off chunks whose maximum term index is the last term of it

### Examples

```pycon
>>> list(fixed_step_chunker([1, 2, 3, 4, 5, 6, 7, 8], chk_size=3))
[[1, 2, 3], [4, 5, 6], [7, 8]]
>>> list(fixed_step_chunker([1, 2, 3, 4, 5, 6, 7, 8], chk_size=3, return_tail=False))
[[1, 2, 3], [4, 5, 6]]
>>> list(fixed_step_chunker([1, 2, 3, 4, 5, 6, 7, 8], chk_size=3))
[[1, 2, 3], [4, 5, 6], [7, 8]]
>>> list(fixed_step_chunker([1, 2, 3, 4, 5, 6, 7, 8], chk_size=3, chk_step=2, return_tail=False))
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
>>> chunks = fixed_step_chunker(
...     range(1, 17, 1), chk_size=3, chk_step=4,
...     start_at=1, stop_at=7,
... )
>>> list(chunks)
[[2, 3, 4], [6, 7]]
```

### imbed.segmentation_util.rechunker(chks, chk_size, chk_step=None, start_at=None, stop_at=None, return_tail=False)

Takes an iterable of chks and produces another iterable of chunks.
The chunks generated by the input chks iterable is assumed to be gap-less and without overlap,
but these do not need to be of fixed size.
The output will be though.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`Chunk`]

### imbed.segmentation_util.wrapped_chunker(src, chunker, \*, ingress=<function identity>, egress=<function identity>)

A function to extend chunking functionality to any source of iterables,
with the ability to wrap the chunks in a function before yielding them.

* **Parameters:**
  * **src** (`IterableSrc`) – an iterable of items
  * **chunker** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`IterableToChunk`], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`Chunk`]], [`int`](https://docs.python.org/3/builtins/functions.html#int)]) – a chunker function or an integer
  * **ingress** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`IterableSrc`], `IterableToChunk`]) – a function to wrap the input iterable
  * **egress** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`Chunk`], `ChunkBasedObj`]) – a function to wrap the output chunks
* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`ChunkBasedObj`]
* **Returns:**
  an iterator of chunk-based objects

### Examples

```pycon
>>> list(wrapped_chunker(range(1, 6), 2))
[[1, 2], [3, 4], [5]]
```

### imbed.segmentation_util.yield_from(it)

A function to do `yield from it`.
Looks like a chunker of chk_size=1, but careful, elements are not wrapped in lists.


# _autosummary/imbed.stores_util.html.md

# imbed.stores_util

Utils for stores

### Functions

| `extension_based_mall_maker`([...])          |    |
|----------------------------------------------|----|
| `mk_blob_store_for_path`(path[, space, ...]) |    |


# _autosummary/imbed.tools.html.md

# imbed.tools

Tools around imbeddings tasks

### Functions

| [`batch_processing_manager`](_autosummary/imbed.tools.html.md#imbed.tools.batch_processing_manager)(oa_stores, batches, ...)   | Sets up the ProcessingManager with the necessary functions and parameters.                                                                              |
|------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`cluster_labeler`](_autosummary/imbed.tools.html.md#imbed.tools.cluster_labeler)(df, \*[, ...])                      | A function that labels clusters give a DataFrame of text segments & cluster indices                                                                     |
| [`compute_embeddings_in_bulk`](_autosummary/imbed.tools.html.md#imbed.tools.compute_embeddings_in_bulk)(text_segments, \*)       | Given a dictionary of {id: text_segment, ...}, uploads the data, submits it for batch embedding computation, and retrieves the result once complete.    |
| `get_batch_obj`(oa_stores, batch)                                                                    |                                                                                                                                                         |
| [`get_output_file_data`](_autosummary/imbed.tools.html.md#imbed.tools.get_output_file_data)(batch, \*, oa_stores[, ...])   | Get the output file data for a batch, along with its status.                                                                                            |
| `on_completed_batch`(oa_stores, batch_obj)                                                           |                                                                                                                                                         |
| [`process_batches`](_autosummary/imbed.tools.html.md#imbed.tools.process_batches)(oa_stores, batches, \*[, ...])      | Processes a set of batches using ProcessingManager, checking their status in cycles until all are completed or the maximum number of cycles is reached. |

### Classes

| [`ClusterLabeler`](_autosummary/imbed.tools.html.md#imbed.tools.ClusterLabeler)(\*[, ...])   | A class that labels clusters give a DataFrame of text segments & cluster indices   |
|------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| `EmbeddingBatchManager`(text_segments, \*[, ...])                            |                                                                                    |

### *class* imbed.tools.ClusterLabeler(, truncate_segment_at_index=100, n_samples=99, context=' ', n_words=4, cluster_idx_col='cluster_idx', get_row_segments='segment', max_unique_clusters=40, prompt='\\nI want a title for the data below.\\nHave the title be no more than {n_words} words long.\\nI will give you the context of the data. \\nYou should not include this context in the title. \\nReaders of the title will assume the context, so only particulars of \\nthe data should be included in the title.\\nThe data represents a sample of the text segments of a particular topic.\\nYou should infer what the topic is and the title should be a very short \\ndescription of how that topic my differ from other topics of the same context.\\nAgain, your title should reflect the particulars of the text segments \\nwithin the given context, not the context itself.\\n\\nDo not surround the title with quotes or brackets or such.\\n\\nThis is the context of the data: {context}.\\n                \\nThe data:\\n                \\n{data}\\n')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A class that labels clusters give a DataFrame of text segments & cluster indices

#### descriptions_of_segments(segments)

A method that returns the descriptions of a cluster

#### label_clusters(df)

A method that returns labels for all clusters of a DataFrame

#### titles_of_segments(segments)

A method that returns the labels of a cluster

### imbed.tools.batch_processing_manager(oa_stores, batches, status_checking_frequency, max_cycles, get_output_file_data)

Sets up the ProcessingManager with the necessary functions and parameters.

* **Parameters:**
  * **oa_stores** – The OpenAI stores object for API interactions.
  * **batches** ([`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[Batch]) – A set of batch objects to process.
  * **status_checking_frequency** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum number of seconds per cycle.
  * **max_cycles** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Maximum number of cycles to perform.
  * **get_output_file_data** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – Function to get batch status and output data.
* **Returns:**
  An instance of ProcessingManager.
* **Return type:**
  `ProcessingManager`

### imbed.tools.cluster_labeler(df, , truncate_segment_at_index=100, n_samples=99, context=' ', n_words=4, cluster_idx_col='cluster_idx', get_row_segments='segment', max_unique_clusters=40, prompt='\\nI want a title for the data below.\\nHave the title be no more than {n_words} words long.\\nI will give you the context of the data. \\nYou should not include this context in the title. \\nReaders of the title will assume the context, so only particulars of \\nthe data should be included in the title.\\nThe data represents a sample of the text segments of a particular topic.\\nYou should infer what the topic is and the title should be a very short \\ndescription of how that topic my differ from other topics of the same context.\\nAgain, your title should reflect the particulars of the text segments \\nwithin the given context, not the context itself.\\n\\nDo not surround the title with quotes or brackets or such.\\n\\nThis is the context of the data: {context}.\\n                \\nThe data:\\n                \\n{data}\\n')

A function that labels clusters give a DataFrame of text segments & cluster indices

### imbed.tools.compute_embeddings_in_bulk(text_segments, \*, batcher=1000, poll_interval=5.0, max_polls=None, verbosity=1, log_func=<built-in function print>, store_factories={'completed_batches': <class 'list'>, 'embeddings': <class 'dict'>, 'submitted_batches': <class 'dict'>}, misc_store_factory=<class 'dict'>, imbed_task_dict_kwargs={'custom_id_per_text': False})

Given a dictionary of {id: text_segment, …}, uploads the data, submits it for batch
embedding computation, and retrieves the result once complete.

* **Parameters:**
  * **text_segments** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[`Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)), [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`SegmentKey` (`KT`), `Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))]]) – A dictionary where keys are unique identifiers and values are text segments.
  * **poll_interval** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Time interval (in seconds) to wait between polling checks for batch completion.
* **Returns:**
  A dictionary with {id: embedding_vector, …} for each input text segment.
* **Return type:**
  [*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict)

### imbed.tools.get_output_file_data(batch, \*, oa_stores, get_batch_obj=<function get_batch_obj>)

Get the output file data for a batch, along with its status.
Returns a tuple of (status, data), where data is None if not completed.

### imbed.tools.process_batches(oa_stores, batches, \*, status_checking_frequency=5.0, max_cycles=None, get_output_file_data=<function get_output_file_data>)

Processes a set of batches using ProcessingManager, checking their status in cycles until all are completed
or the maximum number of cycles is reached.

* **Parameters:**
  * **oa_stores** – The OpenAI stores object for API interactions.
  * **batches** ([`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[Batch]) – A set of batch objects to process.
  * **status_checking_frequency** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Minimum number of seconds per cycle.
  * **max_cycles** ([`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – Maximum number of cycles to perform.
  * **get_output_file_data** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – Function to get batch status and output data.
* **Returns:**
  A dictionary of batch IDs to their output data.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/imbed.util.html.md

# imbed.util

Utils for imbed package.

### Functions

| [`async_call`](_autosummary/imbed.util.html.md#imbed.util.async_call)(func, \*args, \*\*kwargs)             | Calls a function, awaiting it if it's asynchronous, and running it in a thread if it's synchronous.                                                                                            |
|---------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`async_sync_wrapper`](_autosummary/imbed.util.html.md#imbed.util.async_sync_wrapper)(func)                         | A decorator that adds an async and a sync version of a function.                                                                                                                               |
| [`cosine_similarity`](_autosummary/imbed.util.html.md#imbed.util.cosine_similarity)(u, v, \*[, cartesian_product]) | Computes the cosine similarity between two vectors or arrays of vectors.                                                                                                                       |
| `counts`(sr)                                                                                      |                                                                                                                                                                                                |
| `dict_slice`(d, \*args)                                                                           |                                                                                                                                                                                                |
| `ensure_cache`(cache)                                                                             |                                                                                                                                                                                                |
| [`ensure_embedding_dict`](_autosummary/imbed.util.html.md#imbed.util.ensure_embedding_dict)(embeddings)                | Ensure that the embeddings are in the correct format.                                                                                                                                          |
| [`ensure_fullpath`](_autosummary/imbed.util.html.md#imbed.util.ensure_fullpath)(filepath[, conditional_rootdir]) | Ensures a full path, prepending a rootdir if input is a (slash-less) file name.                                                                                                                |
| [`ensure_segments_mapping`](_autosummary/imbed.util.html.md#imbed.util.ensure_segments_mapping)(segments)                | Ensure that the segments are in the correct format.                                                                                                                                            |
| [`fuzzy_induced_graph`](_autosummary/imbed.util.html.md#imbed.util.fuzzy_induced_graph)(graph, inducing_node_set)    | Keep only those (node, neighbors) pairs where both node and a minimum proportion of neighbors are in inducing_node_set.                                                                        |
| [`hash_text`](_autosummary/imbed.util.html.md#imbed.util.hash_text)(text)                                  | Return a hash of the text, ignoring punctuation and capitalization.                                                                                                                            |
| `identity`(x)                                                                                     |                                                                                                                                                                                                |
| `is_string_with_path_seps`(x)                                                                     |                                                                                                                                                                                                |
| `is_submodule_path`(path)                                                                         |                                                                                                                                                                                                |
| `lenient_bytes_decoder`(bytes_)                                                                   |                                                                                                                                                                                                |
| [`load_if_saved`](_autosummary/imbed.util.html.md#imbed.util.load_if_saved)([key, store_attr, ...])            | Decorator to load the value from the store if it is saved, otherwise compute it.                                                                                                               |
| `lower_alphanumeric`(text)                                                                        |                                                                                                                                                                                                |
| [`match_aliases`](_autosummary/imbed.util.html.md#imbed.util.match_aliases)(fields, aliases)                   | Matches the keys of aliases to the given fields, using the values of aliases as the matching logic (could be a list of possible fields, a regular expression, or a custom matching function.). |
| [`merge_data`](_autosummary/imbed.util.html.md#imbed.util.merge_data)(data_1, data_2, \*[, merge_on, ...])  | Merges two sources of data, returning a dataframe.                                                                                                                                             |
| `module_name`(path)                                                                               |                                                                                                                                                                                                |
| [`planar_embeddings`](_autosummary/imbed.util.html.md#imbed.util.planar_embeddings)(kd_embeddings, \*[, ...])      | Takes a mapping of k-dimensional (kd) embeddings and returns a dict of the 2d umap embeddings                                                                                                  |
| [`planar_embeddings_dict_to_df`](_autosummary/imbed.util.html.md#imbed.util.planar_embeddings_dict_to_df)(...[, x_col, ...])  | A function that takes a dict of planar embeddings and returns a pandas DataFrame of the 2d embeddings                                                                                          |
| `planar_embeddings_func`([embeddings_func, ...])                                                  |                                                                                                                                                                                                |
| `submodules_of`(pkg[, include_init])                                                              |                                                                                                                                                                                                |
| [`transpose_iterable`](_autosummary/imbed.util.html.md#imbed.util.transpose_iterable)(iterable)                     | This is useful to do things like:                                                                                                                                                              |
| [`two_d_embedding_dict_to_df`](_autosummary/imbed.util.html.md#imbed.util.two_d_embedding_dict_to_df)(...[, x_col, ...])    | A function that takes a dict of planar embeddings and returns a pandas DataFrame of the 2d embeddings                                                                                          |
| [`umap_2d_embeddings_df`](_autosummary/imbed.util.html.md#imbed.util.umap_2d_embeddings_df)(kd_embeddings, \*[, ...])  | A function that takes a mapping of kd embeddings and returns a pandas DataFrame of the 2d umap embeddings                                                                                      |

### Classes

| `Embeddings`(embeddings[, keys, meta, ...])   |    |
|-----------------------------------------------|----|

### *async* imbed.util.async_call(func, \*args, \*\*kwargs)

Calls a function, awaiting it if it’s asynchronous, and running it in a thread if it’s synchronous.

* **Parameters:**
  * **func** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[`P`, `R`]) – The function to call.
  * **\*args** (`P.args`) – Positional arguments to pass to the function.
  * **\*\*kwargs** (`P.kwargs`) – Keyword arguments to pass to the function.
* **Return type:**
  [`Coroutine`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Coroutine)[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any), `R`]
* **Returns:**
  The result of the function call.

### imbed.util.async_sync_wrapper(func)

A decorator that adds an async and a sync version of a function.

### imbed.util.cosine_similarity(u, v, , cartesian_product=False)

Computes the cosine similarity between two vectors or arrays of vectors.

If both inputs are 1D vectors, returns a float.
If one or both inputs are 2D arrays, returns either a 1D array (row-wise)
or a 2D array (cartesian product of rows) depending on the cartesian_product flag.

Behavior for row-wise (cartesian_product=False):

> - If both arrays have the same number of rows, compares row i of u to row i of v.
> - If one array has only 1 row, it is broadcast against each row of the other array.
>   (Returns a 1D array of length k, where k is the number of rows in the multi-row array.)
* **Parameters:**
  * **u** (*array-like*) – A single vector (1D) or a 2D array (k1 x n),
    where each row is a separate vector.
  * **v** (*array-like*) – A single vector (1D) or a 2D array (k2 x n).
  * **cartesian_product** ([*bool*](https://docs.python.org/3/builtins/functions.html#bool) *,* *optional*) – 
    - If False (default), the function compares rows in a one-to-one fashion (u[i] vs. v[i]),
      **except** if one array has exactly 1 row and the other has multiple rows, in which case
      that single row is broadcast to all rows of the other array.
    - If True, computes the similarity for every combination of rows
      (results in a 2D array of shape (k1, k2)).
* **Returns:**
  - A float if both u and v are 1D vectors.
  - A 1D numpy array if either u or v is 2D and cartesian_product=False.
  - A 2D numpy array if cartesian_product=True.
* **Return type:**
  [*float*](https://docs.python.org/3/builtins/functions.html#float) or np.ndarray
* **Raises:**
  [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – 
  - If the number of columns in u and v do not match.
        - If cartesian_product=False, both arrays have multiple rows but differ in row count.

### Examples

[See here for an explanation of the cases](https://github.com/thorwhalen/imbed/discussions/9#discussioncomment-11968528).

[See here for a performance comparison of numpy (this function) versus scipy](https://github.com/thorwhalen/imbed/discussions/9#discussioncomment-11971474).

Case 1: Both are single 1D vectors

```pycon
>>> u1d = [2, 0]
>>> v1d = [2, 0]
>>> float(cosine_similarity(u1d, v1d))
1.0
```

Case 2: Single 1D vector vs. a 2D array (row-wise broadcast)

```pycon
>>> import numpy as np
>>> M1 = np.array([
...     [2, 0],
...     [0, 2],
...     [2, 2]
... ])
>>> cosine_similarity(u1d, M1)
array([1.        , 0.        , 0.70710678...])
```

Case 3: Two 2D arrays of different row lengths, cartesian_product=False (raises ValueError)

```pycon
>>> M2_different = np.array([
...     [0, 2],
...     [2, 2]
... ])
>>> # Expect a ValueError because M1 has 3 rows and M2_different has 2 rows
>>> cosine_similarity(M1, M2_different, cartesian_product=False)
Traceback (most recent call last):
    ...
ValueError: For row-wise comparison, u and v must have the same number of rows...
```

Case 4: Two 2D arrays of the same number of rows, cartesian_product=False

```pycon
>>> M2 = np.array([
...     [0, 2],
...     [2, 0],
...     [2, 2]
... ])
>>> cosine_similarity(M1, M2, cartesian_product=False)
array([0., 0., 1.])
```

Case 5: Two 2D arrays of the same size, `cartesian_product=True`
(computes every combination of rows => 3 x 3)

```pycon
>>> res5 = cosine_similarity(M1, M2, cartesian_product=True)
>>> np.round(res5, 3)
array([[0.   , 1.   , 0.707],
       [1.   , 0.   , 0.707],
       [0.707, 0.707, 1.   ]])
```

### imbed.util.ensure_embedding_dict(embeddings)

Ensure that the embeddings are in the correct format.

* **Parameters:**
  **embeddings** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`KT`, [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – a dict of embeddings
* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`KT`, [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  a dict of embeddings

### imbed.util.ensure_fullpath(filepath, conditional_rootdir='')

Ensures a full path, prepending a rootdir if input is a (slash-less) file name.

If you pass in a file name, it will be considered relative to the current directory.
In all other situations, the conditional_rootdir is ignored, and the filepath is
taken at face value.
All outputs will be processed to ensure a full path is returned.

```pycon
>>> ensure_fullpath('apple/sauce')
'.../apple/sauce'
>>> assert (
...     ensure_fullpath('apple/sauce')
...     == ensure_fullpath('./apple/sauce')
...     == ensure_fullpath('apple/sauce', '')
... )
```

The only time you actually use the rootdir is when you pass in a file name
that doesn’t have slashes in it.

```pycon
>>> ensure_fullpath('apple', '/root/dir')
'/root/dir/apple'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### imbed.util.ensure_segments_mapping(segments)

Ensure that the segments are in the correct format.

* **Parameters:**
  **segments** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[`Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)), [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[`Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`SegmentKey` (`KT`), `Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))]]) – a SegmentMapping or a Sequence of Segments
* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`SegmentKey` (`KT`), `Segment` ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str))]
* **Returns:**
  a SegmentMapping

### imbed.util.fuzzy_induced_graph(graph, inducing_node_set, min_proportion=1)

Keep only those (node, neighbors) pairs where both node and a minimum proportion of
neighbors are in inducing_node_set.

* **Return type:**
  [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]]

### imbed.util.hash_text(text)

Return a hash of the text, ignoring punctuation and capitalization.

```pycon
>>> hash_text('Hello, world!')
'5eb63bbbe01eeed093cb22bb8f5acdc3'
>>> hash_text('hello world')
'5eb63bbbe01eeed093cb22bb8f5acdc3'
>>> hash_text('Hello, world!') == hash_text('hello world')
True
```

### imbed.util.load_if_saved(key=None, store_attr='saves', save_on_compute=True, print_when_loading_from_file=True)

Decorator to load the value from the store if it is saved, otherwise compute it.

### imbed.util.match_aliases(fields, aliases)

Matches the keys of aliases to the given fields,
using the values of aliases as the matching logic (could be a list of possible
fields, a regular expression, or a custom matching function.).

A dictionary

* **Parameters:**
  * **fields** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`Field`]) – A list of fields
  * **aliases** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`Role`, [`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`Field`], `Regex`, [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[`Field`]], [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[`Field`]]]]) – 

    A dictionary where:
    - Keys are roles (e.g., ‘ID’, ‘Name’) we’re looking for
    - Values are either:
      : - A list of field “aliases” (e.g., [‘id’, ‘user_id’]).
        - A string representing a regular expression (e.g., r’user.\*id’).
        - A function that takes a list of fields and returns a matched field or None.
* **Returns:**
  A dictionary mapping each role to the first matching
  : field found in `fields`, or `None` if no match is
    found. Once a column is matched, it is removed
    from further matching, so it can’t be matched again.
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`Role`, [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[`Field`]]

Example 1: List-based aliases, regex, and custom function matching

```pycon
>>> fields = ['user_id', 'full_name', 'created_at', 'email_address']
>>> aliases = {
...     'ID': ['id', 'user_id'],  # List of possible aliases for 'ID'
...     'Name': r'.*name',  # Regular expression for 'Name'
...     'Date': lambda cols: next((col for col in cols if "date" in col.lower() or "created" in col.lower()), None)  # Custom matching function
... }
>>> match_aliases(fields, aliases)
{'ID': 'user_id', 'Name': 'full_name', 'Date': 'created_at'}
```

### Example 2: Handles conflict resolution by removing matched columns

```pycon
>>> fields = ['id', 'full_name', 'id_created', 'email_address']
>>> aliases = {
...     'Primary ID': ['id'],  # List-based alias that should match 'id' first
...     'Secondary ID': r'id.*',  # Regex to match anything starting with 'id'
...     'Email': lambda cols: next((col for col in cols if 'email' in col.lower()), None)  # Custom function for email
... }
>>> match_aliases(fields, aliases)
{'Primary ID': 'id', 'Secondary ID': 'id_created', 'Email': 'email_address'}
```

### imbed.util.merge_data(data_1, data_2, , merge_on=None, data_1_cols=None, data_2_cols=None, column_index_cursor_start=0)

Merges two sources of data, returning a dataframe.

The sources of data could be numpy arrays or pandas DataFrames.

If they’re both dataframes, the merge_on specification is needed.
If at least one of them is a numpy array, data_1 and data_2 must have the same
number of rows and merge_on is ignored, since the merge will simply be the
concatination of the two datas over the rows (that is, the result will have
that common number of rows and the number of columns will be added).

The optional data_1_cols and data_2_cols are used to transform numpy matrices into
dataframes with the given column names.

* **Parameters:**
  * **data_1** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[`ndarray`, `DataFrame`]) – The first source of data.
  * **data_2** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[`ndarray`, `DataFrame`]) – The second source of data.
  * **merge_on** – The column to merge on, if both data_1 and data_2 are dataframes.
  * **data_1_cols** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The column names for the first source of data, if it is a numpy array.
  * **data_2_cols** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – The column names for the second source of data, if it is a numpy array.
* **Return type:**
  `DataFrame`

### imbed.util.planar_embeddings(kd_embeddings, \*, embeddings_func='umap', preprocess=<bound method Pipeline.fit_transform of Pipeline(steps=[('standardscaler', StandardScaler()), ('pca', PCA())])>, egress=None)

Takes a mapping of k-dimensional (kd) embeddings and returns a dict of the 2d
umap embeddings

* **Parameters:**
  * **kd_embeddings** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`KT`, [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – a dict of kd embeddings
  * **embeddings_func** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'umap'`, `'ncvis'`, `'tsne'`, `'pca'`], [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]]]) – the function to compute the embeddings
  * **preprocessors** – a list of preprocessors to apply to the embeddings
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`KT`, [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  a dict of the 2d umap embeddings

### Example

```pycon
>>> # Make 7 random vectors of dimension 3 (seeded, so that the example is stable)
>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> kd_embeddings = {i: rng.random(3) for i in range(7)}
>>> xy_pairs = planar_embeddings(kd_embeddings, embeddings_func="pca")
>>> list(xy_pairs)
[0, 1, 2, 3, 4, 5, 6]
>>> {len(xy) for xy in xy_pairs.values()}
{2}
```

(The default, `embeddings_func="umap"`, is randomized and needs far more points
than this to be meaningful, so the example uses the deterministic “pca”.)

```pycon
>>> x, y = planar_embeddings.transpose_iterable(xy_pairs.values())
>>> len(x), len(y)
(7, 7)
```

#### TIP
Should you normalize your features (use preprocessors, the default here)?

See [https://umap-learn.readthedocs.io/en/latest/faq.html?utm_source=chatgpt.com#should-i-normalise-my-features](https://umap-learn.readthedocs.io/en/latest/faq.html?utm_source=chatgpt.com#should-i-normalise-my-features)

#### TIP
If you need to get big vectors of the x and y coordinates, you can do this:

```text
x_values, y_values = zip(*planar_embeddings(kd_embeddings).values())
```

Or even, in case you have a pandas dataframe or dict d:

```text
d['x'], d['y'] = zip(*planar_embeddings(d).values())
```

#### TIP
Use planar_embeddings.transpose_iterable to do this in a readabble way:

```text
x_values, y_values = planar_embeddings.transpose_iterable(planar_embeddings(kd_embeddings).values())
```

### imbed.util.planar_embeddings_dict_to_df(planar_embeddings_kv, , x_col='x', y_col='y', index_name='id_', key_col=None)

A function that takes a dict of planar embeddings and returns a pandas DataFrame
of the 2d embeddings

If key_col is not None, the keys are added as a column in the dataframe.

* **Parameters:**
  * **planar_embeddings_kv** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`KT`, [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – a dict of planar embeddings
  * **x_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – the name of the x column
  * **y_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – the name of the y column
  * **index_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the name of the index
  * **key_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – if you want to add a column with the index values copied into them
* **Return type:**
  `DataFrame`
* **Returns:**
  a pandas DataFrame of the 2d embeddings

### Example

```pycon
>>> planar_embeddings_kv = {1: (0.1, 0.2), 2: (0.3, 0.4)}
>>> planar_embeddings_dict_to_df(planar_embeddings_kv)
       x    y
id_
1    0.1  0.2
2    0.3  0.4
```

### imbed.util.transpose_iterable(iterable)

This is useful to do things like:

```pycon
>>> xy_values = [(1, 2), (3, 4), (5, 6)]
>>> x_values, y_values = transpose_iterable(xy_values)
>>> x_values
(1, 3, 5)
>>> y_values
(2, 4, 6)
```

Note that transpose_iterable is an [involution](https://en.wikipedia.org/wiki/Involution_(mathematics))
(if we disregard types).

```pycon
>>> list((x_values, y_values))
[(1, 3, 5), (2, 4, 6)]
```

### imbed.util.two_d_embedding_dict_to_df(planar_embeddings_kv, , x_col='x', y_col='y', index_name='id_', key_col=None)

A function that takes a dict of planar embeddings and returns a pandas DataFrame
of the 2d embeddings

If key_col is not None, the keys are added as a column in the dataframe.

* **Parameters:**
  * **planar_embeddings_kv** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`KT`, [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – a dict of planar embeddings
  * **x_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – the name of the x column
  * **y_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – the name of the y column
  * **index_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – the name of the index
  * **key_col** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – if you want to add a column with the index values copied into them
* **Return type:**
  `DataFrame`
* **Returns:**
  a pandas DataFrame of the 2d embeddings

### Example

```pycon
>>> planar_embeddings_kv = {1: (0.1, 0.2), 2: (0.3, 0.4)}
>>> planar_embeddings_dict_to_df(planar_embeddings_kv)
       x    y
id_
1    0.1  0.2
2    0.3  0.4
```

### imbed.util.umap_2d_embeddings(kd_embeddings, \*, embeddings_func='umap', preprocess=<bound method Pipeline.fit_transform of Pipeline(steps=[('standardscaler', StandardScaler()), ('pca', PCA())])>, egress=None)

Takes a mapping of k-dimensional (kd) embeddings and returns a dict of the 2d
umap embeddings

* **Parameters:**
  * **kd_embeddings** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[`KT`, [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – a dict of kd embeddings
  * **embeddings_func** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)[`'umap'`, `'ncvis'`, `'tsne'`, `'pca'`], [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]]]) – the function to compute the embeddings
  * **preprocessors** – a list of preprocessors to apply to the embeddings
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[`KT`, [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`float`](https://docs.python.org/3/builtins/functions.html#float), [`float`](https://docs.python.org/3/builtins/functions.html#float)]]
* **Returns:**
  a dict of the 2d umap embeddings

### Example

```pycon
>>> # Make 7 random vectors of dimension 3 (seeded, so that the example is stable)
>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> kd_embeddings = {i: rng.random(3) for i in range(7)}
>>> xy_pairs = planar_embeddings(kd_embeddings, embeddings_func="pca")
>>> list(xy_pairs)
[0, 1, 2, 3, 4, 5, 6]
>>> {len(xy) for xy in xy_pairs.values()}
{2}
```

(The default, `embeddings_func="umap"`, is randomized and needs far more points
than this to be meaningful, so the example uses the deterministic “pca”.)

```pycon
>>> x, y = planar_embeddings.transpose_iterable(xy_pairs.values())
>>> len(x), len(y)
(7, 7)
```

#### TIP
Should you normalize your features (use preprocessors, the default here)?

See [https://umap-learn.readthedocs.io/en/latest/faq.html?utm_source=chatgpt.com#should-i-normalise-my-features](https://umap-learn.readthedocs.io/en/latest/faq.html?utm_source=chatgpt.com#should-i-normalise-my-features)

#### TIP
If you need to get big vectors of the x and y coordinates, you can do this:

```text
x_values, y_values = zip(*planar_embeddings(kd_embeddings).values())
```

Or even, in case you have a pandas dataframe or dict d:

```text
d['x'], d['y'] = zip(*planar_embeddings(d).values())
```

#### TIP
Use planar_embeddings.transpose_iterable to do this in a readabble way:

```text
x_values, y_values = planar_embeddings.transpose_iterable(planar_embeddings(kd_embeddings).values())
```

### imbed.util.umap_2d_embeddings_df(kd_embeddings, , x_col='x', y_col='y', index_name='id_', key_col=None)

A function that takes a mapping of kd embeddings and returns a pandas DataFrame
of the 2d umap embeddings

* **Return type:**
  `DataFrame`


# _autosummary/imbed.vector_db.html.md

# imbed.vector_db

Facades for vector databases


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-22 22:20 UTC** from commit <a href="https://github.com/addaix/imbed/commit/3368cccbc7a377f4dd027ef57c94fce754caa638"><code>3368ccc</code></a> on branch <code>main</code>, for **imbed 0.0.28** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                     |
|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/imbed/commit/3368cccbc7a377f4dd027ef57c94fce754caa638"><code>3368cccbc7a377f4dd027ef57c94fce754caa638</code></a> |
| Branch              | <code>main</code>                                                                                                                                   |
| Tags at this commit | none                                                                                                                                                |
| Working tree        | clean                                                                                                                                               |
| Remote              | <code>https://github.com/addaix/imbed</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/imbed</code>                                                                  |
| Run          | <a href="https://github.com/addaix/imbed/actions/runs/45076760034">45076760034</a>         |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>3368cccbc7a377f4dd027ef57c94fce754caa638</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.23  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>shibuya</code>)            |
| accent        | <code>#8d3e00</code>                                             |
| api_generator | <code>autosummary</code>                                         |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code> |
| agent_outputs | <code>true</code>                                                |
| aggregates    | <code>md</code>                                                  |
| ai_artifacts  | <code>true</code>                                                |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/imbed/0.0.28/">0.0.28</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/addaix/imbed && cd imbed
git checkout 3368cccbc7a377f4dd027ef57c94fce754caa638
pip install "epythet==0.2.23"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# api.html.md

# API reference

| [`imbed`](_autosummary/imbed.html.md#module-imbed)   | Tools for imbeddings   |
|-----------------------------------------------------------------------|------------------------|


