caught-you-looking 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,2 @@
1
+ def main() -> None:
2
+ print("Hello from caught-you-looking!")
File without changes
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ import cv2
6
+ from mediapipe.tasks.python.vision.face_landmarker import (
7
+ FaceLandmarker,
8
+ )
9
+
10
+ from caught_you_looking.vision.detection import collect_samples
11
+ from caught_you_looking.vision.headpose import HeadPose
12
+
13
+
14
+ @dataclass
15
+ class MonitorCalibration:
16
+ name: str
17
+ pose: HeadPose
18
+
19
+ @classmethod
20
+ def calibrate(
21
+ cls,
22
+ name: str,
23
+ camera: cv2.VideoCapture,
24
+ landmarker: FaceLandmarker,
25
+ duration: float = 2.0,
26
+ ) -> MonitorCalibration:
27
+ input(f"Look at the center of your monitor {name} and press Enter")
28
+
29
+ poses = collect_samples(camera, landmarker, duration)
30
+
31
+ pose = HeadPose.average_pose(poses)
32
+
33
+ return cls(name, pose)
34
+
35
+ def __str__(self) -> str:
36
+ return f"Name: {self.name}, Pose: {self.pose}"
37
+
38
+
39
+ def find_closest_monitor(
40
+ current_pose: HeadPose, calibrations: list[MonitorCalibration]
41
+ ) -> MonitorCalibration:
42
+ if not calibrations:
43
+ raise ValueError("Cannot get minimum without calibrations")
44
+
45
+ return min(
46
+ calibrations, key=lambda calibration: current_pose.distance_to(calibration.pose)
47
+ )
48
+
49
+
50
+ def calibrate_monitors(
51
+ monitors: list[str],
52
+ camera: cv2.VideoCapture,
53
+ landmarker: FaceLandmarker,
54
+ duration: float = 2.0,
55
+ ) -> list[MonitorCalibration]:
56
+ return [
57
+ MonitorCalibration.calibrate(name, camera, landmarker, duration)
58
+ for name in monitors
59
+ ]
@@ -0,0 +1,29 @@
1
+ import json
2
+ from dataclasses import asdict
3
+ from pathlib import Path
4
+
5
+ from caught_you_looking.vision.headpose import HeadPose
6
+
7
+ from .calibration import MonitorCalibration
8
+
9
+
10
+ def save_calibrations(path: Path, calibrations: list[MonitorCalibration]) -> None:
11
+ data = {"monitors": [asdict(calibration) for calibration in calibrations]}
12
+
13
+ path.parent.mkdir(parents=True, exist_ok=True)
14
+
15
+ with path.open("w", encoding="utf-8") as file:
16
+ json.dump(data, file, indent=4)
17
+
18
+
19
+ def load_calibrations(path: Path) -> list[MonitorCalibration]:
20
+ with path.open("r", encoding="utf-8") as file:
21
+ data = json.load(file)
22
+
23
+ return [
24
+ MonitorCalibration(
25
+ name=calibration["name"],
26
+ pose=HeadPose(**calibration["pose"]),
27
+ )
28
+ for calibration in data["monitors"]
29
+ ]
@@ -0,0 +1,65 @@
1
+ import re
2
+
3
+ import cv2
4
+ from mediapipe.tasks.python.vision.face_landmarker import (
5
+ FaceLandmarker,
6
+ )
7
+
8
+ from caught_you_looking.paths import get_calibration_path, get_calibrations_dir
9
+
10
+ from .calibration import (
11
+ MonitorCalibration,
12
+ calibrate_monitors,
13
+ )
14
+ from .persistence import load_calibrations, save_calibrations
15
+
16
+
17
+ def resolve_calibrations(
18
+ profile: str,
19
+ monitors: list[str],
20
+ camera: cv2.VideoCapture,
21
+ landmarker: FaceLandmarker,
22
+ *,
23
+ recalibrate: bool = False,
24
+ duration: float = 2.0,
25
+ ) -> list[MonitorCalibration]:
26
+ calibration_path = get_calibration_path(profile)
27
+
28
+ if recalibrate or not calibration_path.is_file():
29
+ calibrations = calibrate_monitors(monitors, camera, landmarker, duration)
30
+
31
+ save_calibrations(calibration_path, calibrations)
32
+
33
+ return calibrations
34
+
35
+ calibrations = load_calibrations(calibration_path)
36
+
37
+ if not calibration_matches(monitors, calibrations):
38
+ raise RuntimeError(
39
+ f"Connected monitors do not match profile `{profile}`. "
40
+ "Select another profile or use `--recalibrate`."
41
+ )
42
+
43
+ return calibrations
44
+
45
+
46
+ def list_profiles() -> list[str]:
47
+ directory = get_calibrations_dir()
48
+
49
+ return sorted(path.stem for path in directory.glob("*.json") if path.is_file())
50
+
51
+
52
+ def calibration_matches(
53
+ monitors: list[str], calibrations: list[MonitorCalibration]
54
+ ) -> bool:
55
+ calibrated = set({calibration.name for calibration in calibrations})
56
+ connected = set(monitors)
57
+ return calibrated == connected
58
+
59
+
60
+ def validate_profile_name(name: str) -> str:
61
+ match = re.fullmatch(r"[a-zA-Z0-9_-]+", name)
62
+ if match:
63
+ return match.group()
64
+ else:
65
+ raise ValueError("Profile name is invalid")
@@ -0,0 +1,71 @@
1
+ import argparse
2
+ from argparse import ArgumentTypeError
3
+ from math import isfinite
4
+
5
+ from caught_you_looking.calibration.profiles import validate_profile_name
6
+
7
+
8
+ def parse_args() -> argparse.Namespace:
9
+ parser = argparse.ArgumentParser(
10
+ prog="cyl",
11
+ description="Automatically focuses monitors based on head orientation",
12
+ )
13
+
14
+ parser.add_argument(
15
+ "--recalibrate", action="store_true", help="Force monitor recalibration"
16
+ )
17
+
18
+ parser.add_argument(
19
+ "--dwell-time", type=float, default=0.6, help="Required dwell time in seconds"
20
+ )
21
+
22
+ parser.add_argument(
23
+ "--duration",
24
+ type=float,
25
+ default=2.0,
26
+ help="Required time for monitor calibration",
27
+ )
28
+
29
+ parser.add_argument(
30
+ "--window-size",
31
+ type=int,
32
+ default=5,
33
+ help="Number of head pose samples used for smoothing",
34
+ )
35
+
36
+ parser.add_argument(
37
+ "--profile",
38
+ type=validate_profile_name,
39
+ default="default",
40
+ help="Calibration profile to use",
41
+ )
42
+
43
+ parser.add_argument(
44
+ "--list-profiles",
45
+ action="store_true",
46
+ help="List available calibration profiles",
47
+ )
48
+
49
+ parser.add_argument(
50
+ "--preview",
51
+ action="store_true",
52
+ help="Opens a preview window displaying the captured video",
53
+ )
54
+
55
+ parser.add_argument(
56
+ "--socket-timeout",
57
+ type=validate_socket_timeout,
58
+ default=2.0,
59
+ help="Hyprland socket connection timeout in seconds",
60
+ )
61
+
62
+ return parser.parse_args()
63
+
64
+
65
+ def validate_socket_timeout(value: str) -> float:
66
+ socket_timeout = float(value)
67
+
68
+ if socket_timeout <= 0 or not isfinite(socket_timeout):
69
+ raise ArgumentTypeError("Socket timeout must be positive and finite")
70
+
71
+ return socket_timeout
File without changes
@@ -0,0 +1,32 @@
1
+ import json
2
+ import subprocess
3
+ from typing import Any
4
+
5
+
6
+ def _call_monitors_cmd() -> list[dict[str, Any]]:
7
+ result = subprocess.run(
8
+ ["hyprctl", "monitors", "-j"],
9
+ capture_output=True,
10
+ text=True,
11
+ check=True,
12
+ )
13
+
14
+ return json.loads(result.stdout)
15
+
16
+
17
+ def get_monitors() -> list[str]:
18
+ monitors = _call_monitors_cmd()
19
+
20
+ return [monitor["name"] for monitor in monitors]
21
+
22
+
23
+ def get_focused_monitor() -> str | None:
24
+ monitors = _call_monitors_cmd()
25
+ return next((monitor["name"] for monitor in monitors if monitor["focused"]), None)
26
+
27
+
28
+ def focus_monitor(name: str) -> None:
29
+ subprocess.run(
30
+ ["hyprctl", "dispatch", f'hl.dsp.focus({{ monitor = "{name}" }})'],
31
+ check=True,
32
+ )
@@ -0,0 +1,12 @@
1
+ def parse_focused_monitor_event(event: str) -> str | None:
2
+ event_name, separator, remaining = event.partition(">>")
3
+
4
+ if not separator or event_name != "focusedmon":
5
+ return None
6
+
7
+ monitor_name, separator, _ = remaining.partition(",")
8
+
9
+ if not separator or not monitor_name:
10
+ return None
11
+
12
+ return monitor_name
@@ -0,0 +1,135 @@
1
+ import os
2
+ import socket
3
+ from pathlib import Path
4
+ from queue import Empty, Queue
5
+ from threading import Event, Thread
6
+ from types import TracebackType
7
+ from typing import Self
8
+
9
+ from .events import parse_focused_monitor_event
10
+
11
+
12
+ class HyprlandEventListener:
13
+ def __init__(self, socket_timeout: float = 2.0) -> None:
14
+ self._events: Queue[str] = Queue()
15
+ self._errors: Queue[Exception] = Queue()
16
+
17
+ self._stop_event = Event()
18
+ self._ready_event = Event()
19
+
20
+ self._thread: Thread | None = None
21
+
22
+ self._socket_timeout: float = socket_timeout
23
+
24
+ def __enter__(self) -> Self:
25
+ self.start()
26
+ return self
27
+
28
+ def __exit__(
29
+ self,
30
+ exc_type: type[BaseException] | None,
31
+ exc_value: BaseException | None,
32
+ traceback: TracebackType | None,
33
+ ) -> None:
34
+ self.stop()
35
+
36
+ if exc_type is None:
37
+ self.raise_if_failed()
38
+
39
+ def _listen(self) -> None:
40
+ try:
41
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
42
+ connection.settimeout(self._socket_timeout)
43
+ connection.connect(str(get_event_socket_path()))
44
+
45
+ connection.settimeout(0.5)
46
+
47
+ self._ready_event.set()
48
+
49
+ buffer = b""
50
+
51
+ while not self._stop_event.is_set():
52
+ try:
53
+ data = connection.recv(4096)
54
+ except TimeoutError:
55
+ continue
56
+
57
+ if not data:
58
+ if not self._stop_event.is_set():
59
+ raise ConnectionError("Hyprland event socket disconnected")
60
+ break
61
+
62
+ buffer += data
63
+
64
+ while b"\n" in buffer:
65
+ line, _, buffer = buffer.partition(b"\n")
66
+
67
+ monitor = parse_focused_monitor_event(line.decode("utf-8"))
68
+
69
+ if monitor is not None:
70
+ self._events.put(monitor)
71
+
72
+ except Exception as e: # noqa: BLE001
73
+ self._errors.put(e)
74
+ finally:
75
+ self._stop_event.set()
76
+
77
+ def drain_focus_events(self) -> str | None:
78
+ monitor = None
79
+ try:
80
+ while True:
81
+ monitor = self._events.get_nowait()
82
+ except Empty:
83
+ return monitor
84
+
85
+ def start(self) -> None:
86
+ if self._thread is not None:
87
+ raise RuntimeError("Event listener is already running")
88
+
89
+ self._thread = Thread(target=self._listen)
90
+
91
+ self._thread.start()
92
+
93
+ try:
94
+ if not self._ready_event.wait(timeout=self._socket_timeout + 1.0):
95
+ self.raise_if_failed()
96
+
97
+ raise TimeoutError("Couldn't connect to the Hyprland socket in time")
98
+
99
+ except BaseException:
100
+ self.stop()
101
+ raise
102
+
103
+ def stop(self) -> None:
104
+ self._stop_event.set()
105
+
106
+ if self._thread is not None:
107
+ self._thread.join()
108
+
109
+ def raise_if_failed(self) -> None:
110
+ try:
111
+ error = self._errors.get_nowait()
112
+ except Empty:
113
+ return
114
+
115
+ raise error
116
+
117
+ def is_running(self) -> bool:
118
+ return (
119
+ self._thread is not None
120
+ and self._thread.is_alive()
121
+ and not self._stop_event.is_set()
122
+ )
123
+
124
+
125
+ def get_event_socket_path() -> Path:
126
+ xdg_runtime = os.environ.get("XDG_RUNTIME_DIR")
127
+ hyprland_instance = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
128
+
129
+ if not xdg_runtime or not hyprland_instance:
130
+ raise RuntimeError("Hyprland environment is not available")
131
+
132
+ if not Path(xdg_runtime).is_absolute():
133
+ raise RuntimeError("Invalid XDG_RUNTIME_DIR")
134
+
135
+ return Path(xdg_runtime) / "hypr" / hyprland_instance / ".socket2.sock"
@@ -0,0 +1,51 @@
1
+ from caught_you_looking.calibration.profiles import list_profiles, resolve_calibrations
2
+ from caught_you_looking.cli import parse_args
3
+ from caught_you_looking.hyprland.commands import get_focused_monitor, get_monitors
4
+ from caught_you_looking.hyprland.listener import HyprlandEventListener
5
+ from caught_you_looking.tracking.runtime import run_tracking
6
+ from caught_you_looking.tracking.tracker import MonitorTracker
7
+ from caught_you_looking.vision.camera import open_camera
8
+ from caught_you_looking.vision.detection import create_landmarker
9
+
10
+
11
+ def main() -> None:
12
+ args = parse_args()
13
+
14
+ if args.list_profiles:
15
+ print_profiles()
16
+ return
17
+
18
+ with (
19
+ open_camera() as camera,
20
+ create_landmarker() as landmarker,
21
+ ):
22
+ monitors = get_monitors()
23
+
24
+ calibrations = resolve_calibrations(
25
+ args.profile,
26
+ monitors,
27
+ camera,
28
+ landmarker,
29
+ recalibrate=args.recalibrate,
30
+ duration=args.duration,
31
+ )
32
+
33
+ tracker = MonitorTracker(calibrations, args.window_size, args.dwell_time)
34
+
35
+ with HyprlandEventListener(socket_timeout=args.socket_timeout) as listener:
36
+ tracker.sync_focus(get_focused_monitor())
37
+
38
+ run_tracking(camera, landmarker, tracker, listener, args.preview)
39
+
40
+
41
+ def print_profiles() -> None:
42
+ profiles = list_profiles()
43
+
44
+ if not profiles:
45
+ print("No available profiles.")
46
+ else:
47
+ print(*profiles, sep="\n")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,28 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ def get_data_dir() -> Path:
6
+ fallback = Path.home() / ".local" / "share"
7
+ xdg = os.environ.get("XDG_DATA_HOME")
8
+
9
+ if xdg and Path(xdg).is_absolute():
10
+ return Path(xdg) / "cyl"
11
+
12
+ return fallback / "cyl"
13
+
14
+
15
+ def get_calibrations_dir() -> Path:
16
+ return get_data_dir() / "calibrations"
17
+
18
+
19
+ def get_model_dir() -> Path:
20
+ return get_data_dir() / "models"
21
+
22
+
23
+ def get_calibration_path(profile: str = "default") -> Path:
24
+ return get_calibrations_dir() / f"{profile}.json"
25
+
26
+
27
+ def get_model_path() -> Path:
28
+ return get_model_dir() / "face_landmarker.task"
File without changes
@@ -0,0 +1,44 @@
1
+ import cv2
2
+ from mediapipe.tasks.python.vision.face_landmarker import FaceLandmarker
3
+
4
+ from caught_you_looking.hyprland.commands import focus_monitor
5
+ from caught_you_looking.hyprland.listener import HyprlandEventListener
6
+ from caught_you_looking.vision.detection import detect_head_pose
7
+
8
+ from .tracker import MonitorTracker
9
+
10
+
11
+ def run_tracking(
12
+ camera: cv2.VideoCapture,
13
+ landmarker: FaceLandmarker,
14
+ tracker: MonitorTracker,
15
+ listener: HyprlandEventListener,
16
+ preview: bool = False,
17
+ ) -> None:
18
+ try:
19
+ while listener.is_running():
20
+ sucess, bgr_frame = camera.read()
21
+
22
+ if not sucess:
23
+ break
24
+
25
+ if preview:
26
+ cv2.imshow("HeadFocus", bgr_frame)
27
+
28
+ pose = detect_head_pose(bgr_frame, landmarker)
29
+
30
+ monitor = listener.drain_focus_events()
31
+
32
+ if monitor is not None:
33
+ tracker.sync_focus(monitor)
34
+
35
+ selected = tracker.update(pose)
36
+
37
+ if selected is not None:
38
+ focus_monitor(selected)
39
+ print(f"Selected monitor: {selected}")
40
+
41
+ if preview and cv2.waitKey(1) & 0xFF == ord("q"):
42
+ break
43
+ finally:
44
+ cv2.destroyAllWindows()
@@ -0,0 +1,74 @@
1
+ import time
2
+ from collections import deque
3
+
4
+ from caught_you_looking.calibration.calibration import (
5
+ MonitorCalibration,
6
+ find_closest_monitor,
7
+ )
8
+ from caught_you_looking.vision.headpose import HeadPose
9
+
10
+
11
+ class MonitorTracker:
12
+ def __init__(
13
+ self,
14
+ calibrations: list[MonitorCalibration],
15
+ window_size: int = 5,
16
+ dwell_time: float = 0.6,
17
+ ) -> None:
18
+ if not calibrations:
19
+ raise ValueError("At least one calibrations is required")
20
+
21
+ if window_size < 1:
22
+ raise ValueError("Window size must be positive")
23
+
24
+ if dwell_time < 0:
25
+ raise ValueError("Dwell time must not be negative")
26
+
27
+ self.calibrations = calibrations
28
+ self.current_monitor: str | None = None
29
+ self.candidate_monitor: str | None = None
30
+ self.candidate_since = 0.0
31
+ self.dwell_time = dwell_time
32
+ self.samples: deque[HeadPose] = deque(maxlen=window_size)
33
+
34
+ def update(self, pose: HeadPose | None) -> str | None:
35
+ if pose is not None:
36
+ self.samples.append(pose)
37
+
38
+ avg_over_samples = HeadPose.average_pose(self.samples)
39
+
40
+ closest = find_closest_monitor(avg_over_samples, self.calibrations)
41
+
42
+ if closest.name == self.current_monitor:
43
+ self._reset_candidates()
44
+
45
+ return None
46
+
47
+ elif closest.name != self.candidate_monitor:
48
+ self.candidate_monitor = closest.name
49
+ self.candidate_since = time.monotonic()
50
+
51
+ return None
52
+
53
+ elif time.monotonic() - self.candidate_since >= self.dwell_time:
54
+ self.current_monitor = self.candidate_monitor
55
+ self._reset_candidates()
56
+
57
+ return self.current_monitor
58
+
59
+ else:
60
+ self.samples.clear()
61
+ self._reset_candidates()
62
+
63
+ return None
64
+
65
+ def _reset_candidates(self) -> None:
66
+ self.candidate_monitor = None
67
+ self.candidate_since = 0.0
68
+
69
+ def sync_focus(self, monitor: str | None) -> None:
70
+ if self.current_monitor == monitor:
71
+ return
72
+
73
+ self.current_monitor = monitor
74
+ self._reset_candidates()
File without changes
File without changes
@@ -0,0 +1,17 @@
1
+ from collections.abc import Iterator
2
+ from contextlib import contextmanager
3
+
4
+ import cv2
5
+
6
+
7
+ @contextmanager
8
+ def open_camera(device: int = 0) -> Iterator[cv2.VideoCapture]:
9
+ camera = cv2.VideoCapture(device)
10
+ try:
11
+ if not camera.isOpened():
12
+ raise RuntimeError("Could not open camera")
13
+
14
+ yield camera
15
+ finally:
16
+ camera.release()
17
+ cv2.destroyAllWindows()
@@ -0,0 +1,68 @@
1
+ import time
2
+
3
+ import cv2
4
+ import mediapipe as mp
5
+ import numpy as np
6
+ from mediapipe.tasks.python import BaseOptions
7
+ from mediapipe.tasks.python.vision import RunningMode
8
+ from mediapipe.tasks.python.vision.face_landmarker import (
9
+ FaceLandmarker,
10
+ FaceLandmarkerOptions,
11
+ )
12
+
13
+ from .headpose import HeadPose
14
+ from .models import ensure_model
15
+
16
+
17
+ def create_landmarker():
18
+ model_path = ensure_model()
19
+
20
+ options = FaceLandmarkerOptions(
21
+ base_options=BaseOptions(model_asset_path=str(model_path)),
22
+ running_mode=RunningMode.VIDEO,
23
+ num_faces=1,
24
+ output_facial_transformation_matrixes=True,
25
+ )
26
+
27
+ return FaceLandmarker.create_from_options(options)
28
+
29
+
30
+ def to_mediapipe_image(frame: np.ndarray) -> mp.Image:
31
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
32
+
33
+ return mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_frame)
34
+
35
+
36
+ def collect_samples(
37
+ camera: cv2.VideoCapture, landmarker: FaceLandmarker, duration: float = 2.0
38
+ ) -> list[HeadPose]:
39
+ headposes: list[HeadPose] = []
40
+ start = time.monotonic()
41
+
42
+ while time.monotonic() - start < duration:
43
+ sucess, bgr_frame = camera.read()
44
+
45
+ if not sucess:
46
+ break
47
+
48
+ pose = detect_head_pose(bgr_frame, landmarker)
49
+
50
+ if pose is not None:
51
+ headposes.append(pose)
52
+
53
+ return headposes
54
+
55
+
56
+ def detect_head_pose(frame: np.ndarray, landmarker: FaceLandmarker) -> HeadPose | None:
57
+ mp_image = to_mediapipe_image(frame)
58
+
59
+ timestamp_ms = time.monotonic_ns() // 1000000
60
+
61
+ result = landmarker.detect_for_video(mp_image, timestamp_ms)
62
+
63
+ if result.facial_transformation_matrixes:
64
+ matrix = result.facial_transformation_matrixes[0]
65
+
66
+ return HeadPose.from_matrix(matrix)
67
+ else:
68
+ return None
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from math import hypot
6
+ from statistics import mean
7
+
8
+ import numpy as np
9
+ from scipy.spatial.transform import Rotation
10
+
11
+
12
+ @dataclass
13
+ class HeadPose:
14
+ pitch: float
15
+ yaw: float
16
+ roll: float
17
+
18
+ @classmethod
19
+ def from_matrix(cls, matrix: np.ndarray) -> HeadPose:
20
+ rotation = Rotation.from_matrix(matrix[:3, :3])
21
+ pitch, yaw, role = rotation.as_euler("xyz", degrees=True)
22
+
23
+ return cls(float(pitch), float(yaw), float(role))
24
+
25
+ @classmethod
26
+ def average_pose(cls, samples: Sequence[HeadPose]) -> HeadPose:
27
+ if not samples:
28
+ raise ValueError("cannot average empty head pose samples")
29
+
30
+ return cls(
31
+ pitch=mean(pose.pitch for pose in samples),
32
+ yaw=mean(pose.yaw for pose in samples),
33
+ roll=mean(pose.roll for pose in samples),
34
+ )
35
+
36
+ def __str__(self) -> str:
37
+ return f"Pitch: {self.pitch:.1f}°, Yaw: {self.yaw:.1f}°, Roll: {self.roll:.1f}°"
38
+
39
+ def distance_to(self, other: HeadPose) -> float:
40
+ delta_pitch = self.pitch - other.pitch
41
+ delta_yaw = self.yaw - other.yaw
42
+
43
+ return hypot(delta_pitch, delta_yaw)
@@ -0,0 +1,30 @@
1
+ from pathlib import Path
2
+ from urllib.request import urlretrieve
3
+
4
+ from caught_you_looking.paths import get_model_path
5
+
6
+ MODEL_URL = (
7
+ "https://storage.googleapis.com/mediapipe-models/"
8
+ "face_landmarker/face_landmarker/float16/1/face_landmarker.task"
9
+ )
10
+
11
+
12
+ def download_model(path: Path) -> None:
13
+ path.parent.mkdir(parents=True, exist_ok=True)
14
+
15
+ temp_path = path.with_suffix(path.suffix + ".tmp")
16
+
17
+ try:
18
+ urlretrieve(MODEL_URL, temp_path)
19
+ temp_path.replace(path)
20
+ finally:
21
+ temp_path.unlink(missing_ok=True)
22
+
23
+
24
+ def ensure_model() -> Path:
25
+ path = get_model_path()
26
+
27
+ if not path.is_file():
28
+ download_model(path)
29
+
30
+ return path
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: caught-you-looking
3
+ Version: 0.1.0
4
+ Summary: Automatic monitor focusing based on head orientation for Hyprland.
5
+ Keywords: hyprland,wayland,head-tracking,computer-vision
6
+ Author: Samuel Freundel
7
+ Author-email: Samuel Freundel <samuel.freundel@uni-ulm.de>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Desktop Environment
16
+ Requires-Dist: mediapipe>=1.2.3
17
+ Requires-Dist: numpy>=2.5.5
18
+ Requires-Dist: opencv-python>=5.1.0.95
19
+ Requires-Dist: scipy>=1.18.1
20
+ Requires-Python: >=3.14
21
+ Project-URL: Homepage, https://github.com/safreu/caught-you-looking
22
+ Project-URL: Repository, https://github.com/safreu/caught-you-looking
23
+ Project-URL: Issues, https://github.com/safreu/caught-you-looking/issues
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Caught You Looking
27
+
28
+ [![CI](https://github.com/safreu/caught-you-looking/actions/workflows/ci.yml/badge.svg)](https://github.com/safreu/caught-you-looking/actions/workflows/ci.yml)
29
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
30
+ [![Python](https://img.shields.io/badge/Python-3.14+-blue.svg)](https://www.python.org/)
31
+
32
+ Caught You Looking (`cyl`) is a lightweight utility for Hyprland that automatically focuses monitors based on your head orientation. It uses a webcam and computer vision to determine which monitor you are looking towards, allowing you to switch monitor focus without using your mouse or keyboard.
33
+
34
+ ## Features
35
+
36
+ - Automatic monitor focusing based on head orientation.
37
+ - Individual calibration for each monitor.
38
+ - Persistent, named calibration profiles for different monitor setups.
39
+ - Configurable dwell time and head pose smoothing.
40
+ - Event-based synchronization with manual Hyprland focus changes.
41
+ - Optional live camera preview.
42
+ - Local processing of webcam frames.
43
+ - Automatic download of the required face landmark model.
44
+
45
+ ## Requirements
46
+
47
+ - Linux with Hyprland
48
+ - Python 3.14 or newer
49
+ - A webcam
50
+ - An internet connection for the initial model download
51
+
52
+ ## Installation
53
+
54
+ ### Using uv
55
+
56
+ Install directly from the GitHub repository:
57
+
58
+ ```sh
59
+ uv tool install git+https://github.com/safreu/caught-you-looking.git
60
+ ```
61
+
62
+ ### From source
63
+
64
+ ```sh
65
+ git clone https://github.com/safreu/caught-you-looking.git
66
+ cd caught-you-looking
67
+ uv sync
68
+ uv run cyl
69
+ ```
70
+
71
+ ## Usage
72
+
73
+ Start the application:
74
+
75
+ ```sh
76
+ cyl
77
+ ```
78
+
79
+ On the first launch, the required face landmark model is downloaded and you are guided through the calibration process.
80
+
81
+ Once calibration is complete, the application automatically focuses the monitor you are looking towards.
82
+
83
+ Stop the application using `Ctrl+C`.
84
+
85
+ ### Calibration
86
+
87
+ During calibration, look towards each monitor as instructed. The application collects multiple head pose samples to determine the representative head orientation for each monitor.
88
+
89
+ Calibration results are saved and reused on subsequent launches.
90
+
91
+ To recalibrate your monitors:
92
+
93
+ ```sh
94
+ cyl --recalibrate
95
+ ```
96
+
97
+ To increase the calibration sampling duration:
98
+
99
+ ```sh
100
+ cyl --recalibrate --duration 5
101
+ ```
102
+
103
+ ### Calibration profiles
104
+
105
+ Different monitor setups can be managed using named calibration profiles.
106
+
107
+ ```sh
108
+ cyl --profile home
109
+ cyl --profile office
110
+ ```
111
+
112
+ If the selected profile does not exist, a new calibration is performed.
113
+
114
+ To list available profiles:
115
+
116
+ ```sh
117
+ cyl --list-profiles
118
+ ```
119
+
120
+ To recalibrate an existing profile:
121
+
122
+ ```sh
123
+ cyl --profile home --recalibrate
124
+ ```
125
+
126
+ ### Camera preview
127
+
128
+ To display the captured webcam video while tracking:
129
+
130
+ ```sh
131
+ cyl --preview
132
+ ```
133
+
134
+ ### Configuration
135
+
136
+ | Argument | Default | Description |
137
+ | --- | --- | --- |
138
+ | `--profile` | `default` | Calibration profile to use. |
139
+ | `--recalibrate` | `false` | Force recalibration of the selected profile. |
140
+ | `--duration` | `2.0` | Calibration sampling duration in seconds per monitor. |
141
+ | `--dwell-time` | `0.6` | Required time in seconds before switching monitor focus. |
142
+ | `--window-size` | `5` | Number of head pose samples used for smoothing. |
143
+ | `--socket-timeout` | `2.0` | Hyprland socket connection timeout in seconds. |
144
+ | `--preview` | `false` | Display a live camera preview. |
145
+ | `--list-profiles` | `false` | List available calibration profiles and exit. |
146
+
147
+ For example, to increase the dwell time and smoothing window:
148
+
149
+ ```sh
150
+ cyl --dwell-time 0.8 --window-size 10
151
+ ```
152
+
153
+ For a complete overview of available arguments:
154
+
155
+ ```sh
156
+ cyl --help
157
+ ```
158
+
159
+ ## How it works
160
+
161
+ Caught You Looking uses MediaPipe's Face Landmarker to estimate the orientation of the user's head from webcam frames.
162
+
163
+ During calibration, representative head poses are recorded for each connected monitor. During tracking, the current head pose is smoothed and compared against these calibrated orientations.
164
+
165
+ A monitor is focused only when it remains the closest matching monitor for the configured dwell time. This reduces unintended focus changes caused by brief head movements.
166
+
167
+ The application also listens to Hyprland's event socket to synchronize its internal tracking state with external monitor focus changes.
168
+
169
+ ## Data storage
170
+
171
+ Application data is stored according to the XDG Base Directory Specification.
172
+
173
+ By default, the following directory structure is used:
174
+
175
+ ```text
176
+ ~/.local/share/cyl/
177
+ ├── calibrations/
178
+ │ ├── default.json
179
+ │ └── ...
180
+ └── models/
181
+ └── face_landmarker.task
182
+ ```
183
+
184
+ If `XDG_DATA_HOME` is configured, its location is used instead of `~/.local/share`.
185
+
186
+ Webcam frames are processed locally and are not uploaded or stored by the application.
187
+
188
+ ## Development
189
+
190
+ Clone the repository and install the development dependencies:
191
+
192
+ ```sh
193
+ git clone https://github.com/safreu/caught-you-looking.git
194
+ cd caught-you-looking
195
+ uv sync --dev
196
+ ```
197
+
198
+ ### Running tests
199
+
200
+ ```sh
201
+ uv run pytest
202
+ ```
203
+
204
+ ### Test coverage
205
+
206
+ ```sh
207
+ uv run pytest --cov
208
+ ```
209
+
210
+ ### Linting
211
+
212
+ ```sh
213
+ uv run ruff check .
214
+ ```
215
+
216
+ ### Formatting
217
+
218
+ ```sh
219
+ uv run ruff format .
220
+ ```
221
+
222
+ ## Limitations
223
+
224
+ Caught You Looking currently estimates head orientation rather than eye gaze. Its accuracy depends on webcam positioning, lighting conditions, calibration quality and the physical arrangement of the monitors.
225
+
226
+ ## License
227
+
228
+ This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,26 @@
1
+ caught_you_looking/__init__.py,sha256=VdSMnKqeNRtb1V8Q9b9PvBTCg4xAlz1mqQirlVIIl58,64
2
+ caught_you_looking/calibration/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ caught_you_looking/calibration/calibration.py,sha256=ZuJii09u1pn_TyGwDz3x8clO1dOsESdnVp3tHdomceE,1475
4
+ caught_you_looking/calibration/persistence.py,sha256=6dLR2Kq_0-Pt_T3Lg5keZd_Psrd86JYinEeoIKoK3WM,815
5
+ caught_you_looking/calibration/profiles.py,sha256=RJ5_sIIMiywAvX05jugNIxElN4QVygMPnJdPVQJjILg,1740
6
+ caught_you_looking/cli.py,sha256=Oiz3mEWBKJ4iQUpeq6FybkPPjs9SsIXqHwcqjxSj97k,1795
7
+ caught_you_looking/hyprland/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ caught_you_looking/hyprland/commands.py,sha256=4Iwy242X9YwEohXvY91mjj9clmzGpanGonMSHpDU1Ro,738
9
+ caught_you_looking/hyprland/events.py,sha256=sfBznqeU3y4TMaKEN8RuRqEbTMebGAEQoNUeC8EO_uY,340
10
+ caught_you_looking/hyprland/listener.py,sha256=ayhk8485bkb5VjcjM01qoxljTC7xuRNsN0fhLreHJz0,3810
11
+ caught_you_looking/main.py,sha256=hh6j-R6xiPyBktJMHBR2bHeA_Rr7_g6QJ67j1wFTX_c,1515
12
+ caught_you_looking/paths.py,sha256=XrhdszIM64S__TEmzWvYDbZ_CJWOgkTE80s940qa7fQ,607
13
+ caught_you_looking/tracking/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ caught_you_looking/tracking/runtime.py,sha256=Y7CRkMgEitlySU1PfwOgWJqUoRuu7PfdEG5_xbeHeak,1227
15
+ caught_you_looking/tracking/tracker.py,sha256=J8CwR78Hky_SmYUFotGdsraBNR9nxNMXj6v_xS_95gw,2185
16
+ caught_you_looking/tracking.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ caught_you_looking/vision/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ caught_you_looking/vision/camera.py,sha256=iOl1wKW_hog3szBBz32XeiDeIrUY2X0xrMkxo10qX2Y,398
19
+ caught_you_looking/vision/detection.py,sha256=wraa0bEHOquTJRxuPa7UnwemeZnxYgrsgD5GSajz3AI,1755
20
+ caught_you_looking/vision/headpose.py,sha256=3dQ019D2Rn-6jJ_9EWNEe0W70uSns5bSJU2SyLkh6Ng,1242
21
+ caught_you_looking/vision/models.py,sha256=I-8znCQfkay2vlDjtMR59Y3dzOHe9pD_u5tjga5i0xc,678
22
+ caught_you_looking-0.1.0.dist-info/licenses/LICENSE,sha256=xjGe9qW2XXfsqRr1q76fmGIGGfUcGUtzN5cgNMM-nrU,1072
23
+ caught_you_looking-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
24
+ caught_you_looking-0.1.0.dist-info/entry_points.txt,sha256=Z28TuHU40Hh5J5J7IQoQWj_7WmTnEChfNVI3Mtjm7iE,104
25
+ caught_you_looking-0.1.0.dist-info/METADATA,sha256=GbwDlYSYnn0CwM-qHJ-AIY7aC-kpuWTmtWr0GUP4qV8,6351
26
+ caught_you_looking-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ caught-you-looking = caught_you_looking.main:main
3
+ cyl = caught_you_looking.main:main
4
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Samuel Freundel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.