strata-python 0.2.0__py3-none-any.whl → 0.2.2__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.
- strata_python/__init__.py +2 -1
- strata_python/cli.py +99 -20
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +780 -0
- strata_python/db/__init__.py +116 -0
- strata_python/db/__main__.py +5 -0
- strata_python/db/_alembic/env.py +24 -0
- strata_python/db/_alembic/script.py.mako +28 -0
- strata_python/db/cli.py +199 -0
- strata_python/db/config.py +85 -0
- strata_python/db/engine.py +53 -0
- strata_python/db/guard.py +159 -0
- strata_python/db/migrations.py +243 -0
- strata_python/db/models.py +62 -0
- strata_python/db/project.py +98 -0
- strata_python/db/pytest_plugin.py +205 -0
- strata_python/db/scratch.py +143 -0
- strata_python/db/settings.py +63 -0
- strata_python/db/testing.py +43 -0
- strata_python/db/testserver.py +205 -0
- strata_python/oslib.py +44 -5
- strata_python/pages/__init__.py +21 -0
- strata_python/pages/model.py +241 -0
- strata_python/pages/render.py +273 -0
- strata_python/public_check.py +54 -8
- strata_python/pytest_plugin.py +70 -1
- strata_python/settings.py +243 -42
- strata_python/testing.py +257 -0
- strata_python/web.py +15 -6
- strata_python-0.2.2.dist-info/METADATA +334 -0
- strata_python-0.2.2.dist-info/RECORD +38 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +2 -0
- strata_python-0.2.0.dist-info/METADATA +0 -82
- strata_python-0.2.0.dist-info/RECORD +0 -16
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""The page description: what a scanned page holds, in the scan's own pixels, for drawing it again as a PDF.
|
|
2
|
+
|
|
3
|
+
A reader (a layout model, OCR, a vision model, a font matcher) fills it in; `strata_python.pages.render` draws it. Every
|
|
4
|
+
app that rebuilds pages uses this one shape and one renderer, so an eval that scores a rebuilt page scores exactly what
|
|
5
|
+
the app prints.
|
|
6
|
+
|
|
7
|
+
Page(width=2480, height=3508, dpi=300, blocks=[
|
|
8
|
+
Block(box=(300, 400, 1880, 120), role="heading", lines=[
|
|
9
|
+
Line(box=(600, 410, 1280, 100), spans=[Span("PUNCH AND JUDY", style="caps", size_pt=24)])])],
|
|
10
|
+
figures=[Figure(box=(400, 700, 1680, 1400), image="/srv/app/crops/p12-f1.png")])
|
|
11
|
+
|
|
12
|
+
Boxes are `(x, y, w, h)` in scan pixels from the top left, the same as Tesseract's. A line's spans are drawn one after
|
|
13
|
+
the other as written (spaces are part of their text), from the line box's left edge, on the line's baseline.
|
|
14
|
+
Plain data only (no third-party imports), so an app can build and send descriptions without the `[pdf]` extra."""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Mapping, Sequence
|
|
19
|
+
from dataclasses import MISSING, dataclass, field, fields
|
|
20
|
+
from typing import Any, cast
|
|
21
|
+
|
|
22
|
+
Box = tuple[float, float, float, float]
|
|
23
|
+
|
|
24
|
+
STYLES = ("roman", "italic", "bold", "bold-italic", "small-caps", "caps", "blackletter")
|
|
25
|
+
ROLES = ("body", "heading", "caption", "footnote", "running-head", "folio", "ornament", "rule", "other")
|
|
26
|
+
ALIGNS = ("left", "centre", "right", "justify")
|
|
27
|
+
FIGURE_KINDS = ("figure", "engraving", "ornament", "initial", "rule")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PageError(ValueError):
|
|
31
|
+
"""A description that cannot be drawn: an unknown style, role or alignment, a box that is not four numbers."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _box(v: object, where: str) -> Box:
|
|
35
|
+
if not isinstance(v, Sequence) or isinstance(v, str) or len(cast("Sequence[object]", v)) != 4:
|
|
36
|
+
raise PageError(f"{where}: a box is [x, y, w, h], not {v!r}")
|
|
37
|
+
try:
|
|
38
|
+
x, y, w, h = (float(cast("Any", n)) for n in cast("Sequence[object]", v))
|
|
39
|
+
except (TypeError, ValueError) as e:
|
|
40
|
+
raise PageError(f"{where}: a box is four numbers, not {v!r}") from e
|
|
41
|
+
if w < 0 or h < 0:
|
|
42
|
+
raise PageError(f"{where}: a box has no negative size: {v!r}")
|
|
43
|
+
return (x, y, w, h)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _one_of(v: object, allowed: tuple[str, ...], where: str) -> str:
|
|
47
|
+
if v not in allowed:
|
|
48
|
+
raise PageError(f"{where}: {v!r} is not one of {', '.join(allowed)}")
|
|
49
|
+
return cast("str", v)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _opt_float(v: object) -> float | None:
|
|
53
|
+
return None if v is None else float(cast("Any", v))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _to_dict(obj: Any) -> dict[str, Any]:
|
|
57
|
+
"""A dataclass as JSON: fields at their default left out (the JSON stays small and readable), boxes as lists,
|
|
58
|
+
nested parts through their own to_dict."""
|
|
59
|
+
out: dict[str, Any] = {}
|
|
60
|
+
for f in fields(obj):
|
|
61
|
+
v = getattr(obj, f.name)
|
|
62
|
+
if (f.default is not MISSING and v == f.default) or (
|
|
63
|
+
f.default_factory is not MISSING and v == f.default_factory()
|
|
64
|
+
):
|
|
65
|
+
continue
|
|
66
|
+
if isinstance(v, tuple):
|
|
67
|
+
v = list(cast("tuple[float, ...]", v))
|
|
68
|
+
elif isinstance(v, list):
|
|
69
|
+
v = [x.to_dict() for x in cast("list[Any]", v)]
|
|
70
|
+
out[f.name] = v
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class Span:
|
|
76
|
+
"""A run of text in one style. `face` names a font in the renderer's `fonts` mapping (None: the standard face for the
|
|
77
|
+
style); `size_pt` is the size to set (None: the line's, else one worked out from the line box); `tracking_em` is extra
|
|
78
|
+
advance after each glyph in ems of the size; `hscale` is horizontal scale (1.0 = none); `stroke_em` is the width
|
|
79
|
+
of a stroke drawn round the glyphs, in ems of the size, for print heavier than the face: the stroke is centred on
|
|
80
|
+
the outline, so each edge moves out by half of it (0 or less: no stroke).
|
|
81
|
+
|
|
82
|
+
Geometry measured per word (a font matcher fits each word): `x` is where the span's ink starts and `baseline_y`
|
|
83
|
+
its baseline, both in scan pixels. A span with an `x` is set there rather than after the span before it, and a
|
|
84
|
+
line with any such span is not fitted to its box, since its words are already placed."""
|
|
85
|
+
|
|
86
|
+
text: str
|
|
87
|
+
style: str = "roman"
|
|
88
|
+
face: str | None = None
|
|
89
|
+
size_pt: float | None = None
|
|
90
|
+
tracking_em: float = 0.0
|
|
91
|
+
hscale: float = 1.0
|
|
92
|
+
stroke_em: float = 0.0
|
|
93
|
+
x: float | None = None
|
|
94
|
+
baseline_y: float | None = None
|
|
95
|
+
|
|
96
|
+
def __post_init__(self) -> None:
|
|
97
|
+
_one_of(self.style, STYLES, f"span {self.text[:20]!r}")
|
|
98
|
+
if self.hscale <= 0:
|
|
99
|
+
raise PageError(f"span {self.text[:20]!r}: hscale must be above 0, not {self.hscale}")
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, d: Mapping[str, Any]) -> Span:
|
|
103
|
+
return cls(
|
|
104
|
+
text=str(d.get("text", "")),
|
|
105
|
+
style=str(d.get("style") or "roman"),
|
|
106
|
+
face=d.get("face"),
|
|
107
|
+
size_pt=_opt_float(d.get("size_pt")),
|
|
108
|
+
tracking_em=float(d.get("tracking_em") or 0.0),
|
|
109
|
+
hscale=float(d.get("hscale") or 1.0),
|
|
110
|
+
stroke_em=float(d.get("stroke_em") or 0.0),
|
|
111
|
+
x=_opt_float(d.get("x")),
|
|
112
|
+
baseline_y=_opt_float(d.get("baseline_y")),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def to_dict(self) -> dict[str, Any]:
|
|
116
|
+
return _to_dict(self)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class Line:
|
|
121
|
+
"""One printed line. `baseline_y` is the baseline in scan pixels (None: near the bottom of the box, above the
|
|
122
|
+
descenders); `size_pt` and `face` are the defaults for its spans."""
|
|
123
|
+
|
|
124
|
+
box: Box
|
|
125
|
+
spans: list[Span] = field(default_factory=lambda: list[Span]())
|
|
126
|
+
baseline_y: float | None = None
|
|
127
|
+
size_pt: float | None = None
|
|
128
|
+
face: str | None = None
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def text(self) -> str:
|
|
132
|
+
return "".join(s.text for s in self.spans)
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def from_dict(cls, d: Mapping[str, Any]) -> Line:
|
|
136
|
+
spans = d.get("spans")
|
|
137
|
+
if spans is None: # a reader that gives only the text (OCR): one roman span
|
|
138
|
+
spans = [{"text": d.get("text", "")}]
|
|
139
|
+
return cls(
|
|
140
|
+
box=_box(d.get("box"), f"line {str(d.get('text', ''))[:20]!r}"),
|
|
141
|
+
spans=[Span.from_dict(s) for s in cast("list[Mapping[str, Any]]", spans)],
|
|
142
|
+
baseline_y=_opt_float(d.get("baseline_y")),
|
|
143
|
+
size_pt=_opt_float(d.get("size_pt")),
|
|
144
|
+
face=d.get("face"),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def to_dict(self) -> dict[str, Any]:
|
|
148
|
+
return _to_dict(self)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass
|
|
152
|
+
class Block:
|
|
153
|
+
"""A block of lines with one role. `order` is its place in reading order (None: after the numbered ones, in list
|
|
154
|
+
order); `align` places a line inside its block when it is narrower than its own box allows."""
|
|
155
|
+
|
|
156
|
+
box: Box
|
|
157
|
+
lines: list[Line] = field(default_factory=lambda: list[Line]())
|
|
158
|
+
role: str = "body"
|
|
159
|
+
order: int | None = None
|
|
160
|
+
align: str = "left"
|
|
161
|
+
|
|
162
|
+
def __post_init__(self) -> None:
|
|
163
|
+
_one_of(self.role, ROLES, "block role")
|
|
164
|
+
_one_of(self.align, ALIGNS, "block align")
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def from_dict(cls, d: Mapping[str, Any]) -> Block:
|
|
168
|
+
return cls(
|
|
169
|
+
box=_box(d.get("box"), "block"),
|
|
170
|
+
lines=[Line.from_dict(x) for x in cast("list[Mapping[str, Any]]", d.get("lines") or [])],
|
|
171
|
+
role=str(d.get("role") or "body"),
|
|
172
|
+
order=None if d.get("order") is None else int(d["order"]),
|
|
173
|
+
align=str(d.get("align") or "left"),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def to_dict(self) -> dict[str, Any]:
|
|
177
|
+
return _to_dict(self)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass
|
|
181
|
+
class Figure:
|
|
182
|
+
"""A picture on the page. `image` is the path of its cleaned crop, drawn stretched to the box (None: the box is left
|
|
183
|
+
empty, so a layout can be drawn before the crops exist)."""
|
|
184
|
+
|
|
185
|
+
box: Box
|
|
186
|
+
image: str | None = None
|
|
187
|
+
kind: str = "figure"
|
|
188
|
+
|
|
189
|
+
def __post_init__(self) -> None:
|
|
190
|
+
_one_of(self.kind, FIGURE_KINDS, "figure kind")
|
|
191
|
+
|
|
192
|
+
@classmethod
|
|
193
|
+
def from_dict(cls, d: Mapping[str, Any]) -> Figure:
|
|
194
|
+
return cls(box=_box(d.get("box"), "figure"), image=d.get("image"), kind=str(d.get("kind") or "figure"))
|
|
195
|
+
|
|
196
|
+
def to_dict(self) -> dict[str, Any]:
|
|
197
|
+
return _to_dict(self)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass
|
|
201
|
+
class Page:
|
|
202
|
+
"""A page: its size in scan pixels at `dpi`, which sets the PDF's size in points (72 a inch)."""
|
|
203
|
+
|
|
204
|
+
width: float
|
|
205
|
+
height: float
|
|
206
|
+
dpi: float
|
|
207
|
+
blocks: list[Block] = field(default_factory=lambda: list[Block]())
|
|
208
|
+
figures: list[Figure] = field(default_factory=lambda: list[Figure]())
|
|
209
|
+
|
|
210
|
+
def __post_init__(self) -> None:
|
|
211
|
+
if self.width <= 0 or self.height <= 0 or self.dpi <= 0:
|
|
212
|
+
raise PageError(
|
|
213
|
+
f"a page needs a positive width, height and dpi, not {self.width}x{self.height} at {self.dpi}"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def reading_order(self) -> list[Block]:
|
|
217
|
+
"""The blocks in reading order: numbered ones first by number, then the rest as listed."""
|
|
218
|
+
numbered = sorted((b for b in self.blocks if b.order is not None), key=lambda b: cast("int", b.order))
|
|
219
|
+
return numbered + [b for b in self.blocks if b.order is None]
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def text(self) -> str:
|
|
223
|
+
"""The page's text in reading order, a line a line, blocks apart by a blank line."""
|
|
224
|
+
return "\n\n".join("\n".join(x.text for x in b.lines) for b in self.reading_order() if b.lines)
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_dict(cls, d: Mapping[str, Any]) -> Page:
|
|
228
|
+
try:
|
|
229
|
+
width, height, dpi = float(d["width"]), float(d["height"]), float(d["dpi"])
|
|
230
|
+
except (KeyError, TypeError, ValueError) as e:
|
|
231
|
+
raise PageError(f"a page needs width, height and dpi: {e}") from e
|
|
232
|
+
return cls(
|
|
233
|
+
width=width,
|
|
234
|
+
height=height,
|
|
235
|
+
dpi=dpi,
|
|
236
|
+
blocks=[Block.from_dict(b) for b in cast("list[Mapping[str, Any]]", d.get("blocks") or [])],
|
|
237
|
+
figures=[Figure.from_dict(f) for f in cast("list[Mapping[str, Any]]", d.get("figures") or [])],
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def to_dict(self) -> dict[str, Any]:
|
|
241
|
+
return _to_dict(self)
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Draw page descriptions as a PDF with real text, and read a PDF back as pixels and text (the `[pdf]` extra).
|
|
2
|
+
|
|
3
|
+
pdf = render(page, fonts={"old-standard": "/srv/fonts/OldStandardTT-Regular.ttf"})
|
|
4
|
+
img = rasterise(pdf, dpi=page.dpi) # the same pixels as the scan, to compare ink
|
|
5
|
+
text = read_text(pdf) # what a reader of the PDF gets, in reading order
|
|
6
|
+
|
|
7
|
+
What the renderer does with a description, so a reader knows what to give it:
|
|
8
|
+
- Each line is set on its baseline, from the left of its box (centred or right-aligned in the box for a block aligned
|
|
9
|
+
so), span after span. Blocks are drawn in reading order, so the PDF's text reads back in that order.
|
|
10
|
+
- A span's size is its `size_pt`, else its line's, else `SIZE_OF_BOX` times the line box's height.
|
|
11
|
+
- `tracking_em`, `hscale` and `stroke_em` (a stroke round the glyphs) are applied as given, and a span's own `x`
|
|
12
|
+
and `baseline_y` (a font matcher's per-word fit) place it; a line with placed spans is not fitted again. With `fit` (the default) the glyph spacing of the line is then
|
|
13
|
+
nudged, by at most `FIT_LIMIT_EM` a glyph, so the line fills its box: a near face then lands where the print was
|
|
14
|
+
without the glyphs themselves being stretched.
|
|
15
|
+
- `small-caps` is drawn as capitals with the lower-case letters at `SMALL_CAP` of the size, unless the span's face is a
|
|
16
|
+
small-caps cut (named in `small_caps_faces`), which draws the text as it is; `caps` upper-cases the text.
|
|
17
|
+
- A span with no face, or a face missing from `fonts`, gets the standard PDF face for its style (Times), so a layout
|
|
18
|
+
draws before any font is matched.
|
|
19
|
+
- Figures are drawn first, each crop stretched to its box.
|
|
20
|
+
ReportLab and pdfium have no type stubs, so they are reached through `Any` here; the types of this module's own
|
|
21
|
+
functions are complete."""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import importlib
|
|
27
|
+
import io
|
|
28
|
+
import os
|
|
29
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from typing import TYPE_CHECKING, Any
|
|
32
|
+
|
|
33
|
+
from strata_python.pages.model import Block, Line, Page, PageError, Span
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from PIL import Image
|
|
37
|
+
|
|
38
|
+
SIZE_OF_BOX = (
|
|
39
|
+
0.9 # a Tesseract line box runs from the tallest capital or ascender to the lowest descender: about 0.9-1.1 em
|
|
40
|
+
)
|
|
41
|
+
DESCENT_EM = (
|
|
42
|
+
0.22 # with no baseline given, the baseline sits this far above the box's bottom (a book face's descenders)
|
|
43
|
+
)
|
|
44
|
+
SMALL_CAP = 0.78 # synthesised small capitals: the lower-case letters' size as a share of the capitals'
|
|
45
|
+
FIT_LIMIT_EM = 0.1 # the most a line's glyph spacing is changed to fit its box, in ems a glyph
|
|
46
|
+
STANDARD = {
|
|
47
|
+
"roman": "Times-Roman",
|
|
48
|
+
"italic": "Times-Italic",
|
|
49
|
+
"bold": "Times-Bold",
|
|
50
|
+
"bold-italic": "Times-BoldItalic",
|
|
51
|
+
"small-caps": "Times-Roman",
|
|
52
|
+
"caps": "Times-Roman",
|
|
53
|
+
"blackletter": "Times-Roman",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _rl(module: str) -> Any:
|
|
58
|
+
try:
|
|
59
|
+
return importlib.import_module(module)
|
|
60
|
+
except ImportError as e: # pragma: no cover (the extra is installed wherever this module's tests run)
|
|
61
|
+
raise ImportError("strata_python.pages.render needs the pdf extra: strata-python[pdf]") from e
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Fonts:
|
|
65
|
+
"""The fonts a render may use: each face id's TTF registered with ReportLab once a process, under a name made from
|
|
66
|
+
its path (ReportLab's registry is global, so two apps' faces with the same id must not collide)."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, fonts: Mapping[str, str], small_caps: Collection[str]) -> None:
|
|
69
|
+
self.paths = dict(fonts)
|
|
70
|
+
self.small_caps = set(small_caps)
|
|
71
|
+
self.pdfmetrics: Any = _rl("reportlab.pdfbase.pdfmetrics")
|
|
72
|
+
self.ttfonts: Any = _rl("reportlab.pdfbase.ttfonts")
|
|
73
|
+
|
|
74
|
+
def name(self, span: Span, line: Line) -> str:
|
|
75
|
+
face = span.face or line.face
|
|
76
|
+
path = self.paths.get(face) if face else None
|
|
77
|
+
if not path:
|
|
78
|
+
return STANDARD[span.style]
|
|
79
|
+
if not os.path.isfile(path):
|
|
80
|
+
raise PageError(f"font {face!r}: no such file {path!r}")
|
|
81
|
+
name = "sp-" + hashlib.sha1(os.path.abspath(path).encode()).hexdigest()[:12] # noqa: S324 (a name, not security)
|
|
82
|
+
if name not in self.pdfmetrics.getRegisteredFontNames():
|
|
83
|
+
self.pdfmetrics.registerFont(self.ttfonts.TTFont(name, path))
|
|
84
|
+
return name
|
|
85
|
+
|
|
86
|
+
def is_small_caps_cut(self, span: Span, line: Line) -> bool:
|
|
87
|
+
face = span.face or line.face
|
|
88
|
+
return face is not None and face in self.small_caps and face in self.paths
|
|
89
|
+
|
|
90
|
+
def width(self, text: str, font: str, size: float) -> float:
|
|
91
|
+
return float(self.pdfmetrics.stringWidth(text, font, size))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class _Run:
|
|
96
|
+
"""Text drawn with one font, size, scale, tracking and weight; `x` and `baseline` (scan pixels) when its span was
|
|
97
|
+
placed by a reader, else it follows the run before it."""
|
|
98
|
+
|
|
99
|
+
text: str
|
|
100
|
+
font: str
|
|
101
|
+
size: float
|
|
102
|
+
hscale: float
|
|
103
|
+
track: float # points a glyph
|
|
104
|
+
weight: float # stroke width in points (0: fill only)
|
|
105
|
+
x: float | None = None
|
|
106
|
+
baseline: float | None = None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _runs(line: Line, fonts: _Fonts, default_size: float) -> list[_Run]:
|
|
110
|
+
out: list[_Run] = []
|
|
111
|
+
for span in line.spans:
|
|
112
|
+
size = span.size_pt or line.size_pt or default_size
|
|
113
|
+
font = fonts.name(span, line)
|
|
114
|
+
track, weight = span.tracking_em * size, max(span.stroke_em, 0.0) * size
|
|
115
|
+
text = span.text.upper() if span.style == "caps" else span.text
|
|
116
|
+
if span.style != "small-caps" or fonts.is_small_caps_cut(span, line):
|
|
117
|
+
out.append(_Run(text, font, size, span.hscale, track, weight, span.x, span.baseline_y))
|
|
118
|
+
continue
|
|
119
|
+
# capitals as they are, lower case as smaller capitals; split where the case changes so each piece is one run
|
|
120
|
+
# (only the first piece is placed where the span was measured; the rest follow it)
|
|
121
|
+
pieces: list[tuple[str, bool]] = []
|
|
122
|
+
for ch in text:
|
|
123
|
+
if pieces and pieces[-1][1] == ch.islower():
|
|
124
|
+
pieces[-1] = (pieces[-1][0] + ch, pieces[-1][1])
|
|
125
|
+
else:
|
|
126
|
+
pieces.append((ch, ch.islower()))
|
|
127
|
+
for i, (piece, small) in enumerate(pieces):
|
|
128
|
+
first = i == 0
|
|
129
|
+
out.append(
|
|
130
|
+
_Run(
|
|
131
|
+
piece.upper(),
|
|
132
|
+
font,
|
|
133
|
+
size * SMALL_CAP if small else size,
|
|
134
|
+
span.hscale,
|
|
135
|
+
track,
|
|
136
|
+
weight,
|
|
137
|
+
span.x if first else None,
|
|
138
|
+
span.baseline_y,
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _run_width(fonts: _Fonts, run: _Run, extra: float = 0.0) -> float:
|
|
145
|
+
return fonts.width(run.text, run.font, run.size) * run.hscale + (run.track + extra) * len(run.text)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _draw_line(c: Any, line: Line, block: Block, fonts: _Fonts, k: float, page_h_pt: float, fit: bool) -> None:
|
|
149
|
+
x_px, y_px, w_px, h_px = line.box
|
|
150
|
+
runs = [r for r in _runs(line, fonts, max(h_px * k * SIZE_OF_BOX, 1.0)) if r.text]
|
|
151
|
+
glyphs = sum(len(r.text) for r in runs)
|
|
152
|
+
if not glyphs:
|
|
153
|
+
return
|
|
154
|
+
placed = any(r.x is not None for r in runs)
|
|
155
|
+
natural = sum(_run_width(fonts, r) for r in runs)
|
|
156
|
+
box_w = w_px * k
|
|
157
|
+
extra = 0.0
|
|
158
|
+
if fit and not placed and box_w > 0 and glyphs > 1:
|
|
159
|
+
mean_size = sum(r.size * len(r.text) for r in runs) / glyphs
|
|
160
|
+
limit = FIT_LIMIT_EM * mean_size
|
|
161
|
+
extra = max(-limit, min(limit, (box_w - natural) / glyphs))
|
|
162
|
+
width = natural + extra * glyphs
|
|
163
|
+
x = x_px * k
|
|
164
|
+
if not placed and block.align == "centre":
|
|
165
|
+
x += (box_w - width) / 2
|
|
166
|
+
elif not placed and block.align == "right":
|
|
167
|
+
x += box_w - width
|
|
168
|
+
line_base = line.baseline_y if line.baseline_y is not None else y_px + h_px - DESCENT_EM * runs[0].size / k
|
|
169
|
+
for r in runs: # one text object a run: ReportLab's cursor does not count tracking or scale, so x is ours
|
|
170
|
+
if r.x is not None:
|
|
171
|
+
x = r.x * k
|
|
172
|
+
t = c.beginText(x, page_h_pt - (r.baseline if r.baseline is not None else line_base) * k)
|
|
173
|
+
t.setFont(r.font, r.size)
|
|
174
|
+
t.setHorizScale(r.hscale * 100)
|
|
175
|
+
# PDF scales character spacing by the horizontal scale too (Tz applies to Tc): divide it out, so tracking and
|
|
176
|
+
# fitting are the advance on the page that _run_width counts
|
|
177
|
+
t.setCharSpace((r.track + extra) / r.hscale)
|
|
178
|
+
if r.weight > 0: # fill and stroke the glyphs: heavier print than the face's own weight
|
|
179
|
+
t.setTextRenderMode(2)
|
|
180
|
+
t.textOut(r.text)
|
|
181
|
+
if r.weight > 0:
|
|
182
|
+
# the render mode and line width are graphics state that outlive the text object (and ReportLab assumes a
|
|
183
|
+
# fresh one is fill-only, so it never sets 0 again): save and restore round the run, or every later word
|
|
184
|
+
# on the page would be stroked too
|
|
185
|
+
c.saveState()
|
|
186
|
+
c.setLineWidth(r.weight)
|
|
187
|
+
c.drawText(t)
|
|
188
|
+
c.restoreState()
|
|
189
|
+
else:
|
|
190
|
+
c.drawText(t)
|
|
191
|
+
x += _run_width(fonts, r, extra)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _draw_page(c: Any, page: Page, fonts: _Fonts, fit: bool) -> None:
|
|
195
|
+
k = 72.0 / page.dpi # scan pixels to points
|
|
196
|
+
w_pt, h_pt = page.width * k, page.height * k
|
|
197
|
+
c.setPageSize((w_pt, h_pt))
|
|
198
|
+
for f in page.figures:
|
|
199
|
+
if f.image is None:
|
|
200
|
+
continue
|
|
201
|
+
if not os.path.isfile(f.image):
|
|
202
|
+
raise PageError(f"figure at {list(f.box)}: no such picture {f.image!r}")
|
|
203
|
+
x, y, w, h = f.box
|
|
204
|
+
c.drawImage(f.image, x * k, h_pt - (y + h) * k, w * k, h * k)
|
|
205
|
+
for block in page.reading_order():
|
|
206
|
+
for line in block.lines:
|
|
207
|
+
_draw_line(c, line, block, fonts, k, h_pt, fit)
|
|
208
|
+
c.showPage()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def render(
|
|
212
|
+
pages: Page | Sequence[Page],
|
|
213
|
+
fonts: Mapping[str, str] | None = None,
|
|
214
|
+
*,
|
|
215
|
+
small_caps_faces: Collection[str] = (),
|
|
216
|
+
fit: bool = True,
|
|
217
|
+
title: str | None = None,
|
|
218
|
+
) -> bytes:
|
|
219
|
+
"""The PDF of one page or several (one PDF page each, sized from the scan's pixels and dpi). `fonts` maps face ids
|
|
220
|
+
to TTF or OTF files with TrueType outlines; the faces used are embedded (subset). The output is the same bytes for
|
|
221
|
+
the same input (no creation date or random id), so a cached rebuild compares by hash."""
|
|
222
|
+
canvas: Any = _rl("reportlab.pdfgen.canvas")
|
|
223
|
+
buf = io.BytesIO()
|
|
224
|
+
c = canvas.Canvas(buf, invariant=1, pageCompression=1)
|
|
225
|
+
if title:
|
|
226
|
+
c.setTitle(title)
|
|
227
|
+
f = _Fonts(fonts or {}, small_caps_faces)
|
|
228
|
+
for page in [pages] if isinstance(pages, Page) else pages:
|
|
229
|
+
_draw_page(c, page, f, fit)
|
|
230
|
+
c.save()
|
|
231
|
+
return buf.getvalue()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _document(pdf: bytes) -> Any:
|
|
235
|
+
return _rl("pypdfium2").PdfDocument(pdf)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def page_count(pdf: bytes) -> int:
|
|
239
|
+
doc = _document(pdf)
|
|
240
|
+
try:
|
|
241
|
+
return len(doc)
|
|
242
|
+
finally:
|
|
243
|
+
doc.close()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def rasterise(pdf: bytes, page: int = 0, dpi: float = 300.0) -> Image.Image:
|
|
247
|
+
"""One page of a PDF as a greyscale picture at `dpi` (the scan's dpi gives the scan's size in pixels), white paper."""
|
|
248
|
+
doc = _document(pdf)
|
|
249
|
+
try:
|
|
250
|
+
if not 0 <= page < len(doc):
|
|
251
|
+
raise PageError(f"no page {page} in a PDF of {len(doc)}")
|
|
252
|
+
p = doc[page]
|
|
253
|
+
img = p.render(scale=dpi / 72.0).to_pil().convert("L")
|
|
254
|
+
p.close()
|
|
255
|
+
return img
|
|
256
|
+
finally:
|
|
257
|
+
doc.close()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def read_text(pdf: bytes, page: int | None = None) -> str:
|
|
261
|
+
"""The text a reader gets from the PDF (one page, or every page with a form feed between), in drawing order."""
|
|
262
|
+
doc = _document(pdf)
|
|
263
|
+
try:
|
|
264
|
+
out: list[str] = []
|
|
265
|
+
for i in [page] if page is not None else range(len(doc)):
|
|
266
|
+
p = doc[i]
|
|
267
|
+
tp = p.get_textpage()
|
|
268
|
+
out.append(str(tp.get_text_range()).replace("\r\n", "\n").replace("\r", "\n"))
|
|
269
|
+
tp.close()
|
|
270
|
+
p.close()
|
|
271
|
+
return "\f".join(out)
|
|
272
|
+
finally:
|
|
273
|
+
doc.close()
|
strata_python/public_check.py
CHANGED
|
@@ -5,6 +5,14 @@ release workflow scans the built sdist and wheel (and CI scans the tree) before
|
|
|
5
5
|
catch what is personal in any repo: email addresses, private IPv4 addresses and home-folder paths. Names that are
|
|
6
6
|
personal to one owner (a person, a host name, a port map) cannot be listed here without publishing them, so they come
|
|
7
7
|
from the `STRATA_PUBLIC_DENY` environment variable (one case-insensitive regex per line), which CI fills from a secret.
|
|
8
|
+
|
|
9
|
+
False positives left after that are silenced in the repo, where a reviewer sees them:
|
|
10
|
+
|
|
11
|
+
- `[tool.strata-public-check] exclude = ["web/package-lock.json"]` in pyproject.toml (or `--exclude`): glob patterns
|
|
12
|
+
matched against each file's path in the folder or archive, or any trailing part of it (so an sdist's
|
|
13
|
+
`pkg-1.0/web/package-lock.json` matches too). An excluded file skips the built-in patterns only.
|
|
14
|
+
- `strata-public-check: ignore` anywhere on a line skips the built-in patterns on that line. Never the owner's
|
|
15
|
+
`STRATA_PUBLIC_DENY` patterns: a name the owner listed is never one to publish.
|
|
8
16
|
"""
|
|
9
17
|
|
|
10
18
|
from __future__ import annotations
|
|
@@ -15,12 +23,17 @@ import os
|
|
|
15
23
|
import re
|
|
16
24
|
import sys
|
|
17
25
|
import tarfile
|
|
26
|
+
import tomllib
|
|
18
27
|
import zipfile
|
|
19
28
|
from collections.abc import Iterable, Iterator
|
|
20
29
|
from dataclasses import dataclass
|
|
30
|
+
from fnmatch import fnmatchcase
|
|
21
31
|
from pathlib import Path
|
|
32
|
+
from typing import Any, cast
|
|
22
33
|
|
|
23
34
|
DENY_ENV = "STRATA_PUBLIC_DENY"
|
|
35
|
+
TABLE = "strata-public-check"
|
|
36
|
+
IGNORE = "strata-public-check: ignore"
|
|
24
37
|
|
|
25
38
|
# Placeholders the docs use on purpose (AGENTS.md: examples use /home/ada/..., myapp).
|
|
26
39
|
PLACEHOLDER_USERS = {"ada", "user", "me", "you", "name", "myapp", "runner"}
|
|
@@ -31,7 +44,11 @@ BUILT_IN: dict[str, re.Pattern[str]] = {
|
|
|
31
44
|
"email address": re.compile(
|
|
32
45
|
r"\b(?!noreply@anthropic\.com\b)[A-Za-z0-9._%+-]+@(?!users\.noreply\.github\.com\b)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b"
|
|
33
46
|
),
|
|
34
|
-
|
|
47
|
+
# A whole dotted quad and nothing more: a three-part version (`10.4.2` in package.json, issue #13) or a longer
|
|
48
|
+
# dotted number is not an address. The lookarounds stop a match inside a longer run of digits and dots.
|
|
49
|
+
"private IPv4 address": re.compile(
|
|
50
|
+
r"(?<![\w.])(?:10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2})(?!\.?\d)"
|
|
51
|
+
),
|
|
35
52
|
"home folder path": re.compile(r"(?:/home/|/Users/|[A-Za-z]:\\+Users\\+)(?P<user>[A-Za-z0-9._-]+)"),
|
|
36
53
|
}
|
|
37
54
|
|
|
@@ -62,10 +79,13 @@ def deny_patterns(env: str | None = None) -> list[re.Pattern[str]]:
|
|
|
62
79
|
return [re.compile(line.strip(), re.IGNORECASE) for line in raw.splitlines() if line.strip()]
|
|
63
80
|
|
|
64
81
|
|
|
65
|
-
def scan_text(
|
|
82
|
+
def scan_text(
|
|
83
|
+
where: str, text: str, extra: Iterable[re.Pattern[str]] = (), *, built_in: bool = True
|
|
84
|
+
) -> Iterator[Finding]:
|
|
85
|
+
"""Findings in one file's text. `built_in=False` (an excluded file) checks only the owner's patterns."""
|
|
66
86
|
extra = list(extra)
|
|
67
87
|
for number, line in enumerate(text.splitlines(), 1):
|
|
68
|
-
for kind, pattern in BUILT_IN.items():
|
|
88
|
+
for kind, pattern in BUILT_IN.items() if built_in and IGNORE not in line else ():
|
|
69
89
|
for match in pattern.finditer(line):
|
|
70
90
|
if kind == "home folder path" and match.group("user").lower() in PLACEHOLDER_USERS:
|
|
71
91
|
continue
|
|
@@ -76,6 +96,20 @@ def scan_text(where: str, text: str, extra: Iterable[re.Pattern[str]] = ()) -> I
|
|
|
76
96
|
yield Finding(where, number, f"matches {DENY_ENV} pattern", "(hidden)")
|
|
77
97
|
|
|
78
98
|
|
|
99
|
+
def excluded(name: str, patterns: Iterable[str]) -> bool:
|
|
100
|
+
"""Whether a path (posix, relative to its folder or archive) matches an exclude pattern, whole or at its end."""
|
|
101
|
+
return any(fnmatchcase(name, p) or fnmatchcase(name, "*/" + p) for p in patterns)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def config_excludes(root: Path | None = None) -> list[str]:
|
|
105
|
+
"""`exclude` from `[tool.strata-public-check]` in root's (default: the current folder's) pyproject.toml."""
|
|
106
|
+
f = (root or Path()) / "pyproject.toml"
|
|
107
|
+
if not f.is_file():
|
|
108
|
+
return []
|
|
109
|
+
tool = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {}))
|
|
110
|
+
return [str(p) for p in cast("dict[str, Any]", tool.get(TABLE, {})).get("exclude", [])]
|
|
111
|
+
|
|
112
|
+
|
|
79
113
|
def _is_text(name: str) -> bool:
|
|
80
114
|
path = Path(name)
|
|
81
115
|
hidden = any(part.startswith(".") and part != ".github" for part in path.parts[:-1])
|
|
@@ -103,14 +137,19 @@ def _members(path: Path) -> Iterator[tuple[str, bytes]]:
|
|
|
103
137
|
yield path.as_posix(), path.read_bytes()
|
|
104
138
|
|
|
105
139
|
|
|
106
|
-
def scan(paths: Iterable[Path], extra: Iterable[re.Pattern[str]] = ()) -> list[Finding]:
|
|
107
|
-
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl)."""
|
|
108
|
-
extra = list(extra)
|
|
140
|
+
def scan(paths: Iterable[Path], extra: Iterable[re.Pattern[str]] = (), exclude: Iterable[str] = ()) -> list[Finding]:
|
|
141
|
+
"""Every finding in the given folders, files, sdists (.tar.gz) and wheels (.whl), less the excluded files."""
|
|
142
|
+
extra, exclude = list(extra), list(exclude)
|
|
109
143
|
findings: list[Finding] = []
|
|
110
144
|
for path in paths:
|
|
111
145
|
for where, data in _members(path):
|
|
146
|
+
skip = excluded(where, exclude)
|
|
147
|
+
if skip and not extra:
|
|
148
|
+
continue
|
|
112
149
|
text = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", errors="replace").read()
|
|
113
|
-
|
|
150
|
+
# an excluded file is still checked against the owner's patterns: an exclude is for false positives of the
|
|
151
|
+
# built-in ones, and a name the owner listed is never one to publish (review finding)
|
|
152
|
+
findings.extend(scan_text(where, text, extra, built_in=not skip))
|
|
114
153
|
return findings
|
|
115
154
|
|
|
116
155
|
|
|
@@ -119,8 +158,15 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
119
158
|
prog="strata-public-check", description="Refuse to publish personal or machine-specific details."
|
|
120
159
|
)
|
|
121
160
|
parser.add_argument("paths", nargs="*", type=Path, default=[Path()], help="folders, files, sdists or wheels")
|
|
161
|
+
parser.add_argument(
|
|
162
|
+
"--exclude",
|
|
163
|
+
action="append",
|
|
164
|
+
default=[],
|
|
165
|
+
metavar="GLOB",
|
|
166
|
+
help=f"skip matching files, as well as [tool.{TABLE}] exclude in ./pyproject.toml",
|
|
167
|
+
)
|
|
122
168
|
args = parser.parse_args(argv)
|
|
123
|
-
findings = scan(args.paths, deny_patterns())
|
|
169
|
+
findings = scan(args.paths, deny_patterns(), [*config_excludes(), *args.exclude])
|
|
124
170
|
for finding in findings:
|
|
125
171
|
print(finding, file=sys.stderr)
|
|
126
172
|
if findings:
|