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 ADDED
@@ -0,0 +1,34 @@
1
+ """simplutils - all-in-one developer utilities.
2
+
3
+ Use as a library: from simplutils import b64_encode; b64_encode("hi")
4
+ Use as a CLI: simplutils b64-encode "hi"
5
+ Use as a local UI: simplutils ui (pip install simplutils[ui])
6
+ """
7
+ from .registry import TOOLS, FileResult, Tool, ToolError, groups, load_all
8
+
9
+ load_all()
10
+
11
+ from .tools.ai import ai_classify, ai_extract_json, ai_summarize # noqa: E402
12
+ from .tools.encoding import ( # noqa: E402
13
+ b64_decode, b64_encode, hex_decode, hex_encode,
14
+ html_escape, html_unescape, url_decode, url_encode,
15
+ )
16
+ from .tools.files import b64_to_image, b64_to_pdf, image_to_b64, pdf_to_b64 # noqa: E402
17
+ from .tools.convert import csv_to_json, json_to_csv, json_to_yaml, yaml_to_json # noqa: E402
18
+ from .tools.diff import json_diff, text_diff # noqa: E402
19
+ from .tools.pii import pii_redact, pii_scan, pii_types # noqa: E402
20
+ from .tools.qr import qr_generate, qr_text # noqa: E402
21
+ from .tools.regex import regex_replace, regex_test # noqa: E402
22
+ from .tools.generators import password, random_text, uuid_gen # noqa: E402
23
+ from .tools.mapsearch import map_search # noqa: E402
24
+ from .tools.hashing import hash_text, hmac_text # noqa: E402
25
+ from .tools.images import ( # noqa: E402
26
+ image_compress, image_convert, image_info, image_resize, image_to_pdf,
27
+ )
28
+ from .tools.pdfs import pdf_extract, pdf_info, pdf_merge, pdf_split, pdf_text # noqa: E402
29
+ from .tools.jsontools import json_format, json_minify # noqa: E402
30
+ from .tools.jwt import jwt_decode # noqa: E402
31
+ from .tools.text import case_convert, count, slugify # noqa: E402
32
+ from .tools.timetools import date_to_ts, now, ts_to_date # noqa: E402
33
+
34
+ __version__ = "0.1.0"
simplutils/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
simplutils/cli.py ADDED
@@ -0,0 +1,187 @@
1
+ """Command line interface, generated from the tool registry."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import difflib
6
+ import re
7
+ import sys
8
+ from typing import List, Optional
9
+
10
+ from . import __version__
11
+ from .logs import log_path, setup_logging, tail
12
+ from .registry import FileResult, Tool, ToolError, groups, load_all
13
+ from .textio import decode_text, read_text_file
14
+
15
+ TIP = "Tip: run 'simplutils' with no arguments for a step-by-step menu."
16
+
17
+
18
+ class _Parser(argparse.ArgumentParser):
19
+ """Friendlier errors: suggest the closest command/choice instead of dumping a huge list."""
20
+
21
+ def error(self, message: str):
22
+ m = re.search(
23
+ r"invalid choice: '?(.*?)'?(?:, maybe you meant .*?)? \(choose from (.*)\)",
24
+ message,
25
+ )
26
+ if m:
27
+ bad = m.group(1)
28
+ choices = [c.strip().strip("'") for c in m.group(2).split(",")]
29
+ close = difflib.get_close_matches(bad, choices, n=3, cutoff=0.5)
30
+ msg = f"unknown choice '{bad}'."
31
+ if close:
32
+ msg += " Did you mean: " + ", ".join(close) + "?"
33
+ elif len(choices) <= 8:
34
+ msg += " Choose from: " + ", ".join(choices) + "."
35
+ if self.prog == "simplutils":
36
+ msg += " See all tools with: simplutils list"
37
+ self.exit(2, f"{self.prog}: error: {msg}\n")
38
+ super().error(message)
39
+
40
+
41
+ def _add_tool(sub, t: Tool) -> None:
42
+ sp = sub.add_parser(t.name, help=t.description, description=t.description)
43
+ if t.input_kind == "text":
44
+ sp.add_argument("text", nargs="?", help="input text (omit to read stdin)")
45
+ sp.add_argument("-f", "--file", help="read input text from a file")
46
+ elif t.input_kind == "file":
47
+ sp.add_argument("path", help="input file path ('-' reads binary stdin)")
48
+ elif t.input_kind == "files":
49
+ sp.add_argument("paths", nargs="+", metavar="path", help="input file paths, in order")
50
+ sp.add_argument("-o", "--output", help="save the result to this file instead of printing it")
51
+ for p in t.params:
52
+ flag = "--" + p.name.replace("_", "-")
53
+ if p.type is bool:
54
+ sp.add_argument(flag, action="store_true", dest=p.name)
55
+ else:
56
+ sp.add_argument(
57
+ flag, dest=p.name, type=p.type, choices=p.choices,
58
+ required=p.required, default=None if p.required else p.default,
59
+ help=None if p.required else f"(default: {p.default})",
60
+ )
61
+
62
+
63
+ def build_parser() -> argparse.ArgumentParser:
64
+ parser = _Parser(prog="simplutils", description="All-in-one developer utilities.", epilog=TIP)
65
+ parser.add_argument("--version", action="version", version=f"simplutils {__version__}")
66
+ parser.add_argument("-v", "--verbose", action="store_true", help="also print log messages to the screen")
67
+ sub = parser.add_subparsers(dest="command", metavar="<tool>")
68
+ sub.add_parser("menu", help="step-by-step interactive menu (same as running with no arguments)")
69
+ lst = sub.add_parser("list", help="list all tools (optionally filter by a word)")
70
+ lst.add_argument("query", nargs="?", help="e.g. pdf, base64, image")
71
+ lg = sub.add_parser("logs", help="show the most recent log lines")
72
+ lg.add_argument("-n", type=int, default=20, help="how many lines (default 20)")
73
+ lg.add_argument("--path", action="store_true", help="only print the log file location")
74
+ ui = sub.add_parser("ui", help="launch the local web UI (needs simplutils[ui])")
75
+ ui.add_argument("--port", type=int, default=8080)
76
+ ui.add_argument("--no-browser", action="store_true")
77
+ for t in load_all().values():
78
+ _add_tool(sub, t)
79
+ return parser
80
+
81
+
82
+ def _read_input(t: Tool, args: argparse.Namespace):
83
+ try:
84
+ if t.input_kind == "file":
85
+ if args.path == "-":
86
+ return sys.stdin.buffer.read()
87
+ with open(args.path, "rb") as fh:
88
+ return fh.read()
89
+ if t.input_kind == "files":
90
+ out = []
91
+ for p in args.paths:
92
+ with open(p, "rb") as fh:
93
+ out.append(fh.read())
94
+ return out
95
+ if args.text is not None:
96
+ return args.text
97
+ if args.file:
98
+ return read_text_file(args.file)
99
+ except OSError as e:
100
+ raise ToolError(f"cannot read input: {e}")
101
+ if not sys.stdin.isatty():
102
+ buffer = getattr(sys.stdin, "buffer", None)
103
+ text = decode_text(buffer.read()) if buffer is not None else sys.stdin.read()
104
+ return text.rstrip("\r\n")
105
+ raise ToolError("no input: pass text, --file, or pipe via stdin")
106
+
107
+
108
+ def _emit(result, output: Optional[str]) -> None:
109
+ try:
110
+ if isinstance(result, FileResult):
111
+ path = output or result.filename
112
+ with open(path, "wb") as fh:
113
+ fh.write(result.data)
114
+ print(f"saved {len(result.data)} bytes to {path}")
115
+ elif output:
116
+ with open(output, "w", encoding="utf-8") as fh:
117
+ fh.write(result)
118
+ print(f"saved {len(result)} characters to {output}")
119
+ else:
120
+ print(result)
121
+ except OSError as e:
122
+ raise ToolError(f"cannot write output: {e}")
123
+
124
+
125
+ def _print_list(query: Optional[str]) -> None:
126
+ q = (query or "").lower()
127
+ found = False
128
+ for group, tools in groups().items():
129
+ rows = [t for t in tools if not q or q in t.name or q in t.title.lower() or q in t.description.lower()]
130
+ if rows:
131
+ found = True
132
+ print(f"\n{group}")
133
+ for t in rows:
134
+ print(f" {t.name:<15} {t.description}")
135
+ if not found:
136
+ print(f"No tools match '{query}'. Run 'simplutils list' to see everything.")
137
+ print(f"\n{TIP}\nDetails for any tool: simplutils <tool> -h")
138
+
139
+
140
+ def main(argv: Optional[List[str]] = None) -> int:
141
+ for stream in (sys.stdout, sys.stderr, sys.stdin): # Windows consoles default to cp1252
142
+ if hasattr(stream, "reconfigure"):
143
+ stream.reconfigure(encoding="utf-8")
144
+ parser = build_parser()
145
+ args = parser.parse_args(argv)
146
+ setup_logging(verbose=args.verbose)
147
+
148
+ if args.command is None:
149
+ if argv is None and sys.stdin.isatty() and sys.stdout.isatty():
150
+ from .interactive import start
151
+ return start()
152
+ parser.print_help()
153
+ return 0
154
+ if args.command == "menu":
155
+ from .interactive import start
156
+ return start()
157
+ if args.command == "list":
158
+ _print_list(args.query)
159
+ return 0
160
+ if args.command == "logs":
161
+ if args.path:
162
+ print(log_path())
163
+ return 0
164
+ lines = tail(args.n)
165
+ print("\n".join(lines) if lines else f"(no log entries yet; log file: {log_path()})")
166
+ return 0
167
+ if args.command == "ui":
168
+ try:
169
+ from .ui import run
170
+ except ImportError:
171
+ print("The UI needs extra dependencies: pip install simplutils[ui]", file=sys.stderr)
172
+ return 1
173
+ run(port=args.port, show=not args.no_browser)
174
+ return 0
175
+
176
+ t = load_all()[args.command]
177
+ try:
178
+ options = {p.name: getattr(args, p.name) for p in t.params}
179
+ result = t.run(_read_input(t, args) if t.needs_input else None, **options)
180
+ _emit(result, args.output)
181
+ except ToolError as e:
182
+ print(f"error: {e}", file=sys.stderr)
183
+ return 1
184
+ except Exception as e: # tool bug: the traceback is in the log, keep the screen readable
185
+ print(f"error: unexpected failure ({type(e).__name__}: {e}). Details: {log_path()}", file=sys.stderr)
186
+ return 1
187
+ return 0
@@ -0,0 +1,195 @@
1
+ """Interactive menu: run `simplutils` with no arguments. Pick a tool, answer the prompts. No flags to remember."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ from .registry import FileResult, Param, Tool, ToolError, groups, load_all
8
+ from .textio import read_text_file
9
+
10
+ HELP = (
11
+ "Type a number to pick a tool, or a word to search (e.g. 'pdf', 'base64').\n"
12
+ " q = quit, ? = show this help"
13
+ )
14
+
15
+
16
+ def _clean_path(raw: str) -> str:
17
+ return raw.strip().strip('"').strip("'") # drag & drop adds quotes
18
+
19
+
20
+ class Menu:
21
+ def __init__(self, ask: Optional[Callable[[str], str]] = None, say: Optional[Callable[..., None]] = None):
22
+ # Resolve input/print at call time (not import time) so they can be swapped out.
23
+ self.ask = ask or (lambda prompt="": input(prompt))
24
+ self.say = say or (lambda *a, **k: print(*a, **k))
25
+ self.numbered: List[Tool] = []
26
+ for tools in groups().values():
27
+ self.numbered.extend(tools)
28
+
29
+ # ---- screens -------------------------------------------------------
30
+ def show_tools(self, only: Optional[List[Tool]] = None) -> None:
31
+ shown = only if only is not None else self.numbered
32
+ current = None
33
+ for t in shown:
34
+ if t.group != current:
35
+ current = t.group
36
+ self.say(f"\n {current}")
37
+ self.say(f" {self.numbered.index(t) + 1:>2}. {t.title:<22} {t.description}")
38
+ self.say("")
39
+
40
+ def pick_tool(self) -> Optional[Tool]:
41
+ self.show_tools()
42
+ self.say(HELP)
43
+ while True:
44
+ choice = self.ask("\nTool> ").strip()
45
+ if not choice:
46
+ continue
47
+ low = choice.lower()
48
+ if low in ("q", "quit", "exit"):
49
+ return None
50
+ if low == "?":
51
+ self.show_tools()
52
+ self.say(HELP)
53
+ continue
54
+ if choice.isdigit():
55
+ n = int(choice)
56
+ if 1 <= n <= len(self.numbered):
57
+ return self.numbered[n - 1]
58
+ self.say(f" Please pick 1-{len(self.numbered)}.")
59
+ continue
60
+ matches = [t for t in self.numbered
61
+ if low in t.name or low in t.title.lower() or low in t.description.lower()]
62
+ if not matches:
63
+ self.say(f" Nothing matches '{choice}'. Type ? to see everything.")
64
+ elif len(matches) == 1:
65
+ return matches[0]
66
+ else:
67
+ self.say(f" {len(matches)} matches - type the number:")
68
+ self.show_tools(matches)
69
+
70
+ # ---- prompts -------------------------------------------------------
71
+ def _read_text(self) -> str:
72
+ self.say("Enter the text. Type @path to load it from a file, or << for multi-line input.")
73
+ first = self.ask("Text> ")
74
+ if first.strip().startswith("@"):
75
+ return self._read_file_text(_clean_path(first.strip()[1:]))
76
+ if first.strip() == "<<":
77
+ self.say("(paste your text, then finish with an empty line)")
78
+ lines: List[str] = []
79
+ while True:
80
+ line = self.ask("")
81
+ if line == "":
82
+ break
83
+ lines.append(line)
84
+ return "\n".join(lines)
85
+ return first
86
+
87
+ def _read_file_text(self, path: str) -> str:
88
+ return read_text_file(path)
89
+
90
+ def _read_file_bytes(self, path: str) -> bytes:
91
+ path = _clean_path(path)
92
+ try:
93
+ with open(path, "rb") as fh:
94
+ return fh.read()
95
+ except OSError as e:
96
+ raise ToolError(f"cannot read '{path}': {e}")
97
+
98
+ def _read_input(self, t: Tool) -> Any:
99
+ if t.input_kind == "text":
100
+ return self._read_text()
101
+ if t.input_kind == "file":
102
+ return self._read_file_bytes(self.ask("File path (you can drag the file into this window)> "))
103
+ if t.input_kind == "files":
104
+ self.say("Enter file paths one per line, in order. Press Enter on an empty line when done.")
105
+ out: List[bytes] = []
106
+ while True:
107
+ p = self.ask(f"File {len(out) + 1}> ").strip()
108
+ if not p:
109
+ break
110
+ out.append(self._read_file_bytes(p))
111
+ return out
112
+ return None
113
+
114
+ def _ask_option(self, p: Param) -> Any:
115
+ label = p.name.replace("_", " ")
116
+ if p.choices:
117
+ opts = ", ".join(str(c) for c in p.choices)
118
+ while True:
119
+ ans = self.ask(f"{label} [{opts}] (Enter = {p.default}): ").strip()
120
+ if not ans:
121
+ return None if p.required else p.default
122
+ if ans in [str(c) for c in p.choices]:
123
+ return type(p.choices[0])(ans)
124
+ self.say(f" Choose one of: {opts}")
125
+ if p.type is bool:
126
+ return self.ask(f"{label}? [y/N]: ").strip().lower() in ("y", "yes")
127
+ suffix = "" if p.required else f" (Enter = {p.default!r})"
128
+ while True:
129
+ ans = self.ask(f"{label}{suffix}: ").strip()
130
+ if not ans:
131
+ if p.required:
132
+ self.say(" This one is required.")
133
+ continue
134
+ return p.default
135
+ if p.type is int:
136
+ try:
137
+ return int(ans)
138
+ except ValueError:
139
+ self.say(" Please enter a whole number.")
140
+ continue
141
+ return ans
142
+
143
+ # ---- main flow -----------------------------------------------------
144
+ def run_tool(self, t: Tool) -> None:
145
+ self.say(f"\n== {t.title} ==\n{t.description}\n")
146
+ data = self._read_input(t)
147
+ options: Dict[str, Any] = {}
148
+ if t.params:
149
+ self.say("\nOptions (just press Enter to accept the default):")
150
+ for p in t.params:
151
+ options[p.name] = self._ask_option(p)
152
+ result = t.run(data, **options)
153
+ self._deliver(result)
154
+
155
+ def _deliver(self, result: Any) -> None:
156
+ if isinstance(result, FileResult):
157
+ default = result.filename
158
+ path = _clean_path(self.ask(f"\nSave as (Enter = {default}): ")) or default
159
+ try:
160
+ with open(path, "wb") as fh:
161
+ fh.write(result.data)
162
+ except OSError as e:
163
+ raise ToolError(f"cannot write '{path}': {e}")
164
+ self.say(f"Saved {len(result.data):,} bytes to {os.path.abspath(path)}")
165
+ return
166
+ self.say("\n" + result + "\n")
167
+ path = _clean_path(self.ask("Save the result to a file? Type a path, or Enter to skip: "))
168
+ if path:
169
+ try:
170
+ with open(path, "w", encoding="utf-8") as fh:
171
+ fh.write(result)
172
+ except OSError as e:
173
+ raise ToolError(f"cannot write '{path}': {e}")
174
+ self.say(f"Saved to {os.path.abspath(path)}")
175
+
176
+ def loop(self) -> int:
177
+ self.say("simplutils - pick what you want to do. (Ctrl+C anytime to quit)")
178
+ try:
179
+ while True:
180
+ t = self.pick_tool()
181
+ if t is None:
182
+ return 0
183
+ try:
184
+ self.run_tool(t)
185
+ except ToolError as e:
186
+ self.say(f"\n Problem: {e}")
187
+ self.ask("\nPress Enter to go back to the menu...")
188
+ except (EOFError, KeyboardInterrupt):
189
+ self.say("\nBye!")
190
+ return 0
191
+
192
+
193
+ def start(ask: Optional[Callable[[str], str]] = None, say: Optional[Callable[..., None]] = None) -> int:
194
+ load_all()
195
+ return Menu(ask, say).loop()
simplutils/logs.py ADDED
@@ -0,0 +1,62 @@
1
+ """Logging setup. Logs go to ~/.simplutils/simplutils.log (override the folder with simplutils_LOG_DIR).
2
+
3
+ Privacy: only tool names, sizes, timings and non-text option values are logged,
4
+ never the content you process.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import os
10
+ import sys
11
+ from logging.handlers import RotatingFileHandler
12
+ from pathlib import Path
13
+ from typing import List
14
+
15
+ LOGGER_NAME = "simplutils"
16
+ _FORMAT = "%(asctime)s %(levelname)-7s %(message)s"
17
+ _MARK = "_simplutils_handler"
18
+
19
+
20
+ def log_dir() -> Path:
21
+ return Path(os.environ.get("simplutils_LOG_DIR") or (Path.home() / ".simplutils"))
22
+
23
+
24
+ def log_path() -> Path:
25
+ return log_dir() / "simplutils.log"
26
+
27
+
28
+ def setup_logging(verbose: bool = False) -> None:
29
+ """Attach a rotating file handler (and a console handler if verbose). Safe to call repeatedly."""
30
+ logger = logging.getLogger(LOGGER_NAME)
31
+ for h in list(logger.handlers):
32
+ if getattr(h, _MARK, False):
33
+ logger.removeHandler(h)
34
+ h.close()
35
+ logger.setLevel(logging.DEBUG)
36
+ logger.propagate = False
37
+
38
+ try:
39
+ log_dir().mkdir(parents=True, exist_ok=True)
40
+ fh = RotatingFileHandler(log_path(), maxBytes=1_000_000, backupCount=3, encoding="utf-8")
41
+ fh.setLevel(logging.INFO)
42
+ fh.setFormatter(logging.Formatter(_FORMAT))
43
+ setattr(fh, _MARK, True)
44
+ logger.addHandler(fh)
45
+ except OSError:
46
+ pass # logging must never break the tool (e.g. read-only home folder)
47
+
48
+ if verbose:
49
+ ch = logging.StreamHandler(sys.stderr)
50
+ ch.setLevel(logging.DEBUG)
51
+ ch.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
52
+ setattr(ch, _MARK, True)
53
+ logger.addHandler(ch)
54
+
55
+
56
+ def tail(n: int = 20) -> List[str]:
57
+ """Return the last n lines of the log file."""
58
+ try:
59
+ with open(log_path(), encoding="utf-8", errors="replace") as fh:
60
+ return fh.read().splitlines()[-n:]
61
+ except OSError:
62
+ return []
simplutils/registry.py ADDED
@@ -0,0 +1,161 @@
1
+ """Tool registry: one decorated function = one tool, usable from Python, CLI and UI.
2
+
3
+ Conventions for a tool function:
4
+ * The first parameter decides the input: ``text`` = free-form text,
5
+ ``data`` = one file (``bytes``), ``files`` = several files (``List[bytes]``);
6
+ no such parameter = no input. Return a ``FileResult`` to produce a
7
+ downloadable/savable file.
8
+ * Every other parameter is an *option*. Supported types: str, int, bool
9
+ (bool options must default to False) and ``Literal[...]`` (a choice list).
10
+ * Return a string (or anything printable).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import inspect
15
+ import logging
16
+ import time
17
+ import typing
18
+ from dataclasses import dataclass
19
+ from typing import Any, Callable, Dict, List, Optional, Tuple
20
+
21
+ REQUIRED = inspect.Parameter.empty
22
+ log = logging.getLogger("simplutils")
23
+ log.addHandler(logging.NullHandler()) # library default: stay silent unless the app configures logging
24
+ _INPUT_KINDS = {"text": "text", "data": "file", "files": "files"}
25
+
26
+
27
+ class ToolError(Exception):
28
+ """Raised by a tool for bad user input (shown without a traceback)."""
29
+
30
+
31
+ @dataclass
32
+ class Param:
33
+ name: str
34
+ type: type
35
+ default: Any
36
+ choices: Optional[Tuple[Any, ...]] = None
37
+
38
+ @property
39
+ def required(self) -> bool:
40
+ return self.default is REQUIRED
41
+
42
+
43
+ @dataclass
44
+ class FileResult:
45
+ """Returned by tools that produce a binary file (the CLI saves it, the UI offers a download)."""
46
+ data: bytes
47
+ filename: str
48
+ mime: str = "application/octet-stream"
49
+
50
+
51
+ @dataclass
52
+ class Tool:
53
+ name: str
54
+ title: str
55
+ group: str
56
+ description: str
57
+ func: Callable[..., Any]
58
+ params: List[Param]
59
+ input_kind: str # "none" | "text" | "file" | "files"
60
+
61
+ @property
62
+ def needs_input(self) -> bool:
63
+ return self.input_kind != "none"
64
+
65
+ def _describe_input(self, data: Any) -> str:
66
+ if self.input_kind == "text":
67
+ return f"{len(data)} chars"
68
+ if self.input_kind == "file":
69
+ return f"{len(data)} bytes"
70
+ if self.input_kind == "files":
71
+ return f"{len(data)} files/{sum(len(d) for d in data)} bytes"
72
+ return "none"
73
+
74
+ def _describe_options(self, kwargs: Dict[str, Any]) -> str:
75
+ # Free-text option values (keys, passwords, ...) are never logged.
76
+ shown = {
77
+ k: (v if _loggable(self, k) else "<hidden>") for k, v in kwargs.items()
78
+ }
79
+ return str(shown)
80
+
81
+ def run(self, data: Any = None, **options: Any) -> Any:
82
+ """Run the tool. Returns a str, or a FileResult for file-producing tools."""
83
+ started = time.perf_counter()
84
+ try:
85
+ kwargs = {}
86
+ for p in self.params:
87
+ if p.name in options and options[p.name] is not None:
88
+ kwargs[p.name] = options[p.name]
89
+ elif p.required:
90
+ raise ToolError(f"missing required option: {p.name}")
91
+ if self.needs_input:
92
+ if data is None or (self.input_kind == "files" and not data):
93
+ what = {"text": "text", "file": "file", "files": "files"}[self.input_kind]
94
+ raise ToolError(f"this tool needs input {what}")
95
+ result = self.func(data, **kwargs)
96
+ else:
97
+ result = self.func(**kwargs)
98
+ result = result if isinstance(result, FileResult) else str(result)
99
+ except ToolError as e:
100
+ log.warning("tool=%s failed: %s", self.name, e)
101
+ raise
102
+ except Exception:
103
+ log.exception("tool=%s crashed", self.name)
104
+ raise
105
+ ms = (time.perf_counter() - started) * 1000
106
+ out = f"file {result.filename} {len(result.data)} bytes" if isinstance(result, FileResult) else f"{len(result)} chars"
107
+ log.info("tool=%s ok in=%s options=%s out=%s time=%.0fms", self.name,
108
+ self._describe_input(data) if self.needs_input else "none",
109
+ self._describe_options(kwargs), out, ms)
110
+ return result
111
+
112
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
113
+ return self.func(*args, **kwargs)
114
+
115
+
116
+ def _loggable(t: "Tool", name: str) -> bool:
117
+ p = next((p for p in t.params if p.name == name), None)
118
+ return p is not None and (p.type is not str or p.choices is not None)
119
+
120
+
121
+ TOOLS: Dict[str, Tool] = {}
122
+
123
+
124
+ def tool(name: str, title: str, group: str) -> Callable[[Callable[..., Any]], Tool]:
125
+ def decorator(func: Callable[..., Any]) -> Tool:
126
+ hints = typing.get_type_hints(func)
127
+ sig = inspect.signature(func)
128
+ params: List[Param] = []
129
+ input_kind = "none"
130
+ for i, (pname, p) in enumerate(sig.parameters.items()):
131
+ if i == 0 and pname in _INPUT_KINDS:
132
+ input_kind = _INPUT_KINDS[pname]
133
+ continue
134
+ hint = hints.get(pname, str)
135
+ choices = None
136
+ if typing.get_origin(hint) is typing.Literal:
137
+ choices = typing.get_args(hint)
138
+ hint = type(choices[0])
139
+ params.append(Param(pname, hint, p.default, choices))
140
+ doc = (inspect.getdoc(func) or "").strip().splitlines()
141
+ t = Tool(name, title, group, doc[0] if doc else title, func, params, input_kind)
142
+ if name in TOOLS:
143
+ raise ValueError(f"duplicate tool name: {name}")
144
+ TOOLS[name] = t
145
+ return t
146
+
147
+ return decorator
148
+
149
+
150
+ def load_all() -> Dict[str, Tool]:
151
+ """Import every tool module so they register themselves."""
152
+ from . import tools # noqa: F401
153
+
154
+ return TOOLS
155
+
156
+
157
+ def groups() -> Dict[str, List[Tool]]:
158
+ out: Dict[str, List[Tool]] = {}
159
+ for t in load_all().values():
160
+ out.setdefault(t.group, []).append(t)
161
+ return out
simplutils/textio.py ADDED
@@ -0,0 +1,25 @@
1
+ """Reading text from files and stdin robustly (Windows editors and PowerShell often add a BOM or use UTF-16)."""
2
+ from __future__ import annotations
3
+
4
+ from .registry import ToolError
5
+
6
+
7
+ def decode_text(raw: bytes) -> str:
8
+ """Decode bytes as text: UTF-8 (with or without BOM) or UTF-16 (with BOM). Raises ToolError otherwise."""
9
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
10
+ try:
11
+ return raw.decode("utf-16") # also strips the BOM and detects endianness
12
+ except UnicodeDecodeError:
13
+ raise ToolError("the input looks like UTF-16 but could not be decoded")
14
+ try:
15
+ return raw.decode("utf-8-sig")
16
+ except UnicodeDecodeError:
17
+ raise ToolError("the input is not valid UTF-8 text (is it a binary file, or a legacy encoding?)")
18
+
19
+
20
+ def read_text_file(path: str) -> str:
21
+ try:
22
+ with open(path, "rb") as fh:
23
+ return decode_text(fh.read())
24
+ except OSError as e:
25
+ raise ToolError(f"cannot read '{path}': {e}")
@@ -0,0 +1,5 @@
1
+ """Importing this package registers all tools. Add new modules here."""
2
+ from . import ( # noqa: F401
3
+ ai, convert, diff, encoding, files, generators, hashing, images, jsontools, jwt, mapsearch, pdfs, pii, qr,
4
+ regex, text, timetools,
5
+ )