batch-analytics 0.3.7__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.7 → batch_analytics-0.3.13}/PKG-INFO +1 -1
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/pyproject.toml +1 -1
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/__init__.py +9 -1
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/config.py +9 -2
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/extract.py +49 -2
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/job_runner.py +2 -2
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/transform.py +120 -18
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/PKG-INFO +1 -1
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/README.md +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/setup.cfg +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/__main__.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/__init__.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/correlation.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/linear_regression.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/pca_clustering.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/t_test.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/log.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/modules.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/output/__init__.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/output/base.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/output/clickhouse.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/output/local.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/output/s3.py +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/SOURCES.txt +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/dependency_links.txt +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/entry_points.txt +0 -0
- {batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/requires.txt +0 -0
- {batch_analytics-0.3.7 → 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",
|
|
@@ -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.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/correlation.py
RENAMED
|
File without changes
|
{batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics/analytics/linear_regression.py
RENAMED
|
File without changes
|
{batch_analytics-0.3.7 → 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
|
|
File without changes
|
{batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{batch_analytics-0.3.7 → batch_analytics-0.3.13}/src/batch_analytics.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|