datacompose 0.2.4.1__py3-none-any.whl → 0.2.6.0__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.
Potentially problematic release.
This version of datacompose might be problematic. Click here for more details.
- datacompose/cli/__init__.py +1 -1
- datacompose/cli/commands/add.py +49 -21
- datacompose/cli/commands/init.py +35 -9
- datacompose/cli/commands/list.py +2 -2
- datacompose/cli/config.py +80 -0
- datacompose/cli/main.py +3 -3
- datacompose/generators/base.py +15 -14
- datacompose/generators/pyspark/generator.py +5 -10
- datacompose/operators/__init__.py +1 -1
- datacompose/operators/primitives.py +57 -19
- datacompose/transformers/text/{clean_addresses → addresses}/pyspark/pyspark_primitives.py +68 -13
- datacompose/transformers/text/{clean_emails → emails}/pyspark/pyspark_primitives.py +53 -1
- datacompose/transformers/text/{clean_phone_numbers → phone_numbers}/pyspark/pyspark_primitives.py +416 -366
- datacompose-0.2.6.0.dist-info/METADATA +94 -0
- datacompose-0.2.6.0.dist-info/RECORD +31 -0
- datacompose-0.2.4.1.dist-info/METADATA +0 -449
- datacompose-0.2.4.1.dist-info/RECORD +0 -30
- /datacompose/transformers/text/{clean_addresses → addresses}/__init__.py +0 -0
- /datacompose/transformers/text/{clean_emails → emails}/__init__.py +0 -0
- /datacompose/transformers/text/{clean_phone_numbers → phone_numbers}/__init__.py +0 -0
- {datacompose-0.2.4.1.dist-info → datacompose-0.2.6.0.dist-info}/WHEEL +0 -0
- {datacompose-0.2.4.1.dist-info → datacompose-0.2.6.0.dist-info}/entry_points.txt +0 -0
- {datacompose-0.2.4.1.dist-info → datacompose-0.2.6.0.dist-info}/licenses/LICENSE +0 -0
- {datacompose-0.2.4.1.dist-info → datacompose-0.2.6.0.dist-info}/top_level.txt +0 -0
datacompose/cli/__init__.py
CHANGED
datacompose/cli/commands/add.py
CHANGED
|
@@ -7,6 +7,7 @@ from pathlib import Path
|
|
|
7
7
|
import click
|
|
8
8
|
|
|
9
9
|
from datacompose.cli.colors import dim, error, highlight, info, success
|
|
10
|
+
from datacompose.cli.config import ConfigLoader
|
|
10
11
|
from datacompose.cli.validation import validate_platform, validate_type_for_platform
|
|
11
12
|
from datacompose.transformers.discovery import TransformerDiscovery
|
|
12
13
|
|
|
@@ -85,28 +86,48 @@ _MODULE_DIR = Path(__file__).parent
|
|
|
85
86
|
@click.option(
|
|
86
87
|
"--target",
|
|
87
88
|
"-t",
|
|
88
|
-
default=
|
|
89
|
+
default=None,
|
|
89
90
|
shell_complete=complete_target,
|
|
90
|
-
help="Target platform (e.g., 'pyspark', 'postgres', 'snowflake').
|
|
91
|
+
help="Target platform (e.g., 'pyspark', 'postgres', 'snowflake'). Uses default from datacompose.json if not specified",
|
|
91
92
|
)
|
|
92
93
|
@click.option(
|
|
93
94
|
"--type",
|
|
94
95
|
shell_complete=complete_type,
|
|
95
96
|
help="UDF type for the platform (e.g., 'pandas_udf', 'sql_udf'). Uses platform default if not specified",
|
|
96
97
|
)
|
|
97
|
-
@click.option("--output", "-o", help="Output directory (default: build/{target})")
|
|
98
98
|
@click.option(
|
|
99
|
-
"--
|
|
100
|
-
|
|
101
|
-
help="
|
|
99
|
+
"--output",
|
|
100
|
+
"-o",
|
|
101
|
+
help="Output directory (default: from config or transformers/{target})",
|
|
102
102
|
)
|
|
103
103
|
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
|
|
104
104
|
@click.pass_context
|
|
105
|
-
def add(ctx, transformer, target, type, output,
|
|
105
|
+
def add(ctx, transformer, target, type, output, verbose):
|
|
106
106
|
"""Add UDFs for transformers.
|
|
107
107
|
|
|
108
|
-
TRANSFORMER: Transformer to add UDF for (e.g., '
|
|
108
|
+
TRANSFORMER: Transformer to add UDF for (e.g., 'emails')
|
|
109
109
|
"""
|
|
110
|
+
# Load config to get default target if not specified
|
|
111
|
+
config = ConfigLoader.load_config()
|
|
112
|
+
|
|
113
|
+
if target is None:
|
|
114
|
+
# Try to get default target from config
|
|
115
|
+
target = ConfigLoader.get_default_target(config)
|
|
116
|
+
if target is None:
|
|
117
|
+
print(
|
|
118
|
+
error(
|
|
119
|
+
"Error: No target specified and no default target found in datacompose.json"
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
print(
|
|
123
|
+
info(
|
|
124
|
+
"Please specify a target with --target or run 'datacompose init' to set up defaults"
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
ctx.exit(1)
|
|
128
|
+
elif verbose:
|
|
129
|
+
print(dim(f"Using default target from config: {target}"))
|
|
130
|
+
|
|
110
131
|
# Initialize discovery for validation
|
|
111
132
|
discovery = TransformerDiscovery()
|
|
112
133
|
|
|
@@ -119,12 +140,12 @@ def add(ctx, transformer, target, type, output, template_dir, verbose):
|
|
|
119
140
|
ctx.exit(1)
|
|
120
141
|
|
|
121
142
|
# Combine target and type into generator reference
|
|
122
|
-
exit_code = _run_add(transformer, target, output,
|
|
143
|
+
exit_code = _run_add(transformer, target, output, verbose)
|
|
123
144
|
if exit_code != 0:
|
|
124
145
|
ctx.exit(exit_code)
|
|
125
146
|
|
|
126
147
|
|
|
127
|
-
def _run_add(transformer, target, output,
|
|
148
|
+
def _run_add(transformer, target, output, verbose) -> int:
|
|
128
149
|
"""Execute the add command."""
|
|
129
150
|
# Initialize discovery
|
|
130
151
|
discovery = TransformerDiscovery()
|
|
@@ -135,9 +156,7 @@ def _run_add(transformer, target, output, template_dir, verbose) -> int:
|
|
|
135
156
|
if not transformer_path:
|
|
136
157
|
print(error(f"Error: Transformer not found: {transformer}"))
|
|
137
158
|
print(
|
|
138
|
-
info(
|
|
139
|
-
f"Available transformers: {', '.join(discovery.list_transformers())}"
|
|
140
|
-
)
|
|
159
|
+
info(f"Available transformers: {', '.join(discovery.list_transformers())}")
|
|
141
160
|
)
|
|
142
161
|
return 1
|
|
143
162
|
else:
|
|
@@ -154,18 +173,28 @@ def _run_add(transformer, target, output, template_dir, verbose) -> int:
|
|
|
154
173
|
print(info(f"Available generators: {', '.join(discovery.list_generators())}"))
|
|
155
174
|
return 1
|
|
156
175
|
|
|
157
|
-
# Determine output directory
|
|
176
|
+
# Determine output directory
|
|
158
177
|
if not output:
|
|
159
|
-
|
|
178
|
+
# Try to get output from config first
|
|
179
|
+
config = ConfigLoader.load_config()
|
|
180
|
+
config_output = ConfigLoader.get_target_output(config, target)
|
|
181
|
+
if config_output:
|
|
182
|
+
# Config output already includes 'transformers/pyspark', so use it directly
|
|
183
|
+
output_dir = config_output
|
|
184
|
+
else:
|
|
185
|
+
output_dir = f"transformers/{target}"
|
|
160
186
|
else:
|
|
161
|
-
output_dir =
|
|
187
|
+
output_dir = output
|
|
162
188
|
|
|
163
189
|
try:
|
|
164
190
|
# Create generator instance
|
|
191
|
+
# Note: template_dir is required by base class but not used by current generators
|
|
165
192
|
generator = generator_class(
|
|
166
|
-
template_dir=Path(
|
|
193
|
+
template_dir=Path("."), # Placeholder - not actually used
|
|
194
|
+
output_dir=Path(output_dir),
|
|
195
|
+
verbose=verbose,
|
|
167
196
|
)
|
|
168
|
-
|
|
197
|
+
|
|
169
198
|
# Generate the UDF
|
|
170
199
|
result = generator.generate(
|
|
171
200
|
transformer_name, force=False, transformer_dir=transformer_dir
|
|
@@ -178,14 +207,14 @@ def _run_add(transformer, target, output, template_dir, verbose) -> int:
|
|
|
178
207
|
print(dim(f" Hash: {result.get('hash', 'N/A')}"))
|
|
179
208
|
else:
|
|
180
209
|
print(success(f"✓ UDF generated: {result['output_path']}"))
|
|
181
|
-
if result.get(
|
|
210
|
+
if result.get("test_path"):
|
|
182
211
|
print(success(f"✓ Test created: {result['test_path']}"))
|
|
183
212
|
print(highlight(f"Function name: {result['function_name']}"))
|
|
184
213
|
if verbose:
|
|
185
214
|
print(dim(f" Target: {target}"))
|
|
186
215
|
print(highlight("\nGenerated package contents:"))
|
|
187
216
|
print(f" - UDF code: {result['output_path']}")
|
|
188
|
-
if result.get(
|
|
217
|
+
if result.get("test_path"):
|
|
189
218
|
print(f" - Test file: {result['test_path']}")
|
|
190
219
|
|
|
191
220
|
return 0
|
|
@@ -197,4 +226,3 @@ def _run_add(transformer, target, output, template_dir, verbose) -> int:
|
|
|
197
226
|
|
|
198
227
|
traceback.print_exc()
|
|
199
228
|
return 1
|
|
200
|
-
|
datacompose/cli/commands/init.py
CHANGED
|
@@ -18,10 +18,11 @@ from datacompose.cli.colors import dim, error, highlight, info, success
|
|
|
18
18
|
|
|
19
19
|
DEFAULT_CONFIG = {
|
|
20
20
|
"version": "1.0",
|
|
21
|
+
"default_target": "pyspark",
|
|
21
22
|
"aliases": {"utils": "./src/utils"},
|
|
22
23
|
"targets": {
|
|
23
24
|
"pyspark": {
|
|
24
|
-
"output": "./
|
|
25
|
+
"output": "./transformers/pyspark",
|
|
25
26
|
}
|
|
26
27
|
},
|
|
27
28
|
}
|
|
@@ -57,7 +58,7 @@ class InitCommand:
|
|
|
57
58
|
def get_config_template(template_name: str) -> Dict[str, Any]:
|
|
58
59
|
"""Get configuration template by name."""
|
|
59
60
|
if template_name == "minimal":
|
|
60
|
-
return {"version": "1.0", "targets": {"pyspark": {"output": "./
|
|
61
|
+
return {"version": "1.0", "default_target": "pyspark", "targets": {"pyspark": {"output": "./transformers/pyspark"}}}
|
|
61
62
|
elif template_name == "advanced":
|
|
62
63
|
config = DEFAULT_CONFIG.copy()
|
|
63
64
|
config.update(
|
|
@@ -65,10 +66,10 @@ class InitCommand:
|
|
|
65
66
|
"style": "custom",
|
|
66
67
|
"aliases": {
|
|
67
68
|
"utils": "./src/utils",
|
|
68
|
-
"
|
|
69
|
+
"transformers": "./transformers",
|
|
69
70
|
},
|
|
70
71
|
"include": ["src/**/*"],
|
|
71
|
-
"exclude": ["__pycache__", "
|
|
72
|
+
"exclude": ["__pycache__", "transformers", "*.pyc", ".pytest_cache"],
|
|
72
73
|
"testing": {"framework": "pytest", "test_dir": "./tests"},
|
|
73
74
|
}
|
|
74
75
|
)
|
|
@@ -184,7 +185,7 @@ class InitCommand:
|
|
|
184
185
|
|
|
185
186
|
# Select targets with multi-select
|
|
186
187
|
available_targets = {
|
|
187
|
-
"pyspark": {"output": "./
|
|
188
|
+
"pyspark": {"output": "./transformers/pyspark", "name": "PySpark (Apache Spark)"},
|
|
188
189
|
}
|
|
189
190
|
|
|
190
191
|
selected_targets = InitCommand.prompt_for_targets(available_targets)
|
|
@@ -199,6 +200,31 @@ class InitCommand:
|
|
|
199
200
|
|
|
200
201
|
# Update targets with user selections
|
|
201
202
|
config["targets"] = selected_targets
|
|
203
|
+
|
|
204
|
+
# Set default target to the first selected target (or only target if single)
|
|
205
|
+
target_keys = list(selected_targets.keys())
|
|
206
|
+
if len(target_keys) == 1:
|
|
207
|
+
config["default_target"] = target_keys[0]
|
|
208
|
+
elif len(target_keys) > 1:
|
|
209
|
+
# Ask user to select default target
|
|
210
|
+
print(highlight("\nSelect Default Target"))
|
|
211
|
+
print(dim("Which platform should be used by default when running 'datacompose add'?\n"))
|
|
212
|
+
for i, key in enumerate(target_keys, 1):
|
|
213
|
+
print(f" {i}. {key}")
|
|
214
|
+
print()
|
|
215
|
+
|
|
216
|
+
while True:
|
|
217
|
+
choice = input(f"Select default target (1-{len(target_keys)}): ").strip()
|
|
218
|
+
try:
|
|
219
|
+
choice_idx = int(choice) - 1
|
|
220
|
+
if 0 <= choice_idx < len(target_keys):
|
|
221
|
+
config["default_target"] = target_keys[choice_idx]
|
|
222
|
+
print(dim(f"Default target set to: {target_keys[choice_idx]}\n"))
|
|
223
|
+
break
|
|
224
|
+
else:
|
|
225
|
+
print(error("Invalid selection. Please try again."))
|
|
226
|
+
except ValueError:
|
|
227
|
+
print(error("Please enter a number."))
|
|
202
228
|
|
|
203
229
|
print() # Add spacing
|
|
204
230
|
return config
|
|
@@ -403,11 +429,11 @@ def _run_init(force, output, verbose, yes, skip_completion) -> int:
|
|
|
403
429
|
"2. Source your shell config or restart terminal for tab completion"
|
|
404
430
|
)
|
|
405
431
|
print(
|
|
406
|
-
"3. Add your first transformer: datacompose add
|
|
432
|
+
"3. Add your first transformer: datacompose add emails"
|
|
407
433
|
)
|
|
408
434
|
else:
|
|
409
435
|
print(
|
|
410
|
-
"2. Add your first transformer: datacompose add
|
|
436
|
+
"2. Add your first transformer: datacompose add emails"
|
|
411
437
|
)
|
|
412
438
|
if not skip_completion:
|
|
413
439
|
print(
|
|
@@ -419,7 +445,7 @@ def _run_init(force, output, verbose, yes, skip_completion) -> int:
|
|
|
419
445
|
print(success("✓ Tab completion configured"))
|
|
420
446
|
print(
|
|
421
447
|
highlight(
|
|
422
|
-
"\nRun 'datacompose add
|
|
448
|
+
"\nRun 'datacompose add emails' to get started"
|
|
423
449
|
)
|
|
424
450
|
)
|
|
425
451
|
print(
|
|
@@ -430,7 +456,7 @@ def _run_init(force, output, verbose, yes, skip_completion) -> int:
|
|
|
430
456
|
else:
|
|
431
457
|
print(
|
|
432
458
|
highlight(
|
|
433
|
-
"\nRun 'datacompose add
|
|
459
|
+
"\nRun 'datacompose add emails' to get started"
|
|
434
460
|
)
|
|
435
461
|
)
|
|
436
462
|
if not skip_completion and not yes:
|
datacompose/cli/commands/list.py
CHANGED
|
@@ -95,7 +95,7 @@ class ListCommand:
|
|
|
95
95
|
print(f" • {transformer_name}")
|
|
96
96
|
|
|
97
97
|
print("\nUsage: datacompose add <transformer> --target <platform> [--type <type>]")
|
|
98
|
-
print("Example: datacompose add
|
|
98
|
+
print("Example: datacompose add emails --target pyspark")
|
|
99
99
|
return 0
|
|
100
100
|
|
|
101
101
|
@staticmethod
|
|
@@ -114,5 +114,5 @@ class ListCommand:
|
|
|
114
114
|
print(f" • {gen_type} ({gen_class.__name__})")
|
|
115
115
|
|
|
116
116
|
print("\nUsage: datacompose add <transformer> --target <platform> [--type <type>]")
|
|
117
|
-
print("Example: datacompose add
|
|
117
|
+
print("Example: datacompose add emails --target pyspark")
|
|
118
118
|
return 0
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration management for Datacompose CLI.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConfigLoader:
|
|
11
|
+
"""Load and manage Datacompose configuration."""
|
|
12
|
+
|
|
13
|
+
DEFAULT_CONFIG_FILE = "datacompose.json"
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def load_config(config_path: Optional[Path] = None) -> Optional[Dict[str, Any]]:
|
|
17
|
+
"""Load configuration from datacompose.json.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
config_path: Optional path to config file. Defaults to ./datacompose.json
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
Config dictionary or None if not found
|
|
24
|
+
"""
|
|
25
|
+
if config_path is None:
|
|
26
|
+
config_path = Path(ConfigLoader.DEFAULT_CONFIG_FILE)
|
|
27
|
+
|
|
28
|
+
if not config_path.exists():
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
with open(config_path, 'r') as f:
|
|
33
|
+
return json.load(f)
|
|
34
|
+
except (json.JSONDecodeError, IOError):
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def get_default_target(config: Optional[Dict[str, Any]] = None) -> Optional[str]:
|
|
39
|
+
"""Get the default target from config.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
config: Optional config dict. If None, will load from file.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
Default target name or None
|
|
46
|
+
"""
|
|
47
|
+
if config is None:
|
|
48
|
+
config = ConfigLoader.load_config()
|
|
49
|
+
|
|
50
|
+
if not config:
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
# Check for explicit default_target setting
|
|
54
|
+
if "default_target" in config:
|
|
55
|
+
return config["default_target"]
|
|
56
|
+
|
|
57
|
+
# Otherwise use the first target if only one exists
|
|
58
|
+
targets = config.get("targets", {})
|
|
59
|
+
if len(targets) == 1:
|
|
60
|
+
return list(targets.keys())[0]
|
|
61
|
+
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def get_target_output(config: Optional[Dict[str, Any]], target: str) -> Optional[str]:
|
|
66
|
+
"""Get the output directory for a specific target.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
config: Config dictionary
|
|
70
|
+
target: Target name
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Output directory path or None
|
|
74
|
+
"""
|
|
75
|
+
if not config:
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
targets = config.get("targets", {})
|
|
79
|
+
target_config = targets.get(target, {})
|
|
80
|
+
return target_config.get("output")
|
datacompose/cli/main.py
CHANGED
|
@@ -25,9 +25,9 @@ def cli(ctx):
|
|
|
25
25
|
"""Generate data cleaning UDFs for various platforms.
|
|
26
26
|
|
|
27
27
|
Examples:
|
|
28
|
-
datacompose init
|
|
29
|
-
datacompose add
|
|
30
|
-
datacompose add
|
|
28
|
+
datacompose init # Set up project with default target
|
|
29
|
+
datacompose add emails # Uses default target from config
|
|
30
|
+
datacompose add emails --target snowflake --output sql/udfs/
|
|
31
31
|
datacompose list targets
|
|
32
32
|
"""
|
|
33
33
|
pass
|
datacompose/generators/base.py
CHANGED
|
@@ -105,14 +105,14 @@ class BaseGenerator(ABC):
|
|
|
105
105
|
|
|
106
106
|
def _ensure_init_files(self, output_path: Path):
|
|
107
107
|
"""Ensure __init__.py files exist to make directories importable."""
|
|
108
|
-
# Get all directories from
|
|
108
|
+
# Get all directories from transformers down to the target directory
|
|
109
109
|
path_parts = output_path.parts
|
|
110
110
|
|
|
111
|
-
# Find the
|
|
111
|
+
# Find the transformers directory index
|
|
112
112
|
try:
|
|
113
|
-
|
|
113
|
+
transformers_index = path_parts.index("transformers")
|
|
114
114
|
except ValueError:
|
|
115
|
-
# No
|
|
115
|
+
# No transformers directory found, just create init for immediate parent
|
|
116
116
|
init_file = output_path.parent / "__init__.py"
|
|
117
117
|
if not init_file.exists():
|
|
118
118
|
init_file.touch()
|
|
@@ -120,9 +120,9 @@ class BaseGenerator(ABC):
|
|
|
120
120
|
print(f"Created {init_file}")
|
|
121
121
|
return
|
|
122
122
|
|
|
123
|
-
# Create __init__.py files for
|
|
123
|
+
# Create __init__.py files for transformers and all subdirectories leading to output
|
|
124
124
|
for i in range(
|
|
125
|
-
|
|
125
|
+
transformers_index, len(path_parts) - 1
|
|
126
126
|
): # -1 to exclude the file itself
|
|
127
127
|
dir_path = Path(*path_parts[: i + 1])
|
|
128
128
|
init_file = dir_path / "__init__.py"
|
|
@@ -133,18 +133,19 @@ class BaseGenerator(ABC):
|
|
|
133
133
|
|
|
134
134
|
|
|
135
135
|
def _copy_utils_files(self, output_path: Path):
|
|
136
|
-
"""Copy utility files like primitives.py to the
|
|
137
|
-
# Find the
|
|
136
|
+
"""Copy utility files like primitives.py to the transformers directory."""
|
|
137
|
+
# Find the transformers directory root
|
|
138
138
|
path_parts = output_path.parts
|
|
139
139
|
try:
|
|
140
|
-
|
|
141
|
-
|
|
140
|
+
transformers_index = path_parts.index("transformers")
|
|
141
|
+
transformers_root = Path(*path_parts[:transformers_index + 1])
|
|
142
142
|
except ValueError:
|
|
143
|
-
# Fallback to parent directory if no '
|
|
144
|
-
|
|
143
|
+
# Fallback to parent directory if no 'transformers' in path
|
|
144
|
+
transformers_root = output_path.parent.parent
|
|
145
145
|
|
|
146
|
-
# Create utils directory
|
|
147
|
-
|
|
146
|
+
# Create utils directory in the same directory as the generated files
|
|
147
|
+
# This puts it at transformers/pyspark/utils
|
|
148
|
+
utils_dir = output_path.parent / "utils"
|
|
148
149
|
utils_dir.mkdir(parents=True, exist_ok=True)
|
|
149
150
|
|
|
150
151
|
# Create __init__.py in utils directory
|
|
@@ -39,13 +39,8 @@ class SparkPandasUDFGenerator(BaseGenerator):
|
|
|
39
39
|
|
|
40
40
|
def _get_output_filename(self, transformer_name: str) -> str:
|
|
41
41
|
"""Get the output filename for PySpark primitives."""
|
|
42
|
-
#
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
# Use mapped name if available, otherwise fall back to transformer_name
|
|
50
|
-
output_name = name_mapping.get(transformer_name, f"{transformer_name}_primitives")
|
|
51
|
-
return f"{output_name}.py"
|
|
42
|
+
# Use the transformer name directly as the filename
|
|
43
|
+
# emails -> emails.py
|
|
44
|
+
# addresses -> addresses.py
|
|
45
|
+
# phone_numbers -> phone_numbers.py
|
|
46
|
+
return f"{transformer_name}.py"
|
|
@@ -16,9 +16,13 @@ from typing import Any, Callable, Dict, List, Optional, Sequence
|
|
|
16
16
|
logger = logging.getLogger(__name__)
|
|
17
17
|
|
|
18
18
|
try:
|
|
19
|
-
from pyspark.sql import Column
|
|
19
|
+
from pyspark.sql import Column
|
|
20
|
+
from pyspark.sql import functions as F
|
|
20
21
|
except ImportError:
|
|
21
|
-
|
|
22
|
+
logging.debug("PySpark not available")
|
|
23
|
+
|
|
24
|
+
# Set up module logger
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
22
26
|
|
|
23
27
|
|
|
24
28
|
class SmartPrimitive:
|
|
@@ -120,11 +124,15 @@ class PrimitiveRegistry:
|
|
|
120
124
|
self._primitives = {}
|
|
121
125
|
self._conditionals = {}
|
|
122
126
|
|
|
123
|
-
def register(
|
|
127
|
+
def register(
|
|
128
|
+
self, name: Optional[str] = None, is_conditional: Optional[bool] = None
|
|
129
|
+
):
|
|
124
130
|
"""Decorator to register a function as a SmartPrimitive in this namespace.
|
|
125
131
|
|
|
126
132
|
Args:
|
|
127
133
|
name: Optional name for the primitive (defaults to function name)
|
|
134
|
+
is_conditional: Optional flag to mark as conditional. If None, auto-detects
|
|
135
|
+
based on function name patterns.
|
|
128
136
|
|
|
129
137
|
Returns:
|
|
130
138
|
Decorator function that wraps the target function as a SmartPrimitive
|
|
@@ -139,7 +147,29 @@ class PrimitiveRegistry:
|
|
|
139
147
|
def decorator(func: Callable):
|
|
140
148
|
primitive_name = name or func.__name__
|
|
141
149
|
|
|
142
|
-
if
|
|
150
|
+
# Auto-detect conditional if not explicitly specified
|
|
151
|
+
if is_conditional is None:
|
|
152
|
+
# Check common naming patterns for conditional functions
|
|
153
|
+
conditional_patterns = [
|
|
154
|
+
"is_",
|
|
155
|
+
"has_",
|
|
156
|
+
"needs_",
|
|
157
|
+
"should_",
|
|
158
|
+
"can_",
|
|
159
|
+
"contains_",
|
|
160
|
+
"matches_",
|
|
161
|
+
"equals_",
|
|
162
|
+
"starts_with_",
|
|
163
|
+
"ends_with_",
|
|
164
|
+
]
|
|
165
|
+
is_conditional_auto = any(
|
|
166
|
+
primitive_name.startswith(pattern)
|
|
167
|
+
for pattern in conditional_patterns
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
is_conditional_auto = is_conditional
|
|
171
|
+
|
|
172
|
+
if is_conditional_auto:
|
|
143
173
|
self._conditionals[primitive_name] = SmartPrimitive(
|
|
144
174
|
func, primitive_name
|
|
145
175
|
)
|
|
@@ -217,9 +247,17 @@ class PrimitiveRegistry:
|
|
|
217
247
|
pipeline.__doc__ = func.__doc__
|
|
218
248
|
return pipeline
|
|
219
249
|
|
|
250
|
+
# Auto-detect ALL namespace instances from func.__globals__
|
|
251
|
+
# This allows using multiple namespaces without explicitly passing them
|
|
252
|
+
for var_name, var_value in func.__globals__.items():
|
|
253
|
+
if isinstance(var_value, PrimitiveRegistry):
|
|
254
|
+
# Found a namespace instance
|
|
255
|
+
if var_name not in namespaces:
|
|
256
|
+
namespaces[var_name] = var_value
|
|
257
|
+
|
|
220
258
|
# Try to get the function as a string and parse it
|
|
221
259
|
try:
|
|
222
|
-
compiler = PipelineCompiler(namespaces, debug)
|
|
260
|
+
compiler = PipelineCompiler(namespaces, debug, func.__globals__)
|
|
223
261
|
pipeline = compiler.compile(func)
|
|
224
262
|
|
|
225
263
|
if debug and pipeline.steps:
|
|
@@ -270,7 +308,11 @@ def _fallback_compose(func: Callable, namespaces: Dict, debug: bool) -> Callable
|
|
|
270
308
|
method_name = node.value.func.attr
|
|
271
309
|
namespace = (
|
|
272
310
|
namespaces.get(namespace_name) if namespace_name else None
|
|
273
|
-
) or (
|
|
311
|
+
) or (
|
|
312
|
+
func.__globals__.get(namespace_name)
|
|
313
|
+
if namespace_name
|
|
314
|
+
else None
|
|
315
|
+
)
|
|
274
316
|
if namespace and hasattr(namespace, method_name):
|
|
275
317
|
method = getattr(namespace, method_name)
|
|
276
318
|
|
|
@@ -312,16 +354,6 @@ def _fallback_compose(func: Callable, namespaces: Dict, debug: bool) -> Callable
|
|
|
312
354
|
return pipeline
|
|
313
355
|
|
|
314
356
|
|
|
315
|
-
try:
|
|
316
|
-
from pyspark.sql import Column
|
|
317
|
-
from pyspark.sql import functions as F
|
|
318
|
-
except ImportError:
|
|
319
|
-
logging.debug("PySpark not available")
|
|
320
|
-
|
|
321
|
-
# Set up module logger
|
|
322
|
-
logger = logging.getLogger(__name__)
|
|
323
|
-
|
|
324
|
-
|
|
325
357
|
@dataclass
|
|
326
358
|
class CompiledStep:
|
|
327
359
|
"""A compiled pipeline step"""
|
|
@@ -452,9 +484,15 @@ class StablePipeline:
|
|
|
452
484
|
|
|
453
485
|
|
|
454
486
|
class PipelineCompiler:
|
|
455
|
-
def __init__(
|
|
487
|
+
def __init__(
|
|
488
|
+
self,
|
|
489
|
+
namespaces: Dict[str, Any],
|
|
490
|
+
debug: bool = False,
|
|
491
|
+
func_globals: Optional[Dict] = None,
|
|
492
|
+
):
|
|
456
493
|
self.namespaces = namespaces
|
|
457
494
|
self.debug = debug
|
|
495
|
+
self.func_globals = func_globals or {}
|
|
458
496
|
|
|
459
497
|
def compile(self, func: Callable) -> StablePipeline:
|
|
460
498
|
try:
|
|
@@ -530,7 +568,7 @@ class PipelineCompiler:
|
|
|
530
568
|
|
|
531
569
|
namespace = (
|
|
532
570
|
self.namespaces.get(namespace_name) if namespace_name else None
|
|
533
|
-
) or (
|
|
571
|
+
) or (self.func_globals.get(namespace_name) if namespace_name else None)
|
|
534
572
|
if namespace and hasattr(namespace, method_name):
|
|
535
573
|
method = getattr(namespace, method_name)
|
|
536
574
|
|
|
@@ -552,7 +590,7 @@ class PipelineCompiler:
|
|
|
552
590
|
|
|
553
591
|
namespace = (
|
|
554
592
|
self.namespaces.get(namespace_name) if namespace_name else None
|
|
555
|
-
) or (
|
|
593
|
+
) or (self.func_globals.get(namespace_name) if namespace_name else None)
|
|
556
594
|
if namespace and hasattr(namespace, method_name):
|
|
557
595
|
method = getattr(namespace, method_name)
|
|
558
596
|
|