mostlyai 5.9.2__tar.gz → 5.10.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. {mostlyai-5.9.2 → mostlyai-5.10.0}/PKG-INFO +15 -15
  2. {mostlyai-5.9.2 → mostlyai-5.10.0}/README.md +2 -2
  3. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/__init__.py +2 -2
  4. mostlyai-5.10.0/mostlyai/sdk/_data/constraints/transformations.py +190 -0
  5. mostlyai-5.10.0/mostlyai/sdk/_data/constraints/types/__init__.py +25 -0
  6. mostlyai-5.10.0/mostlyai/sdk/_data/constraints/types/base.py +54 -0
  7. mostlyai-5.10.0/mostlyai/sdk/_data/constraints/types/fixed_combinations.py +95 -0
  8. mostlyai-5.10.0/mostlyai/sdk/_data/constraints/types/inequality.py +148 -0
  9. mostlyai-5.10.0/mostlyai/sdk/_local/__init__.py +13 -0
  10. mostlyai-5.10.0/mostlyai/sdk/_local/execution/__init__.py +13 -0
  11. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_analyze_training_data.py +1 -1
  12. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_create_data_report.py +1 -1
  13. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_create_model_report.py +4 -1
  14. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_deliver_data.py +1 -1
  15. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_encode_training_data.py +1 -1
  16. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_finalize_generation.py +1 -1
  17. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_finalize_training.py +1 -1
  18. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_generate_data.py +12 -1
  19. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_generate_model_report_data.py +1 -1
  20. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_pull_training_data.py +15 -1
  21. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/step_train_model.py +1 -1
  22. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/generators.py +2 -0
  23. mostlyai-5.10.0/mostlyai/sdk/client/__init__.py +13 -0
  24. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/_base_utils.py +1 -1
  25. mostlyai-5.10.0/mostlyai/sdk/client/_constraint_types.py +208 -0
  26. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/_naming_conventions.py +1 -1
  27. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/_utils.py +1 -1
  28. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/api.py +36 -1
  29. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/base.py +1 -1
  30. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/connectors.py +1 -1
  31. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/exceptions.py +1 -1
  32. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/generators.py +1 -1
  33. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/integrations.py +1 -1
  34. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/synthetic_datasets.py +1 -1
  35. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/domain.py +99 -3
  36. {mostlyai-5.9.2 → mostlyai-5.10.0}/pyproject.toml +13 -13
  37. mostlyai-5.9.2/mostlyai/sdk/_local/__init__.py +0 -13
  38. mostlyai-5.9.2/mostlyai/sdk/_local/execution/__init__.py +0 -13
  39. mostlyai-5.9.2/mostlyai/sdk/client/__init__.py +0 -13
  40. {mostlyai-5.9.2 → mostlyai-5.10.0}/.gitignore +0 -0
  41. {mostlyai-5.9.2 → mostlyai-5.10.0}/LICENSE +0 -0
  42. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/__init__.py +0 -0
  43. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/auto_detect.py +0 -0
  44. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/base.py +0 -0
  45. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/context.py +0 -0
  46. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/conversions.py +0 -0
  47. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/__init__.py +0 -0
  48. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/base.py +0 -0
  49. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/bigquery.py +0 -0
  50. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/databricks.py +0 -0
  51. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/hive.py +0 -0
  52. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/mssql.py +0 -0
  53. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/mysql.py +0 -0
  54. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/oracle.py +0 -0
  55. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/postgresql.py +0 -0
  56. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/redshift.py +0 -0
  57. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/snowflake.py +0 -0
  58. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/sqlite.py +0 -0
  59. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/db/types_coercion.py +0 -0
  60. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/dtype.py +0 -0
  61. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/exceptions.py +0 -0
  62. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/__init__.py +0 -0
  63. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/base.py +0 -0
  64. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/__init__.py +0 -0
  65. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/aws.py +0 -0
  66. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/azure.py +0 -0
  67. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/bucket_based.py +0 -0
  68. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/gcs.py +0 -0
  69. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/container/minio.py +0 -0
  70. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/table/__init__.py +0 -0
  71. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/table/csv.py +0 -0
  72. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/table/feather.py +0 -0
  73. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/table/json.py +0 -0
  74. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/table/parquet.py +0 -0
  75. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/file/utils.py +0 -0
  76. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/language_model.py +0 -0
  77. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/metadata_objects.py +0 -0
  78. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/non_context.py +0 -0
  79. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/progress_callback.py +0 -0
  80. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/pull.py +0 -0
  81. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/pull_context.py +0 -0
  82. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/pull_utils.py +0 -0
  83. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/push.py +0 -0
  84. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/util/__init__.py +0 -0
  85. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/util/common.py +0 -0
  86. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_data/util/kerberos.py +0 -0
  87. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/cli.py +0 -0
  88. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/connectors.py +0 -0
  89. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/jobs.py +0 -0
  90. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/migration.py +0 -0
  91. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/execution/plan.py +0 -0
  92. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/progress.py +0 -0
  93. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/routes.py +0 -0
  94. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/server.py +0 -0
  95. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/storage.py +0 -0
  96. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/_local/synthetic_datasets.py +0 -0
  97. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/artifacts.py +0 -0
  98. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/client/datasets.py +0 -0
  99. {mostlyai-5.9.2 → mostlyai-5.10.0}/mostlyai/sdk/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mostlyai
3
- Version: 5.9.2
3
+ Version: 5.10.0
4
4
  Summary: Synthetic Data SDK
5
5
  Project-URL: homepage, https://app.mostly.ai/
6
6
  Project-URL: repository, https://github.com/mostly-ai/mostlyai
@@ -56,11 +56,11 @@ Provides-Extra: local
56
56
  Requires-Dist: adlfs>=2023.4.0; extra == 'local'
57
57
  Requires-Dist: azure-storage-blob>=12.16.0; extra == 'local'
58
58
  Requires-Dist: cloudpathlib[azure,gs,s3]>=0.17.0; extra == 'local'
59
- Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local'
59
+ Requires-Dist: fastapi<0.125,>=0.116.0; extra == 'local'
60
60
  Requires-Dist: filelock>=3.16.1; extra == 'local'
61
61
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local'
62
62
  Requires-Dist: joblib>=1.4.2; extra == 'local'
63
- Requires-Dist: mostlyai-engine==2.3.3; extra == 'local'
63
+ Requires-Dist: mostlyai-engine==2.4.0; extra == 'local'
64
64
  Requires-Dist: mostlyai-qa==1.9.8; extra == 'local'
65
65
  Requires-Dist: networkx<4,>=3.0; extra == 'local'
66
66
  Requires-Dist: openpyxl>=3.1.5; extra == 'local'
@@ -69,20 +69,20 @@ Requires-Dist: s3fs>=2023.1.0; extra == 'local'
69
69
  Requires-Dist: smart-open[azure,gcs,s3]>=6.3.0; extra == 'local'
70
70
  Requires-Dist: sqlalchemy>=2.0.0; extra == 'local'
71
71
  Requires-Dist: sshtunnel<0.5,>=0.4.0; extra == 'local'
72
- Requires-Dist: torch<2.8.1,>=2.8.0; extra == 'local'
73
- Requires-Dist: torchaudio<2.8.1,>=2.8.0; extra == 'local'
74
- Requires-Dist: torchvision<0.23.1,>=0.23.0; extra == 'local'
75
- Requires-Dist: uvicorn<0.35,>=0.34.0; extra == 'local'
72
+ Requires-Dist: torch<2.10.0,>=2.9.0; extra == 'local'
73
+ Requires-Dist: torchaudio<2.10.0,>=2.9.0; extra == 'local'
74
+ Requires-Dist: torchvision<0.25.0,>=0.24.0; extra == 'local'
75
+ Requires-Dist: uvicorn>=0.34.0; extra == 'local'
76
76
  Requires-Dist: xlsxwriter<4,>=3.1.9; extra == 'local'
77
77
  Provides-Extra: local-gpu
78
78
  Requires-Dist: adlfs>=2023.4.0; extra == 'local-gpu'
79
79
  Requires-Dist: azure-storage-blob>=12.16.0; extra == 'local-gpu'
80
80
  Requires-Dist: cloudpathlib[azure,gs,s3]>=0.17.0; extra == 'local-gpu'
81
- Requires-Dist: fastapi<0.116,>=0.115.6; extra == 'local-gpu'
81
+ Requires-Dist: fastapi<0.125,>=0.116.0; extra == 'local-gpu'
82
82
  Requires-Dist: filelock>=3.16.1; extra == 'local-gpu'
83
83
  Requires-Dist: gcsfs>=2023.1.0; extra == 'local-gpu'
84
84
  Requires-Dist: joblib>=1.4.2; extra == 'local-gpu'
85
- Requires-Dist: mostlyai-engine[gpu]==2.3.3; extra == 'local-gpu'
85
+ Requires-Dist: mostlyai-engine[gpu]==2.4.0; extra == 'local-gpu'
86
86
  Requires-Dist: mostlyai-qa==1.9.8; extra == 'local-gpu'
87
87
  Requires-Dist: networkx<4,>=3.0; extra == 'local-gpu'
88
88
  Requires-Dist: openpyxl>=3.1.5; extra == 'local-gpu'
@@ -91,10 +91,10 @@ Requires-Dist: s3fs>=2023.1.0; extra == 'local-gpu'
91
91
  Requires-Dist: smart-open[azure,gcs,s3]>=6.3.0; extra == 'local-gpu'
92
92
  Requires-Dist: sqlalchemy>=2.0.0; extra == 'local-gpu'
93
93
  Requires-Dist: sshtunnel<0.5,>=0.4.0; extra == 'local-gpu'
94
- Requires-Dist: torch<2.8.1,>=2.8.0; extra == 'local-gpu'
95
- Requires-Dist: torchaudio<2.8.1,>=2.8.0; extra == 'local-gpu'
96
- Requires-Dist: torchvision<0.23.1,>=0.23.0; extra == 'local-gpu'
97
- Requires-Dist: uvicorn<0.35,>=0.34.0; extra == 'local-gpu'
94
+ Requires-Dist: torch<2.10.0,>=2.9.0; extra == 'local-gpu'
95
+ Requires-Dist: torchaudio<2.10.0,>=2.9.0; extra == 'local-gpu'
96
+ Requires-Dist: torchvision<0.25.0,>=0.24.0; extra == 'local-gpu'
97
+ Requires-Dist: uvicorn>=0.34.0; extra == 'local-gpu'
98
98
  Requires-Dist: xlsxwriter<4,>=3.1.9; extra == 'local-gpu'
99
99
  Provides-Extra: mssql
100
100
  Requires-Dist: pyodbc<6,>=5.1.0; extra == 'mssql'
@@ -329,12 +329,12 @@ On Linux, one can explicitly install the CPU-only variant of torch together with
329
329
 
330
330
  ```shell
331
331
  # uv pip install
332
- uv pip install --index-strategy unsafe-first-match -U torch==2.8.0+cpu torchvision==0.23.0+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
332
+ uv pip install --index-strategy unsafe-first-match -U torch==2.9.1+cpu torchvision==0.24.1+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
333
333
  ```
334
334
 
335
335
  ```shell
336
336
  # standard pip install
337
- pip install -U torch==2.8.0+cpu torchvision==0.23.0+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
337
+ pip install -U torch==2.9.1+cpu torchvision==0.24.1+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
338
338
  ```
339
339
 
340
340
 
@@ -217,12 +217,12 @@ On Linux, one can explicitly install the CPU-only variant of torch together with
217
217
 
218
218
  ```shell
219
219
  # uv pip install
220
- uv pip install --index-strategy unsafe-first-match -U torch==2.8.0+cpu torchvision==0.23.0+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
220
+ uv pip install --index-strategy unsafe-first-match -U torch==2.9.1+cpu torchvision==0.24.1+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
221
221
  ```
222
222
 
223
223
  ```shell
224
224
  # standard pip install
225
- pip install -U torch==2.8.0+cpu torchvision==0.23.0+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
225
+ pip install -U torch==2.9.1+cpu torchvision==0.24.1+cpu 'mostlyai[local]' --extra-index-url https://download.pytorch.org/whl/cpu
226
226
  ```
227
227
 
228
228
 
@@ -1,4 +1,4 @@
1
- # Copyright 2024-2025 MOSTLY AI
1
+ # Copyright 2025 MOSTLY AI
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -49,4 +49,4 @@ For more information, visit: https://mostly-ai.github.io/mostlyai/
49
49
  from mostlyai.sdk.client.api import MostlyAI
50
50
 
51
51
  __all__ = ["MostlyAI"]
52
- __version__ = "5.9.2" # Do not set this manually. Use poetry version [params].
52
+ __version__ = "5.10.0" # Do not set this manually. Use poetry version [params].
@@ -0,0 +1,190 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """constraint transformation utilities."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ from pathlib import Path
22
+
23
+ import pandas as pd
24
+
25
+ from mostlyai.sdk._data.constraints.types import (
26
+ ConstraintHandler,
27
+ FixedCombinationsHandler,
28
+ InequalityHandler,
29
+ )
30
+ from mostlyai.sdk.client._constraint_types import (
31
+ FixedCombinations,
32
+ Inequality,
33
+ convert_constraint_config_to_typed,
34
+ )
35
+ from mostlyai.sdk.domain import Generator
36
+
37
+ _LOG = logging.getLogger(__name__)
38
+
39
+ # type alias for constraint types
40
+ ConstraintType = FixedCombinations | Inequality
41
+
42
+
43
+ def _create_constraint_handler(constraint: ConstraintType, table=None) -> ConstraintHandler:
44
+ """factory function to create appropriate handler for a constraint."""
45
+ if isinstance(constraint, FixedCombinations):
46
+ return FixedCombinationsHandler(constraint)
47
+ elif isinstance(constraint, Inequality):
48
+ return InequalityHandler(constraint, table=table)
49
+ else:
50
+ raise ValueError(f"unknown constraint type: {type(constraint)}")
51
+
52
+
53
+ class ConstraintTranslator:
54
+ """translates data between user schema and internal schema for constraints."""
55
+
56
+ def __init__(self, constraints: list[ConstraintType], table=None):
57
+ self.constraints = constraints
58
+ self.table = table
59
+ self.handlers = [_create_constraint_handler(c, table=table) for c in constraints]
60
+
61
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
62
+ """transform dataframe from user schema to internal schema."""
63
+ for handler in self.handlers:
64
+ df = handler.to_internal(df)
65
+ return df
66
+
67
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
68
+ """transform dataframe from internal schema back to user schema."""
69
+ for handler in self.handlers:
70
+ df = handler.to_original(df)
71
+ return df
72
+
73
+ def get_all_column_names(self, original_column_names: list[str]) -> list[str]:
74
+ """get list of all column names (original and internal constraint columns)."""
75
+ all_column_names = list(original_column_names)
76
+ for handler in self.handlers:
77
+ all_column_names.extend(handler.get_internal_column_names())
78
+ return all_column_names
79
+
80
+ def get_encoding_types(self) -> dict[str, str]:
81
+ """get combined encoding types for all internal columns."""
82
+ encoding_types = {}
83
+ for handler in self.handlers:
84
+ encoding_types.update(handler.get_encoding_types())
85
+ return encoding_types
86
+
87
+ @staticmethod
88
+ def from_generator_config(
89
+ generator: Generator,
90
+ table_name: str,
91
+ ) -> ConstraintTranslator | None:
92
+ """create constraint translator from generator configuration for a specific table."""
93
+ if not generator.constraints:
94
+ return None
95
+
96
+ table = next((t for t in generator.tables if t.name == table_name), None)
97
+ if not table:
98
+ return None
99
+
100
+ # convert constraints to typed objects and filter by table_name
101
+ typed_constraints = []
102
+ for constraint in generator.constraints:
103
+ typed_constraint = convert_constraint_config_to_typed(constraint)
104
+ if typed_constraint.table_name == table_name:
105
+ typed_constraints.append(typed_constraint)
106
+
107
+ if not typed_constraints:
108
+ return None
109
+
110
+ # pass table to translator so handlers can check column types
111
+ constraint_translator = ConstraintTranslator(typed_constraints, table=table)
112
+ return constraint_translator
113
+
114
+
115
+ def preprocess_constraints_for_training(
116
+ *,
117
+ generator: Generator,
118
+ workspace_dir: Path,
119
+ target_table_name: str,
120
+ ) -> list[str] | None:
121
+ """preprocess constraint transformations for training data:
122
+ - transform constraints from user schema to internal schema (if any)
123
+ - update tgt-meta (encoding-types) and tgt-data with internal columns (if any)
124
+ - return list of all column names (original and internal constraint columns) for use in training
125
+ """
126
+ target_table = next((t for t in generator.tables if t.name == target_table_name), None)
127
+ if not target_table:
128
+ _LOG.debug(f"table {target_table_name} not found in generator")
129
+ return None
130
+
131
+ if not generator.constraints:
132
+ return None
133
+
134
+ # convert constraints to typed objects and filter by table_name
135
+ typed_constraints = []
136
+ for constraint in generator.constraints:
137
+ typed_constraint = convert_constraint_config_to_typed(constraint)
138
+ if typed_constraint.table_name == target_table_name:
139
+ typed_constraints.append(typed_constraint)
140
+
141
+ if not typed_constraints:
142
+ return None
143
+
144
+ _LOG.info(f"preprocessing constraints for table {target_table_name}")
145
+ # pass table to translator so handlers can check column types
146
+ constraint_translator = ConstraintTranslator(typed_constraints, table=target_table)
147
+
148
+ tgt_data_dir = workspace_dir / "OriginalData" / "tgt-data"
149
+ if not tgt_data_dir.exists():
150
+ _LOG.warning(f"data directory not found: {tgt_data_dir}")
151
+ return None
152
+
153
+ parquet_files = sorted(list(tgt_data_dir.glob("part.*.parquet")))
154
+ for parquet_file in parquet_files:
155
+ df = pd.read_parquet(parquet_file)
156
+ df_transformed = constraint_translator.to_internal(df)
157
+ df_transformed.to_parquet(parquet_file, index=True)
158
+
159
+ original_columns = [c.name for c in target_table.columns] if target_table.columns else []
160
+ _update_meta_with_internal_columns(workspace_dir, target_table_name, constraint_translator, parquet_files)
161
+ all_column_names = constraint_translator.get_all_column_names(original_columns)
162
+ return all_column_names
163
+
164
+
165
+ def _update_meta_with_internal_columns(
166
+ workspace_dir: Path,
167
+ table_name: str,
168
+ constraint_translator: ConstraintTranslator,
169
+ parquet_files: list[Path],
170
+ ) -> None:
171
+ """update tgt-meta to reflect internal column structure after transformation."""
172
+ if not parquet_files:
173
+ return
174
+
175
+ meta_dir = workspace_dir / "OriginalData" / "tgt-meta"
176
+ meta_dir.mkdir(parents=True, exist_ok=True)
177
+ encoding_types_file = meta_dir / "encoding-types.json"
178
+
179
+ if encoding_types_file.exists():
180
+ with open(encoding_types_file) as f:
181
+ encoding_types = json.load(f)
182
+
183
+ encoding_types.update(constraint_translator.get_encoding_types())
184
+
185
+ with open(encoding_types_file, "w") as f:
186
+ json.dump(encoding_types, f, indent=2)
187
+
188
+ _LOG.debug(f"updated encoding-types.json with internal columns for {table_name}")
189
+ else:
190
+ _LOG.error(f"encoding-types.json not found to update internal columns for {table_name}")
@@ -0,0 +1,25 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """constraint type handlers."""
16
+
17
+ from mostlyai.sdk._data.constraints.types.base import ConstraintHandler
18
+ from mostlyai.sdk._data.constraints.types.fixed_combinations import FixedCombinationsHandler
19
+ from mostlyai.sdk._data.constraints.types.inequality import InequalityHandler
20
+
21
+ __all__ = [
22
+ "ConstraintHandler",
23
+ "FixedCombinationsHandler",
24
+ "InequalityHandler",
25
+ ]
@@ -0,0 +1,54 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """base constraint handler class."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from abc import ABC, abstractmethod
20
+
21
+ import pandas as pd
22
+
23
+
24
+ class ConstraintHandler(ABC):
25
+ """abstract base class for constraint handlers."""
26
+
27
+ @abstractmethod
28
+ def get_internal_column_names(self) -> list[str]:
29
+ """return list of internal column names created by this handler."""
30
+ pass
31
+
32
+ @abstractmethod
33
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
34
+ """transform dataframe (in-place) from user schema to internal schema."""
35
+ pass
36
+
37
+ @abstractmethod
38
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
39
+ """transform dataframe (in-place) from internal schema back to user schema."""
40
+ pass
41
+
42
+ @abstractmethod
43
+ def get_encoding_types(self) -> dict[str, str]:
44
+ """return encoding types for internal columns."""
45
+ pass
46
+
47
+ def _validate_columns(self, df: pd.DataFrame, columns: list[str]) -> None:
48
+ """validate that all required columns exist in the dataframe."""
49
+ missing_cols = set(columns) - set(df.columns)
50
+ if missing_cols:
51
+ raise ValueError(
52
+ f"Columns {sorted(missing_cols)} required by {self.__class__.__name__} "
53
+ f"not found in dataframe. Available columns: {sorted(df.columns)}"
54
+ )
@@ -0,0 +1,95 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """fixed combinations constraint handler."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import logging
22
+
23
+ import pandas as pd
24
+
25
+ from mostlyai.sdk._data.constraints.types.base import ConstraintHandler
26
+ from mostlyai.sdk.client._constraint_types import FixedCombinations
27
+
28
+ _LOG = logging.getLogger(__name__)
29
+
30
+
31
+ def _generate_internal_column_name(prefix: str, columns: list[str]) -> str:
32
+ """generate a deterministic internal column name."""
33
+ key = "|".join(columns)
34
+ hash_suffix = hashlib.md5(key.encode()).hexdigest()[:8]
35
+ columns_str = "_".join(col.upper() for col in columns)
36
+ return f"__CONSTRAINT_{prefix}_{columns_str}_{hash_suffix}__"
37
+
38
+
39
+ class FixedCombinationsHandler(ConstraintHandler):
40
+ """handler for FixedCombinations constraints."""
41
+
42
+ def __init__(self, constraint: FixedCombinations):
43
+ self.constraint = constraint
44
+ self.table_name = constraint.table_name
45
+ self.columns = constraint.columns
46
+ self.merged_name = _generate_internal_column_name("FC", self.columns)
47
+
48
+ def get_internal_column_names(self) -> list[str]:
49
+ return [self.merged_name]
50
+
51
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
52
+ self._validate_columns(df, self.columns)
53
+
54
+ def merge_row(row):
55
+ values = [row[col] if pd.notna(row[col]) else None for col in self.columns]
56
+ # JSON serialization handles all escaping automatically
57
+ return json.dumps(values, ensure_ascii=False)
58
+
59
+ df[self.merged_name] = df.apply(merge_row, axis=1)
60
+ return df
61
+
62
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
63
+ if self.merged_name in df.columns:
64
+
65
+ def split_row(merged_value: str) -> list[str]:
66
+ if pd.isna(merged_value):
67
+ return [""] * len(self.columns)
68
+ elif merged_value == "_RARE_":
69
+ return ["_RARE_"] * len(self.columns)
70
+ try:
71
+ values = json.loads(merged_value)
72
+ return [str(v) if v is not None else "" for v in values]
73
+ except json.JSONDecodeError:
74
+ _LOG.error(f"failed to decode JSON for {merged_value}; using empty values")
75
+ return [""] * len(self.columns)
76
+
77
+ split_values = df[self.merged_name].apply(split_row)
78
+ split_df = pd.DataFrame(split_values.tolist(), index=df.index)
79
+
80
+ # preserve original index
81
+ original_index = df.index
82
+ split_df.index = original_index
83
+
84
+ # assign to original columns
85
+ for i, col in enumerate(self.columns):
86
+ df[col] = split_df[i].values
87
+
88
+ # drop the merged column
89
+ df = df.drop(columns=[self.merged_name])
90
+ return df
91
+
92
+ def get_encoding_types(self) -> dict[str, str]:
93
+ # always use TABULAR encoding for constraints, regardless of model_type
94
+ # constraints merge columns which requires categorical encoding
95
+ return {self.merged_name: "TABULAR_CATEGORICAL"}
@@ -0,0 +1,148 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """inequality constraint handler."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import logging
21
+
22
+ import pandas as pd
23
+
24
+ from mostlyai.sdk._data.constraints.types.base import ConstraintHandler
25
+ from mostlyai.sdk.client._constraint_types import Inequality
26
+ from mostlyai.sdk.domain import ModelEncodingType
27
+
28
+ _LOG = logging.getLogger(__name__)
29
+
30
+
31
+ def _generate_internal_column_name(prefix: str, columns: list[str]) -> str:
32
+ """generate a deterministic internal column name."""
33
+ key = "|".join(columns)
34
+ hash_suffix = hashlib.md5(key.encode()).hexdigest()[:8]
35
+ columns_str = "_".join(col.upper() for col in columns)
36
+ return f"__CONSTRAINT_{prefix}_{columns_str}_{hash_suffix}__"
37
+
38
+
39
+ class InequalityHandler(ConstraintHandler):
40
+ """handler for Inequality constraints (low <= high)."""
41
+
42
+ _DATETIME_EPOCH = pd.Timestamp("1970-01-01") # reference epoch for delta representation
43
+
44
+ def __init__(self, constraint: Inequality, table=None):
45
+ self.constraint = constraint
46
+ self.table_name = constraint.table_name
47
+ self.low_column = constraint.low_column
48
+ self.high_column = constraint.high_column
49
+ self._delta_column = _generate_internal_column_name("INEQ_DELTA", [self.low_column, self.high_column])
50
+
51
+ # determine if this is a datetime constraint based on table encoding types
52
+ self._is_datetime = False
53
+ if table and table.columns:
54
+ datetime_encodings = {
55
+ ModelEncodingType.tabular_datetime,
56
+ # ModelEncodingType.tabular_datetime_relative, # not supported yet
57
+ }
58
+ # check if either column is datetime-encoded
59
+ self._is_datetime = all(
60
+ col.model_encoding_type in datetime_encodings
61
+ for col in table.columns
62
+ if col.name in {self.low_column, self.high_column}
63
+ )
64
+
65
+ def __repr__(self) -> str:
66
+ return f"{self.low_column} <= {self.high_column}"
67
+
68
+ def get_internal_column_names(self) -> list[str]:
69
+ return [self._delta_column]
70
+
71
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
72
+ self._validate_columns(df, [self.low_column, self.high_column])
73
+ low = df[self.low_column]
74
+ high = df[self.high_column]
75
+
76
+ # handle NAs: if either low or high is NA, set delta to NA
77
+ na_mask = low.isna() | high.isna()
78
+
79
+ zero = pd.Timedelta(0) if self._is_datetime else 0
80
+ delta = high - low
81
+
82
+ # set delta to NA where either low or high is NA
83
+ delta[na_mask] = pd.NA
84
+
85
+ # only check violations where we have valid values
86
+ violations = (delta < zero) & ~na_mask
87
+ if violations.any():
88
+ _LOG.warning(f"detected {violations.sum() / len(delta) * 100:.2f}% inequality violations for {self}")
89
+
90
+ # convert timedelta to datetime using epoch (for datetime constraints)
91
+ if self._is_datetime:
92
+ # represent delta as datetime: epoch + timedelta
93
+ # preserve NAs during conversion
94
+ delta = delta.where(na_mask, self._DATETIME_EPOCH + delta)
95
+ # for numeric, keep as-is (numeric delta)
96
+
97
+ df[self._delta_column] = delta
98
+ return df
99
+
100
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
101
+ """transform from internal schema back to original schema."""
102
+ if self._delta_column not in df.columns:
103
+ return df
104
+
105
+ # prepare data and types
106
+ low = df[self.low_column]
107
+ delta = df[self._delta_column]
108
+ high_dtype = df[self.high_column].dtype
109
+
110
+ # convert datetime back to timedelta if needed
111
+ if self._is_datetime:
112
+ # ensure delta is datetime dtype before subtraction
113
+ delta = pd.to_datetime(delta)
114
+ # preserve NAs during conversion
115
+ delta = delta - self._DATETIME_EPOCH
116
+ delta = delta.astype("timedelta64[ns]") # explicit dtype conversion
117
+
118
+ # RECONSTRUCTION
119
+ low_na = low.isna()
120
+ delta_na = delta.isna()
121
+
122
+ # if low != NA and delta != NA, then high = low + delta
123
+ both_valid = ~low_na & ~delta_na
124
+ df.loc[both_valid, self.high_column] = low[both_valid] + delta[both_valid]
125
+
126
+ # if low != NA and delta == NA, then high = NA
127
+ low_valid_delta_na = ~low_na & delta_na
128
+ df.loc[low_valid_delta_na, self.high_column] = pd.NA
129
+ # else, if low == NA, then high is kept as is
130
+
131
+ # if any violations made it through, apply a primitive correction
132
+ high = df[self.high_column]
133
+ both_valid_for_check = ~low_na & ~high.isna()
134
+ violations = both_valid_for_check & (high < low)
135
+ df.loc[violations, self.high_column] = low[violations]
136
+
137
+ # convert back to original dtype
138
+ if pd.api.types.is_integer_dtype(high_dtype):
139
+ df[self.high_column] = df[self.high_column].astype(high_dtype)
140
+
141
+ return df.drop(columns=[self._delta_column])
142
+
143
+ def get_encoding_types(self) -> dict[str, str]:
144
+ # use TABULAR_DATETIME for datetime constraints to preserve precision
145
+ # use TABULAR_NUMERIC_AUTO for numeric constraints
146
+ if self._is_datetime:
147
+ return {self._delta_column: "TABULAR_DATETIME"}
148
+ return {self._delta_column: "TABULAR_NUMERIC_AUTO"}
@@ -0,0 +1,13 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,13 @@
1
+ # Copyright 2025 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -1,4 +1,4 @@
1
- # Copyright 2024-2025 MOSTLY AI
1
+ # Copyright 2025 MOSTLY AI
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -1,4 +1,4 @@
1
- # Copyright 2024-2025 MOSTLY AI
1
+ # Copyright 2025 MOSTLY AI
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.