kumoai 2.14.0.dev202512141732__py3-none-any.whl → 2.15.0.dev202601131732__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. kumoai/__init__.py +23 -26
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +6 -0
  4. kumoai/client/jobs.py +26 -0
  5. kumoai/connector/utils.py +21 -7
  6. kumoai/experimental/rfm/__init__.py +51 -24
  7. kumoai/experimental/rfm/authenticate.py +3 -4
  8. kumoai/experimental/rfm/backend/local/graph_store.py +37 -46
  9. kumoai/experimental/rfm/backend/local/sampler.py +4 -5
  10. kumoai/experimental/rfm/backend/local/table.py +24 -30
  11. kumoai/experimental/rfm/backend/snow/sampler.py +331 -43
  12. kumoai/experimental/rfm/backend/snow/table.py +166 -56
  13. kumoai/experimental/rfm/backend/sqlite/__init__.py +2 -2
  14. kumoai/experimental/rfm/backend/sqlite/sampler.py +372 -30
  15. kumoai/experimental/rfm/backend/sqlite/table.py +117 -48
  16. kumoai/experimental/rfm/base/__init__.py +8 -1
  17. kumoai/experimental/rfm/base/column.py +96 -10
  18. kumoai/experimental/rfm/base/expression.py +44 -0
  19. kumoai/experimental/rfm/base/mapper.py +69 -0
  20. kumoai/experimental/rfm/base/sampler.py +28 -18
  21. kumoai/experimental/rfm/base/source.py +1 -1
  22. kumoai/experimental/rfm/base/sql_sampler.py +385 -0
  23. kumoai/experimental/rfm/base/table.py +374 -208
  24. kumoai/experimental/rfm/base/utils.py +36 -0
  25. kumoai/experimental/rfm/graph.py +335 -180
  26. kumoai/experimental/rfm/infer/__init__.py +6 -4
  27. kumoai/experimental/rfm/infer/dtype.py +10 -5
  28. kumoai/experimental/rfm/infer/multicategorical.py +1 -1
  29. kumoai/experimental/rfm/infer/pkey.py +4 -2
  30. kumoai/experimental/rfm/infer/stype.py +35 -0
  31. kumoai/experimental/rfm/infer/time_col.py +5 -4
  32. kumoai/experimental/rfm/pquery/executor.py +27 -27
  33. kumoai/experimental/rfm/pquery/pandas_executor.py +29 -31
  34. kumoai/experimental/rfm/relbench.py +76 -0
  35. kumoai/experimental/rfm/rfm.py +606 -361
  36. kumoai/experimental/rfm/sagemaker.py +4 -4
  37. kumoai/experimental/rfm/task_table.py +292 -0
  38. kumoai/pquery/training_table.py +16 -2
  39. kumoai/testing/snow.py +3 -3
  40. kumoai/trainer/distilled_trainer.py +175 -0
  41. kumoai/utils/__init__.py +1 -2
  42. kumoai/utils/display.py +87 -0
  43. kumoai/utils/progress_logger.py +192 -13
  44. kumoai/utils/sql.py +2 -2
  45. {kumoai-2.14.0.dev202512141732.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/METADATA +3 -2
  46. {kumoai-2.14.0.dev202512141732.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/RECORD +49 -40
  47. {kumoai-2.14.0.dev202512141732.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/WHEEL +0 -0
  48. {kumoai-2.14.0.dev202512141732.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/licenses/LICENSE +0 -0
  49. {kumoai-2.14.0.dev202512141732.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/top_level.txt +0 -0
@@ -1,11 +1,16 @@
1
1
  import re
2
- from typing import List, Optional, Sequence, cast
2
+ from collections import Counter
3
+ from collections.abc import Sequence
4
+ from typing import cast
3
5
 
4
6
  import pandas as pd
7
+ from kumoapi.model_plan import MissingType
5
8
  from kumoapi.typing import Dtype
6
9
 
7
10
  from kumoai.experimental.rfm.backend.snow import Connection
8
11
  from kumoai.experimental.rfm.base import (
12
+ ColumnSpec,
13
+ ColumnSpecType,
9
14
  DataBackend,
10
15
  SourceColumn,
11
16
  SourceForeignKey,
@@ -20,6 +25,8 @@ class SnowTable(Table):
20
25
  Args:
21
26
  connection: The connection to a :class:`snowflake` database.
22
27
  name: The name of this table.
28
+ source_name: The source name of this table. If set to ``None``,
29
+ ``name`` is being used.
23
30
  database: The database.
24
31
  schema: The schema.
25
32
  columns: The selected columns of this table.
@@ -32,17 +39,27 @@ class SnowTable(Table):
32
39
  self,
33
40
  connection: Connection,
34
41
  name: str,
42
+ source_name: str | None = None,
35
43
  database: str | None = None,
36
44
  schema: str | None = None,
37
- columns: Optional[Sequence[str]] = None,
38
- primary_key: Optional[str] = None,
39
- time_column: Optional[str] = None,
40
- end_time_column: Optional[str] = None,
45
+ columns: Sequence[ColumnSpecType] | None = None,
46
+ primary_key: MissingType | str | None = MissingType.VALUE,
47
+ time_column: str | None = None,
48
+ end_time_column: str | None = None,
41
49
  ) -> None:
42
50
 
43
- if database is not None and schema is None:
44
- raise ValueError(f"Missing 'schema' for table '{name}' in "
45
- f"database '{database}'")
51
+ if database is None or schema is None:
52
+ with connection.cursor() as cursor:
53
+ cursor.execute("SELECT CURRENT_DATABASE(), CURRENT_SCHEMA()")
54
+ result = cursor.fetchone()
55
+ database = database or result[0]
56
+ assert database is not None
57
+ schema = schema or result[1]
58
+
59
+ if schema is None:
60
+ raise ValueError(f"Unspecified 'schema' for table "
61
+ f"'{source_name or name}' in database "
62
+ f"'{database}'")
46
63
 
47
64
  self._connection = connection
48
65
  self._database = database
@@ -50,61 +67,43 @@ class SnowTable(Table):
50
67
 
51
68
  super().__init__(
52
69
  name=name,
70
+ source_name=source_name,
53
71
  columns=columns,
54
72
  primary_key=primary_key,
55
73
  time_column=time_column,
56
74
  end_time_column=end_time_column,
57
75
  )
58
76
 
77
+ @property
78
+ def source_name(self) -> str:
79
+ names = [self._database, self._schema, self._source_name]
80
+ return '.'.join(names)
81
+
82
+ @property
83
+ def _quoted_source_name(self) -> str:
84
+ names = [self._database, self._schema, self._source_name]
85
+ return '.'.join([quote_ident(name) for name in names])
86
+
59
87
  @property
60
88
  def backend(self) -> DataBackend:
61
89
  return cast(DataBackend, DataBackend.SNOWFLAKE)
62
90
 
63
- @property
64
- def fqn(self) -> str:
65
- r"""The fully-qualified quoted table name."""
66
- names: List[str] = []
67
- if self._database is not None:
68
- names.append(quote_ident(self._database))
69
- if self._schema is not None:
70
- names.append(quote_ident(self._schema))
71
- return '.'.join(names + [quote_ident(self._name)])
72
-
73
- def _get_source_columns(self) -> List[SourceColumn]:
74
- source_columns: List[SourceColumn] = []
91
+ def _get_source_columns(self) -> list[SourceColumn]:
92
+ source_columns: list[SourceColumn] = []
75
93
  with self._connection.cursor() as cursor:
76
94
  try:
77
- sql = f"DESCRIBE TABLE {self.fqn}"
95
+ sql = f"DESCRIBE TABLE {self._quoted_source_name}"
78
96
  cursor.execute(sql)
79
97
  except Exception as e:
80
- names: list[str] = []
81
- if self._database is not None:
82
- names.append(self._database)
83
- if self._schema is not None:
84
- names.append(self._schema)
85
- name = '.'.join(names + [self._name])
86
- raise ValueError(f"Table '{name}' does not exist") from e
98
+ raise ValueError(f"Table '{self.source_name}' does not exist "
99
+ f"in the remote data backend") from e
87
100
 
88
101
  for row in cursor.fetchall():
89
- column, type, _, null, _, is_pkey, is_unique = row[:7]
90
-
91
- type = type.strip().upper()
92
- if type.startswith('NUMBER'):
93
- dtype = Dtype.int
94
- elif type.startswith('VARCHAR'):
95
- dtype = Dtype.string
96
- elif type == 'FLOAT':
97
- dtype = Dtype.float
98
- elif type == 'BOOLEAN':
99
- dtype = Dtype.bool
100
- elif re.search('DATE|TIMESTAMP', type):
101
- dtype = Dtype.date
102
- else:
103
- continue
102
+ column, dtype, _, null, _, is_pkey, is_unique, *_ = row
104
103
 
105
104
  source_column = SourceColumn(
106
105
  name=column,
107
- dtype=dtype,
106
+ dtype=self._to_dtype(dtype),
108
107
  is_primary_key=is_pkey.strip().upper() == 'Y',
109
108
  is_unique_key=is_unique.strip().upper() == 'Y',
110
109
  is_nullable=null.strip().upper() == 'Y',
@@ -113,23 +112,134 @@ class SnowTable(Table):
113
112
 
114
113
  return source_columns
115
114
 
116
- def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
117
- source_fkeys: List[SourceForeignKey] = []
115
+ def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
116
+ source_foreign_keys: list[SourceForeignKey] = []
118
117
  with self._connection.cursor() as cursor:
119
- sql = f"SHOW IMPORTED KEYS IN TABLE {self.fqn}"
118
+ sql = f"SHOW IMPORTED KEYS IN TABLE {self._quoted_source_name}"
120
119
  cursor.execute(sql)
121
- for row in cursor.fetchall():
122
- _, _, _, dst_table, pkey, _, _, _, fkey = row[:9]
123
- source_fkeys.append(SourceForeignKey(fkey, dst_table, pkey))
124
- return source_fkeys
125
-
126
- def _get_sample_df(self) -> pd.DataFrame:
120
+ rows = cursor.fetchall()
121
+ counts = Counter(row[13] for row in rows)
122
+ for row in rows:
123
+ if counts[row[13]] == 1:
124
+ source_foreign_key = SourceForeignKey(
125
+ name=row[8],
126
+ dst_table=f'{row[1]}.{row[2]}.{row[3]}',
127
+ primary_key=row[4],
128
+ )
129
+ source_foreign_keys.append(source_foreign_key)
130
+ return source_foreign_keys
131
+
132
+ def _get_source_sample_df(self) -> pd.DataFrame:
127
133
  with self._connection.cursor() as cursor:
128
134
  columns = [quote_ident(col) for col in self._source_column_dict]
129
- sql = f"SELECT {', '.join(columns)} FROM {self.fqn} LIMIT 1000"
135
+ sql = (f"SELECT {', '.join(columns)} "
136
+ f"FROM {self._quoted_source_name} "
137
+ f"LIMIT {self._NUM_SAMPLE_ROWS}")
138
+ cursor.execute(sql)
139
+ table = cursor.fetch_arrow_all()
140
+
141
+ if table is None:
142
+ raise RuntimeError(f"Table '{self.source_name}' is empty")
143
+
144
+ return self._sanitize(
145
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
146
+ dtype_dict={
147
+ column.name: column.dtype
148
+ for column in self._source_column_dict.values()
149
+ },
150
+ stype_dict=None,
151
+ )
152
+
153
+ def _get_num_rows(self) -> int | None:
154
+ with self._connection.cursor() as cursor:
155
+ quoted_source_name = quote_ident(self._source_name, char="'")
156
+ sql = (f"SHOW TABLES LIKE {quoted_source_name} "
157
+ f"IN SCHEMA {quote_ident(self._database)}."
158
+ f"{quote_ident(self._schema)}")
159
+ cursor.execute(sql)
160
+ num_rows = cursor.fetchone()[7]
161
+
162
+ if num_rows == 0:
163
+ raise RuntimeError("Table '{self.source_name}' is empty")
164
+
165
+ return num_rows
166
+
167
+ def _get_expr_sample_df(
168
+ self,
169
+ columns: Sequence[ColumnSpec],
170
+ ) -> pd.DataFrame:
171
+ with self._connection.cursor() as cursor:
172
+ projections = [
173
+ f"{column.expr} AS {quote_ident(column.name)}"
174
+ for column in columns
175
+ ]
176
+ sql = (f"SELECT {', '.join(projections)} "
177
+ f"FROM {self._quoted_source_name} "
178
+ f"LIMIT {self._NUM_SAMPLE_ROWS}")
130
179
  cursor.execute(sql)
131
180
  table = cursor.fetch_arrow_all()
132
- return table.to_pandas(types_mapper=pd.ArrowDtype)
133
181
 
134
- def _get_num_rows(self) -> Optional[int]:
182
+ if table is None:
183
+ raise RuntimeError(f"Table '{self.source_name}' is empty")
184
+
185
+ return self._sanitize(
186
+ df=table.to_pandas(types_mapper=pd.ArrowDtype),
187
+ dtype_dict={column.name: column.dtype
188
+ for column in columns},
189
+ stype_dict=None,
190
+ )
191
+
192
+ @staticmethod
193
+ def _to_dtype(dtype: str | None) -> Dtype | None:
194
+ if dtype is None:
195
+ return None
196
+ dtype = dtype.strip().upper()
197
+ if dtype.startswith('NUMBER'):
198
+ try: # Parse `scale` from 'NUMBER(precision, scale)':
199
+ scale = int(dtype.split(',')[-1].split(')')[0])
200
+ return Dtype.int if scale == 0 else Dtype.float
201
+ except Exception:
202
+ return Dtype.float
203
+ if dtype == 'FLOAT':
204
+ return Dtype.float
205
+ if dtype.startswith('VARCHAR'):
206
+ return Dtype.string
207
+ if dtype.startswith('BINARY'):
208
+ return Dtype.binary
209
+ if dtype == 'BOOLEAN':
210
+ return Dtype.bool
211
+ if dtype.startswith('DATE') or dtype.startswith('TIMESTAMP'):
212
+ return Dtype.date
213
+ if dtype.startswith('TIME'):
214
+ return Dtype.time
215
+ if dtype.startswith('VECTOR'):
216
+ try: # Parse element data type from 'VECTOR(dtype, dimension)':
217
+ dtype = dtype.split(',')[0].split('(')[1].strip()
218
+ if dtype == 'INT':
219
+ return Dtype.intlist
220
+ elif dtype == 'FLOAT':
221
+ return Dtype.floatlist
222
+ except Exception:
223
+ pass
224
+ return Dtype.unsupported
225
+ if dtype.startswith('ARRAY'):
226
+ try: # Parse element data type from 'ARRAY(dtype)':
227
+ dtype = dtype.split('(', maxsplit=1)[1]
228
+ dtype = dtype.rsplit(')', maxsplit=1)[0]
229
+ _dtype = SnowTable._to_dtype(dtype)
230
+ if _dtype is not None and _dtype.is_int():
231
+ return Dtype.intlist
232
+ elif _dtype is not None and _dtype.is_float():
233
+ return Dtype.floatlist
234
+ elif _dtype is not None and _dtype.is_string():
235
+ return Dtype.stringlist
236
+ except Exception:
237
+ pass
238
+ return Dtype.unsupported
239
+ # Unsupported data types:
240
+ if re.search(
241
+ 'DECFLOAT|VARIANT|OBJECT|MAP|FILE|GEOGRAPHY|GEOMETRY',
242
+ dtype,
243
+ ):
244
+ return Dtype.unsupported
135
245
  return None
@@ -1,5 +1,5 @@
1
1
  from pathlib import Path
2
- from typing import Any, TypeAlias, Union
2
+ from typing import Any, TypeAlias
3
3
 
4
4
  try:
5
5
  import adbc_driver_sqlite.dbapi as adbc
@@ -11,7 +11,7 @@ except ImportError:
11
11
  Connection: TypeAlias = adbc.AdbcSqliteConnection
12
12
 
13
13
 
14
- def connect(uri: Union[str, Path, None] = None, **kwargs: Any) -> Connection:
14
+ def connect(uri: str | Path | None = None, **kwargs: Any) -> Connection:
15
15
  r"""Opens a connection to a :class:`sqlite` database.
16
16
 
17
17
  uri: The path to the database file to be opened.