kumoai 2.12.1__py3-none-any.whl → 2.14.0.dev202512141732__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 (43) hide show
  1. kumoai/__init__.py +18 -9
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +9 -13
  4. kumoai/client/pquery.py +6 -2
  5. kumoai/connector/utils.py +23 -2
  6. kumoai/experimental/rfm/__init__.py +162 -46
  7. kumoai/experimental/rfm/backend/__init__.py +0 -0
  8. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  9. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +37 -90
  10. kumoai/experimental/rfm/backend/local/sampler.py +313 -0
  11. kumoai/experimental/rfm/backend/local/table.py +119 -0
  12. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  13. kumoai/experimental/rfm/backend/snow/sampler.py +119 -0
  14. kumoai/experimental/rfm/backend/snow/table.py +135 -0
  15. kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
  16. kumoai/experimental/rfm/backend/sqlite/sampler.py +112 -0
  17. kumoai/experimental/rfm/backend/sqlite/table.py +115 -0
  18. kumoai/experimental/rfm/base/__init__.py +23 -0
  19. kumoai/experimental/rfm/base/column.py +66 -0
  20. kumoai/experimental/rfm/base/sampler.py +773 -0
  21. kumoai/experimental/rfm/base/source.py +19 -0
  22. kumoai/experimental/rfm/{local_table.py → base/table.py} +152 -141
  23. kumoai/experimental/rfm/{local_graph.py → graph.py} +352 -80
  24. kumoai/experimental/rfm/infer/__init__.py +6 -0
  25. kumoai/experimental/rfm/infer/dtype.py +79 -0
  26. kumoai/experimental/rfm/infer/pkey.py +126 -0
  27. kumoai/experimental/rfm/infer/time_col.py +62 -0
  28. kumoai/experimental/rfm/pquery/pandas_executor.py +1 -1
  29. kumoai/experimental/rfm/rfm.py +233 -174
  30. kumoai/experimental/rfm/sagemaker.py +138 -0
  31. kumoai/spcs.py +1 -3
  32. kumoai/testing/decorators.py +1 -1
  33. kumoai/testing/snow.py +50 -0
  34. kumoai/utils/__init__.py +2 -0
  35. kumoai/utils/sql.py +3 -0
  36. {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/METADATA +12 -2
  37. {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/RECORD +40 -23
  38. kumoai/experimental/rfm/local_graph_sampler.py +0 -184
  39. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  40. kumoai/experimental/rfm/utils.py +0 -344
  41. {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/WHEEL +0 -0
  42. {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/licenses/LICENSE +0 -0
  43. {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/top_level.txt +0 -0
@@ -1,344 +0,0 @@
1
- import re
2
- import warnings
3
- from typing import Any, Dict, Optional
4
-
5
- import numpy as np
6
- import pandas as pd
7
- import pyarrow as pa
8
- from kumoapi.typing import Dtype, Stype
9
-
10
- from kumoai.experimental.rfm.infer import (
11
- contains_categorical,
12
- contains_id,
13
- contains_multicategorical,
14
- contains_timestamp,
15
- )
16
-
17
- # Mapping from pandas/numpy dtypes to Kumo Dtypes
18
- PANDAS_TO_DTYPE: Dict[Any, Dtype] = {
19
- np.dtype('bool'): Dtype.bool,
20
- pd.BooleanDtype(): Dtype.bool,
21
- pa.bool_(): Dtype.bool,
22
- np.dtype('byte'): Dtype.int,
23
- pd.UInt8Dtype(): Dtype.int,
24
- np.dtype('int16'): Dtype.int,
25
- pd.Int16Dtype(): Dtype.int,
26
- np.dtype('int32'): Dtype.int,
27
- pd.Int32Dtype(): Dtype.int,
28
- np.dtype('int64'): Dtype.int,
29
- pd.Int64Dtype(): Dtype.int,
30
- np.dtype('float32'): Dtype.float,
31
- pd.Float32Dtype(): Dtype.float,
32
- np.dtype('float64'): Dtype.float,
33
- pd.Float64Dtype(): Dtype.float,
34
- np.dtype('object'): Dtype.string,
35
- pd.StringDtype(storage='python'): Dtype.string,
36
- pd.StringDtype(storage='pyarrow'): Dtype.string,
37
- pa.string(): Dtype.string,
38
- pa.binary(): Dtype.binary,
39
- np.dtype('datetime64[ns]'): Dtype.date,
40
- np.dtype('timedelta64[ns]'): Dtype.timedelta,
41
- pa.list_(pa.float32()): Dtype.floatlist,
42
- pa.list_(pa.int64()): Dtype.intlist,
43
- pa.list_(pa.string()): Dtype.stringlist,
44
- }
45
-
46
-
47
- def to_dtype(ser: pd.Series) -> Dtype:
48
- """Extracts the :class:`Dtype` from a :class:`pandas.Series`.
49
-
50
- Args:
51
- ser: A :class:`pandas.Series` to analyze.
52
-
53
- Returns:
54
- The data type.
55
- """
56
- if pd.api.types.is_datetime64_any_dtype(ser.dtype):
57
- return Dtype.date
58
-
59
- if isinstance(ser.dtype, pd.CategoricalDtype):
60
- return Dtype.string
61
-
62
- if pd.api.types.is_object_dtype(ser.dtype):
63
- index = ser.iloc[:1000].first_valid_index()
64
- if index is not None and pd.api.types.is_list_like(ser[index]):
65
- pos = ser.index.get_loc(index)
66
- assert isinstance(pos, int)
67
- ser = ser.iloc[pos:pos + 1000].dropna()
68
-
69
- if not ser.map(pd.api.types.is_list_like).all():
70
- raise ValueError("Data contains a mix of list-like and "
71
- "non-list-like values")
72
-
73
- ser = ser[ser.map(lambda x: not isinstance(x, list) or len(x) > 0)]
74
-
75
- dtypes = ser.apply(lambda x: PANDAS_TO_DTYPE.get(
76
- np.array(x).dtype, Dtype.string)).unique().tolist()
77
-
78
- invalid_dtypes = set(dtypes) - {
79
- Dtype.string,
80
- Dtype.int,
81
- Dtype.float,
82
- }
83
- if len(invalid_dtypes) > 0:
84
- raise ValueError(f"Data contains unsupported list data types: "
85
- f"{list(invalid_dtypes)}")
86
-
87
- if Dtype.string in dtypes:
88
- return Dtype.stringlist
89
-
90
- if dtypes == [Dtype.int]:
91
- return Dtype.intlist
92
-
93
- return Dtype.floatlist
94
-
95
- if ser.dtype not in PANDAS_TO_DTYPE:
96
- raise ValueError(f"Unsupported data type '{ser.dtype}'")
97
-
98
- return PANDAS_TO_DTYPE[ser.dtype]
99
-
100
-
101
- def infer_stype(ser: pd.Series, column_name: str, dtype: Dtype) -> Stype:
102
- r"""Infers the semantic type of a column.
103
-
104
- Args:
105
- ser: A :class:`pandas.Series` to analyze.
106
- column_name: The name of the column (used for pattern matching).
107
- dtype: The data type.
108
-
109
- Returns:
110
- The semantic type.
111
- """
112
- if contains_id(ser, column_name, dtype):
113
- return Stype.ID
114
-
115
- if contains_timestamp(ser, column_name, dtype):
116
- return Stype.timestamp
117
-
118
- if contains_multicategorical(ser, column_name, dtype):
119
- return Stype.multicategorical
120
-
121
- if contains_categorical(ser, column_name, dtype):
122
- return Stype.categorical
123
-
124
- return dtype.default_stype
125
-
126
-
127
- def detect_primary_key(
128
- table_name: str,
129
- df: pd.DataFrame,
130
- candidates: list[str],
131
- ) -> Optional[str]:
132
- r"""Auto-detect potential primary key column.
133
-
134
- Args:
135
- table_name: The table name.
136
- df: The pandas DataFrame to analyze
137
- candidates: A list of potential candidates.
138
-
139
- Returns:
140
- The name of the detected primary key, or ``None`` if not found.
141
- """
142
- # A list of (potentially modified) table names that are eligible to match
143
- # with a primary key, i.e.:
144
- # - UserInfo -> User
145
- # - snakecase <-> camelcase
146
- # - camelcase <-> snakecase
147
- # - plural <-> singular (users -> user, eligibilities -> eligibility)
148
- # - verb -> noun (qualifying -> qualify)
149
- _table_names = {table_name}
150
- if table_name.lower().endswith('_info'):
151
- _table_names.add(table_name[:-5])
152
- elif table_name.lower().endswith('info'):
153
- _table_names.add(table_name[:-4])
154
-
155
- table_names = set()
156
- for _table_name in _table_names:
157
- table_names.add(_table_name.lower())
158
- snakecase = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', _table_name)
159
- snakecase = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', snakecase)
160
- table_names.add(snakecase.lower())
161
- camelcase = _table_name.replace('_', '')
162
- table_names.add(camelcase.lower())
163
- if _table_name.lower().endswith('s'):
164
- table_names.add(_table_name.lower()[:-1])
165
- table_names.add(snakecase.lower()[:-1])
166
- table_names.add(camelcase.lower()[:-1])
167
- else:
168
- table_names.add(_table_name.lower() + 's')
169
- table_names.add(snakecase.lower() + 's')
170
- table_names.add(camelcase.lower() + 's')
171
- if _table_name.lower().endswith('ies'):
172
- table_names.add(_table_name.lower()[:-3] + 'y')
173
- table_names.add(snakecase.lower()[:-3] + 'y')
174
- table_names.add(camelcase.lower()[:-3] + 'y')
175
- elif _table_name.lower().endswith('y'):
176
- table_names.add(_table_name.lower()[:-1] + 'ies')
177
- table_names.add(snakecase.lower()[:-1] + 'ies')
178
- table_names.add(camelcase.lower()[:-1] + 'ies')
179
- if _table_name.lower().endswith('ing'):
180
- table_names.add(_table_name.lower()[:-3])
181
- table_names.add(snakecase.lower()[:-3])
182
- table_names.add(camelcase.lower()[:-3])
183
-
184
- scores: list[tuple[str, int]] = []
185
- for col_name in candidates:
186
- col_name_lower = col_name.lower()
187
-
188
- score = 0
189
-
190
- if col_name_lower == 'id':
191
- score += 4
192
-
193
- for table_name_lower in table_names:
194
-
195
- if col_name_lower == table_name_lower:
196
- score += 4 # USER -> USER
197
- break
198
-
199
- for suffix in ['id', 'hash', 'key', 'code', 'uuid']:
200
- if not col_name_lower.endswith(suffix):
201
- continue
202
-
203
- if col_name_lower == f'{table_name_lower}_{suffix}':
204
- score += 5 # USER -> USER_ID
205
- break
206
-
207
- if col_name_lower == f'{table_name_lower}{suffix}':
208
- score += 5 # User -> UserId
209
- break
210
-
211
- if col_name_lower.endswith(f'{table_name_lower}_{suffix}'):
212
- score += 2
213
-
214
- if col_name_lower.endswith(f'{table_name_lower}{suffix}'):
215
- score += 2
216
-
217
- # `rel-bench` hard-coding :(
218
- if table_name == 'studies' and col_name == 'nct_id':
219
- score += 1
220
-
221
- ser = df[col_name].iloc[:1_000_000]
222
- score += 3 * (ser.nunique() / len(ser))
223
-
224
- scores.append((col_name, score))
225
-
226
- scores = [x for x in scores if x[-1] >= 4]
227
- scores.sort(key=lambda x: x[-1], reverse=True)
228
-
229
- if len(scores) == 0:
230
- return None
231
-
232
- if len(scores) == 1:
233
- return scores[0][0]
234
-
235
- # In case of multiple candidates, only return one if its score is unique:
236
- if scores[0][1] != scores[1][1]:
237
- return scores[0][0]
238
-
239
- max_score = max(scores, key=lambda x: x[1])
240
- candidates = [col_name for col_name, score in scores if score == max_score]
241
- warnings.warn(f"Found multiple potential primary keys in table "
242
- f"'{table_name}': {candidates}. Please specify the primary "
243
- f"key for this table manually.")
244
-
245
- return None
246
-
247
-
248
- def detect_time_column(
249
- df: pd.DataFrame,
250
- candidates: list[str],
251
- ) -> Optional[str]:
252
- r"""Auto-detect potential time column.
253
-
254
- Args:
255
- df: The pandas DataFrame to analyze
256
- candidates: A list of potential candidates.
257
-
258
- Returns:
259
- The name of the detected time column, or ``None`` if not found.
260
- """
261
- candidates = [ # Exclude all candidates with `*last*` in column names:
262
- col_name for col_name in candidates
263
- if not re.search(r'(^|_)last(_|$)', col_name, re.IGNORECASE)
264
- ]
265
-
266
- if len(candidates) == 0:
267
- return None
268
-
269
- if len(candidates) == 1:
270
- return candidates[0]
271
-
272
- # If there exists a dedicated `create*` column, use it as time column:
273
- create_candidates = [
274
- candidate for candidate in candidates
275
- if candidate.lower().startswith('create')
276
- ]
277
- if len(create_candidates) == 1:
278
- return create_candidates[0]
279
- if len(create_candidates) > 1:
280
- candidates = create_candidates
281
-
282
- # Find the most optimal time column. Usually, it is the one pointing to
283
- # the oldest timestamps:
284
- with warnings.catch_warnings():
285
- warnings.filterwarnings('ignore', message='Could not infer format')
286
- min_timestamp_dict = {
287
- key: pd.to_datetime(df[key].iloc[:10_000], 'coerce')
288
- for key in candidates
289
- }
290
- min_timestamp_dict = {
291
- key: value.min().tz_localize(None)
292
- for key, value in min_timestamp_dict.items()
293
- }
294
- min_timestamp_dict = {
295
- key: value
296
- for key, value in min_timestamp_dict.items() if not pd.isna(value)
297
- }
298
-
299
- if len(min_timestamp_dict) == 0:
300
- return None
301
-
302
- return min(min_timestamp_dict, key=min_timestamp_dict.get) # type: ignore
303
-
304
-
305
- PUNCTUATION = re.compile(r"[\'\"\.,\(\)\!\?\;\:]")
306
- MULTISPACE = re.compile(r"\s+")
307
-
308
-
309
- def normalize_text(
310
- ser: pd.Series,
311
- max_words: Optional[int] = 50,
312
- ) -> pd.Series:
313
- r"""Normalizes text into a list of lower-case words.
314
-
315
- Args:
316
- ser: The :class:`pandas.Series` to normalize.
317
- max_words: The maximum number of words to return.
318
- This will auto-shrink any large text column to avoid blowing up
319
- context size.
320
- """
321
- if len(ser) == 0 or pd.api.types.is_list_like(ser.iloc[0]):
322
- return ser
323
-
324
- def normalize_fn(line: str) -> list[str]:
325
- line = PUNCTUATION.sub(" ", line)
326
- line = re.sub(r"<br\s*/?>", " ", line) # Handle <br /> or <br>
327
- line = MULTISPACE.sub(" ", line)
328
- words = line.split()
329
- if max_words is not None:
330
- words = words[:max_words]
331
- return words
332
-
333
- ser = ser.fillna('').astype(str)
334
-
335
- if max_words is not None:
336
- # We estimate the number of words as 5 characters + 1 space in an
337
- # English text on average. We need this pre-filter here, as word
338
- # splitting on a giant text can be very expensive:
339
- ser = ser.str[:6 * max_words]
340
-
341
- ser = ser.str.lower()
342
- ser = ser.map(normalize_fn)
343
-
344
- return ser