kumoai 2.13.0.dev202511211730__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 (59) hide show
  1. kumoai/__init__.py +35 -26
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +6 -0
  4. kumoai/client/jobs.py +26 -0
  5. kumoai/client/pquery.py +6 -2
  6. kumoai/connector/utils.py +44 -9
  7. kumoai/experimental/rfm/__init__.py +70 -68
  8. kumoai/experimental/rfm/authenticate.py +3 -4
  9. kumoai/experimental/rfm/backend/__init__.py +0 -0
  10. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  11. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +65 -127
  12. kumoai/experimental/rfm/backend/local/sampler.py +312 -0
  13. kumoai/experimental/rfm/backend/local/table.py +113 -0
  14. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  15. kumoai/experimental/rfm/backend/snow/sampler.py +407 -0
  16. kumoai/experimental/rfm/backend/snow/table.py +245 -0
  17. kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
  18. kumoai/experimental/rfm/backend/sqlite/sampler.py +454 -0
  19. kumoai/experimental/rfm/backend/sqlite/table.py +184 -0
  20. kumoai/experimental/rfm/base/__init__.py +30 -0
  21. kumoai/experimental/rfm/base/column.py +152 -0
  22. kumoai/experimental/rfm/base/expression.py +44 -0
  23. kumoai/experimental/rfm/base/mapper.py +69 -0
  24. kumoai/experimental/rfm/base/sampler.py +783 -0
  25. kumoai/experimental/rfm/base/source.py +19 -0
  26. kumoai/experimental/rfm/base/sql_sampler.py +385 -0
  27. kumoai/experimental/rfm/base/table.py +722 -0
  28. kumoai/experimental/rfm/base/utils.py +36 -0
  29. kumoai/experimental/rfm/{local_graph.py → graph.py} +581 -154
  30. kumoai/experimental/rfm/infer/__init__.py +8 -0
  31. kumoai/experimental/rfm/infer/dtype.py +84 -0
  32. kumoai/experimental/rfm/infer/multicategorical.py +1 -1
  33. kumoai/experimental/rfm/infer/pkey.py +128 -0
  34. kumoai/experimental/rfm/infer/stype.py +35 -0
  35. kumoai/experimental/rfm/infer/time_col.py +63 -0
  36. kumoai/experimental/rfm/pquery/executor.py +27 -27
  37. kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
  38. kumoai/experimental/rfm/relbench.py +76 -0
  39. kumoai/experimental/rfm/rfm.py +783 -481
  40. kumoai/experimental/rfm/sagemaker.py +15 -7
  41. kumoai/experimental/rfm/task_table.py +292 -0
  42. kumoai/pquery/predictive_query.py +10 -6
  43. kumoai/pquery/training_table.py +16 -2
  44. kumoai/testing/decorators.py +1 -1
  45. kumoai/testing/snow.py +50 -0
  46. kumoai/trainer/distilled_trainer.py +175 -0
  47. kumoai/utils/__init__.py +3 -2
  48. kumoai/utils/display.py +87 -0
  49. kumoai/utils/progress_logger.py +192 -13
  50. kumoai/utils/sql.py +3 -0
  51. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/METADATA +10 -8
  52. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/RECORD +55 -30
  53. kumoai/experimental/rfm/local_graph_sampler.py +0 -182
  54. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  55. kumoai/experimental/rfm/local_table.py +0 -545
  56. kumoai/experimental/rfm/utils.py +0 -344
  57. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/WHEEL +0 -0
  58. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/licenses/LICENSE +0 -0
  59. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.15.0.dev202601131732.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,245 @@
1
+ import re
2
+ from collections import Counter
3
+ from collections.abc import Sequence
4
+ from typing import cast
5
+
6
+ import pandas as pd
7
+ from kumoapi.model_plan import MissingType
8
+ from kumoapi.typing import Dtype
9
+
10
+ from kumoai.experimental.rfm.backend.snow import Connection
11
+ from kumoai.experimental.rfm.base import (
12
+ ColumnSpec,
13
+ ColumnSpecType,
14
+ DataBackend,
15
+ SourceColumn,
16
+ SourceForeignKey,
17
+ Table,
18
+ )
19
+ from kumoai.utils import quote_ident
20
+
21
+
22
+ class SnowTable(Table):
23
+ r"""A table backed by a :class:`sqlite` database.
24
+
25
+ Args:
26
+ connection: The connection to a :class:`snowflake` database.
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.
30
+ database: The database.
31
+ schema: The schema.
32
+ columns: The selected columns of this table.
33
+ primary_key: The name of the primary key of this table, if it exists.
34
+ time_column: The name of the time column of this table, if it exists.
35
+ end_time_column: The name of the end time column of this table, if it
36
+ exists.
37
+ """
38
+ def __init__(
39
+ self,
40
+ connection: Connection,
41
+ name: str,
42
+ source_name: str | None = None,
43
+ database: str | None = None,
44
+ schema: str | None = 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,
49
+ ) -> None:
50
+
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}'")
63
+
64
+ self._connection = connection
65
+ self._database = database
66
+ self._schema = schema
67
+
68
+ super().__init__(
69
+ name=name,
70
+ source_name=source_name,
71
+ columns=columns,
72
+ primary_key=primary_key,
73
+ time_column=time_column,
74
+ end_time_column=end_time_column,
75
+ )
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
+
87
+ @property
88
+ def backend(self) -> DataBackend:
89
+ return cast(DataBackend, DataBackend.SNOWFLAKE)
90
+
91
+ def _get_source_columns(self) -> list[SourceColumn]:
92
+ source_columns: list[SourceColumn] = []
93
+ with self._connection.cursor() as cursor:
94
+ try:
95
+ sql = f"DESCRIBE TABLE {self._quoted_source_name}"
96
+ cursor.execute(sql)
97
+ except Exception as e:
98
+ raise ValueError(f"Table '{self.source_name}' does not exist "
99
+ f"in the remote data backend") from e
100
+
101
+ for row in cursor.fetchall():
102
+ column, dtype, _, null, _, is_pkey, is_unique, *_ = row
103
+
104
+ source_column = SourceColumn(
105
+ name=column,
106
+ dtype=self._to_dtype(dtype),
107
+ is_primary_key=is_pkey.strip().upper() == 'Y',
108
+ is_unique_key=is_unique.strip().upper() == 'Y',
109
+ is_nullable=null.strip().upper() == 'Y',
110
+ )
111
+ source_columns.append(source_column)
112
+
113
+ return source_columns
114
+
115
+ def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
116
+ source_foreign_keys: list[SourceForeignKey] = []
117
+ with self._connection.cursor() as cursor:
118
+ sql = f"SHOW IMPORTED KEYS IN TABLE {self._quoted_source_name}"
119
+ cursor.execute(sql)
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:
133
+ with self._connection.cursor() as cursor:
134
+ columns = [quote_ident(col) for col in self._source_column_dict]
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}")
179
+ cursor.execute(sql)
180
+ table = cursor.fetch_arrow_all()
181
+
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
245
+ return None
@@ -0,0 +1,32 @@
1
+ from pathlib import Path
2
+ from typing import Any, TypeAlias
3
+
4
+ try:
5
+ import adbc_driver_sqlite.dbapi as adbc
6
+ except ImportError:
7
+ raise ImportError("No module named 'adbc_driver_sqlite'. Please install "
8
+ "Kumo SDK with the 'sqlite' extension via "
9
+ "`pip install kumoai[sqlite]`.")
10
+
11
+ Connection: TypeAlias = adbc.AdbcSqliteConnection
12
+
13
+
14
+ def connect(uri: str | Path | None = None, **kwargs: Any) -> Connection:
15
+ r"""Opens a connection to a :class:`sqlite` database.
16
+
17
+ uri: The path to the database file to be opened.
18
+ kwargs: Additional connection arguments, following the
19
+ :class:`adbc_driver_sqlite` protocol.
20
+ """
21
+ return adbc.connect(uri, **kwargs)
22
+
23
+
24
+ from .table import SQLiteTable # noqa: E402
25
+ from .sampler import SQLiteSampler # noqa: E402
26
+
27
+ __all__ = [
28
+ 'connect',
29
+ 'Connection',
30
+ 'SQLiteTable',
31
+ 'SQLiteSampler',
32
+ ]