@floless/app 0.174.0 → 0.175.0

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.
Files changed (89) hide show
  1. package/autostart.mjs +117 -10
  2. package/dist/floless-server.cjs +2 -2
  3. package/dist/pdf-engine/floless_pdf/__init__.py +53 -0
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +823 -0
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +245 -0
  6. package/dist/pdf-engine/floless_pdf/geometry.py +115 -0
  7. package/dist/pdf-engine/floless_pdf/images.py +75 -0
  8. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  9. package/dist/pdf-engine/floless_pdf/textrules.py +200 -0
  10. package/dist/schemas/steel.model.v2.schema.json +45 -1
  11. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  12. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  13. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  14. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  15. package/dist/skills/floless-app-steel-model/SKILL.md +14 -1
  16. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  17. package/dist/skills/floless-app-steel-takeoff/SKILL.md +18 -7
  18. package/dist/skills/floless-app-tweak-contract/SKILL.md +3 -2
  19. package/dist/web/agents.js +1 -1
  20. package/dist/web/app.css +120 -15
  21. package/dist/web/app.js +89 -38
  22. package/dist/web/aware-hold.js +10 -0
  23. package/dist/web/aware.js +405 -51
  24. package/dist/web/boot-watchdog.js +249 -0
  25. package/dist/web/card-details.js +88 -0
  26. package/dist/web/chat.css +29 -0
  27. package/dist/web/chat.js +430 -128
  28. package/dist/web/commands-connection-design.js +23 -0
  29. package/dist/web/commands-revit.js +3 -0
  30. package/dist/web/commands-shell.js +226 -10
  31. package/dist/web/commands-steel.js +95 -5
  32. package/dist/web/commands-tekla-parser.js +21 -1
  33. package/dist/web/connection-design-editor.html +71 -0
  34. package/dist/web/connection-design-editor.js +794 -61
  35. package/dist/web/connection-design-handles.js +9 -3
  36. package/dist/web/element-approval.js +74 -0
  37. package/dist/web/element-context.js +76 -6
  38. package/dist/web/element-geometry.js +8 -2
  39. package/dist/web/element-holds.js +68 -5
  40. package/dist/web/element-type-actions.js +22 -3
  41. package/dist/web/element-types.js +12 -5
  42. package/dist/web/element-words.js +15 -11
  43. package/dist/web/grid-place.js +51 -0
  44. package/dist/web/guide.js +2 -0
  45. package/dist/web/index.html +13 -16
  46. package/dist/web/instructor.js +5 -2
  47. package/dist/web/missed-routines.js +6 -1
  48. package/dist/web/model-change-findings.js +147 -32
  49. package/dist/web/model-change-review.js +435 -32
  50. package/dist/web/model-clash-check.css +100 -0
  51. package/dist/web/model-clash-check.js +681 -0
  52. package/dist/web/model-clip-box.js +204 -0
  53. package/dist/web/model-clip-list.js +153 -3
  54. package/dist/web/model-clip-session.js +3 -3
  55. package/dist/web/model-clip-three-overlay.js +135 -25
  56. package/dist/web/model-editor.css +2 -0
  57. package/dist/web/model-elements.js +273 -18
  58. package/dist/web/model-fit-checks.js +354 -0
  59. package/dist/web/model-spatial-panel.js +9 -3
  60. package/dist/web/model-spatial-tools.js +12 -3
  61. package/dist/web/model-tekla-selection.js +74 -0
  62. package/dist/web/model-view-query.js +70 -14
  63. package/dist/web/model-viewport-revit-adapter.js +8 -7
  64. package/dist/web/model-viewport-toolbar.js +8 -4
  65. package/dist/web/pages.js +78 -1
  66. package/dist/web/project-history.js +31 -1
  67. package/dist/web/revit-editor.css +34 -1
  68. package/dist/web/revit-editor.js +176 -55
  69. package/dist/web/run-history.js +8 -0
  70. package/dist/web/sketch-editor.js +141 -2
  71. package/dist/web/sketches.js +192 -6
  72. package/dist/web/start-place.js +46 -0
  73. package/dist/web/steel-3d-core.js +70 -0
  74. package/dist/web/steel-3d-view.js +288 -47
  75. package/dist/web/steel-change-review.css +29 -0
  76. package/dist/web/steel-custom-connection.js +6 -0
  77. package/dist/web/steel-editor.html +532 -33
  78. package/dist/web/steel-filter.html +8 -3
  79. package/dist/web/steel-model-checks.css +76 -0
  80. package/dist/web/steel-model-commands.js +1 -1
  81. package/dist/web/steel-model-v2-commands.js +17 -0
  82. package/dist/web/steel-view-generation.js +6 -2
  83. package/dist/web/teams.js +259 -19
  84. package/dist/web/tekla-editor.html +1 -0
  85. package/dist/web/terminal-requests.js +6 -0
  86. package/dist/web/vendor/connection-engine.js +890 -89
  87. package/dist/web/workspaces.js +630 -48
  88. package/package.json +4 -1
  89. package/preferences-file.mjs +27 -0
@@ -0,0 +1,245 @@
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
+ PAGE_JPEG_QUALITY = 95 # MuPDF's own encoder at today's quality: the oracle's pictures stay byte-identical
60
+
61
+ def __init__(self, doc, number):
62
+ self._doc = doc
63
+ self._page = doc._doc[number]
64
+ self.number = number
65
+ self.rotation = self._page.rotation % 360
66
+ crop = self._page.cropbox
67
+ self.unrotated_size = (crop.width, crop.height)
68
+ r = self._page.rect
69
+ self.size = (r.width, r.height)
70
+ self.rotation_matrix = rotation_matrix(self.rotation, crop.width, crop.height)
71
+ self._markup = None
72
+
73
+ # ---- what came from annotations (markups) ------------------------------------------------------------------
74
+ def _markup_keys(self):
75
+ """The drawings and characters that only an annotation appearance contributes, read by comparing the page
76
+ with a copy whose markup annotations are taken off. Only pages that carry such annotations pay for it."""
77
+ if self._markup is not None:
78
+ return self._markup
79
+ kinds = [a.type[1] for a in self._page.annots()] if self._page.first_annot else []
80
+ if not [k for k in kinds if k not in _NOT_MARKUP]:
81
+ self._markup = (set(), set())
82
+ return self._markup
83
+ bare = fitz.open()
84
+ bare.insert_pdf(self._doc._doc, from_page=self.number, to_page=self.number, annots=False)
85
+ page = bare[0]
86
+ drawings = {_drawing_key(d) for d in page.get_drawings()}
87
+ chars = {_char_key(c) for c in _raw_chars(page)}
88
+ bare.close()
89
+ self._markup = (drawings, chars)
90
+ return self._markup
91
+
92
+ # ---- text ---------------------------------------------------------------------------------------------------
93
+ def chars(self):
94
+ drawings_bare, chars_bare = self._markup_keys()
95
+ annotated = bool(chars_bare) or bool(drawings_bare)
96
+ out = []
97
+ for c in _raw_chars(self._page):
98
+ c["markup"] = annotated and _char_key(c) not in chars_bare
99
+ out.append(c)
100
+ return out
101
+
102
+ def lines(self):
103
+ out = []
104
+ for block in self._page.get_text("dict", flags=_TEXT_ONLY)["blocks"]:
105
+ if block.get("type") != 0:
106
+ continue
107
+ for line in block["lines"]:
108
+ out.append({"bbox": Rect(*line["bbox"]), "dir": tuple(line["dir"]), "spans": [
109
+ {"text": s["text"], "bbox": Rect(*s["bbox"]), "size": s["size"], "font": s["font"],
110
+ "color": s["color"], "flags": s["flags"], "origin": Point(*s["origin"])} for s in line["spans"]]})
111
+ return out
112
+
113
+ def words(self):
114
+ return [tuple(w) for w in self._page.get_text("words")]
115
+
116
+ def text(self):
117
+ return self._page.get_text("text")
118
+
119
+ # ---- linework -----------------------------------------------------------------------------------------------
120
+ def drawings(self):
121
+ bare, _ = self._markup_keys()
122
+ out = []
123
+ clips = [] # (level, scissor) of the clips the next drawing is inside
124
+ for d in self._page.get_drawings(extended=True):
125
+ level = d.get("level", 0)
126
+ while clips and clips[-1][0] >= level:
127
+ clips.pop()
128
+ if d["type"] == "clip":
129
+ clips.append((level, _rect(d["scissor"])))
130
+ continue
131
+ if d["type"] == "group":
132
+ continue
133
+ clip = None
134
+ for _, scissor in clips:
135
+ clip = scissor if clip is None else clip.intersect(scissor)
136
+ rect = _rect(d["rect"])
137
+ row = {
138
+ "type": d["type"], "items": _items(d["items"]), "rect": rect, "clip": clip,
139
+ "visible": rect.intersect(clip) if clip is not None else rect,
140
+ "width": d.get("width"), "color": d.get("color"), "fill": d.get("fill"),
141
+ "dashes": d.get("dashes"), "even_odd": d.get("even_odd"), "closePath": d.get("closePath"),
142
+ "layer": d.get("layer") or "", "markup": bool(bare) and _drawing_key(d) not in bare,
143
+ }
144
+ out.append(row)
145
+ return out
146
+
147
+ # ---- pictures -----------------------------------------------------------------------------------------------
148
+ def _pixmap(self, scale=None, dpi=None, clip=None):
149
+ kw = {"alpha": False}
150
+ if clip is not None:
151
+ kw["clip"] = fitz.Rect(*clip)
152
+ if dpi is not None:
153
+ return self._page.get_pixmap(dpi=int(dpi), **kw)
154
+ return self._page.get_pixmap(matrix=fitz.Matrix(scale or 1.0, scale or 1.0), **kw)
155
+
156
+ def render_jpeg(self, scale=None, dpi=None, clip=None, quality=95):
157
+ pm = self._pixmap(scale, dpi, clip)
158
+ return pm.tobytes("jpeg", jpg_quality=int(quality)), (pm.width, pm.height)
159
+
160
+ def render_png(self, scale=None, dpi=None, clip=None):
161
+ pm = self._pixmap(scale, dpi, clip)
162
+ return pm.tobytes("png"), (pm.width, pm.height)
163
+
164
+ def render(self, scale=None, dpi=None, clip=None):
165
+ """The rendered page as a Pillow RGB image (for comparisons; readers use render_jpeg/png)."""
166
+ from PIL import Image # noqa: PLC0415
167
+ pm = self._pixmap(scale, dpi, clip)
168
+ return Image.frombytes("RGB", (pm.width, pm.height), pm.samples)
169
+
170
+
171
+ def _raw_chars(page):
172
+ out = []
173
+ for block in page.get_text("rawdict", flags=_TEXT_ONLY_RAW)["blocks"]:
174
+ if block.get("type") != 0:
175
+ continue
176
+ for line in block["lines"]:
177
+ for span in line["spans"]:
178
+ for ch in span["chars"]:
179
+ out.append({"c": ch["c"], "box": Rect(*ch["bbox"]), "origin": Point(*ch["origin"]),
180
+ "size": span["size"], "font": span["font"], "color": span["color"],
181
+ "flags": span["flags"], "dir": tuple(line["dir"]),
182
+ # The same keys the pdfium backend gives: the baseline angle (counter-clockwise, in
183
+ # radians, as on the sheet) and the layer, which MuPDF's text reader does not report.
184
+ "angle": round(math.atan2(-line["dir"][1], line["dir"][0]), 4), "layer": ""})
185
+ return out
186
+
187
+
188
+ def _char_key(c):
189
+ b = c["box"]
190
+ return (c["c"], round(b.x0, 2), round(b.y0, 2), round(b.x1, 2), round(b.y1, 2))
191
+
192
+
193
+ def _drawing_key(d):
194
+ r = d["rect"]
195
+ rect = (r.x0, r.y0, r.x1, r.y1) if hasattr(r, "x0") else tuple(r)
196
+ return (d["type"], len(d["items"]),) + tuple(round(v, 2) for v in rect)
197
+
198
+
199
+ class Document:
200
+ def __init__(self, source, count_only_if_locked=False):
201
+ if isinstance(source, (bytes, bytearray)):
202
+ self._doc = fitz.open(stream=bytes(source), filetype="pdf")
203
+ else:
204
+ self._doc = fitz.open(source)
205
+ self.locked = bool(self._doc.needs_pass)
206
+ if self.locked and not count_only_if_locked:
207
+ self._doc.close()
208
+ raise PermissionError("the PDF needs a password")
209
+ self.page_count = self._doc.page_count # MuPDF counts a locked file's pages without the password
210
+ self.engine = {"name": NAME, **versions()}
211
+
212
+ def page(self, number):
213
+ if self.locked:
214
+ raise PermissionError("the PDF needs a password")
215
+ if not 0 <= number < self.page_count:
216
+ raise IndexError("page %d of %d" % (number + 1, self.page_count))
217
+ return Page(self, number)
218
+
219
+ def page_size(self, number):
220
+ """A page's displayed size, `Page.size` (MuPDF reads it without drawing anything)."""
221
+ return self.page(number).size
222
+
223
+ def layers(self):
224
+ """Every layer (optional content group) with its default visibility, in the document's own order."""
225
+ return [{"name": v.get("name", ""), "on": bool(v.get("on"))} for _, v in sorted(self._doc.get_ocgs().items())]
226
+
227
+ @property
228
+ def is_pdf(self):
229
+ return bool(self._doc.is_pdf)
230
+
231
+ def write_pages(self, numbers, out_path, _source_sha256=None):
232
+ """The document narrowed to the 0-based `numbers`, in that order, written to `out_path` exactly as the
233
+ left-for-later piece always was: no metadata, no new id, unused objects dropped. Returns the page count."""
234
+ self._doc.select(list(numbers))
235
+ self._doc.set_metadata({})
236
+ self._doc.del_xml_metadata()
237
+ self._doc.save(out_path, garbage=3, deflate=True, no_new_id=True)
238
+ return {"pages": self._doc.page_count, "structureError": None, "labels": []}
239
+
240
+ def structure_error(self):
241
+ """Why the layer structure could not be read, or None. MuPDF reads it with the page, so always None."""
242
+ return None
243
+
244
+ def close(self):
245
+ 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,75 @@
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), optimised Huffman tables (lossless, slice 2b), chroma
11
+ subsampling 4:2:0, quality from the caller (95 unless the reader asks for less: a whole-page picture on pdfium asks for 88, the Filter
12
+ backdrop for 35).
13
+ - PNG: Pillow's encoder, compression level 6, no optimisation pass.
14
+ - DOWNSAMPLING: a render is made at the requested scale directly, never resampled. Making a picture smaller
15
+ (`fit_within`) is area averaging (Pillow's BOX filter), so a hairline fades rather than vanishes or turns jagged.
16
+
17
+ The pymupdf backend does not come here for pages: it passes MuPDF's own encoder through, unchanged, because its
18
+ output must stay byte-identical to today's readers.
19
+ """
20
+ import io
21
+
22
+ JPEG_QUALITY = 95
23
+ JPEG_SUBSAMPLING = 2 # Pillow's code for 4:2:0
24
+ PNG_COMPRESS_LEVEL = 6
25
+
26
+
27
+ def _pil():
28
+ from PIL import Image, ImageOps # noqa: PLC0415 - Pillow is only needed by readers that make pictures
29
+ return Image, ImageOps
30
+
31
+
32
+ def to_rgb(img):
33
+ """8-bit RGB, any alpha laid on white."""
34
+ Image, _ = _pil()
35
+ if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
36
+ rgba = img.convert("RGBA")
37
+ white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
38
+ return Image.alpha_composite(white, rgba).convert("RGB")
39
+ return img.convert("RGB") if img.mode != "RGB" else img
40
+
41
+
42
+ def encode_jpeg(img, quality=JPEG_QUALITY):
43
+ q = int(quality)
44
+ if not 1 <= q <= 100:
45
+ raise ValueError("JPEG quality must be 1-100, got %r" % (quality,))
46
+ out = io.BytesIO()
47
+ to_rgb(img).save(out, "JPEG", quality=q, subsampling=JPEG_SUBSAMPLING, optimize=True, progressive=False)
48
+ return out.getvalue()
49
+
50
+
51
+ def encode_png(img):
52
+ out = io.BytesIO()
53
+ to_rgb(img).save(out, "PNG", compress_level=PNG_COMPRESS_LEVEL, optimize=False)
54
+ return out.getvalue()
55
+
56
+
57
+ def fit_within(img, max_edge):
58
+ """The picture made no longer than `max_edge` on its long side, by area averaging; unchanged when it fits."""
59
+ Image, _ = _pil()
60
+ w, h = img.size
61
+ if max_edge is None or max(w, h) <= max_edge:
62
+ return img
63
+ k = max_edge / float(max(w, h))
64
+ return img.resize((max(1, round(w * k)), max(1, round(h * k))), Image.Resampling.BOX)
65
+
66
+
67
+ def open_image(source, max_edge=None):
68
+ """A standalone PNG/JPEG (a path or bytes) as RGB, EXIF orientation applied, optionally made smaller."""
69
+ Image, ImageOps = _pil()
70
+ data = source if isinstance(source, (bytes, bytearray)) else open(source, "rb").read()
71
+ img = Image.open(io.BytesIO(data))
72
+ if img.format not in ("PNG", "JPEG"):
73
+ raise ValueError("not a PNG or JPEG image (%s)" % (img.format or "unknown"))
74
+ img = ImageOps.exif_transpose(img)
75
+ return fit_within(to_rgb(img), max_edge)
@@ -0,0 +1,136 @@
1
+ """The page-level readers (pdf-engine slice 2, docs/superpowers/specs/2026-11-23-pdf-engine-slice2-PLAN.md).
2
+
3
+ Engine-neutral: each function takes a document opened by `floless_pdf.open` and uses only the module's API, so the
4
+ product's scripts (server/pdf-page-count.ts, server/steel-read-piece.ts, server/attachment-pages.ts) and the corpus
5
+ parity harness run the SAME code on either engine. Every decision about what is acceptable stays in TypeScript; this
6
+ reads and reports.
7
+
8
+ A per-reader part of the module: its digest is in the records of page-count, page-split, attachment-pages and
9
+ attachment-tiles (their `sources` in server/pdf-engine.ts), not in the shared core.
10
+ """
11
+ import sys
12
+
13
+
14
+ class TooLarge(Exception):
15
+ """A picture over the pixel cap: refused before it is drawn."""
16
+
17
+
18
+ # ---- page count and page bounds (page-count) ------------------------------------------------------------------------
19
+
20
+ def count(doc):
21
+ return doc.page_count
22
+
23
+
24
+ def bounds(doc):
25
+ """Every page's displayed box, (0, 0, width, height) rounded to 0.1 pt, as the archive inspector records it. Read
26
+ from the page tree (`page_size`), never by loading a page."""
27
+ out = []
28
+ for n in range(doc.page_count):
29
+ w, h = doc.page_size(n)
30
+ out.append([round(0.0, 1), round(0.0, 1), round(float(w), 1), round(float(h), 1)])
31
+ return out
32
+
33
+
34
+ # ---- page pictures (attachment-pages) -------------------------------------------------------------------------------
35
+
36
+ def picture_dpi(size, max_edge):
37
+ """The whole-page rule: the long edge near `max_edge` pixels, never under 36 dpi or over 300."""
38
+ longest = max(size[0], size[1]) or 1
39
+ return max(36, min(300, int(int(max_edge) * 72 / longest)))
40
+
41
+
42
+ def _too_large(w, h, dpi, max_pixels):
43
+ return (w * dpi / 72) * (h * dpi / 72) > int(max_pixels)
44
+
45
+
46
+ def page_pictures(doc, max_pages, max_edge, max_pixels):
47
+ """The first `max_pages` pages as JPEGs. Returns (jpegs, skipped 1-based numbers too large to draw, total)."""
48
+ out, skipped = [], []
49
+ for index in range(min(doc.page_count, int(max_pages))):
50
+ page = doc.page(index)
51
+ dpi = picture_dpi(page.size, max_edge)
52
+ if _too_large(page.size[0], page.size[1], dpi, max_pixels):
53
+ skipped.append(index + 1)
54
+ continue
55
+ out.append(page.render_jpeg(dpi=dpi, quality=page.PAGE_JPEG_QUALITY)[0])
56
+ return out, skipped, doc.page_count
57
+
58
+
59
+ def page_picture(doc, index, max_edge, max_pixels):
60
+ """One page (0-based) as a JPEG; TooLarge over the cap."""
61
+ page = doc.page(index)
62
+ dpi = picture_dpi(page.size, max_edge)
63
+ if _too_large(page.size[0], page.size[1], dpi, max_pixels):
64
+ raise TooLarge()
65
+ return page.render_jpeg(dpi=dpi, quality=page.PAGE_JPEG_QUALITY)[0]
66
+
67
+
68
+ # ---- tiles (attachment-tiles) ---------------------------------------------------------------------------------------
69
+
70
+ def tile_boxes(size, grid, overlap):
71
+ """The grid x grid overlapping tiles of a page, left to right and top to bottom, in displayed page space."""
72
+ w, h = size
73
+ tw, th = w / grid, h / grid
74
+ out = []
75
+ for row in range(grid):
76
+ for col in range(grid):
77
+ out.append((max(0.0, col * tw - tw * overlap), max(0.0, row * th - th * overlap),
78
+ min(w, (col + 1) * tw + tw * overlap), min(h, (row + 1) * th + th * overlap)))
79
+ return out
80
+
81
+
82
+ def tiles(doc, index, grid, overlap, dpi, max_pixels):
83
+ """One page (0-based) as overlapping JPEG tiles at `dpi`; TooLarge before any tile is drawn."""
84
+ page = doc.page(index)
85
+ boxes = tile_boxes(page.size, int(grid), float(overlap))
86
+ for x0, y0, x1, y1 in boxes:
87
+ if _too_large(x1 - x0, y1 - y0, int(dpi), max_pixels):
88
+ raise TooLarge()
89
+ return [page.render_jpeg(dpi=int(dpi), clip=box)[0] for box in boxes]
90
+
91
+
92
+ # ---- page split (page-split) ----------------------------------------------------------------------------------------
93
+
94
+ def structure_labels(error):
95
+ """The plain-English label for a document whose structure could not be read (`structure_error()`). A fixed sentence:
96
+ the error itself (a library's message, which can be long) is for the log, never for what a person or the AI reads."""
97
+ if not error:
98
+ return []
99
+ return ["FloLess could not read this PDF's document structure, so its layer settings were not read."]
100
+
101
+
102
+ SPLIT_ANOTHER_WAY_LABEL = ("FloLess could not read this PDF's document structure the usual way, so its pages were split "
103
+ "another way. The drawing's layer settings were kept.")
104
+
105
+
106
+ def split(doc, numbers, out_path, source_sha256=None, allow_fallback=True):
107
+ """The chosen 0-based pages in their own PDF (the left-for-later piece). On pdfium, when pypdf cannot read the
108
+ structure: PyMuPDF makes the piece if it is installed; otherwise PDFium copies the pages into a new document and
109
+ the result says what that loses. With `allow_fallback` False (a forced qualification run) it raises instead."""
110
+ try:
111
+ return dict(doc.write_pages(numbers, out_path, source_sha256), via=doc.engine["name"])
112
+ except PermissionError:
113
+ raise
114
+ except Exception as error: # noqa: BLE001 - only the pdfium backend's StructureError reaches here
115
+ if type(error).__name__ != "StructureError" or not allow_fallback:
116
+ raise
117
+ reason = str(error) or type(error).__name__
118
+ # The exception is for the log (stderr), bounded; the labels below are fixed sentences.
119
+ sys.stderr.write("floless_pdf.pages.split: the document structure could not be read (%s); splitting another way\n"
120
+ % reason[:300].replace("\n", " "))
121
+ try:
122
+ from . import backend_pymupdf # noqa: PLC0415 - installed beside pdfium until the managed runtime ships
123
+ except ImportError:
124
+ backend_pymupdf = None
125
+ if backend_pymupdf is not None:
126
+ other = backend_pymupdf.Document(doc._source) # noqa: SLF001 - the same bytes the pdfium document opened
127
+ try:
128
+ result = other.write_pages(numbers, out_path)
129
+ finally:
130
+ other.close()
131
+ return dict(result, via="pymupdf", structureError=reason, labels=[SPLIT_ANOTHER_WAY_LABEL])
132
+ result = doc.copy_pages(numbers, out_path)
133
+ return dict(result, via="pdfium-copy", structureError=reason, degraded=True,
134
+ labels=structure_labels(reason) + [
135
+ "Its pages were copied into a new PDF without the drawing's layer settings, forms or links, "
136
+ "so a layer the drawing hides can show."])