@floless/app 0.174.0 → 0.174.1
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.
- package/dist/floless-server.cjs +2 -2
- package/dist/pdf-engine/floless_pdf/__init__.py +49 -0
- package/dist/pdf-engine/floless_pdf/backend_pdfium.py +544 -0
- package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +223 -0
- package/dist/pdf-engine/floless_pdf/geometry.py +115 -0
- package/dist/pdf-engine/floless_pdf/images.py +74 -0
- package/dist/pdf-engine/floless_pdf/textrules.py +200 -0
- package/dist/schemas/steel.model.v2.schema.json +1 -0
- package/dist/skills/floless-app-steel-model/SKILL.md +4 -1
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +8 -2
- package/dist/skills/floless-app-tweak-contract/SKILL.md +3 -2
- package/dist/web/commands-steel.js +2 -1
- package/dist/web/model-change-findings.js +53 -8
- package/dist/web/model-change-review.js +24 -5
- package/dist/web/revit-editor.js +2 -0
- package/dist/web/steel-change-review.css +1 -0
- package/dist/web/steel-model-commands.js +1 -1
- package/dist/web/vendor/connection-engine.js +6 -0
- package/package.json +3 -1
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""The pymupdf backend: a thin pass-through to PyMuPDF, the reference while readers migrate (plan section 3.1).
|
|
2
|
+
|
|
3
|
+
It hands back what PyMuPDF reports, reshaped into FloLess's API but with every number as PyMuPDF gave it, so a reader
|
|
4
|
+
moved onto the module with this backend selected passes its existing goldens unchanged. Pictures use MuPDF's own
|
|
5
|
+
encoder for the same reason. Removed in slice 9, with PyMuPDF.
|
|
6
|
+
"""
|
|
7
|
+
import math
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
import pymupdf as fitz
|
|
12
|
+
except ImportError:
|
|
13
|
+
from contextlib import redirect_stdout
|
|
14
|
+
with redirect_stdout(sys.stderr):
|
|
15
|
+
import fitz
|
|
16
|
+
fitz.TOOLS.mupdf_display_errors(False)
|
|
17
|
+
|
|
18
|
+
# MuPDF's default dict/rawdict flags carry every picture's bytes along with the text; on a sheet with large pictures that
|
|
19
|
+
# took minutes for no text. The text is the same without them.
|
|
20
|
+
_TEXT_ONLY = fitz.TEXTFLAGS_DICT & ~fitz.TEXT_PRESERVE_IMAGES
|
|
21
|
+
_TEXT_ONLY_RAW = fitz.TEXTFLAGS_RAWDICT & ~fitz.TEXT_PRESERVE_IMAGES
|
|
22
|
+
|
|
23
|
+
from .geometry import Matrix, Point, Rect, rotation_matrix
|
|
24
|
+
|
|
25
|
+
NAME = "pymupdf"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def versions():
|
|
29
|
+
return {"pymupdf": str(fitz.VersionBind), "mupdf": str(fitz.VersionFitz)}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _pt(p):
|
|
33
|
+
return Point(p.x, p.y)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _rect(r):
|
|
37
|
+
return Rect(r.x0, r.y0, r.x1, r.y1)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _items(items):
|
|
41
|
+
out = []
|
|
42
|
+
for it in items:
|
|
43
|
+
kind = it[0]
|
|
44
|
+
if kind == "re":
|
|
45
|
+
out.append(("re", _rect(it[1]), int(it[2]) if len(it) > 2 else 1))
|
|
46
|
+
elif kind == "qu":
|
|
47
|
+
q = it[1]
|
|
48
|
+
out.append(("qu", _pt(q.ul), _pt(q.ur), _pt(q.ll), _pt(q.lr)))
|
|
49
|
+
else:
|
|
50
|
+
out.append((kind,) + tuple(_pt(p) for p in it[1:]))
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# Annotation subtypes whose appearance MuPDF draws into the page but which are not markups a reviewer added.
|
|
55
|
+
_NOT_MARKUP = {"Link", "Popup"}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Page:
|
|
59
|
+
def __init__(self, doc, number):
|
|
60
|
+
self._doc = doc
|
|
61
|
+
self._page = doc._doc[number]
|
|
62
|
+
self.number = number
|
|
63
|
+
self.rotation = self._page.rotation % 360
|
|
64
|
+
crop = self._page.cropbox
|
|
65
|
+
self.unrotated_size = (crop.width, crop.height)
|
|
66
|
+
r = self._page.rect
|
|
67
|
+
self.size = (r.width, r.height)
|
|
68
|
+
self.rotation_matrix = rotation_matrix(self.rotation, crop.width, crop.height)
|
|
69
|
+
self._markup = None
|
|
70
|
+
|
|
71
|
+
# ---- what came from annotations (markups) ------------------------------------------------------------------
|
|
72
|
+
def _markup_keys(self):
|
|
73
|
+
"""The drawings and characters that only an annotation appearance contributes, read by comparing the page
|
|
74
|
+
with a copy whose markup annotations are taken off. Only pages that carry such annotations pay for it."""
|
|
75
|
+
if self._markup is not None:
|
|
76
|
+
return self._markup
|
|
77
|
+
kinds = [a.type[1] for a in self._page.annots()] if self._page.first_annot else []
|
|
78
|
+
if not [k for k in kinds if k not in _NOT_MARKUP]:
|
|
79
|
+
self._markup = (set(), set())
|
|
80
|
+
return self._markup
|
|
81
|
+
bare = fitz.open()
|
|
82
|
+
bare.insert_pdf(self._doc._doc, from_page=self.number, to_page=self.number, annots=False)
|
|
83
|
+
page = bare[0]
|
|
84
|
+
drawings = {_drawing_key(d) for d in page.get_drawings()}
|
|
85
|
+
chars = {_char_key(c) for c in _raw_chars(page)}
|
|
86
|
+
bare.close()
|
|
87
|
+
self._markup = (drawings, chars)
|
|
88
|
+
return self._markup
|
|
89
|
+
|
|
90
|
+
# ---- text ---------------------------------------------------------------------------------------------------
|
|
91
|
+
def chars(self):
|
|
92
|
+
drawings_bare, chars_bare = self._markup_keys()
|
|
93
|
+
annotated = bool(chars_bare) or bool(drawings_bare)
|
|
94
|
+
out = []
|
|
95
|
+
for c in _raw_chars(self._page):
|
|
96
|
+
c["markup"] = annotated and _char_key(c) not in chars_bare
|
|
97
|
+
out.append(c)
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
def lines(self):
|
|
101
|
+
out = []
|
|
102
|
+
for block in self._page.get_text("dict", flags=_TEXT_ONLY)["blocks"]:
|
|
103
|
+
if block.get("type") != 0:
|
|
104
|
+
continue
|
|
105
|
+
for line in block["lines"]:
|
|
106
|
+
out.append({"bbox": Rect(*line["bbox"]), "dir": tuple(line["dir"]), "spans": [
|
|
107
|
+
{"text": s["text"], "bbox": Rect(*s["bbox"]), "size": s["size"], "font": s["font"],
|
|
108
|
+
"color": s["color"], "flags": s["flags"], "origin": Point(*s["origin"])} for s in line["spans"]]})
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
def words(self):
|
|
112
|
+
return [tuple(w) for w in self._page.get_text("words")]
|
|
113
|
+
|
|
114
|
+
def text(self):
|
|
115
|
+
return self._page.get_text("text")
|
|
116
|
+
|
|
117
|
+
# ---- linework -----------------------------------------------------------------------------------------------
|
|
118
|
+
def drawings(self):
|
|
119
|
+
bare, _ = self._markup_keys()
|
|
120
|
+
out = []
|
|
121
|
+
clips = [] # (level, scissor) of the clips the next drawing is inside
|
|
122
|
+
for d in self._page.get_drawings(extended=True):
|
|
123
|
+
level = d.get("level", 0)
|
|
124
|
+
while clips and clips[-1][0] >= level:
|
|
125
|
+
clips.pop()
|
|
126
|
+
if d["type"] == "clip":
|
|
127
|
+
clips.append((level, _rect(d["scissor"])))
|
|
128
|
+
continue
|
|
129
|
+
if d["type"] == "group":
|
|
130
|
+
continue
|
|
131
|
+
clip = None
|
|
132
|
+
for _, scissor in clips:
|
|
133
|
+
clip = scissor if clip is None else clip.intersect(scissor)
|
|
134
|
+
rect = _rect(d["rect"])
|
|
135
|
+
row = {
|
|
136
|
+
"type": d["type"], "items": _items(d["items"]), "rect": rect, "clip": clip,
|
|
137
|
+
"visible": rect.intersect(clip) if clip is not None else rect,
|
|
138
|
+
"width": d.get("width"), "color": d.get("color"), "fill": d.get("fill"),
|
|
139
|
+
"dashes": d.get("dashes"), "even_odd": d.get("even_odd"), "closePath": d.get("closePath"),
|
|
140
|
+
"layer": d.get("layer") or "", "markup": bool(bare) and _drawing_key(d) not in bare,
|
|
141
|
+
}
|
|
142
|
+
out.append(row)
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
# ---- pictures -----------------------------------------------------------------------------------------------
|
|
146
|
+
def _pixmap(self, scale=None, dpi=None, clip=None):
|
|
147
|
+
kw = {"alpha": False}
|
|
148
|
+
if clip is not None:
|
|
149
|
+
kw["clip"] = fitz.Rect(*clip)
|
|
150
|
+
if dpi is not None:
|
|
151
|
+
return self._page.get_pixmap(dpi=int(dpi), **kw)
|
|
152
|
+
return self._page.get_pixmap(matrix=fitz.Matrix(scale or 1.0, scale or 1.0), **kw)
|
|
153
|
+
|
|
154
|
+
def render_jpeg(self, scale=None, dpi=None, clip=None, quality=95):
|
|
155
|
+
pm = self._pixmap(scale, dpi, clip)
|
|
156
|
+
return pm.tobytes("jpeg", jpg_quality=int(quality)), (pm.width, pm.height)
|
|
157
|
+
|
|
158
|
+
def render_png(self, scale=None, dpi=None, clip=None):
|
|
159
|
+
pm = self._pixmap(scale, dpi, clip)
|
|
160
|
+
return pm.tobytes("png"), (pm.width, pm.height)
|
|
161
|
+
|
|
162
|
+
def render(self, scale=None, dpi=None, clip=None):
|
|
163
|
+
"""The rendered page as a Pillow RGB image (for comparisons; readers use render_jpeg/png)."""
|
|
164
|
+
from PIL import Image # noqa: PLC0415
|
|
165
|
+
pm = self._pixmap(scale, dpi, clip)
|
|
166
|
+
return Image.frombytes("RGB", (pm.width, pm.height), pm.samples)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _raw_chars(page):
|
|
170
|
+
out = []
|
|
171
|
+
for block in page.get_text("rawdict", flags=_TEXT_ONLY_RAW)["blocks"]:
|
|
172
|
+
if block.get("type") != 0:
|
|
173
|
+
continue
|
|
174
|
+
for line in block["lines"]:
|
|
175
|
+
for span in line["spans"]:
|
|
176
|
+
for ch in span["chars"]:
|
|
177
|
+
out.append({"c": ch["c"], "box": Rect(*ch["bbox"]), "origin": Point(*ch["origin"]),
|
|
178
|
+
"size": span["size"], "font": span["font"], "color": span["color"],
|
|
179
|
+
"flags": span["flags"], "dir": tuple(line["dir"]),
|
|
180
|
+
# The same keys the pdfium backend gives: the baseline angle (counter-clockwise, in
|
|
181
|
+
# radians, as on the sheet) and the layer, which MuPDF's text reader does not report.
|
|
182
|
+
"angle": round(math.atan2(-line["dir"][1], line["dir"][0]), 4), "layer": ""})
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _char_key(c):
|
|
187
|
+
b = c["box"]
|
|
188
|
+
return (c["c"], round(b.x0, 2), round(b.y0, 2), round(b.x1, 2), round(b.y1, 2))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _drawing_key(d):
|
|
192
|
+
r = d["rect"]
|
|
193
|
+
rect = (r.x0, r.y0, r.x1, r.y1) if hasattr(r, "x0") else tuple(r)
|
|
194
|
+
return (d["type"], len(d["items"]),) + tuple(round(v, 2) for v in rect)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class Document:
|
|
198
|
+
def __init__(self, source):
|
|
199
|
+
if isinstance(source, (bytes, bytearray)):
|
|
200
|
+
self._doc = fitz.open(stream=bytes(source), filetype="pdf")
|
|
201
|
+
else:
|
|
202
|
+
self._doc = fitz.open(source)
|
|
203
|
+
if self._doc.needs_pass:
|
|
204
|
+
self._doc.close()
|
|
205
|
+
raise PermissionError("the PDF needs a password")
|
|
206
|
+
self.page_count = self._doc.page_count
|
|
207
|
+
self.engine = {"name": NAME, **versions()}
|
|
208
|
+
|
|
209
|
+
def page(self, number):
|
|
210
|
+
if not 0 <= number < self.page_count:
|
|
211
|
+
raise IndexError("page %d of %d" % (number + 1, self.page_count))
|
|
212
|
+
return Page(self, number)
|
|
213
|
+
|
|
214
|
+
def layers(self):
|
|
215
|
+
"""Every layer (optional content group) with its default visibility, in the document's own order."""
|
|
216
|
+
return [{"name": v.get("name", ""), "on": bool(v.get("on"))} for _, v in sorted(self._doc.get_ocgs().items())]
|
|
217
|
+
|
|
218
|
+
def structure_error(self):
|
|
219
|
+
"""Why the layer structure could not be read, or None. MuPDF reads it with the page, so always None."""
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
def close(self):
|
|
223
|
+
self._doc.close()
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Point, Rect and Matrix for FloLess's PDF module (shared core).
|
|
2
|
+
|
|
3
|
+
Page space everywhere is the UNROTATED page: origin at the crop box's top-left corner, y growing down, in PDF
|
|
4
|
+
points. A reader that wants the page as shown applies `Page.rotation_matrix`, exactly as it does today.
|
|
5
|
+
Matrices follow the PDF convention [a b c d e f]; `m1.then(m2)` is "apply m1, then m2".
|
|
6
|
+
"""
|
|
7
|
+
import math
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Matrix:
|
|
11
|
+
__slots__ = ("a", "b", "c", "d", "e", "f")
|
|
12
|
+
|
|
13
|
+
def __init__(self, a=1.0, b=0.0, c=0.0, d=1.0, e=0.0, f=0.0):
|
|
14
|
+
self.a, self.b, self.c, self.d, self.e, self.f = float(a), float(b), float(c), float(d), float(e), float(f)
|
|
15
|
+
|
|
16
|
+
def then(self, m):
|
|
17
|
+
return Matrix(self.a * m.a + self.b * m.c, self.a * m.b + self.b * m.d,
|
|
18
|
+
self.c * m.a + self.d * m.c, self.c * m.b + self.d * m.d,
|
|
19
|
+
self.e * m.a + self.f * m.c + m.e, self.e * m.b + self.f * m.d + m.f)
|
|
20
|
+
|
|
21
|
+
def apply(self, x, y):
|
|
22
|
+
return (x * self.a + y * self.c + self.e, x * self.b + y * self.d + self.f)
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def expansion(self):
|
|
26
|
+
"""How much the matrix scales a length (the square root of its determinant's size)."""
|
|
27
|
+
return math.sqrt(abs(self.a * self.d - self.b * self.c))
|
|
28
|
+
|
|
29
|
+
def as_tuple(self):
|
|
30
|
+
return (self.a, self.b, self.c, self.d, self.e, self.f)
|
|
31
|
+
|
|
32
|
+
def __eq__(self, other):
|
|
33
|
+
return isinstance(other, Matrix) and self.as_tuple() == other.as_tuple()
|
|
34
|
+
|
|
35
|
+
def __repr__(self):
|
|
36
|
+
return "Matrix(%g, %g, %g, %g, %g, %g)" % self.as_tuple()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
IDENTITY = Matrix()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def rotation_matrix(rotation, width, height):
|
|
43
|
+
"""Unrotated page space to the page as shown, for a crop box `width` x `height` (PyMuPDF's convention)."""
|
|
44
|
+
return {0: IDENTITY, 90: Matrix(0, 1, -1, 0, height, 0),
|
|
45
|
+
180: Matrix(-1, 0, 0, -1, width, height), 270: Matrix(0, -1, 1, 0, 0, width)}[rotation % 360]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Point:
|
|
49
|
+
__slots__ = ("x", "y")
|
|
50
|
+
|
|
51
|
+
def __init__(self, x, y):
|
|
52
|
+
self.x, self.y = float(x), float(y)
|
|
53
|
+
|
|
54
|
+
def transform(self, m):
|
|
55
|
+
return Point(*m.apply(self.x, self.y))
|
|
56
|
+
|
|
57
|
+
def as_tuple(self):
|
|
58
|
+
return (self.x, self.y)
|
|
59
|
+
|
|
60
|
+
def __eq__(self, other):
|
|
61
|
+
return isinstance(other, Point) and self.as_tuple() == other.as_tuple()
|
|
62
|
+
|
|
63
|
+
def __iter__(self):
|
|
64
|
+
return iter((self.x, self.y))
|
|
65
|
+
|
|
66
|
+
def __repr__(self):
|
|
67
|
+
return "Point(%g, %g)" % (self.x, self.y)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Rect:
|
|
71
|
+
__slots__ = ("x0", "y0", "x1", "y1")
|
|
72
|
+
|
|
73
|
+
def __init__(self, x0, y0, x1, y1):
|
|
74
|
+
self.x0, self.y0, self.x1, self.y1 = float(x0), float(y0), float(x1), float(y1)
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def around(points):
|
|
78
|
+
xs = [p.x for p in points]
|
|
79
|
+
ys = [p.y for p in points]
|
|
80
|
+
return Rect(min(xs), min(ys), max(xs), max(ys))
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def width(self):
|
|
84
|
+
return self.x1 - self.x0
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def height(self):
|
|
88
|
+
return self.y1 - self.y0
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def empty(self):
|
|
92
|
+
return self.x1 <= self.x0 or self.y1 <= self.y0
|
|
93
|
+
|
|
94
|
+
def union(self, other):
|
|
95
|
+
return Rect(min(self.x0, other.x0), min(self.y0, other.y0), max(self.x1, other.x1), max(self.y1, other.y1))
|
|
96
|
+
|
|
97
|
+
def intersect(self, other):
|
|
98
|
+
r = Rect(max(self.x0, other.x0), max(self.y0, other.y0), min(self.x1, other.x1), min(self.y1, other.y1))
|
|
99
|
+
return r if not r.empty else Rect(r.x0, r.y0, max(r.x0, r.x1), max(r.y0, r.y1))
|
|
100
|
+
|
|
101
|
+
def transform(self, m):
|
|
102
|
+
corners = [Point(*m.apply(x, y)) for x in (self.x0, self.x1) for y in (self.y0, self.y1)]
|
|
103
|
+
return Rect.around(corners)
|
|
104
|
+
|
|
105
|
+
def as_tuple(self):
|
|
106
|
+
return (self.x0, self.y0, self.x1, self.y1)
|
|
107
|
+
|
|
108
|
+
def __eq__(self, other):
|
|
109
|
+
return isinstance(other, Rect) and self.as_tuple() == other.as_tuple()
|
|
110
|
+
|
|
111
|
+
def __iter__(self):
|
|
112
|
+
return iter(self.as_tuple())
|
|
113
|
+
|
|
114
|
+
def __repr__(self):
|
|
115
|
+
return "Rect(%g, %g, %g, %g)" % self.as_tuple()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Picture encoding and standalone image input (shared core; decision (b) of slice 1, Pillow).
|
|
2
|
+
|
|
3
|
+
Written down here and tested (server/pdf-engine/tests/test_images.py), because a tile or backdrop the AI sees is part
|
|
4
|
+
of what a reader produces:
|
|
5
|
+
|
|
6
|
+
- COLOUR: every picture is 8-bit RGB. A page is rendered as RGB on white; an image opened from a file is converted to
|
|
7
|
+
RGB (palette, greyscale and CMYK included) after its EXIF orientation is applied.
|
|
8
|
+
- ALPHA: never kept. A transparent image is laid on white first (straight alpha), so a transparent corner is white,
|
|
9
|
+
not black.
|
|
10
|
+
- JPEG: Pillow's encoder (libjpeg-turbo in the pinned wheel), baseline (not progressive), no optimisation pass, chroma
|
|
11
|
+
subsampling 4:2:0, quality from the caller (95 unless the reader asks for less; the Filter backdrop asks for 35).
|
|
12
|
+
- PNG: Pillow's encoder, compression level 6, no optimisation pass.
|
|
13
|
+
- DOWNSAMPLING: a render is made at the requested scale directly, never resampled. Making a picture smaller
|
|
14
|
+
(`fit_within`) is area averaging (Pillow's BOX filter), so a hairline fades rather than vanishes or turns jagged.
|
|
15
|
+
|
|
16
|
+
The pymupdf backend does not come here for pages: it passes MuPDF's own encoder through, unchanged, because its
|
|
17
|
+
output must stay byte-identical to today's readers.
|
|
18
|
+
"""
|
|
19
|
+
import io
|
|
20
|
+
|
|
21
|
+
JPEG_QUALITY = 95
|
|
22
|
+
JPEG_SUBSAMPLING = 2 # Pillow's code for 4:2:0
|
|
23
|
+
PNG_COMPRESS_LEVEL = 6
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _pil():
|
|
27
|
+
from PIL import Image, ImageOps # noqa: PLC0415 - Pillow is only needed by readers that make pictures
|
|
28
|
+
return Image, ImageOps
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_rgb(img):
|
|
32
|
+
"""8-bit RGB, any alpha laid on white."""
|
|
33
|
+
Image, _ = _pil()
|
|
34
|
+
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
|
35
|
+
rgba = img.convert("RGBA")
|
|
36
|
+
white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
|
|
37
|
+
return Image.alpha_composite(white, rgba).convert("RGB")
|
|
38
|
+
return img.convert("RGB") if img.mode != "RGB" else img
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def encode_jpeg(img, quality=JPEG_QUALITY):
|
|
42
|
+
q = int(quality)
|
|
43
|
+
if not 1 <= q <= 100:
|
|
44
|
+
raise ValueError("JPEG quality must be 1-100, got %r" % (quality,))
|
|
45
|
+
out = io.BytesIO()
|
|
46
|
+
to_rgb(img).save(out, "JPEG", quality=q, subsampling=JPEG_SUBSAMPLING, optimize=False, progressive=False)
|
|
47
|
+
return out.getvalue()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def encode_png(img):
|
|
51
|
+
out = io.BytesIO()
|
|
52
|
+
to_rgb(img).save(out, "PNG", compress_level=PNG_COMPRESS_LEVEL, optimize=False)
|
|
53
|
+
return out.getvalue()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fit_within(img, max_edge):
|
|
57
|
+
"""The picture made no longer than `max_edge` on its long side, by area averaging; unchanged when it fits."""
|
|
58
|
+
Image, _ = _pil()
|
|
59
|
+
w, h = img.size
|
|
60
|
+
if max_edge is None or max(w, h) <= max_edge:
|
|
61
|
+
return img
|
|
62
|
+
k = max_edge / float(max(w, h))
|
|
63
|
+
return img.resize((max(1, round(w * k)), max(1, round(h * k))), Image.Resampling.BOX)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def open_image(source, max_edge=None):
|
|
67
|
+
"""A standalone PNG/JPEG (a path or bytes) as RGB, EXIF orientation applied, optionally made smaller."""
|
|
68
|
+
Image, ImageOps = _pil()
|
|
69
|
+
data = source if isinstance(source, (bytes, bytearray)) else open(source, "rb").read()
|
|
70
|
+
img = Image.open(io.BytesIO(data))
|
|
71
|
+
if img.format not in ("PNG", "JPEG"):
|
|
72
|
+
raise ValueError("not a PNG or JPEG image (%s)" % (img.format or "unknown"))
|
|
73
|
+
img = ImageOps.exif_transpose(img)
|
|
74
|
+
return fit_within(to_rgb(img), max_edge)
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""FloLess's own text rules (plan section 3.3; shared core).
|
|
2
|
+
|
|
3
|
+
PDFium hands over characters with boxes, and its own segmentation is not what FloLess reads by: it glues labels that
|
|
4
|
+
sit apart on one baseline (grid bubbles "5" and "5.1" read as "55.1", D2) and puts a line break after every
|
|
5
|
+
upside-down glyph ("W14X26" read as six lines, D3). So lines, spaces and words are decided here, from glyph geometry,
|
|
6
|
+
by three rules:
|
|
7
|
+
|
|
8
|
+
- the GAP rule: along the baseline, a gap wider than GAP_BREAK x the font size, or a step back of more than
|
|
9
|
+
GAP_BACK x the size, ends the line; a gap wider than GAP_SPACE x the size is a space;
|
|
10
|
+
- the BASELINE rule: a glyph more than BASELINE_OFF x the size off the previous glyph's baseline ends the line;
|
|
11
|
+
- the DIRECTION rule: a glyph whose baseline runs another way starts a new line, and rotated text (not a multiple of
|
|
12
|
+
90 degrees) measures its gap between glyph centres, because its axis-aligned boxes overlap.
|
|
13
|
+
|
|
14
|
+
plus the hyphen mapping (PDFium marks a hyphen at a line end with the control character U+0002, which reads as "-")
|
|
15
|
+
and one space at most between two glyphs (PDFium's own space and the gap rule's never both count).
|
|
16
|
+
|
|
17
|
+
A char is a dict: {"c", "box" (Rect), "origin" (Point), "size", "angle" (radians, baseline direction in the unrotated
|
|
18
|
+
y-down page space), "font", "color", "flags", "layer", "generated" (PDFium made it, not the content)}. A line break
|
|
19
|
+
from the engine is {"c": "\\n", "generated": True}. Nothing here imports an engine.
|
|
20
|
+
"""
|
|
21
|
+
import math
|
|
22
|
+
|
|
23
|
+
GAP_BREAK = 1.0
|
|
24
|
+
GAP_BACK = 0.5
|
|
25
|
+
GAP_SPACE = 0.25
|
|
26
|
+
BASELINE_OFF = 0.6
|
|
27
|
+
ROTATED_GLYPH = 0.7 # for rotated text: the step between glyph centres, less this x the size, is the gap
|
|
28
|
+
AXIS_TOLERANCE = 0.05 # |sin(2 angle)| below this is axis-aligned text
|
|
29
|
+
HYPHEN_MARK = "\x02"
|
|
30
|
+
|
|
31
|
+
BREAK = {"c": "\n", "generated": True}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _space_like(c):
|
|
35
|
+
return c != "" and not c.strip()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _proj(box, ux, uy):
|
|
39
|
+
return [x * ux + y * uy for x, y in ((box.x0, box.y0), (box.x1, box.y0), (box.x0, box.y1), (box.x1, box.y1))]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def gap_and_offset(prev, cur):
|
|
43
|
+
"""(gap along the baseline, distance off the baseline), both in points, measured in `cur`'s direction."""
|
|
44
|
+
a = cur["angle"]
|
|
45
|
+
ux, uy = math.cos(a), math.sin(a)
|
|
46
|
+
pb, cb = prev["box"], cur["box"]
|
|
47
|
+
dx = ((cb.x0 + cb.x1) - (pb.x0 + pb.x1)) / 2
|
|
48
|
+
dy = ((cb.y0 + cb.y1) - (pb.y0 + pb.y1)) / 2
|
|
49
|
+
if abs(math.sin(2 * a)) < AXIS_TOLERANCE:
|
|
50
|
+
gap = min(_proj(cb, ux, uy)) - max(_proj(pb, ux, uy))
|
|
51
|
+
else:
|
|
52
|
+
gap = (dx * ux + dy * uy) - ROTATED_GLYPH * max(cur["size"], 1.0)
|
|
53
|
+
off = abs(-dx * uy + dy * ux)
|
|
54
|
+
return gap, off
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def angle_key(a):
|
|
58
|
+
"""An angle as one value per direction: in [0, 2*pi), rounded, so +pi and -pi (upside-down text whose matrix
|
|
59
|
+
carries float noise or a signed zero) are the same direction."""
|
|
60
|
+
a = round(a % (2 * math.pi), 3)
|
|
61
|
+
return 0.0 if a >= round(2 * math.pi, 3) else a
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def same_direction(a, b):
|
|
65
|
+
return abs(math.remainder(a - b, 2 * math.pi)) <= 1e-3
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def decide(prev, cur):
|
|
69
|
+
"""'break', 'space' or None between two visible glyphs."""
|
|
70
|
+
if not same_direction(cur["angle"], prev["angle"]):
|
|
71
|
+
return "break"
|
|
72
|
+
size = max(cur["size"], 1.0)
|
|
73
|
+
gap, off = gap_and_offset(prev, cur)
|
|
74
|
+
if gap > GAP_BREAK * size or gap < -GAP_BACK * size or off > BASELINE_OFF * size:
|
|
75
|
+
return "break"
|
|
76
|
+
if gap > GAP_SPACE * size:
|
|
77
|
+
return "space"
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def segment(chars):
|
|
82
|
+
"""The engine's char stream re-segmented by FloLess's rules: visible glyphs, real spaces, and BREAK markers."""
|
|
83
|
+
out = []
|
|
84
|
+
prev = None # the last visible glyph on the current line
|
|
85
|
+
last_space = False # the last thing emitted on this line is a space
|
|
86
|
+
pending = None # an engine-generated space waiting to see what follows
|
|
87
|
+
for ch in chars:
|
|
88
|
+
c = ch.get("c", "")
|
|
89
|
+
if c in ("\n", "\r"):
|
|
90
|
+
if ch.get("generated") and prev is not None:
|
|
91
|
+
continue # the engine's own line break: geometry decides (D3)
|
|
92
|
+
out.append(BREAK)
|
|
93
|
+
prev, last_space, pending = None, False, None
|
|
94
|
+
continue
|
|
95
|
+
if "box" not in ch:
|
|
96
|
+
continue
|
|
97
|
+
if c == HYPHEN_MARK:
|
|
98
|
+
ch = dict(ch, c="-")
|
|
99
|
+
c = "-"
|
|
100
|
+
if _space_like(c):
|
|
101
|
+
if prev is None:
|
|
102
|
+
continue
|
|
103
|
+
if ch.get("generated"):
|
|
104
|
+
pending = ch
|
|
105
|
+
elif not last_space:
|
|
106
|
+
out.append(ch)
|
|
107
|
+
last_space = True
|
|
108
|
+
pending = None
|
|
109
|
+
continue
|
|
110
|
+
if not c:
|
|
111
|
+
continue
|
|
112
|
+
if prev is not None:
|
|
113
|
+
verdict = decide(prev, ch)
|
|
114
|
+
if verdict == "break":
|
|
115
|
+
out.append(BREAK)
|
|
116
|
+
last_space = False
|
|
117
|
+
elif (verdict == "space" or pending is not None) and not last_space:
|
|
118
|
+
out.append(dict(prev, c=" ", generated=True))
|
|
119
|
+
pending = None
|
|
120
|
+
out.append(ch)
|
|
121
|
+
prev, last_space = ch, False
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _bbox(chars):
|
|
126
|
+
boxes = [c["box"] for c in chars if "box" in c]
|
|
127
|
+
if not boxes:
|
|
128
|
+
return None
|
|
129
|
+
bb = boxes[0]
|
|
130
|
+
for b in boxes[1:]:
|
|
131
|
+
bb = bb.union(b)
|
|
132
|
+
return bb
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def lines(chars):
|
|
136
|
+
"""Lines of spans. A span is one run of the same font, size, colour, direction and layer on one line."""
|
|
137
|
+
result, line, span, span_key = [], [], None, None
|
|
138
|
+
|
|
139
|
+
def close_span():
|
|
140
|
+
nonlocal span
|
|
141
|
+
if span:
|
|
142
|
+
visible = [c for c in span if not _space_like(c["c"])]
|
|
143
|
+
bb = _bbox(visible or span)
|
|
144
|
+
first = span[0]
|
|
145
|
+
line.append({"text": "".join(c["c"] for c in span), "bbox": bb, "size": first["size"],
|
|
146
|
+
"font": first.get("font", ""), "color": first.get("color", 0), "flags": first.get("flags", 0),
|
|
147
|
+
"origin": first["origin"], "angle": first["angle"], "layer": first.get("layer", "")})
|
|
148
|
+
span = None
|
|
149
|
+
|
|
150
|
+
def close_line():
|
|
151
|
+
nonlocal line
|
|
152
|
+
close_span()
|
|
153
|
+
if line:
|
|
154
|
+
bb = line[0]["bbox"]
|
|
155
|
+
for s in line[1:]:
|
|
156
|
+
bb = bb.union(s["bbox"])
|
|
157
|
+
a = line[0]["angle"]
|
|
158
|
+
result.append({"bbox": bb, "dir": (math.cos(a), math.sin(a)), "spans": line})
|
|
159
|
+
line = []
|
|
160
|
+
|
|
161
|
+
for ch in segment(chars):
|
|
162
|
+
if ch is BREAK or ch.get("c") == "\n":
|
|
163
|
+
close_line()
|
|
164
|
+
continue
|
|
165
|
+
if _space_like(ch["c"]):
|
|
166
|
+
if span is not None:
|
|
167
|
+
span.append(ch)
|
|
168
|
+
continue
|
|
169
|
+
key = (ch.get("font", ""), round(ch["size"], 2), ch.get("color", 0), angle_key(ch["angle"]), ch.get("layer", ""))
|
|
170
|
+
if span is not None and span_key != key:
|
|
171
|
+
close_span()
|
|
172
|
+
if span is None:
|
|
173
|
+
span, span_key = [], key
|
|
174
|
+
span.append(ch)
|
|
175
|
+
close_line()
|
|
176
|
+
return result
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def words(chars):
|
|
180
|
+
"""Words as (x0, y0, x1, y1, text, line_no, word_no): runs of visible glyphs between spaces and breaks."""
|
|
181
|
+
out, cur = [], []
|
|
182
|
+
line_no = 0
|
|
183
|
+
|
|
184
|
+
def flush():
|
|
185
|
+
if cur:
|
|
186
|
+
bb = _bbox(cur)
|
|
187
|
+
out.append((bb.x0, bb.y0, bb.x1, bb.y1, "".join(c["c"] for c in cur), line_no, len(out)))
|
|
188
|
+
cur.clear()
|
|
189
|
+
|
|
190
|
+
for ch in segment(chars):
|
|
191
|
+
if ch is BREAK or ch.get("c") == "\n":
|
|
192
|
+
flush()
|
|
193
|
+
line_no += 1
|
|
194
|
+
continue
|
|
195
|
+
if _space_like(ch["c"]):
|
|
196
|
+
flush()
|
|
197
|
+
continue
|
|
198
|
+
cur.append(ch)
|
|
199
|
+
flush()
|
|
200
|
+
return out
|
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
"typicals": { "type": "array", "maxItems": 50, "items": { "$ref": "#/$defs/typical" }, "description": "#3588: a truss drawn once and marked at several places on the plans. Its parts are ordinary members read on `view`; every other place's copies are ordinary members with ids `<typical id>~<place id>~<part member id>`, which FloLess derives from the parts by the plan rigid motion between the source place's bearing axis and that place's (never scaled). The reader declares the truss and writes each place's plan observations binding that place's members (the copy ids elsewhere); On a model's first read FloLess builds the copies and replaces any the reader wrote; a later read carries the published trusses unchanged and asks about each difference." },
|
|
45
45
|
"read_coverage": { "type": "object", "description": "Written by the server only, never by a reader or the editor: the attached drawing files this model has not read, because a Quick read left them for a later read when the set was too large to read at once (#2554). unknown: more files than the record holds, or a record that could not be read. A reader leaves it out or copies it unchanged.", "additionalProperties": false, "required": ["notRead"], "properties": { "notRead": { "type": "array", "maxItems": 2000, "items": { "type": "object", "additionalProperties": false, "required": ["sha256", "ext", "bytes", "names", "leftOutBy"], "properties": { "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "ext": { "type": "string", "pattern": "^[a-z0-9]{1,8}$" }, "bytes": { "type": "integer", "minimum": 1 }, "names": { "type": "array", "minItems": 1, "maxItems": 40, "items": { "type": "string", "minLength": 1, "maxLength": 260 } }, "leftOutBy": { "type": "object", "additionalProperties": false, "required": ["requestId", "decisionId"], "properties": { "requestId": { "type": "string", "minLength": 1, "maxLength": 200 }, "decisionId": { "type": "string", "minLength": 1, "maxLength": 200 } } } } } }, "unknown": { "const": true } } },
|
|
46
46
|
"ai_decisions": { "type": "array", "description": "Written by the server only, never by a reader or the editor: the AI decisions of Quick model reads this model may rest on (#2521 row 4). A reader leaves it out or copies it unchanged.", "items": { "type": "object", "additionalProperties": false, "required": ["id", "buildId", "channel", "subject", "chosen"], "properties": { "id": { "type": "string", "pattern": "^[0-9a-f]{12}$" }, "buildId": { "type": "string", "minLength": 1, "maxLength": 200 }, "channel": { "enum": ["audit-gap", "height", "setup", "connection", "unmodelled-detail", "filter", "scope"] }, "subject": { "type": "object" }, "chosen": { "type": "string", "maxLength": 2000 }, "value": { "type": "object" } } } },
|
|
47
|
+
"lineage": { "type": "object", "additionalProperties": false, "required": ["id", "began"], "properties": { "id": { "type": "string", "pattern": "^[0-9a-f]{32}$" }, "began": { "enum": ["created", "assigned"] } }, "description": "Written by the server only, never by a reader, the editor, a tweak or the AI: which model this is (#3545), so a change review can prove that two saved states are the same model rather than guess it from matching FloLess ids. `id` is random and never derived from the content; every edit, drawing re-read and save keeps it. `began` says how it came to be: `created` when the model was first written into a project that held no steel model, `assigned` when a model saved before FloLess recorded lineage was given one on its next save (so a review against an earlier saved state cannot prove they are the same model, and says so). ABSENT means the model was saved before FloLess recorded which model it is. A reader leaves it out or copies it unchanged; a writer that replaces the model with another one must start a new one." },
|
|
47
48
|
"detail_bubbles": { "type": "object", "additionalProperties": true, "description": "sheet -> { detail number -> [fx,fy] }: where each detail sits on its sheet's picture, as fractions between 0 and 1 of the picture's width and height. A read may ADD anchors (a person confirms them in Review & approve) and never moves or removes one. Record an anchor only when you have page-normalised coordinates for it." },
|
|
48
49
|
"source": { "type": "object", "additionalProperties": true, "description": "Provenance: where this takeoff was read from (name/path/sheet/sha256/read_at)." },
|
|
49
50
|
"filter": { "type": "object", "additionalProperties": true, "description": "The saved Drawing Filter: source-bound sheets, deterministic elements, and the user's layer/thickness/colour selection. It is prepared and reviewed before members are read." },
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: floless-app-steel-model
|
|
3
3
|
description: The front-door guide for turning a structural steel drawing set into an editable native steel.model/v2 model in floless.app. It orchestrates project setup, set knowledge, AWARE detailer agents, Drawing Filter review, registered plan views, model reading, connection detailing, clash checks, and exports. Use for asks such as "model this steel job from the drawings", "take off this whole set", "start a steel model project", or "/floless-app-steel-model". It is re-runnable and preserves the Filter → Save → read → review → History process end to end.
|
|
4
4
|
metadata:
|
|
5
|
-
version: 0.
|
|
5
|
+
version: 0.43.0
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Steel Model — guide a steel drawing set into an editable model
|
|
@@ -591,6 +591,9 @@ needs to know what bears and what does not.
|
|
|
591
591
|
- **Tekla (or any platform) component INSERTION at bake is deferred** — the connection library +
|
|
592
592
|
per-end references + scoring are editor-verifiable today; native component placement is a later,
|
|
593
593
|
Tekla-gated step. Don't promise it.
|
|
594
|
+
- **Never write the model's `lineage`.** It is FloLess's record of which model this is, kept through
|
|
595
|
+
every edit, re-read and save, and it is how the change review knows two versions are the same model.
|
|
596
|
+
Copy it unchanged or leave it out. To replace the model with a different one, start a new model.
|
|
594
597
|
- **Never report a connection as done on its dimensions alone.** Stages 7-8 are not an optional last pass:
|
|
595
598
|
clash and exact placement are checked on *every* detail built, and whatever does not bear is said out
|
|
596
599
|
loud. This is detailing — "the numbers match" is not the same claim as "it fits", and only one of them
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
two-phase Drawing Filter process: first prepare and save the deterministic Filter, then read only the
|
|
8
8
|
selected evidence into model-global members, registered plan views, observations, and revision history.
|
|
9
9
|
metadata:
|
|
10
|
-
version: 0.
|
|
10
|
+
version: 0.109.0
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
## Shared height study: server-owned reader claims
|
|
@@ -2128,7 +2128,13 @@ document has this shape:
|
|
|
2128
2128
|
```
|
|
2129
2129
|
|
|
2130
2130
|
Follow `schemas/steel.model.v2.schema.json`; closed objects reject unsupported keys. Never include a
|
|
2131
|
-
conversion provenance block or a second contract shape.
|
|
2131
|
+
conversion provenance block or a second contract shape.
|
|
2132
|
+
|
|
2133
|
+
**`lineage` is FloLess's record of which model this is.** Copy it unchanged from the current model, or
|
|
2134
|
+
leave it out; never write, invent or change one. FloLess keeps it through every read, re-read and save,
|
|
2135
|
+
and gives a model that has none one on its next save. A re-read of the same drawings is the same model.
|
|
2136
|
+
If the person wants a different model instead, start a new one rather than rewriting this one, so the
|
|
2137
|
+
change review can say the two are not the same model. Preserve confidential rasters only in the
|
|
2132
2138
|
working project contract; approval and bake strip them from published artifacts.
|
|
2133
2139
|
|
|
2134
2140
|
## Submit through revision-read
|