strata-python 0.2.1__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/cli.py +99 -20
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +780 -0
- strata_python/db/__init__.py +6 -3
- strata_python/db/models.py +15 -3
- strata_python/db/project.py +29 -16
- strata_python/db/pytest_plugin.py +63 -9
- strata_python/db/settings.py +63 -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/settings.py +243 -42
- strata_python/web.py +15 -6
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/METADATA +78 -18
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/RECORD +20 -14
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.1.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
strata_python/db/__init__.py
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
SQLAlchemy models, Alembic migrations generated from them, the `strata-db` command and pytest fixtures. Install the
|
|
3
3
|
extra: `strata-python[db]`.
|
|
4
4
|
|
|
5
|
-
from
|
|
6
|
-
from sqlalchemy.orm import Mapped, mapped_column
|
|
5
|
+
from sqlalchemy import MetaData
|
|
6
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
|
|
7
|
+
from strata_python.db import NAMING_CONVENTION, connect, session
|
|
8
|
+
|
|
9
|
+
class Base(MappedAsDataclass, DeclarativeBase): # the app's own base: written out, so ty and pyright accept it
|
|
10
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
7
11
|
|
|
8
|
-
Base = make_base()
|
|
9
12
|
class Note(Base): # a typed record; Alembic generates the table from it
|
|
10
13
|
__tablename__ = "notes"
|
|
11
14
|
id: Mapped[int] = mapped_column(primary_key=True, init=False)
|
strata_python/db/models.py
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
"""Declarative bases for apps' models.
|
|
2
2
|
|
|
3
|
-
from
|
|
4
|
-
|
|
3
|
+
from sqlalchemy import MetaData
|
|
4
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
|
|
5
|
+
from strata_python.db import NAMING_CONVENTION
|
|
6
|
+
|
|
7
|
+
class Base(MappedAsDataclass, DeclarativeBase): # one per app, in its models module
|
|
8
|
+
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
5
9
|
|
|
6
10
|
class Note(Base):
|
|
7
11
|
__tablename__ = "notes"
|
|
@@ -13,6 +17,12 @@ convention gives every index and constraint a stable name, which Alembic needs t
|
|
|
13
17
|
especially on SQLite (batch mode recreates tables and must name what it recreates). It must stay exactly as it is:
|
|
14
18
|
the apps' existing revisions and databases carry these names, and a change would make every one of them drift.
|
|
15
19
|
`Base` is a ready-made shared one for scripts that only ever load one app's models.
|
|
20
|
+
|
|
21
|
+
An app writes its base class out, as above, rather than `Base = make_base()` (issue #20): ty cannot take a value of
|
|
22
|
+
type `type[...]` as a base class, since it cannot know that value's MRO, and the gate fails on its warning. pyright
|
|
23
|
+
accepts either. A class statement cannot be shared from here instead: SQLAlchemy makes only a *direct* subclass of
|
|
24
|
+
DeclarativeBase a base with its own registry and MetaData, so a subclass of a base defined here would put every app's
|
|
25
|
+
tables in one MetaData. `make_base()` stays for code that needs a fresh base at run time (tests, scripts).
|
|
16
26
|
"""
|
|
17
27
|
|
|
18
28
|
from __future__ import annotations
|
|
@@ -39,7 +49,9 @@ if TYPE_CHECKING:
|
|
|
39
49
|
|
|
40
50
|
|
|
41
51
|
def make_base() -> type[DataclassBase]:
|
|
42
|
-
"""A new declarative base with its own MetaData (so two apps' models never mix in one process)
|
|
52
|
+
"""A new declarative base with its own MetaData (so two apps' models never mix in one process), for code that needs
|
|
53
|
+
one at run time. An app's models module writes its class out instead (see the module docstring): ty cannot
|
|
54
|
+
subclass the result."""
|
|
43
55
|
|
|
44
56
|
class AppBase(MappedAsDataclass, DeclarativeBase):
|
|
45
57
|
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
strata_python/db/project.py
CHANGED
|
@@ -26,6 +26,20 @@ if TYPE_CHECKING:
|
|
|
26
26
|
TABLE = "strata-db"
|
|
27
27
|
|
|
28
28
|
|
|
29
|
+
def find_table(start: str | os.PathLike[str] | None = None) -> tuple[Path, dict[str, Any]] | None:
|
|
30
|
+
"""The nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards: its folder and the table.
|
|
31
|
+
Standard library only, so the pytest plugin can ask without loading SQLAlchemy."""
|
|
32
|
+
p = Path(start or os.getcwd()).resolve()
|
|
33
|
+
for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
|
|
34
|
+
f = d / "pyproject.toml"
|
|
35
|
+
if not f.is_file():
|
|
36
|
+
continue
|
|
37
|
+
cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
|
|
38
|
+
if cfg:
|
|
39
|
+
return d, cast("dict[str, Any]", cfg)
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
29
43
|
@dataclass
|
|
30
44
|
class Project:
|
|
31
45
|
root: Path
|
|
@@ -41,22 +55,21 @@ class Project:
|
|
|
41
55
|
@classmethod
|
|
42
56
|
def load(cls, start: str | os.PathLike[str] | None = None) -> Project:
|
|
43
57
|
"""Find the nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards."""
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
raise FileNotFoundError(f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)")
|
|
58
|
+
found = find_table(start)
|
|
59
|
+
if found is None:
|
|
60
|
+
p = Path(start or os.getcwd()).resolve()
|
|
61
|
+
raise FileNotFoundError(
|
|
62
|
+
f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
|
|
63
|
+
)
|
|
64
|
+
d, cfg = found
|
|
65
|
+
return cls(
|
|
66
|
+
root=d,
|
|
67
|
+
app=cfg["app"],
|
|
68
|
+
models=cfg["models"],
|
|
69
|
+
migrations_dir=(d / cfg.get("migrations", "migrations")).resolve(),
|
|
70
|
+
engine=cfg.get("engine", "portable"),
|
|
71
|
+
schema=cfg.get("schema", cfg["app"]),
|
|
72
|
+
)
|
|
60
73
|
|
|
61
74
|
@property
|
|
62
75
|
def metadata(self) -> MetaData:
|
|
@@ -11,26 +11,34 @@ unless the db extra is installed: nothing here imports SQLAlchemy until a fixtur
|
|
|
11
11
|
|
|
12
12
|
Default backend: SQLite. The migrations run ONCE per session into a template; each test gets a copy (in memory for
|
|
13
13
|
db_engine, a file for db_url), so a test costs a copy, not a migration.
|
|
14
|
-
`pytest --pg` (or STRATA_DB_TEST=postgres, or engine = "postgres" in the project) uses a real Postgres instead:
|
|
14
|
+
`pytest --pg` (also `--strata-pg`; or STRATA_DB_TEST=postgres, or engine = "postgres" in the project) uses a real Postgres instead:
|
|
15
15
|
a template database is migrated once and each test gets `CREATE DATABASE ... TEMPLATE` (a file copy on the server,
|
|
16
16
|
milliseconds), dropped afterwards. That server is a throwaway one, never the real server: STRATA_DB_TEST_ADMIN_URL
|
|
17
17
|
if set (CI), otherwise a private server started for the run (strata_python.db.testserver).
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
When is it on? Only for an app that uses strata_python.db: SQLAlchemy and Alembic are installed (the db extra) AND
|
|
20
|
+
the project says so, by a [tool.strata-db] table in its pyproject.toml (found from pytest's rootdir upwards) or by
|
|
21
|
+
`strata_db = true` in its pytest ini options (`strata_db = false` turns it off whatever else is there). Having
|
|
22
|
+
SQLAlchemy and Alembic installed by some other package is not enough (issue #19): such an app, or one still on the old
|
|
23
|
+
database package, must be able to run pytest with this plugin registered and inert.
|
|
24
|
+
|
|
25
|
+
When it is on, the plugin switches on the test guard (strata_python.db.guard) in pytest_load_initial_conftests, before
|
|
26
|
+
conftest.py or any app module is imported (or, when it is loaded from a conftest.py itself, as in this repo's own
|
|
27
|
+
tests, in pytest_configure, before any test runs): for the whole run, every Postgres connection in the process (connect(),
|
|
21
28
|
create_engine(), psycopg.connect()) and in its subprocesses (STRATA_DB_TESTING=1) is refused unless it is a
|
|
22
29
|
throwaway strata_db_* database. A test that would reach the shared database fails with LiveDatabaseRefused instead.
|
|
23
30
|
"""
|
|
24
31
|
|
|
25
32
|
from __future__ import annotations
|
|
26
33
|
|
|
34
|
+
import contextlib
|
|
27
35
|
import os
|
|
28
36
|
import shutil
|
|
29
37
|
import tempfile
|
|
30
38
|
from collections.abc import Iterator
|
|
31
39
|
from importlib.util import find_spec
|
|
32
40
|
from pathlib import Path
|
|
33
|
-
from typing import TYPE_CHECKING
|
|
41
|
+
from typing import TYPE_CHECKING, cast
|
|
34
42
|
|
|
35
43
|
import pytest
|
|
36
44
|
|
|
@@ -44,25 +52,71 @@ if TYPE_CHECKING:
|
|
|
44
52
|
|
|
45
53
|
TEST_BACKEND = "STRATA_DB_TEST"
|
|
46
54
|
INSTALLED = find_spec("sqlalchemy") is not None and find_spec("alembic") is not None
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
55
|
+
INI = "strata_db"
|
|
56
|
+
PG_DEST = "strata_db_pg"
|
|
57
|
+
PG_HELP = "run strata_python.db fixtures on a throwaway PostgreSQL"
|
|
58
|
+
_ACTIVE = pytest.StashKey[bool]() # per Config, not a module global: pytester runs nested sessions in one process
|
|
50
59
|
|
|
51
60
|
|
|
52
61
|
def pytest_addoption(parser: pytest.Parser) -> None:
|
|
53
|
-
|
|
62
|
+
# Only names of our own here: another plugin (the old database package) may also add --pg, and two addoption
|
|
63
|
+
# calls for one name raise. --pg itself is added once we know the plugin is on (_activate).
|
|
64
|
+
parser.addoption("--strata-pg", action="store_true", dest=PG_DEST, help=PG_HELP)
|
|
65
|
+
parser.addini(INI, type="bool", default=None, help="turn the strata_python.db fixtures and test guard on or off")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def active(config: pytest.Config) -> bool:
|
|
69
|
+
"""Whether this run uses strata_python.db (see the module docstring)."""
|
|
70
|
+
if not INSTALLED:
|
|
71
|
+
return False
|
|
72
|
+
wanted = cast("bool | None", config.getini(INI))
|
|
73
|
+
if wanted is not None:
|
|
74
|
+
return bool(wanted)
|
|
75
|
+
from .project import find_table
|
|
76
|
+
|
|
77
|
+
return find_table(config.rootpath) is not None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _activate(config: pytest.Config, parser: pytest.Parser | None) -> None:
|
|
81
|
+
if _ACTIVE in config.stash:
|
|
82
|
+
return
|
|
83
|
+
config.stash[_ACTIVE] = on = active(config)
|
|
84
|
+
if not on:
|
|
85
|
+
return
|
|
86
|
+
guard.enter_test_mode()
|
|
87
|
+
if parser is not None: # still before the full command line is parsed, so --pg given there is recognised
|
|
88
|
+
# ValueError: another plugin (the old database package) has --pg; it means the same, and db_backend reads it
|
|
89
|
+
with contextlib.suppress(ValueError):
|
|
90
|
+
parser.addoption("--pg", action="store_true", dest=PG_DEST, help=PG_HELP)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@pytest.hookimpl(tryfirst=True)
|
|
94
|
+
def pytest_load_initial_conftests(early_config: pytest.Config, parser: pytest.Parser) -> None:
|
|
95
|
+
_activate(early_config, parser) # entry point or -p: before conftest.py and the app's modules are imported
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def pytest_configure(config: pytest.Config) -> None:
|
|
99
|
+
_activate(config, None) # loaded from a conftest.py (pytest_plugins): the hook above has already run
|
|
54
100
|
|
|
55
101
|
|
|
56
102
|
@pytest.fixture(scope="session")
|
|
57
103
|
def db_project(request: pytest.FixtureRequest) -> Project:
|
|
58
104
|
from .project import Project
|
|
59
105
|
|
|
106
|
+
if not request.config.stash.get(_ACTIVE, False):
|
|
107
|
+
pytest.fail(
|
|
108
|
+
"the strata_python.db fixtures are off: they need the db extra (strata-python[db]) and a [tool.strata-db]"
|
|
109
|
+
f" table in pyproject.toml, or {INI} = true in the pytest ini options",
|
|
110
|
+
pytrace=False,
|
|
111
|
+
)
|
|
60
112
|
return Project.load(request.config.rootpath)
|
|
61
113
|
|
|
62
114
|
|
|
63
115
|
@pytest.fixture(scope="session")
|
|
64
116
|
def db_backend(request: pytest.FixtureRequest, db_project: Project) -> str:
|
|
65
|
-
|
|
117
|
+
cfg = request.config
|
|
118
|
+
pg = cfg.getoption(PG_DEST) or cfg.getoption("--pg", default=False) # ours, or another plugin's --pg
|
|
119
|
+
pg = pg or os.environ.get(TEST_BACKEND) == "postgres" or db_project.postgres_only
|
|
66
120
|
return "postgres" if pg else "sqlite"
|
|
67
121
|
|
|
68
122
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""An app's settings kept in its database: the `SettingsStore` for `strata_python.settings.Settings.bind`.
|
|
2
|
+
|
|
3
|
+
# models.py: the table is part of the app's models, so its migrations create it
|
|
4
|
+
from strata_python.db.settings import settings_table
|
|
5
|
+
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
6
|
+
|
|
7
|
+
# at service start, after the migrations
|
|
8
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # copies ~/.<app>/settings.json in once
|
|
9
|
+
|
|
10
|
+
One row per key, the value as JSON text (a string or a list of strings), so the table has the same shape on SQLite and
|
|
11
|
+
Postgres and in every app. Each update is one transaction with an upsert per key, so concurrent saves of different keys
|
|
12
|
+
never lose one (strata-models' service and its CLI write at the same time).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Mapping
|
|
19
|
+
|
|
20
|
+
from sqlalchemy import Column, MetaData, String, Table, Text, delete, select
|
|
21
|
+
from sqlalchemy.dialects import postgresql, sqlite
|
|
22
|
+
from sqlalchemy.engine import Engine
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def settings_table(metadata: MetaData, name: str = "settings") -> Table:
|
|
26
|
+
"""The settings table in the app's MetaData (its naming convention names the primary key)."""
|
|
27
|
+
return Table(
|
|
28
|
+
name,
|
|
29
|
+
metadata,
|
|
30
|
+
Column("key", String(200), primary_key=True),
|
|
31
|
+
Column("value", Text, nullable=False), # JSON
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TableStore:
|
|
36
|
+
"""Settings in a `settings_table` (see the module docstring)."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, engine: Engine, table: Table) -> None:
|
|
39
|
+
self.engine = engine
|
|
40
|
+
self.table = table
|
|
41
|
+
|
|
42
|
+
def load(self) -> dict[str, object]:
|
|
43
|
+
with self.engine.connect() as c:
|
|
44
|
+
rows = c.execute(select(self.table.c.key, self.table.c.value)).all()
|
|
45
|
+
out: dict[str, object] = {}
|
|
46
|
+
for key, value in rows:
|
|
47
|
+
try:
|
|
48
|
+
out[str(key)] = json.loads(value)
|
|
49
|
+
except ValueError:
|
|
50
|
+
continue # a row edited by hand into something that is not JSON reads as missing, like a broken file
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
def update(self, changes: Mapping[str, object]) -> dict[str, object]:
|
|
54
|
+
t = self.table
|
|
55
|
+
insert = postgresql.insert if self.engine.dialect.name == "postgresql" else sqlite.insert
|
|
56
|
+
with self.engine.begin() as c:
|
|
57
|
+
for k, v in changes.items():
|
|
58
|
+
if v is None:
|
|
59
|
+
c.execute(delete(t).where(t.c.key == k))
|
|
60
|
+
else:
|
|
61
|
+
stmt = insert(t).values(key=k, value=json.dumps(v))
|
|
62
|
+
c.execute(stmt.on_conflict_do_update(index_elements=[t.c.key], set_={"value": stmt.excluded.value}))
|
|
63
|
+
return self.load()
|
strata_python/oslib.py
CHANGED
|
@@ -93,18 +93,57 @@ def kill_tree(pid: int | str, sig: int = 15) -> None:
|
|
|
93
93
|
os.kill(int(pid), sig)
|
|
94
94
|
|
|
95
95
|
|
|
96
|
-
|
|
97
|
-
|
|
96
|
+
# ioprio_set's syscall number per Linux architecture (Python has no wrapper). Elsewhere `ionice` does the same.
|
|
97
|
+
_IOPRIO_SET = {"x86_64": 251, "aarch64": 30, "riscv64": 30, "i686": 289, "i386": 289, "armv7l": 314, "ppc64le": 273}
|
|
98
|
+
_IOPRIO_IDLE = 3 << 13 # IOPRIO_CLASS_IDLE in the top bits of the priority value; idle has no level
|
|
99
|
+
MAC = sys.platform == "darwin"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def lower_priority(nice: int = 19, io: bool = False) -> None:
|
|
103
|
+
"""Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children
|
|
104
|
+
inherit it. Best effort: a refusal is skipped.
|
|
105
|
+
|
|
106
|
+
`io=True` also lowers its disk priority, for batch jobs that read many large files (hashing an archive, exiftool
|
|
107
|
+
over a folder) and should not slow interactive use of the same disk: the idle I/O class on Linux (children
|
|
108
|
+
inherit it), background mode on Windows (CPU and I/O; this process only, Windows does not pass it on), I/O
|
|
109
|
+
throttling on macOS (this process)."""
|
|
98
110
|
if WIN:
|
|
99
111
|
import ctypes
|
|
100
112
|
|
|
101
113
|
with contextlib.suppress(Exception):
|
|
102
|
-
ctypes.windll.kernel32
|
|
103
|
-
|
|
104
|
-
|
|
114
|
+
k32 = ctypes.windll.kernel32
|
|
115
|
+
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x40 if nice >= 15 else 0x4000) # IDLE / BELOW_NORMAL
|
|
116
|
+
if io:
|
|
117
|
+
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00100000) # PROCESS_MODE_BACKGROUND_BEGIN
|
|
105
118
|
return
|
|
106
119
|
with contextlib.suppress(OSError, AttributeError):
|
|
107
120
|
os.nice(nice)
|
|
121
|
+
if io:
|
|
122
|
+
_lower_io_priority()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _lower_io_priority(pid: int = 0) -> None:
|
|
126
|
+
"""Idle I/O for `pid` (0: this process). Other pids are for the tests, which must not lower their own."""
|
|
127
|
+
import ctypes
|
|
128
|
+
import ctypes.util
|
|
129
|
+
import platform
|
|
130
|
+
import shutil
|
|
131
|
+
|
|
132
|
+
if MAC: # pragma: no cover - the Linux leg runs the tests that count; macOS is best effort
|
|
133
|
+
with contextlib.suppress(Exception):
|
|
134
|
+
libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
|
|
135
|
+
libc.setiopolicy_np(0, 0, 3) # IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE
|
|
136
|
+
return
|
|
137
|
+
number = _IOPRIO_SET.get(platform.machine()) if sys.platform.startswith("linux") else None
|
|
138
|
+
if number is not None:
|
|
139
|
+
with contextlib.suppress(Exception):
|
|
140
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
141
|
+
if libc.syscall(number, 1, pid, _IOPRIO_IDLE) == 0: # IOPRIO_WHO_PROCESS
|
|
142
|
+
return
|
|
143
|
+
ionice = shutil.which("ionice")
|
|
144
|
+
if ionice: # another architecture or a refused syscall: util-linux's ionice does the same for our pid
|
|
145
|
+
with contextlib.suppress(OSError):
|
|
146
|
+
subprocess.run([ionice, "-c3", "-p", str(pid or os.getpid())], capture_output=True, check=False) # noqa: S603 (ionice from PATH, our pid)
|
|
108
147
|
|
|
109
148
|
|
|
110
149
|
def venv_python(venv: str) -> str:
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Scanned pages rebuilt as PDFs: the page description (`model`, plain data) and its renderer (`render`, the `[pdf]`
|
|
2
|
+
extra: ReportLab to write, pdfium to read back). See `model` for the shape and `render` for what is drawn how.
|
|
3
|
+
|
|
4
|
+
from strata_python.pages import Block, Figure, Line, Page, Span
|
|
5
|
+
from strata_python.pages.render import rasterise, read_text, render"""
|
|
6
|
+
|
|
7
|
+
from strata_python.pages.model import (
|
|
8
|
+
ALIGNS,
|
|
9
|
+
FIGURE_KINDS,
|
|
10
|
+
ROLES,
|
|
11
|
+
STYLES,
|
|
12
|
+
Block,
|
|
13
|
+
Box,
|
|
14
|
+
Figure,
|
|
15
|
+
Line,
|
|
16
|
+
Page,
|
|
17
|
+
PageError,
|
|
18
|
+
Span,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = ["ALIGNS", "FIGURE_KINDS", "ROLES", "STYLES", "Block", "Box", "Figure", "Line", "Page", "PageError", "Span"]
|
|
@@ -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)
|