nkparser 0.1.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.
nkparser/validator.py ADDED
@@ -0,0 +1,140 @@
1
+ """Validation pass over a built Script object.
2
+
3
+ Each check appends Diagnostic entries to script.diagnostics.
4
+ Checks are independent and non-fatal — a script with errors can still be
5
+ serialized (with potentially degraded output).
6
+
7
+ Diagnostic codes emitted:
8
+ unresolved-variable — push $X where X was never set
9
+ unclosed-group — Group { without matching end_group
10
+ duplicate-name — two nodes share the same 'name' knob value
11
+ orphaned-set — set X whose variable is never push-ed
12
+ missing-root — no Root node in script
13
+ empty-name — node has no name knob or empty name
14
+ invalid-inputs-count — inputs knob is not a valid non-negative integer
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from .models import Script, GroupNode, Diagnostic, DiagnosticSeverity
20
+
21
+
22
+ class Validator:
23
+ def __init__(self, script: Script) -> None:
24
+ self._script = script
25
+
26
+ def validate(self) -> list[Diagnostic]:
27
+ self._check_unclosed_groups()
28
+ self._check_unresolved_variables()
29
+ self._check_duplicate_names()
30
+ self._check_orphaned_sets()
31
+ self._check_missing_root()
32
+ self._check_empty_names()
33
+ self._check_invalid_inputs_count()
34
+ return self._script.diagnostics
35
+
36
+ # ------------------------------------------------------------------
37
+ # Checks
38
+ # ------------------------------------------------------------------
39
+
40
+ def _check_unclosed_groups(self) -> None:
41
+ for node in self._script.all_nodes():
42
+ if isinstance(node, GroupNode) and node.is_unclosed:
43
+ self._emit(
44
+ DiagnosticSeverity.ERROR,
45
+ f"Group node {node.name!r} has no matching 'end_group'",
46
+ "unclosed-group",
47
+ node.source_line,
48
+ )
49
+
50
+ def _check_unresolved_variables(self) -> None:
51
+ set_names = set(self._script._variables.keys())
52
+ for ref in self._script._variable_refs:
53
+ if ref.name not in set_names:
54
+ self._emit(
55
+ DiagnosticSeverity.ERROR,
56
+ f"push references undefined variable '${ref.name}'",
57
+ "unresolved-variable",
58
+ ref.source_line,
59
+ )
60
+
61
+ def _check_duplicate_names(self) -> None:
62
+ seen: dict[str, int] = {}
63
+ for node in self._script.all_nodes():
64
+ n = node.name
65
+ if not n:
66
+ continue
67
+ if n in seen:
68
+ self._emit(
69
+ DiagnosticSeverity.WARNING,
70
+ f"Duplicate node name {n!r} (first at line {seen[n]})",
71
+ "duplicate-name",
72
+ node.source_line,
73
+ )
74
+ else:
75
+ seen[n] = node.source_line
76
+
77
+ def _check_orphaned_sets(self) -> None:
78
+ pushed_names = {ref.name for ref in self._script._variable_refs}
79
+ for name, assignment in self._script._variables.items():
80
+ if name not in pushed_names:
81
+ self._emit(
82
+ DiagnosticSeverity.WARNING,
83
+ f"Variable '{name}' is set but never push-ed",
84
+ "orphaned-set",
85
+ assignment.source_line,
86
+ )
87
+
88
+ def _check_missing_root(self) -> None:
89
+ if self._script.root() is None:
90
+ self._emit(
91
+ DiagnosticSeverity.WARNING,
92
+ "Script has no Root node",
93
+ "missing-root",
94
+ 0,
95
+ )
96
+
97
+ def _check_empty_names(self) -> None:
98
+ for node in self._script.all_nodes():
99
+ if not node.name:
100
+ self._emit(
101
+ DiagnosticSeverity.WARNING,
102
+ f"Node of class {node.node_class!r} has no name",
103
+ "empty-name",
104
+ node.source_line,
105
+ )
106
+
107
+ def _check_invalid_inputs_count(self) -> None:
108
+ for node in self._script.all_nodes():
109
+ k = node.knob("inputs")
110
+ if k is None:
111
+ continue
112
+ raw = k.value.raw
113
+ try:
114
+ val = int(raw)
115
+ if val < 0:
116
+ raise ValueError
117
+ except ValueError:
118
+ self._emit(
119
+ DiagnosticSeverity.WARNING,
120
+ f"Node {node.name!r} has invalid 'inputs' value {raw!r} (expected non-negative integer)",
121
+ "invalid-inputs-count",
122
+ k.source_line,
123
+ )
124
+
125
+ # ------------------------------------------------------------------
126
+ # Helper
127
+ # ------------------------------------------------------------------
128
+
129
+ def _emit(
130
+ self,
131
+ severity: DiagnosticSeverity,
132
+ message: str,
133
+ code: str,
134
+ line: int,
135
+ col: int = 0,
136
+ ) -> None:
137
+ self._script.diagnostics.append(
138
+ Diagnostic(severity=severity, message=message,
139
+ code=code, line=line, col=col)
140
+ )
@@ -0,0 +1,245 @@
1
+ """Visualization utilities for Nuke script node graphs.
2
+
3
+ Two renderers are provided:
4
+
5
+ TextTree
6
+ Renders the script as a human-readable ASCII tree showing each node's
7
+ class, name, and optional knob values.
8
+
9
+ DotExporter
10
+ Exports the node connectivity as a Graphviz DOT file. If the optional
11
+ ``graphviz`` Python package is installed, can also render to PNG/SVG.
12
+
13
+ Usage::
14
+
15
+ from nkparser import Script, TextTree, DotExporter
16
+
17
+ script = Script.from_file("comp.nk")
18
+
19
+ # Print text tree
20
+ print(TextTree(script).render(show_knobs=True))
21
+
22
+ # Export DOT graph
23
+ dot_src = DotExporter(script).export("graph.dot")
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ import subprocess
30
+ from typing import Optional
31
+ from pathlib import Path
32
+
33
+ from .models import Node, Script, GroupNode
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Text tree renderer
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ class TextTree:
41
+ """Render a Script as a Unicode/ASCII node tree."""
42
+
43
+ BRANCH = "├── "
44
+ LAST_BRANCH = "└── "
45
+ PIPE = "│ "
46
+ SPACE = " "
47
+
48
+ def __init__(self, script: Script) -> None:
49
+ self._script = script
50
+
51
+ def render(self, show_knobs: bool = False, max_depth: int = 99) -> str:
52
+ """Return a multi-line string tree representation of the script.
53
+
54
+ Args:
55
+ show_knobs: If True, each node's knobs are printed beneath it.
56
+ max_depth: Maximum nesting depth to display.
57
+ """
58
+ lines: list[str] = []
59
+ header_parts: list[str] = []
60
+ if self._script.nuke_version:
61
+ header_parts.append(f"version {self._script.nuke_version}")
62
+ if self._script.shebang:
63
+ header_parts.append(self._script.shebang)
64
+ lines.append(
65
+ f"Script ({', '.join(header_parts) if header_parts else 'unknown version'})")
66
+
67
+ nodes = self._script.nodes
68
+ for i, node in enumerate(nodes):
69
+ is_last = i == len(nodes) - 1
70
+ self._render_node(node, prefix="", is_last=is_last, depth=0,
71
+ show_knobs=show_knobs, max_depth=max_depth, lines=lines)
72
+ return "\n".join(lines)
73
+
74
+ def _render_node(
75
+ self,
76
+ node: Node,
77
+ prefix: str,
78
+ is_last: bool,
79
+ depth: int,
80
+ show_knobs: bool,
81
+ max_depth: int,
82
+ lines: list[str],
83
+ ) -> None:
84
+ connector = self.LAST_BRANCH if is_last else self.BRANCH
85
+ label = f"{node.node_class}"
86
+ if node.name:
87
+ label += f" [{node.name}]"
88
+ if node._inputs:
89
+ input_names = [
90
+ (n.name or n.node_class) if n else "?"
91
+ for n in node._inputs
92
+ ]
93
+ label += f" ← {', '.join(input_names)}"
94
+ lines.append(f"{prefix}{connector}{label}")
95
+
96
+ extension = self.SPACE if is_last else self.PIPE
97
+
98
+ if show_knobs and depth < max_depth:
99
+ knob_lines = [
100
+ k for k in node.knobs if k.name not in ("name", "xpos", "ypos")
101
+ ]
102
+ for j, knob in enumerate(knob_lines):
103
+ is_last_knob = j == len(knob_lines) - 1 and not (
104
+ isinstance(node, GroupNode) and node.children
105
+ )
106
+ knob_connector = self.LAST_BRANCH if is_last_knob else self.BRANCH
107
+ val_preview = knob.value.raw[:50].replace("\n", "\\n")
108
+ if len(knob.value.raw) > 50:
109
+ val_preview += "..."
110
+ lines.append(
111
+ f"{prefix}{extension}{knob_connector}{knob.name}: {val_preview}")
112
+
113
+ if isinstance(node, GroupNode) and depth < max_depth:
114
+ children = node.children
115
+ for k, child in enumerate(children):
116
+ child_is_last = k == len(children) - 1
117
+ self._render_node(
118
+ child,
119
+ prefix=prefix + extension,
120
+ is_last=child_is_last,
121
+ depth=depth + 1,
122
+ show_knobs=show_knobs,
123
+ max_depth=max_depth,
124
+ lines=lines,
125
+ )
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # DOT / Graphviz exporter
130
+ # ---------------------------------------------------------------------------
131
+
132
+
133
+ class DotExporter:
134
+ """Export a Script's node graph to Graphviz DOT format."""
135
+
136
+ def __init__(self, script: Script) -> None:
137
+ self._script = script
138
+
139
+ def export(
140
+ self,
141
+ output_path: Optional[str] = None,
142
+ *,
143
+ render: bool = False,
144
+ render_format: str = "png",
145
+ dot_command: Optional[str] = None,
146
+ ) -> str:
147
+ """Generate DOT source and optionally write to file.
148
+
149
+ Args:
150
+ output_path: If given, write DOT source to this path.
151
+ render: If True, also render to an image (e.g. PNG) using a
152
+ Graphviz ``dot`` executable. The rendered file is placed
153
+ alongside *output_path* using the DOT file stem.
154
+ render_format: Image format for rendering (default "png").
155
+ dot_command: Optional Graphviz ``dot`` executable path or command
156
+ name. Defaults to the ``NKPARSER_DOT`` environment variable,
157
+ then ``dot``.
158
+
159
+ Returns:
160
+ The DOT source string.
161
+ """
162
+ lines: list[str] = [
163
+ "digraph nk {",
164
+ ' rankdir=TB;',
165
+ ' node [shape=box fontname="Courier" style="filled" fillcolor="#f5f5f5"];',
166
+ ' edge [color="#555555"];',
167
+ ]
168
+
169
+ # Node declarations
170
+ for node in self._script.all_nodes():
171
+ node_id = self._node_id(node)
172
+ label = self._node_label(node)
173
+ color = self._node_color(node.node_class)
174
+ lines.append(f' {node_id} [label="{label}" fillcolor="{color}"];')
175
+
176
+ # Edges
177
+ for node in self._script.all_nodes():
178
+ for i, inp in enumerate(node.inputs):
179
+ if inp is not None:
180
+ src_id = self._node_id(inp)
181
+ dst_id = self._node_id(node)
182
+ if len(node.inputs) > 1:
183
+ lines.append(f' {src_id} -> {dst_id} [label="{i}"];')
184
+ else:
185
+ lines.append(f' {src_id} -> {dst_id};')
186
+
187
+ lines.append("}")
188
+ dot_src = "\n".join(lines) + "\n"
189
+
190
+ if output_path:
191
+ with open(output_path, "w", encoding="utf-8") as fh:
192
+ fh.write(dot_src)
193
+ if render:
194
+ self._try_render(output_path, render_format, dot_command)
195
+
196
+ return dot_src
197
+
198
+ @staticmethod
199
+ def _node_id(node: Node) -> str:
200
+ return f"n{id(node)}"
201
+
202
+ @staticmethod
203
+ def _node_label(node: Node) -> str:
204
+ lines = [node.node_class]
205
+ if node.name:
206
+ lines.append(node.name)
207
+ return "\\n".join(lines)
208
+
209
+ @staticmethod
210
+ def _node_color(node_class: str) -> str:
211
+ color_map: dict[str, str] = {
212
+ "Root": "#ffffcc",
213
+ "Read": "#cce5ff",
214
+ "Write": "#ffcccc",
215
+ "Merge": "#ccffcc",
216
+ "Merge2": "#ccffcc",
217
+ "Grade": "#ffd9b3",
218
+ "ColorCorrect": "#ffd9b3",
219
+ "Blur": "#e0ccff",
220
+ "Viewer": "#d9d9d9",
221
+ "BackdropNode": "#f0f0f0",
222
+ "Group": "#ffe0cc",
223
+ }
224
+ return color_map.get(node_class, "#f5f5f5")
225
+
226
+ @staticmethod
227
+ def _rendered_path(output_path: str, fmt: str) -> Path:
228
+ path = Path(output_path)
229
+ stem_path = path.with_suffix(
230
+ "") if path.suffix.lower() == ".dot" else path
231
+ return stem_path.with_suffix(f".{fmt}")
232
+
233
+ @staticmethod
234
+ def _try_render(output_path: str, fmt: str, dot_command: Optional[str] = None) -> None:
235
+ command = dot_command or os.environ.get("NKPARSER_DOT") or "dot"
236
+ rendered_path = DotExporter._rendered_path(output_path, fmt)
237
+ try:
238
+ subprocess.run(
239
+ [command, f"-T{fmt}", output_path, "-o", str(rendered_path)],
240
+ check=True,
241
+ capture_output=True,
242
+ text=True,
243
+ )
244
+ except (FileNotFoundError, subprocess.CalledProcessError):
245
+ pass
@@ -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,18 @@
1
+ nkparser/__init__.py,sha256=3tN0fVQnOT4yqNKjf5SGUxMuT3hV_merdy_cLAPE1e8,1550
2
+ nkparser/__main__.py,sha256=n5Dr9fVmVUmZk0_929WOwgvMJz86YtvblbccV53f9EY,149
3
+ nkparser/builder.py,sha256=cKnYV4UoFa2Z4KRI-rzDVreZhGEPjXxkf8WAasZRPTE,8895
4
+ nkparser/cli.py,sha256=1sj1vhDZeX6FbGiffNCbjOftlG0VpTtB9B5iFj0y8Bs,13307
5
+ nkparser/errors.py,sha256=mu2qrEfTn_BcTJGSFCFgLAq1BLpueU4_XQuWJ8rX5F4,1171
6
+ nkparser/lexer.py,sha256=rBNmCjgtIkyYTfGWLh03bLS1E95yfto4ovFRT7S0PDE,10063
7
+ nkparser/models.py,sha256=wREz4aiKeLGi_VoDj_GFlFF7_iKnWWfCWlIydpJ1yIc,18002
8
+ nkparser/parser.py,sha256=jO4Sjt353Ua62_euZN0Lh0R3-_Wfw3WpW8GjQyfpJXs,16580
9
+ nkparser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ nkparser/query.py,sha256=HAYKIaA0tq4BLy59oD4RmSbkS8BLGRKCfXXwDv95JrA,4784
11
+ nkparser/serializer.py,sha256=zzzuseJ6TdLsgJjPvwe8qnZtzEEJwNNFnWGnagEVfW4,2766
12
+ nkparser/tokens.py,sha256=VJq5Q6WnmDEMPbEbBX2EbNeOkojeT_Bd2fpn2qB7tp0,1147
13
+ nkparser/validator.py,sha256=JgZGIvYMEMDYC7xXBbLbJ2lqO7rHh0-vAu5ldk5CgIY,5024
14
+ nkparser/visualization.py,sha256=CVo6DVs-rVEwj0KpSyR2q09Hze6bmUDL-nWm8sqqVd4,8317
15
+ nkparser-0.1.0.dist-info/METADATA,sha256=_eNyBrNcsSJ7jMw6N17TxZA4mnvduXOyzhqxgrc4gYk,1914
16
+ nkparser-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
17
+ nkparser-0.1.0.dist-info/entry_points.txt,sha256=x_BcVVFoAbPk_zVeI1Pi0Z_RFRP5yFWJbTDKWtnL5SM,47
18
+ nkparser-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nkparser = nkparser.cli:main