Skip to content

Commit 3cef5dc

Browse files
felixperflerclaude
andcommitted
Address the 18 November code and Mac UI review
- Saving settings keeps the NumCalc mode and saved microphone positions. Omitted editable keys are preserved, null clears them, desktop runs use --numcalc-mode local, and placements are stamped with their mesh so runs ignore positions picked on a different mesh. - project load/save carry a settings revision; a save over a changed file fails with SettingsRevisionConflict and both apps offer to reload. - output_dir no longer defaults into the install location; YAML settings default to their own folder. - Loading and dry runs no longer rewrite legacy files; migrate-settings and app saves migrate head_radius explicitly. - project stage-status returns the final freshness verdict for every receipt format; the Mac and Windows legacy checks are removed. - Mac inspector shows effective defaults, "Awaiting ..." statuses, the resolved Run action, and no duplicate sidebar subtitles. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8a9d489 commit 3cef5dc

34 files changed

Lines changed: 1576 additions & 579 deletions

‎HRTFCalculation/CLI.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,20 @@
1919
def cli() -> None:
2020
arguments = sys.argv[1:]
2121
if not arguments or arguments[0] in {"-h", "--help"}:
22-
print("usage: Pinna2HRTF {" + "|".join((*STEPS, *MACHINE_COMMANDS, "geometry", "ear-canal")) + "} [options]")
22+
print("usage: Pinna2HRTF {" + "|".join((*STEPS, *MACHINE_COMMANDS, "geometry", "ear-canal", "migrate-settings")) + "} [options]")
2323
return
2424
step = arguments[0]
25-
if step in MACHINE_COMMANDS or step in {"geometry", "ear-canal"}:
25+
if step in MACHINE_COMMANDS or step in {"geometry", "ear-canal", "migrate-settings"}:
2626
sys.argv = [f"Pinna2HRTF {step}", *arguments[1:]]
2727
if step == "ear-canal":
2828
from .Preprocessing.src.ear_canal_closer import main
2929
main()
3030
elif step == "geometry":
3131
from .Geometry import main
3232
main()
33+
elif step == "migrate-settings":
34+
from .Compatibility import main
35+
main()
3336
else:
3437
from .Commands import machine_command
3538
machine_command(step)

‎HRTFCalculation/Compatibility.py‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@
77
import os
88
from pathlib import Path
99
import shutil
10+
import sys
1011
import tempfile
11-
import warnings
1212

1313
import yaml
1414

1515
DEPRECATION = "Deprecated; use ear_distance. Will be removed in a future version."
16+
LEGACY_DISTANCE_IMPORTED = "Imported legacy preprocessing.head_radius as ear_distance. Save the project or run Pinna2HRTF migrate-settings to update the file."
1617

1718

1819
def import_legacy_distance(data):
@@ -55,13 +56,13 @@ def annotate_legacy_distance(path, text, encoding, raw):
5556
"""
5657
tree = yaml.compose(text)
5758
if not isinstance(tree, yaml.MappingNode):
58-
return
59+
return False
5960
settings = next((v for k, v in tree.value if k.value == "preprocessing"), None)
6061
if not isinstance(settings, yaml.MappingNode):
61-
return
62+
return False
6263
legacy = next(((k, v) for k, v in settings.value if k.value == "head_radius"), None)
6364
if legacy is None:
64-
return
65+
return False
6566
has_distance = any(k.value == "ear_distance" for k, _ in settings.value)
6667
key, value = legacy
6768
newline = "\r\n" if "\r\n" in text else "\r" if "\r" in text else "\n"
@@ -95,7 +96,7 @@ def annotate_legacy_distance(path, text, encoding, raw):
9596
lines.insert(index + 1, " " * key.start_mark.column + "ear_distance: " + scalar + newline)
9697
updated = "".join(lines)
9798
if updated == text:
98-
return
99+
return False
99100
if import_legacy_distance(yaml.safe_load(updated)) != import_legacy_distance(yaml.safe_load(text)):
100101
raise ValueError("Compatibility annotation changed settings unexpectedly.")
101102
path = Path(path)
@@ -119,20 +120,24 @@ def annotate_legacy_distance(path, text, encoding, raw):
119120
finally:
120121
if temporary is not None and temporary.exists():
121122
temporary.unlink()
123+
return True
122124

123125

124126
def main():
125-
"""Native apps use this loader so compatibility edits share one implementation."""
126127
import argparse
127-
from .Config import load_config
128-
parser = argparse.ArgumentParser(description=__doc__)
128+
from .Config import PipelineConfig
129+
parser = argparse.ArgumentParser(description="Rewrite a legacy preprocessing.head_radius setting as ear_distance. The original file is kept as <name>.head-radius-compat.bak.")
129130
parser.add_argument("path")
130131
args = parser.parse_args()
131-
with warnings.catch_warnings(record=True) as notices:
132-
warnings.simplefilter("always")
133-
config = load_config(args.path)
134-
print(json.dumps({"ear_distance": config.preprocessing.ear_distance,
135-
"warnings": [str(item.message) for item in notices]}))
132+
path = Path(args.path).expanduser().resolve()
133+
try:
134+
raw, text, encoding = read_settings(path)
135+
config = PipelineConfig.model_validate(import_legacy_distance(yaml.safe_load(text) or {}))
136+
migrated = annotate_legacy_distance(path, text, encoding, raw)
137+
except (OSError, ValueError, yaml.YAMLError) as error:
138+
print(json.dumps({"error": type(error).__name__, "message": str(error)}), file=sys.stderr)
139+
raise SystemExit(1) from None
140+
print(json.dumps({"path": str(path), "migrated": migrated, "ear_distance": config.preprocessing.ear_distance}))
136141

137142

138143
if __name__ == "__main__":

‎HRTFCalculation/Config.py‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88

99
import yaml
1010
import warnings
11-
from .Compatibility import import_legacy_distance, read_settings, annotate_legacy_distance
11+
from .Compatibility import LEGACY_DISTANCE_IMPORTED, import_legacy_distance, read_settings
1212

1313
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
1414

1515

1616
DEFAULT_EVALUATION_GRID = "ARI_Grid"
1717
BUNDLED_EVALUATION_GRID_PATH = Path(__file__).resolve().parent / "EvaluationGrids" / DEFAULT_EVALUATION_GRID
18+
OUTPUT_DIR_REQUIRED = "Set paths.output_dir to a writable project folder. Only settings loaded from a YAML file default to that file's folder."
1819

1920

2021
def worktree_root() -> Path:
@@ -59,7 +60,7 @@ class PathsConfig(BaseModel):
5960
edited_right_ear: Path | None = None
6061
left_ear: Path | None = None
6162
right_ear: Path | None = None
62-
output_dir: Path = Field(default_factory=lambda: worktree_root() / "Data" / "temp" / "GuiRun")
63+
output_dir: Path | None = None
6364
external_deps_dir: Path = Field(default_factory=lambda: worktree_root() / "External")
6465
mesh2hrtf_path: Path | None = None
6566
numcalc_executable: Path | None = None
@@ -270,6 +271,10 @@ def resolved(self, base_dir: Path | None = None) -> "PipelineConfig":
270271
clone.manual_ppm.enabled = method == "manual"
271272
clone.inference.enabled = clone.inference.use_predictions_for_preprocessing = method == "mesh2ppm"
272273
base = Path(base_dir or Path.cwd()).resolve()
274+
if clone.paths.output_dir is None:
275+
if base_dir is None:
276+
raise ValueError(OUTPUT_DIR_REQUIRED)
277+
clone.paths.output_dir = base
273278
for section_name in ("paths", "scan_preparation", "inference", "manual_ppm", "postprocessing", "ui"):
274279
section = getattr(clone, section_name)
275280
for name, value in section:
@@ -308,13 +313,12 @@ def resolve_path(path: Path, base: Path) -> Path:
308313

309314
def load_config(path: str | Path) -> PipelineConfig:
310315
config_path = Path(path).expanduser().resolve()
311-
raw, text, encoding = read_settings(config_path)
316+
_, text, _ = read_settings(config_path)
312317
data = yaml.safe_load(text) or {}
313318
config = PipelineConfig.model_validate(import_legacy_distance(data)).resolved(config_path.parent)
314-
try:
315-
annotate_legacy_distance(config_path, text, encoding, raw)
316-
except (OSError, ValueError, yaml.YAMLError) as error:
317-
warnings.warn(f"Legacy head_radius was imported, but the settings file could not be updated: {error}", UserWarning)
319+
preprocessing = data.get("preprocessing")
320+
if isinstance(preprocessing, dict) and "head_radius" in preprocessing and "ear_distance" not in preprocessing:
321+
warnings.warn(LEGACY_DISTANCE_IMPORTED, UserWarning)
318322
return config
319323

320324

@@ -326,10 +330,6 @@ def save_config(config: PipelineConfig | dict[str, Any], path: str | Path) -> No
326330
yaml.safe_dump(data, file, sort_keys=False)
327331

328332

329-
def default_config() -> PipelineConfig:
330-
return PipelineConfig().resolved(worktree_root())
331-
332-
333333
def template_config() -> dict[str, Any]:
334334
template = PipelineConfig().yaml_dict()
335335
template["paths"] = {
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import json
2+
from pathlib import Path
3+
4+
from .FileIdentity import cached_sha256
5+
6+
PLACEMENTS_RELATIVE = Path(".pinna2hrtf") / "microphone-placements.json"
7+
PLACEMENTS_FORMAT = "pinna2hrtf-microphone-placements-v1"
8+
SIDES = ("left", "right")
9+
10+
11+
def placement_key(side: str) -> str:
12+
return "source_position_input_" + side
13+
14+
15+
def read_placements(output_dir: Path) -> dict:
16+
try:
17+
document = json.loads((Path(output_dir) / PLACEMENTS_RELATIVE).read_text(encoding="utf-8"))
18+
except (OSError, ValueError):
19+
return {}
20+
if not isinstance(document, dict) or document.get("format") != PLACEMENTS_FORMAT:
21+
return {}
22+
return {side: document[side] for side in SIDES if isinstance(document.get(side), dict)}
23+
24+
25+
def matching_record(placements: dict, side: str, position) -> dict | None:
26+
record = placements.get(side)
27+
if record is None or position is None or [float(value) for value in position] != record.get("position_mm"):
28+
return None
29+
return record
30+
31+
32+
def status(placements: dict, side: str, position, mesh: Path | None) -> str:
33+
record = matching_record(placements, side, position)
34+
if record is None:
35+
return "unrecorded"
36+
if record.get("mesh_sha256") and mesh is not None and Path(mesh).is_file() and cached_sha256(mesh) == record["mesh_sha256"]:
37+
return "current"
38+
return "stale"
39+
40+
41+
def is_stale(placements: dict, side: str, position, mesh: Path | None) -> bool:
42+
return status(placements, side, position, mesh) == "stale"
43+
44+
45+
def preprocessing_meshes(config) -> dict:
46+
from .RunConfig import preprocessing_input_paths
47+
try:
48+
return dict(zip(SIDES, preprocessing_input_paths(config, lambda _: None)))
49+
except (OSError, ValueError, KeyError):
50+
return {}
51+
52+
53+
def statuses(config) -> dict:
54+
placements = read_placements(config.paths.output_dir)
55+
positions = {side: getattr(config.preprocessing, placement_key(side)) for side in SIDES}
56+
meshes = preprocessing_meshes(config) if placements else {}
57+
return {side: status(placements, side, position, meshes.get(side)) for side, position in positions.items() if position is not None}
58+
59+
60+
def record_placements(config, confirmed_sides) -> None:
61+
previous = read_placements(config.paths.output_dir)
62+
meshes = preprocessing_meshes(config) if confirmed_sides else {}
63+
document = {"format": PLACEMENTS_FORMAT}
64+
for side in SIDES:
65+
position = getattr(config.preprocessing, placement_key(side))
66+
if position is None:
67+
continue
68+
position_mm = [float(value) for value in position]
69+
record = matching_record(previous, side, position)
70+
if side not in confirmed_sides:
71+
document[side] = {"position_mm": position_mm, "mesh_sha256": None}
72+
elif record is not None and record.get("mesh_sha256"):
73+
document[side] = record
74+
elif meshes.get(side) is not None and Path(meshes[side]).is_file():
75+
document[side] = {"position_mm": position_mm, "mesh_sha256": cached_sha256(meshes[side])}
76+
path = Path(config.paths.output_dir) / PLACEMENTS_RELATIVE
77+
if document == {"format": PLACEMENTS_FORMAT, **previous} or (len(document) == 1 and not path.exists()):
78+
return
79+
from .Outputs import write_json
80+
path.parent.mkdir(parents=True, exist_ok=True)
81+
write_json(path, document)
82+
83+
84+
def ignore_stale_placements(config, logger) -> None:
85+
placements = read_placements(config.paths.output_dir)
86+
if not placements:
87+
return
88+
meshes = preprocessing_meshes(config)
89+
for side in SIDES:
90+
position = getattr(config.preprocessing, placement_key(side))
91+
if meshes and meshes.get(side) is None:
92+
continue
93+
if is_stale(placements, side, position, meshes.get(side)):
94+
setattr(config.preprocessing, placement_key(side), None)
95+
logger(stale_message(side))
96+
97+
98+
def stale_message(side: str) -> str:
99+
return f"Ignoring the saved {side} microphone position because it does not match the current {side} ear mesh. Place the microphone again to use it."

‎HRTFCalculation/Preprocessing/__init__.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from HRTFCalculation.Config import BUNDLED_EVALUATION_GRID_PATH, DEFAULT_EVALUATION_GRID, PreprocessingConfig
1919
from HRTFCalculation.Geometry import resolve_geometry, boundary_y, needs_distance_warning
2020
from HRTFCalculation.LiveEvents import emit_live_event
21+
from HRTFCalculation.MicrophonePlacement import is_stale, read_placements, stale_message
2122

2223

2324

@@ -442,11 +443,15 @@ def archive(path, keep_one=False):
442443
stitched = {side: side_dirs[side] / "stitched_head.stl" for side, ear in ears.items() if ear is not None}
443444
graded = {side: side_dirs[side] / "graded_head.ply" for side, ear in ears.items() if ear is not None}
444445
landmarks = {}
446+
placements = read_placements(output_dir) if output_dir is not None else {}
445447
for side, ear in ears.items():
446448
if ear is None:
447449
continue
448450
source_position = settings.source_position_left if side == "left" else settings.source_position_right
449451
source_position_input = settings.source_position_input_left if side == "left" else settings.source_position_input_right
452+
if is_stale(placements, side, source_position_input, left_path if side == "left" else right_path):
453+
logger(stale_message(side))
454+
source_position_input = None
450455
if source_position is None and source_position_input is not None:
451456
source_position = tuple(coordinate + translation for coordinate, translation in zip(source_position_input, translations[side]))
452457
landmarks[side] = {"position": list(source_position), "method": "configured", "confidence": 1.0} if source_position is not None else estimate_ear_canal_position(ear, side=side)

0 commit comments

Comments
 (0)