nkparser 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: nkparser
3
+ Version: 0.1.0
4
+ Summary: Parse, query, and serialize Foundry Nuke .nk script files
5
+ Author-email: Virgil Sisoe <28490646+sisoe24@users.noreply.github.com>
6
+ Requires-Python: >=3.10
7
+ Provides-Extra: dev
8
+ Requires-Dist: mypy; extra == 'dev'
9
+ Requires-Dist: pytest-cov; extra == 'dev'
10
+ Requires-Dist: pytest>=7; extra == 'dev'
11
+ Provides-Extra: graphviz
12
+ Requires-Dist: graphviz>=0.20; extra == 'graphviz'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # nkparser
16
+
17
+ `nkparser` parses, queries, validates, and round-trips Foundry Nuke `.nk` script files.
18
+
19
+ ## Install
20
+
21
+ This project is managed with `uv`.
22
+
23
+ ```bash
24
+ uv sync
25
+ ```
26
+
27
+ Install the package into the current environment:
28
+
29
+ ```bash
30
+ uv pip install .
31
+ ```
32
+
33
+ Install with Graphviz rendering support:
34
+
35
+ ```bash
36
+ uv pip install '.[graphviz]'
37
+ ```
38
+
39
+ ## CLI
40
+
41
+ The package exposes two console scripts:
42
+
43
+ ```bash
44
+ uv run nkparser --help
45
+ uv run nkparse --help
46
+ ```
47
+
48
+ You can also run it as a module:
49
+
50
+ ```bash
51
+ uv run python -m nkparser --help
52
+ ```
53
+
54
+ ### Examples
55
+
56
+ ```bash
57
+ uv run nkparser info tests/fixtures/minimal.nk
58
+ uv run nkparser validate tests/fixtures/malformed_unclosed.nk
59
+ uv run nkparser tree tests/fixtures/complex_groups.nk --knobs
60
+ uv run nkparser nodes tests/fixtures/minimal.nk --class Grade
61
+ uv run nkparser dot tests/fixtures/minimal.nk -o graph.dot
62
+ uv run nkparser dot tests/fixtures/minimal.nk -o graph.dot --render --dot-command /opt/homebrew/bin/dot
63
+ ```
64
+
65
+ ## Development
66
+
67
+ Sync the dev environment:
68
+
69
+ ```bash
70
+ uv sync --dev
71
+ ```
72
+
73
+ Run checks:
74
+
75
+ ```bash
76
+ uv run pytest
77
+ uv run ruff check .
78
+ uv run mypy
79
+ ```
80
+
81
+ Build distributions:
82
+
83
+ ```bash
84
+ uv build
85
+ ```
86
+
87
+ ## Python API
88
+
89
+ ```python
90
+ import nkparser
91
+
92
+ script = nkparser.Script.from_file("comp.nk")
93
+
94
+ print(script.nuke_version)
95
+ print(len(list(script.all_nodes())))
96
+
97
+ reads = script.query().of_class("Read").all()
98
+ grade = script.find("Grade1")
99
+
100
+ if grade:
101
+ grade.set("disable", "true")
102
+
103
+ script.write("comp_modified.nk")
104
+ ```
@@ -0,0 +1,90 @@
1
+ # nkparser
2
+
3
+ `nkparser` parses, queries, validates, and round-trips Foundry Nuke `.nk` script files.
4
+
5
+ ## Install
6
+
7
+ This project is managed with `uv`.
8
+
9
+ ```bash
10
+ uv sync
11
+ ```
12
+
13
+ Install the package into the current environment:
14
+
15
+ ```bash
16
+ uv pip install .
17
+ ```
18
+
19
+ Install with Graphviz rendering support:
20
+
21
+ ```bash
22
+ uv pip install '.[graphviz]'
23
+ ```
24
+
25
+ ## CLI
26
+
27
+ The package exposes two console scripts:
28
+
29
+ ```bash
30
+ uv run nkparser --help
31
+ uv run nkparse --help
32
+ ```
33
+
34
+ You can also run it as a module:
35
+
36
+ ```bash
37
+ uv run python -m nkparser --help
38
+ ```
39
+
40
+ ### Examples
41
+
42
+ ```bash
43
+ uv run nkparser info tests/fixtures/minimal.nk
44
+ uv run nkparser validate tests/fixtures/malformed_unclosed.nk
45
+ uv run nkparser tree tests/fixtures/complex_groups.nk --knobs
46
+ uv run nkparser nodes tests/fixtures/minimal.nk --class Grade
47
+ uv run nkparser dot tests/fixtures/minimal.nk -o graph.dot
48
+ uv run nkparser dot tests/fixtures/minimal.nk -o graph.dot --render --dot-command /opt/homebrew/bin/dot
49
+ ```
50
+
51
+ ## Development
52
+
53
+ Sync the dev environment:
54
+
55
+ ```bash
56
+ uv sync --dev
57
+ ```
58
+
59
+ Run checks:
60
+
61
+ ```bash
62
+ uv run pytest
63
+ uv run ruff check .
64
+ uv run mypy
65
+ ```
66
+
67
+ Build distributions:
68
+
69
+ ```bash
70
+ uv build
71
+ ```
72
+
73
+ ## Python API
74
+
75
+ ```python
76
+ import nkparser
77
+
78
+ script = nkparser.Script.from_file("comp.nk")
79
+
80
+ print(script.nuke_version)
81
+ print(len(list(script.all_nodes())))
82
+
83
+ reads = script.query().of_class("Read").all()
84
+ grade = script.find("Grade1")
85
+
86
+ if grade:
87
+ grade.set("disable", "true")
88
+
89
+ script.write("comp_modified.nk")
90
+ ```
@@ -0,0 +1,68 @@
1
+ """nkparser — Parse, query, and serialize Foundry Nuke .nk script files.
2
+
3
+ Quick start::
4
+
5
+ import nkparser
6
+
7
+ # Parse a .nk file
8
+ script = nkparser.Script.from_file("comp.nk")
9
+
10
+ # Inspect
11
+ print(f"{len(list(script.all_nodes()))} nodes")
12
+ for d in script.diagnostics:
13
+ print(d)
14
+
15
+ # Query
16
+ reads = script.query().of_class("Read").all()
17
+ grade = script.find("Grade1")
18
+
19
+ # Visualize
20
+ print(nkparser.TextTree(script).render(show_knobs=True))
21
+ nkparser.DotExporter(script).export("graph.dot")
22
+
23
+ # Modify
24
+ if grade:
25
+ grade.set("white", "2.0")
26
+
27
+ # Write back
28
+ script.write("comp_modified.nk")
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from .query import NodeQuery
34
+ from .errors import (LexError, ParseError, NkParserError, ValidationError,
35
+ SerializationError)
36
+ from .models import (Knob, Node, Script, GroupNode, KnobValue, Diagnostic,
37
+ KnobValueKind, VariableReference, DiagnosticSeverity,
38
+ VariableAssignment)
39
+ from .visualization import TextTree, DotExporter
40
+
41
+ __version__ = "0.1.0"
42
+
43
+ __all__ = [
44
+ # Core model
45
+ "Script",
46
+ "Node",
47
+ "GroupNode",
48
+ "Knob",
49
+ "KnobValue",
50
+ "KnobValueKind",
51
+ "VariableAssignment",
52
+ "VariableReference",
53
+ "Diagnostic",
54
+ "DiagnosticSeverity",
55
+ # Errors
56
+ "NkParserError",
57
+ "LexError",
58
+ "ParseError",
59
+ "ValidationError",
60
+ "SerializationError",
61
+ # Query
62
+ "NodeQuery",
63
+ # Visualization
64
+ "TextTree",
65
+ "DotExporter",
66
+ # Version
67
+ "__version__",
68
+ ]
@@ -0,0 +1,8 @@
1
+ """Module entry point for `python -m nkparser`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ main()
@@ -0,0 +1,231 @@
1
+ """Builder: converts the raw AST from the Parser into the Script object model.
2
+
3
+ The builder's primary responsibility beyond creating Node/GroupNode instances
4
+ is simulating Nuke's execution-stack connectivity model:
5
+
6
+ 1. Every node pops N items from the execution stack as its inputs, where N is
7
+ the value of its 'inputs' knob (or a class-specific default).
8
+ 2. After processing its inputs, a node pushes itself onto the execution stack.
9
+ 3. 'set X [stack N]' captures the node at depth N without consuming it.
10
+ 4. 'push $X' re-pushes a captured variable, enabling fan-out and merges.
11
+ 5. Unresolved 'push $X' (where X was never set) push None, indicating a
12
+ missing connection.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from .models import (Knob, Node, Script, GroupNode, KnobValue,
18
+ VariableReference, VariableAssignment)
19
+ from .parser import (RawKnob, RawNode, RawSetOp, RawPushOp, RawAddLayer,
20
+ RawStatement)
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Node class default-input-count table
24
+ # ---------------------------------------------------------------------------
25
+
26
+ # These node classes produce no output visible as downstream inputs and/or have
27
+ # zero implicit stream inputs by default.
28
+ _ZERO_INPUT_CLASSES: frozenset[str] = frozenset(
29
+ {
30
+ "Root",
31
+ "Viewer",
32
+ "Read",
33
+ "ReadGeo",
34
+ "ReadGeo2",
35
+ "Constant",
36
+ "CheckerBoard",
37
+ "CheckerBoard2",
38
+ "ColorBars",
39
+ "ColorWheel",
40
+ "StickyNote",
41
+ "BackdropNode",
42
+ "Camera",
43
+ "Camera2",
44
+ "Camera3",
45
+ "Light",
46
+ "Light2",
47
+ "DirectLight",
48
+ "PointLight",
49
+ "SpotLight",
50
+ "Environment",
51
+ "Axis",
52
+ "Axis2",
53
+ "Axis3",
54
+ }
55
+ )
56
+
57
+
58
+ def _default_input_count(node_class: str, knob_inputs: int | None) -> int:
59
+ """Return the number of stream inputs a node should consume from the stack."""
60
+ # If the script explicitly sets 'inputs N', trust it.
61
+ if knob_inputs is not None:
62
+ return knob_inputs
63
+ # Classes that default to 0 inputs
64
+ if node_class in _ZERO_INPUT_CLASSES:
65
+ return 0
66
+ # Everything else defaults to 1 input
67
+ return 1
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Builder
72
+ # ---------------------------------------------------------------------------
73
+
74
+
75
+ class ScriptBuilder:
76
+ """Convert raw AST (header dict + RawStatement list) into a Script."""
77
+
78
+ def __init__(self) -> None:
79
+ self._execution_stack: list[Node | None] = []
80
+ self._variables: dict[str, Node | None] = {}
81
+ self._variable_assignments: dict[str, VariableAssignment] = {}
82
+ self._variable_refs: list[VariableReference] = []
83
+ self._script = Script()
84
+
85
+ def build(
86
+ self,
87
+ header: dict[str, str],
88
+ statements: list[RawStatement],
89
+ ) -> Script:
90
+ self._apply_header(header)
91
+ for stmt in statements:
92
+ self._process_statement(stmt)
93
+ self._script._variables = self._variable_assignments
94
+ self._script._variable_refs = self._variable_refs
95
+ return self._script
96
+
97
+ # ------------------------------------------------------------------
98
+ # Header
99
+ # ------------------------------------------------------------------
100
+
101
+ def _apply_header(self, header: dict[str, str]) -> None:
102
+ self._script.shebang = header.get("shebang")
103
+ self._script.nuke_version = header.get("version")
104
+ self._script.window_layout_xml = header.get("window_layout_xml")
105
+
106
+ # ------------------------------------------------------------------
107
+ # Statement processing
108
+ # ------------------------------------------------------------------
109
+
110
+ def _process_statement(self, stmt: RawStatement) -> None:
111
+ if isinstance(stmt, RawSetOp):
112
+ self._handle_set(stmt)
113
+ elif isinstance(stmt, RawPushOp):
114
+ self._handle_push(stmt)
115
+ elif isinstance(stmt, RawAddLayer):
116
+ self._script.add_layer_declarations.append(stmt.declaration)
117
+ self._script._ordered_statements.append(stmt)
118
+ elif isinstance(stmt, RawNode):
119
+ node = self._build_node(stmt)
120
+ self._connect_inputs(node, stmt)
121
+ self._script.nodes.append(node)
122
+ self._script._ordered_statements.append(node)
123
+ # Push node onto execution stack (it becomes available as an input)
124
+ self._execution_stack.append(node)
125
+
126
+ # ------------------------------------------------------------------
127
+ # Stack operations
128
+ # ------------------------------------------------------------------
129
+
130
+ def _handle_set(self, op: RawSetOp) -> None:
131
+ """Capture stack[op.stack_index] into _variables without consuming."""
132
+ idx = op.stack_index
133
+ if len(self._execution_stack) > idx:
134
+ captured = self._execution_stack[-(idx + 1)]
135
+ else:
136
+ captured = None
137
+ self._variables[op.name] = captured
138
+ self._variable_assignments[op.name] = VariableAssignment(
139
+ name=op.name, stack_index=op.stack_index, source_line=op.source_line
140
+ )
141
+ self._script._ordered_statements.append(op)
142
+
143
+ def _handle_push(self, op: RawPushOp) -> None:
144
+ """Push a previously-captured variable back onto the execution stack."""
145
+ node = self._variables.get(op.ref)
146
+ ref = VariableReference(
147
+ name=op.ref, source_line=op.source_line, resolved=node)
148
+ self._variable_refs.append(ref)
149
+ self._execution_stack.append(node) # None if unresolved
150
+ self._script._ordered_statements.append(op)
151
+
152
+ # ------------------------------------------------------------------
153
+ # Input connection
154
+ # ------------------------------------------------------------------
155
+
156
+ def _connect_inputs(self, node: Node, raw: RawNode) -> None:
157
+ """Pop N items from the execution stack as this node's inputs."""
158
+ # Read the 'inputs' knob value if present
159
+ knob_inputs: int | None = None
160
+ for k in raw.knobs:
161
+ if k.name == "inputs":
162
+ try:
163
+ knob_inputs = int(k.raw_value.strip())
164
+ except ValueError:
165
+ pass
166
+ break
167
+
168
+ n = _default_input_count(raw.node_class, knob_inputs)
169
+ inputs: list[Node | None] = []
170
+ for _ in range(n):
171
+ if self._execution_stack:
172
+ inputs.insert(0, self._execution_stack.pop())
173
+ else:
174
+ inputs.insert(0, None)
175
+ node._inputs = inputs
176
+
177
+ # ------------------------------------------------------------------
178
+ # Node construction
179
+ # ------------------------------------------------------------------
180
+
181
+ def _build_node(self, raw: RawNode) -> Node:
182
+ knobs = [self._build_knob(rk) for rk in raw.knobs]
183
+
184
+ if raw.is_group:
185
+ # Build children, simulating stack within the group context.
186
+ # Groups have their own isolated stack; we save and restore.
187
+ saved_stack = self._execution_stack
188
+ self._execution_stack = []
189
+ children: list[Node] = []
190
+ for child_stmt in raw.children:
191
+ self._process_statement(child_stmt)
192
+ # Collect nodes that were appended to self._script.nodes
193
+ # from this group's children processing — we need to move
194
+ # them into the group's children list instead.
195
+ # Any nodes added to script.nodes during group processing are
196
+ # actually children — move the last N nodes.
197
+ n_children = len(raw.children)
198
+ group_children = self._script.nodes[-n_children:]
199
+ del self._script.nodes[-n_children:]
200
+ # Also remove their ordered statements
201
+ # (re-add them nested under the group in serializer)
202
+ del self._script._ordered_statements[-n_children:]
203
+ children = group_children
204
+ self._execution_stack = saved_stack
205
+ node: Node = GroupNode(
206
+ node_class=raw.node_class,
207
+ knobs=knobs,
208
+ children=children,
209
+ is_unclosed=raw.is_unclosed,
210
+ source_line=raw.source_line,
211
+ source_end_line=raw.source_end_line,
212
+ )
213
+ else:
214
+ node = Node(
215
+ node_class=raw.node_class,
216
+ knobs=knobs,
217
+ source_line=raw.source_line,
218
+ source_end_line=raw.source_end_line,
219
+ )
220
+
221
+ node._script_ref = self._script
222
+ return node
223
+
224
+ def _build_knob(self, rk: RawKnob) -> Knob:
225
+ value = KnobValue.classify(rk.raw_value)
226
+ return Knob(
227
+ name=rk.name,
228
+ value=value,
229
+ source_line=rk.source_line,
230
+ raw_line=rk.raw_line,
231
+ )