Datasets:
Download input_monitor.py from bshepp/cat-keyboard-corpus: direct link, hf CLI and curl.
- Browser
- Download file 7.58 kB
-
https://huggingface.co/datasets/bshepp/cat-keyboard-corpus/resolve/main/input_monitor.py
- Command line
-
hf download hf://datasets/bshepp/cat-keyboard-corpus/input_monitor.py
-
curl -L -o input_monitor.py https://huggingface.co/datasets/bshepp/cat-keyboard-corpus/resolve/main/input_monitor.py
7.58 kB
| #!/usr/bin/env python3 | |
| """Content-free input monitor for the cat keyboard corpus. | |
| Watches the laptop's keyboard, the Dell hotkeys and the trackpad through evdev (read-only, never grabbed, so normal | |
| typing and pointing are unaffected) and records **timing and non-content events only**. It is built so it *cannot* | |
| write what was typed: | |
| - Character keys (letters, digits, punctuation, Space, Tab, Backspace) are logged as a keystroke with the key | |
| identity set to null. You get the time and the fact that a key moved, never which one. | |
| - Non-character keys carry no content, so their name is kept: the modifiers, the arrows, the navigation cluster, | |
| the function keys, Esc, Caps/Num/Scroll Lock, Enter, and the Dell/media hotkeys. The allowlist is ALLOW below; | |
| a code not in it is logged as null, so a mistake fails safe (drops identity) rather than leaking it. | |
| - The trackpad gives touch down/lift, button presses, and per-gesture movement summarised as a contact count and | |
| a bounding box (a paw covers a large box and many contacts; a fingertip a small one). No absolute position of | |
| anything typed, because nothing typed is read here. | |
| Three content levels (--content): | |
| timing - every key event is {t, ev, dev, key: null}: pure rhythm, no identity at all, even for non-char keys. | |
| nonchar - (default) non-char keys keep their name; character keys are null. Trackpad as above. | |
| (there is deliberately no level that records character identities.) | |
| Output: one JSONL per UTC day under ~/data/input_events/ (PRIVATE, under ~/data, never committed; the public corpus | |
| messages.jsonl is promoted from it by hand). Nothing is uploaded. | |
| Needs read access to /dev/input/event* (group `input`): either run under sudo, or the owner adds the account once | |
| with `sudo usermod -aG input tempest` and re-logs-in. Devices are matched by NAME, never by event number. | |
| venv/bin/python investigations/cat_keyboard_corpus/input_monitor.py # nonchar, ~/data/input_events/ | |
| venv/bin/python investigations/cat_keyboard_corpus/input_monitor.py --content timing | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import selectors | |
| import sys | |
| import time | |
| try: | |
| import evdev | |
| from evdev import ecodes | |
| except ImportError: | |
| sys.exit("python-evdev is not installed. In the data_logger venv: uv pip install evdev") | |
| # Devices to watch, by name substring (never by event index). | |
| WANT = ("AT Translated Set 2 keyboard", "Dell WMI hotkeys", "AlpsPS/2 ALPS GlidePoint") | |
| # Non-character keys: content-free, so their identity is kept. Everything else -> logged as null. | |
| def _codes(*names): | |
| out = set() | |
| for n in names: | |
| c = getattr(ecodes, n, None) | |
| if isinstance(c, int): | |
| out.add(c) | |
| return out | |
| ALLOW = _codes( | |
| "KEY_LEFTSHIFT", "KEY_RIGHTSHIFT", "KEY_LEFTCTRL", "KEY_RIGHTCTRL", | |
| "KEY_LEFTALT", "KEY_RIGHTALT", "KEY_LEFTMETA", "KEY_RIGHTMETA", | |
| "KEY_UP", "KEY_DOWN", "KEY_LEFT", "KEY_RIGHT", | |
| "KEY_HOME", "KEY_END", "KEY_PAGEUP", "KEY_PAGEDOWN", "KEY_INSERT", | |
| "KEY_ESC", "KEY_CAPSLOCK", "KEY_NUMLOCK", "KEY_SCROLLLOCK", "KEY_ENTER", "KEY_KPENTER", | |
| "KEY_SYSRQ", "KEY_PAUSE", "KEY_MENU", "KEY_COMPOSE", | |
| *[f"KEY_F{i}" for i in range(1, 25)], | |
| # media / Dell hotkeys (content-free) | |
| "KEY_MUTE", "KEY_VOLUMEUP", "KEY_VOLUMEDOWN", "KEY_BRIGHTNESSUP", "KEY_BRIGHTNESSDOWN", | |
| "KEY_PLAYPAUSE", "KEY_NEXTSONG", "KEY_PREVIOUSSONG", "KEY_STOPCD", | |
| "KEY_WLAN", "KEY_RFKILL", "KEY_SWITCHVIDEOMODE", "KEY_KBDILLUMTOGGLE", | |
| "KEY_TOUCHPAD_TOGGLE", "KEY_TOUCHPAD_ON", "KEY_TOUCHPAD_OFF", | |
| ) | |
| EV_VAL = {0: "up", 1: "down", 2: "repeat"} | |
| def open_devices(): | |
| devs = [] | |
| for path in evdev.list_devices(): | |
| try: | |
| d = evdev.InputDevice(path) | |
| except OSError: | |
| continue | |
| if any(w in d.name for w in WANT): | |
| devs.append(d) | |
| return devs | |
| class Pad: | |
| """Collapses trackpad motion into gesture summaries so no continuous stream is written.""" | |
| def __init__(self): | |
| self.touching = False | |
| self.slots = 0 | |
| self.xmin = self.ymin = 10 ** 9 | |
| self.xmax = self.ymax = -10 ** 9 | |
| self.moves = 0 | |
| self.t0 = None | |
| def reset(self): | |
| self.slots = 0 | |
| self.xmin = self.ymin = 10 ** 9 | |
| self.xmax = self.ymax = -10 ** 9 | |
| self.moves = 0 | |
| self.t0 = None | |
| def feed(self, e, emit): | |
| if e.type == ecodes.EV_KEY and e.code in (ecodes.BTN_LEFT, ecodes.BTN_RIGHT, ecodes.BTN_MIDDLE): | |
| emit({"dev": "pad", "ev": "btn_%s" % {ecodes.BTN_LEFT: "left", ecodes.BTN_RIGHT: "right", | |
| ecodes.BTN_MIDDLE: "mid"}[e.code] + ("_down" if e.value else "_up")}) | |
| return | |
| if e.type == ecodes.EV_KEY and e.code == ecodes.BTN_TOUCH: | |
| if e.value: | |
| self.touching = True | |
| self.reset() | |
| self.t0 = time.time() | |
| elif self.touching: | |
| self.touching = False | |
| emit({"dev": "pad", "ev": "gesture", | |
| "dur_ms": round((time.time() - (self.t0 or time.time())) * 1000), | |
| "contacts": self.slots + 1, "moves": self.moves, | |
| "box": [max(0, self.xmax - self.xmin), max(0, self.ymax - self.ymin)] if self.moves else [0, 0]}) | |
| return | |
| if e.type == ecodes.EV_ABS: | |
| if e.code == ecodes.ABS_MT_SLOT: | |
| self.slots = max(self.slots, e.value) | |
| elif e.code in (ecodes.ABS_MT_POSITION_X, ecodes.ABS_X): | |
| self.xmin = min(self.xmin, e.value); self.xmax = max(self.xmax, e.value); self.moves += 1 | |
| elif e.code in (ecodes.ABS_MT_POSITION_Y, ecodes.ABS_Y): | |
| self.ymin = min(self.ymin, e.value); self.ymax = max(self.ymax, e.value) | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("--content", choices=("timing", "nonchar"), default="nonchar") | |
| ap.add_argument("-o", "--out", default=os.path.expanduser("~/data/input_events")) | |
| a = ap.parse_args() | |
| os.makedirs(a.out, exist_ok=True) | |
| devs = open_devices() | |
| if not devs: | |
| sys.exit("no target input devices found (need group `input`: run under sudo or add the account to it)") | |
| sys.stderr.write("watching: " + ", ".join(repr(d.name) for d in devs) + "\n") | |
| sel = selectors.DefaultSelector() | |
| for d in devs: | |
| sel.register(d, selectors.EVENT_READ) | |
| pad = Pad() | |
| fh = {"day": None, "f": None} | |
| def emit(rec): | |
| now = time.time() | |
| day = time.strftime("%Y-%m-%d", time.gmtime(now)) | |
| if day != fh["day"]: | |
| if fh["f"]: | |
| fh["f"].close() | |
| fh["f"] = open(os.path.join(a.out, day + ".jsonl"), "a") | |
| fh["day"] = day | |
| rec = {"t": round(now, 3), **rec} | |
| fh["f"].write(json.dumps(rec) + "\n") | |
| fh["f"].flush() | |
| try: | |
| while True: | |
| for key, _ in sel.select(): | |
| for e in key.fileobj.read(): | |
| if e.type == ecodes.EV_KEY and e.code < ecodes.BTN_MISC: # a keyboard key | |
| name = ecodes.KEY.get(e.code) | |
| keep = a.content == "nonchar" and e.code in ALLOW | |
| emit({"dev": "kbd", "ev": EV_VAL.get(e.value, str(e.value)), | |
| "key": (name if keep else None)}) | |
| else: | |
| pad.feed(e, emit) | |
| except KeyboardInterrupt: | |
| pass | |
| finally: | |
| if fh["f"]: | |
| fh["f"].close() | |
| if __name__ == "__main__": | |
| main() | |