-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
202 lines (182 loc) · 15.5 KB
/
Copy pathconfig.py
File metadata and controls
202 lines (182 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""Configuration loading, migration, and validation for the sound visualizer."""
from __future__ import annotations
import json
import os
from copy import deepcopy
from pathlib import Path
from typing import Any
DEFAULT_CONFIG: dict[str, Any] = {
"output": {"source": None, "sample_rate": 48000, "block_size": 2048, "channels": "stereo", "fft_size": 2048, "magnitude_mode": "normalized", "magnitude_scale": 1.0, "left_color": "#65E6C5", "right_color": "#FF7AC8", "color": "#65E6C5", "opacity": 1.0},
"input": {"source": None, "sample_rate": 48000, "block_size": 2048, "fft_size": 2048, "magnitude_mode": "scaled", "magnitude_scale": 4000.0, "color": "#FFB347", "opacity": 1.0},
"visual": {"bar_count": 64, "orientation": "circle", "mode": "bars", "line_style": "organic", "background_color": "#000000", "background_opacity": 0.12, "background_image": "", "frame_rate": 60, "bar_width": 0.7, "margin": 12, "radius_ratio": 0.32},
"general": {"click_through": False, "always_on_top": True, "startup_enabled": True, "frequency_min": 100.0, "frequency_max": 16000.0, "smoothing": 0.35, "decay": 0.08, "binning_method": "default", "interpolate_to_zero": False, "window_monitor": "", "window_position": {"x": 0, "y": 0}, "window_size": {"width": 500, "height": 500}, "non_empty_bins": [], "settings_window_monitor": "", "settings_window_position": {"x": 0, "y": 0}, "settings_window_size": {"width": 620, "height": 560}, "settings_window_tab": 0, "settings_window_open": False},
"data": {"show_frequency_markers": False, "marker_mode": "frequency", "data_frequency_mode": "frequency", "marker_values": "110, 220, 440, 880", "marker_opacity": 0.75, "marker_label_position": 1.0, "marker_interpolation_distance": 0.1, "marker_size_start": 0.0, "marker_size_end": 1.0, "accent_marker_size_start": 0.0, "accent_marker_size_end": 1.0, "marker_color": "#FFFFFF", "data_color": "#FFFFFF", "data_opacity": 1.0, "data_font": "Segoe UI", "update_rate": 8.0, "show_output_frequency": False, "show_output_bpm": False, "show_output_volume": False, "show_input_frequency": False, "show_input_bpm": False, "show_input_volume": False, "output_slider_enabled": False, "output_slider_size_start": 0.0, "output_slider_size_end": 1.0, "output_slider_color": "#65E6C5", "input_slider_enabled": False, "input_slider_size_start": 0.0, "input_slider_size_end": 1.0, "input_slider_color": "#FFB347", "slider_velocity": 0.05, "text_layout": {"output_frequency": {"x": 0.5, "y": 0.3, "size_factor": 0.045}, "output_bpm": {"x": 0.5, "y": 0.4, "size_factor": 0.045}, "output_volume": {"x": 0.5, "y": 0.5, "size_factor": 0.045}, "input_frequency": {"x": 0.5, "y": 0.6, "size_factor": 0.045}, "input_bpm": {"x": 0.5, "y": 0.7, "size_factor": 0.045}, "input_volume": {"x": 0.5, "y": 0.8, "size_factor": 0.045}}},
}
_ALLOWED = {"output.channels": {"mono", "stereo"}, "output.magnitude_mode": {"normalized", "scaled"}, "input.magnitude_mode": {"normalized", "scaled"}, "visual.mode": {"bars", "line"}, "visual.orientation": {"flat", "circle"}, "visual.line_style": {"trace", "organic"}, "data.marker_mode": {"frequency", "notes"}, "data.data_frequency_mode": {"frequency", "notes"}, "general.binning_method": {"default", "non_empty"}}
def config_path() -> Path:
app_data = os.environ.get("APPDATA")
return (Path(app_data) if app_data else Path.home() / ".config") / "SoundVisualizer" / "config.json"
def _merge(base: dict[str, Any], overrides: dict[str, Any]) -> dict[str, Any]:
result = deepcopy(base)
for key, value in overrides.items():
if key not in result:
continue
result[key] = _merge(result[key], value) if isinstance(value, dict) and isinstance(result.get(key), dict) else value
return result
def _get(config: dict[str, Any], path: str) -> Any:
value: Any = config
for part in path.split("."):
value = value[part]
return value
def _legacy_stream(legacy: dict[str, Any], stream: str) -> dict[str, Any]:
audio, analysis, visual = legacy.get("audio", {}), legacy.get("analysis", {}), legacy.get("visual", {})
output = stream == "output"
scale = analysis.get(f"{stream}_magnitude_scale", analysis.get("magnitude_scale", DEFAULT_CONFIG[stream]["magnitude_scale"]))
if "magnitude_scale" in analysis and scale <= 100:
scale *= 1000
result = {"source": audio.get("output_device" if output else "input_device"), "sample_rate": audio.get("sample_rate", 48000), "block_size": audio.get("block_size", 2048), "channels": "mono" if audio.get("channels") == 1 else "stereo", "fft_size": analysis.get("fft_size", 2048), "frequency_min": analysis.get("frequency_min", 100.0), "frequency_max": analysis.get("frequency_max", 16000.0), "smoothing": analysis.get("smoothing", 0.35), "decay": analysis.get("decay", 0.08), "magnitude_mode": analysis.get(f"{stream}_magnitude_mode", DEFAULT_CONFIG[stream]["magnitude_mode"]), "magnitude_scale": max(0.01, min(float(scale), 10000.0)), "opacity": visual.get("opacity", 1.0)}
if output:
result.update({"left_color": visual.get("left_color", "#65E6C5"), "right_color": visual.get("right_color", "#FF7AC8")})
else:
result["color"] = visual.get("input_color", "#FFB347")
return result
def _migrate(overrides: dict[str, Any]) -> dict[str, Any]:
if "output" in overrides and "input" in overrides and "general" in overrides:
migrated = deepcopy(overrides)
general = migrated.setdefault("general", {})
output = migrated.get("output", {})
for key in ("frequency_min", "frequency_max", "smoothing", "decay"):
if key not in general and key in output:
general[key] = output[key]
data = migrated.setdefault("data", {})
visual = migrated.setdefault("visual", {})
if isinstance(data.get("slider_velocity"), (int, float)):
data["slider_velocity"] = max(0.0, min(0.1, float(data["slider_velocity"])))
if "marker_size_start" not in data:
data["marker_size_start"] = float(data.get("marker_start", 0.0))
if "marker_size_end" not in data:
data["marker_size_end"] = float(data.get("marker_end", data.get("marker_size", 1.0)))
for stream in ("output", "input"):
size_start = f"{stream}_slider_size_start"
size_end = f"{stream}_slider_size_end"
end_key = f"{stream}_slider_end"
start_key = f"{stream}_slider_start"
if size_start not in data:
data[size_start] = float(data.get(start_key, 0.0))
if size_end not in data:
data[size_end] = float(data.get(end_key, data.get(f"{stream}_slider_size", 1.0)))
data.pop("marker_start", None)
data.pop("marker_end", None)
data.pop("marker_size", None)
data.pop("data_size_factor", None)
data.setdefault("marker_label_position", 1.0)
data.setdefault("marker_interpolation_distance", 0.1)
data.setdefault("accent_marker_size_start", data.get("marker_size_start", 0.0))
data.setdefault("accent_marker_size_end", data.get("marker_size_end", 1.0))
for stream in ("output", "input"):
data.pop(f"{stream}_slider_start", None)
data.pop(f"{stream}_slider_end", None)
data.pop(f"{stream}_slider_size", None)
if "show_output_volume" not in data:
data["show_output_volume"] = False
if "show_input_volume" not in data:
data["show_input_volume"] = False
if "radius" in visual:
visual.pop("radius", None)
migrated["input"].pop("channels", None)
if data.get("marker_mode") in {"frequency", "notes"}:
data.setdefault("data_frequency_mode", data["marker_mode"])
general["binning_method"] = "default" if general.get("binning_method") == "logarithmic" else general.get("binning_method", "default")
if isinstance(visual.get("bar_width"), (int, float)) and visual["bar_width"] > 1:
visual["bar_width"] = 0.7
for old, new in (("slider_output_enabled", "output_slider_enabled"), ("slider_output_start", "output_slider_start"), ("slider_output_end", "output_slider_end"), ("slider_input_enabled", "input_slider_enabled"), ("slider_input_start", "input_slider_start"), ("slider_input_end", "input_slider_end")):
if old in data:
data.setdefault(new, data[old])
if "show_loudest_frequency" in data:
data.setdefault("show_output_frequency", data["show_loudest_frequency"])
if "show_bpm" in data:
data.setdefault("show_output_bpm", data["show_bpm"])
if "bpm_color" in data:
data.setdefault("data_color", data["bpm_color"])
return migrated
visual, analysis, window, startup = overrides.get("visual", {}), overrides.get("analysis", {}), overrides.get("window", {}), overrides.get("startup", {})
migrated = {"output": _legacy_stream(overrides, "output"), "input": _legacy_stream(overrides, "input"), "visual": {key: visual[key] for key in DEFAULT_CONFIG["visual"] if key in visual}, "general": {"click_through": window.get("click_through", False), "always_on_top": window.get("always_on_top", True), "startup_enabled": startup.get("enabled", True), "frequency_min": analysis.get("frequency_min", 100.0), "frequency_max": analysis.get("frequency_max", 16000.0), "smoothing": analysis.get("smoothing", 0.35), "decay": analysis.get("decay", 0.08)}}
migrated["visual"]["bar_count"] = analysis.get("bar_count", DEFAULT_CONFIG["visual"]["bar_count"])
if isinstance(migrated["visual"].get("bar_width"), (int, float)) and migrated["visual"]["bar_width"] > 1:
migrated["visual"]["bar_width"] = 0.7
if visual.get("mode") == "circle":
migrated["visual"].update({"mode": "bars", "orientation": "circle"})
old_data = overrides.get("data", {})
migrated["data"] = {"show_output_frequency": old_data.get("show_loudest_frequency", False), "show_output_bpm": old_data.get("show_bpm", False)}
return migrated
def _validate(config: dict[str, Any]) -> dict[str, Any]:
for path, choices in _ALLOWED.items():
if _get(config, path) not in choices:
raise ValueError(f"{path} must be one of {sorted(choices)}")
ranges = {"sample_rate": (8000, 192000), "block_size": (128, 16384), "fft_size": (256, 65536), "magnitude_scale": (0.01, 10000.0), "opacity": (0.0, 1.0)}
for stream in ("output", "input"):
for key, (minimum, maximum) in ranges.items():
value = config[stream][key]
if not isinstance(value, (int, float)) or isinstance(value, bool) or not minimum <= value <= maximum:
raise ValueError(f"{stream}.{key} must be between {minimum} and {maximum}")
for key, (minimum, maximum) in {"frequency_min": (0.0, 20000.0), "frequency_max": (1.0, 24000.0), "smoothing": (0.0, 1.0), "decay": (0.0, 1.0)}.items():
value = config["general"][key]
if not isinstance(value, (int, float)) or isinstance(value, bool) or not minimum <= value <= maximum:
raise ValueError(f"general.{key} must be between {minimum} and {maximum}")
if config["general"]["frequency_min"] >= config["general"]["frequency_max"]:
raise ValueError("general.frequency_min must be below frequency_max")
if not isinstance(config["general"]["window_monitor"], str):
raise ValueError("general.window_monitor must be text")
for key in ("x", "y"):
if not isinstance(config["general"]["window_position"][key], int):
raise ValueError(f"general.window_position.{key} must be an integer")
for key in ("width", "height"):
if not isinstance(config["general"]["window_size"][key], int) or config["general"]["window_size"][key] < 1:
raise ValueError(f"general.window_size.{key} must be a positive integer")
for path, minimum, maximum in (("visual.bar_count", 1, 512), ("visual.background_opacity", 0.0, 1.0), ("visual.frame_rate", 1, 240), ("visual.bar_width", 0.0, 1.0), ("visual.radius_ratio", 0.0, 1.0)):
value = _get(config, path)
if not isinstance(value, (int, float)) or isinstance(value, bool) or not minimum <= value <= maximum:
raise ValueError(f"{path} must be between {minimum} and {maximum}")
if not isinstance(config["data"]["marker_values"], str):
raise ValueError("data.marker_values must be text")
for key, minimum, maximum in (("marker_opacity", 0.0, 1.0), ("marker_label_position", 0.0, 1.0), ("marker_interpolation_distance", 0.0, 0.1), ("marker_size_start", 0.0, 1.0), ("marker_size_end", 0.0, 1.0), ("accent_marker_size_start", 0.0, 1.0), ("accent_marker_size_end", 0.0, 1.0), ("data_opacity", 0.0, 1.0), ("update_rate", 0.1, 60.0), ("slider_velocity", 0.0, 0.1), ("output_slider_size_start", 0.0, 1.0), ("output_slider_size_end", 0.0, 1.0), ("input_slider_size_start", 0.0, 1.0), ("input_slider_size_end", 0.0, 1.0)):
value = config["data"][key]
if not isinstance(value, (int, float)) or isinstance(value, bool) or not minimum <= value <= maximum:
raise ValueError(f"data.{key} must be between {minimum} and {maximum}")
if config["data"]["marker_size_start"] > config["data"]["marker_size_end"]:
raise ValueError("data.marker_size_start must not exceed marker_size_end")
if config["data"]["accent_marker_size_start"] > config["data"]["accent_marker_size_end"]:
raise ValueError("data.accent_marker_size_start must not exceed accent_marker_size_end")
for stream in ("output", "input"):
if config["data"][f"{stream}_slider_size_start"] > config["data"][f"{stream}_slider_size_end"]:
raise ValueError(f"data.{stream}_slider_size_start must not exceed {stream}_slider_size_end")
if not isinstance(config["general"]["interpolate_to_zero"], bool):
raise ValueError("general.interpolate_to_zero must be boolean")
if not isinstance(config["general"]["non_empty_bins"], list) or any(not isinstance(value, bool) for value in config["general"]["non_empty_bins"]):
raise ValueError("general.non_empty_bins must be a boolean list")
for name, layout in config["data"]["text_layout"].items():
if name not in {"output_frequency", "output_bpm", "output_volume", "input_frequency", "input_bpm", "input_volume"}:
raise ValueError(f"data.text_layout contains unknown field {name}")
for key in ("x", "y"):
if not isinstance(layout[key], (int, float)) or not 0.0 <= layout[key] <= 1.0:
raise ValueError(f"data.text_layout.{name}.{key} must be between 0 and 1")
if not 0.005 <= layout["size_factor"] <= 0.25:
raise ValueError(f"data.text_layout.{name}.size_factor is invalid")
return config
def load_config(path: Path | None = None) -> dict[str, Any]:
target = path or config_path()
if not target.exists():
return deepcopy(DEFAULT_CONFIG)
try:
overrides = json.loads(target.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise ValueError(f"Could not read configuration at {target}: {error}") from error
if not isinstance(overrides, dict):
raise ValueError("Configuration root must be a JSON object")
return _validate(_merge(DEFAULT_CONFIG, _migrate(overrides)))
def save_config(config: dict[str, Any], path: Path | None = None) -> Path:
target = path or config_path()
validated = _validate(_merge(DEFAULT_CONFIG, config))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(validated, indent=2) + "\n", encoding="utf-8")
return target