mostlyai 5.9.2__tar.gz → 5.10.1__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.1}/PKG-INFO +15 -15
  2. {mostlyai-5.9.2 → mostlyai-5.10.1}/README.md +2 -2
  3. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/__init__.py +2 -2
  4. mostlyai-5.10.1/mostlyai/sdk/_data/constraints/transformations.py +193 -0
  5. mostlyai-5.10.1/mostlyai/sdk/_data/constraints/types/__init__.py +25 -0
  6. mostlyai-5.10.1/mostlyai/sdk/_data/constraints/types/base.py +54 -0
  7. mostlyai-5.10.1/mostlyai/sdk/_data/constraints/types/fixed_combinations.py +95 -0
  8. mostlyai-5.10.1/mostlyai/sdk/_data/constraints/types/inequality.py +202 -0
  9. mostlyai-5.10.1/mostlyai/sdk/_local/__init__.py +13 -0
  10. mostlyai-5.10.1/mostlyai/sdk/_local/execution/__init__.py +13 -0
  11. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_analyze_training_data.py +1 -1
  12. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_create_data_report.py +1 -1
  13. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_create_model_report.py +4 -1
  14. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_deliver_data.py +1 -1
  15. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_encode_training_data.py +1 -1
  16. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_finalize_generation.py +1 -1
  17. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_finalize_training.py +1 -1
  18. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_generate_data.py +13 -1
  19. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_generate_model_report_data.py +1 -1
  20. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_pull_training_data.py +15 -1
  21. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/step_train_model.py +1 -1
  22. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/generators.py +2 -0
  23. mostlyai-5.10.1/mostlyai/sdk/client/__init__.py +13 -0
  24. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/_base_utils.py +1 -1
  25. mostlyai-5.10.1/mostlyai/sdk/client/_constraint_types.py +208 -0
  26. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/_naming_conventions.py +1 -1
  27. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/_utils.py +1 -1
  28. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/api.py +36 -1
  29. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/base.py +1 -1
  30. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/connectors.py +1 -1
  31. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/exceptions.py +1 -1
  32. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/generators.py +1 -1
  33. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/integrations.py +1 -1
  34. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/synthetic_datasets.py +1 -1
  35. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/domain.py +99 -3
  36. {mostlyai-5.9.2 → mostlyai-5.10.1}/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.1}/.gitignore +0 -0
  41. {mostlyai-5.9.2 → mostlyai-5.10.1}/LICENSE +0 -0
  42. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/__init__.py +0 -0
  43. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/auto_detect.py +0 -0
  44. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/base.py +0 -0
  45. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/context.py +0 -0
  46. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/conversions.py +0 -0
  47. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/__init__.py +0 -0
  48. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/base.py +0 -0
  49. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/bigquery.py +0 -0
  50. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/databricks.py +0 -0
  51. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/hive.py +0 -0
  52. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/mssql.py +0 -0
  53. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/mysql.py +0 -0
  54. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/oracle.py +0 -0
  55. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/postgresql.py +0 -0
  56. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/redshift.py +0 -0
  57. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/snowflake.py +0 -0
  58. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/sqlite.py +0 -0
  59. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/db/types_coercion.py +0 -0
  60. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/dtype.py +0 -0
  61. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/exceptions.py +0 -0
  62. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/__init__.py +0 -0
  63. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/base.py +0 -0
  64. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/__init__.py +0 -0
  65. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/aws.py +0 -0
  66. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/azure.py +0 -0
  67. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/bucket_based.py +0 -0
  68. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/gcs.py +0 -0
  69. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/container/minio.py +0 -0
  70. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/table/__init__.py +0 -0
  71. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/table/csv.py +0 -0
  72. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/table/feather.py +0 -0
  73. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/table/json.py +0 -0
  74. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/table/parquet.py +0 -0
  75. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/file/utils.py +0 -0
  76. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/language_model.py +0 -0
  77. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/metadata_objects.py +0 -0
  78. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/non_context.py +0 -0
  79. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/progress_callback.py +0 -0
  80. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/pull.py +0 -0
  81. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/pull_context.py +0 -0
  82. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/pull_utils.py +0 -0
  83. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/push.py +0 -0
  84. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/util/__init__.py +0 -0
  85. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/util/common.py +0 -0
  86. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_data/util/kerberos.py +0 -0
  87. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/cli.py +0 -0
  88. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/connectors.py +0 -0
  89. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/jobs.py +0 -0
  90. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/migration.py +0 -0
  91. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/execution/plan.py +0 -0
  92. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/progress.py +0 -0
  93. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/routes.py +0 -0
  94. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/server.py +0 -0
  95. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/storage.py +0 -0
  96. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/_local/synthetic_datasets.py +0 -0
  97. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/artifacts.py +0 -0
  98. {mostlyai-5.9.2 → mostlyai-5.10.1}/mostlyai/sdk/client/datasets.py +0 -0
  99. {mostlyai-5.9.2 → mostlyai-5.10.1}/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.1
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.1" # Do not set this manually. Use poetry version [params].
@@ -0,0 +1,193 @@
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(
44
+ constraint: ConstraintType, table=None, workspace_dir: Path | None = None
45
+ ) -> ConstraintHandler:
46
+ """factory function to create appropriate handler for a constraint."""
47
+ if isinstance(constraint, FixedCombinations):
48
+ return FixedCombinationsHandler(constraint)
49
+ elif isinstance(constraint, Inequality):
50
+ return InequalityHandler(constraint, table=table, workspace_dir=workspace_dir)
51
+ else:
52
+ raise ValueError(f"unknown constraint type: {type(constraint)}")
53
+
54
+
55
+ class ConstraintTranslator:
56
+ """translates data between user schema and internal schema for constraints."""
57
+
58
+ def __init__(self, constraints: list[ConstraintType], table=None, workspace_dir: Path | None = None):
59
+ self.constraints = constraints
60
+ self.table = table
61
+ self.handlers = [_create_constraint_handler(c, table=table, workspace_dir=workspace_dir) for c in constraints]
62
+
63
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
64
+ """transform dataframe from user schema to internal schema."""
65
+ for handler in self.handlers:
66
+ df = handler.to_internal(df)
67
+ return df
68
+
69
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
70
+ """transform dataframe from internal schema back to user schema."""
71
+ for handler in self.handlers:
72
+ df = handler.to_original(df)
73
+ return df
74
+
75
+ def get_all_column_names(self, original_column_names: list[str]) -> list[str]:
76
+ """get list of all column names (original and internal constraint columns)."""
77
+ all_column_names = list(original_column_names)
78
+ for handler in self.handlers:
79
+ all_column_names.extend(handler.get_internal_column_names())
80
+ return all_column_names
81
+
82
+ def get_encoding_types(self) -> dict[str, str]:
83
+ """get combined encoding types for all internal columns."""
84
+ encoding_types = {}
85
+ for handler in self.handlers:
86
+ encoding_types.update(handler.get_encoding_types())
87
+ return encoding_types
88
+
89
+ @staticmethod
90
+ def from_generator_config(
91
+ generator: Generator,
92
+ table_name: str,
93
+ workspace_dir: Path | None = None,
94
+ ) -> ConstraintTranslator | None:
95
+ """create constraint translator from generator configuration for a specific table."""
96
+ if not generator.constraints:
97
+ return None
98
+
99
+ table = next((t for t in generator.tables if t.name == table_name), None)
100
+ if not table:
101
+ return None
102
+
103
+ # convert constraints to typed objects and filter by table_name
104
+ typed_constraints = []
105
+ for constraint in generator.constraints:
106
+ typed_constraint = convert_constraint_config_to_typed(constraint)
107
+ if typed_constraint.table_name == table_name:
108
+ typed_constraints.append(typed_constraint)
109
+
110
+ if not typed_constraints:
111
+ return None
112
+
113
+ # pass table to translator so handlers can check column types
114
+ constraint_translator = ConstraintTranslator(typed_constraints, table=table, workspace_dir=workspace_dir)
115
+ return constraint_translator
116
+
117
+
118
+ def preprocess_constraints_for_training(
119
+ *,
120
+ generator: Generator,
121
+ workspace_dir: Path,
122
+ target_table_name: str,
123
+ ) -> list[str] | None:
124
+ """preprocess constraint transformations for training data:
125
+ - transform constraints from user schema to internal schema (if any)
126
+ - update tgt-meta (encoding-types) and tgt-data with internal columns (if any)
127
+ - return list of all column names (original and internal constraint columns) for use in training
128
+ """
129
+ target_table = next((t for t in generator.tables if t.name == target_table_name), None)
130
+ if not target_table:
131
+ _LOG.debug(f"table {target_table_name} not found in generator")
132
+ return None
133
+
134
+ if not generator.constraints:
135
+ return None
136
+
137
+ # convert constraints to typed objects and filter by table_name
138
+ typed_constraints = []
139
+ for constraint in generator.constraints:
140
+ typed_constraint = convert_constraint_config_to_typed(constraint)
141
+ if typed_constraint.table_name == target_table_name:
142
+ typed_constraints.append(typed_constraint)
143
+
144
+ if not typed_constraints:
145
+ return None
146
+
147
+ _LOG.info(f"preprocessing constraints for table {target_table_name}")
148
+ # pass table to translator so handlers can check column types
149
+ constraint_translator = ConstraintTranslator(typed_constraints, table=target_table)
150
+
151
+ tgt_data_dir = workspace_dir / "OriginalData" / "tgt-data"
152
+ if not tgt_data_dir.exists():
153
+ _LOG.warning(f"data directory not found: {tgt_data_dir}")
154
+ return None
155
+
156
+ parquet_files = sorted(list(tgt_data_dir.glob("part.*.parquet")))
157
+ for parquet_file in parquet_files:
158
+ df = pd.read_parquet(parquet_file)
159
+ df_transformed = constraint_translator.to_internal(df)
160
+ df_transformed.to_parquet(parquet_file, index=True)
161
+
162
+ original_columns = [c.name for c in target_table.columns] if target_table.columns else []
163
+ _update_meta_with_internal_columns(workspace_dir, target_table_name, constraint_translator, parquet_files)
164
+ all_column_names = constraint_translator.get_all_column_names(original_columns)
165
+ return all_column_names
166
+
167
+
168
+ def _update_meta_with_internal_columns(
169
+ workspace_dir: Path,
170
+ table_name: str,
171
+ constraint_translator: ConstraintTranslator,
172
+ parquet_files: list[Path],
173
+ ) -> None:
174
+ """update tgt-meta to reflect internal column structure after transformation."""
175
+ if not parquet_files:
176
+ return
177
+
178
+ meta_dir = workspace_dir / "OriginalData" / "tgt-meta"
179
+ meta_dir.mkdir(parents=True, exist_ok=True)
180
+ encoding_types_file = meta_dir / "encoding-types.json"
181
+
182
+ if encoding_types_file.exists():
183
+ with open(encoding_types_file) as f:
184
+ encoding_types = json.load(f)
185
+
186
+ encoding_types.update(constraint_translator.get_encoding_types())
187
+
188
+ with open(encoding_types_file, "w") as f:
189
+ json.dump(encoding_types, f, indent=2)
190
+
191
+ _LOG.debug(f"updated encoding-types.json with internal columns for {table_name}")
192
+ else:
193
+ _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,202 @@
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
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import pandas as pd
25
+
26
+ from mostlyai.sdk._data.constraints.types.base import ConstraintHandler
27
+ from mostlyai.sdk.client._constraint_types import Inequality
28
+ from mostlyai.sdk.domain import ModelEncodingType
29
+
30
+ _LOG = logging.getLogger(__name__)
31
+
32
+
33
+ def _generate_internal_column_name(prefix: str, columns: list[str]) -> str:
34
+ """generate a deterministic internal column name."""
35
+ key = "|".join(columns)
36
+ hash_suffix = hashlib.md5(key.encode()).hexdigest()[:8]
37
+ columns_str = "_".join(col.upper() for col in columns)
38
+ return f"__CONSTRAINT_{prefix}_{columns_str}_{hash_suffix}__"
39
+
40
+
41
+ class InequalityHandler(ConstraintHandler):
42
+ """handler for Inequality constraints (low <= high)."""
43
+
44
+ _DATETIME_EPOCH = pd.Timestamp("1970-01-01") # reference epoch for delta representation
45
+
46
+ def __init__(self, constraint: Inequality, table=None, workspace_dir: Path | None = None):
47
+ self.constraint = constraint
48
+ self.table_name = constraint.table_name
49
+ self.low_column = constraint.low_column
50
+ self.high_column = constraint.high_column
51
+ self._delta_column = _generate_internal_column_name("INEQ_DELTA", [self.low_column, self.high_column])
52
+ self.workspace_dir = workspace_dir
53
+
54
+ # determine if this is a datetime constraint based on table encoding types
55
+ self._is_datetime = False
56
+ if table and table.columns:
57
+ datetime_encodings = {
58
+ ModelEncodingType.tabular_datetime,
59
+ # ModelEncodingType.tabular_datetime_relative, # not supported yet
60
+ }
61
+ # check if either column is datetime-encoded
62
+ self._is_datetime = all(
63
+ col.model_encoding_type in datetime_encodings
64
+ for col in table.columns
65
+ if col.name in {self.low_column, self.high_column}
66
+ )
67
+
68
+ def __repr__(self) -> str:
69
+ return f"{self.low_column} <= {self.high_column}"
70
+
71
+ def get_internal_column_names(self) -> list[str]:
72
+ return [self._delta_column]
73
+
74
+ def to_internal(self, df: pd.DataFrame) -> pd.DataFrame:
75
+ self._validate_columns(df, [self.low_column, self.high_column])
76
+ low = df[self.low_column]
77
+ high = df[self.high_column]
78
+
79
+ # handle NAs: if either low or high is NA, set delta to NA
80
+ na_mask = low.isna() | high.isna()
81
+
82
+ zero = pd.Timedelta(0) if self._is_datetime else 0
83
+ delta = high - low
84
+
85
+ # set delta to NA where either low or high is NA
86
+ delta[na_mask] = pd.NA
87
+
88
+ # only check violations where we have valid values
89
+ violations = (delta < zero) & ~na_mask
90
+ if violations.any():
91
+ _LOG.warning(f"detected {violations.sum() / len(delta) * 100:.2f}% inequality violations for {self}")
92
+
93
+ # convert timedelta to datetime using epoch (for datetime constraints)
94
+ if self._is_datetime:
95
+ # represent delta as datetime: epoch + timedelta
96
+ # preserve NAs during conversion
97
+ delta = delta.where(na_mask, self._DATETIME_EPOCH + delta)
98
+ # for numeric, keep as-is (numeric delta)
99
+
100
+ df[self._delta_column] = delta
101
+ return df
102
+
103
+ def to_original(self, df: pd.DataFrame) -> pd.DataFrame:
104
+ """transform from internal schema back to original schema."""
105
+ if self._delta_column not in df.columns:
106
+ return df
107
+
108
+ # prepare data and types
109
+ low = df[self.low_column]
110
+ delta = df[self._delta_column]
111
+ high_dtype = df[self.high_column].dtype
112
+
113
+ # convert datetime back to timedelta if needed
114
+ if self._is_datetime:
115
+ # ensure delta is datetime dtype before subtraction
116
+ delta = pd.to_datetime(delta)
117
+ # preserve NAs during conversion
118
+ delta = delta - self._DATETIME_EPOCH
119
+ delta = delta.astype("timedelta64[ns]") # explicit dtype conversion
120
+
121
+ # RECONSTRUCTION
122
+ low_na = low.isna()
123
+ delta_na = delta.isna()
124
+
125
+ # if low != NA and delta != NA, then high = low + delta
126
+ both_valid = ~low_na & ~delta_na
127
+ df.loc[both_valid, self.high_column] = low[both_valid] + delta[both_valid]
128
+
129
+ # if low != NA and delta == NA, then high = NA
130
+ low_valid_delta_na = ~low_na & delta_na
131
+ df.loc[low_valid_delta_na, self.high_column] = pd.NA
132
+ # else, if low == NA, then high is kept as is
133
+
134
+ # if any violations made it through, apply a primitive correction
135
+ high = df[self.high_column]
136
+ both_valid_for_check = ~low_na & ~high.isna()
137
+ violations = both_valid_for_check & (high < low)
138
+ df.loc[violations, self.high_column] = low[violations]
139
+
140
+ # clip to training data bounds
141
+ if self.workspace_dir is not None:
142
+ self._clip_to_training_bounds(df)
143
+
144
+ # convert back to original dtype
145
+ if pd.api.types.is_integer_dtype(high_dtype):
146
+ df[self.high_column] = df[self.high_column].astype(high_dtype)
147
+
148
+ return df.drop(columns=[self._delta_column])
149
+
150
+ def _extract_min_max_from_stats(self, col_stats: dict) -> tuple[Any, Any]:
151
+ """extract min/max from column stats, handling all encoding types (same pattern as parse_min_max)."""
152
+ # try bins/min5/max5 arrays first (for binned/digit/datetime encoding)
153
+ values = col_stats.get("bins", []) + col_stats.get("min5", []) + col_stats.get("max5", [])
154
+ if values:
155
+ return min(values), max(values)
156
+ # fall back to direct min/max (for other encoding types or when arrays are empty)
157
+ return col_stats.get("min"), col_stats.get("max")
158
+
159
+ def _clip_to_training_bounds(self, df: pd.DataFrame) -> None:
160
+ """clip high column values to min/max from training data stats."""
161
+ from mostlyai.engine._workspace import Workspace
162
+
163
+ workspace = Workspace(self.workspace_dir)
164
+ tgt_stats = workspace.tgt_stats.read()
165
+ if not tgt_stats or self.high_column not in tgt_stats.get("columns", {}):
166
+ return
167
+
168
+ col_stats = tgt_stats["columns"][self.high_column]
169
+ min_val, max_val = self._extract_min_max_from_stats(col_stats)
170
+ if min_val is None and max_val is None:
171
+ return
172
+
173
+ high = df[self.high_column]
174
+ low = df[self.low_column]
175
+ if self._is_datetime:
176
+ if min_val is not None:
177
+ min_val = pd.to_datetime(min_val)
178
+ df.loc[high.notna() & (high < min_val), self.high_column] = min_val
179
+ if max_val is not None:
180
+ max_val = pd.to_datetime(max_val)
181
+ df.loc[high.notna() & (high > max_val), self.high_column] = max_val
182
+ else:
183
+ if min_val is not None:
184
+ min_val = float(min_val)
185
+ df.loc[high.notna() & (high < min_val), self.high_column] = min_val
186
+ if max_val is not None:
187
+ max_val = float(max_val)
188
+ df.loc[high.notna() & (high > max_val), self.high_column] = max_val
189
+
190
+ # ensure constraint is still satisfied after clipping
191
+ # if clipping made high < low, set high = low
192
+ high = df[self.high_column]
193
+ both_valid = low.notna() & high.notna()
194
+ violations = both_valid & (high < low)
195
+ df.loc[violations, self.high_column] = low[violations]
196
+
197
+ def get_encoding_types(self) -> dict[str, str]:
198
+ # use TABULAR_DATETIME for datetime constraints to preserve precision
199
+ # use TABULAR_NUMERIC_AUTO for numeric constraints
200
+ if self._is_datetime:
201
+ return {self._delta_column: "TABULAR_DATETIME"}
202
+ return {self._delta_column: "TABULAR_NUMERIC_AUTO"}