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.
@@ -0,0 +1,211 @@
1
+ """Find and redact personal data and secrets in text, entirely offline.
2
+
3
+ Detection is heuristic (regex + checksums such as Luhn / Verhoeff / IBAN mod-97). It catches the
4
+ common cases but is NOT a guarantee - always review before sharing sensitive text.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import logging
10
+ import re
11
+ import secrets
12
+ from collections import Counter
13
+ from dataclasses import dataclass
14
+ from typing import Callable, List, Optional, Set, Tuple
15
+
16
+ from typing import Literal
17
+
18
+ from ..registry import ToolError, tool
19
+
20
+ G = "Privacy (PII)"
21
+ log = logging.getLogger("simplutils")
22
+
23
+
24
+ # ---------------------------------------------------------------- checksums
25
+ def luhn_ok(value: str) -> bool:
26
+ digits = [int(c) for c in re.sub(r"\D", "", value)]
27
+ if not 13 <= len(digits) <= 19 or len(set(digits)) == 1:
28
+ return False
29
+ total = 0
30
+ for i, d in enumerate(reversed(digits)):
31
+ if i % 2:
32
+ d = d * 2 - 9 if d > 4 else d * 2
33
+ total += d
34
+ return total % 10 == 0
35
+
36
+
37
+ _D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
38
+ [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
39
+ [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
40
+ [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]
41
+ _P = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
42
+ [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
43
+ [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]
44
+ _INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]
45
+
46
+
47
+ def verhoeff_ok(value: str) -> bool:
48
+ c = 0
49
+ for i, ch in enumerate(reversed(re.sub(r"\D", "", value))):
50
+ c = _D[c][_P[i % 8][int(ch)]]
51
+ return c == 0
52
+
53
+
54
+ def verhoeff_check_digit(number: str) -> str:
55
+ c = 0
56
+ for i, ch in enumerate(reversed(number)):
57
+ c = _D[c][_P[(i + 1) % 8][int(ch)]]
58
+ return str(_INV[c])
59
+
60
+
61
+ def iban_ok(value: str) -> bool:
62
+ s = re.sub(r"\s", "", value).upper()
63
+ if not 15 <= len(s) <= 34:
64
+ return False
65
+ moved = s[4:] + s[:4]
66
+ num = "".join(str(int(c, 36)) for c in moved)
67
+ return int(num) % 97 == 1
68
+
69
+
70
+ # ---------------------------------------------------------------- detectors
71
+ @dataclass
72
+ class Finding:
73
+ kind: str
74
+ start: int
75
+ end: int
76
+ value: str
77
+
78
+
79
+ # (kind, regex, capture group to redact, validator). Order = priority: earlier wins on overlap.
80
+ _DETECTORS: List[Tuple[str, "re.Pattern[str]", int, Optional[Callable[[str], bool]]]] = [
81
+ ("private-key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----"), 0, None),
82
+ ("aws-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), 0, None),
83
+ ("github-token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), 0, None),
84
+ ("slack-token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"), 0, None),
85
+ ("google-api-key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b"), 0, None),
86
+ ("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*"), 0, None),
87
+ ("bearer-token", re.compile(r"\bBearer\s+([A-Za-z0-9._~+/=-]{16,})"), 1, None),
88
+ ("url-password", re.compile(r"(?<=://)[^\s:/@]+:([^\s@/]+)(?=@)"), 1, None),
89
+ ("password", re.compile(
90
+ r"(?i)\b(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token)\b[\"']?\s*[:=]\s*[\"']?([^\s\"',;]{4,})"),
91
+ 1, None),
92
+ ("credit-card", re.compile(r"(?<![\d-])(?:\d[ -]?){12,18}\d(?![\d-])"), 0, luhn_ok),
93
+ ("iban", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\b"), 0, iban_ok),
94
+ ("aadhaar", re.compile(r"(?<!\d)[2-9]\d{3}[ -]?\d{4}[ -]?\d{4}(?!\d)"), 0, verhoeff_ok),
95
+ ("ssn", re.compile(r"\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b"), 0, None),
96
+ ("pan", re.compile(r"\b[A-Z]{5}\d{4}[A-Z]\b"), 0, None),
97
+ ("email", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}"), 0, None),
98
+ # not part of a longer dotted number (version strings like 1.2.3.4.5)
99
+ ("ip-address", re.compile(
100
+ r"(?<![\w.])(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)(?!\w|\.\d)"), 0, None),
101
+ ("phone", re.compile(
102
+ r"(?<![\w.])(?:\+91[ -]?|0)?[6-9]\d{4}[ -]?\d{5}(?!\w)" # India mobile
103
+ r"|(?<![\w.])(?:\+?1[ .-]?)?\(?\d{3}\)?[ .-]\d{3}[ .-]\d{4}(?!\w)" # US / Canada
104
+ r"|(?<![\w.])\+\d{1,3}[ -]?\d{1,4}(?:[ -]?\d{2,4}){2,4}(?!\w)"), 0, None), # other international
105
+ ]
106
+
107
+ KINDS: List[str] = [d[0] for d in _DETECTORS]
108
+ _FULL_MASK = {"private-key", "aws-key", "github-token", "slack-token", "google-api-key", "jwt",
109
+ "bearer-token", "url-password", "password"} # secrets are never partially revealed
110
+
111
+
112
+ def detect(text: str, kinds: Optional[Set[str]] = None) -> List[Finding]:
113
+ """Return non-overlapping findings sorted by position.
114
+
115
+ `kinds` limits what is *reported*. Every detector still claims the text it matches, so a type
116
+ you switched off keeps suppressing weaker guesses (e.g. excluding "credit-card" does not make
117
+ the same digits show up as a "phone", and "user:pass@host" is not mistaken for an email).
118
+ """
119
+ taken = bytearray(len(text))
120
+ found: List[Finding] = []
121
+ for kind, rx, group, check in _DETECTORS:
122
+ report = kinds is None or kind in kinds
123
+ for m in rx.finditer(text):
124
+ s, e = m.span(group)
125
+ if s < 0 or any(taken[s:e]):
126
+ continue
127
+ value = text[s:e]
128
+ if check is not None and not check(value):
129
+ continue
130
+ taken[s:e] = b"\x01" * (e - s)
131
+ if report:
132
+ found.append(Finding(kind, s, e, value))
133
+ found.sort(key=lambda f: f.start)
134
+ return found
135
+
136
+
137
+ def _parse_kinds(spec: str, exclude: str) -> Optional[Set[str]]:
138
+ def names(s: str) -> Set[str]:
139
+ out = {x.strip().lower() for x in s.split(",") if x.strip()}
140
+ bad = out - set(KINDS)
141
+ if bad:
142
+ raise ToolError(f"unknown type(s): {', '.join(sorted(bad))}. See: simplutils pii-types")
143
+ return out
144
+
145
+ only, skip = names(spec), names(exclude)
146
+ if not only and not skip:
147
+ return None
148
+ return (only or set(KINDS)) - skip
149
+
150
+
151
+ def _replacement(f: Finding, mode: str, salt: bytes) -> str:
152
+ tag = f.kind.upper()
153
+ if mode == "label" or f.kind == "private-key":
154
+ return f"[{tag}]"
155
+ if mode == "hash":
156
+ return f"[{tag}#{hashlib.sha256(salt + f.value.encode()).hexdigest()[:8]}]"
157
+ if f.kind in _FULL_MASK:
158
+ return "********"
159
+ idx = [i for i, c in enumerate(f.value) if c.isalnum()]
160
+ keep = set(idx[-4:]) if len(idx) > 4 else set()
161
+ return "".join(c if (not c.isalnum() or i in keep) else "*" for i, c in enumerate(f.value))
162
+
163
+
164
+ def _log_summary(action: str, findings: List[Finding]) -> None:
165
+ counts = dict(Counter(f.kind for f in findings))
166
+ log.info("%s: %d finding(s) %s", action, len(findings), counts) # counts only, never values
167
+
168
+
169
+ @tool("pii-redact", "PII Redact", G)
170
+ def pii_redact(text: str, mode: Literal["label", "mask", "hash"] = "label", only: str = "", exclude: str = "") -> str:
171
+ """Replace emails, phones, cards, IDs, API keys and passwords with safe placeholders (runs offline)."""
172
+ findings = detect(text, _parse_kinds(only, exclude))
173
+ _log_summary("pii-redact", findings)
174
+ salt = secrets.token_bytes(16) # random per run: same value -> same token within this text only
175
+ out, pos = [], 0
176
+ for f in findings:
177
+ out.append(text[pos:f.start])
178
+ out.append(_replacement(f, mode, salt))
179
+ pos = f.end
180
+ out.append(text[pos:])
181
+ return "".join(out)
182
+
183
+
184
+ def _preview(v: str) -> str:
185
+ v = " ".join(v.split())
186
+ return v[:2] + "***" if len(v) > 4 else "***"
187
+
188
+
189
+ @tool("pii-scan", "PII Scan (report)", G)
190
+ def pii_scan(text: str, only: str = "", exclude: str = "") -> str:
191
+ """Report what personal data / secrets the text seems to contain, without printing the values."""
192
+ findings = detect(text, _parse_kinds(only, exclude))
193
+ _log_summary("pii-scan", findings)
194
+ if not findings:
195
+ return "Nothing detected. (Checks are heuristic - this is not a guarantee.)"
196
+ counts = Counter(f.kind for f in findings)
197
+ lines = [f"Found {len(findings)} potential item(s) of {len(counts)} type(s)", "", "Summary"]
198
+ lines += [f" {k:<15} {n}" for k, n in counts.most_common()]
199
+ lines += ["", "Details (values are hidden)"]
200
+ for f in findings[:500]:
201
+ line_no = text.count("\n", 0, f.start) + 1
202
+ lines.append(f" line {line_no:<5} {f.kind:<15} {_preview(f.value)}")
203
+ if len(findings) > 500:
204
+ lines.append(f" ... {len(findings) - 500} more")
205
+ return "\n".join(lines)
206
+
207
+
208
+ @tool("pii-types", "PII Types", G)
209
+ def pii_types() -> str:
210
+ """List everything the PII tools can detect (use these names with --only / --exclude)."""
211
+ return "\n".join(KINDS)
simplutils/tools/qr.py ADDED
@@ -0,0 +1,40 @@
1
+ """QR code generation (needs segno: pip install simplutils[extras])."""
2
+ import io
3
+ from typing import Literal
4
+
5
+ from ..registry import FileResult, ToolError, tool
6
+
7
+ G = "QR"
8
+ _ERR = Literal["L", "M", "Q", "H"]
9
+
10
+
11
+ def _make(text: str, error: str):
12
+ try:
13
+ import segno
14
+ except ImportError:
15
+ raise ToolError("this tool needs segno: pip install simplutils[extras]")
16
+ try:
17
+ return segno.make(text, error=error, boost_error=False)
18
+ except Exception as e: # e.g. data too long for a QR code
19
+ raise ToolError(f"cannot make QR code: {e}")
20
+
21
+
22
+ @tool("qr-generate", "QR Code (image)", G)
23
+ def qr_generate(text: str, kind: Literal["png", "svg"] = "png", scale: int = 8, error: _ERR = "M") -> FileResult:
24
+ """Make a QR code image (PNG or SVG). `error` is the correction level: L, M, Q or H (more = bigger code)."""
25
+ if not 1 <= scale <= 50:
26
+ raise ToolError("scale must be 1-50")
27
+ qr = _make(text, error)
28
+ buf = io.BytesIO()
29
+ qr.save(buf, kind=kind, scale=scale, border=4)
30
+ mime = "image/png" if kind == "png" else "image/svg+xml"
31
+ return FileResult(buf.getvalue(), f"qr.{kind}", mime)
32
+
33
+
34
+ @tool("qr-text", "QR Code (terminal)", G)
35
+ def qr_text(text: str, error: _ERR = "M") -> str:
36
+ """Draw a QR code as text blocks you can scan straight from the terminal."""
37
+ qr = _make(text, error)
38
+ buf = io.StringIO()
39
+ qr.terminal(out=buf, compact=True)
40
+ return buf.getvalue().rstrip("\n")
@@ -0,0 +1,44 @@
1
+ import re
2
+
3
+ from ..registry import ToolError, tool
4
+
5
+ G = "Text"
6
+ MAX_MATCHES = 200
7
+
8
+
9
+ def _compile(pattern: str, ignore_case: bool, multiline: bool, dotall: bool):
10
+ flags = (re.I if ignore_case else 0) | (re.M if multiline else 0) | (re.S if dotall else 0)
11
+ try:
12
+ return re.compile(pattern, flags)
13
+ except re.error as e:
14
+ raise ToolError(f"invalid regex: {e}")
15
+
16
+
17
+ @tool("regex-test", "Regex Tester", G)
18
+ def regex_test(text: str, pattern: str, ignore_case: bool = False, multiline: bool = False, dotall: bool = False) -> str:
19
+ """Find all matches of a regex in the text, with positions and capture groups."""
20
+ rx = _compile(pattern, ignore_case, multiline, dotall)
21
+ matches = list(rx.finditer(text))
22
+ if not matches:
23
+ return "No matches."
24
+ lines = [f"{len(matches)} match{'es' if len(matches) != 1 else ''}"]
25
+ for i, m in enumerate(matches[:MAX_MATCHES], 1):
26
+ lines.append(f"#{i} [{m.start()}:{m.end()}] {m.group(0)!r}")
27
+ for n, g in enumerate(m.groups(), 1):
28
+ lines.append(f" group {n}: {g!r}")
29
+ for name, g in m.groupdict().items():
30
+ lines.append(f" <{name}>: {g!r}")
31
+ if len(matches) > MAX_MATCHES:
32
+ lines.append(f"... {len(matches) - MAX_MATCHES} more not shown")
33
+ return "\n".join(lines)
34
+
35
+
36
+ @tool("regex-replace", "Regex Replace", G)
37
+ def regex_replace(text: str, pattern: str, replacement: str, ignore_case: bool = False,
38
+ multiline: bool = False, dotall: bool = False) -> str:
39
+ r"""Replace regex matches. In the replacement use \1, \2 or \g<name> for capture groups."""
40
+ rx = _compile(pattern, ignore_case, multiline, dotall)
41
+ try:
42
+ return rx.sub(replacement, text)
43
+ except (re.error, IndexError) as e:
44
+ raise ToolError(f"invalid replacement: {e}")
@@ -0,0 +1,49 @@
1
+ import re
2
+ import unicodedata
3
+ from typing import Literal
4
+
5
+ from ..registry import tool
6
+
7
+ G = "Text"
8
+ Style = Literal["snake", "camel", "pascal", "kebab", "constant", "title", "upper", "lower"]
9
+
10
+
11
+ def _words(text: str):
12
+ text = re.sub(r"[^0-9A-Za-z]+", " ", text)
13
+ return re.findall(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+", text)
14
+
15
+
16
+ @tool("case-convert", "Case Converter", G)
17
+ def case_convert(text: str, style: Style = "snake") -> str:
18
+ """Convert text between snake, camel, pascal, kebab and other cases."""
19
+ w = _words(text)
20
+ lo = [x.lower() for x in w]
21
+ if style == "snake":
22
+ return "_".join(lo)
23
+ if style == "kebab":
24
+ return "-".join(lo)
25
+ if style == "constant":
26
+ return "_".join(lo).upper()
27
+ if style == "pascal":
28
+ return "".join(x.capitalize() for x in lo)
29
+ if style == "camel":
30
+ return (lo[0] + "".join(x.capitalize() for x in lo[1:])) if lo else ""
31
+ if style == "title":
32
+ return " ".join(x.capitalize() for x in lo)
33
+ if style == "upper":
34
+ return text.upper()
35
+ return text.lower()
36
+
37
+
38
+ @tool("slugify", "Slugify", G)
39
+ def slugify(text: str) -> str:
40
+ """Make a URL-friendly slug."""
41
+ t = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
42
+ return re.sub(r"[^a-z0-9]+", "-", t.lower()).strip("-")
43
+
44
+
45
+ @tool("count", "Word & Char Count", G)
46
+ def count(text: str) -> str:
47
+ """Count characters, words and lines."""
48
+ lines = len(text.splitlines()) if text else 0
49
+ return f"characters: {len(text)}\nwords: {len(text.split())}\nlines: {lines}"
@@ -0,0 +1,41 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from ..registry import ToolError, tool
4
+
5
+ G = "Time"
6
+
7
+
8
+ @tool("ts-to-date", "Timestamp → Date", G)
9
+ def ts_to_date(text: str) -> str:
10
+ """Convert a Unix timestamp (seconds or milliseconds) to a date."""
11
+ try:
12
+ n = float(text.strip())
13
+ except ValueError:
14
+ raise ToolError("not a number")
15
+ if abs(n) > 1e11: # looks like milliseconds
16
+ n /= 1000
17
+ try:
18
+ dt = datetime.fromtimestamp(n, timezone.utc)
19
+ except (OverflowError, OSError, ValueError):
20
+ raise ToolError("timestamp out of range")
21
+ return f"UTC: {dt.isoformat()}\nLocal: {dt.astimezone().isoformat()}"
22
+
23
+
24
+ @tool("date-to-ts", "Date → Timestamp", G)
25
+ def date_to_ts(text: str) -> str:
26
+ """Convert an ISO date/time (e.g. 2026-01-31 14:30) to a Unix timestamp. Naive = UTC."""
27
+ try:
28
+ dt = datetime.fromisoformat(text.strip().replace("Z", "+00:00"))
29
+ except ValueError:
30
+ raise ToolError("use ISO format, e.g. 2026-01-31T14:30:00")
31
+ if dt.tzinfo is None:
32
+ dt = dt.replace(tzinfo=timezone.utc)
33
+ s = dt.timestamp()
34
+ return f"seconds: {int(s)}\nmilliseconds: {int(s * 1000)}"
35
+
36
+
37
+ @tool("now", "Current Time", G)
38
+ def now() -> str:
39
+ """Show the current time as ISO and Unix timestamp."""
40
+ n = datetime.now(timezone.utc)
41
+ return f"UTC: {n.isoformat()}\nUnix: {int(n.timestamp())}"
simplutils/ui.py ADDED
@@ -0,0 +1,186 @@
1
+ """Local web UI (NiceGUI), generated from the tool registry. Runs entirely on localhost."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import inspect
6
+ import json
7
+
8
+ from nicegui import ui
9
+
10
+ from .logs import setup_logging
11
+ from .registry import FileResult, Tool, groups, load_all
12
+ from .tools.files import detect_image
13
+
14
+
15
+ def _data_uri(data: bytes, mime: str) -> str:
16
+ return f"data:{mime};base64,{base64.b64encode(data).decode()}"
17
+
18
+
19
+ def _tool_panel(t: Tool) -> None:
20
+ values = {p.name: (None if p.required else p.default) for p in t.params}
21
+ refs = {}
22
+ state = {"bytes": None, "result": None, "files": [], "names": []}
23
+
24
+ def show_preview(data: bytes, mime: str) -> None:
25
+ refs["preview"].clear()
26
+ if mime.startswith("image/"):
27
+ with refs["preview"]:
28
+ ui.image(_data_uri(data, mime)).classes("max-w-md border rounded")
29
+
30
+ def run(*_) -> None:
31
+ state["result"] = None
32
+ refs["download"].set_visibility(False)
33
+ try:
34
+ if t.input_kind == "file":
35
+ data = state["bytes"]
36
+ if data is None:
37
+ refs["output"].value = "Upload a file to begin."
38
+ return
39
+ elif t.input_kind == "files":
40
+ data = state["files"]
41
+ if not data:
42
+ refs["output"].value = "Upload one or more files to begin (they are used in upload order)."
43
+ return
44
+ elif t.input_kind == "text":
45
+ data = refs["input"].value
46
+ if not data:
47
+ refs["output"].value = ""
48
+ return
49
+ else:
50
+ data = None
51
+ result = t.run(data, **values)
52
+ except Exception as e: # ToolError or anything unexpected
53
+ refs["output"].value = f"Error: {e}"
54
+ return
55
+ if isinstance(result, FileResult):
56
+ state["result"] = result
57
+ refs["output"].value = f"Ready: {result.filename} ({len(result.data):,} bytes) - use Download"
58
+ refs["download"].set_visibility(True)
59
+ show_preview(result.data, result.mime)
60
+ else:
61
+ refs["output"].value = result
62
+
63
+ async def on_upload(e) -> None:
64
+ data = e.file.read()
65
+ if inspect.isawaitable(data):
66
+ data = await data
67
+ if t.input_kind == "files":
68
+ state["files"].append(data)
69
+ state["names"].append(e.file.name)
70
+ refs["filename"].text = "Files (in order): " + ", ".join(state["names"])
71
+ run()
72
+ return
73
+ state["bytes"] = data
74
+ refs["filename"].text = f"{e.file.name} ({len(data):,} bytes)"
75
+ kind = detect_image(data)
76
+ refs["preview"].clear()
77
+ if kind:
78
+ show_preview(data, kind[0])
79
+ run()
80
+
81
+ def clear_files() -> None:
82
+ state["files"].clear()
83
+ state["names"].clear()
84
+ refs["upload"].reset()
85
+ refs["filename"].text = ""
86
+ run()
87
+
88
+ ui.label(t.title).classes("text-2xl font-bold")
89
+ ui.label(t.description).classes("text-gray-500")
90
+
91
+ if t.input_kind == "text":
92
+ refs["input"] = ui.textarea("Input", on_change=run).props("outlined autogrow").classes("w-full")
93
+ elif t.input_kind in ("file", "files"):
94
+ multi = t.input_kind == "files"
95
+ refs["upload"] = ui.upload(
96
+ label="Drop files here or click +" if multi else "Drop a file here or click +",
97
+ multiple=multi, auto_upload=True, on_upload=on_upload,
98
+ ).classes("w-full")
99
+ refs["filename"] = ui.label("").classes("text-sm text-gray-500")
100
+ if multi:
101
+ ui.button("Clear files", on_click=clear_files, icon="delete").props("flat dense")
102
+ refs["preview"] = ui.column()
103
+
104
+ if t.params:
105
+ with ui.row().classes("items-center gap-4"):
106
+ for p in t.params:
107
+ def setter(name):
108
+ def _set(e):
109
+ values[name] = e.value
110
+ run()
111
+ return _set
112
+ label = p.name.replace("_", " ")
113
+ if p.choices:
114
+ ui.select(list(p.choices), value=p.default, label=label, on_change=setter(p.name))
115
+ elif p.type is bool:
116
+ ui.switch(label, value=False, on_change=setter(p.name))
117
+ elif p.type is int:
118
+ ui.number(label, value=None if p.required else p.default, precision=0,
119
+ on_change=lambda e, n=p.name: (values.__setitem__(n, int(e.value) if e.value is not None else None), run()))
120
+ else:
121
+ ui.input(label, value="" if p.required else p.default, on_change=setter(p.name))
122
+
123
+ refs["output"] = ui.textarea("Output").props("outlined readonly autogrow").classes("w-full")
124
+
125
+ def copy() -> None:
126
+ ui.run_javascript(f"navigator.clipboard.writeText({json.dumps(refs['output'].value)})")
127
+ ui.notify("Copied", type="positive")
128
+
129
+ def download() -> None:
130
+ r = state["result"]
131
+ if r is not None:
132
+ ui.download(r.data, r.filename, r.mime)
133
+
134
+ with ui.row():
135
+ ui.button("Run", on_click=run, icon="play_arrow")
136
+ ui.button("Copy output", on_click=copy, icon="content_copy").props("outline")
137
+ refs["download"] = ui.button("Download file", on_click=download, icon="download").props("color=positive")
138
+ refs["download"].set_visibility(False)
139
+ run()
140
+
141
+
142
+ def run(port: int = 8080, show: bool = True) -> None:
143
+ setup_logging()
144
+ all_tools = load_all()
145
+ state = {"tool": next(iter(all_tools)), "query": ""}
146
+
147
+ @ui.page("/")
148
+ def index() -> None:
149
+ dark = ui.dark_mode()
150
+
151
+ @ui.refreshable
152
+ def nav() -> None:
153
+ q = state["query"].lower()
154
+ for group, tools in groups().items():
155
+ matches = [t for t in tools if q in t.title.lower() or q in t.name or q in t.description.lower()]
156
+ if not matches:
157
+ continue
158
+ ui.label(group).classes("text-xs uppercase text-gray-500 mt-3")
159
+ for t in matches:
160
+ ui.button(t.title, on_click=lambda t=t: select(t.name)).props(
161
+ "flat no-caps align=left" + ("" if t.name != state["tool"] else " color=primary")
162
+ ).classes("w-full")
163
+
164
+ @ui.refreshable
165
+ def panel() -> None:
166
+ _tool_panel(all_tools[state["tool"]])
167
+
168
+ def select(name: str) -> None:
169
+ state["tool"] = name
170
+ nav.refresh()
171
+ panel.refresh()
172
+
173
+ def search(e) -> None:
174
+ state["query"] = e.value or ""
175
+ nav.refresh()
176
+
177
+ with ui.header().classes("items-center justify-between"):
178
+ ui.label("simplutils").classes("text-xl font-bold")
179
+ ui.button(icon="dark_mode", on_click=dark.toggle).props("flat round color=white")
180
+ with ui.left_drawer(fixed=True).props("width=260"):
181
+ ui.input(placeholder="Search tools...", on_change=search).props("outlined dense clearable").classes("w-full")
182
+ nav()
183
+ with ui.column().classes("w-full max-w-4xl mx-auto p-4"):
184
+ panel()
185
+
186
+ ui.run(title="simplutils", port=port, show=show, reload=False, favicon="🧰")