batch-analytics 0.3.6__tar.gz → 0.3.13__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.
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/PKG-INFO +1 -1
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/pyproject.toml +1 -1
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/__init__.py +9 -1
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/t_test.py +114 -17
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/config.py +9 -2
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/extract.py +49 -2
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/job_runner.py +2 -2
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/transform.py +120 -18
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/PKG-INFO +1 -1
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/README.md +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/setup.cfg +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/__main__.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/__init__.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/correlation.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/linear_regression.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/pca_clustering.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/log.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/modules.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/output/__init__.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/output/base.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/output/clickhouse.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/output/local.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/output/s3.py +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/SOURCES.txt +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/dependency_links.txt +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/entry_points.txt +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/requires.txt +0 -0
- {batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/top_level.txt +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "batch-analytics"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.13"
|
|
8
8
|
description = "PySpark batch analytics: Extract, Transform, Stage, and analytical modules (linear regression, correlation, PCA, t-test)."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -13,8 +13,14 @@ Analytics modules:
|
|
|
13
13
|
"""
|
|
14
14
|
|
|
15
15
|
from .config import BatchAnalyticsConfig, SparkK8sConfig
|
|
16
|
-
from .extract import
|
|
16
|
+
from .extract import (
|
|
17
|
+
extract_all,
|
|
18
|
+
extract_table,
|
|
19
|
+
extract_unified,
|
|
20
|
+
parse_extract_filter_values,
|
|
21
|
+
)
|
|
17
22
|
from .transform import (
|
|
23
|
+
expand_kv_blob_column,
|
|
18
24
|
extract_anchor_id,
|
|
19
25
|
load_staged,
|
|
20
26
|
remove_duplicates,
|
|
@@ -28,10 +34,12 @@ from .job_runner import run_pipeline, create_spark_session
|
|
|
28
34
|
__all__ = [
|
|
29
35
|
"BatchAnalyticsConfig",
|
|
30
36
|
"SparkK8sConfig",
|
|
37
|
+
"expand_kv_blob_column",
|
|
31
38
|
"extract_anchor_id",
|
|
32
39
|
"extract_all",
|
|
33
40
|
"extract_table",
|
|
34
41
|
"extract_unified",
|
|
42
|
+
"parse_extract_filter_values",
|
|
35
43
|
"remove_duplicates",
|
|
36
44
|
"stage_to_clickhouse",
|
|
37
45
|
"transform",
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"""
|
|
2
|
-
Module 4: T-test
|
|
2
|
+
Module 4: T-test and one-way ANOVA for comparing means across groups.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
import logging
|
|
6
|
-
from typing import Any, Dict
|
|
6
|
+
from typing import Any, Dict, List
|
|
7
7
|
|
|
8
8
|
from pyspark.sql import DataFrame, SparkSession
|
|
9
9
|
from pyspark.sql.functions import col, avg, stddev, count
|
|
@@ -20,18 +20,17 @@ def run_t_test(
|
|
|
20
20
|
config: BatchAnalyticsConfig,
|
|
21
21
|
) -> Dict[str, Any]:
|
|
22
22
|
"""
|
|
23
|
-
|
|
23
|
+
Compare means across groups or two numeric columns.
|
|
24
24
|
|
|
25
|
-
Supports
|
|
26
|
-
1. Value + group: one numeric column, one categorical column
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
25
|
+
Supports:
|
|
26
|
+
1. Value + group: one numeric column, one categorical column.
|
|
27
|
+
- **2 groups:** Welch's t-test (unequal variances).
|
|
28
|
+
- **3+ groups:** one-way ANOVA (F-test on equal means).
|
|
29
|
+
2. Two columns: two numeric columns, Welch t-test on their column means.
|
|
30
30
|
|
|
31
31
|
Returns:
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
- t_statistic, p_value, difference (mean_a - mean_b)
|
|
32
|
+
For Welch: ``group_a``, ``group_b``, ``t_statistic``, ``p_value``, ``test`` = ``\"Welch\"``.
|
|
33
|
+
For ANOVA: ``groups``, ``f_statistic``, ``p_value``, ``test`` = ``\"one_way_anova\"``, SS/df.
|
|
35
34
|
"""
|
|
36
35
|
value_col = (config.analytics.ttest_value_column or "").strip()
|
|
37
36
|
group_col = (config.analytics.ttest_group_column or "").strip()
|
|
@@ -46,7 +45,7 @@ def run_t_test(
|
|
|
46
45
|
if col_a and col_b and col_a in df.columns and col_b in df.columns:
|
|
47
46
|
return _run_t_test_two_columns(df, col_a, col_b)
|
|
48
47
|
|
|
49
|
-
# Fallback:
|
|
48
|
+
# Fallback: first numeric + string-like column with at least 2 distinct groups
|
|
50
49
|
numeric_cols = [
|
|
51
50
|
f.name for f in df.schema.fields
|
|
52
51
|
if "double" in str(f.dataType).lower()
|
|
@@ -60,8 +59,10 @@ def run_t_test(
|
|
|
60
59
|
for nc in numeric_cols:
|
|
61
60
|
for sc in string_cols:
|
|
62
61
|
distinct = df.select(sc).distinct().count()
|
|
63
|
-
if distinct
|
|
64
|
-
logger.info(
|
|
62
|
+
if distinct >= 2:
|
|
63
|
+
logger.info(
|
|
64
|
+
"Auto-selected value=%s, group=%s (%d groups)", nc, sc, distinct
|
|
65
|
+
)
|
|
65
66
|
return _run_t_test_by_group(df, nc, sc)
|
|
66
67
|
|
|
67
68
|
raise ValueError(
|
|
@@ -76,7 +77,7 @@ def _run_t_test_by_group(
|
|
|
76
77
|
value_col: str,
|
|
77
78
|
group_col: str,
|
|
78
79
|
) -> Dict[str, Any]:
|
|
79
|
-
"""
|
|
80
|
+
"""Compare mean of value_col across groups: Welch (2 groups) or one-way ANOVA (3+)."""
|
|
80
81
|
df_num = df.select(
|
|
81
82
|
col(value_col).cast(DoubleType()).alias("_val"),
|
|
82
83
|
col(group_col).cast("string").alias("_grp"),
|
|
@@ -92,11 +93,15 @@ def _run_t_test_by_group(
|
|
|
92
93
|
.collect()
|
|
93
94
|
)
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
k = len(stats)
|
|
97
|
+
if k < 2:
|
|
96
98
|
raise ValueError(
|
|
97
|
-
f"
|
|
99
|
+
f"Need at least 2 groups in {group_col} for comparison. Found: {[r['_grp'] for r in stats]}"
|
|
98
100
|
)
|
|
99
101
|
|
|
102
|
+
if k > 2:
|
|
103
|
+
return _run_one_way_anova(stats, value_col, group_col)
|
|
104
|
+
|
|
100
105
|
r0, r1 = stats[0], stats[1]
|
|
101
106
|
return _compute_t_test_result(
|
|
102
107
|
group_a=r0["_grp"],
|
|
@@ -110,6 +115,98 @@ def _run_t_test_by_group(
|
|
|
110
115
|
)
|
|
111
116
|
|
|
112
117
|
|
|
118
|
+
def _run_one_way_anova(
|
|
119
|
+
stats_rows: List[Any],
|
|
120
|
+
value_col: str,
|
|
121
|
+
group_col: str,
|
|
122
|
+
) -> Dict[str, Any]:
|
|
123
|
+
"""
|
|
124
|
+
One-way ANOVA from per-group mean, sample stddev, and n (Spark ``stddev`` uses ddof=1).
|
|
125
|
+
|
|
126
|
+
SS_within = sum_i (n_i - 1) * s_i^2
|
|
127
|
+
SS_between = sum_i n_i * (mean_i - grand_mean)^2
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
from scipy import stats as scipy_stats
|
|
131
|
+
except ImportError:
|
|
132
|
+
raise ImportError("ANOVA requires scipy. Install with: pip install scipy")
|
|
133
|
+
|
|
134
|
+
groups: List[Dict[str, Any]] = []
|
|
135
|
+
for r in stats_rows:
|
|
136
|
+
name = r["_grp"]
|
|
137
|
+
mean = float(r["mean"])
|
|
138
|
+
std_raw = r["std"]
|
|
139
|
+
std = 0.0 if std_raw is None else float(std_raw)
|
|
140
|
+
n = int(r["n"])
|
|
141
|
+
groups.append(
|
|
142
|
+
{"name": name, "mean": mean, "std": std, "n": n}
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
k = len(groups)
|
|
146
|
+
N = sum(g["n"] for g in groups)
|
|
147
|
+
if N <= k:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"ANOVA needs more observations than groups (N={N}, k={k})"
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
grand_mean = sum(g["n"] * g["mean"] for g in groups) / N
|
|
153
|
+
ss_between = sum(g["n"] * (g["mean"] - grand_mean) ** 2 for g in groups)
|
|
154
|
+
ss_within = sum(
|
|
155
|
+
(g["n"] - 1) * (g["std"] ** 2) for g in groups if g["n"] > 1
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
df_between = k - 1
|
|
159
|
+
df_within = N - k
|
|
160
|
+
if df_within <= 0:
|
|
161
|
+
raise ValueError(
|
|
162
|
+
f"ANOVA: df_within must be positive (N={N}, k={k})"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
ms_between = ss_between / df_between
|
|
166
|
+
ms_within = ss_within / df_within if df_within > 0 else 0.0
|
|
167
|
+
|
|
168
|
+
if ms_within <= 0.0:
|
|
169
|
+
if ms_between <= 0.0:
|
|
170
|
+
f_stat = 0.0
|
|
171
|
+
p_value = 1.0
|
|
172
|
+
else:
|
|
173
|
+
f_stat = float("inf")
|
|
174
|
+
p_value = 0.0
|
|
175
|
+
else:
|
|
176
|
+
f_stat = ms_between / ms_within
|
|
177
|
+
p_value = float(scipy_stats.f.sf(f_stat, df_between, df_within))
|
|
178
|
+
|
|
179
|
+
out: Dict[str, Any] = {
|
|
180
|
+
"test": "one_way_anova",
|
|
181
|
+
"value_column": value_col,
|
|
182
|
+
"group_column": group_col,
|
|
183
|
+
"k_groups": k,
|
|
184
|
+
"n_total": N,
|
|
185
|
+
"grand_mean": grand_mean,
|
|
186
|
+
"f_statistic": f_stat,
|
|
187
|
+
"p_value": p_value,
|
|
188
|
+
"df_between": df_between,
|
|
189
|
+
"df_within": df_within,
|
|
190
|
+
"ss_between": ss_between,
|
|
191
|
+
"ss_within": ss_within,
|
|
192
|
+
"ms_between": ms_between,
|
|
193
|
+
"ms_within": ms_within,
|
|
194
|
+
"groups": [
|
|
195
|
+
{
|
|
196
|
+
"name": g["name"],
|
|
197
|
+
"mean": g["mean"],
|
|
198
|
+
"std": g["std"],
|
|
199
|
+
"n": g["n"],
|
|
200
|
+
}
|
|
201
|
+
for g in sorted(groups, key=lambda x: str(x["name"]))
|
|
202
|
+
],
|
|
203
|
+
}
|
|
204
|
+
if f_stat == float("inf"):
|
|
205
|
+
out["f_statistic"] = None
|
|
206
|
+
out["f_statistic_note"] = "infinite (MS_within == 0, reject equal means if SS_between > 0)"
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
113
210
|
def _run_t_test_two_columns(df: DataFrame, col_a: str, col_b: str) -> Dict[str, Any]:
|
|
114
211
|
"""T-test: compare means of two numeric columns."""
|
|
115
212
|
df_num = df.select(
|
|
@@ -55,13 +55,18 @@ class ExtractConfig:
|
|
|
55
55
|
use_native_connector: bool = os.environ.get(
|
|
56
56
|
"BATCH_USE_NATIVE_CONNECTOR", "false"
|
|
57
57
|
).lower() == "true"
|
|
58
|
+
# Optional WHERE col IN (...) after read. Empty filter_column = no filter (full table).
|
|
59
|
+
# filter_values: comma-separated list, or JSON array e.g. ["a","b"] for values containing commas.
|
|
60
|
+
filter_column: str = os.environ.get("BATCH_EXTRACT_FILTER_COLUMN", "").strip()
|
|
61
|
+
filter_values: str = os.environ.get("BATCH_EXTRACT_FILTER_VALUES", "").strip()
|
|
58
62
|
|
|
59
63
|
|
|
60
64
|
@dataclass
|
|
61
65
|
class TransformConfig:
|
|
62
66
|
"""Transform stage configuration."""
|
|
63
67
|
|
|
64
|
-
#
|
|
68
|
+
# Order: extract anchor_id from add_dimension(s) column, then dedupe by these keys.
|
|
69
|
+
# Deduplication keys (comma-separated). Empty = dropDuplicates() on full row (all columns).
|
|
65
70
|
dedup_columns: str = os.environ.get("BATCH_DEDUP_COLUMNS", "")
|
|
66
71
|
# Staging output path (local or S3)
|
|
67
72
|
staging_path: str = os.environ.get(
|
|
@@ -73,8 +78,10 @@ class TransformConfig:
|
|
|
73
78
|
staging_format: str = os.environ.get("BATCH_STAGING_FORMAT", "clickhouse")
|
|
74
79
|
# Staging table name in ClickHouse (when format=clickhouse)
|
|
75
80
|
staging_table: str = os.environ.get("BATCH_STAGING_TABLE", "analytics_staging")
|
|
76
|
-
#
|
|
81
|
+
# Source column holding a JSON object or Python dict string; every top-level key becomes a new String column
|
|
82
|
+
# (see transform.expand_kv_blob_column). Example: add_dimensions {'anchor_id':'...','lot':'A1'}
|
|
77
83
|
add_dimension_column: str = os.environ.get("BATCH_ADD_DIMENSION_COLUMN", "add_dimension")
|
|
84
|
+
# Legacy: no longer used; output column names match JSON keys (e.g. anchor_id). Kept for env compatibility.
|
|
78
85
|
anchor_id_column: str = os.environ.get("BATCH_ANCHOR_ID_COLUMN", "anchor_id")
|
|
79
86
|
|
|
80
87
|
|
|
@@ -2,17 +2,63 @@
|
|
|
2
2
|
Extract stage: Load data from ClickHouse using Spark ClickHouse connector or JDBC.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
import logging
|
|
6
|
-
import os
|
|
7
7
|
from typing import Dict, List, Optional
|
|
8
8
|
|
|
9
9
|
from pyspark.sql import DataFrame, SparkSession
|
|
10
|
+
from pyspark.sql.functions import col
|
|
10
11
|
|
|
11
12
|
from .config import BatchAnalyticsConfig
|
|
12
13
|
|
|
13
14
|
logger = logging.getLogger(__name__)
|
|
14
15
|
|
|
15
16
|
|
|
17
|
+
def parse_extract_filter_values(raw: str) -> List[str]:
|
|
18
|
+
"""
|
|
19
|
+
Parse BATCH_EXTRACT_FILTER_VALUES: comma-separated tokens, or JSON array string.
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
a,b,c -> ["a","b","c"]
|
|
23
|
+
["GP/A","GP/B"] -> JSON list (values may contain commas)
|
|
24
|
+
"""
|
|
25
|
+
text = (raw or "").strip()
|
|
26
|
+
if not text:
|
|
27
|
+
return []
|
|
28
|
+
if text.startswith("["):
|
|
29
|
+
try:
|
|
30
|
+
data = json.loads(text)
|
|
31
|
+
if isinstance(data, list):
|
|
32
|
+
out = [str(x).strip() for x in data if str(x).strip()]
|
|
33
|
+
return out
|
|
34
|
+
except json.JSONDecodeError:
|
|
35
|
+
logger.warning("BATCH_EXTRACT_FILTER_VALUES looks like JSON but failed to parse; using comma split")
|
|
36
|
+
return [p.strip() for p in text.split(",") if p.strip()]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _apply_extract_filter(df: DataFrame, config: BatchAnalyticsConfig) -> DataFrame:
|
|
40
|
+
"""Apply col IN (values) when filter_column is set; empty column = no filter."""
|
|
41
|
+
col_name = (config.extract.filter_column or "").strip()
|
|
42
|
+
if not col_name:
|
|
43
|
+
return df
|
|
44
|
+
if col_name not in df.columns:
|
|
45
|
+
logger.warning(
|
|
46
|
+
"BATCH_EXTRACT_FILTER_COLUMN=%r not in extracted columns %s; skipping filter",
|
|
47
|
+
col_name,
|
|
48
|
+
df.columns,
|
|
49
|
+
)
|
|
50
|
+
return df
|
|
51
|
+
values = parse_extract_filter_values(config.extract.filter_values)
|
|
52
|
+
if not values:
|
|
53
|
+
logger.warning(
|
|
54
|
+
"BATCH_EXTRACT_FILTER_COLUMN=%r set but BATCH_EXTRACT_FILTER_VALUES is empty; skipping IN filter",
|
|
55
|
+
col_name,
|
|
56
|
+
)
|
|
57
|
+
return df
|
|
58
|
+
filtered = df.filter(col(col_name).isin(values))
|
|
59
|
+
return filtered
|
|
60
|
+
|
|
61
|
+
|
|
16
62
|
def _read_via_format(spark: SparkSession, cfg: BatchAnalyticsConfig, table: str) -> Optional[DataFrame]:
|
|
17
63
|
"""
|
|
18
64
|
Read from ClickHouse using the native format API (clickhouse-spark-runtime).
|
|
@@ -60,12 +106,13 @@ def extract_table(
|
|
|
60
106
|
Uses native connector if configured, otherwise JDBC.
|
|
61
107
|
"""
|
|
62
108
|
if config.extract.use_native_connector:
|
|
63
|
-
df =
|
|
109
|
+
df = _read_via_format(spark, config, table)
|
|
64
110
|
if df is None:
|
|
65
111
|
df = _read_via_jdbc(spark, config, table)
|
|
66
112
|
else:
|
|
67
113
|
df = _read_via_jdbc(spark, config, table)
|
|
68
114
|
|
|
115
|
+
df = _apply_extract_filter(df, config)
|
|
69
116
|
logger.info("Extracted table %s: %d rows", table, df.count())
|
|
70
117
|
return df
|
|
71
118
|
|
|
@@ -270,9 +270,9 @@ def run_pipeline(
|
|
|
270
270
|
else:
|
|
271
271
|
df_transformed = df_raw # df_raw already loaded from staged when not run_extract
|
|
272
272
|
if run_extract and run_analytics:
|
|
273
|
-
from .transform import
|
|
273
|
+
from .transform import expand_kv_blob_column, remove_duplicates
|
|
274
274
|
|
|
275
|
-
df_transformed =
|
|
275
|
+
df_transformed = expand_kv_blob_column(df_raw, config)
|
|
276
276
|
dedup_cols = (
|
|
277
277
|
[c.strip() for c in config.transform.dedup_columns.split(",") if c.strip()]
|
|
278
278
|
if config.transform.dedup_columns
|
|
@@ -1,42 +1,143 @@
|
|
|
1
1
|
"""
|
|
2
|
-
Transform stage: Clean data (remove duplicates),
|
|
2
|
+
Transform stage: Clean data (remove duplicates), expand JSON/KV blob column, and stage.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
import ast
|
|
6
|
+
import json
|
|
5
7
|
import logging
|
|
6
8
|
import os
|
|
7
|
-
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any, Dict, List, Optional, Sequence, Set
|
|
8
11
|
|
|
9
12
|
from pyspark.sql import DataFrame, SparkSession
|
|
10
|
-
from pyspark.sql.functions import
|
|
13
|
+
from pyspark.sql.functions import col, explode, map_keys, udf
|
|
14
|
+
from pyspark.sql.types import MapType, StringType
|
|
11
15
|
|
|
12
16
|
from .config import BatchAnalyticsConfig
|
|
13
17
|
|
|
14
18
|
logger = logging.getLogger(__name__)
|
|
15
19
|
|
|
16
20
|
|
|
17
|
-
def
|
|
21
|
+
def _stringify_leaf(v: Any) -> str:
|
|
22
|
+
if v is None:
|
|
23
|
+
return ""
|
|
24
|
+
if isinstance(v, (dict, list)):
|
|
25
|
+
return json.dumps(v, separators=(",", ":"))
|
|
26
|
+
return str(v)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_blob_to_strmap(s: Any) -> Dict[str, str]:
|
|
30
|
+
"""
|
|
31
|
+
Parse a cell value into a flat string map (top-level keys only).
|
|
32
|
+
|
|
33
|
+
Accepts standard JSON objects or Python repr dicts (e.g. single-quoted).
|
|
34
|
+
Non-dict / unparsable input yields an empty map.
|
|
35
|
+
"""
|
|
36
|
+
if s is None:
|
|
37
|
+
return {}
|
|
38
|
+
text = str(s).strip()
|
|
39
|
+
if not text:
|
|
40
|
+
return {}
|
|
41
|
+
obj: Any = None
|
|
42
|
+
try:
|
|
43
|
+
obj = json.loads(text)
|
|
44
|
+
except json.JSONDecodeError:
|
|
45
|
+
pass
|
|
46
|
+
if obj is None:
|
|
47
|
+
try:
|
|
48
|
+
obj = ast.literal_eval(text)
|
|
49
|
+
except (ValueError, SyntaxError, MemoryError):
|
|
50
|
+
return {}
|
|
51
|
+
if not isinstance(obj, dict):
|
|
52
|
+
return {}
|
|
53
|
+
out: Dict[str, str] = {}
|
|
54
|
+
for k, v in obj.items():
|
|
55
|
+
key = str(k).strip()
|
|
56
|
+
if not key:
|
|
57
|
+
continue
|
|
58
|
+
out[key] = _stringify_leaf(v)
|
|
59
|
+
return out
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _spark_safe_base_name(key: str) -> str:
|
|
63
|
+
"""Sanitize JSON key to a usable Spark column name."""
|
|
64
|
+
s = re.sub(r"[^0-9a-zA-Z_]", "_", key.strip())
|
|
65
|
+
s = re.sub(r"_+", "_", s).strip("_")
|
|
66
|
+
if not s:
|
|
67
|
+
return "kv_key"
|
|
68
|
+
if s[0].isdigit():
|
|
69
|
+
s = "c_" + s
|
|
70
|
+
return s
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _unique_column_name(base: str, used: Set[str]) -> str:
|
|
74
|
+
name = base
|
|
75
|
+
n = 1
|
|
76
|
+
while name in used:
|
|
77
|
+
n += 1
|
|
78
|
+
name = f"{base}_{n}"
|
|
79
|
+
used.add(name)
|
|
80
|
+
return name
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def expand_kv_blob_column(
|
|
18
84
|
df: DataFrame,
|
|
19
85
|
config: BatchAnalyticsConfig,
|
|
20
86
|
) -> DataFrame:
|
|
21
87
|
"""
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
88
|
+
Parse the configured blob column into top-level key/value pairs and add one String column per key.
|
|
89
|
+
|
|
90
|
+
No per-key user configuration: every distinct key observed in the column (across the dataset)
|
|
91
|
+
becomes a column; values are strings (nested dict/list serialized as JSON). Empty / null cells
|
|
92
|
+
yield nulls in those columns.
|
|
93
|
+
|
|
94
|
+
Source column: ``config.transform.add_dimension_column`` (env ``BATCH_ADD_DIMENSION_COLUMN``).
|
|
25
95
|
"""
|
|
26
96
|
col_name = config.transform.add_dimension_column
|
|
27
|
-
out_col = config.transform.anchor_id_column
|
|
28
|
-
|
|
29
97
|
if col_name not in df.columns:
|
|
30
|
-
logger.debug("
|
|
98
|
+
logger.debug("KV blob column %r not found, skipping expansion", col_name)
|
|
31
99
|
return df
|
|
32
100
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
101
|
+
parse_udf = udf(parse_blob_to_strmap, MapType(StringType(), StringType()))
|
|
102
|
+
with_map = df.withColumn("_kv_blob_map", parse_udf(col(col_name)))
|
|
103
|
+
|
|
104
|
+
key_rows = (
|
|
105
|
+
with_map.select(explode(map_keys(col("_kv_blob_map"))).alias("_k"))
|
|
106
|
+
.where(col("_k").isNotNull())
|
|
107
|
+
.distinct()
|
|
108
|
+
.collect()
|
|
109
|
+
)
|
|
110
|
+
all_keys: List[str] = sorted({str(r._k).strip() for r in key_rows if r._k and str(r._k).strip()})
|
|
111
|
+
|
|
112
|
+
if not all_keys:
|
|
113
|
+
logger.info("No keys found in KV blob column %r; dropping temporary map only", col_name)
|
|
114
|
+
return with_map.drop("_kv_blob_map")
|
|
115
|
+
|
|
116
|
+
used: Set[str] = set(with_map.columns)
|
|
117
|
+
out = with_map
|
|
118
|
+
added: List[str] = []
|
|
119
|
+
for k in all_keys:
|
|
120
|
+
base = _spark_safe_base_name(k)
|
|
121
|
+
target = _unique_column_name(base, used)
|
|
122
|
+
added.append(target)
|
|
123
|
+
out = out.withColumn(target, col("_kv_blob_map").getItem(k))
|
|
124
|
+
|
|
125
|
+
out = out.drop("_kv_blob_map")
|
|
126
|
+
logger.info(
|
|
127
|
+
"Expanded KV blob column %r into %d columns: %s",
|
|
128
|
+
col_name,
|
|
129
|
+
len(added),
|
|
130
|
+
", ".join(added),
|
|
131
|
+
)
|
|
132
|
+
return out
|
|
37
133
|
|
|
38
|
-
|
|
39
|
-
|
|
134
|
+
|
|
135
|
+
def extract_anchor_id(
|
|
136
|
+
df: DataFrame,
|
|
137
|
+
config: BatchAnalyticsConfig,
|
|
138
|
+
) -> DataFrame:
|
|
139
|
+
"""Backward-compatible name: expands all keys from the blob column (not only ``anchor_id``)."""
|
|
140
|
+
return expand_kv_blob_column(df, config)
|
|
40
141
|
|
|
41
142
|
|
|
42
143
|
def remove_duplicates(
|
|
@@ -69,10 +170,11 @@ def transform(
|
|
|
69
170
|
config: BatchAnalyticsConfig,
|
|
70
171
|
) -> DataFrame:
|
|
71
172
|
"""
|
|
72
|
-
Apply transformation only:
|
|
173
|
+
Apply transformation only: (1) expand JSON/KV blob column into one column per top-level key,
|
|
174
|
+
(2) deduplicate by BATCH_DEDUP_COLUMNS if set, else by full row.
|
|
73
175
|
Does not write anywhere. Use stage_to_clickhouse() separately to persist.
|
|
74
176
|
"""
|
|
75
|
-
transformed =
|
|
177
|
+
transformed = expand_kv_blob_column(df, config)
|
|
76
178
|
dedup_cols = (
|
|
77
179
|
[c.strip() for c in config.transform.dedup_columns.split(",") if c.strip()]
|
|
78
180
|
if config.transform.dedup_columns
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/correlation.py
RENAMED
|
File without changes
|
{batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/linear_regression.py
RENAMED
|
File without changes
|
{batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics/analytics/pca_clustering.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{batch_analytics-0.3.6 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|