lumitray 0.2.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.
lumitray/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """LumiTray automatic display brightness."""
2
+
3
+ __version__ = "0.2.0"
lumitray/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from lumitray.cli import main
2
+
3
+ raise SystemExit(main())
lumitray/app.py ADDED
@@ -0,0 +1,188 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import time
5
+
6
+ from lumitray.camera import CameraUnavailableError
7
+ from lumitray.config import AppConfig
8
+ from lumitray.estimator import InvalidFrameError
9
+ from lumitray.models import PowerState, SampleResult
10
+ from lumitray.policy import BrightnessPolicy
11
+
12
+
13
+ class LumiTrayService:
14
+ def __init__(
15
+ self,
16
+ config: AppConfig,
17
+ sampler,
18
+ power_monitor,
19
+ brightness,
20
+ config_store=None,
21
+ clock=time.monotonic,
22
+ ):
23
+ self.config = config
24
+ self.sampler = sampler
25
+ self.power_monitor = power_monitor
26
+ self.brightness = brightness
27
+ self.config_store = config_store
28
+ self._clock = clock
29
+ self.policy = BrightnessPolicy(config)
30
+ self.pause_until = 0.0
31
+ self.last_applied: int | None = None
32
+ self.failures = 0
33
+ self.last_result = SampleResult(status="starting", power=PowerState.UNKNOWN.value)
34
+ self.logger = logging.getLogger(__name__)
35
+
36
+ def now(self) -> float:
37
+ return self._clock()
38
+
39
+ def _power_state(self) -> PowerState:
40
+ try:
41
+ return self.power_monitor.power_state()
42
+ except Exception:
43
+ return PowerState.UNKNOWN
44
+
45
+ def _finish(self, result: SampleResult, failed: bool = False) -> SampleResult:
46
+ self.failures = self.failures + 1 if failed else 0
47
+ self.last_result = result
48
+ self.logger.info(
49
+ "status=%s power=%s luminance=%s current=%s target=%s changed=%s message=%s",
50
+ result.status,
51
+ result.power,
52
+ result.luminance,
53
+ result.current_brightness,
54
+ result.target_brightness,
55
+ result.changed,
56
+ result.message,
57
+ )
58
+ return result
59
+
60
+ def run_once(self) -> SampleResult:
61
+ power = self._power_state()
62
+ if not self.config.enabled:
63
+ return self._finish(SampleResult("disabled", power.value))
64
+ now = self.now()
65
+ if self.pause_until > now:
66
+ return self._finish(SampleResult("paused", power.value))
67
+
68
+ try:
69
+ current = self.brightness.get_brightness()
70
+ except Exception as error:
71
+ return self._finish(
72
+ SampleResult("brightness_error", power.value, message=str(error)),
73
+ failed=True,
74
+ )
75
+
76
+ if (
77
+ self.last_applied is not None
78
+ and abs(current - self.last_applied) > self.config.deadband_percent
79
+ ):
80
+ self.pause_until = now + self.config.manual_pause_seconds
81
+ return self._finish(
82
+ SampleResult(
83
+ "manual_override",
84
+ power.value,
85
+ current_brightness=current,
86
+ message="Automatic adjustment paused for 15 minutes",
87
+ )
88
+ )
89
+
90
+ try:
91
+ sample = self.sampler.sample()
92
+ except (CameraUnavailableError, InvalidFrameError, OSError) as error:
93
+ return self._finish(
94
+ SampleResult(
95
+ "camera_error",
96
+ power.value,
97
+ current_brightness=current,
98
+ message=str(error),
99
+ ),
100
+ failed=True,
101
+ )
102
+
103
+ try:
104
+ target = self.policy.choose_brightness(sample.luminance, current)
105
+ if target is None:
106
+ return self._finish(
107
+ SampleResult(
108
+ "unchanged",
109
+ power.value,
110
+ sample.luminance,
111
+ current,
112
+ current,
113
+ False,
114
+ sample.acquisition_seconds,
115
+ )
116
+ )
117
+ self.brightness.set_brightness(target)
118
+ except Exception as error:
119
+ return self._finish(
120
+ SampleResult(
121
+ "brightness_error",
122
+ power.value,
123
+ sample.luminance,
124
+ current,
125
+ message=str(error),
126
+ acquisition_seconds=sample.acquisition_seconds,
127
+ ),
128
+ failed=True,
129
+ )
130
+
131
+ self.last_applied = target
132
+ return self._finish(
133
+ SampleResult(
134
+ "adjusted",
135
+ power.value,
136
+ sample.luminance,
137
+ current,
138
+ target,
139
+ True,
140
+ sample.acquisition_seconds,
141
+ )
142
+ )
143
+
144
+ def pause(self) -> None:
145
+ self.pause_until = self.now() + self.config.manual_pause_seconds
146
+
147
+ def resume(self) -> None:
148
+ self.pause_until = 0.0
149
+ self.last_applied = None
150
+ self.policy.reset_smoothing()
151
+
152
+ def set_enabled(self, enabled: bool) -> None:
153
+ self.config.enabled = enabled
154
+ self.resume()
155
+ self._save()
156
+
157
+ def adjust_bias(self, delta: int) -> int:
158
+ self.config.bias_percent = max(-100, min(100, self.config.bias_percent + delta))
159
+ self.policy.reset_smoothing()
160
+ self._save()
161
+ return self.config.bias_percent
162
+
163
+ def quick_calibrate(self) -> int:
164
+ sample = self.sampler.sample()
165
+ brightness = self.brightness.get_brightness()
166
+ self.config.add_calibration_point(sample.luminance, brightness)
167
+ self.policy.reset_smoothing()
168
+ self._save()
169
+ return brightness
170
+
171
+ def reload_config(self) -> AppConfig:
172
+ if self.config_store is not None:
173
+ self.config = self.config_store.load()
174
+ self.policy = BrightnessPolicy(self.config)
175
+ self.last_applied = None
176
+ return self.config
177
+
178
+ def _save(self) -> None:
179
+ if self.config_store is not None:
180
+ self.config_store.save(self.config)
181
+
182
+ def status_text(self) -> str:
183
+ result = self.last_result
184
+ text = f"{result.status.replace('_', ' ').title()} · {result.power}"
185
+ if self.pause_until > self.now():
186
+ remaining = max(0, round((self.pause_until - self.now()) / 60))
187
+ text += f" · resumes in {remaining} min"
188
+ return text
lumitray/autostart.py ADDED
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shlex
5
+ import sys
6
+ from pathlib import Path
7
+
8
+
9
+ def autostart_path() -> Path:
10
+ if sys.platform == "win32":
11
+ roaming = Path(
12
+ os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming"))
13
+ )
14
+ return (
15
+ roaming
16
+ / "Microsoft"
17
+ / "Windows"
18
+ / "Start Menu"
19
+ / "Programs"
20
+ / "Startup"
21
+ / "LumiTray.cmd"
22
+ )
23
+ if sys.platform.startswith("linux"):
24
+ config = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
25
+ return config / "autostart" / "lumitray.desktop"
26
+ raise RuntimeError(f"Autostart is not supported on {sys.platform}")
27
+
28
+
29
+ def set_autostart(enabled: bool) -> None:
30
+ path = autostart_path()
31
+ if not enabled:
32
+ path.unlink(missing_ok=True)
33
+ return
34
+ path.parent.mkdir(parents=True, exist_ok=True)
35
+ if sys.platform == "win32":
36
+ executable = Path(sys.executable).with_name("pythonw.exe")
37
+ path.write_text(
38
+ f'@"{executable}" -m lumitray tray\r\n', encoding="utf-8"
39
+ )
40
+ else:
41
+ content = (
42
+ "[Desktop Entry]\n"
43
+ "Type=Application\n"
44
+ "Name=LumiTray\n"
45
+ f"Exec={shlex.quote(sys.executable)} -m lumitray tray\n"
46
+ "Terminal=false\n"
47
+ "X-GNOME-Autostart-enabled=true\n"
48
+ )
49
+ path.write_text(content, encoding="utf-8")
@@ -0,0 +1 @@
1
+ """Operating-system integrations for LumiTray."""
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol
4
+
5
+
6
+ class BrightnessBackendError(RuntimeError):
7
+ """The operating system could not read or set display brightness."""
8
+
9
+
10
+ class BrightnessBackend(Protocol):
11
+ def get_brightness(self) -> int: ...
12
+
13
+ def set_brightness(self, percent: int) -> None: ...
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ from lumitray.backends.windows_camera import WinRtCameraSampler
6
+ from lumitray.camera import CameraSampler
7
+
8
+
9
+ def create_camera_sampler(camera_index: int = 0):
10
+ if sys.platform == "win32":
11
+ return WinRtCameraSampler(camera_index)
12
+ return CameraSampler(camera_index)
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ import platform
4
+
5
+ from lumitray.backends.linux_brightness import LinuxBrightnessBackend
6
+ from lumitray.backends.windows_brightness import WindowsBrightnessBackend
7
+
8
+
9
+ def create_brightness_backend(platform_name: str | None = None):
10
+ system = (platform_name or platform.system()).lower()
11
+ if system == "windows":
12
+ return WindowsBrightnessBackend()
13
+ if system == "linux":
14
+ return LinuxBrightnessBackend()
15
+ raise RuntimeError(f"Unsupported platform: {system}")
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+
5
+ from lumitray.backends.base import BrightnessBackendError
6
+
7
+
8
+ class LinuxBrightnessBackend:
9
+ def _run(self, *args: str) -> str:
10
+ try:
11
+ result = subprocess.run(
12
+ ["brightnessctl", *args],
13
+ capture_output=True,
14
+ text=True,
15
+ check=True,
16
+ timeout=5,
17
+ shell=False,
18
+ )
19
+ return result.stdout.strip()
20
+ except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
21
+ raise BrightnessBackendError(
22
+ "brightnessctl failed; install it and check backlight permissions"
23
+ ) from error
24
+
25
+ def get_brightness(self) -> int:
26
+ current = int(self._run("get"))
27
+ maximum = int(self._run("max"))
28
+ if maximum <= 0:
29
+ raise BrightnessBackendError("Backlight reported an invalid maximum")
30
+ return max(0, min(100, round(current * 100 / maximum)))
31
+
32
+ def set_brightness(self, percent: int) -> None:
33
+ if not 0 <= int(percent) <= 100:
34
+ raise ValueError("Brightness must be between 0 and 100")
35
+ self._run("set", f"{int(percent)}%")
@@ -0,0 +1,16 @@
1
+ from __future__ import annotations
2
+
3
+ import psutil
4
+
5
+ from lumitray.models import PowerState
6
+
7
+
8
+ class PsutilPowerMonitor:
9
+ def power_state(self) -> PowerState:
10
+ try:
11
+ battery = psutil.sensors_battery()
12
+ except (AttributeError, OSError):
13
+ return PowerState.UNKNOWN
14
+ if battery is None or battery.power_plugged is None:
15
+ return PowerState.UNKNOWN
16
+ return PowerState.AC if battery.power_plugged else PowerState.BATTERY
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ from lumitray.backends.base import BrightnessBackendError
4
+
5
+
6
+ class WindowsBrightnessBackend:
7
+ def _module(self):
8
+ try:
9
+ import screen_brightness_control as sbc
10
+ except ImportError as error:
11
+ raise BrightnessBackendError(
12
+ "screen-brightness-control is not installed"
13
+ ) from error
14
+ return sbc
15
+
16
+ def get_brightness(self) -> int:
17
+ try:
18
+ value = self._module().get_brightness(display=0)
19
+ if isinstance(value, list):
20
+ if not value:
21
+ raise BrightnessBackendError("No controllable internal display found")
22
+ value = value[0]
23
+ brightness = int(value)
24
+ except BrightnessBackendError:
25
+ raise
26
+ except Exception as error:
27
+ raise BrightnessBackendError(
28
+ f"Unable to read internal display brightness: {error}"
29
+ ) from error
30
+ if not 0 <= brightness <= 100:
31
+ raise BrightnessBackendError(f"Invalid brightness value: {brightness}")
32
+ return brightness
33
+
34
+ def set_brightness(self, percent: int) -> None:
35
+ if not 0 <= int(percent) <= 100:
36
+ raise ValueError("Brightness must be between 0 and 100")
37
+ try:
38
+ self._module().set_brightness(int(percent), display=0)
39
+ except Exception as error:
40
+ raise BrightnessBackendError(
41
+ f"Unable to set internal display brightness: {error}"
42
+ ) from error
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import time
5
+
6
+ import cv2
7
+ import numpy as np
8
+
9
+ from lumitray.camera import CameraUnavailableError
10
+ from lumitray.estimator import estimate_luminance
11
+ from lumitray.models import CameraSample
12
+
13
+
14
+ class WinRtCameraSampler:
15
+ """Capture one native Windows camera frame without persisting image data."""
16
+
17
+ def __init__(self, camera_index: int = 0):
18
+ self.camera_index = camera_index
19
+
20
+ @staticmethod
21
+ def _close(resource) -> None:
22
+ if resource is not None:
23
+ try:
24
+ resource.close()
25
+ except Exception:
26
+ pass
27
+
28
+ async def _capture_frame(self) -> np.ndarray:
29
+ from winsdk.system import Array
30
+ from winsdk.windows.devices.enumeration import DeviceClass, DeviceInformation
31
+ from winsdk.windows.media.capture import (
32
+ MediaCapture,
33
+ MediaCaptureInitializationSettings,
34
+ StreamingCaptureMode,
35
+ )
36
+ from winsdk.windows.media.mediaproperties import ImageEncodingProperties
37
+ from winsdk.windows.storage.streams import DataReader, InMemoryRandomAccessStream
38
+
39
+ capture = MediaCapture()
40
+ stream = None
41
+ reader = None
42
+ try:
43
+ devices = await DeviceInformation.find_all_async(DeviceClass.VIDEO_CAPTURE)
44
+ if self.camera_index >= len(devices):
45
+ raise CameraUnavailableError(
46
+ f"Camera {self.camera_index} is not available"
47
+ )
48
+ settings = MediaCaptureInitializationSettings()
49
+ settings.streaming_capture_mode = StreamingCaptureMode.VIDEO
50
+ settings.video_device_id = devices[self.camera_index].id
51
+ await capture.initialize_async(settings)
52
+
53
+ properties = ImageEncodingProperties.create_jpeg()
54
+ properties.width = 320
55
+ properties.height = 240
56
+ stream = InMemoryRandomAccessStream()
57
+ await capture.capture_photo_to_stream_async(properties, stream)
58
+ size = stream.size
59
+ if size <= 0:
60
+ raise CameraUnavailableError("Windows camera returned an empty frame")
61
+
62
+ reader = DataReader(stream.get_input_stream_at(0))
63
+ await reader.load_async(size)
64
+ values = Array("B", size)
65
+ reader.read_bytes(values)
66
+ encoded = bytes(bytearray(values))
67
+ frame = cv2.imdecode(
68
+ np.frombuffer(encoded, dtype=np.uint8), cv2.IMREAD_COLOR
69
+ )
70
+ if frame is None:
71
+ raise CameraUnavailableError("Unable to decode native camera frame")
72
+ return frame
73
+ finally:
74
+ self._close(reader)
75
+ self._close(stream)
76
+ self._close(capture)
77
+
78
+ def sample(self) -> CameraSample:
79
+ started = time.perf_counter()
80
+ try:
81
+ frame = asyncio.run(self._capture_frame())
82
+ except CameraUnavailableError:
83
+ raise
84
+ except Exception as error:
85
+ raise CameraUnavailableError(
86
+ f"Native Windows camera capture failed: {error}"
87
+ ) from error
88
+ return CameraSample(
89
+ luminance=estimate_luminance(frame),
90
+ acquisition_seconds=time.perf_counter() - started,
91
+ )
lumitray/camera.py ADDED
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import time
5
+
6
+ import cv2
7
+
8
+ from lumitray.estimator import InvalidFrameError, estimate_luminance
9
+ from lumitray.models import CameraSample
10
+
11
+
12
+ class CameraUnavailableError(RuntimeError):
13
+ """The selected webcam cannot be opened or read."""
14
+
15
+
16
+ class CameraSampler:
17
+ def __init__(self, camera_index: int = 0):
18
+ self.camera_index = camera_index
19
+
20
+ def sample(self) -> CameraSample:
21
+ started = time.perf_counter()
22
+ if sys.platform == "win32":
23
+ capture = cv2.VideoCapture(self.camera_index, cv2.CAP_MSMF)
24
+ else:
25
+ capture = cv2.VideoCapture(self.camera_index)
26
+ try:
27
+ if not capture.isOpened():
28
+ raise CameraUnavailableError(
29
+ f"Unable to open camera {self.camera_index}; check privacy settings"
30
+ )
31
+ capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
32
+ capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
33
+
34
+ for attempt in range(2):
35
+ ok, frame = capture.read()
36
+ if not ok:
37
+ if attempt == 1:
38
+ raise CameraUnavailableError(
39
+ "Unable to capture a frame from the selected camera"
40
+ )
41
+ continue
42
+ try:
43
+ luminance = estimate_luminance(frame)
44
+ except InvalidFrameError:
45
+ if attempt == 1:
46
+ raise
47
+ continue
48
+ return CameraSample(
49
+ luminance=luminance,
50
+ acquisition_seconds=time.perf_counter() - started,
51
+ )
52
+ raise CameraUnavailableError("Unable to capture a usable camera frame")
53
+ finally:
54
+ capture.release()