simplutils 0.1.0__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.
- simplutils/__init__.py +34 -0
- simplutils/__main__.py +3 -0
- simplutils/cli.py +187 -0
- simplutils/interactive.py +195 -0
- simplutils/logs.py +62 -0
- simplutils/registry.py +161 -0
- simplutils/textio.py +25 -0
- simplutils/tools/__init__.py +5 -0
- simplutils/tools/ai.py +239 -0
- simplutils/tools/convert.py +118 -0
- simplutils/tools/diff.py +74 -0
- simplutils/tools/encoding.py +66 -0
- simplutils/tools/files.py +88 -0
- simplutils/tools/generators.py +75 -0
- simplutils/tools/hashing.py +20 -0
- simplutils/tools/images.py +163 -0
- simplutils/tools/jsontools.py +24 -0
- simplutils/tools/jwt.py +32 -0
- simplutils/tools/mapsearch.py +178 -0
- simplutils/tools/pdfs.py +133 -0
- simplutils/tools/pii.py +211 -0
- simplutils/tools/qr.py +40 -0
- simplutils/tools/regex.py +44 -0
- simplutils/tools/text.py +49 -0
- simplutils/tools/timetools.py +41 -0
- simplutils/ui.py +186 -0
- simplutils-0.1.0.dist-info/METADATA +1081 -0
- simplutils-0.1.0.dist-info/RECORD +31 -0
- simplutils-0.1.0.dist-info/WHEEL +4 -0
- simplutils-0.1.0.dist-info/entry_points.txt +2 -0
- simplutils-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Image tools (need Pillow: pip install simplutils[files])."""
|
|
2
|
+
import io
|
|
3
|
+
from typing import List, Literal
|
|
4
|
+
|
|
5
|
+
from ..registry import FileResult, ToolError, tool
|
|
6
|
+
|
|
7
|
+
G = "Images"
|
|
8
|
+
MAX_SIDE = 20000
|
|
9
|
+
|
|
10
|
+
# key -> (Pillow format, mime, extension)
|
|
11
|
+
_FORMATS = {
|
|
12
|
+
"png": ("PNG", "image/png", "png"),
|
|
13
|
+
"jpg": ("JPEG", "image/jpeg", "jpg"),
|
|
14
|
+
"webp": ("WEBP", "image/webp", "webp"),
|
|
15
|
+
"bmp": ("BMP", "image/bmp", "bmp"),
|
|
16
|
+
"gif": ("GIF", "image/gif", "gif"),
|
|
17
|
+
}
|
|
18
|
+
_BY_PIL = {v[0]: k for k, v in _FORMATS.items()}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _pil():
|
|
22
|
+
try:
|
|
23
|
+
from PIL import Image, ImageOps
|
|
24
|
+
except ImportError:
|
|
25
|
+
raise ToolError("this tool needs Pillow: pip install simplutils[files]")
|
|
26
|
+
return Image, ImageOps
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _open(data: bytes):
|
|
30
|
+
"""Open an image, honour EXIF rotation. Returns (image, source format key)."""
|
|
31
|
+
Image, ImageOps = _pil()
|
|
32
|
+
try:
|
|
33
|
+
img = Image.open(io.BytesIO(data))
|
|
34
|
+
fmt = _BY_PIL.get(img.format, "png")
|
|
35
|
+
img.load()
|
|
36
|
+
return ImageOps.exif_transpose(img), fmt
|
|
37
|
+
except ToolError:
|
|
38
|
+
raise
|
|
39
|
+
except Exception as e:
|
|
40
|
+
raise ToolError(f"cannot read image: {e}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _flatten(img):
|
|
44
|
+
"""Convert to RGB, putting transparency on a white background."""
|
|
45
|
+
Image, _ = _pil()
|
|
46
|
+
if img.mode in ("RGB", "L"):
|
|
47
|
+
return img
|
|
48
|
+
rgba = img.convert("RGBA")
|
|
49
|
+
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
50
|
+
bg.paste(rgba, mask=rgba.split()[3])
|
|
51
|
+
return bg
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _check_quality(q: int) -> None:
|
|
55
|
+
if not 1 <= q <= 100:
|
|
56
|
+
raise ToolError("quality must be 1-100")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _encode(img, key: str, quality: int = 90) -> bytes:
|
|
60
|
+
pil_fmt = _FORMATS[key][0]
|
|
61
|
+
params = {}
|
|
62
|
+
if pil_fmt == "JPEG":
|
|
63
|
+
img = _flatten(img)
|
|
64
|
+
params = {"quality": quality, "optimize": True}
|
|
65
|
+
elif pil_fmt == "WEBP":
|
|
66
|
+
params = {"quality": quality}
|
|
67
|
+
elif pil_fmt == "PNG":
|
|
68
|
+
params = {"optimize": True}
|
|
69
|
+
buf = io.BytesIO()
|
|
70
|
+
try:
|
|
71
|
+
img.save(buf, pil_fmt, **params)
|
|
72
|
+
except Exception as e:
|
|
73
|
+
raise ToolError(f"cannot save as {key}: {e}")
|
|
74
|
+
return buf.getvalue()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _result(data: bytes, key: str, stem: str) -> FileResult:
|
|
78
|
+
_, mime, ext = _FORMATS[key]
|
|
79
|
+
return FileResult(data, f"{stem}.{ext}", mime)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@tool("image-convert", "Image Convert", G)
|
|
83
|
+
def image_convert(data: bytes, to: Literal["png", "jpg", "webp", "bmp", "gif"] = "png", quality: int = 90) -> FileResult:
|
|
84
|
+
"""Convert an image to PNG, JPG, WebP, BMP or GIF (animated images keep only the first frame)."""
|
|
85
|
+
_check_quality(quality)
|
|
86
|
+
img, _ = _open(data)
|
|
87
|
+
return _result(_encode(img, to, quality), to, "converted")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@tool("image-resize", "Image Resize", G)
|
|
91
|
+
def image_resize(data: bytes, width: int = 0, height: int = 0, scale: int = 0, exact: bool = False) -> FileResult:
|
|
92
|
+
"""Resize by width, height, or percent `scale`. Width+height fits inside the box (aspect kept) unless `exact`."""
|
|
93
|
+
Image, _ = _pil()
|
|
94
|
+
if min(width, height, scale) < 0:
|
|
95
|
+
raise ToolError("values cannot be negative")
|
|
96
|
+
if not (width or height or scale):
|
|
97
|
+
raise ToolError("give a width, a height, or a scale (percent), e.g. --width 800")
|
|
98
|
+
if scale and (width or height):
|
|
99
|
+
raise ToolError("use either scale or width/height, not both")
|
|
100
|
+
img, key = _open(data)
|
|
101
|
+
w0, h0 = img.size
|
|
102
|
+
if scale:
|
|
103
|
+
w, h = round(w0 * scale / 100), round(h0 * scale / 100)
|
|
104
|
+
elif width and height:
|
|
105
|
+
if exact:
|
|
106
|
+
w, h = width, height
|
|
107
|
+
else:
|
|
108
|
+
ratio = min(width / w0, height / h0)
|
|
109
|
+
w, h = round(w0 * ratio), round(h0 * ratio)
|
|
110
|
+
elif width:
|
|
111
|
+
w, h = width, round(h0 * width / w0)
|
|
112
|
+
else:
|
|
113
|
+
w, h = round(w0 * height / h0), height
|
|
114
|
+
w, h = max(w, 1), max(h, 1)
|
|
115
|
+
if max(w, h) > MAX_SIDE:
|
|
116
|
+
raise ToolError(f"result would be {w}x{h}; the limit is {MAX_SIDE}px per side")
|
|
117
|
+
resample = getattr(getattr(Image, "Resampling", Image), "LANCZOS")
|
|
118
|
+
return _result(_encode(img.resize((w, h), resample), key), key, "resized")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@tool("image-compress", "Image Compress", G)
|
|
122
|
+
def image_compress(data: bytes, quality: int = 70, max_width: int = 0) -> FileResult:
|
|
123
|
+
"""Shrink file size (JPG/WebP use `quality`; PNG is optimised losslessly). Optionally cap the width."""
|
|
124
|
+
Image, _ = _pil()
|
|
125
|
+
_check_quality(quality)
|
|
126
|
+
img, key = _open(data)
|
|
127
|
+
resized = False
|
|
128
|
+
if max_width and img.width > max_width:
|
|
129
|
+
h = max(round(img.height * max_width / img.width), 1)
|
|
130
|
+
img = img.resize((max_width, h), getattr(getattr(Image, "Resampling", Image), "LANCZOS"))
|
|
131
|
+
resized = True
|
|
132
|
+
out = _encode(img, key, quality)
|
|
133
|
+
if len(out) >= len(data) and not resized:
|
|
134
|
+
out = data # could not improve; keep the original bytes
|
|
135
|
+
return _result(out, key, "compressed")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@tool("image-info", "Image Info", G)
|
|
139
|
+
def image_info(data: bytes) -> str:
|
|
140
|
+
"""Show an image's format, dimensions, colour mode and file size."""
|
|
141
|
+
Image, _ = _pil()
|
|
142
|
+
try:
|
|
143
|
+
img = Image.open(io.BytesIO(data))
|
|
144
|
+
fmt, size, mode = img.format, img.size, img.mode
|
|
145
|
+
frames = getattr(img, "n_frames", 1)
|
|
146
|
+
except Exception as e:
|
|
147
|
+
raise ToolError(f"cannot read image: {e}")
|
|
148
|
+
lines = [f"format: {fmt}", f"size: {size[0]} x {size[1]} px", f"mode: {mode}", f"file size: {len(data):,} bytes"]
|
|
149
|
+
if frames > 1:
|
|
150
|
+
lines.append(f"frames: {frames}")
|
|
151
|
+
return "\n".join(lines)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@tool("image-to-pdf", "Images → PDF", G)
|
|
155
|
+
def image_to_pdf(files: List[bytes]) -> FileResult:
|
|
156
|
+
"""Combine one or more images into a single PDF (one image per page, in the order given)."""
|
|
157
|
+
pages = [_flatten(_open(f)[0]) for f in files]
|
|
158
|
+
buf = io.BytesIO()
|
|
159
|
+
try:
|
|
160
|
+
pages[0].save(buf, "PDF", save_all=True, append_images=pages[1:], resolution=100.0)
|
|
161
|
+
except Exception as e:
|
|
162
|
+
raise ToolError(f"cannot build PDF: {e}")
|
|
163
|
+
return FileResult(buf.getvalue(), "images.pdf", "application/pdf")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from ..registry import ToolError, tool
|
|
4
|
+
|
|
5
|
+
G = "JSON"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _load(text: str):
|
|
9
|
+
try:
|
|
10
|
+
return json.loads(text)
|
|
11
|
+
except json.JSONDecodeError as e:
|
|
12
|
+
raise ToolError(f"invalid JSON: {e}")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@tool("json-format", "JSON Format", G)
|
|
16
|
+
def json_format(text: str, indent: int = 2, sort_keys: bool = False) -> str:
|
|
17
|
+
"""Validate and pretty-print JSON."""
|
|
18
|
+
return json.dumps(_load(text), indent=indent, sort_keys=sort_keys, ensure_ascii=False)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@tool("json-minify", "JSON Minify", G)
|
|
22
|
+
def json_minify(text: str) -> str:
|
|
23
|
+
"""Validate and compact JSON onto one line."""
|
|
24
|
+
return json.dumps(_load(text), separators=(",", ":"), ensure_ascii=False)
|
simplutils/tools/jwt.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import json
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
|
|
5
|
+
from ..registry import ToolError, tool
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _part(s: str) -> dict:
|
|
9
|
+
s += "=" * (-len(s) % 4)
|
|
10
|
+
try:
|
|
11
|
+
return json.loads(base64.urlsafe_b64decode(s))
|
|
12
|
+
except Exception as e:
|
|
13
|
+
raise ToolError(f"invalid JWT segment: {e}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@tool("jwt-decode", "JWT Decode", "Security")
|
|
17
|
+
def jwt_decode(text: str) -> str:
|
|
18
|
+
"""Decode a JWT's header and payload (signature is NOT verified)."""
|
|
19
|
+
parts = text.strip().split(".")
|
|
20
|
+
if len(parts) != 3:
|
|
21
|
+
raise ToolError("a JWT has 3 dot-separated parts")
|
|
22
|
+
header, payload = _part(parts[0]), _part(parts[1])
|
|
23
|
+
out = {"header": header, "payload": payload}
|
|
24
|
+
now = datetime.now(timezone.utc).timestamp()
|
|
25
|
+
for claim in ("iat", "nbf", "exp"):
|
|
26
|
+
v = payload.get(claim)
|
|
27
|
+
if isinstance(v, (int, float)):
|
|
28
|
+
out.setdefault("times", {})[claim] = datetime.fromtimestamp(v, timezone.utc).isoformat()
|
|
29
|
+
exp = payload.get("exp")
|
|
30
|
+
if isinstance(exp, (int, float)):
|
|
31
|
+
out["expired"] = exp < now
|
|
32
|
+
return json.dumps(out, indent=2, ensure_ascii=False)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Search a map (JSON object/list, or YAML) without writing a snippet: find, count, get, tally."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from typing import Any, Callable, Iterator, List, Literal, Tuple
|
|
6
|
+
|
|
7
|
+
from ..registry import ToolError, tool
|
|
8
|
+
|
|
9
|
+
G = "Data"
|
|
10
|
+
|
|
11
|
+
_PATH_TOKEN = re.compile(r'\["((?:[^"\\]|\\.)*)"\]|\[(-?\d+|\*)\]|([^.\[\]]+)')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load(text: Any) -> Any:
|
|
15
|
+
if isinstance(text, (dict, list)): # library use: pass your dict/list directly
|
|
16
|
+
return text
|
|
17
|
+
try:
|
|
18
|
+
data = json.loads(text)
|
|
19
|
+
except json.JSONDecodeError as json_err:
|
|
20
|
+
try:
|
|
21
|
+
import yaml
|
|
22
|
+
except ImportError:
|
|
23
|
+
raise ToolError(f"input is not valid JSON ({json_err}). "
|
|
24
|
+
"To also read YAML: pip install \"simplutils[extras]\"")
|
|
25
|
+
try:
|
|
26
|
+
data = yaml.safe_load(text)
|
|
27
|
+
except yaml.YAMLError as e:
|
|
28
|
+
raise ToolError(f"input is neither valid JSON nor valid YAML: {e}")
|
|
29
|
+
except RecursionError:
|
|
30
|
+
raise ToolError("input is nested too deeply")
|
|
31
|
+
if not isinstance(data, (dict, list)):
|
|
32
|
+
raise ToolError("input must be a JSON object or list (a map to search in)")
|
|
33
|
+
return data
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _fmt_key(path: str, key: Any) -> str:
|
|
37
|
+
k = str(key)
|
|
38
|
+
if any(c in k for c in '.[]"') or k == "" or k == "*":
|
|
39
|
+
return f"{path}[{json.dumps(k, ensure_ascii=False)}]"
|
|
40
|
+
return f"{path}.{k}" if path else k
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _walk(node: Any, path: str = "") -> Iterator[Tuple[str, Any, Any, bool]]:
|
|
44
|
+
"""Yield (path, key, value, is_leaf) for every entry, in one pass (iterative, no recursion limit)."""
|
|
45
|
+
stack: List[Tuple[Any, str]] = [(node, path)]
|
|
46
|
+
while stack:
|
|
47
|
+
cur, p = stack.pop()
|
|
48
|
+
if isinstance(cur, dict):
|
|
49
|
+
items = [(k, v, _fmt_key(p, k)) for k, v in cur.items()]
|
|
50
|
+
elif isinstance(cur, list):
|
|
51
|
+
items = [(i, v, f"{p}[{i}]") for i, v in enumerate(cur)]
|
|
52
|
+
else:
|
|
53
|
+
continue
|
|
54
|
+
for k, v, kp in items:
|
|
55
|
+
leaf = not isinstance(v, (dict, list))
|
|
56
|
+
yield kp, k, v, leaf
|
|
57
|
+
stack.extend((v, kp) for k, v, kp in reversed(items) if isinstance(v, (dict, list)))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _text(v: Any) -> str:
|
|
61
|
+
return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _short(v: Any, n: int = 80) -> str:
|
|
65
|
+
s = json.dumps(v, ensure_ascii=False)
|
|
66
|
+
return s if len(s) <= n else s[: n - 3] + "..."
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _matcher(query: str, mode: str, ignore_case: bool) -> Callable[[str], bool]:
|
|
70
|
+
if mode == "regex":
|
|
71
|
+
try:
|
|
72
|
+
rx = re.compile(query, re.IGNORECASE if ignore_case else 0)
|
|
73
|
+
except re.error as e:
|
|
74
|
+
raise ToolError(f"invalid regex: {e}")
|
|
75
|
+
return lambda s: rx.search(s) is not None
|
|
76
|
+
q = query.lower() if ignore_case else query
|
|
77
|
+
norm = (lambda s: s.lower()) if ignore_case else (lambda s: s)
|
|
78
|
+
if mode == "contains":
|
|
79
|
+
return lambda s: q in norm(s)
|
|
80
|
+
return lambda s: norm(s) == q
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _get(node: Any, path: str) -> List[Any]:
|
|
84
|
+
tokens = []
|
|
85
|
+
pos = 0
|
|
86
|
+
path = path.strip()
|
|
87
|
+
while pos < len(path):
|
|
88
|
+
if path[pos] == ".":
|
|
89
|
+
pos += 1
|
|
90
|
+
continue
|
|
91
|
+
m = _PATH_TOKEN.match(path, pos)
|
|
92
|
+
if not m:
|
|
93
|
+
raise ToolError(f"cannot read the path near '{path[pos:]}'. Example: users[0].name or users[*].email")
|
|
94
|
+
quoted, index, name = m.groups()
|
|
95
|
+
if quoted is not None:
|
|
96
|
+
tokens.append(("key", json.loads(f'"{quoted}"')))
|
|
97
|
+
elif index is not None:
|
|
98
|
+
tokens.append(("star", None) if index == "*" else ("index", int(index)))
|
|
99
|
+
else:
|
|
100
|
+
tokens.append(("star", None) if name == "*" else ("key", name))
|
|
101
|
+
pos = m.end()
|
|
102
|
+
if not tokens:
|
|
103
|
+
raise ToolError("give a path, e.g. users[0].name")
|
|
104
|
+
current = [(node, "")]
|
|
105
|
+
for kind, val in tokens:
|
|
106
|
+
nxt = []
|
|
107
|
+
for n, p in current:
|
|
108
|
+
if kind == "star":
|
|
109
|
+
if isinstance(n, dict):
|
|
110
|
+
nxt.extend((v, _fmt_key(p, k)) for k, v in n.items())
|
|
111
|
+
elif isinstance(n, list):
|
|
112
|
+
nxt.extend((v, f"{p}[{i}]") for i, v in enumerate(n))
|
|
113
|
+
elif kind == "index":
|
|
114
|
+
if isinstance(n, list) and -len(n) <= val < len(n):
|
|
115
|
+
nxt.append((n[val], f"{p}[{val}]"))
|
|
116
|
+
else:
|
|
117
|
+
if isinstance(n, dict) and val in n:
|
|
118
|
+
nxt.append((n[val], _fmt_key(p, val)))
|
|
119
|
+
elif isinstance(n, list) and val.lstrip("-").isdigit() and -len(n) <= int(val) < len(n):
|
|
120
|
+
nxt.append((n[int(val)], f"{p}[{int(val)}]"))
|
|
121
|
+
if not nxt:
|
|
122
|
+
raise ToolError(f"nothing found at '{path}' (stopped at '{val if kind != 'star' else '*'}')")
|
|
123
|
+
current = nxt
|
|
124
|
+
return [v for v, _ in current]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@tool("map-search", "Map Search", G)
|
|
128
|
+
def map_search(
|
|
129
|
+
text: str,
|
|
130
|
+
action: Literal["find", "count", "get", "tally"] = "find",
|
|
131
|
+
by: Literal["key", "value"] = "key",
|
|
132
|
+
query: str = "",
|
|
133
|
+
match: Literal["exact", "contains", "regex"] = "exact",
|
|
134
|
+
ignore_case: bool = False,
|
|
135
|
+
limit: int = 100,
|
|
136
|
+
) -> str:
|
|
137
|
+
"""Search a JSON/YAML map: find or count keys/values, get a value by path, tally values of a key."""
|
|
138
|
+
if not query:
|
|
139
|
+
raise ToolError("tell me what to look for: query (a key or value to search; for 'get' a path like a.b[0].c)")
|
|
140
|
+
if limit < 1:
|
|
141
|
+
raise ToolError("limit must be at least 1")
|
|
142
|
+
data = _load(text)
|
|
143
|
+
|
|
144
|
+
if action == "get":
|
|
145
|
+
found = _get(data, query)
|
|
146
|
+
return json.dumps(found[0] if len(found) == 1 and "*" not in query else found,
|
|
147
|
+
indent=2, ensure_ascii=False)
|
|
148
|
+
|
|
149
|
+
is_match = _matcher(query, match, ignore_case)
|
|
150
|
+
if action == "tally" and by != "key":
|
|
151
|
+
raise ToolError("tally counts the values of a key, so use by=key (e.g. query=city)")
|
|
152
|
+
|
|
153
|
+
hits: List[Tuple[str, Any]] = [] # (path, value)
|
|
154
|
+
for path, key, value, leaf in _walk(data):
|
|
155
|
+
if by == "key":
|
|
156
|
+
if is_match(str(key)):
|
|
157
|
+
hits.append((path, value))
|
|
158
|
+
elif leaf and is_match(_text(value)):
|
|
159
|
+
hits.append((path, value))
|
|
160
|
+
|
|
161
|
+
what = "keys" if by == "key" else "values"
|
|
162
|
+
if action == "count":
|
|
163
|
+
return str(len(hits))
|
|
164
|
+
if not hits:
|
|
165
|
+
return "No matches."
|
|
166
|
+
if action == "tally":
|
|
167
|
+
counts = Counter(json.dumps(v, sort_keys=True, ensure_ascii=False) for _, v in hits)
|
|
168
|
+
rows = counts.most_common(limit)
|
|
169
|
+
width = max(len(r[0]) for r in rows)
|
|
170
|
+
out = [f"{v:<{width}} {n}" for v, n in rows]
|
|
171
|
+
if len(counts) > limit:
|
|
172
|
+
out.append(f"... and {len(counts) - limit} more distinct values")
|
|
173
|
+
return f"{len(hits)} match(es) across {len(counts)} distinct value(s)\n" + "\n".join(out)
|
|
174
|
+
|
|
175
|
+
shown = [f"{p}: {_short(v)}" for p, v in hits[:limit]]
|
|
176
|
+
if len(hits) > limit:
|
|
177
|
+
shown.append(f"... and {len(hits) - limit} more (raise limit to see them)")
|
|
178
|
+
return f"{len(hits)} matching {what}\n" + "\n".join(shown)
|
simplutils/tools/pdfs.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""PDF tools (need pypdf: pip install simplutils[files])."""
|
|
2
|
+
import io
|
|
3
|
+
import zipfile
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
from ..registry import FileResult, ToolError, tool
|
|
7
|
+
|
|
8
|
+
G = "PDF"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _pypdf():
|
|
12
|
+
try:
|
|
13
|
+
import pypdf
|
|
14
|
+
except ImportError:
|
|
15
|
+
raise ToolError("this tool needs pypdf: pip install simplutils[files]")
|
|
16
|
+
return pypdf
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _reader(data: bytes):
|
|
20
|
+
pypdf = _pypdf()
|
|
21
|
+
if b"%PDF-" not in data[:1024]:
|
|
22
|
+
raise ToolError("this does not look like a PDF file")
|
|
23
|
+
try:
|
|
24
|
+
r = pypdf.PdfReader(io.BytesIO(data))
|
|
25
|
+
if r.is_encrypted and r.decrypt("") == 0:
|
|
26
|
+
raise ToolError("the PDF is password-protected")
|
|
27
|
+
len(r.pages) # force parsing now so errors surface here
|
|
28
|
+
return r
|
|
29
|
+
except ToolError:
|
|
30
|
+
raise
|
|
31
|
+
except Exception as e:
|
|
32
|
+
raise ToolError(f"cannot read PDF: {e}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_pages(spec: str, total: int) -> List[int]:
|
|
36
|
+
"""'1-3,5,8-' -> 0-based page indexes (order and repeats kept). 1-based input."""
|
|
37
|
+
out: List[int] = []
|
|
38
|
+
for part in spec.replace(" ", "").split(","):
|
|
39
|
+
if not part:
|
|
40
|
+
continue
|
|
41
|
+
try:
|
|
42
|
+
if "-" in part:
|
|
43
|
+
a, b = part.split("-", 1)
|
|
44
|
+
start, end = int(a) if a else 1, int(b) if b else total
|
|
45
|
+
else:
|
|
46
|
+
start = end = int(part)
|
|
47
|
+
except ValueError:
|
|
48
|
+
raise ToolError(f"bad page range: '{part}' (use e.g. 1-3,5,8-)")
|
|
49
|
+
if start < 1 or end > total or start > end:
|
|
50
|
+
raise ToolError(f"pages must be between 1 and {total} (got '{part}')")
|
|
51
|
+
out.extend(range(start - 1, end))
|
|
52
|
+
if not out:
|
|
53
|
+
raise ToolError("no pages selected")
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _write(writer) -> bytes:
|
|
58
|
+
buf = io.BytesIO()
|
|
59
|
+
writer.write(buf)
|
|
60
|
+
return buf.getvalue()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@tool("pdf-merge", "PDF Merge", G)
|
|
64
|
+
def pdf_merge(files: List[bytes]) -> FileResult:
|
|
65
|
+
"""Merge two or more PDFs into one, in the order given."""
|
|
66
|
+
if len(files) < 2:
|
|
67
|
+
raise ToolError("give at least two PDFs to merge")
|
|
68
|
+
writer = _pypdf().PdfWriter()
|
|
69
|
+
for f in files:
|
|
70
|
+
for page in _reader(f).pages:
|
|
71
|
+
writer.add_page(page)
|
|
72
|
+
return FileResult(_write(writer), "merged.pdf", "application/pdf")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@tool("pdf-extract", "PDF Extract Pages", G)
|
|
76
|
+
def pdf_extract(data: bytes, pages: str) -> FileResult:
|
|
77
|
+
"""Keep only the given pages, e.g. --pages 1-3,5,8- (order and repeats are respected)."""
|
|
78
|
+
r = _reader(data)
|
|
79
|
+
writer = _pypdf().PdfWriter()
|
|
80
|
+
for i in parse_pages(pages, len(r.pages)):
|
|
81
|
+
writer.add_page(r.pages[i])
|
|
82
|
+
return FileResult(_write(writer), "extracted.pdf", "application/pdf")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@tool("pdf-split", "PDF Split", G)
|
|
86
|
+
def pdf_split(data: bytes) -> FileResult:
|
|
87
|
+
"""Split a PDF into one file per page, delivered as a ZIP."""
|
|
88
|
+
r = _reader(data)
|
|
89
|
+
n = len(r.pages)
|
|
90
|
+
width = max(len(str(n)), 2)
|
|
91
|
+
pypdf = _pypdf()
|
|
92
|
+
buf = io.BytesIO()
|
|
93
|
+
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
|
94
|
+
for i, page in enumerate(r.pages, 1):
|
|
95
|
+
w = pypdf.PdfWriter()
|
|
96
|
+
w.add_page(page)
|
|
97
|
+
z.writestr(f"page_{i:0{width}d}.pdf", _write(w))
|
|
98
|
+
return FileResult(buf.getvalue(), "split.zip", "application/zip")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@tool("pdf-text", "PDF → Text", G)
|
|
102
|
+
def pdf_text(data: bytes, pages: str = "") -> str:
|
|
103
|
+
"""Extract text from a PDF (all pages, or e.g. --pages 1-3). Scanned PDFs have no text layer."""
|
|
104
|
+
r = _reader(data)
|
|
105
|
+
idx = parse_pages(pages, len(r.pages)) if pages else range(len(r.pages))
|
|
106
|
+
parts = []
|
|
107
|
+
for i in idx:
|
|
108
|
+
try:
|
|
109
|
+
txt = (r.pages[i].extract_text() or "").strip()
|
|
110
|
+
except Exception as e:
|
|
111
|
+
txt = f"(could not extract: {e})"
|
|
112
|
+
parts.append(f"--- page {i + 1} ---\n{txt}")
|
|
113
|
+
out = "\n\n".join(parts)
|
|
114
|
+
if not any(p.split("\n", 1)[1].strip() for p in parts if "\n" in p):
|
|
115
|
+
out += "\n\n(no text found - this may be a scanned PDF)"
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@tool("pdf-info", "PDF Info", G)
|
|
120
|
+
def pdf_info(data: bytes) -> str:
|
|
121
|
+
"""Show page count, page size, title/author and file size."""
|
|
122
|
+
r = _reader(data)
|
|
123
|
+
meta = r.metadata or {}
|
|
124
|
+
first = r.pages[0].mediabox if len(r.pages) else None
|
|
125
|
+
lines = [f"pages: {len(r.pages)}"]
|
|
126
|
+
if first is not None:
|
|
127
|
+
lines.append(f"page size: {float(first.width):.0f} x {float(first.height):.0f} pt")
|
|
128
|
+
lines.append(f"file size: {len(data):,} bytes")
|
|
129
|
+
lines.append(f"encrypted: {'yes' if r.is_encrypted else 'no'}")
|
|
130
|
+
for key, label in (("/Title", "title"), ("/Author", "author"), ("/Producer", "producer")):
|
|
131
|
+
if meta.get(key):
|
|
132
|
+
lines.append(f"{label}: {meta.get(key)}")
|
|
133
|
+
return "\n".join(lines)
|