brickscape 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.
- brickscape/__init__.py +11 -0
- brickscape/__main__.py +66 -0
- brickscape/catalog/__init__.py +161 -0
- brickscape/catalog/gobricks.py +146 -0
- brickscape/catalog/lego.py +72 -0
- brickscape/config.py +26 -0
- brickscape/core/__init__.py +1 -0
- brickscape/core/brick.py +518 -0
- brickscape/core/free.py +62 -0
- brickscape/core/geom.py +218 -0
- brickscape/core/kit.py +888 -0
- brickscape/core/snaps.py +353 -0
- brickscape/core/snot.py +52 -0
- brickscape/core/space.py +51 -0
- brickscape/io/__init__.py +1 -0
- brickscape/io/analyze_ref.py +165 -0
- brickscape/io/export.py +148 -0
- brickscape/io/lxf.py +125 -0
- brickscape/plan.py +468 -0
- brickscape/review/__init__.py +1 -0
- brickscape/review/appearance.py +122 -0
- brickscape/review/blender_steps.py +117 -0
- brickscape/review/blender_view.py +110 -0
- brickscape/review/instructions.py +158 -0
- brickscape/review/profile.py +134 -0
- brickscape/review/render.py +188 -0
- brickscape/review/views.py +77 -0
- brickscape/schema.py +166 -0
- brickscape/server.py +359 -0
- brickscape/terrain/__init__.py +1 -0
- brickscape/terrain/facets.py +171 -0
- brickscape/terrain/greenery.py +570 -0
- brickscape/terrain/ground.py +340 -0
- brickscape/terrain/hill.py +235 -0
- brickscape/terrain/pillars.py +474 -0
- brickscape/terrain/rock2.py +474 -0
- brickscape/terrain/rock3.py +453 -0
- brickscape/terrain/water.py +150 -0
- brickscape/validate.py +251 -0
- brickscape-0.1.0.dist-info/METADATA +373 -0
- brickscape-0.1.0.dist-info/RECORD +45 -0
- brickscape-0.1.0.dist-info/WHEEL +5 -0
- brickscape-0.1.0.dist-info/entry_points.txt +3 -0
- brickscape-0.1.0.dist-info/licenses/LICENSE +21 -0
- brickscape-0.1.0.dist-info/top_level.txt +1 -0
brickscape/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""brickscape: design LEGO builds that can actually be built.
|
|
2
|
+
|
|
3
|
+
brickscape.core placement on the stud grid (brick), part solids (geom),
|
|
4
|
+
typed connections (snaps), helpers (kit, snot, free)
|
|
5
|
+
brickscape.terrain generators: rock, cliffs, terraces, paths, water, greenery, trees
|
|
6
|
+
brickscape.catalog part sources: official LEGO (default) or GoBricks
|
|
7
|
+
brickscape.validate strict checks every output goes through
|
|
8
|
+
brickscape.review renders and appearance metrics
|
|
9
|
+
brickscape.io reading .ldr/.mpd/.io/.lxf models
|
|
10
|
+
"""
|
|
11
|
+
__version__ = "0.1.0"
|
brickscape/__main__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""brickscape command line.
|
|
2
|
+
|
|
3
|
+
brickscape setup download the LDraw library + Blender add-on (via
|
|
4
|
+
ldraw-mcp), connection data and LEGO part data
|
|
5
|
+
brickscape serve run the MCP server (stdio), same as brickscape-mcp
|
|
6
|
+
brickscape build PLAN.json [--source S] compile a build plan -> brickscape-out/<name>/
|
|
7
|
+
brickscape render NAME the 4 standard views
|
|
8
|
+
brickscape export NAME Studio .io file
|
|
9
|
+
brickscape parts NAME [--source S] parts.csv + BrickLink wanted list
|
|
10
|
+
brickscape instructions NAME [--per-step N] PDF instructions
|
|
11
|
+
brickscape check MODEL [--source S] strict validation of any .ldr/.mpd/.io
|
|
12
|
+
brickscape guide print the plan guide (all operations)
|
|
13
|
+
|
|
14
|
+
Part source S: lego (default) or gobricks.
|
|
15
|
+
"""
|
|
16
|
+
import argparse, sys
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def setup():
|
|
20
|
+
from brickscape.catalog import lego
|
|
21
|
+
from brickscape.core import snaps
|
|
22
|
+
import subprocess
|
|
23
|
+
print("LDraw library + Blender add-on (ldraw-mcp-setup) ...")
|
|
24
|
+
subprocess.run([sys.executable, "-m", "ldraw_mcp.setup_cli"], check=False)
|
|
25
|
+
print("official LEGO part data (Rebrickable) ->", lego.download())
|
|
26
|
+
print("connection data (LDCad shadow library) ->", snaps.download())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv=None):
|
|
30
|
+
ap = argparse.ArgumentParser(prog="brickscape", description=__doc__,
|
|
31
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
32
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
33
|
+
sub.add_parser("setup"); sub.add_parser("serve"); sub.add_parser("guide")
|
|
34
|
+
for c in ("build", "check", "parts"):
|
|
35
|
+
p = sub.add_parser(c); p.add_argument("arg"); p.add_argument("--source", default="lego")
|
|
36
|
+
for c in ("render", "export"):
|
|
37
|
+
p = sub.add_parser(c); p.add_argument("arg")
|
|
38
|
+
p = sub.add_parser("instructions"); p.add_argument("arg"); p.add_argument("--per-step", type=int, default=10)
|
|
39
|
+
a = ap.parse_args(argv)
|
|
40
|
+
if a.cmd == "setup":
|
|
41
|
+
return setup()
|
|
42
|
+
if a.cmd == "serve":
|
|
43
|
+
from brickscape.server import main as serve
|
|
44
|
+
return serve()
|
|
45
|
+
from brickscape import server as S
|
|
46
|
+
if a.cmd == "guide":
|
|
47
|
+
print(S.guide())
|
|
48
|
+
elif a.cmd == "build":
|
|
49
|
+
print(S.build(open(a.arg).read(), source=a.source))
|
|
50
|
+
elif a.cmd == "check":
|
|
51
|
+
print(S.check(a.arg, source=a.source))
|
|
52
|
+
elif a.cmd == "parts":
|
|
53
|
+
print(S.parts_list(a.arg, source=a.source))
|
|
54
|
+
elif a.cmd == "render":
|
|
55
|
+
from brickscape.review.views import standard_views
|
|
56
|
+
import os
|
|
57
|
+
d = S._dir(a.arg)
|
|
58
|
+
print(standard_views(os.path.join(d, "model.ldr"), os.path.join(d, "renders"))["sheet"])
|
|
59
|
+
elif a.cmd == "export":
|
|
60
|
+
print(S.export(a.arg))
|
|
61
|
+
elif a.cmd == "instructions":
|
|
62
|
+
print(S.instructions(a.arg, parts_per_step=a.per_step))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
if __name__ == "__main__":
|
|
66
|
+
main()
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Part sources: which parts and colours exist and can be bought.
|
|
2
|
+
|
|
3
|
+
lego official LEGO (default): part/colour pairs LEGO has actually produced, from
|
|
4
|
+
Rebrickable's free CSV downloads (elements.csv), cached in BRICKSCAPE_DATA.
|
|
5
|
+
gobricks GoBricks / Brickwith moulds, colours and prices.
|
|
6
|
+
|
|
7
|
+
get(name) -> Source with: resolve(part) -> catalog id or None, colours(part) -> set of LDraw
|
|
8
|
+
colour codes (None = unknown), price(part) -> USD or None, substitute(part) -> part or None.
|
|
9
|
+
"""
|
|
10
|
+
from brickscape.config import SOURCE
|
|
11
|
+
|
|
12
|
+
# LDraw files that are the same mould under another number (suffix variants)
|
|
13
|
+
ALIASES = {"3040": "3040b", "3023": "3023b", "6141": "4073", "4073": "6141", "3062": "3062b",
|
|
14
|
+
"3665": "3665a", "4460": "4460b", "3794": "15573", "3794b": "15573", "3069": "3069b",
|
|
15
|
+
"3068": "3068b", "3070": "3070b", "2654": "2654a", "4032": "4032a", "3741": "3741a",
|
|
16
|
+
"4287": "4287a", "4460a": "4460b", "3678a": "3678b", "3684": "3684c", "3684a": "3684c",
|
|
17
|
+
"3040a": "3040b"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def candidates(part):
|
|
21
|
+
p = part.lower()
|
|
22
|
+
out = [p, ALIASES.get(p, ""), p.rstrip("abcd"), p + "b", p + "a"]
|
|
23
|
+
seen = []
|
|
24
|
+
for c in out:
|
|
25
|
+
if c and c not in seen:
|
|
26
|
+
seen.append(c)
|
|
27
|
+
return seen
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Source:
|
|
31
|
+
name = "base"
|
|
32
|
+
|
|
33
|
+
def resolve(self, part): # pragma: no cover - interface
|
|
34
|
+
raise NotImplementedError
|
|
35
|
+
|
|
36
|
+
def colours(self, part):
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
def price(self, part):
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
def substitute(self, part):
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
def check(self, counts):
|
|
46
|
+
"""counts: {(part, colour): n}. -> report dict used by validate and parts lists."""
|
|
47
|
+
rep = {"source": self.name, "pieces": 0, "missing": {}, "bad_colour": {}, "substitutes": {},
|
|
48
|
+
"cost_usd": None}
|
|
49
|
+
cost, priced = 0.0, True
|
|
50
|
+
for (p, c), n in counts.items():
|
|
51
|
+
rep["pieces"] += n
|
|
52
|
+
r = self.resolve(p)
|
|
53
|
+
if not r:
|
|
54
|
+
s = self.substitute(p)
|
|
55
|
+
if s and self.resolve(s):
|
|
56
|
+
rep["substitutes"][p] = s
|
|
57
|
+
r = self.resolve(s)
|
|
58
|
+
else:
|
|
59
|
+
rep["missing"][p] = rep["missing"].get(p, 0) + n
|
|
60
|
+
continue
|
|
61
|
+
cols = self.colours(r)
|
|
62
|
+
if cols is not None and int(c) not in cols:
|
|
63
|
+
rep["bad_colour"][f"{p}/{c}"] = n
|
|
64
|
+
pr = self.price(r)
|
|
65
|
+
if pr is None:
|
|
66
|
+
priced = False
|
|
67
|
+
else:
|
|
68
|
+
cost += pr * n
|
|
69
|
+
rep["cost_usd"] = round(cost, 2) if priced else None
|
|
70
|
+
return rep
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_cache = {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get(name=None):
|
|
77
|
+
name = (name or SOURCE).lower()
|
|
78
|
+
if name not in _cache:
|
|
79
|
+
if name == "lego":
|
|
80
|
+
from brickscape.catalog.lego import Lego
|
|
81
|
+
_cache[name] = Lego()
|
|
82
|
+
elif name == "gobricks":
|
|
83
|
+
from brickscape.catalog.gobricks import GoBricks
|
|
84
|
+
_cache[name] = GoBricks()
|
|
85
|
+
else:
|
|
86
|
+
raise ValueError(f"unknown part source {name!r} (use 'lego' or 'gobricks')")
|
|
87
|
+
return _cache[name]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_RGB = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def rgb(code):
|
|
94
|
+
"""LDraw colour code -> (r, g, b) from LDConfig.ldr."""
|
|
95
|
+
global _RGB
|
|
96
|
+
if _RGB is None:
|
|
97
|
+
import os, re
|
|
98
|
+
from brickscape.config import LDRAW
|
|
99
|
+
_RGB = {}
|
|
100
|
+
for line in open(os.path.join(LDRAW, "LDConfig.ldr"), errors="ignore"):
|
|
101
|
+
m = re.match(r"0 !COLOUR (\S+)\s+CODE\s+(\d+)\s+VALUE\s+#([0-9A-Fa-f]{6})", line)
|
|
102
|
+
if m:
|
|
103
|
+
h = m.group(3)
|
|
104
|
+
_RGB[int(m.group(2))] = (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16), "ALPHA" in line)
|
|
105
|
+
return _RGB.get(int(code))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _lab(c):
|
|
109
|
+
"""sRGB (0-255) -> CIE L*a*b*."""
|
|
110
|
+
def lin(v):
|
|
111
|
+
v /= 255
|
|
112
|
+
return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
|
|
113
|
+
r, g, b = (lin(v) for v in c[:3])
|
|
114
|
+
X = (0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.9505
|
|
115
|
+
Y = 0.2126 * r + 0.7152 * g + 0.0722 * b
|
|
116
|
+
Z = (0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.089
|
|
117
|
+
f = lambda t: t ** (1 / 3) if t > 0.008856 else 7.787 * t + 16 / 116
|
|
118
|
+
return (116 * f(Y) - 16, 500 * (f(X) - f(Y)), 200 * (f(Y) - f(Z)))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def nearest_colour(src, part, code):
|
|
122
|
+
"""The colour closest to `code` that the part exists in at this source (same transparency),
|
|
123
|
+
or None if the source knows no colours for the part."""
|
|
124
|
+
r = src.resolve(part)
|
|
125
|
+
cols = src.colours(r) if r else None
|
|
126
|
+
if not cols:
|
|
127
|
+
return None
|
|
128
|
+
if int(code) in cols:
|
|
129
|
+
return int(code)
|
|
130
|
+
c0 = rgb(code)
|
|
131
|
+
if c0 is None:
|
|
132
|
+
return None
|
|
133
|
+
L0 = _lab(c0)
|
|
134
|
+
best, bd = None, 1e9
|
|
135
|
+
for c in cols:
|
|
136
|
+
c1 = rgb(c)
|
|
137
|
+
if c1 is None or c1[3] != c0[3]:
|
|
138
|
+
continue
|
|
139
|
+
L1 = _lab(c1)
|
|
140
|
+
d = sum((a - b) ** 2 for a, b in zip(L0, L1)) ** 0.5
|
|
141
|
+
ch0, ch1 = (L0[1] ** 2 + L0[2] ** 2) ** 0.5, (L1[1] ** 2 + L1[2] ** 2) ** 0.5
|
|
142
|
+
if ch0 > 15 and ch1 < 10:
|
|
143
|
+
d += 40 # a coloured part should stay coloured, not go grey/black
|
|
144
|
+
if d < bd:
|
|
145
|
+
best, bd = c, d
|
|
146
|
+
return best
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def fix_colours(b, source=None):
|
|
150
|
+
"""Recolour parts whose colour doesn't exist for them at the source to the nearest one that
|
|
151
|
+
does. -> {"part/old": new}."""
|
|
152
|
+
src = get(source)
|
|
153
|
+
out = {}
|
|
154
|
+
for i, p in enumerate(b.pieces):
|
|
155
|
+
if i in b.roots:
|
|
156
|
+
continue
|
|
157
|
+
n = nearest_colour(src, p.part, p.color)
|
|
158
|
+
if n is not None and n != p.color:
|
|
159
|
+
out[f"{p.part}/{p.color}"] = n
|
|
160
|
+
p.color = n
|
|
161
|
+
return out
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""GoBricks (brickwith.com) catalog: what we can actually buy.
|
|
2
|
+
|
|
3
|
+
Files (catalog/):
|
|
4
|
+
gobricks_parts.csv/.json : every GoBricks part (1721): GDS code, LDraw id, name, category,
|
|
5
|
+
number of colours, min/max price (USD), popularity
|
|
6
|
+
gobricks_colours.json : GoBricks colour id -> LDraw colour id, name, hex
|
|
7
|
+
gobricks_part_colours.json: cache {ldraw part: [LDraw colour ids available]} (fetched per part)
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
python3 -I tools/catalog.py check model.ldr # what's buyable, cost estimate, substitutes
|
|
11
|
+
python3 -I tools/catalog.py fetch 3024 3005 # fill the colour cache for parts (1 s apart)
|
|
12
|
+
"""
|
|
13
|
+
import os, sys, json, re, time, subprocess, collections
|
|
14
|
+
from brickscape.config import DATA
|
|
15
|
+
from brickscape.catalog import Source, candidates
|
|
16
|
+
CAT = os.path.join(DATA, "gobricks")
|
|
17
|
+
BASE = "https://www.brickwith.com/en/parts/x/{}"
|
|
18
|
+
|
|
19
|
+
# LDraw parts that are the same mould under another number (old/new suffixes, variants)
|
|
20
|
+
ALIASES = {"3040": "3040b", "3023": "3023b", "6141": "4073", "4073": "6141", "3062": "3062b",
|
|
21
|
+
"3665": "3665a", "60481": "60481", "4460": "4460b", "3794": "15573", "3794b": "15573",
|
|
22
|
+
"3069": "3069b", "3068": "3068b", "3070": "3070b", "2654": "2654a", "4032": "4032a",
|
|
23
|
+
"3741": "3741a", "4287": "4287a", "4460a": "4460b", "3678a": "3678b", "3684": "3684c",
|
|
24
|
+
"3684a": "3684c", "3040a": "3040b", "60481a": "60481a"}
|
|
25
|
+
# not sold: nearest GoBricks part with the same look/role (used by check() as a suggestion)
|
|
26
|
+
SUBSTITUTE = {"2339": "76768", # Arch 1x5x4 -> Arch 1x5x4 irregular bow
|
|
27
|
+
"4589": "59900", # Cone 1x1 -> Cone 1x1 with top groove
|
|
28
|
+
"92947": "3941", # Round 2x2 with grille -> Round 2x2 with axle hole
|
|
29
|
+
"87620": None, # Brick 2x2 facet: not sold (use 2x2 corner bricks / slopes)
|
|
30
|
+
"4150": "14769", "26601": "2450", "11212": "3031"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _load(name, default):
|
|
34
|
+
p = os.path.join(CAT, name)
|
|
35
|
+
return json.load(open(p)) if os.path.exists(p) else default
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parts():
|
|
39
|
+
rows = _load("gobricks_parts.json", [])
|
|
40
|
+
by = {}
|
|
41
|
+
for r in rows:
|
|
42
|
+
if r["ldraw"]:
|
|
43
|
+
by.setdefault(r["ldraw"].lower(), r)
|
|
44
|
+
return by
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def lookup(part, table=None):
|
|
48
|
+
table = table or parts()
|
|
49
|
+
p = part.lower()
|
|
50
|
+
for cand in (p, ALIASES.get(p, ""), p.rstrip("abcd"), p + "b", p + "a"):
|
|
51
|
+
if cand and cand in table:
|
|
52
|
+
return table[cand]
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fetch_colours(ldraw_ids, delay=1.0):
|
|
57
|
+
"""Fetch the available colours of parts (one polite request per part) into the cache."""
|
|
58
|
+
cache = _load("gobricks_part_colours.json", {})
|
|
59
|
+
cols = _load("gobricks_colours.json", {})
|
|
60
|
+
table = parts()
|
|
61
|
+
for pid in ldraw_ids:
|
|
62
|
+
r = lookup(pid, table)
|
|
63
|
+
if not r or r["ldraw"] in cache:
|
|
64
|
+
continue
|
|
65
|
+
out = subprocess.run(["curl", "-s", "-H", "RSC: 1", BASE.format(r["ldraw"])],
|
|
66
|
+
capture_output=True, text=True).stdout
|
|
67
|
+
for m in re.finditer(r'\{"color_id":"(\d+)","color_hex_value":"([^"]*)","ldraw_color_id":"([^"]*)"'
|
|
68
|
+
r'[^{}]*?"color_name":"([^"]*)"', out):
|
|
69
|
+
cols[m.group(1)] = {"ldraw": m.group(3), "hex": m.group(2), "name": m.group(4)}
|
|
70
|
+
skus = set(re.findall(r'"sku_code":"%s-(\d+)"' % re.escape(r["gobricks"]), out))
|
|
71
|
+
cache[r["ldraw"]] = sorted({cols[c]["ldraw"] for c in skus if c in cols and cols[c]["ldraw"]},
|
|
72
|
+
key=lambda v: int(v) if v.isdigit() else 0)
|
|
73
|
+
print(f" {r['ldraw']:8s} {len(cache[r['ldraw']])} colours", flush=True)
|
|
74
|
+
json.dump(cache, open(os.path.join(CAT, "gobricks_part_colours.json"), "w")) # save as we go
|
|
75
|
+
json.dump(cols, open(os.path.join(CAT, "gobricks_colours.json"), "w"), indent=0)
|
|
76
|
+
time.sleep(delay)
|
|
77
|
+
json.dump(cache, open(os.path.join(CAT, "gobricks_part_colours.json"), "w"))
|
|
78
|
+
json.dump(cols, open(os.path.join(CAT, "gobricks_colours.json"), "w"), indent=0)
|
|
79
|
+
return cache
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def check(ldr):
|
|
83
|
+
"""Part list of a model against the catalog: buyable?, colour available?, estimated cost."""
|
|
84
|
+
table = parts()
|
|
85
|
+
cache = _load("gobricks_part_colours.json", {})
|
|
86
|
+
cnt = collections.Counter()
|
|
87
|
+
for l in open(ldr):
|
|
88
|
+
t = l.split()
|
|
89
|
+
if t[:1] == ["1"]:
|
|
90
|
+
cnt[(t[-1][:-4], t[1])] += 1
|
|
91
|
+
total, missing, badcol, cost, subs = 0, collections.Counter(), collections.Counter(), 0.0, {}
|
|
92
|
+
for (p, c), n in cnt.items():
|
|
93
|
+
if p.lower() in ("3811",):
|
|
94
|
+
continue
|
|
95
|
+
total += n
|
|
96
|
+
r = lookup(p, table)
|
|
97
|
+
if not r and SUBSTITUTE.get(p):
|
|
98
|
+
r = lookup(SUBSTITUTE[p], table)
|
|
99
|
+
subs[p] = SUBSTITUTE[p]
|
|
100
|
+
if not r:
|
|
101
|
+
missing[p] += n
|
|
102
|
+
continue
|
|
103
|
+
cost += n * r["min_price"]
|
|
104
|
+
avail = cache.get(r["ldraw"])
|
|
105
|
+
if avail is not None and c not in avail:
|
|
106
|
+
badcol[(p, c)] += n
|
|
107
|
+
return {"pieces": total, "cost_usd": round(cost, 2), "not_sold": missing.most_common(),
|
|
108
|
+
"colour_not_sold": badcol.most_common(), "lots": len(cnt), "substituted": subs}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
if sys.argv[1] == "fetch":
|
|
113
|
+
fetch_colours(sys.argv[2:])
|
|
114
|
+
elif sys.argv[1] == "check":
|
|
115
|
+
r = check(sys.argv[2])
|
|
116
|
+
print(f"{r['pieces']} pieces, {r['lots']} part/colour lots, est. ${r['cost_usd']} at GoBricks min prices")
|
|
117
|
+
print("not sold by GoBricks:", r["not_sold"][:30])
|
|
118
|
+
print("substituted:", r["substituted"])
|
|
119
|
+
print("colour not sold (only for parts in the colour cache):", r["colour_not_sold"][:30])
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class GoBricks(Source):
|
|
123
|
+
name = "gobricks"
|
|
124
|
+
|
|
125
|
+
def __init__(self):
|
|
126
|
+
self.table = parts()
|
|
127
|
+
if not self.table:
|
|
128
|
+
raise RuntimeError(f"GoBricks catalog missing ({CAT}/gobricks_parts.json)")
|
|
129
|
+
self.cache = _load("gobricks_part_colours.json", {})
|
|
130
|
+
|
|
131
|
+
def resolve(self, part):
|
|
132
|
+
for c in candidates(part):
|
|
133
|
+
if c in self.table:
|
|
134
|
+
return self.table[c]["ldraw"]
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
def colours(self, part):
|
|
138
|
+
v = self.cache.get(part)
|
|
139
|
+
return None if v is None else {int(c) for c in v}
|
|
140
|
+
|
|
141
|
+
def price(self, part):
|
|
142
|
+
r = self.table.get(part.lower())
|
|
143
|
+
return r and r["min_price"]
|
|
144
|
+
|
|
145
|
+
def substitute(self, part):
|
|
146
|
+
return SUBSTITUTE.get(part)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Official LEGO parts, from Rebrickable's CSV downloads (https://rebrickable.com/downloads/).
|
|
2
|
+
|
|
3
|
+
`brickscape setup` downloads parts.csv.gz, colors.csv.gz and elements.csv.gz into
|
|
4
|
+
BRICKSCAPE_DATA/rebrickable. A part/colour pair counts as real when LEGO produced an element
|
|
5
|
+
for it. Rebrickable colour ids follow LDraw colour codes only for the basic colours (olive
|
|
6
|
+
green, the trans blues and others differ), so colours are matched by name against the LDraw
|
|
7
|
+
library's LDConfig.ldr.
|
|
8
|
+
"""
|
|
9
|
+
import csv, gzip, os, re, urllib.request
|
|
10
|
+
from brickscape.config import DATA, LDRAW
|
|
11
|
+
from brickscape.catalog import Source, candidates
|
|
12
|
+
|
|
13
|
+
URL = "https://cdn.rebrickable.com/media/downloads/{}.csv.gz"
|
|
14
|
+
FILES = ("parts", "colors", "elements")
|
|
15
|
+
DIR = os.path.join(DATA, "rebrickable")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _norm(n):
|
|
19
|
+
n = n.lower().replace("gray", "grey").replace("_", " ").replace("-", " ")
|
|
20
|
+
n = n.replace("lt ", "light ").replace("dk ", "dark ")
|
|
21
|
+
return re.sub(r"[^a-z0-9]", "", n)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def colour_map():
|
|
25
|
+
"""Rebrickable colour id -> LDraw colour code (by name; unmatched exotic colours dropped)."""
|
|
26
|
+
ld = {}
|
|
27
|
+
for line in open(os.path.join(LDRAW, "LDConfig.ldr"), errors="ignore"):
|
|
28
|
+
m = re.match(r"0 !COLOUR (\S+)\s+CODE\s+(\d+)", line)
|
|
29
|
+
if m:
|
|
30
|
+
ld[_norm(m.group(1))] = int(m.group(2))
|
|
31
|
+
return {int(r["id"]): ld[_norm(r["name"])] for r in _rows("colors") if _norm(r["name"]) in ld}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def download(force=False):
|
|
35
|
+
os.makedirs(DIR, exist_ok=True)
|
|
36
|
+
for f in FILES:
|
|
37
|
+
out = os.path.join(DIR, f + ".csv.gz")
|
|
38
|
+
if os.path.exists(out) and not force:
|
|
39
|
+
continue
|
|
40
|
+
req = urllib.request.Request(URL.format(f), headers={"User-Agent": "brickscape"})
|
|
41
|
+
with urllib.request.urlopen(req, timeout=120) as r, open(out, "wb") as w:
|
|
42
|
+
w.write(r.read())
|
|
43
|
+
return DIR
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _rows(name):
|
|
47
|
+
path = os.path.join(DIR, name + ".csv.gz")
|
|
48
|
+
if not os.path.exists(path):
|
|
49
|
+
raise RuntimeError(f"official LEGO part data missing ({path}): run `brickscape setup`")
|
|
50
|
+
with gzip.open(path, "rt", encoding="utf-8") as f:
|
|
51
|
+
yield from csv.DictReader(f)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Lego(Source):
|
|
55
|
+
name = "lego"
|
|
56
|
+
|
|
57
|
+
def __init__(self):
|
|
58
|
+
self.parts = {r["part_num"].lower(): r["name"] for r in _rows("parts")}
|
|
59
|
+
self.cols, cmap = {}, colour_map()
|
|
60
|
+
for r in _rows("elements"):
|
|
61
|
+
c = cmap.get(int(r["color_id"]))
|
|
62
|
+
if c is not None:
|
|
63
|
+
self.cols.setdefault(r["part_num"].lower(), set()).add(c)
|
|
64
|
+
|
|
65
|
+
def resolve(self, part):
|
|
66
|
+
for c in candidates(part):
|
|
67
|
+
if c in self.parts:
|
|
68
|
+
return c
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
def colours(self, part):
|
|
72
|
+
return self.cols.get(part)
|
brickscape/config.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Where brickscape finds things. Everything can be overridden with environment variables.
|
|
2
|
+
|
|
3
|
+
LDRAW_LIBRARY_PATH LDraw parts library (default ~/.ldraw; `ldraw-mcp-setup` installs it)
|
|
4
|
+
LDRAW_MCP_BLENDER Blender binary (default: `blender` on PATH, via ldraw-mcp)
|
|
5
|
+
BRICKSCAPE_DATA catalog cache (default ~/.cache/brickscape)
|
|
6
|
+
BRICKSCAPE_SOURCE default part source: "lego" (default) or "gobricks"
|
|
7
|
+
"""
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
LDRAW = os.path.expanduser(os.environ.get("LDRAW_LIBRARY_PATH", "~/.ldraw"))
|
|
11
|
+
DATA = os.path.expanduser(os.environ.get("BRICKSCAPE_DATA", "~/.cache/brickscape"))
|
|
12
|
+
SOURCE = os.environ.get("BRICKSCAPE_SOURCE", "lego")
|
|
13
|
+
PKG = os.path.dirname(os.path.abspath(__file__))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def blender():
|
|
17
|
+
from ldraw_mcp.render import find_blender
|
|
18
|
+
b = find_blender()
|
|
19
|
+
if not b:
|
|
20
|
+
raise RuntimeError("Blender not found: install Blender 4.x or set LDRAW_MCP_BLENDER")
|
|
21
|
+
return b
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def blender_script():
|
|
25
|
+
import ldraw_mcp
|
|
26
|
+
return os.path.join(os.path.dirname(ldraw_mcp.__file__), "blender_script.py")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|