chromapi 1.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.
- chromapi/__init__.py +2 -0
- chromapi/__main__.py +6 -0
- chromapi/assets/audio/alert.wav +0 -0
- chromapi/assets/audio/chromapi_scream.wav +0 -0
- chromapi/assets/audio/confused.wav +0 -0
- chromapi/assets/audio/dizzy.wav +0 -0
- chromapi/assets/audio/excited.wav +0 -0
- chromapi/assets/audio/greeting.wav +0 -0
- chromapi/assets/audio/happy.wav +0 -0
- chromapi/assets/audio/no.wav +0 -0
- chromapi/assets/audio/purring.wav +0 -0
- chromapi/assets/audio/sad.wav +0 -0
- chromapi/assets/audio/scared.wav +0 -0
- chromapi/assets/audio/sleepy.wav +0 -0
- chromapi/assets/audio/squeak.wav +0 -0
- chromapi/assets/audio/surprised.wav +0 -0
- chromapi/assets/audio/thinking.wav +0 -0
- chromapi/assets/audio/upset.wav +0 -0
- chromapi/assets/audio/yes.wav +0 -0
- chromapi/assets/favicon.ico +0 -0
- chromapi/assets/firmware/chromapi_stm32_core_v2.0.0.hex +2222 -0
- chromapi/assets/firmware/flash.sh +88 -0
- chromapi/assets/moves/README.md +48 -0
- chromapi/assets/moves/angry.json +1 -0
- chromapi/assets/moves/confused.json +1 -0
- chromapi/assets/moves/dizzy.json +1 -0
- chromapi/assets/moves/excited.json +1 -0
- chromapi/assets/moves/greeting.json +1 -0
- chromapi/assets/moves/happy.json +1 -0
- chromapi/assets/moves/joy.json +1 -0
- chromapi/assets/moves/kick.json +1 -0
- chromapi/assets/moves/metadata.jsonl +15 -0
- chromapi/assets/moves/no.json +1 -0
- chromapi/assets/moves/purring.json +1 -0
- chromapi/assets/moves/sad.json +1 -0
- chromapi/assets/moves/scared.json +1 -0
- chromapi/assets/moves/surprised.json +1 -0
- chromapi/assets/moves/tired.json +1 -0
- chromapi/assets/moves/yes.json +1 -0
- chromapi/chromapi.py +1460 -0
- chromapi/cli.py +106 -0
- chromapi/config/config.yaml +118 -0
- chromapi/estimation/__init__.py +6 -0
- chromapi/estimation/attitude.py +107 -0
- chromapi/hardware/__init__.py +2 -0
- chromapi/hardware/battery.py +54 -0
- chromapi/hardware/fan.py +165 -0
- chromapi/hardware/motherboard_bridge.py +345 -0
- chromapi/input/__init__.py +2 -0
- chromapi/input/gamepad.py +379 -0
- chromapi/input/pairing.py +98 -0
- chromapi/kinematics/__init__.py +10 -0
- chromapi/kinematics/kromatics.py +324 -0
- chromapi/kinematics/poses.py +29 -0
- chromapi/kinematics/topology.py +26 -0
- chromapi/kinematics/types.py +21 -0
- chromapi/locomotion/__init__.py +7 -0
- chromapi/locomotion/balance.py +284 -0
- chromapi/locomotion/gait.py +595 -0
- chromapi/locomotion/recorded_move.py +290 -0
- chromapi/media/__init__.py +2 -0
- chromapi/media/audio.py +424 -0
- chromapi/media/led.py +461 -0
- chromapi/model/LICENSE +438 -0
- chromapi/model/mjcf/additional.xml +21 -0
- chromapi/model/mjcf/assets/18650_li_ion_battery.msh +0 -0
- chromapi/model/mjcf/assets/18650_li_ion_battery.part +13 -0
- chromapi/model/mjcf/assets/battery_holder.msh +0 -0
- chromapi/model/mjcf/assets/battery_holder.part +13 -0
- chromapi/model/mjcf/assets/camera_imx219_d160.msh +0 -0
- chromapi/model/mjcf/assets/camera_imx219_d160.part +13 -0
- chromapi/model/mjcf/assets/chromapi_logo.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo.part +13 -0
- chromapi/model/mjcf/assets/chromapi_logo_circle.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo_inner.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo_outer.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_motherboard.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_motherboard.part +13 -0
- chromapi/model/mjcf/assets/composant2_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant2_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/composant3_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant3_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/composant4_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant4_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1_1.msh +0 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1_1.part +13 -0
- chromapi/model/mjcf/assets/corps14.msh +0 -0
- chromapi/model/mjcf/assets/corps14.part +13 -0
- chromapi/model/mjcf/assets/fan_nf_a4x10.msh +0 -0
- chromapi/model/mjcf/assets/fan_nf_a4x10.part +13 -0
- chromapi/model/mjcf/assets/foot.msh +0 -0
- chromapi/model/mjcf/assets/foot.part +13 -0
- chromapi/model/mjcf/assets/left_coxa.msh +0 -0
- chromapi/model/mjcf/assets/left_coxa.part +13 -0
- chromapi/model/mjcf/assets/left_femur.msh +0 -0
- chromapi/model/mjcf/assets/left_femur.part +13 -0
- chromapi/model/mjcf/assets/left_tibia.msh +0 -0
- chromapi/model/mjcf/assets/left_tibia.part +13 -0
- chromapi/model/mjcf/assets/microswitch.msh +0 -0
- chromapi/model/mjcf/assets/microswitch.part +13 -0
- chromapi/model/mjcf/assets/power_switch.msh +0 -0
- chromapi/model/mjcf/assets/power_switch.part +13 -0
- chromapi/model/mjcf/assets/raspberry_pi_4_model_b.msh +0 -0
- chromapi/model/mjcf/assets/raspberry_pi_4_model_b.part +13 -0
- chromapi/model/mjcf/assets/right_coxa.msh +0 -0
- chromapi/model/mjcf/assets/right_coxa.part +13 -0
- chromapi/model/mjcf/assets/right_femur.msh +0 -0
- chromapi/model/mjcf/assets/right_femur.part +13 -0
- chromapi/model/mjcf/assets/right_tibia.msh +0 -0
- chromapi/model/mjcf/assets/right_tibia.part +13 -0
- chromapi/model/mjcf/assets/robot_case_bottom.msh +0 -0
- chromapi/model/mjcf/assets/robot_case_bottom.part +13 -0
- chromapi/model/mjcf/assets/robot_case_top.msh +0 -0
- chromapi/model/mjcf/assets/robot_case_top.part +13 -0
- chromapi/model/mjcf/assets/rpi_battery_bracket.msh +0 -0
- chromapi/model/mjcf/assets/rpi_battery_bracket.part +13 -0
- chromapi/model/mjcf/assets/speaker.msh +0 -0
- chromapi/model/mjcf/assets/speaker.part +13 -0
- chromapi/model/mjcf/assets/vis_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/vis_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/vis_1__corps1_1.msh +0 -0
- chromapi/model/mjcf/assets/vis_1__corps1_1.part +13 -0
- chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.msh +0 -0
- chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
- chromapi/model/mjcf/config.json +14 -0
- chromapi/model/mjcf/robot.xml +639 -0
- chromapi/model/mjcf/scene.xml +24 -0
- chromapi/model/urdf/assets/18650_li_ion_battery.part +13 -0
- chromapi/model/urdf/assets/18650_li_ion_battery.stl +0 -0
- chromapi/model/urdf/assets/battery_holder.part +13 -0
- chromapi/model/urdf/assets/battery_holder.stl +0 -0
- chromapi/model/urdf/assets/camera_imx219_d160.part +13 -0
- chromapi/model/urdf/assets/camera_imx219_d160.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo.part +13 -0
- chromapi/model/urdf/assets/chromapi_logo.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_circle.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_inner.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_outer.stl +0 -0
- chromapi/model/urdf/assets/chromapi_motherboard.part +13 -0
- chromapi/model/urdf/assets/chromapi_motherboard.stl +0 -0
- chromapi/model/urdf/assets/composant2_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant2_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/composant3_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant3_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/composant4_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant4_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/connector_f_1__corps1.part +13 -0
- chromapi/model/urdf/assets/connector_f_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/connector_f_1__corps1_1.part +13 -0
- chromapi/model/urdf/assets/connector_f_1__corps1_1.stl +0 -0
- chromapi/model/urdf/assets/corps14.part +13 -0
- chromapi/model/urdf/assets/corps14.stl +0 -0
- chromapi/model/urdf/assets/fan_nf_a4x10.part +13 -0
- chromapi/model/urdf/assets/fan_nf_a4x10.stl +0 -0
- chromapi/model/urdf/assets/foot.part +13 -0
- chromapi/model/urdf/assets/foot.stl +0 -0
- chromapi/model/urdf/assets/left_coxa.part +13 -0
- chromapi/model/urdf/assets/left_coxa.stl +0 -0
- chromapi/model/urdf/assets/left_femur.part +13 -0
- chromapi/model/urdf/assets/left_femur.stl +0 -0
- chromapi/model/urdf/assets/left_tibia.part +13 -0
- chromapi/model/urdf/assets/left_tibia.stl +0 -0
- chromapi/model/urdf/assets/microswitch.part +13 -0
- chromapi/model/urdf/assets/microswitch.stl +0 -0
- chromapi/model/urdf/assets/power_switch.part +13 -0
- chromapi/model/urdf/assets/power_switch.stl +0 -0
- chromapi/model/urdf/assets/raspberry_pi_4_model_b.part +13 -0
- chromapi/model/urdf/assets/raspberry_pi_4_model_b.stl +0 -0
- chromapi/model/urdf/assets/right_coxa.part +13 -0
- chromapi/model/urdf/assets/right_coxa.stl +0 -0
- chromapi/model/urdf/assets/right_femur.part +13 -0
- chromapi/model/urdf/assets/right_femur.stl +0 -0
- chromapi/model/urdf/assets/right_tibia.part +13 -0
- chromapi/model/urdf/assets/right_tibia.stl +0 -0
- chromapi/model/urdf/assets/robot_case_bottom.part +13 -0
- chromapi/model/urdf/assets/robot_case_bottom.stl +0 -0
- chromapi/model/urdf/assets/robot_case_top.part +13 -0
- chromapi/model/urdf/assets/robot_case_top.stl +0 -0
- chromapi/model/urdf/assets/rpi_battery_bracket.part +13 -0
- chromapi/model/urdf/assets/rpi_battery_bracket.stl +0 -0
- chromapi/model/urdf/assets/speaker.part +13 -0
- chromapi/model/urdf/assets/speaker.stl +0 -0
- chromapi/model/urdf/assets/vis_1__corps1.part +13 -0
- chromapi/model/urdf/assets/vis_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/vis_1__corps1_1.part +13 -0
- chromapi/model/urdf/assets/vis_1__corps1_1.stl +0 -0
- chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
- chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
- chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.stl +0 -0
- chromapi/model/urdf/config.json +8 -0
- chromapi/model/urdf/robot.urdf +2587 -0
- chromapi/utils/calibrate_imu_mount.py +80 -0
- chromapi/utils/calibrate_servo_centers.py +432 -0
- chromapi/utils/flash.py +141 -0
- chromapi/utils/health.py +210 -0
- chromapi/utils/report.py +75 -0
- chromapi/utils/setup_motors.py +189 -0
- chromapi/utils/sim_server.py +126 -0
- chromapi/web/__init__.py +2 -0
- chromapi/web/access.py +167 -0
- chromapi/web/app.py +1136 -0
- chromapi/web/camera.py +202 -0
- chromapi/web/static/fonts/varela-round.woff2 +0 -0
- chromapi/web/static/index.html +1079 -0
- chromapi/web/static/logo.png +0 -0
- chromapi/web/static/motherboard_front.png +0 -0
- chromapi/web/static/socket.io.min.js +7 -0
- chromapi-1.0.0.dist-info/METADATA +222 -0
- chromapi-1.0.0.dist-info/RECORD +219 -0
- chromapi-1.0.0.dist-info/WHEEL +5 -0
- chromapi-1.0.0.dist-info/entry_points.txt +2 -0
- chromapi-1.0.0.dist-info/licenses/LICENSE +201 -0
- chromapi-1.0.0.dist-info/licenses/src/chromapi/model/LICENSE +438 -0
- chromapi-1.0.0.dist-info/top_level.txt +1 -0
chromapi/media/audio.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Audio playback and microphone streaming for Chromapi.
|
|
3
|
+
|
|
4
|
+
Optional dependency (``pip install chromapi[audio]``, i.e. ``sounddevice``) - every function
|
|
5
|
+
here is best-effort: a missing dependency, no audio device (headless CI, SSH without audio
|
|
6
|
+
forwarding, ...), or a bad file all log a warning and return ``False``/``None``, never raise. A
|
|
7
|
+
sound cue is not something that should ever take down a control loop.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import threading
|
|
14
|
+
import wave
|
|
15
|
+
from math import gcd
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Callable, Dict, Optional, Union
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import numpy.typing as npt
|
|
21
|
+
from scipy.signal import resample_poly
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
#: Maps WAV sample width (bytes) to the numpy dtype ``wave``'s raw frames decode to.
|
|
26
|
+
_DTYPE_BY_SAMPLE_WIDTH: Dict[int, "npt.DTypeLike"] = {1: np.uint8, 2: np.int16, 4: np.int32}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
#: Full-scale divisor for each integer sample width ``wave`` can hand back, to convert to a
|
|
30
|
+
#: float32 [-1, 1] range before applying :func:`play_wav`'s ``volume`` gain. ``uint8`` PCM is
|
|
31
|
+
#: offset-encoded (silence = 128, not 0), unlike the signed 16/32-bit formats.
|
|
32
|
+
_FULL_SCALE_BY_SAMPLE_WIDTH: Dict[int, float] = {1: 128.0, 2: 32768.0, 4: 2147483648.0}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _to_float32(samples: npt.NDArray[Any], sample_width: int) -> npt.NDArray[np.float32]:
|
|
36
|
+
"""Convert raw PCM samples (as decoded by ``wave``) to float32 in [-1, 1]."""
|
|
37
|
+
full_scale = _FULL_SCALE_BY_SAMPLE_WIDTH[sample_width]
|
|
38
|
+
offset = 128.0 if sample_width == 1 else 0.0
|
|
39
|
+
return ((samples.astype(np.float32) - offset) / full_scale).astype(np.float32)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _device_default_samplerate(sd: Any, device: Union[int, str, None]) -> Optional[int]:
|
|
43
|
+
"""Best-effort lookup of an output device's native sample rate [Hz], or ``None`` if unknown."""
|
|
44
|
+
try:
|
|
45
|
+
info = sd.query_devices(device, kind="output") if device is not None else sd.query_devices(kind="output")
|
|
46
|
+
rate = info.get("default_samplerate") # [Hz]
|
|
47
|
+
return int(round(rate)) if rate else None
|
|
48
|
+
except Exception:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _resample_to(samples: npt.NDArray[np.float32], orig_rate: int, target_rate: int) -> npt.NDArray[np.float32]:
|
|
53
|
+
"""Resample (mono or multi-channel, shape ``(n,)``/``(n, channels)``) float32 audio from ``orig_rate`` to ``target_rate`` [Hz]."""
|
|
54
|
+
if orig_rate == target_rate:
|
|
55
|
+
return samples
|
|
56
|
+
divisor = gcd(orig_rate, target_rate)
|
|
57
|
+
up, down = target_rate // divisor, orig_rate // divisor
|
|
58
|
+
return np.asarray(resample_poly(samples, up, down, axis=0), dtype=np.float32)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _decode_wav(path: Union[str, Path], volume: float) -> Optional[Any]:
|
|
62
|
+
"""Decode a .wav file to float32 [-1, 1] samples, applying ``volume``."""
|
|
63
|
+
try:
|
|
64
|
+
with wave.open(str(path), "rb") as wav_file:
|
|
65
|
+
n_channels = wav_file.getnchannels()
|
|
66
|
+
sample_width = wav_file.getsampwidth() # [byte]
|
|
67
|
+
sample_rate = wav_file.getframerate() # [Hz]
|
|
68
|
+
raw = wav_file.readframes(wav_file.getnframes())
|
|
69
|
+
except (OSError, wave.Error) as exc:
|
|
70
|
+
logger.warning("_decode_wav(%s): could not read the file (%s)", path, exc)
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
dtype = _DTYPE_BY_SAMPLE_WIDTH.get(sample_width)
|
|
74
|
+
if dtype is None:
|
|
75
|
+
logger.warning(
|
|
76
|
+
"_decode_wav(%s): unsupported sample width (%d bytes)", path, sample_width
|
|
77
|
+
)
|
|
78
|
+
return None
|
|
79
|
+
flat_samples = np.frombuffer(raw, dtype=dtype)
|
|
80
|
+
samples: npt.NDArray[Any] = (
|
|
81
|
+
flat_samples.reshape(-1, n_channels) if n_channels > 1 else flat_samples
|
|
82
|
+
)
|
|
83
|
+
scaled = np.clip(_to_float32(samples, sample_width) * volume, -1.0, 1.0)
|
|
84
|
+
return scaled, sample_rate, n_channels
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def play_wav(
|
|
88
|
+
path: Union[str, Path],
|
|
89
|
+
wait: bool = True,
|
|
90
|
+
volume: float = 0.5,
|
|
91
|
+
device: Union[int, str, None] = None,
|
|
92
|
+
) -> bool:
|
|
93
|
+
"""Play a .wav file through an output device by opening a stream, playing, and closing it.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
path: Path to a .wav file.
|
|
97
|
+
wait: If True (default), block until playback finishes. If False, start playback and
|
|
98
|
+
return immediately, e.g. to play a cue without delaying a motion.
|
|
99
|
+
volume: Linear gain applied before playback, defaults to 0.5.
|
|
100
|
+
device: Passed straight to ``sounddevice`` (index, name substring, or ``None`` for the
|
|
101
|
+
system default output).
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
True if playback started, False if it was skipped.
|
|
105
|
+
|
|
106
|
+
"""
|
|
107
|
+
try:
|
|
108
|
+
import sounddevice as sd
|
|
109
|
+
except ImportError:
|
|
110
|
+
logger.warning(
|
|
111
|
+
"play_wav(%s): 'sounddevice' not installed (pip install chromapi[audio]) - "
|
|
112
|
+
"skipping playback",
|
|
113
|
+
path,
|
|
114
|
+
)
|
|
115
|
+
return False
|
|
116
|
+
|
|
117
|
+
decoded = _decode_wav(path, volume)
|
|
118
|
+
if decoded is None:
|
|
119
|
+
return False
|
|
120
|
+
scaled, sample_rate, _n_channels = decoded
|
|
121
|
+
|
|
122
|
+
play_rate = sample_rate # [Hz]
|
|
123
|
+
device_rate = _device_default_samplerate(sd, device) # [Hz]
|
|
124
|
+
if device_rate and device_rate != sample_rate:
|
|
125
|
+
try:
|
|
126
|
+
scaled = _resample_to(scaled, sample_rate, device_rate)
|
|
127
|
+
play_rate = device_rate
|
|
128
|
+
except Exception:
|
|
129
|
+
logger.exception(
|
|
130
|
+
"play_wav(%s): resampling %d Hz -> %d Hz failed - playing at the file's own rate instead",
|
|
131
|
+
path,
|
|
132
|
+
sample_rate,
|
|
133
|
+
device_rate,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
sd.play(scaled, samplerate=play_rate, device=device)
|
|
138
|
+
if wait:
|
|
139
|
+
sd.wait()
|
|
140
|
+
except Exception:
|
|
141
|
+
logger.exception("play_wav(%s): playback failed - no audio device available?", path)
|
|
142
|
+
return False
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def find_output_device(name_hint: str) -> Optional[int]:
|
|
147
|
+
"""Return the index of the first output-capable device whose name contains ``name_hint``."""
|
|
148
|
+
try:
|
|
149
|
+
import sounddevice as sd
|
|
150
|
+
except ImportError:
|
|
151
|
+
return None
|
|
152
|
+
try:
|
|
153
|
+
devices = sd.query_devices()
|
|
154
|
+
except Exception:
|
|
155
|
+
logger.exception("find_output_device(%r): could not query audio devices", name_hint)
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
hint = name_hint.lower()
|
|
159
|
+
for index, device in enumerate(devices):
|
|
160
|
+
if device.get("max_output_channels", 0) > 0 and hint in str(device.get("name", "")).lower():
|
|
161
|
+
return index
|
|
162
|
+
logger.warning(
|
|
163
|
+
"find_output_device(%r): no output device matched - falling back to the system default",
|
|
164
|
+
name_hint,
|
|
165
|
+
)
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _match_channels(samples: npt.NDArray[np.float32], n_channels: int, target_channels: int) -> npt.NDArray[np.float32]:
|
|
170
|
+
"""Adapt ``samples`` (``n_channels`` wide) to ``target_channels`` - mono <-> N only."""
|
|
171
|
+
if n_channels == target_channels:
|
|
172
|
+
return samples
|
|
173
|
+
if n_channels == 1 and target_channels > 1:
|
|
174
|
+
mono = samples.reshape(-1, 1) if samples.ndim == 1 else samples
|
|
175
|
+
return np.tile(mono, (1, target_channels)).astype(np.float32)
|
|
176
|
+
if target_channels == 1 and n_channels > 1:
|
|
177
|
+
return np.asarray(samples.mean(axis=1), dtype=np.float32)
|
|
178
|
+
logger.warning(
|
|
179
|
+
"_match_channels: cannot adapt %d-channel audio to %d channels - playing as-is",
|
|
180
|
+
n_channels,
|
|
181
|
+
target_channels,
|
|
182
|
+
)
|
|
183
|
+
return samples
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class PersistentAudioOutput:
|
|
187
|
+
"""Plays .wav files through one long-lived, callback-driven ``sd.OutputStream``.
|
|
188
|
+
|
|
189
|
+
This is more efficient than :func:`play_wav` if many short clips are played back-to-back.
|
|
190
|
+
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
def __init__(
|
|
194
|
+
self, samplerate: Optional[int] = None, channels: int = 1, device: Union[int, str, None] = None
|
|
195
|
+
) -> None:
|
|
196
|
+
"""Configure the output (``samplerate`` [Hz]) - opens no stream until :meth:`start`."""
|
|
197
|
+
self.samplerate = samplerate # [Hz]
|
|
198
|
+
self.channels = channels
|
|
199
|
+
self.device = device
|
|
200
|
+
self._stream: Optional[Any] = None
|
|
201
|
+
self._lock = threading.Lock()
|
|
202
|
+
self._pending: npt.NDArray[np.float32] = np.zeros((0, channels), dtype=np.float32)
|
|
203
|
+
|
|
204
|
+
def start(self) -> bool:
|
|
205
|
+
"""Open the callback-driven output stream."""
|
|
206
|
+
if self._stream is not None:
|
|
207
|
+
return False
|
|
208
|
+
try:
|
|
209
|
+
import sounddevice as sd
|
|
210
|
+
except ImportError:
|
|
211
|
+
logger.warning("PersistentAudioOutput.start(): 'sounddevice' not installed - skipping")
|
|
212
|
+
return False
|
|
213
|
+
try:
|
|
214
|
+
self._stream = sd.OutputStream(
|
|
215
|
+
samplerate=self.samplerate,
|
|
216
|
+
channels=self.channels,
|
|
217
|
+
dtype="float32",
|
|
218
|
+
device=self.device,
|
|
219
|
+
callback=self._callback,
|
|
220
|
+
latency="high",
|
|
221
|
+
)
|
|
222
|
+
self._stream.start()
|
|
223
|
+
except Exception:
|
|
224
|
+
logger.exception("PersistentAudioOutput.start(): could not open the output device")
|
|
225
|
+
self._stream = None
|
|
226
|
+
return False
|
|
227
|
+
self.samplerate = int(round(self._stream.samplerate))
|
|
228
|
+
return True
|
|
229
|
+
|
|
230
|
+
def _callback(self, outdata: npt.NDArray[np.float32], frames: int, time_info: object, status: object) -> None:
|
|
231
|
+
"""PortAudio calls this from its own real-time thread whenever it needs ``frames`` more."""
|
|
232
|
+
if status:
|
|
233
|
+
logger.warning("PersistentAudioOutput: %s", status)
|
|
234
|
+
with self._lock:
|
|
235
|
+
available = len(self._pending)
|
|
236
|
+
n = min(frames, available)
|
|
237
|
+
if n > 0:
|
|
238
|
+
outdata[:n] = self._pending[:n]
|
|
239
|
+
self._pending = self._pending[n:]
|
|
240
|
+
if n < frames:
|
|
241
|
+
outdata[n:] = 0.0
|
|
242
|
+
|
|
243
|
+
def play(self, path: Union[str, Path], volume: float = 0.4) -> bool:
|
|
244
|
+
"""Decode ``path``, adapt it to this stream's rate/channels, and queue it for playback."""
|
|
245
|
+
if self._stream is None:
|
|
246
|
+
logger.warning("PersistentAudioOutput.play(%s): not started - skipping", path)
|
|
247
|
+
return False
|
|
248
|
+
decoded = _decode_wav(path, volume)
|
|
249
|
+
if decoded is None:
|
|
250
|
+
return False
|
|
251
|
+
samples, sample_rate, n_channels = decoded
|
|
252
|
+
return self.write(samples, sample_rate, n_channels, label=str(path))
|
|
253
|
+
|
|
254
|
+
def write(self, samples: npt.NDArray[np.float32], sample_rate: int, n_channels: int = 1, label: str = "stream") -> bool:
|
|
255
|
+
"""Queue raw float32 ``samples`` [-1, 1] at ``sample_rate`` [Hz]."""
|
|
256
|
+
if self._stream is None:
|
|
257
|
+
return False
|
|
258
|
+
assert self.samplerate is not None
|
|
259
|
+
if sample_rate != self.samplerate:
|
|
260
|
+
try:
|
|
261
|
+
samples = _resample_to(samples, sample_rate, self.samplerate)
|
|
262
|
+
except Exception:
|
|
263
|
+
logger.exception(
|
|
264
|
+
"PersistentAudioOutput.write(%s): resampling %d Hz -> %d Hz failed - skipping",
|
|
265
|
+
label,
|
|
266
|
+
sample_rate,
|
|
267
|
+
self.samplerate,
|
|
268
|
+
)
|
|
269
|
+
return False
|
|
270
|
+
samples = _match_channels(samples, n_channels, self.channels)
|
|
271
|
+
if samples.ndim == 1:
|
|
272
|
+
samples = samples.reshape(-1, 1)
|
|
273
|
+
with self._lock:
|
|
274
|
+
self._pending = np.concatenate([self._pending, samples], axis=0)
|
|
275
|
+
return True
|
|
276
|
+
|
|
277
|
+
def stop(self) -> None:
|
|
278
|
+
"""Close the stream and drop any pending audio."""
|
|
279
|
+
if self._stream is not None:
|
|
280
|
+
try:
|
|
281
|
+
self._stream.stop()
|
|
282
|
+
self._stream.close()
|
|
283
|
+
except Exception:
|
|
284
|
+
logger.exception("PersistentAudioOutput.stop(): error closing the output stream")
|
|
285
|
+
self._stream = None
|
|
286
|
+
with self._lock:
|
|
287
|
+
self._pending = np.zeros((0, self.channels), dtype=np.float32)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def to_int16_mono(frames: npt.NDArray[np.float32], gain: float = 1.0) -> bytes:
|
|
291
|
+
"""``(n, channels)`` float32 frames -> little-endian int16 mono bytes, channels summed, ``gain`` applied, clipped.
|
|
292
|
+
|
|
293
|
+
Summed rather than averaged: Chromapi's mono microphone comes on one of two channels, the other stays silent.
|
|
294
|
+
"""
|
|
295
|
+
mono = np.asarray(frames, dtype=np.float32).reshape(len(frames), -1).sum(axis=1) * gain
|
|
296
|
+
return bytes((np.clip(mono, -1.0, 1.0) * 32767.0).astype("<i2").tobytes())
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
AGC_TARGET_RMS = 0.2 # -14 dBFS
|
|
300
|
+
AGC_MAX_GAIN = 16.0
|
|
301
|
+
AGC_RISE = 0.05 # fraction of the way up per chunk: ~1 s to reach a quiet voice with 40 ms chunks
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class AutoGain:
|
|
305
|
+
"""Per-chunk automatic gain: :meth:`apply` returns the chunk scaled towards :data:`AGC_TARGET_RMS`."""
|
|
306
|
+
|
|
307
|
+
def __init__(self, max_gain: float = AGC_MAX_GAIN) -> None:
|
|
308
|
+
"""Start at unit gain."""
|
|
309
|
+
self.max_gain = max_gain
|
|
310
|
+
self.gain = 1.0
|
|
311
|
+
|
|
312
|
+
def apply(self, mono: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]:
|
|
313
|
+
"""``mono`` [-1, 1] scaled by the current gain, updated from this chunk's level."""
|
|
314
|
+
rms = float(np.sqrt(np.mean(np.square(mono)))) if len(mono) else 0.0
|
|
315
|
+
wanted = min(self.max_gain, max(1.0, AGC_TARGET_RMS / max(rms, 1e-9)))
|
|
316
|
+
self.gain = wanted if wanted < self.gain else self.gain + AGC_RISE * (wanted - self.gain)
|
|
317
|
+
return np.asarray(mono * self.gain, dtype=np.float32)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
NS_FRAME = 512 # [samples] half-overlapped
|
|
321
|
+
NS_BAND_HZ = (150.0, 4000.0) # [Hz] voice band kept
|
|
322
|
+
NS_OVER = 1.2 # over-subtraction
|
|
323
|
+
NS_FLOOR = 0.1 # -20 dB of noise left
|
|
324
|
+
NS_NOISE_RISE_DB_S = 3.0 # [dB/s] noise estimate rise, slow so a voice is not learnt
|
|
325
|
+
NS_NOISE_FALL = 0.2 # per frame
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
class NoiseSuppressor:
|
|
329
|
+
"""Streaming spectral subtraction of steady noise (fan, servos); delays the sound by one frame.
|
|
330
|
+
|
|
331
|
+
ponytail: stationary noise only; RNNoise if that is not enough.
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
def __init__(self, samplerate: int = 16000) -> None:
|
|
335
|
+
"""Nothing learnt yet: the first frames set the noise estimate."""
|
|
336
|
+
n = NS_FRAME
|
|
337
|
+
self.hop = n // 2
|
|
338
|
+
self.window = np.sqrt(np.hanning(n + 1)[:n]).astype(np.float32) # sqrt-Hann
|
|
339
|
+
freqs = np.fft.rfftfreq(n, 1.0 / samplerate)
|
|
340
|
+
self.band = ((freqs >= NS_BAND_HZ[0]) & (freqs <= NS_BAND_HZ[1])).astype(np.float32)
|
|
341
|
+
self.frame = np.zeros(n, dtype=np.float32)
|
|
342
|
+
self.acc = np.zeros(n, dtype=np.float32) # overlap-add
|
|
343
|
+
self.pending = np.zeros(0, dtype=np.float32)
|
|
344
|
+
self.out = np.zeros(self.hop, dtype=np.float32)
|
|
345
|
+
self.power: Optional[npt.NDArray[np.float64]] = None
|
|
346
|
+
self.noise: Optional[npt.NDArray[np.float64]] = None
|
|
347
|
+
self.gain = np.ones(n // 2 + 1)
|
|
348
|
+
self.rise = 10.0 ** (NS_NOISE_RISE_DB_S / 10.0 * self.hop / samplerate)
|
|
349
|
+
|
|
350
|
+
def apply(self, mono: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]:
|
|
351
|
+
"""``mono`` denoised, same length, delayed."""
|
|
352
|
+
self.pending = np.concatenate([self.pending, np.asarray(mono, dtype=np.float32)])
|
|
353
|
+
done = []
|
|
354
|
+
while len(self.pending) >= self.hop:
|
|
355
|
+
self.frame = np.concatenate([self.frame[self.hop:], self.pending[:self.hop]])
|
|
356
|
+
self.pending = self.pending[self.hop:]
|
|
357
|
+
spec = np.fft.rfft(self.frame * self.window)
|
|
358
|
+
p = np.abs(spec) ** 2
|
|
359
|
+
self.power = p if self.power is None else 0.5 * self.power + 0.5 * p
|
|
360
|
+
if self.noise is None:
|
|
361
|
+
self.noise = self.power.copy()
|
|
362
|
+
self.noise = np.where(self.power < self.noise, self.noise + NS_NOISE_FALL * (self.power - self.noise),
|
|
363
|
+
np.minimum(self.power, self.noise * self.rise))
|
|
364
|
+
g = np.maximum(NS_FLOOR, 1.0 - NS_OVER * self.noise / np.maximum(p, 1e-12))
|
|
365
|
+
self.gain = np.maximum(g, 0.5 * (self.gain + g))
|
|
366
|
+
self.acc += np.fft.irfft(spec * self.gain * self.band, NS_FRAME).astype(np.float32) * self.window
|
|
367
|
+
done.append(self.acc[:self.hop].copy())
|
|
368
|
+
self.acc = np.concatenate([self.acc[self.hop:], np.zeros(self.hop, dtype=np.float32)])
|
|
369
|
+
self.out = np.concatenate([self.out, *done])
|
|
370
|
+
y, self.out = self.out[:len(mono)], self.out[len(mono):]
|
|
371
|
+
return y
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
class MicStream:
|
|
375
|
+
"""Live microphone stream: fixed ``gain``, :class:`NoiseSuppressor`, :class:`AutoGain`, tanh limiter."""
|
|
376
|
+
|
|
377
|
+
def __init__(
|
|
378
|
+
self, on_chunk: Callable[[bytes], None], samplerate: int = 16000, block_s: float = 0.04,
|
|
379
|
+
gain: float = 1.0, device: Union[int, str, None] = None, denoise: bool = True,
|
|
380
|
+
) -> None:
|
|
381
|
+
"""``samplerate`` [Hz], chunks of ``block_s`` [s]; opens nothing until :meth:`start`."""
|
|
382
|
+
self.on_chunk, self.samplerate, self.block_s, self.gain, self.device = on_chunk, samplerate, block_s, gain, device
|
|
383
|
+
self.denoiser = NoiseSuppressor(samplerate) if denoise else None
|
|
384
|
+
self.auto_gain = AutoGain()
|
|
385
|
+
self._stream: Optional[Any] = None
|
|
386
|
+
|
|
387
|
+
def start(self) -> bool:
|
|
388
|
+
"""Open the input (2 channels if the device has them, else 1) and start sending chunks."""
|
|
389
|
+
try:
|
|
390
|
+
import sounddevice as sd
|
|
391
|
+
except ImportError:
|
|
392
|
+
logger.warning("MicStream.start(): 'sounddevice' not installed - skipping")
|
|
393
|
+
return False
|
|
394
|
+
|
|
395
|
+
def _callback(indata: npt.NDArray[np.float32], frames: int, time_info: object, status: object) -> None:
|
|
396
|
+
try:
|
|
397
|
+
mono = np.asarray(indata, dtype=np.float32).reshape(frames, -1).sum(axis=1) * self.gain
|
|
398
|
+
if self.denoiser is not None:
|
|
399
|
+
mono = self.denoiser.apply(mono)
|
|
400
|
+
self.on_chunk(to_int16_mono(np.tanh(self.auto_gain.apply(mono))[:, None]))
|
|
401
|
+
except Exception: # never let an exception reach PortAudio's thread
|
|
402
|
+
logger.exception("MicStream: chunk dropped")
|
|
403
|
+
|
|
404
|
+
for channels in (2, 1):
|
|
405
|
+
try:
|
|
406
|
+
self._stream = sd.InputStream(samplerate=self.samplerate, channels=channels, dtype="float32",
|
|
407
|
+
device=self.device, blocksize=round(self.samplerate * self.block_s),
|
|
408
|
+
callback=_callback)
|
|
409
|
+
self._stream.start()
|
|
410
|
+
return True
|
|
411
|
+
except Exception:
|
|
412
|
+
self._stream = None
|
|
413
|
+
logger.warning("MicStream.start(): could not open the microphone")
|
|
414
|
+
return False
|
|
415
|
+
|
|
416
|
+
def stop(self) -> None:
|
|
417
|
+
"""Close the input."""
|
|
418
|
+
if self._stream is not None:
|
|
419
|
+
try:
|
|
420
|
+
self._stream.stop()
|
|
421
|
+
self._stream.close()
|
|
422
|
+
except Exception:
|
|
423
|
+
logger.exception("MicStream.stop(): error closing the input stream")
|
|
424
|
+
self._stream = None
|