mostlyai 0.4.3__tar.gz → 0.4.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: mostlyai
3
- Version: 0.4.3
3
+ Version: 0.4.5
4
4
  Summary: The official Python client for the MOSTLY AI platform.
5
5
  Home-page: https://app.mostly.ai/
6
6
  License: Proprietary
@@ -18,6 +18,8 @@ Requires-Dist: pandas (>=1.5.3,<3.0.0)
18
18
  Requires-Dist: pyarrow (>=14.0.0)
19
19
  Requires-Dist: pydantic (>=2.4.2,<3.0.0)
20
20
  Requires-Dist: rich (>=13.7.0)
21
+ Project-URL: Documentation, https://mostly-ai.github.io/mostly-python/
22
+ Project-URL: Source, https://github.com/mostly-ai/mostly-python
21
23
  Description-Content-Type: text/markdown
22
24
 
23
25
  # MOSTLY AI - GenAI for Tabular Data
@@ -97,6 +99,10 @@ g.training.wait()
97
99
  # import / export
98
100
  g.export_to_file(file_path)
99
101
  mostly.generators.import_from_file(file_path)
102
+
103
+ # clone
104
+ cloned_g = g.clone(training_status="NEW") # clone the generator for new training
105
+ cloned_g = g.clone(training_status="CONTINUE") # clone the generator and reuse its weights for continued training
100
106
  ```
101
107
 
102
108
  ### Synthetic Datasets
@@ -75,6 +75,10 @@ g.training.wait()
75
75
  # import / export
76
76
  g.export_to_file(file_path)
77
77
  mostly.generators.import_from_file(file_path)
78
+
79
+ # clone
80
+ cloned_g = g.clone(training_status="NEW") # clone the generator for new training
81
+ cloned_g = g.clone(training_status="CONTINUE") # clone the generator and reuse its weights for continued training
78
82
  ```
79
83
 
80
84
  ### Synthetic Datasets
@@ -1,4 +1,4 @@
1
1
  from mostlyai.api import MostlyAI
2
2
 
3
3
  __all__ = ["MostlyAI"]
4
- __version__ = "0.4.3" # Do not set this manually. Use poetry version [params].
4
+ __version__ = "0.4.5" # Do not set this manually. Use poetry version [params].
@@ -20,6 +20,11 @@ from pydantic import BaseModel, ConfigDict, Field
20
20
  from rich.console import Console
21
21
 
22
22
  from mostlyai.exceptions import APIError, APIStatusError
23
+ from mostlyai.naming_conventions import (
24
+ snake_to_camel,
25
+ map_snake_to_camel_case,
26
+ map_camel_to_snake_case,
27
+ )
23
28
 
24
29
  GET = "GET"
25
30
  POST = "POST"
@@ -73,6 +78,8 @@ class _MostlyBaseClient:
73
78
  response_type: type = dict,
74
79
  raw_response: bool = False,
75
80
  is_api_call: bool = True,
81
+ do_json_camel_case: bool = True,
82
+ do_response_dict_snake_case: bool = True,
76
83
  do_include_client: bool = True,
77
84
  extra_key_values: Optional[dict] = None,
78
85
  **kwargs,
@@ -88,6 +95,8 @@ class _MostlyBaseClient:
88
95
  :param response_type: a specific type to return (e.g. Pydantic class)
89
96
  :param raw_response: whether to just return a raw response (e.g. content)
90
97
  :param is_api_call: True by default; if False, API_SECTION and SECTION won't be prefixed
98
+ :param do_json_camel_case: ensure a provided json follows camelCase conventions
99
+ :param do_response_dict_snake_case: ensure the returned dict follows snake_case conventions
91
100
  :param do_include_client: True by default; if True, client property will be included in the returned instance
92
101
  :param extra_key_values: Any extra information storage to include in the returned object
93
102
  :param kwargs: httpx's request function's kwargs
@@ -105,6 +114,9 @@ class _MostlyBaseClient:
105
114
  f"The overall {request_size=} exceeds {MAX_REQUEST_SIZE}.", UserWarning
106
115
  )
107
116
 
117
+ if "json" in kwargs and do_json_camel_case:
118
+ kwargs["json"] = map_snake_to_camel_case(kwargs["json"])
119
+
108
120
  try:
109
121
  with httpx.Client(timeout=self.timeout, verify=self.ssl_verify) as client:
110
122
  response = client.request(method=verb, url=full_url, **kwargs)
@@ -135,6 +147,8 @@ class _MostlyBaseClient:
135
147
  response_json["client"] = self
136
148
  if isinstance(extra_key_values, dict):
137
149
  response_json["extra_key_values"] = extra_key_values
150
+ elif response_type == dict and do_response_dict_snake_case:
151
+ response_json = map_camel_to_snake_case(response_json)
138
152
  return (
139
153
  response_type(**response_json)
140
154
  if isinstance(response_json, dict)
@@ -157,7 +171,7 @@ class Paginator(Generic[T]):
157
171
  self.object_class = object_class
158
172
  self.offset = kwargs.pop("offset", 0)
159
173
  self.limit = kwargs.pop("limit", 50)
160
- self.params = {_snake_to_camel(k): v for k, v in kwargs.items()}
174
+ self.params = {snake_to_camel(k): v for k, v in kwargs.items()}
161
175
  self.current_items = []
162
176
  self.current_index = 0
163
177
  self.is_last_page = False
@@ -233,11 +247,6 @@ class CustomBaseModel(BaseModel):
233
247
  setattr(self, key, value)
234
248
 
235
249
 
236
- def _snake_to_camel(snake_str: str) -> str:
237
- components = snake_str.split("_")
238
- return components[0] + "".join(x.title() for x in components[1:])
239
-
240
-
241
250
  def _get_total_size(obj, seen=None):
242
251
  """Recursively finds size of objects in bytes."""
243
252
  size = sys.getsizeof(obj)
@@ -143,6 +143,15 @@ class _MostlyGeneratorsClient(_MostlyBaseClient, _MostlySharesMixin):
143
143
  response = self.request(verb=DELETE, path=[generator_id])
144
144
  return response
145
145
 
146
+ def _clone(self, generator_id: str, training_status: str) -> Generator:
147
+ response = self.request(
148
+ verb=POST,
149
+ path=[generator_id, "clone"],
150
+ json={"trainingStatus": training_status},
151
+ response_type=Generator,
152
+ )
153
+ return response
154
+
146
155
  def _config(self, generator_id: str) -> Generator:
147
156
  response = self.request(verb=GET, path=[generator_id, "config"])
148
157
  return response
@@ -1,5 +1,5 @@
1
1
  # generated by datamodel-codegen:
2
- # timestamp: 2024-10-01T16:53:09+00:00
2
+ # timestamp: 2024-11-14T17:29:08+00:00
3
3
 
4
4
  from __future__ import annotations
5
5
 
@@ -469,6 +469,45 @@ class RareCategoryReplacementMethod(str, Enum):
469
469
  sample = "SAMPLE"
470
470
 
471
471
 
472
+ class ModelConfigurationDifferentialPrivacy(CustomBaseModel):
473
+ """
474
+ The optional differential privacy configuration for training the model.
475
+ If not provided, then no differential privacy will be applied.
476
+
477
+ """
478
+
479
+ max_epsilon: Annotated[
480
+ Optional[float],
481
+ Field(
482
+ None,
483
+ alias="maxEpsilon",
484
+ description="Specifies the maximum allowable epsilon value. If the training process exceeds this threshold, it will be terminated early. Only model checkpoints with epsilon values below this limit will be retained. \nIf not provided, the training will proceed without early termination based on epsilon constraints.\n",
485
+ ge=0.0,
486
+ le=10000.0,
487
+ ),
488
+ ] = None
489
+ noise_multiplier: Annotated[
490
+ Optional[float],
491
+ Field(
492
+ 1.5,
493
+ alias="noiseMultiplier",
494
+ description="The ratio of the standard deviation of the Gaussian noise to the L2-sensitivity of the function to which the noise is added (How much noise to add).\n",
495
+ ge=0.0,
496
+ le=10000.0,
497
+ ),
498
+ ] = 1.5
499
+ max_grad_norm: Annotated[
500
+ Optional[float],
501
+ Field(
502
+ 1.0,
503
+ alias="maxGradNorm",
504
+ description="The maximum norm of the per-sample gradients for training the model with differential privacy.\n",
505
+ ge=0.0,
506
+ le=10000.0,
507
+ ),
508
+ ] = 1.0
509
+
510
+
472
511
  class Accuracy(CustomBaseModel):
473
512
  overall: Annotated[
474
513
  Optional[float],
@@ -617,6 +656,7 @@ class ProgressStatus(str, Enum):
617
656
  """
618
657
  The status of a job or a step.
619
658
  NEW: The job/step is being configured, and has not started yet
659
+ CONTINUE: The job/step is being configured, but has existing artefacts
620
660
  ON_HOLD: The job/step has been started, but is kept on hold
621
661
  QUEUED: The job/step has been started, and is awaiting for resources to execute
622
662
  IN_PROGRESS: The job/step is currently running
@@ -627,6 +667,7 @@ class ProgressStatus(str, Enum):
627
667
  """
628
668
 
629
669
  new = "NEW"
670
+ continue_ = "CONTINUE"
630
671
  on_hold = "ON_HOLD"
631
672
  queued = "QUEUED"
632
673
  in_progress = "IN_PROGRESS"
@@ -1100,7 +1141,13 @@ class User(CustomBaseModel):
1100
1141
  id: Annotated[
1101
1142
  Optional[str], Field(None, description="The unique identifier of a user")
1102
1143
  ] = None
1103
- name: Annotated[Optional[str], Field(None, description="The name of a user")] = None
1144
+ first_name: Annotated[
1145
+ Optional[str],
1146
+ Field(None, alias="firstName", description="First name of a user"),
1147
+ ] = None
1148
+ last_name: Annotated[
1149
+ Optional[str], Field(None, alias="lastName", description="Last name of a user")
1150
+ ] = None
1104
1151
  email: Annotated[Optional[str], Field(None, description="The email of a user")] = (
1105
1152
  None
1106
1153
  )
@@ -1110,7 +1157,13 @@ class CurrentUser(CustomBaseModel):
1110
1157
  id: Annotated[
1111
1158
  Optional[str], Field(None, description="The unique identifier of a user")
1112
1159
  ] = None
1113
- name: Annotated[Optional[str], Field(None, description="The name of a user")] = None
1160
+ first_name: Annotated[
1161
+ Optional[str],
1162
+ Field(None, alias="firstName", description="First name of a user"),
1163
+ ] = None
1164
+ last_name: Annotated[
1165
+ Optional[str], Field(None, alias="lastName", description="Last name of a user")
1166
+ ] = None
1114
1167
  email: Annotated[Optional[str], Field(None, description="The email of a user")] = (
1115
1168
  None
1116
1169
  )
@@ -1163,7 +1216,6 @@ class ModelConfiguration(CustomBaseModel):
1163
1216
  "MOSTLY_AI/Large",
1164
1217
  "MOSTLY_AI/LSTMFromScratch-3m",
1165
1218
  "microsoft/phi-1_5",
1166
- "Locutusque/TinyMistral-248M",
1167
1219
  ]
1168
1220
  ],
1169
1221
  ),
@@ -1242,6 +1294,10 @@ class ModelConfiguration(CustomBaseModel):
1242
1294
  description="Specifies, if the rare categories for categoricals will be replaced by a constant\n_RARE_ or by a sample from non-rare categories.\nOnly applicable if valueProtection is set to True.\n",
1243
1295
  ),
1244
1296
  ] = "CONSTANT"
1297
+ differential_privacy: Annotated[
1298
+ Optional[ModelConfigurationDifferentialPrivacy],
1299
+ Field(None, alias="differentialPrivacy"),
1300
+ ] = None
1245
1301
  compute: Optional[str] = None
1246
1302
 
1247
1303
 
@@ -1794,6 +1850,14 @@ class Generator(CustomBaseModel):
1794
1850
  file_path.write_bytes(bytes)
1795
1851
  return file_path
1796
1852
 
1853
+ def clone(self, training_status: Literal["NEW", "CONTINUE"] = "NEW") -> "Generator":
1854
+ """
1855
+ Clone generator
1856
+
1857
+ :param training_status: The training status of the cloned generator
1858
+ """
1859
+ return self.client._clone(generator_id=self.id, training_status=training_status)
1860
+
1797
1861
  class Training:
1798
1862
  def __init__(self, _generator: "Generator"):
1799
1863
  self.generator = _generator
@@ -0,0 +1,39 @@
1
+ import re
2
+ from typing import Callable
3
+
4
+
5
+ def snake_to_camel(snake_str: str) -> str:
6
+ components = snake_str.split("_")
7
+ return components[0] + "".join(x.title() for x in components[1:])
8
+
9
+
10
+ def camel_to_snake(camel_str: str) -> str:
11
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", camel_str).lower()
12
+
13
+
14
+ def convert_case(input_data: dict, conv_func: Callable[[str], str]) -> dict:
15
+ if not isinstance(input_data, dict):
16
+ return input_data
17
+
18
+ new_dict = {}
19
+ for key, value in input_data.items():
20
+ new_key = conv_func(key)
21
+ # recursively convert nested dictionaries or lists
22
+ if isinstance(value, dict):
23
+ new_dict[new_key] = convert_case(value, conv_func)
24
+ elif isinstance(value, list):
25
+ new_dict[new_key] = [
26
+ convert_case(item, conv_func) if isinstance(item, dict) else item
27
+ for item in value
28
+ ]
29
+ else:
30
+ new_dict[new_key] = value
31
+ return new_dict
32
+
33
+
34
+ def map_snake_to_camel_case(input_dict: dict) -> dict:
35
+ return convert_case(input_dict, snake_to_camel)
36
+
37
+
38
+ def map_camel_to_snake_case(input_dict: dict) -> dict:
39
+ return convert_case(input_dict, camel_to_snake)
@@ -31,12 +31,12 @@ class _MostlySharesClient(_MostlyBaseClient):
31
31
  user_email: str,
32
32
  permission_level: PermissionLevel,
33
33
  ):
34
- config = {"userEmail": user_email, "permissionLevel": permission_level}
34
+ config = {"user_email": user_email, "permission_level": permission_level}
35
35
  resource_type = self.RESOURCE_TYPE.get(type(resource))
36
36
  self.request(verb=POST, path=[resource_type, resource.id], json=config)
37
37
 
38
38
  def _unshare(self, resource: ShareableResource, user_email: str):
39
- config = {"userEmail": user_email}
39
+ config = {"user_email": user_email}
40
40
  resource_type = self.RESOURCE_TYPE.get(type(resource))
41
41
  self.request(verb=DELETE, path=[resource_type, resource.id], json=config)
42
42
 
@@ -23,6 +23,7 @@ from mostlyai.model import (
23
23
  StepCode,
24
24
  SyntheticDataset,
25
25
  )
26
+ from mostlyai.naming_conventions import map_camel_to_snake_case
26
27
 
27
28
  warnings.simplefilter("always", DeprecationWarning)
28
29
 
@@ -173,13 +174,15 @@ def _harmonize_sd_config(
173
174
  size = size if size is not None else {}
174
175
  seed = seed if seed is not None else {}
175
176
 
177
+ config = map_camel_to_snake_case(config)
178
+
176
179
  if isinstance(generator, Generator):
177
180
  generator_id = str(generator.id)
178
181
  elif generator is not None:
179
182
  generator_id = str(generator)
180
- elif "generatorId" not in config:
183
+ elif "generator_id" not in config:
181
184
  raise ValueError(
182
- "Either a generator or a configuration with a generatorId must be provided."
185
+ "Either a generator or a configuration with a generator_id must be provided."
183
186
  )
184
187
 
185
188
  if (
@@ -193,8 +196,8 @@ def _harmonize_sd_config(
193
196
  else:
194
197
  subject_tables = []
195
198
 
196
- # insert generatorId into config
197
- config["generatorId"] = generator_id
199
+ # insert generator_id into config
200
+ config["generator_id"] = generator_id
198
201
 
199
202
  # normalize size
200
203
  if not isinstance(size, dict):
@@ -213,18 +216,18 @@ def _harmonize_sd_config(
213
216
  config["tables"] = []
214
217
  for table in generator.tables:
215
218
  configuration = {
216
- "sampleSize": None,
217
- "sampleSeedData": None,
218
- "sampleSeedDict": None,
219
+ "sample_size": None,
220
+ "sample_seed_data": None,
221
+ "sample_seed_dict": None,
219
222
  }
220
223
  if table.name in subject_tables:
221
- configuration["sampleSize"] = size.get(table.name)
222
- configuration["sampleSeedData"] = (
224
+ configuration["sample_size"] = size.get(table.name)
225
+ configuration["sample_seed_data"] = (
223
226
  seed.get(table.name)
224
227
  if not isinstance(seed.get(table.name), list)
225
228
  else None
226
229
  )
227
- configuration["sampleSeedDict"] = (
230
+ configuration["sample_seed_dict"] = (
228
231
  seed.get(table.name)
229
232
  if isinstance(seed.get(table.name), list)
230
233
  else None
@@ -238,25 +241,27 @@ def _harmonize_sd_config(
238
241
  tables = config["tables"] if "tables" in config else []
239
242
  for table in tables:
240
243
  if (
241
- "sampleSeedData" in table["configuration"]
242
- and table["configuration"]["sampleSeedData"] is not None
244
+ "sample_seed_data" in table["configuration"]
245
+ and table["configuration"]["sample_seed_data"] is not None
243
246
  ):
244
- if isinstance(table["configuration"]["sampleSeedData"], pd.DataFrame):
245
- table["configuration"]["sampleSeedData"] = _convert_to_base64(
246
- table["configuration"]["sampleSeedData"]
247
+ if isinstance(table["configuration"]["sample_seed_data"], pd.DataFrame):
248
+ table["configuration"]["sample_seed_data"] = _convert_to_base64(
249
+ table["configuration"]["sample_seed_data"]
250
+ )
251
+ elif isinstance(table["configuration"]["sample_seed_data"], (Path, str)):
252
+ _, df = _read_table_from_path(
253
+ table["configuration"]["sample_seed_data"]
247
254
  )
248
- elif isinstance(table["configuration"]["sampleSeedData"], (Path, str)):
249
- _, df = _read_table_from_path(table["configuration"]["sampleSeedData"])
250
- table["configuration"]["sampleSeedData"] = _convert_to_base64(df)
255
+ table["configuration"]["sample_seed_data"] = _convert_to_base64(df)
251
256
  del df
252
257
  else:
253
- raise ValueError("sampleSeedData must be a DataFrame or a file path")
258
+ raise ValueError("sample_seed_data must be a DataFrame or a file path")
254
259
  if (
255
- "sampleSeedDict" in table["configuration"]
256
- and table["configuration"]["sampleSeedDict"] is not None
260
+ "sample_seed_dict" in table["configuration"]
261
+ and table["configuration"]["sample_seed_dict"] is not None
257
262
  ):
258
- table["configuration"]["sampleSeedDict"] = _convert_to_base64(
259
- table["configuration"]["sampleSeedDict"], format="jsonl"
263
+ table["configuration"]["sample_seed_dict"] = _convert_to_base64(
264
+ table["configuration"]["sample_seed_dict"], format="jsonl"
260
265
  )
261
266
 
262
267
  return config
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "mostlyai"
3
- version = "0.4.3"
3
+ version = "0.4.5"
4
4
  description = "The official Python client for the MOSTLY AI platform."
5
5
  homepage = "https://app.mostly.ai/"
6
6
  authors = ["MOSTLY AI <office@mostly.ai>"]
@@ -11,6 +11,11 @@ packages = [
11
11
  ]
12
12
  exclude = ["tools/", "tools/**/*"]
13
13
 
14
+ [tool.poetry.urls]
15
+ "Homepage" = "https://app.mostly.ai/"
16
+ "Documentation" = "https://mostly-ai.github.io/mostly-python/"
17
+ "Source" = "https://github.com/mostly-ai/mostly-python"
18
+
14
19
  [tool.poetry.dependencies]
15
20
  python = "^3.9"
16
21
  pydantic = "^2.4.2"
File without changes
File without changes