mostlyai 4.3.4__tar.gz → 4.4.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.
- {mostlyai-4.3.4 → mostlyai-4.4.1}/PKG-INFO +1 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/__init__.py +1 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/conversions.py +2 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/base.py +9 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/table/csv.py +2 -2
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/table/feather.py +2 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/table/json.py +2 -2
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/table/parquet.py +2 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/utils.py +29 -10
- mostlyai-4.4.1/mostlyai/sdk/_local/connectors.py +94 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/jobs.py +1 -4
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_finalize_generation.py +7 -45
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/routes.py +33 -3
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/_naming_conventions.py +4 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/connectors.py +39 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/generators.py +1 -1
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/domain.py +212 -25
- {mostlyai-4.3.4 → mostlyai-4.4.1}/pyproject.toml +1 -1
- mostlyai-4.3.4/mostlyai/sdk/_local/connectors.py +0 -50
- {mostlyai-4.3.4 → mostlyai-4.4.1}/.gitignore +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/LICENSE +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/README.md +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/auto_detect.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/base.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/context.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/base.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/bigquery.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/databricks.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/hive.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/mssql.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/mysql.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/oracle.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/postgresql.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/snowflake.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/sqlite.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/db/types_coercion.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/dtype.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/exceptions.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/aws.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/azure.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/bucket_based.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/gcs.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/container/minio.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/file/table/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/language_model.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/metadata_objects.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/non_context.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/progress_callback.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/pull.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/pull_context.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/pull_utils.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/push.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/util/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/util/common.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_data/util/kerberos.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/cli.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/plan.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_analyze_training_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_create_data_report.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_create_model_report.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_deliver_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_encode_training_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_finalize_training.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_generate_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_generate_model_report_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_pull_training_data.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/execution/step_train_model.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/generators.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/progress.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/server.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/storage.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/_local/synthetic_datasets.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/__init__.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/_base_utils.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/_utils.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/api.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/base.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/exceptions.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/client/synthetic_datasets.py +0 -0
- {mostlyai-4.3.4 → mostlyai-4.4.1}/mostlyai/sdk/py.typed +0 -0
|
@@ -33,6 +33,7 @@ CONNECTOR_TYPE_CONTAINER_CLASS_MAP = {
|
|
|
33
33
|
ConnectorType.bigquery: "mostlyai.sdk._data.db.bigquery.BigQueryContainer",
|
|
34
34
|
ConnectorType.databricks: "mostlyai.sdk._data.db.databricks.DatabricksContainer",
|
|
35
35
|
ConnectorType.hive: "mostlyai.sdk._data.db.hive.HiveContainer",
|
|
36
|
+
ConnectorType.sqlite: "mostlyai.sdk._data.db.sqlite.SqliteContainer",
|
|
36
37
|
ConnectorType.azure_storage: "mostlyai.sdk._data.file.container.azure.AzureBlobFileContainer",
|
|
37
38
|
ConnectorType.google_cloud_storage: "mostlyai.sdk._data.file.container.gcs.GcsContainer",
|
|
38
39
|
ConnectorType.s3_storage: "mostlyai.sdk._data.file.container.aws.AwsS3FileContainer",
|
|
@@ -49,6 +50,7 @@ CONNECTOR_TYPE_CONTAINER_PARAMS_CLASS_MAP = {
|
|
|
49
50
|
ConnectorType.bigquery: "mostlyai.sdk._data.metadata_objects.BigQueryContainerParameters",
|
|
50
51
|
ConnectorType.databricks: "mostlyai.sdk._data.metadata_objects.DatabricksContainerParameters",
|
|
51
52
|
ConnectorType.hive: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
|
|
53
|
+
ConnectorType.sqlite: "mostlyai.sdk._data.metadata_objects.SqlAlchemyContainerParameters",
|
|
52
54
|
ConnectorType.azure_storage: "mostlyai.sdk._data.metadata_objects.AzureBlobFileContainerParameters",
|
|
53
55
|
ConnectorType.google_cloud_storage: "mostlyai.sdk._data.metadata_objects.GcsContainerParameters",
|
|
54
56
|
ConnectorType.s3_storage: "mostlyai.sdk._data.metadata_objects.AwsS3FileContainerParameters",
|
|
@@ -365,6 +365,15 @@ class FileDataTable(DataTable, abc.ABC):
|
|
|
365
365
|
def _get_columns(self) -> list[str]:
|
|
366
366
|
return [c.name for c in self.dataset.schema if c.name != ""]
|
|
367
367
|
|
|
368
|
+
def handle_if_exists(self, if_exists: str = "fail") -> str:
|
|
369
|
+
destination_exists = self.container.path.exists()
|
|
370
|
+
if destination_exists:
|
|
371
|
+
if if_exists == "fail":
|
|
372
|
+
raise MostlyDataException("Destination location already exists.")
|
|
373
|
+
elif if_exists == "append" and self.IS_WRITE_APPEND_ALLOWED:
|
|
374
|
+
return "a"
|
|
375
|
+
return "w"
|
|
376
|
+
|
|
368
377
|
|
|
369
378
|
class FileContainer(DataContainer):
|
|
370
379
|
SCHEMES = ["http", "https"]
|
|
@@ -107,8 +107,8 @@ class CsvDataTable(FileDataTable):
|
|
|
107
107
|
super()._lazy_fetch(item)
|
|
108
108
|
return
|
|
109
109
|
|
|
110
|
-
def write_data(self, df: pd.DataFrame, **kwargs):
|
|
111
|
-
mode =
|
|
110
|
+
def write_data(self, df: pd.DataFrame, if_exists: str = "append", **kwargs):
|
|
111
|
+
mode = self.handle_if_exists(if_exists)
|
|
112
112
|
df.to_csv(
|
|
113
113
|
self.container.path_str,
|
|
114
114
|
mode=mode,
|
|
@@ -32,7 +32,8 @@ class FeatherDataTable(FileDataTable):
|
|
|
32
32
|
def _get_dataset_format(self):
|
|
33
33
|
return ds.FeatherFileFormat()
|
|
34
34
|
|
|
35
|
-
def write_data(self, df: pd.DataFrame, **kwargs):
|
|
35
|
+
def write_data(self, df: pd.DataFrame, if_exists: str = "replace", **kwargs):
|
|
36
|
+
self.handle_if_exists(if_exists) # will gracefully handle append as replace
|
|
36
37
|
df.to_feather(
|
|
37
38
|
self.container.path_str,
|
|
38
39
|
storage_options=self.container.storage_options,
|
|
@@ -119,7 +119,7 @@ class JsonDataTable(FileDataTable):
|
|
|
119
119
|
# Note: this currently reads all data; optimize later
|
|
120
120
|
return self.read_data().dtypes.to_dict()
|
|
121
121
|
|
|
122
|
-
def write_data(self, df: pd.DataFrame, **kwargs):
|
|
122
|
+
def write_data(self, df: pd.DataFrame, if_exists: str = "append", **kwargs):
|
|
123
123
|
# Convert to ISO format so that pyarrow.json.read_json can auto-detect these
|
|
124
124
|
for c in df:
|
|
125
125
|
if is_date_dtype(df[c]):
|
|
@@ -133,6 +133,6 @@ class JsonDataTable(FileDataTable):
|
|
|
133
133
|
.dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
134
134
|
.str[:-7]
|
|
135
135
|
)
|
|
136
|
-
mode =
|
|
136
|
+
mode = self.handle_if_exists(if_exists)
|
|
137
137
|
df.to_json(self.container.path_str, orient="records", lines=True, mode=mode)
|
|
138
138
|
# raise MostlyException("write to cloud buckets not yet supported")
|
|
@@ -48,7 +48,8 @@ class ParquetDataTable(FileDataTable):
|
|
|
48
48
|
def _get_columns(self):
|
|
49
49
|
return self.get_columns(exclude_complex_types=True)
|
|
50
50
|
|
|
51
|
-
def write_data(self, df: pd.DataFrame, **kwargs):
|
|
51
|
+
def write_data(self, df: pd.DataFrame, if_exists: str = "replace", **kwargs):
|
|
52
|
+
self.handle_if_exists(if_exists) # will gracefully handle append as replace
|
|
52
53
|
df.to_parquet(
|
|
53
54
|
self.container.path_str,
|
|
54
55
|
storage_options=self.container.storage_options,
|
|
@@ -44,6 +44,18 @@ FILE_EXT_DATA_TABLE_CLASS_MAP = {
|
|
|
44
44
|
|
|
45
45
|
def read_data_table_from_path(
|
|
46
46
|
container_object: FileContainer, return_class: bool = False
|
|
47
|
+
) -> FileDataTable | type[FileDataTable]:
|
|
48
|
+
return _fetch_file_data_table(container_object, return_class, is_read=True)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def write_data_table_to_path(
|
|
52
|
+
container_object: FileContainer, return_class: bool = False
|
|
53
|
+
) -> FileDataTable | type[FileDataTable]:
|
|
54
|
+
return _fetch_file_data_table(container_object, return_class, is_read=False)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _fetch_file_data_table(
|
|
58
|
+
container_object: FileContainer, return_class: bool, is_read: bool
|
|
47
59
|
) -> FileDataTable | type[FileDataTable]:
|
|
48
60
|
# determine table_name
|
|
49
61
|
table_name = container_object.path.absolute().name
|
|
@@ -52,13 +64,16 @@ def read_data_table_from_path(
|
|
|
52
64
|
if "." in table_name:
|
|
53
65
|
table_name = ".".join(table_name.split(".")[:-1])
|
|
54
66
|
# determine file extension
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
67
|
+
if is_read:
|
|
68
|
+
_LOG.info(f"detect data files for `{container_object.path}`")
|
|
69
|
+
file_list = container_object.list_valid_files()
|
|
70
|
+
_LOG.info(container_object.path)
|
|
71
|
+
_LOG.info(file_list)
|
|
72
|
+
_LOG.info(f"detected {len(file_list)} files: {file_list}")
|
|
73
|
+
if len(file_list) == 0:
|
|
74
|
+
raise MostlyDataException("No data files found.")
|
|
75
|
+
else:
|
|
76
|
+
file_list = [container_object.path]
|
|
62
77
|
_, file_type = get_file_name_and_type(file_list[0])
|
|
63
78
|
data_table_cls = FILE_EXT_DATA_TABLE_CLASS_MAP.get(file_type)
|
|
64
79
|
if return_class:
|
|
@@ -68,17 +83,21 @@ def read_data_table_from_path(
|
|
|
68
83
|
container=container_object,
|
|
69
84
|
path=file_list,
|
|
70
85
|
name=table_name,
|
|
86
|
+
is_output=not is_read,
|
|
71
87
|
)
|
|
72
88
|
return data_table
|
|
73
89
|
|
|
74
90
|
|
|
75
|
-
def make_data_table_from_container(container: DataContainer) -> DataTable:
|
|
91
|
+
def make_data_table_from_container(container: DataContainer, is_output=False) -> DataTable:
|
|
76
92
|
if isinstance(container, SqlAlchemyContainer):
|
|
77
93
|
# handle DB containers
|
|
78
94
|
data_table_class = container.table_class()
|
|
79
95
|
elif isinstance(container, FileContainer):
|
|
80
96
|
# handle local fs and bucket containers
|
|
81
|
-
|
|
97
|
+
if is_output:
|
|
98
|
+
data_table_class = write_data_table_to_path(container, return_class=True)
|
|
99
|
+
else:
|
|
100
|
+
data_table_class = read_data_table_from_path(container, return_class=True)
|
|
82
101
|
else:
|
|
83
102
|
raise RuntimeError(f"Unknown container type: {type(container)}")
|
|
84
|
-
return data_table_class(container=container)
|
|
103
|
+
return data_table_class(container=container, is_output=is_output)
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
from pathlib import Path
|
|
16
|
+
from io import BytesIO
|
|
17
|
+
import pandas as pd
|
|
18
|
+
from fastapi import HTTPException
|
|
19
|
+
|
|
20
|
+
from mostlyai.sdk._data.conversions import create_container_from_connector
|
|
21
|
+
from mostlyai.sdk._data.util.common import encrypt, get_passphrase
|
|
22
|
+
from mostlyai.sdk._local.storage import write_connector_to_json
|
|
23
|
+
from mostlyai.sdk.domain import (
|
|
24
|
+
ConnectorConfig,
|
|
25
|
+
Connector,
|
|
26
|
+
ConnectorPatchConfig,
|
|
27
|
+
ConnectorAccessType,
|
|
28
|
+
ConnectorReadDataConfig,
|
|
29
|
+
ConnectorWriteDataConfig,
|
|
30
|
+
)
|
|
31
|
+
from mostlyai.sdk._data.file.utils import make_data_table_from_container
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def create_connector(home_dir: Path, config: ConnectorConfig, test_connection: bool = True) -> Connector:
|
|
35
|
+
config = encrypt_connector_config(config)
|
|
36
|
+
connector = Connector(**config.model_dump())
|
|
37
|
+
if test_connection:
|
|
38
|
+
do_test_connection(connector)
|
|
39
|
+
connector_dir = home_dir / "connectors" / connector.id
|
|
40
|
+
write_connector_to_json(connector_dir, connector)
|
|
41
|
+
return connector
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def encrypt_connector_config(config: ConnectorConfig | ConnectorPatchConfig) -> ConnectorConfig | ConnectorPatchConfig:
|
|
45
|
+
# mimic the encryption of secrets and ssl parameters in local mode
|
|
46
|
+
attrs = (attr for attr in (config.secrets, config.ssl) if attr is not None)
|
|
47
|
+
for attr in attrs:
|
|
48
|
+
for k, v in attr.items():
|
|
49
|
+
attr[k] = encrypt(v, get_passphrase())
|
|
50
|
+
return config
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def do_test_connection(connector: Connector) -> bool:
|
|
54
|
+
# mimic the test connection service in local mode
|
|
55
|
+
try:
|
|
56
|
+
_ = create_container_from_connector(connector)
|
|
57
|
+
except Exception as e:
|
|
58
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
59
|
+
return True
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _data_table_from_connector_and_location(connector: Connector, location: str, is_output: bool):
|
|
63
|
+
container = create_container_from_connector(connector)
|
|
64
|
+
meta = container.set_location(location)
|
|
65
|
+
data_table = make_data_table_from_container(container, is_output=is_output)
|
|
66
|
+
data_table.name = meta["table_name"] if hasattr(container, "dbname") else "data"
|
|
67
|
+
return data_table
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def read_data_from_connector(connector: Connector, config: ConnectorReadDataConfig) -> pd.DataFrame:
|
|
71
|
+
if connector.access_type not in {ConnectorAccessType.read_data, ConnectorAccessType.write_data}:
|
|
72
|
+
raise HTTPException(status_code=400, detail="Connector does not have read access")
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
data_table = _data_table_from_connector_and_location(
|
|
76
|
+
connector=connector, location=config.location, is_output=False
|
|
77
|
+
)
|
|
78
|
+
return data_table.read_data(limit=config.limit, shuffle=config.shuffle)
|
|
79
|
+
except Exception as e:
|
|
80
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def write_data_to_connector(connector: Connector, config: ConnectorWriteDataConfig) -> None:
|
|
84
|
+
if connector.access_type != ConnectorAccessType.write_data:
|
|
85
|
+
raise HTTPException(status_code=400, detail="Connector does not have write access")
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
data_table = _data_table_from_connector_and_location(
|
|
89
|
+
connector=connector, location=config.location, is_output=True
|
|
90
|
+
)
|
|
91
|
+
df = pd.read_parquet(BytesIO(config.file))
|
|
92
|
+
data_table.write_data(df, if_exists=config.if_exists.value.lower())
|
|
93
|
+
except Exception as e:
|
|
94
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
@@ -34,7 +34,6 @@ from mostlyai.sdk._local.execution.step_encode_training_data import execute_step
|
|
|
34
34
|
from mostlyai.sdk._local.execution.step_finalize_generation import (
|
|
35
35
|
execute_step_finalize_generation,
|
|
36
36
|
create_generation_schema,
|
|
37
|
-
update_total_rows_and_datapoints,
|
|
38
37
|
)
|
|
39
38
|
from mostlyai.sdk._local.execution.step_generate_data import execute_step_generate_data
|
|
40
39
|
from mostlyai.sdk._local.execution.step_generate_model_report_data import (
|
|
@@ -505,7 +504,7 @@ class Execution:
|
|
|
505
504
|
step="finalize_generation",
|
|
506
505
|
)
|
|
507
506
|
|
|
508
|
-
|
|
507
|
+
execute_step_finalize_generation(
|
|
509
508
|
schema=schema,
|
|
510
509
|
is_probe=False,
|
|
511
510
|
job_workspace_dir=self._job_workspace_dir,
|
|
@@ -516,8 +515,6 @@ class Execution:
|
|
|
516
515
|
),
|
|
517
516
|
)
|
|
518
517
|
|
|
519
|
-
update_total_rows_and_datapoints(self._synthetic_dataset, usage)
|
|
520
|
-
|
|
521
518
|
def execute_deliver_data(self):
|
|
522
519
|
schema = create_generation_schema(
|
|
523
520
|
generator=self._generator,
|
|
@@ -14,7 +14,6 @@
|
|
|
14
14
|
import logging
|
|
15
15
|
import uuid
|
|
16
16
|
import zipfile
|
|
17
|
-
from collections import defaultdict
|
|
18
17
|
from pathlib import Path
|
|
19
18
|
from typing import Literal
|
|
20
19
|
|
|
@@ -31,7 +30,7 @@ from mostlyai.sdk._data.util.common import (
|
|
|
31
30
|
NON_CONTEXT_COLUMN_INFIX,
|
|
32
31
|
IS_NULL,
|
|
33
32
|
)
|
|
34
|
-
from mostlyai.sdk.domain import Generator
|
|
33
|
+
from mostlyai.sdk.domain import Generator
|
|
35
34
|
|
|
36
35
|
_LOG = logging.getLogger(__name__)
|
|
37
36
|
|
|
@@ -42,9 +41,7 @@ def execute_step_finalize_generation(
|
|
|
42
41
|
is_probe: bool,
|
|
43
42
|
job_workspace_dir: Path,
|
|
44
43
|
update_progress: ProgressCallback | None = None,
|
|
45
|
-
) ->
|
|
46
|
-
usage = calculate_usage(schema)
|
|
47
|
-
|
|
44
|
+
) -> None:
|
|
48
45
|
# short circuit for probing
|
|
49
46
|
delivery_dir = job_workspace_dir / "FinalizedSyntheticData"
|
|
50
47
|
if is_probe:
|
|
@@ -55,11 +52,14 @@ def execute_step_finalize_generation(
|
|
|
55
52
|
delivery_dir=delivery_dir,
|
|
56
53
|
export_csv=False,
|
|
57
54
|
)
|
|
58
|
-
return
|
|
55
|
+
return
|
|
59
56
|
|
|
60
57
|
random_samples_dir = job_workspace_dir / "RandomSamples"
|
|
61
58
|
zip_dir = job_workspace_dir / "ZIP"
|
|
62
|
-
|
|
59
|
+
|
|
60
|
+
# calculate total datapoints (rows × columns) across all tables
|
|
61
|
+
total_datapoints = sum(table.row_count * len(table.columns) for table in schema.tables.values())
|
|
62
|
+
export_csv = total_datapoints < 100_000_000 # only export CSV if datapoints < 100M
|
|
63
63
|
|
|
64
64
|
with ProgressCallbackWrapper(update_progress, description="Finalize generation") as progress:
|
|
65
65
|
# init progress with total_count; +4 for the 4 steps below
|
|
@@ -94,44 +94,6 @@ def execute_step_finalize_generation(
|
|
|
94
94
|
zip_data(delivery_dir=delivery_dir, format="csv", out_dir=zip_dir)
|
|
95
95
|
progress.update(advance=1)
|
|
96
96
|
|
|
97
|
-
return usage
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def calculate_usage(schema: Schema) -> list[dict]:
|
|
101
|
-
usage = []
|
|
102
|
-
for table_name, table in schema.tables.items():
|
|
103
|
-
n_rows = table.row_count
|
|
104
|
-
# language columns depend on the average length (of a sample)
|
|
105
|
-
language_columns = [
|
|
106
|
-
col for col in table.columns if table.encoding_types[col] == ModelEncodingType.language_text
|
|
107
|
-
]
|
|
108
|
-
language_samples = next(table.read_chunks(columns=language_columns, fetch_chunk_size=1_000))
|
|
109
|
-
# the weight of any non-language columns is 1
|
|
110
|
-
assumed_avg_token_size = 5
|
|
111
|
-
column_weights = defaultdict(
|
|
112
|
-
lambda: 1,
|
|
113
|
-
{
|
|
114
|
-
col: language_samples[col].str.len().mean() / assumed_avg_token_size
|
|
115
|
-
if not language_samples[col].empty
|
|
116
|
-
else 1
|
|
117
|
-
for col in language_columns
|
|
118
|
-
},
|
|
119
|
-
)
|
|
120
|
-
if language_columns:
|
|
121
|
-
_LOG.info(f"{table=} has language columns with weights {dict(column_weights)} for usage calculation")
|
|
122
|
-
n_weighted_columns = sum(column_weights[col] for col in table.encoding_types)
|
|
123
|
-
total_datapoints = int(n_rows * n_weighted_columns)
|
|
124
|
-
usage.append(dict(table=table.name, total_datapoints=total_datapoints, total_rows=n_rows))
|
|
125
|
-
return usage
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def update_total_rows_and_datapoints(synthetic_dataset: SyntheticDataset, usage: list[dict]):
|
|
129
|
-
for table_usage in usage:
|
|
130
|
-
table = next(t for t in synthetic_dataset.tables if t.name == table_usage["table"])
|
|
131
|
-
table.total_rows = table_usage["total_rows"]
|
|
132
|
-
table.total_datapoints = table_usage["total_datapoints"]
|
|
133
|
-
return usage
|
|
134
|
-
|
|
135
97
|
|
|
136
98
|
def format_datetime(df: pd.DataFrame) -> pd.DataFrame:
|
|
137
99
|
for column in df.columns:
|
|
@@ -19,10 +19,12 @@ import uuid
|
|
|
19
19
|
import zipfile
|
|
20
20
|
from io import BytesIO
|
|
21
21
|
from pathlib import Path
|
|
22
|
+
import tempfile
|
|
22
23
|
|
|
23
|
-
from fastapi import APIRouter, Body, HTTPException, UploadFile, File
|
|
24
|
+
from fastapi import APIRouter, Body, HTTPException, UploadFile, File, Form
|
|
24
25
|
from fastapi.encoders import jsonable_encoder
|
|
25
26
|
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse, HTMLResponse, RedirectResponse
|
|
27
|
+
from starlette.background import BackgroundTask
|
|
26
28
|
|
|
27
29
|
from mostlyai import sdk
|
|
28
30
|
from mostlyai.sdk._data.conversions import create_container_from_connector
|
|
@@ -56,6 +58,9 @@ from mostlyai.sdk.domain import (
|
|
|
56
58
|
GeneratorCloneTrainingStatus,
|
|
57
59
|
SyntheticDatasetReportType,
|
|
58
60
|
SyntheticDatasetListItem,
|
|
61
|
+
ConnectorReadDataConfig,
|
|
62
|
+
IfExists,
|
|
63
|
+
ConnectorWriteDataConfig,
|
|
59
64
|
)
|
|
60
65
|
from mostlyai.sdk._local.storage import (
|
|
61
66
|
read_generator_from_json,
|
|
@@ -166,8 +171,6 @@ class Routes:
|
|
|
166
171
|
@self.router.get("/connectors/{id}", response_model=Connector)
|
|
167
172
|
async def get_connector(id: str) -> Connector:
|
|
168
173
|
connector_dir = self.home_dir / "connectors" / id
|
|
169
|
-
if not connector_dir.exists():
|
|
170
|
-
raise HTTPException(status_code=404, detail=f"Connector `{id}` not found")
|
|
171
174
|
connector = read_connector_from_json(connector_dir)
|
|
172
175
|
return connector
|
|
173
176
|
|
|
@@ -224,6 +227,33 @@ class Routes:
|
|
|
224
227
|
]
|
|
225
228
|
return JSONResponse(status_code=200, content=columns)
|
|
226
229
|
|
|
230
|
+
@self.router.post("/connectors/{id}/read-data")
|
|
231
|
+
async def read_data(id: str, config: ConnectorReadDataConfig = Body(...)) -> StreamingResponse:
|
|
232
|
+
connector_dir = self.home_dir / "connectors" / id
|
|
233
|
+
connector = read_connector_from_json(connector_dir)
|
|
234
|
+
df = connectors.read_data_from_connector(connector, config)
|
|
235
|
+
|
|
236
|
+
# this file can only be safely removed once the streaming response is complete
|
|
237
|
+
tmp_path = tempfile.mktemp(suffix=".parquet")
|
|
238
|
+
df.to_parquet(tmp_path)
|
|
239
|
+
|
|
240
|
+
return StreamingResponse(
|
|
241
|
+
open(tmp_path, mode="rb"),
|
|
242
|
+
media_type="application/octet-stream",
|
|
243
|
+
headers={"Content-Disposition": "attachment; filename=data.parquet"},
|
|
244
|
+
background=BackgroundTask(Path(tmp_path).unlink, missing_ok=True),
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
@self.router.post("/connectors/{id}/write-data")
|
|
248
|
+
async def write_data(
|
|
249
|
+
id: str, file: UploadFile = File(...), location: str = Form(...), if_exists: IfExists = Form("FAIL")
|
|
250
|
+
) -> None:
|
|
251
|
+
connector_dir = self.home_dir / "connectors" / id
|
|
252
|
+
connector = read_connector_from_json(connector_dir)
|
|
253
|
+
file_content = await file.read()
|
|
254
|
+
config = ConnectorWriteDataConfig(location=location, file=file_content, if_exists=if_exists)
|
|
255
|
+
connectors.write_data_to_connector(connector, config)
|
|
256
|
+
|
|
227
257
|
## GENERATORS
|
|
228
258
|
|
|
229
259
|
@self.router.get("/generators")
|
|
@@ -22,7 +22,10 @@ def _snake_to_camel(snake_str: str) -> str:
|
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
def _camel_to_snake(camel_str: str) -> str:
|
|
25
|
-
|
|
25
|
+
# handle acronyms by treating consecutive uppercase letters as a group
|
|
26
|
+
s1 = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", camel_str) # e.g., "GPUTime" -> "GPU_Time"
|
|
27
|
+
s2 = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", s1) # e.g., "virtualGPU" -> "virtual_GPU"
|
|
28
|
+
return s2.lower()
|
|
26
29
|
|
|
27
30
|
|
|
28
31
|
def _convert_case(input_data: dict, conv_func: Callable[[str], str]) -> dict:
|
|
@@ -13,10 +13,13 @@
|
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
|
|
15
15
|
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import io
|
|
16
18
|
from typing import Any
|
|
17
19
|
from collections.abc import Iterator
|
|
18
20
|
|
|
19
21
|
import rich
|
|
22
|
+
import pandas as pd
|
|
20
23
|
|
|
21
24
|
from mostlyai.sdk.client.base import (
|
|
22
25
|
DELETE,
|
|
@@ -31,6 +34,8 @@ from mostlyai.sdk.domain import (
|
|
|
31
34
|
ConnectorListItem,
|
|
32
35
|
ConnectorPatchConfig,
|
|
33
36
|
ConnectorConfig,
|
|
37
|
+
ConnectorWriteDataConfig,
|
|
38
|
+
IfExists,
|
|
34
39
|
)
|
|
35
40
|
|
|
36
41
|
|
|
@@ -166,3 +171,37 @@ class _MostlyConnectorsClient(_MostlyBaseClient):
|
|
|
166
171
|
def _schema(self, connector_id: str, location: str) -> list[dict[str, Any]]:
|
|
167
172
|
response = self.request(verb=GET, path=[connector_id, "schema"], params={"location": location})
|
|
168
173
|
return response
|
|
174
|
+
|
|
175
|
+
def _read_data(
|
|
176
|
+
self, connector_id: str, location: str, limit: int | None = None, shuffle: bool = False
|
|
177
|
+
) -> pd.DataFrame:
|
|
178
|
+
response = self.request(
|
|
179
|
+
verb=POST,
|
|
180
|
+
path=[connector_id, "read-data"],
|
|
181
|
+
json={"location": location, "limit": limit, "shuffle": shuffle},
|
|
182
|
+
raw_response=True,
|
|
183
|
+
)
|
|
184
|
+
content_bytes = response.content
|
|
185
|
+
df = pd.read_parquet(io.BytesIO(content_bytes))
|
|
186
|
+
return df
|
|
187
|
+
|
|
188
|
+
def _write_data(
|
|
189
|
+
self, connector_id: str, data: pd.DataFrame, location: str, if_exists: IfExists = IfExists.fail
|
|
190
|
+
) -> None:
|
|
191
|
+
buffer = io.BytesIO()
|
|
192
|
+
data.to_parquet(buffer, index=False)
|
|
193
|
+
buffer.seek(0)
|
|
194
|
+
|
|
195
|
+
files = {
|
|
196
|
+
"file": ("data.parquet", buffer, "application/octet-stream"),
|
|
197
|
+
}
|
|
198
|
+
config_data = ConnectorWriteDataConfig(location=location, if_exists=if_exists.upper()).model_dump(
|
|
199
|
+
mode="json", exclude_unset=True
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
self.request(
|
|
203
|
+
verb="POST",
|
|
204
|
+
path=[connector_id, "write-data"],
|
|
205
|
+
files=files,
|
|
206
|
+
data=config_data,
|
|
207
|
+
)
|
|
@@ -291,7 +291,7 @@ class _MostlyGeneratorsClient(_MostlyBaseClient):
|
|
|
291
291
|
response = self.request(
|
|
292
292
|
verb=POST,
|
|
293
293
|
path=[generator_id, "clone"],
|
|
294
|
-
json={"trainingStatus": training_status},
|
|
294
|
+
json={"trainingStatus": training_status.upper()},
|
|
295
295
|
response_type=Generator,
|
|
296
296
|
)
|
|
297
297
|
return response
|