Coverage for haystack/dataclasses/sparse_embedding.py: 100%
14 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-21 13:53 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-21 13:53 +0000
1# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2#
3# SPDX-License-Identifier: Apache-2.0
5from dataclasses import asdict, dataclass
6from typing import Any
8from haystack.utils.dataclasses import _warn_on_inplace_mutation
11@_warn_on_inplace_mutation
12@dataclass
13class SparseEmbedding:
14 """
15 Class representing a sparse embedding.
17 :param indices: List of indices of non-zero elements in the embedding.
18 :param values: List of values of non-zero elements in the embedding.
19 """
21 indices: list[int]
22 values: list[float]
24 def __post_init__(self) -> None:
25 """
26 Checks if the indices and values lists are of the same length.
28 Raises a ValueError if they are not.
29 """
30 if len(self.indices) != len(self.values):
31 raise ValueError("Length of indices and values must be the same.")
33 def to_dict(self) -> dict[str, Any]:
34 """
35 Convert the SparseEmbedding object to a dictionary.
37 :returns:
38 Serialized sparse embedding.
39 """
40 return asdict(self)
42 @classmethod
43 def from_dict(cls, sparse_embedding_dict: dict[str, Any]) -> "SparseEmbedding":
44 """
45 Deserializes the sparse embedding from a dictionary.
47 :param sparse_embedding_dict:
48 Dictionary to deserialize from.
49 :returns:
50 Deserialized sparse embedding.
51 """
52 return cls(**sparse_embedding_dict)