-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutput_from_kcl.py
229 lines (174 loc) · 7.01 KB
/
output_from_kcl.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
221
222
223
224
225
226
227
228
229
import asyncio
import os
import re
import tomllib
from concurrent.futures import ProcessPoolExecutor
from io import BytesIO
from operator import itemgetter
from pathlib import Path
import kcl
import requests
from kcl import UnitLength
from PIL import Image
RETRIES = 5
# Map strings to kcl units
UNIT_MAP = {
'in': kcl.UnitLength.In,
'mm': kcl.UnitLength.Mm,
'ft': kcl.UnitLength.Ft,
'm': kcl.UnitLength.M,
'cm': kcl.UnitLength.Cm,
'yd': kcl.UnitLength.Yd,
}
def export_step(code: str, kcl_path: Path, save_path: Path, unit_length: UnitLength = kcl.UnitLength.Mm) -> bool:
# determine the current directory
current_dir = os.getcwd()
# switch to the kcl path so imports work
os.chdir(kcl_path.parent)
try:
export_response = asyncio.run(
kcl.execute_and_export(code, unit_length, kcl.FileExportFormat.Step)
)
stl_path = save_path.with_suffix(".step")
with open(stl_path, "wb") as out:
out.write(bytes(export_response[0].contents))
# switch back to the directory we started in
os.chdir(current_dir)
return True
except Exception as e:
print(e)
# switch back to the directory we started in
os.chdir(current_dir)
return False
def find_files(
path: str | Path, valid_suffixes: list[str], name_pattern: str | None = None
) -> list[Path]:
"""
Recursively find files in a folder by a list of provided suffixes or file naming pattern
Args:
path: str | Path
Root folder to search
valid_suffixes: Container[str]
List of valid suffixes to find files by (e.g. ".stp", ".step")
name_pattern: str
Name pattern to additionally filter files by (e.g. "_component")
Returns:
list[Path]
"""
path = Path(path)
valid_suffixes = [i.lower() for i in valid_suffixes]
return sorted(
file for file in path.rglob("*")
if file.suffix.lower() in valid_suffixes and
(name_pattern is None or re.match(name_pattern, file.name))
)
def get_units(kcl_path: Path) -> UnitLength:
settings_path = kcl_path.parent / "project.toml"
if not settings_path.exists():
return kcl.UnitLength.Mm
with open(settings_path, "rb") as f:
data = tomllib.load(f)
try:
return UNIT_MAP[data['settings']['modeling']['base_unit']]
except KeyError:
return kcl.UnitLength.Mm
def snapshot(code: str, kcl_path: Path, save_path: Path, unit_length: UnitLength = kcl.UnitLength.Mm) -> bool:
# determine the current directory
current_dir = os.getcwd()
# switch to the kcl path so imports work
os.chdir(kcl_path.parent)
try:
snapshot_response = asyncio.run(
kcl.execute_and_snapshot(code, unit_length, kcl.ImageFormat.Png)
)
image = Image.open(BytesIO(bytearray(snapshot_response)))
im_path = save_path.with_suffix(".png")
image.save(im_path)
# switch back to the directory we started in
os.chdir(current_dir)
return True
except Exception as e:
print(e)
# switch back to the directory we started in
os.chdir(current_dir)
return False
def process_single_kcl(kcl_path: Path) -> dict:
# The part name is the parent folder since each file is main.kcl
part_name = kcl_path.parent.name
print(f"Processing {part_name}")
# determine units based on project.toml
units = get_units(kcl_path)
# read the file to get the code as a string
with open(kcl_path, "r") as inp:
code = str(inp.read())
# determine the root dir, which is where this python script
root_dir = Path(__file__).parent
# step and screenshots for the part are based on the root dir
step_path = root_dir / "step" / part_name
screenshots_path = root_dir / "screenshots" / part_name
# attempt step export
export_status = export_step(code=code, kcl_path=kcl_path, save_path=step_path, unit_length=units)
count = 1
while not export_status and count < RETRIES:
export_status = export_step(code=code, kcl_path=kcl_path, save_path=step_path, unit_length=units)
count += 1
# attempt screenshot
snapshot_status = snapshot(code=code, kcl_path=kcl_path, save_path=screenshots_path, unit_length=units)
count = 1
while not snapshot_status and count < RETRIES:
snapshot_status = snapshot(code=code, kcl_path=kcl_path, save_path=screenshots_path, unit_length=units)
count += 1
# find relative paths, used for building the README.md
kcl_rel_path = kcl_path.relative_to(Path(__file__).parent)
step_rel_path = step_path.relative_to(Path(__file__).parent).with_suffix(".step")
screenshot_rel_path = screenshots_path.relative_to(Path(__file__).parent).with_suffix(".png")
# readme string for the part
readme_entry = (
f"#### [{part_name}]({kcl_rel_path}) ([step]({step_rel_path})) ([screenshot]({screenshot_rel_path}))\n"
f"[![{part_name}]({screenshot_rel_path})]({kcl_rel_path})"
)
return {"filename": f"{kcl_rel_path}", "export_status": export_status, "snapshot_status": snapshot_status,
"readme_entry": readme_entry}
def update_readme(new_content: str, search_string: str = '---\n') -> None:
with open("README.md", 'r', encoding='utf-8') as file:
lines = file.readlines()
# Find the line containing the search string
found_index = -1
for i, line in enumerate(lines):
if search_string in line:
found_index = i
break
new_lines = lines[:found_index + 1]
new_lines.append(new_content)
# Write the modified content back to the file
with open("README.md", 'w', encoding='utf-8') as file:
file.writelines(new_lines)
file.write("\n")
def main():
kcl_files = find_files(path=Path(__file__).parent, valid_suffixes=[".kcl"], name_pattern="main")
# run concurrently
with ProcessPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(process_single_kcl, kcl_file) for kcl_file in kcl_files]
results = [future.result() for future in futures]
results = sorted(results, key=itemgetter('filename'))
if False in [i["export_status"] for i in results]:
comment_body = "The following files failed to export to STEP format:\n"
for i in results:
if not i["export_status"]:
comment_body += f"{i['filename']}\n"
url = f"https://api.github.com/repos/{os.getenv('GH_REPO')}/issues/{os.getenv('GH_PR')}/comments"
headers = {
'Authorization': f'token {os.getenv("GH_TOKEN")}',
}
json_data = {
'body': comment_body,
}
requests.post(url, headers=headers, json=json_data, timeout=60)
new_readme_links = []
for result in results:
if result["export_status"] and result["snapshot_status"]:
new_readme_links.append(result["readme_entry"])
new_readme_str = "\n".join(new_readme_links)
update_readme(new_readme_str)
if __name__ == "__main__":
main()