micforge 1.3.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 (70) hide show
  1. micforge/__init__.py +3 -0
  2. micforge/__main__.py +4 -0
  3. micforge/analysis/__init__.py +0 -0
  4. micforge/analysis/stats.py +133 -0
  5. micforge/audio/__init__.py +0 -0
  6. micforge/audio/backend.py +32 -0
  7. micforge/audio/cues.py +110 -0
  8. micforge/audio/device_watch.py +237 -0
  9. micforge/audio/devices.py +160 -0
  10. micforge/audio/engine.py +746 -0
  11. micforge/audio/fileio.py +45 -0
  12. micforge/audio/latency.py +169 -0
  13. micforge/audio/loopback.py +113 -0
  14. micforge/audio/metrics.py +134 -0
  15. micforge/audio/noise_profile.py +250 -0
  16. micforge/audio/recorder.py +100 -0
  17. micforge/audio/ring.py +89 -0
  18. micforge/cli.py +293 -0
  19. micforge/commands/__init__.py +0 -0
  20. micforge/commands/calibrate.py +47 -0
  21. micforge/commands/common.py +69 -0
  22. micforge/commands/devices_cmd.py +86 -0
  23. micforge/commands/diagnostics_cmd.py +68 -0
  24. micforge/commands/doctor.py +127 -0
  25. micforge/commands/files.py +48 -0
  26. micforge/commands/help_cmd.py +449 -0
  27. micforge/commands/latency_test.py +65 -0
  28. micforge/commands/live.py +321 -0
  29. micforge/commands/preset_cmd.py +142 -0
  30. micforge/commands/test_mic.py +98 -0
  31. micforge/commands/wizard.py +70 -0
  32. micforge/config.py +279 -0
  33. micforge/diagnostics.py +308 -0
  34. micforge/dsp/__init__.py +0 -0
  35. micforge/dsp/aec.py +388 -0
  36. micforge/dsp/base.py +30 -0
  37. micforge/dsp/biquad.py +144 -0
  38. micforge/dsp/chain.py +153 -0
  39. micforge/dsp/cofilite.py +427 -0
  40. micforge/dsp/compressor.py +109 -0
  41. micforge/dsp/deesser.py +64 -0
  42. micforge/dsp/denoise.py +181 -0
  43. micforge/dsp/deverb.py +227 -0
  44. micforge/dsp/export_cofilite.py +111 -0
  45. micforge/dsp/gate.py +76 -0
  46. micforge/dsp/leveler.py +74 -0
  47. micforge/dsp/proximity.py +164 -0
  48. micforge/dsp/util.py +80 -0
  49. micforge/errors.py +25 -0
  50. micforge/logging_setup.py +25 -0
  51. micforge/models/cofilite.onnx +0 -0
  52. micforge/presets.py +284 -0
  53. micforge/profile_store.py +41 -0
  54. micforge/ui/__init__.py +0 -0
  55. micforge/ui/dashboard.py +573 -0
  56. micforge/ui/hotkeys.py +169 -0
  57. micforge/ui/keys.py +64 -0
  58. micforge/ui/report.py +88 -0
  59. micforge/ui/settings_gui.py +899 -0
  60. micforge/ui/theme.py +42 -0
  61. micforge/ui/tray.py +276 -0
  62. micforge/ui/tuning.py +138 -0
  63. micforge/ui/widgets.py +109 -0
  64. micforge/util/autostart.py +56 -0
  65. micforge-1.3.0.dist-info/METADATA +334 -0
  66. micforge-1.3.0.dist-info/RECORD +70 -0
  67. micforge-1.3.0.dist-info/WHEEL +5 -0
  68. micforge-1.3.0.dist-info/entry_points.txt +2 -0
  69. micforge-1.3.0.dist-info/licenses/LICENSE +22 -0
  70. micforge-1.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,74 @@
1
+ """Slow automatic level control (so quiet and loud talking end up similar)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+
6
+ import numpy as np
7
+
8
+ from .base import Processor
9
+ from .util import block_rms, db2lin_a, expand_gain, time_const_coeff
10
+
11
+
12
+ class Leveler(Processor):
13
+ name = "leveler"
14
+
15
+ def __init__(
16
+ self,
17
+ sample_rate: int,
18
+ target_db: float = -20.0,
19
+ max_gain_db: float = 9.0,
20
+ max_cut_db: float = 6.0,
21
+ gate_db: float = -48.0,
22
+ attack_ms: float = 250.0,
23
+ release_ms: float = 1500.0,
24
+ window_ms: float = 400.0,
25
+ enabled: bool = True,
26
+ ) -> None:
27
+ super().__init__(sample_rate, enabled)
28
+ self.target_db = target_db
29
+ self.max_gain_db = max_gain_db
30
+ self.max_cut_db = max_cut_db
31
+ self.gate_db = gate_db
32
+ self.attack_ms = attack_ms
33
+ self.release_ms = release_ms
34
+ self.window_ms = window_ms
35
+ self._size = max(16, int(sample_rate * 0.01))
36
+ self.reset()
37
+
38
+ def reset(self) -> None:
39
+ self._g_db = 0.0
40
+ self._power: float | None = None
41
+ self._prev = 1.0
42
+
43
+ def process(self, x: np.ndarray) -> np.ndarray:
44
+ n = x.shape[0]
45
+ if n == 0:
46
+ return x
47
+ size = self._size
48
+ rate = self.sample_rate / size
49
+ a_win = time_const_coeff(self.window_ms, rate)
50
+ a_dn = time_const_coeff(self.attack_ms, rate)
51
+ a_up = time_const_coeff(self.release_ms, rate)
52
+
53
+ rms = block_rms(x, size)
54
+ g = self._g_db
55
+ out = np.empty(rms.shape[0])
56
+ for i, r in enumerate(rms):
57
+ p = float(r * r)
58
+ level_db = 10.0 * math.log10(max(p, 1e-20))
59
+ if level_db > self.gate_db: # only learn from actual speech
60
+ self._power = p if self._power is None else a_win * self._power + (1 - a_win) * p
61
+ if self._power is not None and level_db > self.gate_db:
62
+ lv = 10.0 * math.log10(max(self._power, 1e-20))
63
+ desired = min(self.max_gain_db, max(-self.max_cut_db, self.target_db - lv))
64
+ coef = a_dn if desired < g else a_up
65
+ g = desired + coef * (g - desired)
66
+ out[i] = g
67
+ self._g_db = float(g)
68
+ gains = db2lin_a(out)
69
+ gain = expand_gain(self._prev, gains, n, size)
70
+ self._prev = float(gains[-1])
71
+ return x * gain
72
+
73
+ def telemetry(self) -> dict[str, float]:
74
+ return {"gain_db": self._g_db}
@@ -0,0 +1,164 @@
1
+ """Voice Proximity and Chest Resonance Synthesizer.
2
+
3
+ Simulates the physical acoustic proximity effect of professional cardioid broadcast
4
+ microphones (e.g. Shure SM7B, Electro-Voice RE20) for thin headset, USB, or desk mics.
5
+
6
+ Features:
7
+ 1. Dynamic Chest Resonance: Level-dependent resonant boost (80-180 Hz) tailored to
8
+ the human vocal fundamental (F0), avoiding low-frequency rumble during silence.
9
+ 2. Even-Harmonic Warmth: Gentle asymmetric tube/transformer saturation on low frequencies,
10
+ adding depth and broadcast thickness.
11
+ 3. Adaptive Anti-Mud Guard: Proportional attenuation around 250-350 Hz to keep speech
12
+ clear, articulate, and free of "boxy" resonance.
13
+ 4. Ultra-low latency: Zero algorithmic delay, <0.05ms execution time per 10ms block.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from .base import Processor
23
+ from .biquad import design_biquad, sosfilt
24
+ from .util import EPS, db2lin, lin2db
25
+
26
+
27
+ class VoiceProximity(Processor):
28
+ name = "proximity"
29
+
30
+ def __init__(
31
+ self,
32
+ sample_rate: int,
33
+ amount: float = 0.5,
34
+ body_hz: float = 120.0,
35
+ warmth: float = 0.35,
36
+ mud_cleanup: float = 0.4,
37
+ enabled: bool = True,
38
+ ) -> None:
39
+ super().__init__(sample_rate, enabled)
40
+ self.amount = float(min(1.0, max(0.0, amount)))
41
+ self.body_hz = float(min(250.0, max(70.0, body_hz)))
42
+ self.warmth = float(min(1.0, max(0.0, warmth)))
43
+ self.mud_cleanup = float(min(1.0, max(0.0, mud_cleanup)))
44
+
45
+ # Filter states
46
+ self._zi_body: np.ndarray | None = None
47
+ self._zi_mud: np.ndarray | None = None
48
+ self._zi_lowpass: np.ndarray | None = None
49
+
50
+ # Level follower for speech presence
51
+ self._env = 0.0
52
+ self._boost_telemetry = 0.0
53
+ self._warmth_telemetry = 0.0
54
+
55
+ # Pre-allocated scratch buffers
56
+ self._scratch_low = np.zeros(1024, dtype=np.float32)
57
+ self._scratch_body = np.zeros(1024, dtype=np.float32)
58
+
59
+ self._recompute_filters()
60
+
61
+ def _recompute_filters(self) -> None:
62
+ fs = float(self.sample_rate)
63
+ # 1. Body peak filter around body_hz (80-180 Hz)
64
+ # Maximum boost is +9 dB when amount = 1.0
65
+ peak_gain_db = self.amount * 8.5
66
+ sos_body = design_biquad("peak", fs, self.body_hz, q=1.2, gain_db=peak_gain_db)
67
+ self._sos_body = np.atleast_2d(sos_body)
68
+ self._zi_body = np.zeros((self._sos_body.shape[0], 2), dtype=np.float64)
69
+
70
+ # 2. Mud cleanup notch around 280-320 Hz
71
+ # Cuts up to -4.5 dB when mud_cleanup and amount are high
72
+ mud_hz = min(self.body_hz * 2.5, 340.0)
73
+ mud_cut_db = - (self.amount * self.mud_cleanup * 4.5)
74
+ sos_mud = design_biquad("peak", fs, mud_hz, q=1.4, gain_db=mud_cut_db)
75
+ self._sos_mud = np.atleast_2d(sos_mud)
76
+ self._zi_mud = np.zeros((self._sos_mud.shape[0], 2), dtype=np.float64)
77
+
78
+ # 3. Lowpass filter at 250 Hz for harmonic warmth saturation path
79
+ sos_lp = design_biquad("lowpass", fs, 250.0, q=0.7071)
80
+ self._sos_lp = np.atleast_2d(sos_lp)
81
+ self._zi_lowpass = np.zeros((self._sos_lp.shape[0], 2), dtype=np.float64)
82
+
83
+ def set_amount(self, amount: float) -> None:
84
+ self.amount = float(min(1.0, max(0.0, amount)))
85
+ self._recompute_filters()
86
+
87
+ def set_body_hz(self, hz: float) -> None:
88
+ self.body_hz = float(min(250.0, max(70.0, hz)))
89
+ self._recompute_filters()
90
+
91
+ def set_warmth(self, warmth: float) -> None:
92
+ self.warmth = float(min(1.0, max(0.0, warmth)))
93
+
94
+ def set_mud_cleanup(self, cleanup: float) -> None:
95
+ self.mud_cleanup = float(min(1.0, max(0.0, cleanup)))
96
+ self._recompute_filters()
97
+
98
+ def reset(self) -> None:
99
+ if self._zi_body is not None:
100
+ self._zi_body.fill(0.0)
101
+ if self._zi_mud is not None:
102
+ self._zi_mud.fill(0.0)
103
+ if self._zi_lowpass is not None:
104
+ self._zi_lowpass.fill(0.0)
105
+ self._env = 0.0
106
+ self._boost_telemetry = 0.0
107
+ self._warmth_telemetry = 0.0
108
+
109
+ def process(self, x: np.ndarray) -> np.ndarray:
110
+ if not self.enabled or self.amount <= 1e-4 or x.size == 0:
111
+ return x
112
+
113
+ n = x.shape[0]
114
+
115
+ # 1. Speech activity envelope (tracks RMS to avoid boosting background room rumble)
116
+ x_rms = float(np.sqrt(np.mean(x * x)))
117
+ # Attack fast (10ms), release medium (80ms)
118
+ att = 0.15
119
+ rel = 0.02
120
+ if x_rms > self._env:
121
+ self._env = (1.0 - att) * self._env + att * x_rms
122
+ else:
123
+ self._env = (1.0 - rel) * self._env + rel * x_rms
124
+
125
+ # Smooth voicing gate: between -45 dBFS and -25 dBFS
126
+ env_db = 20.0 * math.log10(max(self._env, EPS))
127
+ # Gate factor: 0.0 (silence) to 1.0 (voiced speech)
128
+ voice_factor = float(np.clip((env_db + 45.0) / 20.0, 0.0, 1.0))
129
+
130
+ if voice_factor < 0.05:
131
+ self._boost_telemetry = 0.0
132
+ self._warmth_telemetry = 0.0
133
+ return x
134
+
135
+ # 2. Body resonance & Mud cleanup filters
136
+ filtered, self._zi_body = sosfilt(self._sos_body, x, zi=self._zi_body)
137
+ cleaned, self._zi_mud = sosfilt(self._sos_mud, filtered, zi=self._zi_mud)
138
+
139
+ # Blend dry and filtered based on voice presence
140
+ eff_amount = self.amount * voice_factor
141
+ y = (1.0 - eff_amount) * x + eff_amount * cleaned
142
+
143
+ # 3. Low-Frequency Harmonic Saturation (Warmth)
144
+ if self.warmth > 0.01:
145
+ # Extract low frequencies below 250 Hz
146
+ low_band, self._zi_lowpass = sosfilt(self._sos_lp, x, zi=self._zi_lowpass)
147
+ # Asymmetric soft-knee saturation: adds even-order 2nd harmonic (warmth)
148
+ # and mild 3rd harmonic (density)
149
+ drive = self.warmth * 2.2 * voice_factor
150
+ sat_low = np.tanh(low_band * (1.0 + drive)) - low_band
151
+ y = y + sat_low * (self.warmth * 0.45 * voice_factor)
152
+ self._warmth_telemetry = drive
153
+ else:
154
+ self._warmth_telemetry = 0.0
155
+
156
+ self._boost_telemetry = self.amount * 8.5 * voice_factor
157
+ return y.astype(np.float32, copy=False)
158
+
159
+ def telemetry(self) -> dict[str, float]:
160
+ return {
161
+ "boost_db": self._boost_telemetry,
162
+ "warmth_drive": self._warmth_telemetry,
163
+ }
164
+
micforge/dsp/util.py ADDED
@@ -0,0 +1,80 @@
1
+ """Small numeric helpers shared by the DSP stages."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+
6
+ import numpy as np
7
+
8
+ EPS = 1e-10
9
+
10
+
11
+ def db2lin(db: float) -> float:
12
+ return 10.0 ** (db / 20.0)
13
+
14
+
15
+ def lin2db(x: float) -> float:
16
+ return 20.0 * math.log10(max(x, EPS))
17
+
18
+
19
+ def db2lin_a(db: np.ndarray | float) -> np.ndarray:
20
+ return np.power(10.0, np.asarray(db, dtype=np.float64) / 20.0)
21
+
22
+
23
+ def lin2db_a(x: np.ndarray | float) -> np.ndarray:
24
+ return 20.0 * np.log10(np.maximum(np.asarray(x, dtype=np.float64), EPS))
25
+
26
+
27
+ def rms_db(x: np.ndarray) -> float:
28
+ if x.size == 0:
29
+ return -120.0
30
+ return 10.0 * math.log10(max(float(np.mean(np.square(x, dtype=np.float64))), EPS * EPS))
31
+
32
+
33
+ def peak_db(x: np.ndarray) -> float:
34
+ if x.size == 0:
35
+ return -120.0
36
+ return lin2db(float(np.max(np.abs(x))))
37
+
38
+
39
+ def time_const_coeff(ms: float, rate_hz: float) -> float:
40
+ """One-pole smoothing coefficient for a time constant of `ms` at `rate_hz`."""
41
+ if ms <= 0:
42
+ return 0.0
43
+ return math.exp(-1.0 / (ms * 1e-3 * rate_hz))
44
+
45
+
46
+ def n_blocks(n: int, size: int) -> int:
47
+ return -(-n // size)
48
+
49
+
50
+ def block_peak(x: np.ndarray, size: int) -> np.ndarray:
51
+ n = x.shape[0]
52
+ m = n_blocks(n, size)
53
+ pad = m * size - n
54
+ a = np.abs(x)
55
+ if pad:
56
+ a = np.concatenate((a, np.zeros(pad, dtype=a.dtype)))
57
+ return a.reshape(m, size).max(axis=1)
58
+
59
+
60
+ def block_rms(x: np.ndarray, size: int) -> np.ndarray:
61
+ n = x.shape[0]
62
+ m = n_blocks(n, size)
63
+ pad = m * size - n
64
+ sq = np.square(x, dtype=np.float64)
65
+ if pad:
66
+ sq = np.concatenate((sq, np.zeros(pad)))
67
+ sums = sq.reshape(m, size).sum(axis=1)
68
+ counts = np.full(m, float(size))
69
+ if pad:
70
+ counts[-1] = size - pad
71
+ return np.sqrt(sums / counts)
72
+
73
+
74
+ def expand_gain(prev: float, targets: np.ndarray, n: int, size: int) -> np.ndarray:
75
+ """Linearly ramp a per-sub-block gain curve out to one gain value per sample."""
76
+ m = targets.shape[0]
77
+ edges = np.minimum(np.arange(1, m + 1) * size, n)
78
+ xp = np.concatenate(([0], edges))
79
+ fp = np.concatenate(([prev], targets))
80
+ return np.interp(np.arange(n), xp, fp).astype(np.float32)
micforge/errors.py ADDED
@@ -0,0 +1,25 @@
1
+ """Exception hierarchy. The CLI catches MicforgeError and prints it cleanly."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class MicforgeError(Exception):
6
+ """Base class for all expected, user-facing errors."""
7
+
8
+ hint: str | None = None
9
+
10
+ def __init__(self, message: str, hint: str | None = None) -> None:
11
+ super().__init__(message)
12
+ if hint:
13
+ self.hint = hint
14
+
15
+
16
+ class ConfigError(MicforgeError):
17
+ """Invalid or unreadable configuration."""
18
+
19
+
20
+ class DeviceError(MicforgeError):
21
+ """Audio device missing, unsupported, or ambiguous."""
22
+
23
+
24
+ class AudioBackendError(MicforgeError):
25
+ """PortAudio / sounddevice unavailable or failed."""
@@ -0,0 +1,25 @@
1
+ """File-only logging. Console logging would corrupt the live dashboard."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from logging.handlers import RotatingFileHandler
6
+
7
+ from .config import APP_NAME, config_dir
8
+
9
+
10
+ def setup_logging(debug: bool = False) -> None:
11
+ root = logging.getLogger(APP_NAME)
12
+ if root.handlers:
13
+ return
14
+ root.setLevel(logging.DEBUG if debug else logging.INFO)
15
+ try:
16
+ d = config_dir()
17
+ d.mkdir(parents=True, exist_ok=True)
18
+ handler: logging.Handler = RotatingFileHandler(
19
+ d / f"{APP_NAME}.log", maxBytes=512_000, backupCount=2, encoding="utf-8"
20
+ )
21
+ except OSError:
22
+ handler = logging.NullHandler()
23
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
24
+ root.addHandler(handler)
25
+ root.propagate = False
Binary file
micforge/presets.py ADDED
@@ -0,0 +1,284 @@
1
+ """Built-in presets + user presets (JSON files in <config dir>/presets/)."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .config import ChainConfig, DenoiseConfig, EQBand, GateConfig, config_dir
13
+ from .errors import ConfigError
14
+
15
+
16
+ def _discord() -> ChainConfig:
17
+ return ChainConfig(
18
+ highpass_hz=90,
19
+ eq=[
20
+ EQBand("peak", 300, -2.5, 1.0), # clear boxy "mud"
21
+ EQBand("peak", 3200, 3.0, 0.9), # presence / intelligibility
22
+ EQBand("highshelf", 9000, 3.0, 0.7), # air
23
+ ],
24
+ )
25
+
26
+
27
+ def _de_muffle() -> ChainConfig:
28
+ cfg = _discord()
29
+ cfg.eq = [
30
+ EQBand("peak", 250, -3.5, 1.0),
31
+ EQBand("peak", 2800, 4.5, 0.8),
32
+ EQBand("peak", 5000, 3.0, 1.0),
33
+ EQBand("highshelf", 8500, 5.0, 0.7),
34
+ ]
35
+ cfg.denoise = DenoiseConfig(strength=0.8, max_reduction_db=20)
36
+ cfg.deesser.threshold_db = -34.0
37
+ cfg.deesser.ratio = 4.0
38
+ return cfg
39
+
40
+
41
+ def _noisy_room() -> ChainConfig:
42
+ cfg = _discord()
43
+ cfg.highpass_hz = 110
44
+ cfg.denoise = DenoiseConfig(strength=1.0, max_reduction_db=28)
45
+ cfg.gate = GateConfig(threshold_db=-44, range_db=30, hold_ms=100)
46
+ return cfg
47
+
48
+
49
+ def _gaming() -> ChainConfig:
50
+ cfg = _discord()
51
+ cfg.aec.enabled = True # Ready to cancel game speaker bleed
52
+ cfg.deverb.amount = 0.45
53
+ cfg.proximity.amount = 0.55
54
+ cfg.proximity.warmth = 0.4
55
+ return cfg
56
+
57
+
58
+ def _broadcast() -> ChainConfig:
59
+ cfg = _discord()
60
+ cfg.highpass_hz = 75
61
+ cfg.deverb.amount = 0.5
62
+ cfg.deverb.room_decay = 0.35
63
+ cfg.proximity.amount = 0.75 # Deep radio chest resonance
64
+ cfg.proximity.body_hz = 115.0
65
+ cfg.proximity.warmth = 0.5
66
+ cfg.proximity.mud_cleanup = 0.5
67
+ cfg.compressor.makeup_db = 2.5
68
+ return cfg
69
+
70
+
71
+ def _studio() -> ChainConfig:
72
+ cfg = ChainConfig(
73
+ highpass_hz=70,
74
+ eq=[EQBand("peak", 3500, 1.5, 0.8), EQBand("highshelf", 10000, 1.5, 0.7)],
75
+ )
76
+ cfg.denoise = DenoiseConfig(strength=0.25, max_reduction_db=10)
77
+ cfg.deverb.amount = 0.25
78
+ cfg.proximity.amount = 0.35
79
+ cfg.gate.enabled = False
80
+ cfg.leveler.enabled = False
81
+ cfg.compressor.ratio = 2.0
82
+ cfg.compressor.makeup_db = 1.5
83
+ return cfg
84
+
85
+
86
+ def _bypass() -> ChainConfig:
87
+ cfg = ChainConfig(highpass_hz=0)
88
+ cfg.aec.enabled = False
89
+ cfg.denoise.enabled = False
90
+ cfg.deverb.enabled = False
91
+ cfg.gate.enabled = False
92
+ cfg.proximity.enabled = False
93
+ cfg.eq_enabled = False
94
+ cfg.deesser.enabled = False
95
+ cfg.leveler.enabled = False
96
+ cfg.compressor.enabled = False
97
+ cfg.limiter.enabled = False
98
+ return cfg
99
+
100
+
101
+ BUILTIN: dict[str, tuple[Any, str]] = {
102
+ "discord": (_discord, "Balanced default: de-mud, presence boost, noise suppression, leveling."),
103
+ "gaming": (_gaming, "Optimized for gaming: AEC echo cancellation, room de-verb, voice punch."),
104
+ "broadcast": (_broadcast, "Rich radio presence: deep chest resonance, warmth, studio de-verb."),
105
+ "de_muffle": (_de_muffle, "Stronger brightening for dull/muffled mics (headset, bad placement)."),
106
+ "noisy_room": (_noisy_room, "Aggressive denoise + gate for fans, keyboards, thin walls."),
107
+ "studio": (_studio, "Light touch for good mics in quiet rooms."),
108
+ "bypass": (_bypass, "Everything off. Useful for A/B and routing checks."),
109
+ }
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class PresetInfo:
114
+ name: str
115
+ description: str
116
+ builtin: bool
117
+
118
+
119
+ def user_preset_dir() -> Path:
120
+ return config_dir() / "presets"
121
+
122
+
123
+ def sanitize_preset_name(name: str) -> str:
124
+ """Sanitize preset name to be safe for filenames and CLI arguments."""
125
+ clean = re.sub(r"[^\w\-. ]", "_", name.strip())
126
+ clean = clean.replace(" ", "_")
127
+ if not clean:
128
+ raise ConfigError("Preset name cannot be empty.")
129
+ return clean
130
+
131
+
132
+ def _user_presets() -> dict[str, ChainConfig]:
133
+ out: dict[str, ChainConfig] = {}
134
+ d = user_preset_dir()
135
+ if not d.is_dir():
136
+ return out
137
+ for p in sorted(d.glob("*.json")):
138
+ try:
139
+ raw = json.loads(p.read_text(encoding="utf-8"))
140
+ if isinstance(raw, dict):
141
+ out[p.stem] = ChainConfig.from_dict(raw)
142
+ except (OSError, ValueError, ConfigError):
143
+ continue # a broken user file must never take the app down
144
+ return out
145
+
146
+
147
+ def list_presets() -> list[PresetInfo]:
148
+ """List all presets (built-in and custom user presets) with descriptions."""
149
+ infos = [PresetInfo(n, desc, True) for n, (_, desc) in BUILTIN.items()]
150
+ user_map = _user_presets()
151
+ d = user_preset_dir()
152
+ for name, cfg in user_map.items():
153
+ if name in BUILTIN:
154
+ continue
155
+ desc = "Custom user preset"
156
+ json_path = d / f"{name}.json"
157
+ if json_path.is_file():
158
+ try:
159
+ raw = json.loads(json_path.read_text(encoding="utf-8"))
160
+ if isinstance(raw, dict) and "_description" in raw and raw["_description"]:
161
+ desc = str(raw["_description"])
162
+ except Exception:
163
+ pass
164
+ infos.append(PresetInfo(name, desc, False))
165
+ return infos
166
+
167
+
168
+ def get_preset(name: str) -> ChainConfig:
169
+ """Retrieve preset ChainConfig by name (user preset takes priority, then built-in)."""
170
+ user = _user_presets()
171
+ if name in user:
172
+ return copy.deepcopy(user[name])
173
+ if name in BUILTIN:
174
+ return BUILTIN[name][0]()
175
+ raise ConfigError(
176
+ f"Unknown preset {name!r}.",
177
+ hint="Available: " + ", ".join(p.name for p in list_presets()),
178
+ )
179
+
180
+
181
+ def get_preset_description(name: str) -> str:
182
+ """Retrieve preset human-readable description by name."""
183
+ for p in list_presets():
184
+ if p.name == name:
185
+ return p.description
186
+ return ""
187
+
188
+
189
+ def save_preset(
190
+ name: str,
191
+ config: ChainConfig,
192
+ overwrite: bool = False,
193
+ description: str = "",
194
+ ) -> Path:
195
+ """Save a custom user preset to disk."""
196
+ clean_name = sanitize_preset_name(name)
197
+ if clean_name.lower() in {k.lower() for k in BUILTIN}:
198
+ raise ConfigError(
199
+ f"Cannot overwrite built-in preset '{clean_name}'. Please choose a custom name."
200
+ )
201
+
202
+ target = user_preset_dir() / f"{clean_name}.json"
203
+ if target.is_file() and not overwrite:
204
+ raise ConfigError(
205
+ f"Preset '{clean_name}' already exists. Use overwrite=True or pass --force to replace it."
206
+ )
207
+
208
+ config.validate()
209
+ data = config.to_dict()
210
+ data["_name"] = clean_name
211
+ data["_description"] = description or "Custom user preset"
212
+ data["_updated_at"] = datetime.now(timezone.utc).isoformat()
213
+
214
+ target.parent.mkdir(parents=True, exist_ok=True)
215
+ target.write_text(json.dumps(data, indent=2), encoding="utf-8")
216
+ return target
217
+
218
+
219
+ def delete_preset(name: str) -> None:
220
+ """Delete a custom user preset from disk."""
221
+ clean_name = sanitize_preset_name(name)
222
+ if clean_name.lower() in {k.lower() for k in BUILTIN}:
223
+ raise ConfigError(f"Cannot delete built-in preset '{clean_name}'. Built-ins are permanent.")
224
+
225
+ target = user_preset_dir() / f"{clean_name}.json"
226
+ if not target.is_file():
227
+ raise ConfigError(f"User preset '{clean_name}' does not exist.")
228
+
229
+ target.unlink()
230
+
231
+
232
+ def export_preset(name: str, target_path: str | Path) -> Path:
233
+ """Export a preset (built-in or user) to an external JSON file."""
234
+ cfg = get_preset(name)
235
+ target = Path(target_path).resolve()
236
+ target.parent.mkdir(parents=True, exist_ok=True)
237
+
238
+ data = cfg.to_dict()
239
+ data["_name"] = name
240
+ data["_exported_from"] = "micforge"
241
+ data["_exported_at"] = datetime.now(timezone.utc).isoformat()
242
+
243
+ target.write_text(json.dumps(data, indent=2), encoding="utf-8")
244
+ return target
245
+
246
+
247
+ def import_preset(
248
+ source_path: str | Path,
249
+ name: str | None = None,
250
+ overwrite: bool = False,
251
+ ) -> str:
252
+ """Import an external preset JSON file into user presets."""
253
+ src = Path(source_path).resolve()
254
+ if not src.is_file():
255
+ raise ConfigError(f"Preset file not found: {src}")
256
+
257
+ try:
258
+ raw = json.loads(src.read_text(encoding="utf-8"))
259
+ except Exception as exc:
260
+ raise ConfigError(f"Invalid JSON file in {src.name}: {exc}")
261
+
262
+ if not isinstance(raw, dict):
263
+ raise ConfigError(f"Preset file {src.name} must contain a JSON dictionary.")
264
+
265
+ cfg = ChainConfig.from_dict(raw)
266
+ target_name = name or raw.get("_name") or src.stem
267
+ desc = raw.get("_description", f"Imported from {src.name}")
268
+
269
+ save_preset(target_name, cfg, overwrite=overwrite, description=desc)
270
+ return sanitize_preset_name(target_name)
271
+
272
+
273
+ def clone_preset(
274
+ source_name: str,
275
+ new_name: str,
276
+ overwrite: bool = False,
277
+ description: str = "",
278
+ ) -> ChainConfig:
279
+ """Clone an existing preset (built-in or user) as a new custom preset."""
280
+ src_cfg = get_preset(source_name)
281
+ cloned = copy.deepcopy(src_cfg)
282
+ desc = description or f"Cloned from {source_name}"
283
+ save_preset(new_name, cloned, overwrite=overwrite, description=desc)
284
+ return cloned
@@ -0,0 +1,41 @@
1
+ """Persist the calibrated room-noise profile."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+
6
+ import numpy as np
7
+
8
+ from .config import config_dir
9
+
10
+ log = logging.getLogger("micforge.profile")
11
+
12
+
13
+ def _path(sample_rate: int):
14
+ return config_dir() / f"noise_profile_{sample_rate}.npz"
15
+
16
+
17
+ def save_profile(psd: np.ndarray, sample_rate: int, noise_db: float, gate_threshold_db: float) -> None:
18
+ p = _path(sample_rate)
19
+ p.parent.mkdir(parents=True, exist_ok=True)
20
+ np.savez(p, psd=psd, sample_rate=sample_rate, noise_db=noise_db, gate_threshold_db=gate_threshold_db)
21
+
22
+
23
+ def load_profile(sample_rate: int) -> tuple[np.ndarray, float, float] | None:
24
+ """Returns (psd, noise_db, gate_threshold_db) or None."""
25
+ p = _path(sample_rate)
26
+ if not p.exists():
27
+ return None
28
+ try:
29
+ with np.load(p) as z:
30
+ return z["psd"].astype(np.float64), float(z["noise_db"]), float(z["gate_threshold_db"])
31
+ except (OSError, ValueError, KeyError):
32
+ log.warning("ignoring unreadable noise profile %s", p)
33
+ return None
34
+
35
+
36
+ def clear_profile(sample_rate: int) -> bool:
37
+ p = _path(sample_rate)
38
+ if p.exists():
39
+ p.unlink()
40
+ return True
41
+ return False
File without changes