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.
Files changed (302) hide show
  1. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/00_start_here.ipynb +647 -0
  2. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01_data_discovery.ipynb +1165 -0
  3. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_a_temporal_text_deep_dive.ipynb +961 -0
  4. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_temporal_deep_dive.ipynb +1690 -0
  5. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01b_temporal_quality.ipynb +679 -0
  6. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01c_temporal_patterns.ipynb +3305 -0
  7. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01d_event_aggregation.ipynb +1463 -0
  8. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02_column_deep_dive.ipynb +1430 -0
  9. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02a_text_columns_deep_dive.ipynb +854 -0
  10. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/03_quality_assessment.ipynb +1639 -0
  11. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/04_relationship_analysis.ipynb +1890 -0
  12. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/05_multi_dataset.ipynb +1457 -0
  13. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/06_feature_opportunities.ipynb +1624 -0
  14. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/07_modeling_readiness.ipynb +780 -0
  15. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/08_baseline_experiments.ipynb +979 -0
  16. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/09_business_alignment.ipynb +572 -0
  17. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/10_spec_generation.ipynb +1179 -0
  18. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/11_scoring_validation.ipynb +1418 -0
  19. churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/12_view_documentation.ipynb +151 -0
  20. churnkit-0.75.0a1.dist-info/METADATA +229 -0
  21. churnkit-0.75.0a1.dist-info/RECORD +302 -0
  22. churnkit-0.75.0a1.dist-info/WHEEL +4 -0
  23. churnkit-0.75.0a1.dist-info/entry_points.txt +2 -0
  24. churnkit-0.75.0a1.dist-info/licenses/LICENSE +202 -0
  25. customer_retention/__init__.py +37 -0
  26. customer_retention/analysis/__init__.py +0 -0
  27. customer_retention/analysis/auto_explorer/__init__.py +62 -0
  28. customer_retention/analysis/auto_explorer/exploration_manager.py +470 -0
  29. customer_retention/analysis/auto_explorer/explorer.py +258 -0
  30. customer_retention/analysis/auto_explorer/findings.py +291 -0
  31. customer_retention/analysis/auto_explorer/layered_recommendations.py +485 -0
  32. customer_retention/analysis/auto_explorer/recommendation_builder.py +148 -0
  33. customer_retention/analysis/auto_explorer/recommendations.py +418 -0
  34. customer_retention/analysis/business/__init__.py +26 -0
  35. customer_retention/analysis/business/ab_test_designer.py +144 -0
  36. customer_retention/analysis/business/fairness_analyzer.py +166 -0
  37. customer_retention/analysis/business/intervention_matcher.py +121 -0
  38. customer_retention/analysis/business/report_generator.py +222 -0
  39. customer_retention/analysis/business/risk_profile.py +199 -0
  40. customer_retention/analysis/business/roi_analyzer.py +139 -0
  41. customer_retention/analysis/diagnostics/__init__.py +20 -0
  42. customer_retention/analysis/diagnostics/calibration_analyzer.py +133 -0
  43. customer_retention/analysis/diagnostics/cv_analyzer.py +144 -0
  44. customer_retention/analysis/diagnostics/error_analyzer.py +107 -0
  45. customer_retention/analysis/diagnostics/leakage_detector.py +394 -0
  46. customer_retention/analysis/diagnostics/noise_tester.py +140 -0
  47. customer_retention/analysis/diagnostics/overfitting_analyzer.py +190 -0
  48. customer_retention/analysis/diagnostics/segment_analyzer.py +122 -0
  49. customer_retention/analysis/discovery/__init__.py +8 -0
  50. customer_retention/analysis/discovery/config_generator.py +49 -0
  51. customer_retention/analysis/discovery/discovery_flow.py +19 -0
  52. customer_retention/analysis/discovery/type_inferencer.py +147 -0
  53. customer_retention/analysis/interpretability/__init__.py +13 -0
  54. customer_retention/analysis/interpretability/cohort_analyzer.py +185 -0
  55. customer_retention/analysis/interpretability/counterfactual.py +175 -0
  56. customer_retention/analysis/interpretability/individual_explainer.py +141 -0
  57. customer_retention/analysis/interpretability/pdp_generator.py +103 -0
  58. customer_retention/analysis/interpretability/shap_explainer.py +106 -0
  59. customer_retention/analysis/jupyter_save_hook.py +28 -0
  60. customer_retention/analysis/notebook_html_exporter.py +136 -0
  61. customer_retention/analysis/notebook_progress.py +60 -0
  62. customer_retention/analysis/plotly_preprocessor.py +154 -0
  63. customer_retention/analysis/recommendations/__init__.py +54 -0
  64. customer_retention/analysis/recommendations/base.py +158 -0
  65. customer_retention/analysis/recommendations/cleaning/__init__.py +11 -0
  66. customer_retention/analysis/recommendations/cleaning/consistency.py +107 -0
  67. customer_retention/analysis/recommendations/cleaning/deduplicate.py +94 -0
  68. customer_retention/analysis/recommendations/cleaning/impute.py +67 -0
  69. customer_retention/analysis/recommendations/cleaning/outlier.py +71 -0
  70. customer_retention/analysis/recommendations/datetime/__init__.py +3 -0
  71. customer_retention/analysis/recommendations/datetime/extract.py +149 -0
  72. customer_retention/analysis/recommendations/encoding/__init__.py +3 -0
  73. customer_retention/analysis/recommendations/encoding/categorical.py +114 -0
  74. customer_retention/analysis/recommendations/pipeline.py +74 -0
  75. customer_retention/analysis/recommendations/registry.py +76 -0
  76. customer_retention/analysis/recommendations/selection/__init__.py +3 -0
  77. customer_retention/analysis/recommendations/selection/drop_column.py +56 -0
  78. customer_retention/analysis/recommendations/transform/__init__.py +4 -0
  79. customer_retention/analysis/recommendations/transform/power.py +94 -0
  80. customer_retention/analysis/recommendations/transform/scale.py +112 -0
  81. customer_retention/analysis/visualization/__init__.py +15 -0
  82. customer_retention/analysis/visualization/chart_builder.py +2619 -0
  83. customer_retention/analysis/visualization/console.py +122 -0
  84. customer_retention/analysis/visualization/display.py +171 -0
  85. customer_retention/analysis/visualization/number_formatter.py +36 -0
  86. customer_retention/artifacts/__init__.py +3 -0
  87. customer_retention/artifacts/fit_artifact_registry.py +146 -0
  88. customer_retention/cli.py +93 -0
  89. customer_retention/core/__init__.py +0 -0
  90. customer_retention/core/compat/__init__.py +193 -0
  91. customer_retention/core/compat/detection.py +99 -0
  92. customer_retention/core/compat/ops.py +48 -0
  93. customer_retention/core/compat/pandas_backend.py +57 -0
  94. customer_retention/core/compat/spark_backend.py +75 -0
  95. customer_retention/core/components/__init__.py +11 -0
  96. customer_retention/core/components/base.py +79 -0
  97. customer_retention/core/components/components/__init__.py +13 -0
  98. customer_retention/core/components/components/deployer.py +26 -0
  99. customer_retention/core/components/components/explainer.py +26 -0
  100. customer_retention/core/components/components/feature_eng.py +33 -0
  101. customer_retention/core/components/components/ingester.py +34 -0
  102. customer_retention/core/components/components/profiler.py +34 -0
  103. customer_retention/core/components/components/trainer.py +38 -0
  104. customer_retention/core/components/components/transformer.py +36 -0
  105. customer_retention/core/components/components/validator.py +37 -0
  106. customer_retention/core/components/enums.py +33 -0
  107. customer_retention/core/components/orchestrator.py +94 -0
  108. customer_retention/core/components/registry.py +59 -0
  109. customer_retention/core/config/__init__.py +39 -0
  110. customer_retention/core/config/column_config.py +95 -0
  111. customer_retention/core/config/experiments.py +71 -0
  112. customer_retention/core/config/pipeline_config.py +117 -0
  113. customer_retention/core/config/source_config.py +83 -0
  114. customer_retention/core/utils/__init__.py +28 -0
  115. customer_retention/core/utils/leakage.py +85 -0
  116. customer_retention/core/utils/severity.py +53 -0
  117. customer_retention/core/utils/statistics.py +90 -0
  118. customer_retention/generators/__init__.py +0 -0
  119. customer_retention/generators/notebook_generator/__init__.py +167 -0
  120. customer_retention/generators/notebook_generator/base.py +55 -0
  121. customer_retention/generators/notebook_generator/cell_builder.py +49 -0
  122. customer_retention/generators/notebook_generator/config.py +47 -0
  123. customer_retention/generators/notebook_generator/databricks_generator.py +48 -0
  124. customer_retention/generators/notebook_generator/local_generator.py +48 -0
  125. customer_retention/generators/notebook_generator/project_init.py +174 -0
  126. customer_retention/generators/notebook_generator/runner.py +150 -0
  127. customer_retention/generators/notebook_generator/script_generator.py +110 -0
  128. customer_retention/generators/notebook_generator/stages/__init__.py +19 -0
  129. customer_retention/generators/notebook_generator/stages/base_stage.py +86 -0
  130. customer_retention/generators/notebook_generator/stages/s01_ingestion.py +100 -0
  131. customer_retention/generators/notebook_generator/stages/s02_profiling.py +95 -0
  132. customer_retention/generators/notebook_generator/stages/s03_cleaning.py +180 -0
  133. customer_retention/generators/notebook_generator/stages/s04_transformation.py +165 -0
  134. customer_retention/generators/notebook_generator/stages/s05_feature_engineering.py +115 -0
  135. customer_retention/generators/notebook_generator/stages/s06_feature_selection.py +97 -0
  136. customer_retention/generators/notebook_generator/stages/s07_model_training.py +176 -0
  137. customer_retention/generators/notebook_generator/stages/s08_deployment.py +81 -0
  138. customer_retention/generators/notebook_generator/stages/s09_monitoring.py +112 -0
  139. customer_retention/generators/notebook_generator/stages/s10_batch_inference.py +642 -0
  140. customer_retention/generators/notebook_generator/stages/s11_feature_store.py +348 -0
  141. customer_retention/generators/orchestration/__init__.py +23 -0
  142. customer_retention/generators/orchestration/code_generator.py +196 -0
  143. customer_retention/generators/orchestration/context.py +147 -0
  144. customer_retention/generators/orchestration/data_materializer.py +188 -0
  145. customer_retention/generators/orchestration/databricks_exporter.py +411 -0
  146. customer_retention/generators/orchestration/doc_generator.py +311 -0
  147. customer_retention/generators/pipeline_generator/__init__.py +26 -0
  148. customer_retention/generators/pipeline_generator/findings_parser.py +727 -0
  149. customer_retention/generators/pipeline_generator/generator.py +142 -0
  150. customer_retention/generators/pipeline_generator/models.py +166 -0
  151. customer_retention/generators/pipeline_generator/renderer.py +2125 -0
  152. customer_retention/generators/spec_generator/__init__.py +37 -0
  153. customer_retention/generators/spec_generator/databricks_generator.py +433 -0
  154. customer_retention/generators/spec_generator/generic_generator.py +373 -0
  155. customer_retention/generators/spec_generator/mlflow_pipeline_generator.py +685 -0
  156. customer_retention/generators/spec_generator/pipeline_spec.py +298 -0
  157. customer_retention/integrations/__init__.py +0 -0
  158. customer_retention/integrations/adapters/__init__.py +13 -0
  159. customer_retention/integrations/adapters/base.py +10 -0
  160. customer_retention/integrations/adapters/factory.py +25 -0
  161. customer_retention/integrations/adapters/feature_store/__init__.py +6 -0
  162. customer_retention/integrations/adapters/feature_store/base.py +57 -0
  163. customer_retention/integrations/adapters/feature_store/databricks.py +94 -0
  164. customer_retention/integrations/adapters/feature_store/feast_adapter.py +97 -0
  165. customer_retention/integrations/adapters/feature_store/local.py +75 -0
  166. customer_retention/integrations/adapters/mlflow/__init__.py +6 -0
  167. customer_retention/integrations/adapters/mlflow/base.py +32 -0
  168. customer_retention/integrations/adapters/mlflow/databricks.py +54 -0
  169. customer_retention/integrations/adapters/mlflow/experiment_tracker.py +161 -0
  170. customer_retention/integrations/adapters/mlflow/local.py +50 -0
  171. customer_retention/integrations/adapters/storage/__init__.py +5 -0
  172. customer_retention/integrations/adapters/storage/base.py +33 -0
  173. customer_retention/integrations/adapters/storage/databricks.py +76 -0
  174. customer_retention/integrations/adapters/storage/local.py +59 -0
  175. customer_retention/integrations/feature_store/__init__.py +47 -0
  176. customer_retention/integrations/feature_store/definitions.py +215 -0
  177. customer_retention/integrations/feature_store/manager.py +744 -0
  178. customer_retention/integrations/feature_store/registry.py +412 -0
  179. customer_retention/integrations/iteration/__init__.py +28 -0
  180. customer_retention/integrations/iteration/context.py +212 -0
  181. customer_retention/integrations/iteration/feedback_collector.py +184 -0
  182. customer_retention/integrations/iteration/orchestrator.py +168 -0
  183. customer_retention/integrations/iteration/recommendation_tracker.py +341 -0
  184. customer_retention/integrations/iteration/signals.py +212 -0
  185. customer_retention/integrations/llm_context/__init__.py +4 -0
  186. customer_retention/integrations/llm_context/context_builder.py +201 -0
  187. customer_retention/integrations/llm_context/prompts.py +100 -0
  188. customer_retention/integrations/streaming/__init__.py +103 -0
  189. customer_retention/integrations/streaming/batch_integration.py +149 -0
  190. customer_retention/integrations/streaming/early_warning_model.py +227 -0
  191. customer_retention/integrations/streaming/event_schema.py +214 -0
  192. customer_retention/integrations/streaming/online_store_writer.py +249 -0
  193. customer_retention/integrations/streaming/realtime_scorer.py +261 -0
  194. customer_retention/integrations/streaming/trigger_engine.py +293 -0
  195. customer_retention/integrations/streaming/window_aggregator.py +393 -0
  196. customer_retention/stages/__init__.py +0 -0
  197. customer_retention/stages/cleaning/__init__.py +9 -0
  198. customer_retention/stages/cleaning/base.py +28 -0
  199. customer_retention/stages/cleaning/missing_handler.py +160 -0
  200. customer_retention/stages/cleaning/outlier_handler.py +204 -0
  201. customer_retention/stages/deployment/__init__.py +28 -0
  202. customer_retention/stages/deployment/batch_scorer.py +106 -0
  203. customer_retention/stages/deployment/champion_challenger.py +299 -0
  204. customer_retention/stages/deployment/model_registry.py +182 -0
  205. customer_retention/stages/deployment/retraining_trigger.py +245 -0
  206. customer_retention/stages/features/__init__.py +73 -0
  207. customer_retention/stages/features/behavioral_features.py +266 -0
  208. customer_retention/stages/features/customer_segmentation.py +505 -0
  209. customer_retention/stages/features/feature_definitions.py +265 -0
  210. customer_retention/stages/features/feature_engineer.py +551 -0
  211. customer_retention/stages/features/feature_manifest.py +340 -0
  212. customer_retention/stages/features/feature_selector.py +239 -0
  213. customer_retention/stages/features/interaction_features.py +160 -0
  214. customer_retention/stages/features/temporal_features.py +243 -0
  215. customer_retention/stages/ingestion/__init__.py +9 -0
  216. customer_retention/stages/ingestion/load_result.py +32 -0
  217. customer_retention/stages/ingestion/loaders.py +195 -0
  218. customer_retention/stages/ingestion/source_registry.py +130 -0
  219. customer_retention/stages/modeling/__init__.py +31 -0
  220. customer_retention/stages/modeling/baseline_trainer.py +139 -0
  221. customer_retention/stages/modeling/cross_validator.py +125 -0
  222. customer_retention/stages/modeling/data_splitter.py +205 -0
  223. customer_retention/stages/modeling/feature_scaler.py +99 -0
  224. customer_retention/stages/modeling/hyperparameter_tuner.py +107 -0
  225. customer_retention/stages/modeling/imbalance_handler.py +282 -0
  226. customer_retention/stages/modeling/mlflow_logger.py +95 -0
  227. customer_retention/stages/modeling/model_comparator.py +149 -0
  228. customer_retention/stages/modeling/model_evaluator.py +138 -0
  229. customer_retention/stages/modeling/threshold_optimizer.py +131 -0
  230. customer_retention/stages/monitoring/__init__.py +37 -0
  231. customer_retention/stages/monitoring/alert_manager.py +328 -0
  232. customer_retention/stages/monitoring/drift_detector.py +201 -0
  233. customer_retention/stages/monitoring/performance_monitor.py +242 -0
  234. customer_retention/stages/preprocessing/__init__.py +5 -0
  235. customer_retention/stages/preprocessing/transformer_manager.py +284 -0
  236. customer_retention/stages/profiling/__init__.py +256 -0
  237. customer_retention/stages/profiling/categorical_distribution.py +269 -0
  238. customer_retention/stages/profiling/categorical_target_analyzer.py +274 -0
  239. customer_retention/stages/profiling/column_profiler.py +527 -0
  240. customer_retention/stages/profiling/distribution_analysis.py +483 -0
  241. customer_retention/stages/profiling/drift_detector.py +310 -0
  242. customer_retention/stages/profiling/feature_capacity.py +507 -0
  243. customer_retention/stages/profiling/pattern_analysis_config.py +513 -0
  244. customer_retention/stages/profiling/profile_result.py +212 -0
  245. customer_retention/stages/profiling/quality_checks.py +1632 -0
  246. customer_retention/stages/profiling/relationship_detector.py +256 -0
  247. customer_retention/stages/profiling/relationship_recommender.py +454 -0
  248. customer_retention/stages/profiling/report_generator.py +520 -0
  249. customer_retention/stages/profiling/scd_analyzer.py +151 -0
  250. customer_retention/stages/profiling/segment_analyzer.py +632 -0
  251. customer_retention/stages/profiling/segment_aware_outlier.py +265 -0
  252. customer_retention/stages/profiling/target_level_analyzer.py +217 -0
  253. customer_retention/stages/profiling/temporal_analyzer.py +388 -0
  254. customer_retention/stages/profiling/temporal_coverage.py +488 -0
  255. customer_retention/stages/profiling/temporal_feature_analyzer.py +692 -0
  256. customer_retention/stages/profiling/temporal_feature_engineer.py +703 -0
  257. customer_retention/stages/profiling/temporal_pattern_analyzer.py +636 -0
  258. customer_retention/stages/profiling/temporal_quality_checks.py +278 -0
  259. customer_retention/stages/profiling/temporal_target_analyzer.py +241 -0
  260. customer_retention/stages/profiling/text_embedder.py +87 -0
  261. customer_retention/stages/profiling/text_processor.py +115 -0
  262. customer_retention/stages/profiling/text_reducer.py +60 -0
  263. customer_retention/stages/profiling/time_series_profiler.py +303 -0
  264. customer_retention/stages/profiling/time_window_aggregator.py +376 -0
  265. customer_retention/stages/profiling/type_detector.py +382 -0
  266. customer_retention/stages/profiling/window_recommendation.py +288 -0
  267. customer_retention/stages/temporal/__init__.py +166 -0
  268. customer_retention/stages/temporal/access_guard.py +180 -0
  269. customer_retention/stages/temporal/cutoff_analyzer.py +235 -0
  270. customer_retention/stages/temporal/data_preparer.py +178 -0
  271. customer_retention/stages/temporal/point_in_time_join.py +134 -0
  272. customer_retention/stages/temporal/point_in_time_registry.py +148 -0
  273. customer_retention/stages/temporal/scenario_detector.py +163 -0
  274. customer_retention/stages/temporal/snapshot_manager.py +259 -0
  275. customer_retention/stages/temporal/synthetic_coordinator.py +66 -0
  276. customer_retention/stages/temporal/timestamp_discovery.py +531 -0
  277. customer_retention/stages/temporal/timestamp_manager.py +255 -0
  278. customer_retention/stages/transformation/__init__.py +13 -0
  279. customer_retention/stages/transformation/binary_handler.py +85 -0
  280. customer_retention/stages/transformation/categorical_encoder.py +245 -0
  281. customer_retention/stages/transformation/datetime_transformer.py +97 -0
  282. customer_retention/stages/transformation/numeric_transformer.py +181 -0
  283. customer_retention/stages/transformation/pipeline.py +257 -0
  284. customer_retention/stages/validation/__init__.py +60 -0
  285. customer_retention/stages/validation/adversarial_scoring_validator.py +205 -0
  286. customer_retention/stages/validation/business_sense_gate.py +173 -0
  287. customer_retention/stages/validation/data_quality_gate.py +235 -0
  288. customer_retention/stages/validation/data_validators.py +511 -0
  289. customer_retention/stages/validation/feature_quality_gate.py +183 -0
  290. customer_retention/stages/validation/gates.py +117 -0
  291. customer_retention/stages/validation/leakage_gate.py +352 -0
  292. customer_retention/stages/validation/model_validity_gate.py +213 -0
  293. customer_retention/stages/validation/pipeline_validation_runner.py +264 -0
  294. customer_retention/stages/validation/quality_scorer.py +544 -0
  295. customer_retention/stages/validation/rule_generator.py +57 -0
  296. customer_retention/stages/validation/scoring_pipeline_validator.py +446 -0
  297. customer_retention/stages/validation/timeseries_detector.py +769 -0
  298. customer_retention/transforms/__init__.py +47 -0
  299. customer_retention/transforms/artifact_store.py +50 -0
  300. customer_retention/transforms/executor.py +157 -0
  301. customer_retention/transforms/fitted.py +92 -0
  302. customer_retention/transforms/ops.py +148 -0
@@ -0,0 +1,37 @@
1
+ from .databricks_generator import DatabricksSpecGenerator
2
+ from .generic_generator import GenericSpecGenerator
3
+ from .mlflow_pipeline_generator import (
4
+ CleanAction,
5
+ MLflowConfig,
6
+ MLflowPipelineGenerator,
7
+ RecommendationParser,
8
+ TransformAction,
9
+ )
10
+ from .pipeline_spec import (
11
+ ColumnSpec,
12
+ FeatureSpec,
13
+ ModelSpec,
14
+ PipelineSpec,
15
+ QualityGateSpec,
16
+ SchemaSpec,
17
+ SourceSpec,
18
+ TransformSpec,
19
+ )
20
+
21
+ __all__ = [
22
+ "PipelineSpec",
23
+ "SourceSpec",
24
+ "SchemaSpec",
25
+ "ColumnSpec",
26
+ "TransformSpec",
27
+ "FeatureSpec",
28
+ "ModelSpec",
29
+ "QualityGateSpec",
30
+ "GenericSpecGenerator",
31
+ "DatabricksSpecGenerator",
32
+ "MLflowPipelineGenerator",
33
+ "MLflowConfig",
34
+ "RecommendationParser",
35
+ "CleanAction",
36
+ "TransformAction",
37
+ ]
@@ -0,0 +1,433 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Dict, List
4
+
5
+ from .pipeline_spec import PipelineSpec
6
+
7
+
8
+ class DatabricksSpecGenerator:
9
+ def __init__(self,
10
+ catalog: str = "main",
11
+ schema: str = "default",
12
+ output_dir: str = "./databricks_artifacts"):
13
+ self.catalog = catalog
14
+ self.schema = schema
15
+ self.output_dir = Path(output_dir)
16
+
17
+ def generate_lakeflow_connect(self, spec: PipelineSpec) -> dict:
18
+ sources = []
19
+ for source in spec.sources:
20
+ sources.append({
21
+ "name": source.name,
22
+ "type": self._infer_connector_type(source.format),
23
+ "path": source.path,
24
+ "options": source.options
25
+ })
26
+
27
+ return {
28
+ "ingestion": {
29
+ "name": f"{spec.name}_ingestion",
30
+ "version": spec.version,
31
+ "target_catalog": self.catalog,
32
+ "target_schema": self.schema,
33
+ "sources": sources,
34
+ "target_tables": [
35
+ {
36
+ "name": f"{spec.name}_bronze",
37
+ "format": "delta",
38
+ "mode": "append"
39
+ }
40
+ ],
41
+ "schedule": {
42
+ "quartz_cron_expression": "0 0 * * * ?",
43
+ "timezone_id": "UTC"
44
+ }
45
+ }
46
+ }
47
+
48
+ def _infer_connector_type(self, format: str) -> str:
49
+ format_map = {
50
+ "csv": "file",
51
+ "parquet": "file",
52
+ "json": "file",
53
+ "delta": "delta",
54
+ "jdbc": "jdbc",
55
+ "kafka": "kafka"
56
+ }
57
+ return format_map.get(format.lower(), "file")
58
+
59
+ def generate_dlt_pipeline(self, spec: PipelineSpec) -> str:
60
+ lines = [
61
+ "import dlt",
62
+ "from pyspark.sql import functions as F",
63
+ "",
64
+ f"# DLT Pipeline: {spec.name}",
65
+ f"# Version: {spec.version}",
66
+ "",
67
+ ]
68
+
69
+ lines.extend(self._generate_bronze_tables(spec))
70
+ lines.append("")
71
+ lines.extend(self._generate_silver_tables(spec))
72
+ lines.append("")
73
+ lines.extend(self._generate_gold_tables(spec))
74
+
75
+ return "\n".join(lines)
76
+
77
+ def _generate_bronze_tables(self, spec: PipelineSpec) -> List[str]:
78
+ lines = ["# Bronze Layer - Raw Data Ingestion", ""]
79
+
80
+ for source in spec.sources:
81
+ table_name = f"{spec.name}_bronze"
82
+ lines.extend([
83
+ '@dlt.table(',
84
+ f' name="{table_name}",',
85
+ f' comment="Raw data from {source.name}"',
86
+ ')',
87
+ '@dlt.expect_or_drop("valid_record", "1=1")',
88
+ f'def {table_name}():',
89
+ ' return (',
90
+ ' spark.read',
91
+ f' .format("{source.format}")',
92
+ f' .load("{source.path}")',
93
+ ' )',
94
+ ""
95
+ ])
96
+
97
+ return lines
98
+
99
+ def _generate_silver_tables(self, spec: PipelineSpec) -> List[str]:
100
+ lines = ["# Silver Layer - Cleaned and Standardized", ""]
101
+
102
+ table_name = f"{spec.name}_silver"
103
+ bronze_table = f"{spec.name}_bronze"
104
+
105
+ expectations = []
106
+ for gate in spec.quality_gates:
107
+ if gate.gate_type == "null_percentage":
108
+ expectations.append(
109
+ f'@dlt.expect_or_warn("{gate.name}", "{gate.column} IS NOT NULL")'
110
+ )
111
+
112
+ lines.extend([
113
+ '@dlt.table(',
114
+ f' name="{table_name}",',
115
+ ' comment="Cleaned and standardized data"',
116
+ ')',
117
+ ])
118
+ for exp in expectations:
119
+ lines.append(exp)
120
+
121
+ lines.extend([
122
+ f'def {table_name}():',
123
+ f' df = dlt.read("{bronze_table}")',
124
+ ""
125
+ ])
126
+
127
+ if spec.silver_transforms:
128
+ for transform in spec.silver_transforms:
129
+ if transform.transform_type == "standard_scaling":
130
+ col = transform.input_columns[0]
131
+ out_col = transform.output_columns[0]
132
+ lines.append(f' # {transform.name}')
133
+ lines.append(f' df = df.withColumn("{out_col}", F.col("{col}"))')
134
+ elif transform.transform_type == "one_hot_encoding":
135
+ col = transform.input_columns[0]
136
+ lines.append(f' # {transform.name}')
137
+ lines.append(' # Note: One-hot encoding applied in feature engineering')
138
+
139
+ lines.append("")
140
+
141
+ lines.extend([
142
+ ' return df',
143
+ ""
144
+ ])
145
+
146
+ return lines
147
+
148
+ def _generate_gold_tables(self, spec: PipelineSpec) -> List[str]:
149
+ lines = ["# Gold Layer - Feature Engineering", ""]
150
+
151
+ table_name = f"{spec.name}_gold"
152
+ silver_table = f"{spec.name}_silver"
153
+
154
+ lines.extend([
155
+ '@dlt.table(',
156
+ f' name="{table_name}",',
157
+ ' comment="Feature-engineered data ready for modeling"',
158
+ ')',
159
+ f'def {table_name}():',
160
+ f' df = dlt.read("{silver_table}")',
161
+ ""
162
+ ])
163
+
164
+ if spec.feature_definitions:
165
+ for feature in spec.feature_definitions:
166
+ lines.append(f' # Feature: {feature.name}')
167
+ if feature.computation == "days_since_today":
168
+ col = feature.source_columns[0]
169
+ lines.append(
170
+ f' df = df.withColumn("{feature.name}", '
171
+ f'F.datediff(F.current_date(), F.col("{col}")))'
172
+ )
173
+
174
+ lines.append("")
175
+
176
+ lines.extend([
177
+ ' return df',
178
+ ""
179
+ ])
180
+
181
+ return lines
182
+
183
+ def generate_workflow_jobs(self, spec: PipelineSpec) -> dict:
184
+ tasks = [
185
+ {
186
+ "task_key": "run_dlt_pipeline",
187
+ "pipeline_task": {
188
+ "pipeline_id": f"{{{{pipelines.{spec.name}_dlt.id}}}}"
189
+ }
190
+ },
191
+ {
192
+ "task_key": "train_model",
193
+ "depends_on": [{"task_key": "run_dlt_pipeline"}],
194
+ "notebook_task": {
195
+ "notebook_path": f"/Repos/{spec.name}/notebooks/train_model",
196
+ "base_parameters": {
197
+ "catalog": self.catalog,
198
+ "schema": self.schema,
199
+ "table": f"{spec.name}_gold"
200
+ }
201
+ }
202
+ },
203
+ {
204
+ "task_key": "validate_model",
205
+ "depends_on": [{"task_key": "train_model"}],
206
+ "notebook_task": {
207
+ "notebook_path": f"/Repos/{spec.name}/notebooks/validate_model"
208
+ }
209
+ }
210
+ ]
211
+
212
+ return {
213
+ "name": f"{spec.name}_workflow",
214
+ "tasks": tasks,
215
+ "schedule": {
216
+ "quartz_cron_expression": "0 0 0 * * ?",
217
+ "timezone_id": "UTC",
218
+ "pause_status": "UNPAUSED"
219
+ },
220
+ "email_notifications": {
221
+ "on_failure": []
222
+ },
223
+ "max_concurrent_runs": 1,
224
+ "trigger": {
225
+ "periodic": {
226
+ "interval": 1,
227
+ "unit": "DAYS"
228
+ }
229
+ }
230
+ }
231
+
232
+ def generate_feature_tables(self, spec: PipelineSpec) -> str:
233
+ primary_key = None
234
+ if spec.schema and spec.schema.primary_key:
235
+ primary_key = spec.schema.primary_key
236
+
237
+ lines = [
238
+ "from databricks.feature_store import FeatureStoreClient",
239
+ "from databricks.feature_store import FeatureLookup",
240
+ "from pyspark.sql import functions as F",
241
+ "",
242
+ f"# Feature Store Tables for {spec.name}",
243
+ "",
244
+ "fs = FeatureStoreClient()",
245
+ "",
246
+ '# Create feature table',
247
+ f'feature_table_name = "{self.catalog}.{self.schema}.{spec.name}_features"',
248
+ ""
249
+ ]
250
+
251
+ if primary_key:
252
+ lines.extend([
253
+ f'# Define the feature table with primary key: {primary_key}',
254
+ 'fs.create_table(',
255
+ ' name=feature_table_name,',
256
+ f' primary_keys=["{primary_key}"],',
257
+ f' df=spark.table("{self.catalog}.{self.schema}.{spec.name}_gold"),',
258
+ f' description="Features for {spec.name}"',
259
+ ')',
260
+ ""
261
+ ])
262
+ else:
263
+ lines.extend([
264
+ '# Write features to table',
265
+ f'df = spark.table("{self.catalog}.{self.schema}.{spec.name}_gold")',
266
+ 'fs.write_table(',
267
+ ' name=feature_table_name,',
268
+ ' df=df,',
269
+ ' mode="overwrite"',
270
+ ')',
271
+ ""
272
+ ])
273
+
274
+ if spec.feature_definitions:
275
+ lines.extend([
276
+ "# Feature lookups for training",
277
+ "feature_lookups = ["
278
+ ])
279
+ for feature in spec.feature_definitions:
280
+ lines.append(' FeatureLookup(')
281
+ lines.append(' table_name=feature_table_name,')
282
+ lines.append(f' feature_names=["{feature.name}"],')
283
+ if primary_key:
284
+ lines.append(f' lookup_key="{primary_key}"')
285
+ lines.append(' ),')
286
+ lines.append("]")
287
+
288
+ return "\n".join(lines)
289
+
290
+ def generate_mlflow_experiment(self, spec: PipelineSpec) -> str:
291
+ target = spec.model_config.target_column if spec.model_config else "target"
292
+ model_type = spec.model_config.model_type if spec.model_config else "gradient_boosting"
293
+ model_name = spec.model_config.name if spec.model_config else "model"
294
+
295
+ lines = [
296
+ "import mlflow",
297
+ "import mlflow.spark",
298
+ "from pyspark.ml.classification import GBTClassifier, RandomForestClassifier",
299
+ "from pyspark.ml.evaluation import BinaryClassificationEvaluator",
300
+ "",
301
+ f"# MLflow Experiment: {spec.name}",
302
+ "",
303
+ f'mlflow.set_experiment("/Users/{{username}}/{spec.name}_experiment")',
304
+ "",
305
+ f'with mlflow.start_run(run_name="{model_name}"):',
306
+ ' # Load training data',
307
+ f' df = spark.table("{self.catalog}.{self.schema}.{spec.name}_gold")',
308
+ "",
309
+ ' # Log parameters',
310
+ f' mlflow.log_param("target_column", "{target}")',
311
+ f' mlflow.log_param("model_type", "{model_type}")',
312
+ ""
313
+ ]
314
+
315
+ if spec.model_config and spec.model_config.hyperparameters:
316
+ lines.append(" # Log hyperparameters")
317
+ for key, value in spec.model_config.hyperparameters.items():
318
+ lines.append(f' mlflow.log_param("{key}", {repr(value)})')
319
+ lines.append("")
320
+
321
+ lines.extend([
322
+ ' # Train model',
323
+ ' model = GBTClassifier(',
324
+ ' featuresCol="features",',
325
+ f' labelCol="{target}",',
326
+ ' maxIter=100',
327
+ ' )',
328
+ "",
329
+ ' trained_model = model.fit(df)',
330
+ "",
331
+ ' # Log model',
332
+ f' mlflow.spark.log_model(trained_model, "{model_name}")',
333
+ "",
334
+ ' # Register model in Unity Catalog',
335
+ ' mlflow.register_model(',
336
+ f' f"runs/{{mlflow.active_run().info.run_id}}/{model_name}",',
337
+ f' "{self.catalog}.{self.schema}.{spec.name}_model"',
338
+ ' )',
339
+ ])
340
+
341
+ return "\n".join(lines)
342
+
343
+ def generate_unity_catalog_schema(self, spec: PipelineSpec) -> str:
344
+ lines = [
345
+ f"-- Unity Catalog Schema for {spec.name}",
346
+ f"-- Generated from PipelineSpec version {spec.version}",
347
+ "",
348
+ f"CREATE SCHEMA IF NOT EXISTS {self.catalog}.{self.schema};",
349
+ "",
350
+ ]
351
+
352
+ for layer in ["bronze", "silver", "gold"]:
353
+ table_name = f"{spec.name}_{layer}"
354
+ lines.extend([
355
+ f"CREATE OR REPLACE TABLE {self.catalog}.{self.schema}.{table_name} (",
356
+ ])
357
+
358
+ if spec.schema:
359
+ col_defs = []
360
+ for col in spec.schema.columns:
361
+ spark_type = self._to_spark_type(col.data_type)
362
+ nullable = "" if col.nullable else " NOT NULL"
363
+ col_defs.append(f" {col.name} {spark_type}{nullable}")
364
+
365
+ lines.append(",\n".join(col_defs))
366
+
367
+ lines.extend([
368
+ ")",
369
+ "USING DELTA",
370
+ f"COMMENT '{layer.title()} layer table for {spec.name}';",
371
+ ""
372
+ ])
373
+
374
+ return "\n".join(lines)
375
+
376
+ def _to_spark_type(self, data_type: str) -> str:
377
+ type_map = {
378
+ "string": "STRING",
379
+ "integer": "INT",
380
+ "float": "DOUBLE",
381
+ "timestamp": "TIMESTAMP",
382
+ "date": "DATE",
383
+ "boolean": "BOOLEAN"
384
+ }
385
+ return type_map.get(data_type.lower(), "STRING")
386
+
387
+ def generate_all(self, spec: PipelineSpec) -> Dict[str, Any]:
388
+ return {
389
+ "lakeflow_connect": self.generate_lakeflow_connect(spec),
390
+ "dlt_pipeline": self.generate_dlt_pipeline(spec),
391
+ "workflow_jobs": self.generate_workflow_jobs(spec),
392
+ "feature_tables": self.generate_feature_tables(spec),
393
+ "mlflow_experiment": self.generate_mlflow_experiment(spec),
394
+ "unity_catalog_schema": self.generate_unity_catalog_schema(spec)
395
+ }
396
+
397
+ def save_all(self, spec: PipelineSpec) -> List[str]:
398
+ self.output_dir.mkdir(parents=True, exist_ok=True)
399
+ saved_files = []
400
+
401
+ artifacts = self.generate_all(spec)
402
+
403
+ lakeflow_path = self.output_dir / f"{spec.name}_lakeflow_connect.json"
404
+ with open(lakeflow_path, "w") as f:
405
+ json.dump(artifacts["lakeflow_connect"], f, indent=2)
406
+ saved_files.append(str(lakeflow_path))
407
+
408
+ dlt_path = self.output_dir / f"{spec.name}_dlt_pipeline.py"
409
+ with open(dlt_path, "w") as f:
410
+ f.write(artifacts["dlt_pipeline"])
411
+ saved_files.append(str(dlt_path))
412
+
413
+ jobs_path = self.output_dir / f"{spec.name}_workflow_jobs.json"
414
+ with open(jobs_path, "w") as f:
415
+ json.dump(artifacts["workflow_jobs"], f, indent=2)
416
+ saved_files.append(str(jobs_path))
417
+
418
+ features_path = self.output_dir / f"{spec.name}_feature_tables.py"
419
+ with open(features_path, "w") as f:
420
+ f.write(artifacts["feature_tables"])
421
+ saved_files.append(str(features_path))
422
+
423
+ mlflow_path = self.output_dir / f"{spec.name}_mlflow_experiment.py"
424
+ with open(mlflow_path, "w") as f:
425
+ f.write(artifacts["mlflow_experiment"])
426
+ saved_files.append(str(mlflow_path))
427
+
428
+ schema_path = self.output_dir / f"{spec.name}_unity_catalog.sql"
429
+ with open(schema_path, "w") as f:
430
+ f.write(artifacts["unity_catalog_schema"])
431
+ saved_files.append(str(schema_path))
432
+
433
+ return saved_files