pikvm-auto 0.3.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.
pikvm_auto/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """pikvm-auto package.
2
+
3
+ pikvmautomation, library, and ansible modules
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pikvm_auto._internal.cli import get_parser, main
9
+ from pikvm_auto._internal.commands.hid import (
10
+ HIDAction,
11
+ HIDClient,
12
+ actions_from_yaml,
13
+ canonical_key,
14
+ )
15
+ from pikvm_auto._internal.commands.info import run_info
16
+ from pikvm_auto._internal.config import PiKVMSettings
17
+
18
+ __all__: list[str] = [
19
+ "HIDAction",
20
+ "HIDClient",
21
+ "PiKVMSettings",
22
+ "actions_from_yaml",
23
+ "canonical_key",
24
+ "get_parser",
25
+ "main",
26
+ "run_info",
27
+ ]
28
+
29
+ from pikvm_auto._internal.commands.screenshot import (
30
+ ScreenMatch,
31
+ ScreenshotClient,
32
+ fuzzy_score,
33
+ )
34
+
35
+ __all__ += ["ScreenMatch", "ScreenshotClient", "fuzzy_score"]
pikvm_auto/__main__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Entry-point module, in case you use `python -m pikvm_auto`.
2
+
3
+ Why does this file exist, and why `__main__`? For more info, read:
4
+
5
+ - https://www.python.org/dev/peps/pep-0338/
6
+ - https://docs.python.org/3/using/cmdline.html#cmdoption-m
7
+ """
8
+
9
+ import sys
10
+
11
+ from pikvm_auto._internal.cli import main
12
+
13
+ if __name__ == "__main__":
14
+ sys.exit(main(sys.argv[1:]))
File without changes
@@ -0,0 +1,97 @@
1
+ # Why does this file exist, and why not put this in `__main__`?
2
+ #
3
+ # You might be tempted to import things from `__main__` later,
4
+ # but that will cause problems: the code will get executed twice:
5
+ #
6
+ # - When you run `python -m pikvm_auto` python will execute
7
+ # `__main__.py` as a script. That means there won't be any
8
+ # `pikvm_auto.__main__` in `sys.modules`.
9
+ # - When you import `__main__` it will get executed again (as a module) because
10
+ # there's no `pikvm_auto.__main__` in `sys.modules`.
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import sys
16
+ from typing import Any
17
+
18
+ from pikvm_auto._internal import debug
19
+ from pikvm_auto._internal.commands.info import run_info
20
+ from pikvm_auto._internal.config import PiKVMSettings
21
+
22
+
23
+ class _DebugInfo(argparse.Action):
24
+ def __init__(self, nargs: int | str | None = 0, **kwargs: Any) -> None:
25
+ super().__init__(nargs=nargs, **kwargs)
26
+
27
+ def __call__(self, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
28
+ debug._print_debug_info()
29
+ sys.exit(0)
30
+
31
+
32
+ def _add_connection_args(parser: argparse.ArgumentParser) -> None:
33
+ group = parser.add_argument_group("connection")
34
+ group.add_argument("--host", help="PiKVM hostname or IP.")
35
+ group.add_argument("--user", help="PiKVM username (default: admin).")
36
+ group.add_argument("--password", help="PiKVM password.")
37
+ group.add_argument("--schema", help="Protocol: http or https (default: https).")
38
+ group.add_argument("--cert-trusted", action="store_true", help="Trust SSL certificate.")
39
+
40
+
41
+ def get_parser() -> argparse.ArgumentParser:
42
+ """Return the CLI argument parser.
43
+
44
+ Returns:
45
+ An argparse parser.
46
+ """
47
+ parser = argparse.ArgumentParser(prog="pikvm-auto")
48
+ parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {debug._get_version()}")
49
+ parser.add_argument("--debug-info", action=_DebugInfo, help="Print debug information.")
50
+
51
+ subparsers = parser.add_subparsers(dest="command")
52
+
53
+ info_parser = subparsers.add_parser("info", help="Show PiKVM system info and health status.")
54
+ _add_connection_args(info_parser)
55
+
56
+ return parser
57
+
58
+
59
+ def _build_settings(opts: argparse.Namespace) -> PiKVMSettings:
60
+ overrides: dict[str, Any] = {}
61
+ if opts.host:
62
+ overrides["host"] = opts.host
63
+ if opts.user:
64
+ overrides["user"] = opts.user
65
+ if opts.password:
66
+ overrides["password"] = opts.password
67
+ if opts.schema:
68
+ overrides["schema_"] = opts.schema
69
+ if opts.cert_trusted:
70
+ overrides["cert_trusted"] = opts.cert_trusted
71
+ return PiKVMSettings(**overrides)
72
+
73
+
74
+ def main(args: list[str] | None = None) -> int:
75
+ """Run the main program.
76
+
77
+ This function is executed when you type `pikvm-auto` or `python -m pikvm_auto`.
78
+
79
+ Parameters:
80
+ args: Arguments passed from the command line.
81
+
82
+ Returns:
83
+ An exit code.
84
+ """
85
+ parser = get_parser()
86
+ opts = parser.parse_args(args=args)
87
+
88
+ if opts.command is None:
89
+ parser.print_help()
90
+ return 0
91
+
92
+ if opts.command == "info":
93
+ settings = _build_settings(opts)
94
+ client = settings.create_client()
95
+ return run_info(client)
96
+
97
+ return 0
File without changes
@@ -0,0 +1,297 @@
1
+ # HID input library for PiKVM.
2
+ #
3
+ # Provides a high-level interface for sending keyboard input via the kvmd HTTP
4
+ # API (key taps, chorded shortcuts, text typing, and timed sequences).
5
+ #
6
+ # HTTP wiring
7
+ # -----------
8
+ # pikvm-lib 0.5.0's BuildPiKVM does NOT use a requests.Session. Upstream calls
9
+ # the module-level requests.get / requests.post functions directly with
10
+ # headers=self.headers and verify=self.certificate_trusted on every call.
11
+ # HIDClient follows the same pattern: it reads headers, hostname, schema, and
12
+ # certificate_trusted from the passed PiKVM instance and calls the
13
+ # module-level requests.post directly. The PiKVM object exposes no persistent
14
+ # HTTP session attribute. Tests must monkeypatch
15
+ # pikvm_auto._internal.commands.hid.requests.post rather than any session.
16
+ #
17
+ # Modifier key aliases
18
+ # --------------------
19
+ # Short modifier aliases (ctrl, alt, shift, meta/win) default to the LEFT
20
+ # variant of the corresponding kvmd key code (ControlLeft, AltLeft, ShiftLeft,
21
+ # MetaLeft). To target the right-hand modifier, pass the canonical name
22
+ # directly (ControlRight, AltRight, ShiftRight, MetaRight).
23
+
24
+ from __future__ import annotations
25
+
26
+ import time
27
+ from dataclasses import dataclass
28
+ from typing import TYPE_CHECKING, Literal
29
+
30
+ import requests
31
+
32
+ if TYPE_CHECKING:
33
+ from pikvm_lib.pikvm import PiKVM
34
+
35
+
36
+ @dataclass
37
+ class HIDAction:
38
+ """A single HID action in a scripted input sequence.
39
+
40
+ Fields:
41
+ kind: one of "key", "shortcut", "text", "wait".
42
+ key: single key name (used when ``kind == "key"``).
43
+ keys: list of key names for a chord (used when ``kind == "shortcut"``).
44
+ text: text to type (used when ``kind == "text"``).
45
+ seconds: delay in seconds (used when ``kind == "wait"``).
46
+ """
47
+
48
+ kind: Literal["key", "shortcut", "text", "wait"]
49
+ key: str | None = None
50
+ keys: list[str] | None = None
51
+ text: str | None = None
52
+ seconds: float | None = None
53
+
54
+
55
+ # Friendly alias → kvmd canonical key code.
56
+ # Modifier aliases default to the LEFT variant; use the canonical name to
57
+ # target the right-hand modifier.
58
+ _KEY_ALIASES: dict[str, str] = {
59
+ # Function keys F1..F12
60
+ **{f"f{i}": f"F{i}" for i in range(1, 13)},
61
+ # Arrow keys
62
+ "up": "ArrowUp",
63
+ "down": "ArrowDown",
64
+ "left": "ArrowLeft",
65
+ "right": "ArrowRight",
66
+ # Common singles
67
+ "enter": "Enter",
68
+ "return": "Enter",
69
+ "esc": "Escape",
70
+ "escape": "Escape",
71
+ "tab": "Tab",
72
+ "del": "Delete",
73
+ "delete": "Delete",
74
+ "backspace": "Backspace",
75
+ "space": "Space",
76
+ "home": "Home",
77
+ "end": "End",
78
+ "pageup": "PageUp",
79
+ "pagedown": "PageDown",
80
+ # Modifiers default to LEFT variant
81
+ "ctrl": "ControlLeft",
82
+ "alt": "AltLeft",
83
+ "shift": "ShiftLeft",
84
+ "meta": "MetaLeft",
85
+ "win": "MetaLeft",
86
+ }
87
+
88
+ # Canonical key codes that do not share a common prefix (Key*, Arrow*, Digit*,
89
+ # Numpad*) but are still valid passthroughs.
90
+ _CANONICAL_SINGLES: frozenset[str] = frozenset(
91
+ {
92
+ "Enter",
93
+ "Escape",
94
+ "Tab",
95
+ "Delete",
96
+ "Backspace",
97
+ "Space",
98
+ "Home",
99
+ "End",
100
+ "PageUp",
101
+ "PageDown",
102
+ "Insert",
103
+ "CapsLock",
104
+ "ControlLeft",
105
+ "ControlRight",
106
+ "AltLeft",
107
+ "AltRight",
108
+ "ShiftLeft",
109
+ "ShiftRight",
110
+ "MetaLeft",
111
+ "MetaRight",
112
+ "Minus",
113
+ "Equal",
114
+ "BracketLeft",
115
+ "BracketRight",
116
+ "Backslash",
117
+ "Semicolon",
118
+ "Quote",
119
+ "Backquote",
120
+ "Comma",
121
+ "Period",
122
+ "Slash",
123
+ },
124
+ )
125
+
126
+ _CANONICAL_PREFIXES: tuple[str, ...] = ("Key", "Arrow", "Digit", "Numpad")
127
+
128
+
129
+ def canonical_key(key: str) -> str:
130
+ """Return the kvmd canonical code for ``key``.
131
+
132
+ Lookup order:
133
+ 1. Friendly alias (case-insensitive) — e.g. ``f11`` → ``KeyF11``.
134
+ 2. Canonical passthrough — names with a known prefix (``Key*``,
135
+ ``Arrow*``, ``Digit*``, ``Numpad*``) or known singles (``Enter``,
136
+ ``ControlRight``, …) are returned unchanged.
137
+
138
+ Raises ``ValueError`` if the key cannot be resolved.
139
+ """
140
+ if not isinstance(key, str) or not key:
141
+ raise ValueError(f"unknown key: {key!r}")
142
+
143
+ lower = key.lower()
144
+ if lower in _KEY_ALIASES:
145
+ return _KEY_ALIASES[lower]
146
+
147
+ if key in _CANONICAL_SINGLES:
148
+ return key
149
+ if key.startswith(_CANONICAL_PREFIXES):
150
+ return key
151
+
152
+ raise ValueError(f"unknown key: {key!r}")
153
+
154
+
155
+ class HIDClient:
156
+ """High-level HID input client for PiKVM.
157
+
158
+ Reads ``headers``, ``hostname``, ``schema``, and ``certificate_trusted``
159
+ from the passed ``PiKVM`` instance and calls the module-level
160
+ ``requests.post`` directly (matching pikvm-lib's own pattern — see module
161
+ docstring).
162
+ """
163
+
164
+ def __init__(self, pikvm: PiKVM) -> None:
165
+ self._headers = pikvm.headers
166
+ self._base = f"{pikvm.schema}://{pikvm.hostname}"
167
+ self._verify = pikvm.certificate_trusted
168
+
169
+ def _send_key(self, code: str, state: str) -> None:
170
+ """POST a single key press or release event to kvmd.
171
+
172
+ ``state`` is the string ``"true"`` (press) or ``"false"`` (release) —
173
+ kvmd's API spec documents the ``state`` query parameter as a boolean,
174
+ serialised as a lowercase string.
175
+ """
176
+ resp = requests.post(
177
+ f"{self._base}/api/hid/events/send_key",
178
+ params={"key": code, "state": state},
179
+ headers=self._headers,
180
+ verify=self._verify,
181
+ timeout=10,
182
+ )
183
+ resp.raise_for_status()
184
+
185
+ def tap(self, key: str) -> None:
186
+ """Press and release a single key."""
187
+ code = canonical_key(key)
188
+ self._send_key(code, "true")
189
+ self._send_key(code, "false")
190
+
191
+ def press(self, key: str, *, hold_ms: int = 50) -> None:
192
+ """Press a key, hold it for ``hold_ms`` milliseconds, then release."""
193
+ code = canonical_key(key)
194
+ self._send_key(code, "true")
195
+ time.sleep(hold_ms / 1000)
196
+ self._send_key(code, "false")
197
+
198
+ def shortcut(self, keys: list[str]) -> None:
199
+ """Send a chord atomically via kvmd's ``/api/hid/events/send_shortcut``.
200
+
201
+ Server-side timing is more reliable than a synthesised press/release
202
+ sequence, so this delegates the entire chord to kvmd.
203
+ """
204
+ if not keys:
205
+ raise ValueError("shortcut() requires at least one key")
206
+ codes = ",".join(canonical_key(k) for k in keys)
207
+ resp = requests.post(
208
+ f"{self._base}/api/hid/events/send_shortcut",
209
+ params={"keys": codes},
210
+ headers=self._headers,
211
+ verify=self._verify,
212
+ timeout=10,
213
+ )
214
+ resp.raise_for_status()
215
+
216
+ def type_text(self, text: str, *, slow: bool = False) -> None:
217
+ """Type a string via ``/api/hid/print``.
218
+
219
+ ``limit=0`` means unlimited length. ``slow=True`` adds inter-character
220
+ delays server-side for flaky guest input handling.
221
+ """
222
+ if not text:
223
+ raise ValueError("type_text() requires non-empty text")
224
+ params: dict[str, str | int] = {"limit": 0}
225
+ if slow:
226
+ params["slow"] = "true"
227
+ resp = requests.post(
228
+ f"{self._base}/api/hid/print",
229
+ params=params,
230
+ data=text,
231
+ headers=self._headers,
232
+ verify=self._verify,
233
+ timeout=30,
234
+ )
235
+ resp.raise_for_status()
236
+
237
+ def play(self, actions: list[HIDAction]) -> None:
238
+ """Execute a sequence of HID actions in order.
239
+
240
+ Each action is dispatched by ``kind``:
241
+ - ``"wait"`` → ``time.sleep(a.seconds or 0)``
242
+ - ``"key"`` → ``self.tap(a.key)`` (requires ``a.key``)
243
+ - ``"shortcut"`` → ``self.shortcut(a.keys)`` (requires ``a.keys``)
244
+ - ``"text"`` → ``self.type_text(a.text)`` (requires ``a.text``)
245
+ """
246
+ for a in actions:
247
+ if a.kind == "wait":
248
+ time.sleep(a.seconds or 0)
249
+ elif a.kind == "key":
250
+ if a.key is None:
251
+ raise ValueError("HIDAction(kind='key') requires 'key'")
252
+ self.tap(a.key)
253
+ elif a.kind == "shortcut":
254
+ if a.keys is None:
255
+ raise ValueError("HIDAction(kind='shortcut') requires 'keys'")
256
+ self.shortcut(a.keys)
257
+ elif a.kind == "text":
258
+ if a.text is None:
259
+ raise ValueError("HIDAction(kind='text') requires 'text'")
260
+ self.type_text(a.text)
261
+ else:
262
+ raise ValueError(f"unknown HIDAction kind: {a.kind!r}")
263
+
264
+
265
+ _VALID_KINDS: frozenset[str] = frozenset({"key", "shortcut", "text", "wait"})
266
+
267
+
268
+ def actions_from_yaml(raw: list[dict]) -> list[HIDAction]:
269
+ """Build a list of ``HIDAction`` from raw dicts (e.g. parsed YAML).
270
+
271
+ Each dict must have a valid ``kind`` plus the relevant payload fields
272
+ (``key``, ``keys``, ``text``, ``seconds``). Unknown kinds raise
273
+ ``ValueError`` with the offending item index.
274
+ """
275
+ out: list[HIDAction] = []
276
+ for i, item in enumerate(raw):
277
+ kind = item.get("kind")
278
+ if kind not in _VALID_KINDS:
279
+ raise ValueError(f"unknown HIDAction kind: {kind!r} (item {i})")
280
+ if kind == "key" and not item.get("key"):
281
+ raise ValueError(f"HIDAction kind=key requires 'key' (item {i})")
282
+ if kind == "shortcut" and not item.get("keys"):
283
+ raise ValueError(f"HIDAction kind=shortcut requires 'keys' (item {i})")
284
+ if kind == "text" and item.get("text") is None:
285
+ raise ValueError(f"HIDAction kind=text requires 'text' (item {i})")
286
+ if kind == "wait" and item.get("seconds") is None:
287
+ raise ValueError(f"HIDAction kind=wait requires 'seconds' (item {i})")
288
+ out.append(
289
+ HIDAction(
290
+ kind=kind,
291
+ key=item.get("key"),
292
+ keys=item.get("keys"),
293
+ text=item.get("text"),
294
+ seconds=item.get("seconds"),
295
+ ),
296
+ )
297
+ return out
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from pikvm_lib.pikvm import PiKVM
6
+
7
+
8
+ def run_info(client: PiKVM) -> int:
9
+ system_info = client.get_system_info()
10
+ atx_state = client.get_atx_state()
11
+ streamer_state = client.get_streamer_state()
12
+
13
+ _print_section("System Info", system_info.get("result", {}))
14
+ _print_section("ATX / Power Status", atx_state.get("result", {}))
15
+ _print_section("Streamer Status", streamer_state.get("result", {}))
16
+
17
+ return 0
18
+
19
+
20
+ def _print_section(title: str, data: dict) -> None:
21
+ print(f"\n{'=' * 40}")
22
+ print(f" {title}")
23
+ print(f"{'=' * 40}")
24
+ print(json.dumps(data, indent=2))
@@ -0,0 +1,210 @@
1
+ # Screenshot + OCR library for PiKVM.
2
+ #
3
+ # Covers /api/streamer/snapshot in both raw-frame and OCR modes, plus a
4
+ # fuzzy-match polling helper (wait_for_text).
5
+ #
6
+ # HTTP wiring
7
+ # -----------
8
+ # pikvm-lib 0.5.0's BuildPiKVM does NOT use a requests.Session. Upstream calls
9
+ # the module-level requests.get / requests.post functions directly with
10
+ # headers=self.headers and verify=self.certificate_trusted on every call.
11
+ # ScreenshotClient follows the same pattern: it reads headers, hostname,
12
+ # schema, and certificate_trusted from the passed PiKVM instance and calls
13
+ # the module-level requests.get directly. Tests must monkeypatch
14
+ # pikvm_auto._internal.commands.screenshot.requests.get rather than any
15
+ # session attribute.
16
+
17
+ from __future__ import annotations
18
+
19
+ import time
20
+ from dataclasses import dataclass, field
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING
24
+
25
+ import requests
26
+
27
+ if TYPE_CHECKING:
28
+ from pikvm_lib.pikvm import PiKVM
29
+
30
+ try:
31
+ from rapidfuzz import fuzz as _fuzz
32
+
33
+ _HAVE_RAPIDFUZZ = True
34
+ except ImportError:
35
+ _HAVE_RAPIDFUZZ = False
36
+ import difflib
37
+
38
+
39
+ @dataclass
40
+ class ScreenMatch:
41
+ """Result of a fuzzy screen-text match.
42
+
43
+ Fields:
44
+ matched: True if the final score was at or above the threshold.
45
+ score: Final similarity score in [0.0, 1.0].
46
+ expected: Expected text that was searched for.
47
+ ocr_text: Last OCR'd screen text observed.
48
+ elapsed: Total time spent polling, in seconds.
49
+ captures: Any screenshot files saved during polling.
50
+ """
51
+
52
+ matched: bool
53
+ score: float
54
+ expected: str
55
+ ocr_text: str
56
+ elapsed: float
57
+ captures: list[Path] = field(default_factory=list)
58
+
59
+
60
+ def fuzzy_score(
61
+ expected: str,
62
+ actual: str,
63
+ *,
64
+ case_sensitive: bool = False,
65
+ ) -> float:
66
+ """Return a substring-aware fuzzy similarity score in [0.0, 1.0].
67
+
68
+ Uses ``rapidfuzz.fuzz.partial_ratio`` when available (handles substring
69
+ matches and OCR character-level errors). Falls back to a ``difflib``
70
+ ``SequenceMatcher`` sliding window if rapidfuzz isn't installed.
71
+ """
72
+ if not expected:
73
+ return 1.0
74
+ if not actual:
75
+ return 0.0
76
+ e, a = (expected, actual) if case_sensitive else (expected.lower(), actual.lower())
77
+
78
+ if _HAVE_RAPIDFUZZ:
79
+ return _fuzz.partial_ratio(e, a) / 100.0
80
+
81
+ # Fallback: sliding window of len(expected) over actual
82
+ elen = len(e)
83
+ if elen >= len(a):
84
+ return difflib.SequenceMatcher(None, e, a).ratio()
85
+ best = 0.0
86
+ for i in range(len(a) - elen + 1):
87
+ chunk = a[i : i + elen]
88
+ r = difflib.SequenceMatcher(None, e, chunk).ratio()
89
+ best = max(best, r)
90
+ if best >= 1.0:
91
+ break
92
+ return best
93
+
94
+
95
+ class ScreenshotClient:
96
+ """Client for /api/streamer/snapshot + OCR.
97
+
98
+ Reads ``headers``, ``hostname``, ``schema``, and ``certificate_trusted``
99
+ from the passed ``PiKVM`` instance and calls the module-level
100
+ ``requests.get`` directly (matching pikvm-lib's own pattern — see the
101
+ module comment block at the top of this file).
102
+ """
103
+
104
+ def __init__(self, pikvm: PiKVM) -> None:
105
+ self._headers = pikvm.headers
106
+ self._base = f"{pikvm.schema}://{pikvm.hostname}"
107
+ self._verify = pikvm.certificate_trusted
108
+
109
+ def capture(self, *, ocr: bool = False) -> bytes:
110
+ """Fetch a screenshot via ``/api/streamer/snapshot``.
111
+
112
+ With ``ocr=True`` the response Content-Type is ``text/plain`` (the
113
+ kvmd OCR result); otherwise it is ``image/jpeg`` binary data.
114
+ """
115
+ params: dict[str, str] = {}
116
+ params["allow_offline"] = "1"
117
+ if ocr:
118
+ params["ocr"] = "true"
119
+ resp = requests.get(
120
+ f"{self._base}/api/streamer/snapshot",
121
+ params=params,
122
+ headers=self._headers,
123
+ verify=self._verify,
124
+ timeout=30,
125
+ )
126
+ resp.raise_for_status()
127
+ return resp.content
128
+
129
+ def capture_to(self, path: Path | str) -> Path:
130
+ """Capture and save to disk. Returns the resolved ``Path``.
131
+
132
+ Missing parent directories are created automatically.
133
+ """
134
+ if not path:
135
+ raise ValueError("capture_to() requires a non-empty path")
136
+ p = Path(path)
137
+ p.parent.mkdir(parents=True, exist_ok=True)
138
+ p.write_bytes(self.capture())
139
+ return p
140
+
141
+ def capture_text(self) -> str:
142
+ """Capture the screen and return the OCR'd text."""
143
+ return self.capture(ocr=True).decode("utf-8", errors="replace")
144
+
145
+ def wait_for_text(
146
+ self,
147
+ expected: str,
148
+ *,
149
+ threshold: float = 0.9,
150
+ timeout: float = 60.0,
151
+ interval: float = 1.0,
152
+ capture_dir: Path | None = None,
153
+ case_sensitive: bool = False,
154
+ ) -> ScreenMatch:
155
+ """Poll OCR until fuzzy_score(expected, screen) >= threshold or timeout.
156
+
157
+ Returns a ``ScreenMatch`` with the ``matched`` flag, final score, the
158
+ last OCR text observed, total elapsed seconds, and any screenshot
159
+ files saved to ``capture_dir``.
160
+ """
161
+ if not expected:
162
+ raise ValueError("wait_for_text() requires non-empty expected text")
163
+ if not 0.0 <= threshold <= 1.0:
164
+ raise ValueError(f"threshold must be in [0.0, 1.0], got {threshold}")
165
+ if timeout < 0:
166
+ raise ValueError(f"timeout must be non-negative, got {timeout}")
167
+ if interval <= 0:
168
+ raise ValueError(f"interval must be positive, got {interval}")
169
+ start = time.monotonic()
170
+ deadline = start + timeout
171
+ captures: list[Path] = []
172
+ attempt = 0
173
+
174
+ while True:
175
+ attempt += 1
176
+ try:
177
+ text = self.capture_text()
178
+ except requests.RequestException:
179
+ text = ""
180
+ score = fuzzy_score(expected, text, case_sensitive=case_sensitive)
181
+
182
+ if capture_dir is not None:
183
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
184
+ p = Path(capture_dir) / f"{stamp}-{attempt:03d}.jpeg"
185
+ try:
186
+ self.capture_to(p)
187
+ captures.append(p)
188
+ except requests.RequestException:
189
+ pass
190
+
191
+ if score >= threshold:
192
+ return ScreenMatch(
193
+ matched=True,
194
+ score=score,
195
+ expected=expected,
196
+ ocr_text=text,
197
+ elapsed=time.monotonic() - start,
198
+ captures=captures,
199
+ )
200
+
201
+ if time.monotonic() >= deadline:
202
+ return ScreenMatch(
203
+ matched=False,
204
+ score=score,
205
+ expected=expected,
206
+ ocr_text=text,
207
+ elapsed=time.monotonic() - start,
208
+ captures=captures,
209
+ )
210
+ time.sleep(interval)
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, ClassVar
5
+
6
+ from pikvm_lib.pikvm import PiKVM
7
+ from pydantic import Field
8
+ from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource
9
+
10
+
11
+ class PiKVMSettings(BaseSettings):
12
+ """Settings for connecting to a PiKVM device.
13
+
14
+ Supports three configuration sources (highest priority first):
15
+ 1. Direct kwargs (CLI flag overrides)
16
+ 2. PIKVM_* environment variables
17
+ 3. Config file at ~/.config/pikvm-auto/config.toml
18
+ """
19
+
20
+ _toml_path: ClassVar[Path] = Path.home() / ".config" / "pikvm-auto" / "config.toml"
21
+
22
+ model_config = SettingsConfigDict(
23
+ env_prefix="PIKVM_",
24
+ )
25
+
26
+ host: str
27
+ user: str = "admin"
28
+ password: str
29
+ schema_: str = Field("https", alias="PIKVM_SCHEMA", validation_alias="PIKVM_SCHEMA")
30
+ cert_trusted: bool = False
31
+
32
+ @classmethod
33
+ def settings_customise_sources(
34
+ cls,
35
+ settings_cls: type[BaseSettings],
36
+ init_settings: PydanticBaseSettingsSource,
37
+ env_settings: PydanticBaseSettingsSource,
38
+ dotenv_settings: PydanticBaseSettingsSource,
39
+ file_secret_settings: PydanticBaseSettingsSource,
40
+ **kwargs: Any,
41
+ ) -> tuple[PydanticBaseSettingsSource, ...]:
42
+ """Customise settings sources to include TOML config file.
43
+
44
+ Priority (highest to lowest):
45
+ 1. init_settings (direct kwargs / CLI overrides)
46
+ 2. env_settings (PIKVM_* environment variables)
47
+ 3. TOML config file (~/.config/pikvm-auto/config.toml)
48
+ """
49
+ toml_source = TomlConfigSettingsSource(
50
+ settings_cls,
51
+ toml_file=cls._toml_path,
52
+ )
53
+ return init_settings, env_settings, toml_source
54
+
55
+ def create_client(self) -> PiKVM:
56
+ """Create a PiKVM client instance from the current settings."""
57
+ return PiKVM(
58
+ hostname=self.host,
59
+ username=self.user,
60
+ password=self.password,
61
+ schema=self.schema_,
62
+ cert_trusted=self.cert_trusted,
63
+ )
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from importlib import metadata
8
+
9
+
10
+ @dataclass
11
+ class _Variable:
12
+ """Dataclass describing an environment variable."""
13
+
14
+ name: str
15
+ """Variable name."""
16
+ value: str
17
+ """Variable value."""
18
+
19
+
20
+ @dataclass
21
+ class _Package:
22
+ """Dataclass describing a Python package."""
23
+
24
+ name: str
25
+ """Package name."""
26
+ version: str
27
+ """Package version."""
28
+
29
+
30
+ @dataclass
31
+ class _Environment:
32
+ """Dataclass to store environment information."""
33
+
34
+ interpreter_name: str
35
+ """Python interpreter name."""
36
+ interpreter_version: str
37
+ """Python interpreter version."""
38
+ interpreter_path: str
39
+ """Path to Python executable."""
40
+ platform: str
41
+ """Operating System."""
42
+ packages: list[_Package]
43
+ """Installed packages."""
44
+ variables: list[_Variable]
45
+ """Environment variables."""
46
+
47
+
48
+ def _interpreter_name_version() -> tuple[str, str]:
49
+ if hasattr(sys, "implementation"):
50
+ impl = sys.implementation.version
51
+ version = f"{impl.major}.{impl.minor}.{impl.micro}"
52
+ kind = impl.releaselevel
53
+ if kind != "final":
54
+ version += kind[0] + str(impl.serial)
55
+ return sys.implementation.name, version
56
+ return "", "0.0.0"
57
+
58
+
59
+ def _get_version(dist: str = "pikvm-auto") -> str:
60
+ """Get version of the given distribution.
61
+
62
+ Parameters:
63
+ dist: A distribution name.
64
+
65
+ Returns:
66
+ A version number.
67
+ """
68
+ try:
69
+ return metadata.version(dist)
70
+ except metadata.PackageNotFoundError:
71
+ return "0.0.0"
72
+
73
+
74
+ def _get_debug_info() -> _Environment:
75
+ """Get debug/environment information.
76
+
77
+ Returns:
78
+ Environment information.
79
+ """
80
+ py_name, py_version = _interpreter_name_version()
81
+ packages = ["pikvm-auto"]
82
+ variables = ["PYTHONPATH", *[var for var in os.environ if var.startswith("PIKVM_AUTO")]]
83
+ return _Environment(
84
+ interpreter_name=py_name,
85
+ interpreter_version=py_version,
86
+ interpreter_path=sys.executable,
87
+ platform=platform.platform(),
88
+ variables=[_Variable(var, val) for var in variables if (val := os.getenv(var))],
89
+ packages=[_Package(pkg, _get_version(pkg)) for pkg in packages],
90
+ )
91
+
92
+
93
+ def _print_debug_info() -> None:
94
+ """Print debug/environment information."""
95
+ info = _get_debug_info()
96
+ print(f"- __System__: {info.platform}")
97
+ print(f"- __Python__: {info.interpreter_name} {info.interpreter_version} ({info.interpreter_path})")
98
+ print("- __Environment variables__:")
99
+ for var in info.variables:
100
+ print(f" - `{var.name}`: `{var.value}`")
101
+ print("- __Installed packages__:")
102
+ for pkg in info.packages:
103
+ print(f" - `{pkg.name}` v{pkg.version}")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ _print_debug_info()
pikvm_auto/py.typed ADDED
File without changes
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: pikvm-auto
3
+ Version: 0.3.0
4
+ Summary: pikvmautomation, library, and ansible modules
5
+ Author-Email: KettleOfKetchup <kettleofketchup@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Documentation
19
+ Classifier: Topic :: Software Development
20
+ Classifier: Topic :: Utilities
21
+ Classifier: Typing :: Typed
22
+ Project-URL: Homepage, https://kettleofketchup.github.io/pikvm-auto
23
+ Project-URL: Documentation, https://kettleofketchup.github.io/pikvm-auto
24
+ Project-URL: Changelog, https://kettleofketchup.github.io/pikvm-auto/changelog
25
+ Project-URL: Repository, https://github.com/kettleofketchup/pikvm-auto
26
+ Project-URL: Issues, https://github.com/kettleofketchup/pikvm-auto/issues
27
+ Project-URL: Discussions, https://github.com/kettleofketchup/pikvm-auto/discussions
28
+ Project-URL: Gitter, https://gitter.im/pikvm-auto/community
29
+ Project-URL: Funding, https://github.com/sponsors/kettleofketchup
30
+ Requires-Python: >=3.10
31
+ Requires-Dist: pikvm-lib>=0.5.0
32
+ Requires-Dist: pydantic-settings>=2.13.1
33
+ Requires-Dist: rapidfuzz>=3.0
34
+ Description-Content-Type: text/markdown
35
+
36
+ # pikvm-auto
37
+
38
+ [![ci](https://github.com/kettleofketchup/pikvm-auto/workflows/ci/badge.svg)](https://github.com/kettleofketchup/pikvm-auto/actions?query=workflow%3Aci)
39
+ [![documentation](https://img.shields.io/badge/docs-zensical-FF9100.svg?style=flat)](https://kettleofketchup.github.io/pikvm-auto/)
40
+ [![pypi version](https://img.shields.io/pypi/v/pikvm-auto.svg)](https://pypi.org/project/pikvm-auto/)
41
+ [![gitter](https://img.shields.io/badge/matrix-chat-4DB798.svg?style=flat)](https://app.gitter.im/#/room/#pikvm-auto:gitter.im)
42
+
43
+ pikvmautomation, library, and ansible modules
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install pikvm-auto
49
+ ```
50
+
51
+ With [`uv`](https://docs.astral.sh/uv/):
52
+
53
+ ```bash
54
+ uv tool install pikvm-auto
55
+ ```
@@ -0,0 +1,16 @@
1
+ pikvm_auto-0.3.0.dist-info/METADATA,sha256=0g4SEswEnwP85kL_WwuPBvgxZhIN-2vctfYglhmumY0,2299
2
+ pikvm_auto-0.3.0.dist-info/WHEEL,sha256=Z36eTX6lG3PITRleSd5hAZHCcz52yg3c0JQVxKBbLW0,90
3
+ pikvm_auto-0.3.0.dist-info/entry_points.txt,sha256=BuScwF5RTJuJiCxhp04Dnc1XZv5FJRGEl1yr_Cdb1xE,77
4
+ pikvm_auto-0.3.0.dist-info/licenses/LICENSE,sha256=TRD-XzqhdrBbIpokiGa61wuDTBc_ElKoFP9HSNihODc,10255
5
+ pikvm_auto/__init__.py,sha256=Vg1eEwVNOYv6jbxlm4NQe_XcbV3R3TBZWarBlD7uE9A,747
6
+ pikvm_auto/__main__.py,sha256=23pOM6rlCbkun7mcyocHQIs1Rd-VyBl8ygfJFID0qqY,355
7
+ pikvm_auto/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pikvm_auto/_internal/cli.py,sha256=0EkSG-bt5LeYseHrJxWsHNlmuiwXEjXESWHIjcGosPQ,3166
9
+ pikvm_auto/_internal/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ pikvm_auto/_internal/commands/hid.py,sha256=P-x2QDMZkG1IJMjZ8zhhDGxKIWUun4PeSAioYNfEIU8,10077
11
+ pikvm_auto/_internal/commands/info.py,sha256=_7UZrJVz9W7HgbHy8c3B8pmtpOifIeOajHvnO8MEIG8,642
12
+ pikvm_auto/_internal/commands/screenshot.py,sha256=zccQc49o9KvXn7q6fRiDI4K3Q7tC19S26hn6VkIDIWI,6959
13
+ pikvm_auto/_internal/config.py,sha256=uAjj_L739Z_g5NoY6LHWqZGocdppYKP57ybVqndXpwQ,2096
14
+ pikvm_auto/_internal/debug.py,sha256=pqnDwBccezFGXAq2c_hQWtjX2FUv6b7mE26az_U1yK4,2818
15
+ pikvm_auto/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ pikvm_auto-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.8)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ pikvm-auto = pikvm_auto._internal.cli:main
3
+
4
+ [gui_scripts]
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.