fable-model 0.1.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ from .common import BitVectorEntity, AttributeValueEntity, HealthResponse
2
+ from .mask import (
3
+ HashStrategy,
4
+ DoubleHash,
5
+ TripleHash,
6
+ EnhancedDoubleHash,
7
+ RandomHash,
8
+ AnyHashStrategy,
9
+ HashAlgorithm,
10
+ HashFunction,
11
+ HashConfig,
12
+ FilterType,
13
+ CLKFilter,
14
+ RBFFilter,
15
+ CLKRBFFilter,
16
+ AnyFilter,
17
+ Hardener,
18
+ BalanceHardener,
19
+ XORFoldHardener,
20
+ PermuteHardener,
21
+ RandomizedResponseHardener,
22
+ Rule90Hardener,
23
+ RehashHardener,
24
+ AnyHardener,
25
+ MaskConfig,
26
+ AttributeSalt,
27
+ StaticAttributeConfig,
28
+ WeightedAttributeConfig,
29
+ EntityMaskRequest,
30
+ EntityMaskResponse,
31
+ BaseMaskRequest,
32
+ )
33
+ from .match import (
34
+ SimilarityMeasure,
35
+ MatchConfig,
36
+ VectorMatchRequest,
37
+ VectorMatchResponse,
38
+ Match,
39
+ BaseMatchRequest,
40
+ MatchMethod,
41
+ )
42
+ from .transform import (
43
+ EmptyValueHandling,
44
+ TransformConfig,
45
+ Transformer,
46
+ NormalizationTransformer,
47
+ DateTimeTransformer,
48
+ CharacterFilterTransformer,
49
+ MappingTransformer,
50
+ NumberTransformer,
51
+ PhoneticCodeTransformer,
52
+ PhoneticCodeAlgorithm,
53
+ AnyTransformer,
54
+ AttributeTransformerConfig,
55
+ GlobalTransformerConfig,
56
+ EntityTransformRequest,
57
+ EntityTransformResponse,
58
+ BaseTransformRequest,
59
+ )
60
+
61
+ __all__ = [
62
+ "BitVectorEntity",
63
+ "AttributeValueEntity",
64
+ "HealthResponse",
65
+ "SimilarityMeasure",
66
+ "MatchConfig",
67
+ "VectorMatchRequest",
68
+ "VectorMatchResponse",
69
+ "Match",
70
+ "EmptyValueHandling",
71
+ "TransformConfig",
72
+ "Transformer",
73
+ "NormalizationTransformer",
74
+ "DateTimeTransformer",
75
+ "CharacterFilterTransformer",
76
+ "MappingTransformer",
77
+ "NumberTransformer",
78
+ "PhoneticCodeTransformer",
79
+ "PhoneticCodeAlgorithm",
80
+ "AnyTransformer",
81
+ "AttributeTransformerConfig",
82
+ "EmptyValueHandling",
83
+ "EntityTransformRequest",
84
+ "EntityTransformResponse",
85
+ "GlobalTransformerConfig",
86
+ "EntityTransformRequest",
87
+ "EntityTransformResponse",
88
+ "HashStrategy",
89
+ "DoubleHash",
90
+ "TripleHash",
91
+ "EnhancedDoubleHash",
92
+ "RandomHash",
93
+ "AnyHashStrategy",
94
+ "HashAlgorithm",
95
+ "HashFunction",
96
+ "HashConfig",
97
+ "FilterType",
98
+ "CLKFilter",
99
+ "RBFFilter",
100
+ "CLKRBFFilter",
101
+ "AnyFilter",
102
+ "Hardener",
103
+ "BalanceHardener",
104
+ "XORFoldHardener",
105
+ "PermuteHardener",
106
+ "RandomizedResponseHardener",
107
+ "Rule90Hardener",
108
+ "RehashHardener",
109
+ "AnyHardener",
110
+ "MaskConfig",
111
+ "AttributeSalt",
112
+ "StaticAttributeConfig",
113
+ "WeightedAttributeConfig",
114
+ "EntityMaskRequest",
115
+ "EntityMaskResponse",
116
+ "BaseMaskRequest",
117
+ "BaseTransformRequest",
118
+ "BaseMatchRequest",
119
+ "MatchMethod",
120
+ ]
fable_model/common.py ADDED
@@ -0,0 +1,21 @@
1
+ from typing import Literal
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+
5
+
6
+ class ParentModel(BaseModel):
7
+ model_config = ConfigDict(extra="forbid")
8
+
9
+
10
+ class AttributeValueEntity(ParentModel):
11
+ id: str
12
+ attributes: dict[str, str]
13
+
14
+
15
+ class BitVectorEntity(ParentModel):
16
+ id: str
17
+ value: str
18
+
19
+
20
+ class HealthResponse(ParentModel):
21
+ status: Literal["ok"] = "ok"
fable_model/mask.py ADDED
@@ -0,0 +1,287 @@
1
+ from enum import Enum
2
+ from typing import Literal, Union, Annotated
3
+
4
+ from pydantic import Field, conint, confloat, model_validator
5
+ from typing_extensions import Self
6
+
7
+ from fable_model.common import ParentModel, BitVectorEntity, AttributeValueEntity
8
+
9
+
10
+ class HashStrategy(str, Enum):
11
+ double_hash = "double_hash"
12
+ triple_hash = "triple_hash"
13
+ enhanced_double_hash = "enhanced_double_hash"
14
+ random_hash = "random_hash"
15
+
16
+
17
+ class DoubleHash(ParentModel):
18
+ name: Literal[HashStrategy.double_hash] = HashStrategy.double_hash
19
+
20
+
21
+ class TripleHash(ParentModel):
22
+ name: Literal[HashStrategy.triple_hash] = HashStrategy.triple_hash
23
+
24
+
25
+ class EnhancedDoubleHash(ParentModel):
26
+ name: Literal[HashStrategy.enhanced_double_hash] = HashStrategy.enhanced_double_hash
27
+
28
+
29
+ class RandomHash(ParentModel):
30
+ name: Literal[HashStrategy.random_hash] = HashStrategy.random_hash
31
+
32
+
33
+ AnyHashStrategy = Union[DoubleHash, TripleHash, EnhancedDoubleHash, RandomHash]
34
+
35
+
36
+ class HashAlgorithm(str, Enum):
37
+ md5 = "md5"
38
+ sha1 = "sha1"
39
+ sha256 = "sha256"
40
+ sha512 = "sha512"
41
+
42
+
43
+ class HashFunction(ParentModel):
44
+ algorithms: list[HashAlgorithm] = Field(min_length=1)
45
+ key: str | None = None
46
+
47
+
48
+ class HashConfig(ParentModel):
49
+ function: HashFunction
50
+ strategy: AnyHashStrategy = Field(discriminator="name")
51
+
52
+
53
+ class FilterType(str, Enum):
54
+ clk = "clk"
55
+ rbf = "rbf"
56
+ clkrbf = "clkrbf"
57
+
58
+
59
+ class CLKFilter(ParentModel):
60
+ type: Literal[FilterType.clk] = FilterType.clk
61
+ filter_size: conint(gt=0)
62
+ hash_values: conint(gt=0)
63
+
64
+
65
+ class RBFFilter(ParentModel):
66
+ type: Literal[FilterType.rbf] = FilterType.rbf
67
+ hash_values: conint(gt=0)
68
+ seed: int
69
+
70
+
71
+ class CLKRBFFilter(ParentModel):
72
+ type: Literal[FilterType.clkrbf] = FilterType.clkrbf
73
+ hash_values: conint(gt=0)
74
+
75
+
76
+ AnyFilter = Union[CLKFilter, RBFFilter, CLKRBFFilter]
77
+
78
+
79
+ class Hardener(str, Enum):
80
+ balance = "balance"
81
+ xor_fold = "xor_fold"
82
+ permute = "permute"
83
+ randomized_response = "randomized_response"
84
+ rule_90 = "rule_90"
85
+ rehash = "rehash"
86
+
87
+
88
+ class BalanceHardener(ParentModel):
89
+ name: Literal[Hardener.balance] = Hardener.balance
90
+
91
+
92
+ class XORFoldHardener(ParentModel):
93
+ name: Literal[Hardener.xor_fold] = Hardener.xor_fold
94
+
95
+
96
+ class PermuteHardener(ParentModel):
97
+ name: Literal[Hardener.permute] = Hardener.permute
98
+ seed: int
99
+
100
+
101
+ class RandomizedResponseHardener(ParentModel):
102
+ name: Literal[Hardener.randomized_response] = Hardener.randomized_response
103
+ probability: confloat(ge=0, le=1)
104
+ seed: int
105
+
106
+
107
+ class Rule90Hardener(ParentModel):
108
+ name: Literal[Hardener.rule_90] = Hardener.rule_90
109
+
110
+
111
+ class RehashHardener(ParentModel):
112
+ name: Literal[Hardener.rehash] = Hardener.rehash
113
+ window_size: conint(gt=0, le=32)
114
+ window_step: conint(gt=0)
115
+ samples: conint(gt=0)
116
+
117
+
118
+ AnyHardener = Union[
119
+ BalanceHardener,
120
+ PermuteHardener,
121
+ RandomizedResponseHardener,
122
+ XORFoldHardener,
123
+ RehashHardener,
124
+ Rule90Hardener,
125
+ ]
126
+
127
+
128
+ class MaskConfig(ParentModel):
129
+ token_size: conint(gt=1)
130
+ hash: HashConfig
131
+ prepend_attribute_name: Annotated[bool, Field(default=True)]
132
+ filter: Annotated[AnyFilter, Field(discriminator="type")]
133
+ padding: Annotated[str, Field(default="")]
134
+ hardeners: Annotated[list[Annotated[AnyHardener, Field(..., discriminator="name")]], Field(default_factory=list)]
135
+
136
+
137
+ class AttributeSalt(ParentModel):
138
+ value: str | None = None
139
+ attribute: str | None = None
140
+
141
+ @model_validator(mode="after")
142
+ def validate_mutually_exclusive_attributes(self) -> Self:
143
+ if self.value and self.attribute:
144
+ raise ValueError("value and attribute cannot be set at the same time")
145
+
146
+ if not self.value and not self.attribute:
147
+ raise ValueError("neither value nor attribute is set")
148
+
149
+ return self
150
+
151
+
152
+ class StaticAttributeConfig(ParentModel):
153
+ attribute_name: str
154
+ salt: AttributeSalt | None = Field(default=None)
155
+
156
+
157
+ class WeightedAttributeConfig(ParentModel):
158
+ attribute_name: str
159
+ salt: AttributeSalt | None = Field(default=None)
160
+ weight: confloat(gt=0)
161
+ average_token_count: confloat(gt=0)
162
+
163
+
164
+ class BaseMaskRequest(ParentModel):
165
+ config: MaskConfig
166
+ attributes: Annotated[list[WeightedAttributeConfig] | list[StaticAttributeConfig], Field(default_factory=list)]
167
+
168
+ def with_entities(self, entities: list[AttributeValueEntity]) -> "EntityMaskRequest":
169
+ return EntityMaskRequest(
170
+ config=self.config,
171
+ attributes=self.attributes,
172
+ entities=entities,
173
+ )
174
+
175
+
176
+ class EntityMaskRequest(BaseMaskRequest):
177
+ entities: Annotated[list[AttributeValueEntity], Field(min_length=1)]
178
+
179
+ @model_validator(mode="after")
180
+ def validate_attribute_type(self) -> Self:
181
+ if self.config.filter.type == FilterType.clk:
182
+ # if no attribute configs are specified, return early
183
+ if len(self.attributes) == 0:
184
+ return self
185
+
186
+ # check that all supplied attribute configs are static
187
+ if all([isinstance(a, StaticAttributeConfig) for a in self.attributes]):
188
+ return self
189
+
190
+ raise ValueError(
191
+ f"`{self.config.filter.type.value}` filters require static attribute configurations, but "
192
+ f"weighted ones were found"
193
+ )
194
+ else:
195
+ if len(self.attributes) == 0:
196
+ raise ValueError(
197
+ f"`{self.config.filter.type.value}` filters require weighted attribute "
198
+ f"configurations, but none were found"
199
+ )
200
+
201
+ # check that all supplied attribute configs are weighted
202
+ if all([isinstance(a, WeightedAttributeConfig) for a in self.attributes]):
203
+ return self
204
+
205
+ raise ValueError(
206
+ f"`{self.config.filter.type.value}` filters require weighted attribute configurations, "
207
+ f"but static ones were found"
208
+ )
209
+
210
+ def _check_attribute_not_present_on_entities(self, attr_name: str) -> list[AttributeValueEntity]:
211
+ return [e for e in self.entities if attr_name not in e.attributes]
212
+
213
+ @model_validator(mode="after")
214
+ def validate_configured_attributes_present_on_entities(self) -> Self:
215
+ # if no attributes are configured, we can skip this
216
+ if len(self.attributes) == 0:
217
+ return self
218
+
219
+ attribute_name_to_non_present_entity_id_dict: dict[str, list[str]] = {}
220
+
221
+ for attr_conf in self.attributes:
222
+ attr_name = attr_conf.attribute_name
223
+ non_present_entities = self._check_attribute_not_present_on_entities(attr_name)
224
+
225
+ # if attribute is present on all entities, continue
226
+ if len(non_present_entities) == 0:
227
+ continue
228
+
229
+ # otherwise add it to the dict
230
+ attribute_name_to_non_present_entity_id_dict[attr_name] = [e.id for e in non_present_entities]
231
+
232
+ # throw an error if there are any attributes with configurations that are not present on some entities
233
+ if len(attribute_name_to_non_present_entity_id_dict) != 0:
234
+ entity_str = ",".join(
235
+ [
236
+ f"`{attr_name}` on entities with ID `{'`, `'.join(entity_ids)}`"
237
+ for attr_name, entity_ids in attribute_name_to_non_present_entity_id_dict.items()
238
+ ]
239
+ )
240
+
241
+ raise ValueError(f"some configured attributes are not present on entities: {entity_str}")
242
+
243
+ return self
244
+
245
+ @model_validator(mode="after")
246
+ def validate_attribute_salt_present_on_all_entities(self) -> Self:
247
+ # if no attributes are configured, we can skip this
248
+ if len(self.attributes) == 0:
249
+ return self
250
+
251
+ attribute_name_to_non_present_entity_id_dict: dict[str, list[str]] = {}
252
+
253
+ for attr_conf in self.attributes:
254
+ salt = attr_conf.salt
255
+
256
+ # if no salt is configured, skip this step
257
+ if salt is None or salt.attribute is None:
258
+ continue
259
+
260
+ # retrieve the attribute name
261
+ attr_name = salt.attribute
262
+ non_present_entities = self._check_attribute_not_present_on_entities(attr_name)
263
+
264
+ # if attribute is present on all entities, continue
265
+ if len(non_present_entities) == 0:
266
+ continue
267
+
268
+ # otherwise add it to the dict
269
+ attribute_name_to_non_present_entity_id_dict[attr_name] = [e.id for e in non_present_entities]
270
+
271
+ # throw an error if there are any attributes that are not present on some entities
272
+ if len(attribute_name_to_non_present_entity_id_dict) != 0:
273
+ entity_str = ",".join(
274
+ [
275
+ f"`{attr_name}` on entities with ID `{'`, `'.join(entity_ids)}`"
276
+ for attr_name, entity_ids in attribute_name_to_non_present_entity_id_dict.items()
277
+ ]
278
+ )
279
+
280
+ raise ValueError(f"some configured attribute salts are not present on entities: {entity_str}")
281
+
282
+ return self
283
+
284
+
285
+ class EntityMaskResponse(ParentModel):
286
+ config: MaskConfig
287
+ entities: list[BitVectorEntity]
fable_model/match.py ADDED
@@ -0,0 +1,50 @@
1
+ from enum import Enum
2
+ from typing import Annotated
3
+
4
+ from pydantic import confloat, Field
5
+
6
+ from fable_model.common import ParentModel, BitVectorEntity
7
+
8
+
9
+ class MatchMethod(str, Enum):
10
+ crosswise = "crosswise"
11
+ pairwise = "pairwise"
12
+
13
+
14
+ class SimilarityMeasure(str, Enum):
15
+ dice = "dice"
16
+ cosine = "cosine"
17
+ jaccard = "jaccard"
18
+
19
+
20
+ class MatchConfig(ParentModel):
21
+ measure: SimilarityMeasure
22
+ threshold: confloat(ge=0, le=1)
23
+ method: MatchMethod = MatchMethod.crosswise
24
+
25
+
26
+ class BaseMatchRequest(ParentModel):
27
+ config: MatchConfig
28
+
29
+ def with_vectors(self, domain_lst: list[BitVectorEntity], range_lst: list[BitVectorEntity]) -> "VectorMatchRequest":
30
+ return VectorMatchRequest(
31
+ config=self.config,
32
+ domain=domain_lst,
33
+ range=range_lst,
34
+ )
35
+
36
+
37
+ class VectorMatchRequest(BaseMatchRequest):
38
+ domain: Annotated[list[BitVectorEntity], Field(min_length=1)]
39
+ range: Annotated[list[BitVectorEntity], Field(min_length=1)]
40
+
41
+
42
+ class Match(ParentModel):
43
+ domain: BitVectorEntity
44
+ range: BitVectorEntity
45
+ similarity: float
46
+
47
+
48
+ class VectorMatchResponse(ParentModel):
49
+ config: MatchConfig
50
+ matches: list[Match]
@@ -0,0 +1,118 @@
1
+ from enum import Enum
2
+ from typing import Literal, Union, Annotated
3
+
4
+ from pydantic import Field, conint, model_validator
5
+ from typing_extensions import Self
6
+
7
+ from fable_model.common import ParentModel, AttributeValueEntity
8
+
9
+
10
+ class EmptyValueHandling(str, Enum):
11
+ ignore = "ignore"
12
+ error = "error"
13
+ skip = "skip"
14
+
15
+
16
+ class TransformConfig(ParentModel):
17
+ empty_value: EmptyValueHandling
18
+
19
+
20
+ class Transformer(str, Enum):
21
+ normalization = "normalization"
22
+ date_time = "date_time"
23
+ character_filter = "character_filter"
24
+ mapping = "mapping"
25
+ number = "number"
26
+ phonetic_code = "phonetic_code"
27
+
28
+
29
+ class NormalizationTransformer(ParentModel):
30
+ name: Literal[Transformer.normalization] = Transformer.normalization
31
+
32
+
33
+ class DateTimeTransformer(ParentModel):
34
+ name: Literal[Transformer.date_time] = Transformer.date_time
35
+ input_format: str
36
+ output_format: str
37
+
38
+
39
+ class CharacterFilterTransformer(ParentModel):
40
+ name: Literal[Transformer.character_filter] = Transformer.character_filter
41
+ characters: str | None = None
42
+
43
+
44
+ class MappingTransformer(ParentModel):
45
+ name: Literal[Transformer.mapping] = Transformer.mapping
46
+ mapping: Annotated[dict[str, str], Field(min_length=1)]
47
+ default_value: str | None = None
48
+ inline: bool = False
49
+
50
+
51
+ class NumberTransformer(ParentModel):
52
+ name: Literal[Transformer.number] = Transformer.number
53
+ decimal_places: conint(ge=0)
54
+
55
+
56
+ class PhoneticCodeAlgorithm(str, Enum):
57
+ soundex = "soundex"
58
+ metaphone = "metaphone"
59
+ refined_soundex = "refined_soundex"
60
+ fuzzy_soundex = "fuzzy_soundex"
61
+ cologne = "cologne"
62
+
63
+
64
+ class PhoneticCodeTransformer(ParentModel):
65
+ name: Literal[Transformer.phonetic_code] = Transformer.phonetic_code
66
+ algorithm: PhoneticCodeAlgorithm
67
+
68
+
69
+ AnyTransformer = Union[
70
+ NormalizationTransformer,
71
+ DateTimeTransformer,
72
+ CharacterFilterTransformer,
73
+ MappingTransformer,
74
+ NumberTransformer,
75
+ PhoneticCodeTransformer,
76
+ ]
77
+
78
+
79
+ class AttributeTransformerConfig(ParentModel):
80
+ attribute_name: str
81
+ transformers: Annotated[list[Annotated[AnyTransformer, Field(..., discriminator="name")]], Field(min_length=1)]
82
+
83
+
84
+ class GlobalTransformerConfig(ParentModel):
85
+ before: Annotated[list[Annotated[AnyTransformer, Field(..., discriminator="name")]], Field(default_factory=list)]
86
+ after: Annotated[list[Annotated[AnyTransformer, Field(..., discriminator="name")]], Field(default_factory=list)]
87
+
88
+
89
+ class BaseTransformRequest(ParentModel):
90
+ config: TransformConfig
91
+ attribute_transformers: Annotated[list[AttributeTransformerConfig], Field(default_factory=list)]
92
+ global_transformers: Annotated[GlobalTransformerConfig, Field(default_factory=GlobalTransformerConfig)]
93
+
94
+ @model_validator(mode="after")
95
+ def validate_at_least_one_transformer(self) -> Self:
96
+ if len(self.attribute_transformers) == 0 and (
97
+ len(self.global_transformers.before) + len(self.global_transformers.after) == 0
98
+ ):
99
+ raise ValueError("attribute and global transformers are empty: must contain at least one")
100
+
101
+ return self
102
+
103
+ def with_entities(self, entities: list[AttributeValueEntity]) -> "EntityTransformRequest":
104
+ return EntityTransformRequest(
105
+ config=self.config,
106
+ attribute_transformers=self.attribute_transformers,
107
+ global_transformers=self.global_transformers,
108
+ entities=entities,
109
+ )
110
+
111
+
112
+ class EntityTransformRequest(BaseTransformRequest):
113
+ entities: Annotated[list[AttributeValueEntity], Field(min_length=1)]
114
+
115
+
116
+ class EntityTransformResponse(ParentModel):
117
+ config: TransformConfig
118
+ entities: list[AttributeValueEntity]
@@ -0,0 +1,324 @@
1
+ Metadata-Version: 2.4
2
+ Name: fable-model
3
+ Version: 0.1.7
4
+ Summary: Data models utilized in the FABLE ecosystem's HTTP-based PPRL service.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: record linkage,privacy,bloom filter
8
+ Author: Maximilian Jugl
9
+ Requires-Python: >=3.10
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Dist: pydantic (>=2.7.0,<3.0.0)
21
+ Project-URL: Repository, https://github.com/ul-mds/fable-model
22
+ Description-Content-Type: text/markdown
23
+
24
+ [![PyPI](https://img.shields.io/pypi/v/fable-model?cacheSeconds=0)](https://pypi.org/project/fable-model/)
25
+ [![Python Versions](https://img.shields.io/pypi/pyversions/fable-model?cacheSeconds=0)](https://pypi.org/project/fable-model/)
26
+ ![Code Coverage](https://img.shields.io/badge/Coverage-98%25-brightgreen.svg)
27
+ [![License](https://img.shields.io/pypi/l/fable-model?cacheSeconds=0)](https://pypi.org/project/fable-model/)
28
+
29
+ # FABLE Model
30
+
31
+ This package contains model classes that are used in the FABLE (**F**ederated
32
+ **A**nonymized **B**loom filter **L**inkage **E**ngine) ecosystem's PPRL service for validation purposes.
33
+ They were developed with the intention of creating an HTTP-based service for Bloom filter-based record linkage.
34
+ It includes models for the service's data transformation, masking and bit vector matching routines.
35
+ Validation, serialization and deserialization are done using [Pydantic](https://docs.pydantic.dev/latest/).
36
+ It is rare to use this package directly.
37
+ Rather, it powers the functionalities of other packages.
38
+
39
+ ## Data models
40
+
41
+ Models for entity pre-processing, masking and bit vector matching are exposed through this package.
42
+ The following examples are taken from the test suites of the
43
+ [FABLE PPRL service package](https://github.com/ul-mds/fable-pprl-service) and show additional
44
+ validation steps in addition to the ones native to Pydantic.
45
+
46
+ ### Entity transformation
47
+
48
+ ```python
49
+ from fable_model import (
50
+ EntityTransformRequest,
51
+ TransformConfig,
52
+ EmptyValueHandling,
53
+ AttributeValueEntity,
54
+ AttributeTransformerConfig,
55
+ NumberTransformer,
56
+ GlobalTransformerConfig,
57
+ NormalizationTransformer,
58
+ CharacterFilterTransformer,
59
+ )
60
+
61
+ # This is a valid config.
62
+ _ = EntityTransformRequest(
63
+ config=TransformConfig(empty_value=EmptyValueHandling.ignore),
64
+ entities=[
65
+ AttributeValueEntity(
66
+ id="001",
67
+ attributes={
68
+ "bar1": " 12.345 ",
69
+ "bar2": " 12.345 "
70
+ }
71
+ )
72
+ ],
73
+ attribute_transformers=[
74
+ AttributeTransformerConfig(
75
+ attribute_name="bar1",
76
+ transformers=[
77
+ NumberTransformer(decimal_places=2)
78
+ ]
79
+ )
80
+ ],
81
+ global_transformers=GlobalTransformerConfig(
82
+ before=[
83
+ NormalizationTransformer()
84
+ ],
85
+ after=[
86
+ CharacterFilterTransformer(characters=".")
87
+ ]
88
+ )
89
+ )
90
+
91
+ from uuid import uuid4
92
+
93
+ # Validation will fail since no transformers have been defined.
94
+ _ = EntityTransformRequest(
95
+ config=TransformConfig(empty_value=EmptyValueHandling.ignore),
96
+ entities=[
97
+ AttributeValueEntity(
98
+ id=str(uuid4()),
99
+ attributes={
100
+ "foo": "bar"
101
+ }
102
+ )
103
+ ],
104
+ attribute_transformers=[]
105
+ )
106
+ # => ValidationError: attribute and global transformers are empty: must contain at least one
107
+ ```
108
+
109
+ ### Entity masking
110
+
111
+ ```python
112
+ from fable_model import (
113
+ EntityMaskRequest,
114
+ MaskConfig,
115
+ HashConfig,
116
+ HashFunction,
117
+ HashAlgorithm,
118
+ DoubleHash,
119
+ CLKFilter,
120
+ AttributeValueEntity,
121
+ StaticAttributeConfig,
122
+ AttributeSalt,
123
+ CLKRBFFilter,
124
+ )
125
+
126
+ # This is a valid config.
127
+ _ = EntityMaskRequest(
128
+ config=MaskConfig(
129
+ token_size=2,
130
+ hash=HashConfig(
131
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
132
+ strategy=DoubleHash()
133
+ ),
134
+ filter=CLKFilter(filter_size=1024, hash_values=5),
135
+ padding="_"
136
+ ),
137
+ entities=[
138
+ AttributeValueEntity(
139
+ id="001",
140
+ attributes={
141
+ "first_name": "John",
142
+ "last_name": "Doe",
143
+ "date_of_birth": "1987-06-05",
144
+ "gender": "m"
145
+ }
146
+ )
147
+ ]
148
+ )
149
+
150
+ # This is an invalid config since salting an attribute can only be done through a fixed value
151
+ # or another attribute on an entity, not both at the same time.
152
+ _ = EntityMaskRequest(
153
+ config=MaskConfig(
154
+ token_size=2,
155
+ hash=HashConfig(
156
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
157
+ strategy=DoubleHash()
158
+ ),
159
+ filter=CLKFilter(filter_size=1024, hash_values=5),
160
+ padding="_"
161
+ ),
162
+ entities=[
163
+ AttributeValueEntity(
164
+ id="001",
165
+ attributes={
166
+ "first_name": "foobar",
167
+ "salt": "0123456789"
168
+ }
169
+ )
170
+ ],
171
+ attributes=[
172
+ StaticAttributeConfig(
173
+ attribute_name="first_name",
174
+ salt=AttributeSalt(
175
+ value="my_salt",
176
+ attribute="salt"
177
+ )
178
+ )
179
+ ]
180
+ )
181
+ # => ValidationError: value and attribute cannot be set at the same time
182
+
183
+ # This also fails if neither a static value nor an attribute are set for salting.
184
+ _ = EntityMaskRequest(
185
+ config=MaskConfig(
186
+ token_size=2,
187
+ hash=HashConfig(
188
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
189
+ strategy=DoubleHash()
190
+ ),
191
+ filter=CLKFilter(filter_size=1024, hash_values=5),
192
+ padding="_"
193
+ ),
194
+ entities=[
195
+ AttributeValueEntity(
196
+ id="001",
197
+ attributes={
198
+ "first_name": "foobar",
199
+ "salt": "0123456789"
200
+ }
201
+ )
202
+ ],
203
+ attributes=[
204
+ StaticAttributeConfig(
205
+ attribute_name="first_name",
206
+ salt=AttributeSalt()
207
+ )
208
+ ]
209
+ )
210
+ # => ValidationError: neither value nor attribute is set
211
+
212
+ # When using a weighted filter (RBF, CLKRBF), an error will be thrown if any attribute configuration
213
+ # provided is static, not weighted. The same applies vice versa, meaning if CLK is specified as a filter and
214
+ # weighted attribute configurations are provided.
215
+ _ = EntityMaskRequest(
216
+ config=MaskConfig(
217
+ token_size=2,
218
+ hash=HashConfig(
219
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
220
+ strategy=DoubleHash()
221
+ ),
222
+ filter=CLKRBFFilter(hash_values=5),
223
+ padding="_"
224
+ ),
225
+ entities=[
226
+ AttributeValueEntity(
227
+ id="001",
228
+ attributes={
229
+ "first_name": "foobar",
230
+ "salt": "0123456789"
231
+ }
232
+ )
233
+ ],
234
+ attributes=[
235
+ StaticAttributeConfig(
236
+ attribute_name="first_name",
237
+ salt=AttributeSalt(value="my_salt")
238
+ )
239
+ ]
240
+ )
241
+ # => ValidationError: `clkrbf` filters require weighted attribute configurations, but static ones were found
242
+
243
+ # Weighted filters (RBF, CLKRBF) always require weighted attribute configurations. If none
244
+ # are provided, validation fails.
245
+ _ = EntityMaskRequest(
246
+ config=MaskConfig(
247
+ token_size=2,
248
+ hash=HashConfig(
249
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
250
+ strategy=DoubleHash()
251
+ ),
252
+ filter=CLKRBFFilter(hash_values=5),
253
+ padding="_"
254
+ ),
255
+ entities=[
256
+ AttributeValueEntity(
257
+ id="001",
258
+ attributes={
259
+ "first_name": "foobar",
260
+ "salt": "0123456789"
261
+ }
262
+ )
263
+ ]
264
+ )
265
+ # => ValidationError: `clkrbf` filters require weighted attribute configurations, but none were found
266
+
267
+ # If a configuration is provided for an attribute that doesn't exist on some entities, validation fails.
268
+ _ = EntityMaskRequest(
269
+ config=MaskConfig(
270
+ token_size=2,
271
+ hash=HashConfig(
272
+ function=HashFunction(algorithms=[HashAlgorithm.sha1]),
273
+ strategy=DoubleHash()
274
+ ),
275
+ filter=CLKFilter(filter_size=1024, hash_values=5),
276
+ padding="_"
277
+ ),
278
+ entities=[
279
+ AttributeValueEntity(
280
+ id="001",
281
+ attributes={
282
+ "first_name": "foobar"
283
+ }
284
+ )
285
+ ],
286
+ attributes=[
287
+ StaticAttributeConfig(
288
+ attribute_name="last_name",
289
+ salt=AttributeSalt(value="my_salt")
290
+ )
291
+ ]
292
+ )
293
+ # => ValidationError: some configured attributes are not present on entities: `last_name` on entities with ID `001`
294
+ ```
295
+
296
+ ### Bit vector matching
297
+
298
+ ```python
299
+ from fable_model import VectorMatchRequest, MatchConfig, SimilarityMeasure, BitVectorEntity
300
+
301
+ _ = VectorMatchRequest(
302
+ config=MatchConfig(
303
+ measure=SimilarityMeasure.jaccard,
304
+ threshold=0.8
305
+ ),
306
+ domain=[
307
+ BitVectorEntity(
308
+ id="D001",
309
+ value="kY7yXn+rmp8L0nyGw5NlMw=="
310
+ )
311
+ ],
312
+ range=[
313
+ BitVectorEntity(
314
+ id="R001",
315
+ value="qig0C1i8YttqhPwo4VqLlg=="
316
+ )
317
+ ]
318
+ )
319
+ ```
320
+
321
+ ## License
322
+
323
+ MIT.
324
+
@@ -0,0 +1,9 @@
1
+ fable_model/__init__.py,sha256=AmmVhPKSBZsKHcmo7OGka6TChIDzT-GeWo7ErgZW5Z4,2671
2
+ fable_model/common.py,sha256=OspzFIWtm4T4BgdeluuSaJAmlLYy-YZuIqERf9nt7o4,370
3
+ fable_model/mask.py,sha256=r3byVS8-08zDfzRrousf6DSsvN8qil5l0ABhZvSZyQM,9095
4
+ fable_model/match.py,sha256=nHH-mK7gthCtq31-lcP4k59rxR8m4gBzMN9ciW93XHg,1182
5
+ fable_model/transform.py,sha256=yWmN7OWE8P8wtNAqU1NZeyk5kDn-pymkSokx9fj2qnk,3642
6
+ fable_model-0.1.7.dist-info/METADATA,sha256=OutOur1YL5qwJOQ72sGJ0ZMkOBwcKHayT6_g81BbumI,9466
7
+ fable_model-0.1.7.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
8
+ fable_model-0.1.7.dist-info/licenses/LICENSE,sha256=Q-Ktj_VJi4SeAGoslkUojX0DD9cZFxaw36u4FR5f61o,1117
9
+ fable_model-0.1.7.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 University Medical Center Leipzig, Dept. Medical Data Science
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.