forked from fookatchu/SL1toPhoton
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSL1_to_Photon.py
executable file
·220 lines (174 loc) · 7.4 KB
/
SL1_to_Photon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
import glob
import os
import sys
import zipfile
import tempfile
import argparse
import pyphotonfile
import multiprocessing
import io
from PIL import Image
from pyphotonfile.photonfile import SubLayer
class SL1Reader:
def __init__(self, filepath):
self.zf = zipfile.ZipFile(filepath, "r")
self.config = self._read_config_file("config.ini")
self.prusa_config = self._read_config_file("prusaslicer.ini")
self.n_layers = 0
for filename in self.zf.namelist():
# skip all files in subdirectories (e.g. thumbnails)
if os.path.dirname(filename) != "":
continue
if filename.startswith(self.config["jobDir"]) and ".png" in filename:
self.n_layers += 1
def _read_config_file(self, name="config.ini") -> dict[str, str]:
try:
config_file = self.zf.read(name)
except KeyError:
raise FileNotFoundError(f"ERROR: Did not find {name} in zip file. Is that really an SL1 file?")
config = {}
for line in config_file.decode().splitlines():
key, value = line.strip().split("=", 1)
config[key.strip()] = value.strip().replace("\\n", "\n")
return config
def read_thumbnail(self, size="800x480") -> Image.Image:
try:
tb = self.zf.read(f"thumbnail/thumbnail{size}.png")
except KeyError:
raise FileNotFoundError(
f"ERROR: Did not find thumbnail of size {size} in zip file. Is that really an SL1 file?"
)
return Image.open(io.BytesIO(tb))
def extract_images(self, dirpath):
try:
os.makedirs(dirpath)
except OSError:
pass # Means it already exists. We're file with that.
for filename in self.zf.namelist():
if os.path.dirname(filename) != "": # skip all files in subdirectories (e.g. thumbnails)
continue
if ".png" in filename:
data = self.zf.read(filename)
with open(os.path.join(dirpath, filename), "bw") as f:
f.write(data)
if __name__ == "__main__":
desc = """Convert an SL1 file to a Photon file."""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("sl1_file", help="SL1 file to convert.")
parser.add_argument("-f", "--force", action="store_true", help="overwrite existing files")
# parser.add_argument("--timelapse", action='store_true', default=False, help="set all exposures to 1s. Useful for debugging exposure with no resin.")
parser.add_argument("-q", "--quiet", action="store_true", default=False)
parser.add_argument("-bls", "--bottomliftspeed", help="bottom lifting speed (40)", default="40")
parser.add_argument("-ls", "--liftspeed", help="lifting speed (40)", default="40")
parser.add_argument("-rs", "--retractspeed", help="retract speed (180)", default="180")
parser.add_argument("-o", "--output", help="photon file output path")
args = parser.parse_args()
def log(*a, **b):
if not args.quiet:
print(*a, **b)
if not os.path.exists(args.sl1_file):
raise FileNotFoundError(f"File {args.sl1_file} does not exist!")
sl1 = SL1Reader(args.sl1_file)
all_args = []
# Additional args from material_notes
locations = ["material_notes", "printer_notes"]
for location in locations:
notes = sl1.prusa_config[location]
_flags_designator = "photonflags "
for line in notes.splitlines():
if line.startswith(_flags_designator):
flags = line[len(_flags_designator) :]
log(f"Found additional flags in {location}: {flags}")
# all_args += [a for a in flags.split() if len(a)]
if len(all_args):
# sys.argv += all_args
log(f"Final args: {sys.argv}")
args = parser.parse_args()
parser.parse_args()
if args.output is None:
base, ext = os.path.splitext(args.sl1_file)
photon_path = sl1.config["jobDir"] + ".photon"
else:
photon_path = args.output
if os.path.exists(photon_path) and not args.force:
raise FileExistsError(
f"File {os.path.basename(photon_path)} already exists!. move or use -f flag to force overwrite."
)
photon = pyphotonfile.Photon()
photon.version = 2
# Printer settings
photon.bed_x = 68.04000091552734
photon.bed_y = 120.95999908447266
photon.bed_z = 155.0
# Slicing settings
photon.anti_aliasing_level = 0
photon.layer_levels = 1
photon.layer_height = float(sl1.config["layerHeight"])
photon.bottom_layers = int(sl1.config["numFade"])
photon.bottom_layer_count = int(sl1.config["numFade"])
# Lift settings
photon.lifting_speed = float(args.liftspeed)
photon.lifting_distance = 5.0
photon.bottom_lift_speed = float(args.bottomliftspeed)
photon.bottom_lift_distance = 6.0
photon.retract_speed = float(args.retractspeed)
# Curing settings
photon.exposure_time = float(sl1.config["expTime"])
photon.exposure_time_bottom = float(sl1.config["expTimeFirst"])
photon.bottom_light_off_delay = 0.0
photon.light_off_delay = 0.0
photon.off_time = 1.0
photon.light_pwm = 255
photon.light_pwm_bottom = 255
# Meta
photon.volume_ml = float(sl1.config["usedMaterial"])
photon.weight_g = float(sl1.config["usedMaterial"])
photon.cost_dollars = 1.0
photon.print_properties_length = 60
photon.print_time = int(float(sl1.config["printTime"]))
photon.set_preview_highres(sl1.read_thumbnail(size="800x480"))
photon.set_preview_lowres(sl1.read_thumbnail(size="400x400"))
# Strange settings
photon.p1 = 1.875
photon.p2 = 9.453131998900351e23
photon.p3 = 0.0
photon.p4 = 8.407790785948902e-45
log("=== PARAMETERS ===")
log("Layers: {}".format(sl1.n_layers))
log(" Height: {}".format(photon.layer_height))
log(" Exposure Time: {}".format(photon.exposure_time))
log(" Lifting Speed: {}".format(photon.lifting_speed))
log(" Lifting distance: {}".format(photon.lifting_distance))
log()
log("Bottom Layers: {}".format(photon.bottom_layers))
log(" Exposure Time: {}".format(photon.exposure_time_bottom))
log(" Lifting Speed: {}".format(photon.bottom_lift_speed))
log(" Lifting distance: {}".format(photon.bottom_lift_distance))
log("Retract speed: {}".format(photon.retract_speed))
log()
log("=== META ===")
log("Used material: {} g.".format(sl1.config["usedMaterial"]))
log()
log("=== CONVERSION ===")
with tempfile.TemporaryDirectory() as tmpdirname:
log("extracting layers... ", end="")
sl1.extract_images(tmpdirname)
log("DONE")
layers = sorted(glob.glob(os.path.join(tmpdirname, "*.png")))
def convert_layer(filepath):
global counter
with counter.get_lock():
counter.value += 1
log(f"converting layer {counter.value} / {sl1.n_layers}", end="\r")
Image.open(filepath).rotate(180).save(filepath)
return photon.create_layer(filepath)
counter = multiprocessing.Value("i", 0)
pool = multiprocessing.Pool(initargs=(counter,))
try:
photon.layers = pool.map(convert_layer, layers)
except KeyboardInterrupt:
log("Aborted.")
log()
photon.write(photon_path)
log("Output file written to: {}".format(photon_path))