churnkit 0.75.0a1__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.
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/00_start_here.ipynb +647 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01_data_discovery.ipynb +1165 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_a_temporal_text_deep_dive.ipynb +961 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_temporal_deep_dive.ipynb +1690 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01b_temporal_quality.ipynb +679 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01c_temporal_patterns.ipynb +3305 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01d_event_aggregation.ipynb +1463 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02_column_deep_dive.ipynb +1430 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02a_text_columns_deep_dive.ipynb +854 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/03_quality_assessment.ipynb +1639 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/04_relationship_analysis.ipynb +1890 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/05_multi_dataset.ipynb +1457 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/06_feature_opportunities.ipynb +1624 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/07_modeling_readiness.ipynb +780 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/08_baseline_experiments.ipynb +979 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/09_business_alignment.ipynb +572 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/10_spec_generation.ipynb +1179 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/11_scoring_validation.ipynb +1418 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/12_view_documentation.ipynb +151 -0
- churnkit-0.75.0a1.dist-info/METADATA +229 -0
- churnkit-0.75.0a1.dist-info/RECORD +302 -0
- churnkit-0.75.0a1.dist-info/WHEEL +4 -0
- churnkit-0.75.0a1.dist-info/entry_points.txt +2 -0
- churnkit-0.75.0a1.dist-info/licenses/LICENSE +202 -0
- customer_retention/__init__.py +37 -0
- customer_retention/analysis/__init__.py +0 -0
- customer_retention/analysis/auto_explorer/__init__.py +62 -0
- customer_retention/analysis/auto_explorer/exploration_manager.py +470 -0
- customer_retention/analysis/auto_explorer/explorer.py +258 -0
- customer_retention/analysis/auto_explorer/findings.py +291 -0
- customer_retention/analysis/auto_explorer/layered_recommendations.py +485 -0
- customer_retention/analysis/auto_explorer/recommendation_builder.py +148 -0
- customer_retention/analysis/auto_explorer/recommendations.py +418 -0
- customer_retention/analysis/business/__init__.py +26 -0
- customer_retention/analysis/business/ab_test_designer.py +144 -0
- customer_retention/analysis/business/fairness_analyzer.py +166 -0
- customer_retention/analysis/business/intervention_matcher.py +121 -0
- customer_retention/analysis/business/report_generator.py +222 -0
- customer_retention/analysis/business/risk_profile.py +199 -0
- customer_retention/analysis/business/roi_analyzer.py +139 -0
- customer_retention/analysis/diagnostics/__init__.py +20 -0
- customer_retention/analysis/diagnostics/calibration_analyzer.py +133 -0
- customer_retention/analysis/diagnostics/cv_analyzer.py +144 -0
- customer_retention/analysis/diagnostics/error_analyzer.py +107 -0
- customer_retention/analysis/diagnostics/leakage_detector.py +394 -0
- customer_retention/analysis/diagnostics/noise_tester.py +140 -0
- customer_retention/analysis/diagnostics/overfitting_analyzer.py +190 -0
- customer_retention/analysis/diagnostics/segment_analyzer.py +122 -0
- customer_retention/analysis/discovery/__init__.py +8 -0
- customer_retention/analysis/discovery/config_generator.py +49 -0
- customer_retention/analysis/discovery/discovery_flow.py +19 -0
- customer_retention/analysis/discovery/type_inferencer.py +147 -0
- customer_retention/analysis/interpretability/__init__.py +13 -0
- customer_retention/analysis/interpretability/cohort_analyzer.py +185 -0
- customer_retention/analysis/interpretability/counterfactual.py +175 -0
- customer_retention/analysis/interpretability/individual_explainer.py +141 -0
- customer_retention/analysis/interpretability/pdp_generator.py +103 -0
- customer_retention/analysis/interpretability/shap_explainer.py +106 -0
- customer_retention/analysis/jupyter_save_hook.py +28 -0
- customer_retention/analysis/notebook_html_exporter.py +136 -0
- customer_retention/analysis/notebook_progress.py +60 -0
- customer_retention/analysis/plotly_preprocessor.py +154 -0
- customer_retention/analysis/recommendations/__init__.py +54 -0
- customer_retention/analysis/recommendations/base.py +158 -0
- customer_retention/analysis/recommendations/cleaning/__init__.py +11 -0
- customer_retention/analysis/recommendations/cleaning/consistency.py +107 -0
- customer_retention/analysis/recommendations/cleaning/deduplicate.py +94 -0
- customer_retention/analysis/recommendations/cleaning/impute.py +67 -0
- customer_retention/analysis/recommendations/cleaning/outlier.py +71 -0
- customer_retention/analysis/recommendations/datetime/__init__.py +3 -0
- customer_retention/analysis/recommendations/datetime/extract.py +149 -0
- customer_retention/analysis/recommendations/encoding/__init__.py +3 -0
- customer_retention/analysis/recommendations/encoding/categorical.py +114 -0
- customer_retention/analysis/recommendations/pipeline.py +74 -0
- customer_retention/analysis/recommendations/registry.py +76 -0
- customer_retention/analysis/recommendations/selection/__init__.py +3 -0
- customer_retention/analysis/recommendations/selection/drop_column.py +56 -0
- customer_retention/analysis/recommendations/transform/__init__.py +4 -0
- customer_retention/analysis/recommendations/transform/power.py +94 -0
- customer_retention/analysis/recommendations/transform/scale.py +112 -0
- customer_retention/analysis/visualization/__init__.py +15 -0
- customer_retention/analysis/visualization/chart_builder.py +2619 -0
- customer_retention/analysis/visualization/console.py +122 -0
- customer_retention/analysis/visualization/display.py +171 -0
- customer_retention/analysis/visualization/number_formatter.py +36 -0
- customer_retention/artifacts/__init__.py +3 -0
- customer_retention/artifacts/fit_artifact_registry.py +146 -0
- customer_retention/cli.py +93 -0
- customer_retention/core/__init__.py +0 -0
- customer_retention/core/compat/__init__.py +193 -0
- customer_retention/core/compat/detection.py +99 -0
- customer_retention/core/compat/ops.py +48 -0
- customer_retention/core/compat/pandas_backend.py +57 -0
- customer_retention/core/compat/spark_backend.py +75 -0
- customer_retention/core/components/__init__.py +11 -0
- customer_retention/core/components/base.py +79 -0
- customer_retention/core/components/components/__init__.py +13 -0
- customer_retention/core/components/components/deployer.py +26 -0
- customer_retention/core/components/components/explainer.py +26 -0
- customer_retention/core/components/components/feature_eng.py +33 -0
- customer_retention/core/components/components/ingester.py +34 -0
- customer_retention/core/components/components/profiler.py +34 -0
- customer_retention/core/components/components/trainer.py +38 -0
- customer_retention/core/components/components/transformer.py +36 -0
- customer_retention/core/components/components/validator.py +37 -0
- customer_retention/core/components/enums.py +33 -0
- customer_retention/core/components/orchestrator.py +94 -0
- customer_retention/core/components/registry.py +59 -0
- customer_retention/core/config/__init__.py +39 -0
- customer_retention/core/config/column_config.py +95 -0
- customer_retention/core/config/experiments.py +71 -0
- customer_retention/core/config/pipeline_config.py +117 -0
- customer_retention/core/config/source_config.py +83 -0
- customer_retention/core/utils/__init__.py +28 -0
- customer_retention/core/utils/leakage.py +85 -0
- customer_retention/core/utils/severity.py +53 -0
- customer_retention/core/utils/statistics.py +90 -0
- customer_retention/generators/__init__.py +0 -0
- customer_retention/generators/notebook_generator/__init__.py +167 -0
- customer_retention/generators/notebook_generator/base.py +55 -0
- customer_retention/generators/notebook_generator/cell_builder.py +49 -0
- customer_retention/generators/notebook_generator/config.py +47 -0
- customer_retention/generators/notebook_generator/databricks_generator.py +48 -0
- customer_retention/generators/notebook_generator/local_generator.py +48 -0
- customer_retention/generators/notebook_generator/project_init.py +174 -0
- customer_retention/generators/notebook_generator/runner.py +150 -0
- customer_retention/generators/notebook_generator/script_generator.py +110 -0
- customer_retention/generators/notebook_generator/stages/__init__.py +19 -0
- customer_retention/generators/notebook_generator/stages/base_stage.py +86 -0
- customer_retention/generators/notebook_generator/stages/s01_ingestion.py +100 -0
- customer_retention/generators/notebook_generator/stages/s02_profiling.py +95 -0
- customer_retention/generators/notebook_generator/stages/s03_cleaning.py +180 -0
- customer_retention/generators/notebook_generator/stages/s04_transformation.py +165 -0
- customer_retention/generators/notebook_generator/stages/s05_feature_engineering.py +115 -0
- customer_retention/generators/notebook_generator/stages/s06_feature_selection.py +97 -0
- customer_retention/generators/notebook_generator/stages/s07_model_training.py +176 -0
- customer_retention/generators/notebook_generator/stages/s08_deployment.py +81 -0
- customer_retention/generators/notebook_generator/stages/s09_monitoring.py +112 -0
- customer_retention/generators/notebook_generator/stages/s10_batch_inference.py +642 -0
- customer_retention/generators/notebook_generator/stages/s11_feature_store.py +348 -0
- customer_retention/generators/orchestration/__init__.py +23 -0
- customer_retention/generators/orchestration/code_generator.py +196 -0
- customer_retention/generators/orchestration/context.py +147 -0
- customer_retention/generators/orchestration/data_materializer.py +188 -0
- customer_retention/generators/orchestration/databricks_exporter.py +411 -0
- customer_retention/generators/orchestration/doc_generator.py +311 -0
- customer_retention/generators/pipeline_generator/__init__.py +26 -0
- customer_retention/generators/pipeline_generator/findings_parser.py +727 -0
- customer_retention/generators/pipeline_generator/generator.py +142 -0
- customer_retention/generators/pipeline_generator/models.py +166 -0
- customer_retention/generators/pipeline_generator/renderer.py +2125 -0
- customer_retention/generators/spec_generator/__init__.py +37 -0
- customer_retention/generators/spec_generator/databricks_generator.py +433 -0
- customer_retention/generators/spec_generator/generic_generator.py +373 -0
- customer_retention/generators/spec_generator/mlflow_pipeline_generator.py +685 -0
- customer_retention/generators/spec_generator/pipeline_spec.py +298 -0
- customer_retention/integrations/__init__.py +0 -0
- customer_retention/integrations/adapters/__init__.py +13 -0
- customer_retention/integrations/adapters/base.py +10 -0
- customer_retention/integrations/adapters/factory.py +25 -0
- customer_retention/integrations/adapters/feature_store/__init__.py +6 -0
- customer_retention/integrations/adapters/feature_store/base.py +57 -0
- customer_retention/integrations/adapters/feature_store/databricks.py +94 -0
- customer_retention/integrations/adapters/feature_store/feast_adapter.py +97 -0
- customer_retention/integrations/adapters/feature_store/local.py +75 -0
- customer_retention/integrations/adapters/mlflow/__init__.py +6 -0
- customer_retention/integrations/adapters/mlflow/base.py +32 -0
- customer_retention/integrations/adapters/mlflow/databricks.py +54 -0
- customer_retention/integrations/adapters/mlflow/experiment_tracker.py +161 -0
- customer_retention/integrations/adapters/mlflow/local.py +50 -0
- customer_retention/integrations/adapters/storage/__init__.py +5 -0
- customer_retention/integrations/adapters/storage/base.py +33 -0
- customer_retention/integrations/adapters/storage/databricks.py +76 -0
- customer_retention/integrations/adapters/storage/local.py +59 -0
- customer_retention/integrations/feature_store/__init__.py +47 -0
- customer_retention/integrations/feature_store/definitions.py +215 -0
- customer_retention/integrations/feature_store/manager.py +744 -0
- customer_retention/integrations/feature_store/registry.py +412 -0
- customer_retention/integrations/iteration/__init__.py +28 -0
- customer_retention/integrations/iteration/context.py +212 -0
- customer_retention/integrations/iteration/feedback_collector.py +184 -0
- customer_retention/integrations/iteration/orchestrator.py +168 -0
- customer_retention/integrations/iteration/recommendation_tracker.py +341 -0
- customer_retention/integrations/iteration/signals.py +212 -0
- customer_retention/integrations/llm_context/__init__.py +4 -0
- customer_retention/integrations/llm_context/context_builder.py +201 -0
- customer_retention/integrations/llm_context/prompts.py +100 -0
- customer_retention/integrations/streaming/__init__.py +103 -0
- customer_retention/integrations/streaming/batch_integration.py +149 -0
- customer_retention/integrations/streaming/early_warning_model.py +227 -0
- customer_retention/integrations/streaming/event_schema.py +214 -0
- customer_retention/integrations/streaming/online_store_writer.py +249 -0
- customer_retention/integrations/streaming/realtime_scorer.py +261 -0
- customer_retention/integrations/streaming/trigger_engine.py +293 -0
- customer_retention/integrations/streaming/window_aggregator.py +393 -0
- customer_retention/stages/__init__.py +0 -0
- customer_retention/stages/cleaning/__init__.py +9 -0
- customer_retention/stages/cleaning/base.py +28 -0
- customer_retention/stages/cleaning/missing_handler.py +160 -0
- customer_retention/stages/cleaning/outlier_handler.py +204 -0
- customer_retention/stages/deployment/__init__.py +28 -0
- customer_retention/stages/deployment/batch_scorer.py +106 -0
- customer_retention/stages/deployment/champion_challenger.py +299 -0
- customer_retention/stages/deployment/model_registry.py +182 -0
- customer_retention/stages/deployment/retraining_trigger.py +245 -0
- customer_retention/stages/features/__init__.py +73 -0
- customer_retention/stages/features/behavioral_features.py +266 -0
- customer_retention/stages/features/customer_segmentation.py +505 -0
- customer_retention/stages/features/feature_definitions.py +265 -0
- customer_retention/stages/features/feature_engineer.py +551 -0
- customer_retention/stages/features/feature_manifest.py +340 -0
- customer_retention/stages/features/feature_selector.py +239 -0
- customer_retention/stages/features/interaction_features.py +160 -0
- customer_retention/stages/features/temporal_features.py +243 -0
- customer_retention/stages/ingestion/__init__.py +9 -0
- customer_retention/stages/ingestion/load_result.py +32 -0
- customer_retention/stages/ingestion/loaders.py +195 -0
- customer_retention/stages/ingestion/source_registry.py +130 -0
- customer_retention/stages/modeling/__init__.py +31 -0
- customer_retention/stages/modeling/baseline_trainer.py +139 -0
- customer_retention/stages/modeling/cross_validator.py +125 -0
- customer_retention/stages/modeling/data_splitter.py +205 -0
- customer_retention/stages/modeling/feature_scaler.py +99 -0
- customer_retention/stages/modeling/hyperparameter_tuner.py +107 -0
- customer_retention/stages/modeling/imbalance_handler.py +282 -0
- customer_retention/stages/modeling/mlflow_logger.py +95 -0
- customer_retention/stages/modeling/model_comparator.py +149 -0
- customer_retention/stages/modeling/model_evaluator.py +138 -0
- customer_retention/stages/modeling/threshold_optimizer.py +131 -0
- customer_retention/stages/monitoring/__init__.py +37 -0
- customer_retention/stages/monitoring/alert_manager.py +328 -0
- customer_retention/stages/monitoring/drift_detector.py +201 -0
- customer_retention/stages/monitoring/performance_monitor.py +242 -0
- customer_retention/stages/preprocessing/__init__.py +5 -0
- customer_retention/stages/preprocessing/transformer_manager.py +284 -0
- customer_retention/stages/profiling/__init__.py +256 -0
- customer_retention/stages/profiling/categorical_distribution.py +269 -0
- customer_retention/stages/profiling/categorical_target_analyzer.py +274 -0
- customer_retention/stages/profiling/column_profiler.py +527 -0
- customer_retention/stages/profiling/distribution_analysis.py +483 -0
- customer_retention/stages/profiling/drift_detector.py +310 -0
- customer_retention/stages/profiling/feature_capacity.py +507 -0
- customer_retention/stages/profiling/pattern_analysis_config.py +513 -0
- customer_retention/stages/profiling/profile_result.py +212 -0
- customer_retention/stages/profiling/quality_checks.py +1632 -0
- customer_retention/stages/profiling/relationship_detector.py +256 -0
- customer_retention/stages/profiling/relationship_recommender.py +454 -0
- customer_retention/stages/profiling/report_generator.py +520 -0
- customer_retention/stages/profiling/scd_analyzer.py +151 -0
- customer_retention/stages/profiling/segment_analyzer.py +632 -0
- customer_retention/stages/profiling/segment_aware_outlier.py +265 -0
- customer_retention/stages/profiling/target_level_analyzer.py +217 -0
- customer_retention/stages/profiling/temporal_analyzer.py +388 -0
- customer_retention/stages/profiling/temporal_coverage.py +488 -0
- customer_retention/stages/profiling/temporal_feature_analyzer.py +692 -0
- customer_retention/stages/profiling/temporal_feature_engineer.py +703 -0
- customer_retention/stages/profiling/temporal_pattern_analyzer.py +636 -0
- customer_retention/stages/profiling/temporal_quality_checks.py +278 -0
- customer_retention/stages/profiling/temporal_target_analyzer.py +241 -0
- customer_retention/stages/profiling/text_embedder.py +87 -0
- customer_retention/stages/profiling/text_processor.py +115 -0
- customer_retention/stages/profiling/text_reducer.py +60 -0
- customer_retention/stages/profiling/time_series_profiler.py +303 -0
- customer_retention/stages/profiling/time_window_aggregator.py +376 -0
- customer_retention/stages/profiling/type_detector.py +382 -0
- customer_retention/stages/profiling/window_recommendation.py +288 -0
- customer_retention/stages/temporal/__init__.py +166 -0
- customer_retention/stages/temporal/access_guard.py +180 -0
- customer_retention/stages/temporal/cutoff_analyzer.py +235 -0
- customer_retention/stages/temporal/data_preparer.py +178 -0
- customer_retention/stages/temporal/point_in_time_join.py +134 -0
- customer_retention/stages/temporal/point_in_time_registry.py +148 -0
- customer_retention/stages/temporal/scenario_detector.py +163 -0
- customer_retention/stages/temporal/snapshot_manager.py +259 -0
- customer_retention/stages/temporal/synthetic_coordinator.py +66 -0
- customer_retention/stages/temporal/timestamp_discovery.py +531 -0
- customer_retention/stages/temporal/timestamp_manager.py +255 -0
- customer_retention/stages/transformation/__init__.py +13 -0
- customer_retention/stages/transformation/binary_handler.py +85 -0
- customer_retention/stages/transformation/categorical_encoder.py +245 -0
- customer_retention/stages/transformation/datetime_transformer.py +97 -0
- customer_retention/stages/transformation/numeric_transformer.py +181 -0
- customer_retention/stages/transformation/pipeline.py +257 -0
- customer_retention/stages/validation/__init__.py +60 -0
- customer_retention/stages/validation/adversarial_scoring_validator.py +205 -0
- customer_retention/stages/validation/business_sense_gate.py +173 -0
- customer_retention/stages/validation/data_quality_gate.py +235 -0
- customer_retention/stages/validation/data_validators.py +511 -0
- customer_retention/stages/validation/feature_quality_gate.py +183 -0
- customer_retention/stages/validation/gates.py +117 -0
- customer_retention/stages/validation/leakage_gate.py +352 -0
- customer_retention/stages/validation/model_validity_gate.py +213 -0
- customer_retention/stages/validation/pipeline_validation_runner.py +264 -0
- customer_retention/stages/validation/quality_scorer.py +544 -0
- customer_retention/stages/validation/rule_generator.py +57 -0
- customer_retention/stages/validation/scoring_pipeline_validator.py +446 -0
- customer_retention/stages/validation/timeseries_detector.py +769 -0
- customer_retention/transforms/__init__.py +47 -0
- customer_retention/transforms/artifact_store.py +50 -0
- customer_retention/transforms/executor.py +157 -0
- customer_retention/transforms/fitted.py +92 -0
- customer_retention/transforms/ops.py +148 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from customer_retention.analysis.auto_explorer import ExplorationFindings
|
|
9
|
+
from customer_retention.core.config.column_config import ColumnConfig, ColumnType
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class PipelineContext:
|
|
14
|
+
run_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
|
|
15
|
+
project_name: str = "customer_retention"
|
|
16
|
+
started_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
|
17
|
+
raw_data_path: Optional[str] = None
|
|
18
|
+
bronze_path: Optional[str] = None
|
|
19
|
+
silver_path: Optional[str] = None
|
|
20
|
+
gold_path: Optional[str] = None
|
|
21
|
+
exploration_findings: Optional[ExplorationFindings] = None
|
|
22
|
+
profiling_results: Optional[Dict] = None
|
|
23
|
+
cleaning_report: Optional[Dict] = None
|
|
24
|
+
transformation_pipeline: Optional[Any] = None
|
|
25
|
+
feature_manifest: Optional[Any] = None
|
|
26
|
+
selected_features: Optional[List[str]] = None
|
|
27
|
+
model_results: Optional[Dict] = None
|
|
28
|
+
validation_results: Optional[Dict] = None
|
|
29
|
+
current_df: Optional[Any] = None
|
|
30
|
+
current_stage: str = "raw"
|
|
31
|
+
artifacts: Dict[str, str] = field(default_factory=dict)
|
|
32
|
+
delta_versions: Dict[str, int] = field(default_factory=dict)
|
|
33
|
+
run_type: str = "exploration"
|
|
34
|
+
_context_dir: str = "./runs"
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def column_types(self) -> Dict[str, ColumnType]:
|
|
38
|
+
return self.exploration_findings.column_types if self.exploration_findings else {}
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def column_configs(self) -> Dict[str, ColumnConfig]:
|
|
42
|
+
return self.exploration_findings.column_configs if self.exploration_findings else {}
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def target_column(self) -> Optional[str]:
|
|
46
|
+
return self.exploration_findings.target_column if self.exploration_findings else None
|
|
47
|
+
|
|
48
|
+
def build_commit_metadata(self) -> Dict[str, str]:
|
|
49
|
+
return {
|
|
50
|
+
"run_id": self.run_id,
|
|
51
|
+
"run_type": self.run_type,
|
|
52
|
+
"pipeline_stage": self.current_stage,
|
|
53
|
+
"timestamp": self.started_at,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
def save(self, path: str = None):
|
|
57
|
+
Path(self._context_dir).mkdir(parents=True, exist_ok=True)
|
|
58
|
+
if path is None:
|
|
59
|
+
path = f"{self._context_dir}/{self.run_id}_context.json"
|
|
60
|
+
data = {
|
|
61
|
+
"run_id": self.run_id,
|
|
62
|
+
"project_name": self.project_name,
|
|
63
|
+
"started_at": self.started_at,
|
|
64
|
+
"raw_data_path": self.raw_data_path,
|
|
65
|
+
"bronze_path": self.bronze_path,
|
|
66
|
+
"silver_path": self.silver_path,
|
|
67
|
+
"gold_path": self.gold_path,
|
|
68
|
+
"current_stage": self.current_stage,
|
|
69
|
+
"artifacts": self.artifacts,
|
|
70
|
+
"delta_versions": self.delta_versions,
|
|
71
|
+
"run_type": self.run_type,
|
|
72
|
+
"exploration_findings_path": None
|
|
73
|
+
}
|
|
74
|
+
if self.exploration_findings:
|
|
75
|
+
findings_path = f"{self._context_dir}/{self.run_id}_findings.yaml"
|
|
76
|
+
self.exploration_findings.save(findings_path)
|
|
77
|
+
data["exploration_findings_path"] = findings_path
|
|
78
|
+
with open(path, "w") as f:
|
|
79
|
+
json.dump(data, f, indent=2)
|
|
80
|
+
print(f"Context saved: {path}")
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def load(cls, path: str) -> "PipelineContext":
|
|
84
|
+
with open(path, "r") as f:
|
|
85
|
+
data = json.load(f)
|
|
86
|
+
exploration_findings = None
|
|
87
|
+
if data.get("exploration_findings_path"):
|
|
88
|
+
exploration_findings = ExplorationFindings.load(data["exploration_findings_path"])
|
|
89
|
+
ctx = cls(
|
|
90
|
+
run_id=data["run_id"],
|
|
91
|
+
project_name=data["project_name"],
|
|
92
|
+
started_at=data["started_at"],
|
|
93
|
+
raw_data_path=data.get("raw_data_path"),
|
|
94
|
+
bronze_path=data.get("bronze_path"),
|
|
95
|
+
silver_path=data.get("silver_path"),
|
|
96
|
+
gold_path=data.get("gold_path"),
|
|
97
|
+
current_stage=data.get("current_stage", "raw"),
|
|
98
|
+
artifacts=data.get("artifacts", {}),
|
|
99
|
+
delta_versions=data.get("delta_versions", {}),
|
|
100
|
+
run_type=data.get("run_type", "exploration"),
|
|
101
|
+
exploration_findings=exploration_findings
|
|
102
|
+
)
|
|
103
|
+
ctx._context_dir = str(Path(path).parent)
|
|
104
|
+
return ctx
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ContextManager:
|
|
108
|
+
def __init__(self, context: PipelineContext, auto_save: bool = True):
|
|
109
|
+
self.context = context
|
|
110
|
+
self.auto_save = auto_save
|
|
111
|
+
|
|
112
|
+
def update(self, **kwargs):
|
|
113
|
+
for key, value in kwargs.items():
|
|
114
|
+
if hasattr(self.context, key):
|
|
115
|
+
setattr(self.context, key, value)
|
|
116
|
+
if self.auto_save:
|
|
117
|
+
self.context.save()
|
|
118
|
+
|
|
119
|
+
def add_artifact(self, name: str, path: str):
|
|
120
|
+
self.context.artifacts[name] = path
|
|
121
|
+
if self.auto_save:
|
|
122
|
+
self.context.save()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def setup_notebook_context(
|
|
126
|
+
project_name: str = None,
|
|
127
|
+
exploration_findings: Any = None,
|
|
128
|
+
resume_run: str = None,
|
|
129
|
+
output_dir: str = "./runs"
|
|
130
|
+
) -> Tuple[PipelineContext, ContextManager]:
|
|
131
|
+
if resume_run:
|
|
132
|
+
context_path = f"{output_dir}/{resume_run}_context.json"
|
|
133
|
+
context = PipelineContext.load(context_path)
|
|
134
|
+
print(f"Resumed run: {context.run_id}")
|
|
135
|
+
else:
|
|
136
|
+
context = PipelineContext(project_name=project_name or "customer_retention")
|
|
137
|
+
context._context_dir = output_dir
|
|
138
|
+
if exploration_findings:
|
|
139
|
+
if isinstance(exploration_findings, str):
|
|
140
|
+
context.exploration_findings = ExplorationFindings.load(exploration_findings)
|
|
141
|
+
else:
|
|
142
|
+
context.exploration_findings = exploration_findings
|
|
143
|
+
context.raw_data_path = context.exploration_findings.source_path
|
|
144
|
+
print(f"New run: {context.run_id}")
|
|
145
|
+
print(f"Loaded findings: {len(context.column_types)} columns")
|
|
146
|
+
print(f"Target: {context.target_column}")
|
|
147
|
+
return context, ContextManager(context)
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Optional, Tuple
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.preprocessing import RobustScaler, StandardScaler
|
|
7
|
+
|
|
8
|
+
from customer_retention.analysis.auto_explorer.layered_recommendations import (
|
|
9
|
+
LayeredRecommendation,
|
|
10
|
+
RecommendationRegistry,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DataMaterializer:
|
|
15
|
+
def __init__(self, registry: RecommendationRegistry, output_dir: Optional[str] = None,
|
|
16
|
+
storage=None, context=None):
|
|
17
|
+
self.registry = registry
|
|
18
|
+
self.output_dir = output_dir or "./prepared_data"
|
|
19
|
+
self.storage = storage or _get_storage()
|
|
20
|
+
self.context = context
|
|
21
|
+
|
|
22
|
+
def transform(self, df: pd.DataFrame) -> pd.DataFrame:
|
|
23
|
+
df = self.apply_bronze(df)
|
|
24
|
+
df = self.apply_silver(df)
|
|
25
|
+
df = self.apply_gold(df)
|
|
26
|
+
return df
|
|
27
|
+
|
|
28
|
+
def materialize(self, df: pd.DataFrame, output_name: str) -> Tuple[pd.DataFrame, str]:
|
|
29
|
+
result_df = self.transform(df)
|
|
30
|
+
output_path = self._save(result_df, output_name)
|
|
31
|
+
return result_df, output_path
|
|
32
|
+
|
|
33
|
+
def apply_bronze(self, df: pd.DataFrame) -> pd.DataFrame:
|
|
34
|
+
if not self.registry.bronze:
|
|
35
|
+
return df
|
|
36
|
+
df = df.copy()
|
|
37
|
+
for rec in self.registry.bronze.null_handling:
|
|
38
|
+
df = self._apply_null_handling(df, rec)
|
|
39
|
+
for rec in self.registry.bronze.outlier_handling:
|
|
40
|
+
df = self._apply_outlier_handling(df, rec)
|
|
41
|
+
for rec in self.registry.bronze.type_conversions:
|
|
42
|
+
df = self._apply_type_conversion(df, rec)
|
|
43
|
+
for rec in self.registry.bronze.filtering:
|
|
44
|
+
df = self._apply_filtering(df, rec)
|
|
45
|
+
return df
|
|
46
|
+
|
|
47
|
+
def apply_silver(self, df: pd.DataFrame) -> pd.DataFrame:
|
|
48
|
+
if not self.registry.silver:
|
|
49
|
+
return df
|
|
50
|
+
df = df.copy()
|
|
51
|
+
for rec in self.registry.silver.aggregations:
|
|
52
|
+
df = self._apply_aggregation(df, rec)
|
|
53
|
+
for rec in self.registry.silver.derived_columns:
|
|
54
|
+
df = self._apply_derived(df, rec)
|
|
55
|
+
return df
|
|
56
|
+
|
|
57
|
+
def apply_gold(self, df: pd.DataFrame) -> pd.DataFrame:
|
|
58
|
+
if not self.registry.gold:
|
|
59
|
+
return df
|
|
60
|
+
df = df.copy()
|
|
61
|
+
for rec in self.registry.gold.transformations:
|
|
62
|
+
df = self._apply_transformation(df, rec)
|
|
63
|
+
for rec in self.registry.gold.encoding:
|
|
64
|
+
df = self._apply_encoding(df, rec)
|
|
65
|
+
for rec in self.registry.gold.scaling:
|
|
66
|
+
df = self._apply_scaling(df, rec)
|
|
67
|
+
return df
|
|
68
|
+
|
|
69
|
+
def _apply_null_handling(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
70
|
+
col = rec.target_column
|
|
71
|
+
if col not in df.columns:
|
|
72
|
+
return df
|
|
73
|
+
strategy = rec.parameters.get("strategy", "median")
|
|
74
|
+
if strategy == "median":
|
|
75
|
+
df[col] = df[col].fillna(df[col].median())
|
|
76
|
+
elif strategy == "mean":
|
|
77
|
+
df[col] = df[col].fillna(df[col].mean())
|
|
78
|
+
elif strategy == "mode":
|
|
79
|
+
df[col] = df[col].fillna(df[col].mode().iloc[0] if len(df[col].mode()) > 0 else df[col])
|
|
80
|
+
elif strategy == "zero":
|
|
81
|
+
df[col] = df[col].fillna(0)
|
|
82
|
+
return df
|
|
83
|
+
|
|
84
|
+
def _apply_outlier_handling(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
85
|
+
col = rec.target_column
|
|
86
|
+
if col not in df.columns:
|
|
87
|
+
return df
|
|
88
|
+
method = rec.parameters.get("method", "iqr")
|
|
89
|
+
if method == "iqr":
|
|
90
|
+
factor = rec.parameters.get("factor", 1.5)
|
|
91
|
+
q1, q3 = df[col].quantile([0.25, 0.75])
|
|
92
|
+
iqr = q3 - q1
|
|
93
|
+
lower, upper = q1 - factor * iqr, q3 + factor * iqr
|
|
94
|
+
df[col] = df[col].clip(lower, upper)
|
|
95
|
+
return df
|
|
96
|
+
|
|
97
|
+
def _apply_type_conversion(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
98
|
+
col = rec.target_column
|
|
99
|
+
if col not in df.columns:
|
|
100
|
+
return df
|
|
101
|
+
target_type = rec.parameters.get("target_type", "str")
|
|
102
|
+
if target_type == "datetime":
|
|
103
|
+
df[col] = pd.to_datetime(df[col])
|
|
104
|
+
else:
|
|
105
|
+
df[col] = df[col].astype(target_type)
|
|
106
|
+
return df
|
|
107
|
+
|
|
108
|
+
def _apply_filtering(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
109
|
+
col = rec.target_column
|
|
110
|
+
if rec.action == "drop" and col in df.columns:
|
|
111
|
+
df = df.drop(columns=[col])
|
|
112
|
+
return df
|
|
113
|
+
|
|
114
|
+
def _apply_aggregation(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
115
|
+
col = rec.target_column
|
|
116
|
+
if col not in df.columns or not self.registry.silver:
|
|
117
|
+
return df
|
|
118
|
+
entity_col = self.registry.silver.entity_column
|
|
119
|
+
agg_func = rec.parameters.get("aggregation", "sum")
|
|
120
|
+
feature_name = f"{col}_{agg_func}"
|
|
121
|
+
df[feature_name] = df.groupby(entity_col)[col].transform(agg_func)
|
|
122
|
+
return df
|
|
123
|
+
|
|
124
|
+
def _apply_derived(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
125
|
+
return df
|
|
126
|
+
|
|
127
|
+
def _apply_transformation(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
128
|
+
col = rec.target_column
|
|
129
|
+
if col not in df.columns:
|
|
130
|
+
return df
|
|
131
|
+
method = rec.parameters.get("method", "log")
|
|
132
|
+
if method == "log":
|
|
133
|
+
df[col] = np.log1p(df[col])
|
|
134
|
+
elif method == "sqrt":
|
|
135
|
+
df[col] = np.sqrt(df[col])
|
|
136
|
+
return df
|
|
137
|
+
|
|
138
|
+
def _apply_encoding(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
139
|
+
col = rec.target_column
|
|
140
|
+
if col not in df.columns:
|
|
141
|
+
return df
|
|
142
|
+
method = rec.parameters.get("method", "one_hot")
|
|
143
|
+
if method == "one_hot":
|
|
144
|
+
dummies = pd.get_dummies(df[col], prefix=col, drop_first=False)
|
|
145
|
+
df = pd.concat([df.drop(columns=[col]), dummies], axis=1)
|
|
146
|
+
return df
|
|
147
|
+
|
|
148
|
+
def _apply_scaling(self, df: pd.DataFrame, rec: LayeredRecommendation) -> pd.DataFrame:
|
|
149
|
+
col = rec.target_column
|
|
150
|
+
if col not in df.columns:
|
|
151
|
+
return df
|
|
152
|
+
method = rec.parameters.get("method", "standard")
|
|
153
|
+
scaler = StandardScaler() if method == "standard" else RobustScaler()
|
|
154
|
+
df[col] = scaler.fit_transform(df[[col]])
|
|
155
|
+
return df
|
|
156
|
+
|
|
157
|
+
def _save(self, df: pd.DataFrame, output_name: str) -> str:
|
|
158
|
+
Path(self.output_dir).mkdir(parents=True, exist_ok=True)
|
|
159
|
+
output_path = f"{self.output_dir}/{output_name}"
|
|
160
|
+
if self.storage:
|
|
161
|
+
metadata = self.context.build_commit_metadata() if self.context else None
|
|
162
|
+
self.storage.write(df, output_path, metadata=metadata)
|
|
163
|
+
if self.context:
|
|
164
|
+
version = len(self.storage.history(output_path)) - 1
|
|
165
|
+
self.context.delta_versions[output_path] = version
|
|
166
|
+
else:
|
|
167
|
+
output_path = f"{output_path}.parquet"
|
|
168
|
+
df.to_parquet(output_path, index=False)
|
|
169
|
+
return output_path
|
|
170
|
+
|
|
171
|
+
def compare_runs(self, path: str, version_a: int, version_b: int) -> pd.DataFrame:
|
|
172
|
+
if not self.storage:
|
|
173
|
+
raise RuntimeError("DeltaStorage required for version comparison")
|
|
174
|
+
df_a = self.storage.read(path, version=version_a)
|
|
175
|
+
df_b = self.storage.read(path, version=version_b)
|
|
176
|
+
return pd.DataFrame({
|
|
177
|
+
"metric": ["row_count", "column_count"],
|
|
178
|
+
"version_a": [len(df_a), len(df_a.columns)],
|
|
179
|
+
"version_b": [len(df_b), len(df_b.columns)],
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _get_storage():
|
|
184
|
+
try:
|
|
185
|
+
from customer_retention.integrations.adapters.factory import get_delta
|
|
186
|
+
return get_delta(force_local=True)
|
|
187
|
+
except ImportError:
|
|
188
|
+
return None
|