virtual-extruders 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.
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: virtual-extruders
3
+ Version: 0.1.0
4
+ Summary: A CLI tool to convert multi-extruder 3D printer G-code to single extruder.
5
+ Author-email: stygian-violet <stygianviol3t@proton.me>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/stygian-violet/virtual-extruders
8
+ Project-URL: Source, https://github.com/stygian-violet/virtual-extruders
9
+ Project-URL: Issues, https://github.com/stygian-violet/virtual-extruders/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Manufacturing
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: File Formats
18
+ Classifier: Topic :: Printing
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ virtual-extruders
26
+ =================
27
+
28
+ .. image:: https://img.shields.io/pypi/v/virtual-extruders.svg
29
+ :target: https://pypi.python.org/pypi/virtual-extruders
30
+ .. image:: https://img.shields.io/pypi/status/virtual-extruders.svg
31
+ :target: https://pypi.python.org/pypi/virtual-extruders
32
+ .. image:: https://img.shields.io/pypi/format/virtual-extruders.svg
33
+ :target: https://pypi.python.org/pypi/virtual-extruders
34
+ .. image:: https://img.shields.io/pypi/pyversions/virtual-extruders.svg
35
+ :target: https://python.org
36
+ .. image:: https://img.shields.io/pypi/l/virtual-extruders.svg
37
+ :target: https://github.com/stygian-violet/virtual-extruders/blob/master/LICENSE
38
+
39
+ Overview
40
+ --------
41
+
42
+ Convert G-code for a multi-extruder 3D printer to single extruder,
43
+ substituting tool selection with manual filament change.
44
+
45
+ Requirements
46
+ ------------
47
+
48
+ - `Python <https://www.python.org/>`__ >= 3.10
49
+
50
+ Installation
51
+ ------------
52
+
53
+ Pip
54
+ ^^^
55
+
56
+ .. code-block:: console
57
+
58
+ pip install virtual-extruders
59
+
60
+ Portable
61
+ ^^^^^^^^
62
+
63
+ Copy `virtual_extruders.py
64
+ <https://github.com/stygian-violet/virtual-extruders/blob/master/virtual_extruders.py>`__
65
+ to any directory and make it executable.
66
+
67
+ .. code-block:: console
68
+
69
+ install -m755 -D -t ~/.config/PrusaSlicer/scripts virtual_extruders.py
70
+
71
+ Usage
72
+ -----
73
+
74
+ CLI
75
+ ^^^
76
+
77
+ The command-line interface can be used
78
+ with ``virtual-extruders`` if it was installed with a package manager
79
+ or with ``/path/to/virtual_extruders.py`` otherwise.
80
+
81
+ ::
82
+
83
+ > ./virtual_extruders.py -h
84
+ usage: virtual_extruders.py [-h] [-V] [-i] [-f] [-g GCODE [GCODE ...]] file
85
+
86
+ positional arguments:
87
+ file g-code file
88
+
89
+ options:
90
+ -h, --help show this help message and exit
91
+ -V, --version show program's version number and exit
92
+ -i, --in-place edit the file in place
93
+ -f, --skip-first skip first tool change
94
+ -g, --tool-change-gcode GCODE [GCODE ...]
95
+ set tool change g-code (default: [';TOOL_CHANGE',
96
+ 'M117 Insert filament [next_extruder] and resume
97
+ printing', 'M600', ';TOOL_CHANGE_END'])
98
+
99
+ PrusaSlicer
100
+ ^^^^^^^^^^^
101
+
102
+ To use this program as a post-processing script in PrusaSlicer,
103
+ add the following line to the **Post-processing scripts** parameter
104
+ in **Print Settings** → **Output options**:
105
+
106
+ .. code-block:: console
107
+
108
+ virtual-extruders -i -f
109
+
110
+ For more detailed configuration instructions and a test model, see
111
+ `How to change filament mid-layer
112
+ <https://www.printables.com/model/1908968-how-to-change-filament-mid-layer>`__.
113
+
114
+ Development
115
+ -----------
116
+
117
+ Installation
118
+ ^^^^^^^^^^^^
119
+
120
+ .. code-block:: console
121
+
122
+ python -m venv env
123
+ source env/bin/activate
124
+ pip install --group dev -e .
125
+
126
+ Building
127
+ ^^^^^^^^
128
+
129
+ .. code-block:: console
130
+
131
+ python -m build
132
+
133
+ Testing
134
+ ^^^^^^^
135
+
136
+ .. code-block:: console
137
+
138
+ coverage run && coverage report
139
+
140
+ Linting
141
+ ^^^^^^^
142
+
143
+ .. code-block:: console
144
+
145
+ ruff check && mypy
146
+
147
+ Uploading
148
+ ^^^^^^^^^
149
+
150
+ .. code-block:: console
151
+
152
+ twine upload dist/*
153
+
154
+ Licenses
155
+ --------
156
+
157
+ - `virtual-extruders <https://github.com/stygian-violet/virtual-extruders/blob/master/LICENSE>`__
@@ -0,0 +1,7 @@
1
+ virtual_extruders.py,sha256=SyshmXXe64BXJ2OiwBbxoE7IZk_tmcmhH-aPhrBBbAM,9515
2
+ virtual_extruders-0.1.0.dist-info/licenses/LICENSE,sha256=BE7P7AaFAXFKuL7aXWj5CGeItaOj6znl5toGAtRkBxM,1082
3
+ virtual_extruders-0.1.0.dist-info/METADATA,sha256=k0ohCOnJmDDuQCI9KDHiR9qkTPgePDErzXa4u0W5mZM,4114
4
+ virtual_extruders-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ virtual_extruders-0.1.0.dist-info/entry_points.txt,sha256=bmwFTJHoaMbhRB4458RvxZKuQCKx8B--0Vq2YFas9q8,61
6
+ virtual_extruders-0.1.0.dist-info/top_level.txt,sha256=2ckYnOQzw2rMHEej2UopJrbjK9J3Xkq9DHVSrESUjAQ,18
7
+ virtual_extruders-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ virtual-extruders = virtual_extruders:main
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 stygian-violet.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ virtual_extruders
virtual_extruders.py ADDED
@@ -0,0 +1,310 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ import re
5
+ import sys
6
+ from argparse import ArgumentParser, Namespace
7
+ from collections.abc import Generator, Iterable
8
+ from contextlib import contextmanager
9
+ from typing import Any, NamedTuple, TextIO
10
+
11
+ __appname__ = 'virtual-extruders'
12
+ __version__ = '0.1.0'
13
+
14
+ NAME_VERSION = f'{__appname__} {__version__}'
15
+
16
+
17
+ RE_TOOL = re.compile(r'^T([0-9]+)$')
18
+ NON_TOOL_T = {'M106', 'M117', 'M118'}
19
+ SET_TEMPERATURE = {'M104', 'M109'}
20
+
21
+ RE_TOOL_CHANGE_BLOCK_START = re.compile(r'^\s*;\s*TOOL_CHANGE(?:_START)?\s*$')
22
+ RE_TOOL_CHANGE_BLOCK_END = re.compile(r'^\s*;\s*TOOL_CHANGE_END\s*$')
23
+
24
+ DEFAULT_TOOL_CHANGE_BLOCK_START = ';TOOL_CHANGE'
25
+ DEFAULT_TOOL_CHANGE_BLOCK_END = ';TOOL_CHANGE_END'
26
+ DEFAULT_TOOL_CHANGE_GCODE = [
27
+ DEFAULT_TOOL_CHANGE_BLOCK_START,
28
+ 'M117 Insert filament [next_extruder] and resume printing',
29
+ 'M600',
30
+ DEFAULT_TOOL_CHANGE_BLOCK_END
31
+ ]
32
+
33
+ VIRTUAL_UNUSED = 'not used for virtual extruders'
34
+ FIRST_TOOL_CHANGE_UNUSED = 'first tool change is not needed for virtual extruders'
35
+
36
+ INPLACE_STDIN = '--in-place can not be used with standard input'
37
+
38
+
39
+ class GCodeError(Exception):
40
+ def __init__(self, message: str, line: str | None, line_n: int | None):
41
+ self.message = message
42
+ self.line = line
43
+ self.line_n = line_n
44
+
45
+ def __str__(self) -> str:
46
+ res = ['error']
47
+ if self.line is not None or self.line_n is not None:
48
+ res.append('at line')
49
+ if self.line_n is not None:
50
+ res.append(str(self.line_n))
51
+ if self.line is not None:
52
+ res.append(repr(self.line))
53
+ return f'{" ".join(res)}: {self.message}'
54
+
55
+
56
+ class ToolTemperature(NamedTuple):
57
+ command: str
58
+ temperature: str
59
+ tool: int
60
+
61
+
62
+ def comment_out(line: str, message: str = '') -> str:
63
+ if not line:
64
+ return f'; {message}' if message else ''
65
+ start = ';' if line[0] != ';' else ''
66
+ if not message:
67
+ return f'{start}{line}'
68
+ separator = ',' if ';' in line else ' ;'
69
+ return f'{start}{line}{separator} {message}'
70
+
71
+
72
+ def split(line: str) -> tuple[list[str], str]:
73
+ line = line.strip()
74
+ comment = ''
75
+ try:
76
+ i = line.index(';')
77
+ except ValueError:
78
+ pass
79
+ else:
80
+ comment = line[i:]
81
+ line = line[:i].strip()
82
+ return line.split(), comment
83
+
84
+
85
+ def join(cmd: list[str], comment: str) -> str:
86
+ if not cmd:
87
+ return comment
88
+ line = ' '.join(cmd)
89
+ if comment:
90
+ return f'{line} {comment}'
91
+ return line
92
+
93
+
94
+ def format_lines(
95
+ lines: str | Iterable[str],
96
+ **kwargs: Any
97
+ ) -> Generator[str, None, None]:
98
+ replace = [(f'[{name}]', str(value)) for name, value in kwargs.items()]
99
+ if isinstance(lines, str):
100
+ lines = (lines,)
101
+ for line in lines:
102
+ for old, new in replace:
103
+ line = line.replace(old, new)
104
+ yield line
105
+
106
+
107
+ def get_tool_change_gcode(gcode: list[str] | None) -> list[str]:
108
+ if gcode is None:
109
+ return DEFAULT_TOOL_CHANGE_GCODE
110
+ if not gcode or not RE_TOOL_CHANGE_BLOCK_START.match(gcode[0]):
111
+ gcode.insert(0, DEFAULT_TOOL_CHANGE_BLOCK_START)
112
+ if not RE_TOOL_CHANGE_BLOCK_END.match(gcode[-1]):
113
+ gcode.append(DEFAULT_TOOL_CHANGE_BLOCK_END)
114
+ return gcode
115
+
116
+
117
+ @contextmanager
118
+ def open_input(name: str | None) -> Generator[TextIO, None, None]:
119
+ if name is None:
120
+ yield sys.stdin
121
+ else:
122
+ with open(name, 'r') as fp:
123
+ yield fp
124
+
125
+
126
+ @contextmanager
127
+ def open_output(name: str | None) -> Generator[TextIO, None, None]:
128
+ if name is None:
129
+ yield sys.stdout
130
+ else:
131
+ with open(name, 'w') as fp:
132
+ yield fp
133
+
134
+
135
+ def parse_tool_selection(cmd: list[str]) -> int | None:
136
+ if len(cmd) == 1 and (m := RE_TOOL.match(cmd[0])):
137
+ return int(m.group(1))
138
+ return None
139
+
140
+
141
+ def parse_tool_temperature(cmd: list[str]) -> ToolTemperature | None:
142
+ if len(cmd) != 3 or cmd[0] not in SET_TEMPERATURE:
143
+ return None
144
+ for i in range(2):
145
+ if m := RE_TOOL.match(cmd[i + 1]):
146
+ return ToolTemperature(cmd[0], cmd[2 - i], int(m.group(1)))
147
+ return None
148
+
149
+
150
+ def process(
151
+ lines: Iterable[str],
152
+ *,
153
+ skip_first_tool_change: bool = False,
154
+ tool_change_gcode: list[str] | None = None
155
+ ) -> Generator[str, None, None]:
156
+ first_tool_change = True
157
+ insert_tool_change_gcode = False
158
+
159
+ set_temperature_tool = None
160
+ temperature = None
161
+
162
+ in_tool_change_block = False
163
+ tool_change_block_start = None
164
+ tool_change_block_start_n = None
165
+
166
+ tool_change_gcode = get_tool_change_gcode(tool_change_gcode)
167
+
168
+ for line_n, line in enumerate(lines, 1):
169
+ cmd, comment = split(line)
170
+ if FIRST_TOOL_CHANGE_UNUSED in comment:
171
+ first_tool_change = False
172
+ elif RE_TOOL_CHANGE_BLOCK_START.match(line):
173
+ if in_tool_change_block:
174
+ raise GCodeError(
175
+ 'unterminated tool change block',
176
+ tool_change_block_start,
177
+ tool_change_block_start_n
178
+ )
179
+ tool_change_block_start = line
180
+ tool_change_block_start_n = line_n
181
+ in_tool_change_block = True
182
+ if first_tool_change and skip_first_tool_change:
183
+ yield comment_out('', FIRST_TOOL_CHANGE_UNUSED)
184
+ line = comment_out(line)
185
+ elif RE_TOOL_CHANGE_BLOCK_END.match(line):
186
+ if not in_tool_change_block:
187
+ raise GCodeError(
188
+ 'unmatched tool change block end',
189
+ line, line_n
190
+ )
191
+ in_tool_change_block = False
192
+ if first_tool_change:
193
+ first_tool_change = False
194
+ if skip_first_tool_change:
195
+ line = comment_out(line)
196
+ elif (
197
+ skip_first_tool_change
198
+ and first_tool_change
199
+ and in_tool_change_block
200
+ ):
201
+ line = comment_out(line)
202
+ elif not cmd:
203
+ pass
204
+ elif (tool := parse_tool_selection(cmd)) is not None:
205
+ skip = False
206
+ if first_tool_change and not in_tool_change_block:
207
+ insert_tool_change_gcode = True
208
+ first_tool_change = False
209
+ skip = skip_first_tool_change
210
+ if insert_tool_change_gcode:
211
+ tool_change_block: Iterable[str]= format_lines(
212
+ tool_change_gcode,
213
+ next_extruder=tool
214
+ )
215
+ if skip:
216
+ yield comment_out('', FIRST_TOOL_CHANGE_UNUSED)
217
+ tool_change_block = map(comment_out, tool_change_block)
218
+ yield from tool_change_block
219
+ line = comment_out(line, VIRTUAL_UNUSED)
220
+ elif (temp := parse_tool_temperature(cmd)) is not None:
221
+ if set_temperature_tool is None:
222
+ set_temperature_tool = temp.tool
223
+ if temp.tool == set_temperature_tool:
224
+ temperature = temp.temperature
225
+ yield join([temp.command, temp.temperature], comment)
226
+ elif temp.temperature != temperature:
227
+ raise GCodeError(
228
+ f'extruders {set_temperature_tool} and {temp.tool}'
229
+ ' have different temperatures: '
230
+ f' {temperature} != {temp.temperature}',
231
+ line, line_n
232
+ )
233
+ line = comment_out(line, VIRTUAL_UNUSED)
234
+ elif (
235
+ cmd[0] not in NON_TOOL_T
236
+ and any(RE_TOOL.match(word) for word in cmd)
237
+ ):
238
+ raise GCodeError(
239
+ 'T* g-code processing is not implemented for this line',
240
+ line, line_n
241
+ )
242
+ yield line
243
+
244
+ if in_tool_change_block:
245
+ raise GCodeError(
246
+ 'unterminated tool change block',
247
+ tool_change_block_start,
248
+ tool_change_block_start_n
249
+ )
250
+
251
+
252
+ def parse_args(args: list[str] | None) -> Namespace:
253
+ parser = ArgumentParser()
254
+ parser.add_argument(
255
+ '-V', '--version', action='version', version=NAME_VERSION
256
+ )
257
+ parser.add_argument(
258
+ '-i', '--in-place', action='store_true',
259
+ help='edit the file in place'
260
+ )
261
+ parser.add_argument(
262
+ '-f', '--skip-first', action='store_true',
263
+ help='skip first tool change'
264
+ )
265
+ parser.add_argument(
266
+ '-g', '--tool-change-gcode', nargs='+', metavar='GCODE',
267
+ help=f'set tool change g-code (default: {DEFAULT_TOOL_CHANGE_GCODE})'
268
+ )
269
+ parser.add_argument('input', metavar='file', help='g-code file')
270
+
271
+ res = parser.parse_args(args)
272
+
273
+ if res.input == '-':
274
+ res.input = None
275
+
276
+ if res.in_place:
277
+ if res.input is None:
278
+ parser.error(INPLACE_STDIN)
279
+ res.output = res.input + '.tmp'
280
+ else:
281
+ res.output = None
282
+
283
+ return res
284
+
285
+
286
+ def main(argv: list[str] | None = None) -> None:
287
+ args = parse_args(argv)
288
+
289
+ try:
290
+ with (
291
+ open_input(args.input) as input_file,
292
+ open_output(args.output) as output_file
293
+ ):
294
+ for line in process(
295
+ (l.rstrip('\n') for l in input_file),
296
+ skip_first_tool_change=args.skip_first,
297
+ tool_change_gcode=args.tool_change_gcode
298
+ ):
299
+ output_file.write(f'{line}\n')
300
+ except:
301
+ if args.output is not None and os.path.exists(args.output):
302
+ os.remove(args.output)
303
+ raise
304
+ else:
305
+ if args.in_place:
306
+ os.rename(args.output, args.input)
307
+
308
+
309
+ if __name__ == '__main__':
310
+ main()