basal-engine 3.0.3__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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/ordercheck.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Option-order check: how often the top pick changes when the options are shown in another order, and what averaging
|
|
2
|
+
over K orders (basal-serve --order-average K) gains and costs.
|
|
3
|
+
|
|
4
|
+
basal-bench --order-check --model Remek/basal-omni-1.0-mini # bundled examples, serving default
|
|
5
|
+
basal-bench --order-check --model Remek/basal-omni-1.0-mini --mode eager --questions dev.jsonl --average 2 4 6
|
|
6
|
+
|
|
7
|
+
Questions file (JSONL), as basal-bench: {"state": ..., "question": ..., "options": [...], "gold": <index, optional>}.
|
|
8
|
+
Every question is read in its first M option orders (basal.server.option_orders: the given order, the reversed one,
|
|
9
|
+
then each rotation and its reverse; M = the largest of 3 and --average), all orders of a question in one call over
|
|
10
|
+
one state. Reported per mode:
|
|
11
|
+
flip_reversed share of questions whose top option (single order) differs between the given and the reversed order
|
|
12
|
+
flip_rotated the same for the order rotated by one (the first option moved last; with 2 options = reversed)
|
|
13
|
+
flip_any the top option differs in at least one of the M orders
|
|
14
|
+
first_share share of single-order top picks at the first position, over the M orders (chance: mean 1 / k)
|
|
15
|
+
acc_given, acc_reversed, acc_rotated accuracy of each single order (with gold)
|
|
16
|
+
acc_mean<K> accuracy of the mean over the first K orders, as --order-average K serves it (K = 1: the given order)
|
|
17
|
+
agree_mean<K> share of questions whose mean-over-K top option equals the given order's
|
|
18
|
+
lat_mean<K>_ms median latency of one question with its first K orders at batch size 1 (--lat-n questions)
|
|
19
|
+
Flip rates and accuracies are also split by the number of options (by_k).
|
|
20
|
+
"""
|
|
21
|
+
import argparse
|
|
22
|
+
import json
|
|
23
|
+
import statistics
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
|
|
27
|
+
from .engine import resolve
|
|
28
|
+
from .jsonl import finite, write_json
|
|
29
|
+
from .prompt import letter_ids, model_format, render
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def top(p):
|
|
33
|
+
return max(range(len(p)), key=p.__getitem__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def canonical(perms, probs):
|
|
37
|
+
"""Position probabilities of each order -> the probabilities of each order in the canonical option order."""
|
|
38
|
+
out = []
|
|
39
|
+
for perm, p in zip(perms, probs):
|
|
40
|
+
c = [0.0] * len(perm)
|
|
41
|
+
for pos, j in enumerate(perm):
|
|
42
|
+
c[j] = float(p[pos])
|
|
43
|
+
out.append(c)
|
|
44
|
+
return out
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def mean(rows):
|
|
48
|
+
return [sum(x) / len(rows) for x in zip(*rows)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def groups_for(tok, qs, m, fmt=1):
|
|
52
|
+
"""Each question in its first m option orders -> [(question, perms, prompts, code ids per prompt)]."""
|
|
53
|
+
from .server import option_orders
|
|
54
|
+
out = []
|
|
55
|
+
for q in qs:
|
|
56
|
+
k = len(q["options"])
|
|
57
|
+
perms = option_orders(k, m)
|
|
58
|
+
prompts = [render(tok, q["state"], q["question"], [q["options"][c] for c in p], fmt=fmt) for p in perms]
|
|
59
|
+
ids = letter_ids(tok, prompts[0], k, fmt)
|
|
60
|
+
if ids and k >= 2:
|
|
61
|
+
out.append((q, perms, prompts, [ids] * len(perms)))
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def summarise(groups, canon, averages):
|
|
66
|
+
"""Per-question canonical probabilities of every order -> the report (without latencies)."""
|
|
67
|
+
rot_of = lambda k: list(range(1, k)) + [0] # the order rotated by one
|
|
68
|
+
rows = []
|
|
69
|
+
for (q, perms, _, _), c in zip(groups, canon):
|
|
70
|
+
k = len(perms[0])
|
|
71
|
+
tops = [top(x) for x in c]
|
|
72
|
+
rot = perms.index(rot_of(k))
|
|
73
|
+
pos = [p.index(t) for p, t in zip(perms, tops)] # position of each order's top pick
|
|
74
|
+
rows.append(dict(k=k, gold=q.get("gold"), tops=tops, rev=tops[1] != tops[0], rot=tops[rot] != tops[0],
|
|
75
|
+
any=len(set(tops)) > 1, first=sum(x == 0 for x in pos) / len(pos), chance=1 / k,
|
|
76
|
+
rot_i=rot, means={K: top(mean(c[:K])) for K in averages}))
|
|
77
|
+
gold = all(r["gold"] is not None for r in rows)
|
|
78
|
+
|
|
79
|
+
def block(rs):
|
|
80
|
+
n = len(rs)
|
|
81
|
+
if not n:
|
|
82
|
+
return {}
|
|
83
|
+
b = dict(n=n, flip_reversed=sum(r["rev"] for r in rs) / n, flip_rotated=sum(r["rot"] for r in rs) / n,
|
|
84
|
+
flip_any=sum(r["any"] for r in rs) / n, first_share=sum(r["first"] for r in rs) / n,
|
|
85
|
+
first_chance=sum(r["chance"] for r in rs) / n)
|
|
86
|
+
if gold:
|
|
87
|
+
b.update(acc_given=sum(r["tops"][0] == r["gold"] for r in rs) / n,
|
|
88
|
+
acc_reversed=sum(r["tops"][1] == r["gold"] for r in rs) / n,
|
|
89
|
+
acc_rotated=sum(r["tops"][r["rot_i"]] == r["gold"] for r in rs) / n)
|
|
90
|
+
for K in averages:
|
|
91
|
+
if gold:
|
|
92
|
+
b[f"acc_mean{K}"] = sum(r["means"][K] == r["gold"] for r in rs) / n
|
|
93
|
+
b[f"agree_mean{K}"] = sum(r["means"][K] == r["tops"][0] for r in rs) / n
|
|
94
|
+
return b
|
|
95
|
+
|
|
96
|
+
out = block(rows)
|
|
97
|
+
out["by_k"] = {label: block([r for r in rows if lo <= r["k"] <= hi])
|
|
98
|
+
for label, lo, hi in (("2", 2, 2), ("3-4", 3, 4), ("5+", 5, 10 ** 6))
|
|
99
|
+
if any(lo <= r["k"] <= hi for r in rows)}
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def latencies(be, groups, averages, lat_n):
|
|
104
|
+
"""Median latency of one question with its first K orders at batch size 1, per K."""
|
|
105
|
+
from .bench import timed
|
|
106
|
+
out = {}
|
|
107
|
+
for K in averages:
|
|
108
|
+
lat = []
|
|
109
|
+
for g in groups[: lat_n + 3]:
|
|
110
|
+
unit = [(g[2][:K], g[3][:K])]
|
|
111
|
+
be.run_shared(unit) # warm-up of the shapes
|
|
112
|
+
lat += timed(lambda: be.run_shared(unit), 1, be)
|
|
113
|
+
out[f"lat_mean{K}_ms"] = statistics.median(lat[3:] or lat) * 1000
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run(be, qs, fmt, averages, lat_n):
|
|
118
|
+
m = max([3] + list(averages))
|
|
119
|
+
groups = groups_for(be.tok, qs, m, fmt)
|
|
120
|
+
probs = []
|
|
121
|
+
for i in range(0, len(groups), 16):
|
|
122
|
+
probs += be.run_shared([(g[2], g[3]) for g in groups[i: i + 16]])
|
|
123
|
+
canon = [canonical(g[1], p) for g, p in zip(groups, probs)]
|
|
124
|
+
r = summarise(groups, canon, averages)
|
|
125
|
+
if lat_n > 0:
|
|
126
|
+
r.update(latencies(be, groups, averages, min(lat_n, len(groups))))
|
|
127
|
+
return r
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def main(argv=None):
|
|
131
|
+
from .bench import DEFAULT_QUESTIONS, build, device_name, questions_or_exit
|
|
132
|
+
from .server import default_mode
|
|
133
|
+
ap = argparse.ArgumentParser(prog="basal-bench --order-check", description=__doc__,
|
|
134
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
135
|
+
ap.add_argument("--model", default="Remek/basal-1.5-4.5B")
|
|
136
|
+
ap.add_argument("--mode", default=None, help="a basal-bench mode (default: the serving default)")
|
|
137
|
+
ap.add_argument("--questions", nargs="+", default=DEFAULT_QUESTIONS,
|
|
138
|
+
help="JSONL file(s) with simple items (default: the bundled examples)")
|
|
139
|
+
ap.add_argument("--n", type=int, default=1000)
|
|
140
|
+
ap.add_argument("--average", nargs="+", type=int, default=[1, 2, 4],
|
|
141
|
+
help="K values of the mean over the first K option orders (as basal-serve --order-average K)")
|
|
142
|
+
ap.add_argument("--lat-n", dest="lat_n", type=int, default=50, help="questions timed per K (0: no timing)")
|
|
143
|
+
ap.add_argument("--out", default=None, help="write the result as JSON")
|
|
144
|
+
a = ap.parse_args(argv)
|
|
145
|
+
if any(K < 1 for K in a.average):
|
|
146
|
+
raise SystemExit("--average: K >= 1 option orders")
|
|
147
|
+
mode = a.mode or default_mode(a.model)
|
|
148
|
+
md = resolve(a.model)
|
|
149
|
+
fmt = model_format(md)
|
|
150
|
+
qs = questions_or_exit(a.questions, a.n)
|
|
151
|
+
t0 = time.time()
|
|
152
|
+
be = build(mode, md, fmt=fmt)
|
|
153
|
+
r = dict(mode=mode, model=a.model, gpu=device_name(be), load_s=round(time.time() - t0, 1),
|
|
154
|
+
**run(be, qs, fmt, sorted(set(a.average)), a.lat_n))
|
|
155
|
+
print(json.dumps({k: round(v, 4) if isinstance(v, float) else v for k, v in r.items() if k != "by_k"}), flush=True)
|
|
156
|
+
for label, b in r["by_k"].items():
|
|
157
|
+
print(f" {label} options: n {b['n']}, flip reversed {b['flip_reversed']:.3f}, rotated "
|
|
158
|
+
f"{b['flip_rotated']:.3f}, any {b['flip_any']:.3f}", flush=True)
|
|
159
|
+
if a.out:
|
|
160
|
+
write_json(a.out, finite(r), indent=1) # whole or not at all; a rate without a value: null
|
|
161
|
+
return r
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
main(sys.argv[1:])
|
basal/pdf.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""PDF text for basal-navigate build (basal-engine[pdf]: pypdf, BSD-3-Clause, pure Python): the text of each page and the
|
|
2
|
+
outline, read in a child process within limits, so a hostile PDF (a decompression bomb, a page tree of millions of
|
|
3
|
+
pages, a content stream that never ends) cannot take the builder's memory or time.
|
|
4
|
+
|
|
5
|
+
read(path) -> {"pages": [text of page 1, ...], "outline": [(page index, depth, title), ...], "unreadable": n}
|
|
6
|
+
|
|
7
|
+
PDFError (a ValueError) says what is wrong or which limit a file crossed, and the basal-navigate build option that
|
|
8
|
+
raises it (max_mb, max_pages, seconds) or that the limit is fixed there (max_chars, memory_mb). The limits (LIMITS;
|
|
9
|
+
each a keyword of read): max_mb (the file, checked before it is opened), max_pages, seconds (the whole file, wall
|
|
10
|
+
clock; the child's CPU time too), page_chars (the text kept of a page), max_chars (all the pages of a file), memory_mb
|
|
11
|
+
(the child's address space; Linux only, where the kernel enforces it). pypdf itself stops a stream that decompresses
|
|
12
|
+
past 75 MB: that page is counted unreadable and the others are read. An encrypted PDF is read when the empty password
|
|
13
|
+
opens it, else refused.
|
|
14
|
+
"""
|
|
15
|
+
import importlib.util
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import signal
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
INSTALL = 'PDF input needs the pdf extra: uv pip install "basal-engine[pdf]" (pypdf)'
|
|
24
|
+
LIMITS = {"max_mb": 100, "max_pages": 2000, "seconds": 300, "page_chars": 100_000, "max_chars": 10_000_000,
|
|
25
|
+
"memory_mb": 2048}
|
|
26
|
+
OUTLINE = 10_000 # outline entries kept (titles cut at 200 characters, depth at most 6)
|
|
27
|
+
|
|
28
|
+
# The child: only the standard library and pypdf (no basal), started isolated (-I: no current folder, no PYTHON*
|
|
29
|
+
# variables such as PYTHONPATH, no user site), its answer one JSON object on stdout. A pypdf this process finds only
|
|
30
|
+
# through PYTHONPATH or the user site is not the child's: read() says so (_isolated) instead of the install line.
|
|
31
|
+
_CHILD = r'''
|
|
32
|
+
import json, logging, sys
|
|
33
|
+
a = json.loads(sys.argv[1])
|
|
34
|
+
|
|
35
|
+
def say(**kw):
|
|
36
|
+
sys.stdout.write(json.dumps(kw))
|
|
37
|
+
sys.stdout.flush()
|
|
38
|
+
raise SystemExit(0)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
import resource
|
|
42
|
+
cpu = int(a["seconds"]) + 1
|
|
43
|
+
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 1))
|
|
44
|
+
if sys.platform.startswith("linux"):
|
|
45
|
+
m = int(a["memory_mb"]) * 2 ** 20
|
|
46
|
+
resource.setrlimit(resource.RLIMIT_AS, (m, m))
|
|
47
|
+
except (ImportError, ValueError, OSError):
|
|
48
|
+
pass
|
|
49
|
+
try:
|
|
50
|
+
import pypdf
|
|
51
|
+
except ImportError:
|
|
52
|
+
say(error="nopypdf")
|
|
53
|
+
logging.disable(logging.WARNING) # pypdf's notes on malformed files: not the builder's output
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def clean(t):
|
|
57
|
+
"""Lone surrogates (pypdf decodes a ToUnicode CMap's <D800> with surrogatepass) as U+FFFD, a pair as its character:
|
|
58
|
+
the tree is written as UTF-8, which has no lone surrogate."""
|
|
59
|
+
return t.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
|
|
60
|
+
|
|
61
|
+
def outline(r):
|
|
62
|
+
"""(page index, depth, title) of the outline's entries in its order, by page (a nested list: the children of the
|
|
63
|
+
entry before it; 6 levels, a["outline"] entries at most)."""
|
|
64
|
+
out = []
|
|
65
|
+
|
|
66
|
+
def walk(items, depth):
|
|
67
|
+
for x in items:
|
|
68
|
+
if len(out) >= a["outline"]:
|
|
69
|
+
return
|
|
70
|
+
if isinstance(x, list):
|
|
71
|
+
if depth < 5:
|
|
72
|
+
walk(x, depth + 1)
|
|
73
|
+
continue
|
|
74
|
+
try:
|
|
75
|
+
page = r.get_destination_page_number(x)
|
|
76
|
+
except Exception:
|
|
77
|
+
continue
|
|
78
|
+
if isinstance(page, int) and page >= 0:
|
|
79
|
+
out.append((page, depth, clean(str(x.title))[:200]))
|
|
80
|
+
walk(r.outline, 0)
|
|
81
|
+
return sorted(out, key=lambda e: e[0]) # (stable: an entry's order within its page is kept)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
r = pypdf.PdfReader(a["path"], strict=False)
|
|
85
|
+
if r.is_encrypted:
|
|
86
|
+
try:
|
|
87
|
+
ok = r.decrypt("")
|
|
88
|
+
except Exception as e: # (AES without the cryptography package)
|
|
89
|
+
say(error="encrypted", why=f"{type(e).__name__}: {str(e)[:200]}")
|
|
90
|
+
if not ok:
|
|
91
|
+
say(error="encrypted")
|
|
92
|
+
n = len(r.pages)
|
|
93
|
+
if n > a["max_pages"]:
|
|
94
|
+
say(error="pages", pages=n)
|
|
95
|
+
texts, total, bad = [], 0, 0
|
|
96
|
+
for i in range(n):
|
|
97
|
+
try:
|
|
98
|
+
t = r.pages[i].extract_text() or ""
|
|
99
|
+
except MemoryError:
|
|
100
|
+
raise
|
|
101
|
+
except Exception: # a page pypdf cannot read (a stream past its 75 MB, a broken one): no text, counted
|
|
102
|
+
t, bad = "", bad + 1
|
|
103
|
+
t = clean(t)[: a["page_chars"]]
|
|
104
|
+
total += len(t)
|
|
105
|
+
if total > a["max_chars"]:
|
|
106
|
+
say(error="chars", page=i + 1)
|
|
107
|
+
texts.append(t)
|
|
108
|
+
try:
|
|
109
|
+
toc = outline(r)
|
|
110
|
+
except Exception:
|
|
111
|
+
toc = []
|
|
112
|
+
say(pages=texts, outline=toc, unreadable=bad)
|
|
113
|
+
except MemoryError:
|
|
114
|
+
say(error="memory")
|
|
115
|
+
except Exception as e:
|
|
116
|
+
say(error="unreadable", why=f"{type(e).__name__}: {str(e)[:200]}")
|
|
117
|
+
'''
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class PDFError(ValueError):
|
|
121
|
+
"""A PDF that cannot be read, or one beyond a limit: the message names the file, and the option that raises the
|
|
122
|
+
limit or that the limit is fixed."""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def available():
|
|
126
|
+
"""None when pypdf imports here (this process: its PYTHONPATH and user site too), else the install hint."""
|
|
127
|
+
return None if importlib.util.find_spec("pypdf") is not None else INSTALL
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _isolated():
|
|
131
|
+
"""The child's "no pypdf": the install line, or, when this process has pypdf (found through PYTHONPATH or the user
|
|
132
|
+
site, which the isolated child does not read), where it is and where the reader needs it."""
|
|
133
|
+
spec = importlib.util.find_spec("pypdf")
|
|
134
|
+
if spec is None:
|
|
135
|
+
return INSTALL
|
|
136
|
+
where = Path(spec.origin).parent.parent if spec.origin else "PYTHONPATH or the user site"
|
|
137
|
+
return (f"the PDF reader runs isolated (python -I: no PYTHONPATH, no user site) and has no pypdf, which this "
|
|
138
|
+
f"process finds in {where}; install it into {sys.prefix}: uv pip install \"basal-engine[pdf]\"")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def read(path, **limits):
|
|
142
|
+
"""The pages' text and the outline of the PDF at path, read in a child process within LIMITS (and the given
|
|
143
|
+
ones) -> {"pages", "outline", "unreadable"}; PDFError with what is wrong."""
|
|
144
|
+
unknown = set(limits) - set(LIMITS)
|
|
145
|
+
if unknown:
|
|
146
|
+
raise TypeError(f"unknown PDF limit(s): {', '.join(sorted(unknown))} (limits: {', '.join(LIMITS)})")
|
|
147
|
+
lim = {**LIMITS, **{k: v for k, v in limits.items() if v is not None}}
|
|
148
|
+
if available():
|
|
149
|
+
raise PDFError(f"{path}: {INSTALL}")
|
|
150
|
+
size = os.path.getsize(path)
|
|
151
|
+
if size > lim["max_mb"] * 2 ** 20:
|
|
152
|
+
raise PDFError(f"{path}: {size / 2 ** 20:.1f} MB, more than the {lim['max_mb']} MB a PDF may have "
|
|
153
|
+
"(--pdf-max-mb)")
|
|
154
|
+
args = json.dumps({**lim, "outline": OUTLINE, "path": str(Path(path).resolve())})
|
|
155
|
+
try:
|
|
156
|
+
p = subprocess.run([sys.executable, "-I", "-c", _CHILD, args], capture_output=True, text=True,
|
|
157
|
+
timeout=lim["seconds"])
|
|
158
|
+
except subprocess.TimeoutExpired:
|
|
159
|
+
raise PDFError(f"{path}: not read in {lim['seconds']} s (--pdf-seconds)") from None
|
|
160
|
+
try:
|
|
161
|
+
out = json.loads(p.stdout)
|
|
162
|
+
except ValueError:
|
|
163
|
+
out = None
|
|
164
|
+
if not isinstance(out, dict):
|
|
165
|
+
code = p.returncode
|
|
166
|
+
# (Windows has neither signal: a crash there is an exit code)
|
|
167
|
+
why = ("its CPU time ran out" if code in (-getattr(signal, "SIGXCPU", 24), -getattr(signal, "SIGKILL", 9)) else
|
|
168
|
+
f"the reader stopped (exit {code})")
|
|
169
|
+
last = (p.stderr.strip().splitlines() or [""])[-1][:200]
|
|
170
|
+
raise PDFError(f"{path}: {why}{': ' + last if last else ''}")
|
|
171
|
+
error = out.get("error")
|
|
172
|
+
if error is None:
|
|
173
|
+
return {"pages": out["pages"], "outline": [tuple(x) for x in out["outline"]], "unreadable": out["unreadable"]}
|
|
174
|
+
raise PDFError(f"{path}: " + {
|
|
175
|
+
"nopypdf": _isolated(),
|
|
176
|
+
"encrypted": "encrypted with a password: give an unencrypted copy" + (f" ({out['why']})" if out.get("why")
|
|
177
|
+
else ""),
|
|
178
|
+
"pages": f"{out.get('pages')} pages, more than the {lim['max_pages']} a PDF may have (--pdf-max-pages)",
|
|
179
|
+
"chars": f"more than {lim['max_chars']:,} characters of text by page {out.get('page')} (a fixed limit: "
|
|
180
|
+
"split the PDF)",
|
|
181
|
+
"memory": f"it needs more than the {lim['memory_mb']} MB of memory its reader may use (a fixed limit)",
|
|
182
|
+
"unreadable": f"not a PDF pypdf can read ({out.get('why')})",
|
|
183
|
+
}.get(error, error))
|