pyscribe-app 2.0.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.
Files changed (69) hide show
  1. pyscribe/__init__.py +5 -0
  2. pyscribe/__main__.py +4 -0
  3. pyscribe/app.py +153 -0
  4. pyscribe/audio/__init__.py +1 -0
  5. pyscribe/audio/backend.py +75 -0
  6. pyscribe/audio/coretap.py +139 -0
  7. pyscribe/audio/importer.py +80 -0
  8. pyscribe/audio/macos.py +10 -0
  9. pyscribe/audio/mixdown.py +26 -0
  10. pyscribe/audio/monitor.py +150 -0
  11. pyscribe/audio/owned.py +43 -0
  12. pyscribe/audio/platform.py +30 -0
  13. pyscribe/audio/portaudio.py +93 -0
  14. pyscribe/audio/pulse.py +130 -0
  15. pyscribe/audio/recorder.py +554 -0
  16. pyscribe/audio/split.py +19 -0
  17. pyscribe/audio/wasapi.py +96 -0
  18. pyscribe/domain/__init__.py +1 -0
  19. pyscribe/domain/devices.py +42 -0
  20. pyscribe/domain/errors.py +2 -0
  21. pyscribe/domain/formats.py +9 -0
  22. pyscribe/domain/jobs.py +79 -0
  23. pyscribe/domain/notes.py +99 -0
  24. pyscribe/domain/runs.py +72 -0
  25. pyscribe/domain/timeline.py +125 -0
  26. pyscribe/domain/transcript.py +149 -0
  27. pyscribe/domain/transcription.py +161 -0
  28. pyscribe/engine/__init__.py +15 -0
  29. pyscribe/engine/api.py +42 -0
  30. pyscribe/engine/audio_io.py +107 -0
  31. pyscribe/engine/cuda_libs.py +36 -0
  32. pyscribe/engine/diarize.py +53 -0
  33. pyscribe/engine/hub.py +70 -0
  34. pyscribe/engine/models.py +76 -0
  35. pyscribe/engine/parakeet.py +41 -0
  36. pyscribe/engine/pipeline.py +71 -0
  37. pyscribe/engine/process.py +118 -0
  38. pyscribe/engine/runtime.py +31 -0
  39. pyscribe/engine/tokens.py +24 -0
  40. pyscribe/engine/whisper.py +64 -0
  41. pyscribe/jobs/__init__.py +1 -0
  42. pyscribe/jobs/manager.py +332 -0
  43. pyscribe/jobs/protocol.py +57 -0
  44. pyscribe/jobs/remote.py +350 -0
  45. pyscribe/jobs/runners.py +102 -0
  46. pyscribe/py.typed +0 -0
  47. pyscribe/storage/__init__.py +1 -0
  48. pyscribe/storage/atomic.py +58 -0
  49. pyscribe/storage/instance.py +66 -0
  50. pyscribe/storage/runs.py +277 -0
  51. pyscribe/storage/settings.py +120 -0
  52. pyscribe/summary/__init__.py +1 -0
  53. pyscribe/summary/claude_cli.py +200 -0
  54. pyscribe/ui/__init__.py +1 -0
  55. pyscribe/ui/controller.py +525 -0
  56. pyscribe/ui/dialogs.py +40 -0
  57. pyscribe/ui/formatting.py +63 -0
  58. pyscribe/ui/native.py +34 -0
  59. pyscribe/ui/page.py +1078 -0
  60. pyscribe/ui/ports.py +19 -0
  61. pyscribe/ui/security.py +35 -0
  62. pyscribe/ui/theme.py +176 -0
  63. pyscribe/worker/__init__.py +1 -0
  64. pyscribe/worker/server.py +252 -0
  65. pyscribe_app-2.0.0.dist-info/METADATA +279 -0
  66. pyscribe_app-2.0.0.dist-info/RECORD +69 -0
  67. pyscribe_app-2.0.0.dist-info/WHEEL +4 -0
  68. pyscribe_app-2.0.0.dist-info/entry_points.txt +4 -0
  69. pyscribe_app-2.0.0.dist-info/licenses/LICENSE +21 -0
pyscribe/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """PyScribe: record audio devices and transcribe them with speaker labels."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("pyscribe-app")
pyscribe/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from pyscribe.app import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
pyscribe/app.py ADDED
@@ -0,0 +1,153 @@
1
+ """Composition root: builds the services and opens the PyScribe window."""
2
+
3
+ import argparse
4
+ import logging
5
+ import socket
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ from nicegui import app, ui
11
+
12
+ from pyscribe import __version__
13
+ from pyscribe.audio.importer import recover_interrupted
14
+ from pyscribe.audio.monitor import LevelMonitor
15
+ from pyscribe.audio.platform import default_backend
16
+ from pyscribe.audio.recorder import Recorder
17
+ from pyscribe.jobs.manager import JobManager
18
+ from pyscribe.storage.instance import AlreadyRunningError, hold_instance_lock
19
+ from pyscribe.storage.runs import RunStore
20
+ from pyscribe.storage.settings import SettingsError, SettingsStore, default_settings_path
21
+ from pyscribe.summary.claude_cli import ClaudeCli
22
+ from pyscribe.ui.controller import AppController, Services
23
+ from pyscribe.ui.dialogs import TypedPathDialogs
24
+ from pyscribe.ui.native import BrowserClipboard, NativeDialogs
25
+ from pyscribe.ui.page import Page
26
+ from pyscribe.ui.security import protect
27
+
28
+ if TYPE_CHECKING:
29
+ from pyscribe.ui.ports import Dialogs
30
+
31
+ logger = logging.getLogger(__name__)
32
+ DEFAULT_PORT = 8080
33
+ MAX_PORT = 65535
34
+ HOST = "127.0.0.1"
35
+ PORT_BUSY = "Port {port} is already in use. Choose another one with --port.\n"
36
+
37
+
38
+ def local_now() -> datetime:
39
+ return datetime.now().astimezone()
40
+
41
+
42
+ def port_number(text: str) -> int:
43
+ try:
44
+ port = int(text)
45
+ except ValueError:
46
+ port = 0
47
+ if not 1 <= port <= MAX_PORT:
48
+ msg = f"must be a number from 1 to {MAX_PORT}"
49
+ raise argparse.ArgumentTypeError(msg)
50
+ return port
51
+
52
+
53
+ def port_is_free(port: int) -> bool:
54
+ try:
55
+ socket.create_server((HOST, port)).close()
56
+ except OSError:
57
+ return False
58
+ return True
59
+
60
+
61
+ def create_controller(settings_path: Path) -> AppController:
62
+ settings_store = SettingsStore(settings_path)
63
+ store = RunStore(settings_store.load().save_dir)
64
+ backend = default_backend()
65
+ summarizer = ClaudeCli()
66
+ services = Services(
67
+ backend=backend,
68
+ monitor=LevelMonitor(backend),
69
+ recorder=Recorder(backend, store, wall_clock=local_now),
70
+ store=store,
71
+ jobs=JobManager(store, now=local_now),
72
+ settings_store=settings_store,
73
+ now=local_now,
74
+ summarizer=summarizer,
75
+ stop_summaries=summarizer.shutdown,
76
+ )
77
+ controller = AppController(services)
78
+ for run_id in recover_interrupted(store):
79
+ logger.warning("Recording %s was interrupted; its audio up to the crash was kept.", run_id)
80
+ services.jobs.load_existing()
81
+ services.jobs.start()
82
+ try:
83
+ controller.refresh_devices()
84
+ except OSError as error: # the window shows it, and its refresh button tries again
85
+ logger.warning("Could not list the audio devices: %s", error)
86
+ return controller
87
+
88
+
89
+ def main(argv: list[str] | None = None) -> None:
90
+ parser = argparse.ArgumentParser(description="Record audio devices and transcribe them.")
91
+ parser.add_argument("--version", action="version", version=f"pyscribe {__version__}")
92
+ parser.add_argument(
93
+ "--settings",
94
+ type=Path,
95
+ default=default_settings_path(),
96
+ help="Settings file to use (default: %(default)s)",
97
+ )
98
+ parser.add_argument(
99
+ "--mode",
100
+ choices=["window", "browser", "server"],
101
+ default="window",
102
+ help="window: desktop window (default); browser: open in the web browser; "
103
+ "server: serve on localhost without opening anything.",
104
+ )
105
+ parser.add_argument(
106
+ "--port",
107
+ type=port_number,
108
+ default=None,
109
+ help=f"Port for --mode browser and --mode server (default: {DEFAULT_PORT})",
110
+ )
111
+ args = parser.parse_args(argv)
112
+ if args.port is not None and args.mode == "window":
113
+ parser.error("--port only applies with --mode browser or --mode server.")
114
+ port = None if args.mode == "window" else args.port or DEFAULT_PORT
115
+ logging.basicConfig(
116
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s"
117
+ )
118
+ try:
119
+ lock = hold_instance_lock(args.settings)
120
+ except AlreadyRunningError as error:
121
+ parser.exit(1, f"{error}\n")
122
+ with lock:
123
+ if port is not None and not port_is_free(port):
124
+ parser.exit(1, PORT_BUSY.format(port=port))
125
+ try:
126
+ controller = create_controller(args.settings)
127
+ except SettingsError as error:
128
+ parser.exit(1, f"{error}\n")
129
+ _serve(controller, args.mode, port)
130
+
131
+
132
+ def _serve(controller: AppController, mode: str, port: int | None) -> None:
133
+ app.on_shutdown(controller.shutdown)
134
+ protect(app)
135
+ native = mode == "window"
136
+ dialogs: Dialogs = NativeDialogs() if native else TypedPathDialogs()
137
+
138
+ async def root() -> None:
139
+ await Page(controller, dialogs, BrowserClipboard()).render()
140
+
141
+ ui.run(
142
+ root,
143
+ title="PyScribe",
144
+ host=HOST,
145
+ port=port,
146
+ native=native,
147
+ show=mode != "server",
148
+ window_size=(1280, 900) if native else None,
149
+ dark=None,
150
+ reload=False,
151
+ show_welcome_message=False,
152
+ favicon="🎙️",
153
+ )
@@ -0,0 +1 @@
1
+ """Capturing audio devices into run folders."""
@@ -0,0 +1,75 @@
1
+ """The port between the recorder and a concrete audio API."""
2
+
3
+ import time
4
+ from collections.abc import Callable, Iterator
5
+ from contextlib import contextmanager
6
+ from typing import Protocol
7
+
8
+ import numpy as np
9
+ import numpy.typing as npt
10
+
11
+ from pyscribe.domain.devices import AudioDevice
12
+
13
+ Block = npt.NDArray[np.float32]
14
+ BlockCallback = Callable[[Block, float], None]
15
+ """Receives a mono float32 block and the monotonic time its last sample was captured."""
16
+ RECONNECT_EVERY_S = 2.0
17
+ """How often a device whose stream died is opened again (headset dongles, for instance,
18
+ re-enumerate when a call starts). A recording continues the device's track once it is back."""
19
+
20
+
21
+ class InputStream(Protocol):
22
+ @property
23
+ def active(self) -> bool: ...
24
+
25
+ def close(self) -> None:
26
+ """Stop delivering blocks and release the device. Idempotent; never raises."""
27
+ ...
28
+
29
+
30
+ class AudioBackend(Protocol):
31
+ """Listing and opening raise OSError, and only OSError, when the audio API fails."""
32
+
33
+ def list_devices(self) -> list[AudioDevice]: ...
34
+
35
+ def open_stream(self, device: AudioDevice, on_block: BlockCallback) -> InputStream: ...
36
+
37
+
38
+ class Clock(Protocol):
39
+ def now(self) -> float: ...
40
+
41
+
42
+ class MonotonicClock:
43
+ def now(self) -> float:
44
+ # time.monotonic ticks every 15.6 ms on Windows: too coarse to stamp 20 ms audio blocks.
45
+ return time.perf_counter()
46
+
47
+
48
+ @contextmanager
49
+ def device_errors(what: str) -> Iterator[None]:
50
+ """Report any failure of an audio library as an OSError that says what was attempted.
51
+
52
+ The libraries do not agree on their exception types (SoundCard raises RuntimeError and
53
+ AssertionError when the sound server restarts, PortAudio its own error), but callers
54
+ handle unavailable devices alone, and a stray exception would end a whole recording.
55
+ """
56
+ try:
57
+ yield
58
+ except OSError:
59
+ raise
60
+ except Exception as error:
61
+ msg = f"{what}: {error}"
62
+ raise OSError(msg) from error
63
+
64
+
65
+ def relisted(backend: AudioBackend, device: AudioDevice) -> AudioDevice:
66
+ """Return the device as the backend lists it now (same id), for opening it again.
67
+
68
+ A device that came back may have changed its rate or channels; one that is not listed (or a
69
+ listing that fails) leaves the known description, and opening it reports what is wrong.
70
+ """
71
+ try:
72
+ listed = backend.list_devices()
73
+ except OSError:
74
+ return device
75
+ return next((d for d in listed if d.id == device.id), device)
@@ -0,0 +1,139 @@
1
+ """macOS speakers through Core Audio process taps (catap; macOS 14.2 or later).
2
+
3
+ A tap reads what a device plays without changing its output. macOS asks once for the "System
4
+ Audio Recording" permission (granted to the terminal when started from one) while the tap starts;
5
+ until it is answered the start blocks, so PyScribe gives up after START_TIMEOUT_S with the fix.
6
+ """
7
+
8
+ import logging
9
+ import threading
10
+
11
+ import catap
12
+ import numpy as np
13
+ import sounddevice as sd
14
+
15
+ from pyscribe.audio.backend import BlockCallback, Clock, MonotonicClock, device_errors
16
+ from pyscribe.audio.mixdown import downmix
17
+ from pyscribe.domain.devices import AudioDevice, DeviceKind, device_id
18
+
19
+ _FLOAT32_BITS = 32
20
+ START_TIMEOUT_S = 10.0
21
+ PERMISSION_HELP = (
22
+ "Allow PyScribe (or the terminal that started it) under System Settings > Privacy & Security "
23
+ "> Screen & System Audio Recording, then try again."
24
+ )
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class TapStream:
29
+ def __init__(
30
+ self, session: catap.RecordingSession, unusable: threading.Event | None = None
31
+ ) -> None:
32
+ self._session = session
33
+ self._unusable = unusable or threading.Event()
34
+ """Set when the tap delivers a format it cannot be recorded in; it is then reopened."""
35
+ self._closed = False
36
+
37
+ @property
38
+ def active(self) -> bool:
39
+ return (
40
+ not self._closed
41
+ and self._session.is_recording
42
+ and not self._session.capture_failed
43
+ and not self._unusable.is_set()
44
+ )
45
+
46
+ def close(self) -> None:
47
+ """Destroy the tap. Never raises, so stopping a recording always finishes."""
48
+ if self._closed:
49
+ return
50
+ self._closed = True
51
+ try:
52
+ self._session.close()
53
+ except Exception:
54
+ logger.exception("Core Audio tap did not close cleanly")
55
+
56
+
57
+ class CoreAudioTapBackend:
58
+ def __init__(self, clock: Clock | None = None) -> None:
59
+ self._clock = clock or MonotonicClock()
60
+
61
+ def list_devices(self) -> list[AudioDevice]:
62
+ """Output devices as Core Audio names them; their nominal rate is the tap's rate."""
63
+ found: list[AudioDevice] = []
64
+ with device_errors("Cannot list the audio devices"):
65
+ for info in sd.query_devices():
66
+ channels = int(info["max_output_channels"])
67
+ if channels < 1:
68
+ continue
69
+ name = str(info["name"])
70
+ found.append(
71
+ AudioDevice(
72
+ id=device_id(DeviceKind.OUTPUT, name),
73
+ name=name,
74
+ kind=DeviceKind.OUTPUT,
75
+ sample_rate=int(info["default_samplerate"]),
76
+ channels=channels,
77
+ )
78
+ )
79
+ return found
80
+
81
+ def open_stream(self, device: AudioDevice, on_block: BlockCallback) -> TapStream:
82
+ clock = self._clock
83
+ unusable = threading.Event()
84
+
85
+ def on_buffer(buffer: catap.AudioBuffer) -> None:
86
+ fmt = buffer.format
87
+ if (
88
+ not fmt.is_float
89
+ or fmt.bits_per_sample != _FLOAT32_BITS
90
+ or (round(fmt.sample_rate) != device.sample_rate)
91
+ ):
92
+ # The stream turns inactive, so the recorder reports the device lost and reopens it
93
+ # with the format it has now; nothing else would show that it went silent.
94
+ if not unusable.is_set():
95
+ unusable.set()
96
+ logger.error("%s delivers an unexpected format: %s", device.name, fmt)
97
+ return
98
+ samples = np.frombuffer(buffer.data, dtype=np.float32)
99
+ frames = samples.reshape(buffer.frame_count, fmt.num_channels)
100
+ on_block(downmix(frames), clock.now())
101
+
102
+ try:
103
+ session = catap.record_device(device.name, on_buffer=on_buffer)
104
+ except Exception as error:
105
+ msg = f"Cannot record what {device.name} plays: {error}"
106
+ raise OSError(msg) from error
107
+ _start(session, device.name)
108
+ return TapStream(session, unusable)
109
+
110
+
111
+ def _start(session: catap.RecordingSession, name: str) -> None:
112
+ """Start the tap, or give up after START_TIMEOUT_S and close it whenever it does start."""
113
+ done, abandoned, lock = threading.Event(), threading.Event(), threading.Lock()
114
+ failure: list[str] = []
115
+
116
+ def run() -> None:
117
+ try:
118
+ session.start()
119
+ except Exception as error:
120
+ logger.exception("The Core Audio tap for %s did not start", name)
121
+ failure.append(str(error))
122
+ with lock:
123
+ if abandoned.is_set() and not failure:
124
+ TapStream(session).close()
125
+ done.set()
126
+
127
+ threading.Thread(target=run, name=f"tap-start:{name}", daemon=True).start()
128
+ done.wait(START_TIMEOUT_S)
129
+ with lock:
130
+ if not done.is_set():
131
+ abandoned.set()
132
+ msg = (
133
+ f"macOS did not let PyScribe record what {name} plays within "
134
+ f"{START_TIMEOUT_S:.0f} s. {PERMISSION_HELP}"
135
+ )
136
+ raise OSError(msg)
137
+ if failure:
138
+ msg = f"Cannot record what {name} plays: {failure[0]}"
139
+ raise OSError(msg)
@@ -0,0 +1,80 @@
1
+ """Bringing existing audio files in as runs, and repairing runs a crash left mid-recording."""
2
+
3
+ import logging
4
+ import shutil
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+
8
+ from pyscribe.domain.runs import RecordingState, RunInfo, TrackInfo, TrackKind, track_labels
9
+ from pyscribe.engine.audio_io import AudioDecodeError, decoded_duration, probe
10
+ from pyscribe.storage.runs import RunStore
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def import_audio(store: RunStore, source: Path, created: datetime) -> RunInfo:
16
+ """Copy `source` into a new run folder. Raises AudioDecodeError for files without audio."""
17
+ duration, rate = probe(source)
18
+ if duration <= 0:
19
+ msg = f"{source.name} contains no audio."
20
+ raise AudioDecodeError(msg)
21
+ run_id, path = store.create_run_dir(created)
22
+ file = f"01-audio{source.suffix.lower()}"
23
+ try:
24
+ staging = path / f".{file}.partial"
25
+ shutil.copyfile(source, staging)
26
+ staging.replace(path / file)
27
+ info = RunInfo(
28
+ id=run_id,
29
+ created=created,
30
+ duration_s=duration,
31
+ state=RecordingState.COMPLETE,
32
+ tracks=(
33
+ TrackInfo(
34
+ file=file,
35
+ label=track_labels([TrackKind.FILE])[0],
36
+ kind=TrackKind.FILE,
37
+ device_name=source.name,
38
+ sample_rate=rate,
39
+ ),
40
+ ),
41
+ source="import",
42
+ )
43
+ store.save_info(info)
44
+ except BaseException:
45
+ # Without recording.json the folder is unlisted, and holds a copy of the whole audio.
46
+ shutil.rmtree(path, ignore_errors=True)
47
+ raise
48
+ return info
49
+
50
+
51
+ def recover_interrupted(store: RunStore) -> list[str]:
52
+ """Mark runs a crash left "recording" as interrupted, with the duration actually written."""
53
+ recovered = []
54
+ for entry in store.list_runs():
55
+ info = entry.info
56
+ if info is None or info.state is not RecordingState.RECORDING:
57
+ continue
58
+ run_dir = store.run_dir(info.id)
59
+ durations = [
60
+ _playable_seconds(run_dir / t.file) for t in info.tracks if (run_dir / t.file).exists()
61
+ ]
62
+ store.save_info(
63
+ info.model_copy(
64
+ update={
65
+ "state": RecordingState.INTERRUPTED,
66
+ "duration_s": max(durations, default=0),
67
+ }
68
+ )
69
+ )
70
+ recovered.append(info.id)
71
+ return recovered
72
+
73
+
74
+ def _playable_seconds(path: Path) -> float:
75
+ """Seconds of audio that can be decoded; a file cut off inside its header has none."""
76
+ try:
77
+ return decoded_duration(path)
78
+ except AudioDecodeError as error:
79
+ logger.warning("No audio can be recovered from %s: %s", path, error)
80
+ return 0.0
@@ -0,0 +1,10 @@
1
+ """macOS: microphones through PortAudio, speakers through Core Audio taps."""
2
+
3
+ from pyscribe.audio.coretap import CoreAudioTapBackend
4
+ from pyscribe.audio.portaudio import PortAudioBackend
5
+ from pyscribe.audio.split import SplitBackend
6
+
7
+
8
+ class MacBackend(SplitBackend):
9
+ def __init__(self) -> None:
10
+ super().__init__(inputs=PortAudioBackend(), outputs=CoreAudioTapBackend())
@@ -0,0 +1,26 @@
1
+ """Mixing the channels of a device down to the mono track that is recorded."""
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ from pyscribe.audio.backend import Block
7
+
8
+ STEREO = 2
9
+
10
+
11
+ def downmix(frames: npt.NDArray[np.float32]) -> Block:
12
+ """Mix (frames, channels) audio to mono.
13
+
14
+ Mono and stereo are averaged, the usual fold-down. With more channels an average would record
15
+ a microphone on one input of an 8-channel interface 18 dB down, so there each channel is
16
+ weighted by its loudness in the block: a signal on one channel keeps its level (silent inputs
17
+ weigh nothing), and channels carrying the same signal give that signal, not the sum. The
18
+ weights add up to one, so the mix cannot clip. Stereo is not weighted, because the weights
19
+ change from block to block as sound pans, which would be heard as a wavering level.
20
+ """
21
+ loudness = np.sqrt(np.einsum("ij,ij->j", frames, frames))
22
+ total = loudness.sum()
23
+ if frames.shape[1] <= STEREO or total == 0: # also: a silent block has no weights
24
+ return frames.mean(axis=1, dtype=np.float32)
25
+ mono: Block = frames @ (loudness / total)
26
+ return mono
@@ -0,0 +1,150 @@
1
+ """Live levels for every device, whether it is being recorded or not.
2
+
3
+ The monitor holds its own shared-mode stream per device (WASAPI allows several), so meters keep
4
+ moving while the recorder opens and closes its streams. Nothing it hears is stored.
5
+
6
+ Opening a device can take seconds, so streams are opened without holding the lock that `levels`
7
+ and `problems` need, and `revive`, which the UI calls on every tick, never waits for one.
8
+ """
9
+
10
+ import logging
11
+ import threading
12
+ from collections import deque
13
+ from collections.abc import Sequence
14
+ from dataclasses import dataclass, field
15
+
16
+ import numpy as np
17
+
18
+ from pyscribe.audio.backend import (
19
+ RECONNECT_EVERY_S,
20
+ AudioBackend,
21
+ Block,
22
+ Clock,
23
+ InputStream,
24
+ MonotonicClock,
25
+ relisted,
26
+ )
27
+ from pyscribe.domain.devices import AudioDevice, meter_level
28
+
29
+ WINDOW_S = 0.3
30
+ """A meter shows the loudest block of this last moment, so it neither flickers nor sticks."""
31
+ REVIVE_WAIT_S = 0.1
32
+ """How long `revive` waits for the devices it reopens before it leaves them to finish alone."""
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ @dataclass(slots=True)
37
+ class _Meter:
38
+ device: AudioDevice
39
+ opened_at: float
40
+ """Monotonic time of the last attempt to open the device."""
41
+ stream: InputStream | None = None
42
+ problem: str | None = None
43
+ recent: deque[tuple[float, float]] = field(default_factory=lambda: deque(maxlen=64))
44
+
45
+
46
+ class LevelMonitor:
47
+ def __init__(self, backend: AudioBackend, clock: Clock | None = None) -> None:
48
+ self._backend = backend
49
+ self._clock = clock or MonotonicClock()
50
+ self._lock = threading.Lock()
51
+ """Guards the meters; held only briefly, because audio callbacks take it too."""
52
+ self._watching = threading.Lock()
53
+ """Serialises `watch`, so a stream being opened is never dropped by a concurrent call."""
54
+ self._meters: dict[str, _Meter] = {}
55
+
56
+ def watch(self, devices: Sequence[AudioDevice]) -> None:
57
+ """Meter exactly these devices from now on."""
58
+ wanted = {d.id: d for d in devices}
59
+ with self._watching:
60
+ with self._lock:
61
+ stale = [i for i in self._meters if i not in wanted]
62
+ closing = [self._meters.pop(i) for i in stale]
63
+ for meter in closing:
64
+ if meter.stream is not None:
65
+ meter.stream.close()
66
+ for device in devices:
67
+ with self._lock:
68
+ if device.id in self._meters:
69
+ continue
70
+ meter = self._meters[device.id] = _Meter(device, self._clock.now())
71
+ self._open(meter, device)
72
+
73
+ def revive(self) -> None:
74
+ """Open again, at most every RECONNECT_EVERY_S, the meters whose stream stopped.
75
+
76
+ The reopening runs on its own thread; this waits briefly for it, so a device that opens
77
+ at once is metering when it returns, and a slow one does not stall the caller.
78
+ """
79
+ now = self._clock.now()
80
+ with self._lock:
81
+ due = [
82
+ m
83
+ for m in self._meters.values()
84
+ if (m.stream is None or not m.stream.active)
85
+ and now - m.opened_at >= RECONNECT_EVERY_S
86
+ ]
87
+ if not due:
88
+ return
89
+ for meter in due:
90
+ meter.opened_at = now
91
+ reviver = threading.Thread(
92
+ target=self._reopen, args=(due,), name="meter-revive", daemon=True
93
+ )
94
+ reviver.start()
95
+ reviver.join(REVIVE_WAIT_S)
96
+
97
+ def _reopen(self, meters: list[_Meter]) -> None:
98
+ for meter in meters:
99
+ if meter.stream is not None:
100
+ meter.stream.close()
101
+ self._open(meter, relisted(self._backend, meter.device))
102
+
103
+ def _open(self, meter: _Meter, device: AudioDevice) -> None:
104
+ """Open the device, then hand the stream to the meter, unless it was dropped meanwhile."""
105
+ try:
106
+ stream = self._backend.open_stream(device, _Listener(meter, self._lock))
107
+ except OSError as error:
108
+ self._report(meter, str(error))
109
+ return
110
+ with self._lock:
111
+ current = self._meters.get(meter.device.id) is meter
112
+ if current:
113
+ meter.stream, meter.problem, meter.device = stream, None, device
114
+ if not current:
115
+ stream.close()
116
+
117
+ def _report(self, meter: _Meter, problem: str) -> None:
118
+ with self._lock:
119
+ changed = meter.problem != problem
120
+ meter.stream, meter.problem = None, problem
121
+ if changed:
122
+ logger.warning("Cannot meter %s: %s", meter.device.name, problem)
123
+
124
+ def close(self) -> None:
125
+ self.watch([])
126
+
127
+ def levels(self) -> dict[str, float]:
128
+ since = self._clock.now() - WINDOW_S
129
+ with self._lock:
130
+ return {
131
+ device_id: meter_level(max((r for t, r in meter.recent if t >= since), default=0))
132
+ for device_id, meter in self._meters.items()
133
+ }
134
+
135
+ def problems(self) -> dict[str, str]:
136
+ with self._lock:
137
+ return {i: p for i, m in self._meters.items() if (p := m.problem) is not None}
138
+
139
+
140
+ class _Listener:
141
+ """Stream callback: only computes an RMS value, so it never slows the audio thread."""
142
+
143
+ def __init__(self, meter: _Meter, lock: threading.Lock) -> None:
144
+ self._meter = meter
145
+ self._lock = lock
146
+
147
+ def __call__(self, block: Block, captured_at: float) -> None:
148
+ rms = float(np.sqrt(np.mean(np.square(block)))) if len(block) else 0.0
149
+ with self._lock:
150
+ self._meter.recent.append((captured_at, rms))