diff --git a/.github/workflows/listening-lab.yml b/.github/workflows/listening-lab.yml new file mode 100644 index 00000000..873b03c2 --- /dev/null +++ b/.github/workflows/listening-lab.yml @@ -0,0 +1,37 @@ +name: Early Listening Lab GUI + +on: + push: + branches: [main] + paths: + - 'ui/listening_lab.py' + - 'tests/test_listening_lab.py' + - 'docs/LISTENING_LAB.md' + - '.github/workflows/listening-lab.yml' + pull_request: + paths: + - 'ui/listening_lab.py' + - 'tests/test_listening_lab.py' + - 'docs/LISTENING_LAB.md' + - '.github/workflows/listening-lab.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + controller-and-gui: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install Tk and virtual display + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends python3-tk xvfb + - name: Python syntax check + run: python3 -m py_compile ui/listening_lab.py tests/test_listening_lab.py + - name: Fake-player subprocess regressions + run: python3 -m unittest discover -s tests -p 'test_listening_lab.py' -v + - name: Native GUI construction under Xvfb + run: xvfb-run -a python3 ui/listening_lab.py --smoke-test diff --git a/README.md b/README.md index b9a2577b..b013b3a8 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,18 @@ PSYCLE-LINUX exists to bring the workflow and behaviour of the original Psycle M This project is not a ground-up DAW redesign. +## Early human-ear Listening Lab (experimental) + +An opt-in, **candidate-only desktop listening GUI** is available at +[`ui/listening_lab.py`](ui/listening_lab.py). It opens local `.psy` +songs with the existing C++ `psycle-player`, supports ALSA/JACK output, +Stop, optional WAV output, and hash-bound JSON listening notes. See +[the Linux setup and listening procedure](docs/LISTENING_LAB.md). + +This is a temporary human-observation harness requested on 9 November 2026, +**not** the finished Psycle tracker interface or an original-Psycle +compatibility verdict. The deferred engine/parity gates remain in force. + ## Current priority — bounded original-Psycle investigation The previous implementation roadmap is **deferred**, with its history and diff --git a/docs/LISTENING_LAB.md b/docs/LISTENING_LAB.md new file mode 100644 index 00000000..de44ae49 --- /dev/null +++ b/docs/LISTENING_LAB.md @@ -0,0 +1,121 @@ +# PSYCLE-LINUX Listening Lab — early human-ear feedback + +Status: **experimental GUI for the preserved C++ candidate player**, not the +full tracker UI or a certification of original Psycle 1.12.0 compatibility. + +This small Python/Tk desktop application makes the already-maintained +historical psycle-player executable accessible to human listening tests. +It does **not** change the original engine, import any unlicensed songs, +claim a working Machine View, or modify the frozen evidence matrix. + +The maintainer explicitly requested an early audible feedback tool on +9 November 2026, taking a narrowly scoped UI-test exception to the +deferred roadmap. The full Qt Widgets tracker UI remains deferred; this +temporary wrapper is not its architectural replacement. + +## Launch on Ubuntu + +Requires Python 3, Tk (Ubuntu package python3-tk), a desktop session, +and the previously maintained C++ psycle-player build. + +~~~sh +sudo apt-get install python3-tk +# From PSYCLE-LINUX repository root: +python3 ui/listening_lab.py +~~~ + +No PyPI packages, virtual environments, containers, or Node/npm are needed. + +If the player has not been built, reproduce the **Phase 6B historical-player** +build from .github/workflows/phase6b-player-build.yml (Ubuntu 24.04 reference). +The workflow pins the upstream support sources and historical plugin interface, +installs Qt/qmake and C++ library dependencies, and builds the C++ binary at: + +~~~text +psycle-cpp-r12005-sanitized/psycle-player/++qmake/psycle-player +~~~ + +**Do not bypass the staging hashes or copy unknown SDK files to make the +build pass.** The GUI refuses to launch when that player is missing. A +different locally built candidate path may be supplied explicitly: + +~~~sh +python3 ui/listening_lab.py \ + --player /path/to/psycle-player \ + --song /path/to/your-song.psy +~~~ + +The --player option is intentionally explicit so reports can identify the +actual executable bytes; selecting an executable does not assert that it is +the frozen Phase 6B build. The GUI hashes both song and player in its report. + +## Listening procedure + +1. **Lower system output volume** before starting. There is no in-app gain + limiter; headphones and speakers are driven by the selected audio backend. +2. Load a .psy song you own or are permitted to test. Use project-generated + synthetic fixtures where practical. The public repository deliberately + excludes historical demo songs with unresolved redistribution permissions. +3. Select alsa (typical desktop), jack (if available), or dummy (silent + diagnostic control). Optional device names are forwarded literally as + separate arguments, with no shell expansion. Driver availability depends on + the compiled player, and the historical player may fall back to + dummy after reporting an unavailable output driver: **audio silence is + not proof that the song has no sound**. +4. Click **Play song** and listen. The historical CLI loops until stopped; + the GUI sends Enter to its --wait stdin to stop and finalize. + A bounded terminate/kill fallback prevents a hung child from running + indefinitely. **Stop normally before closing or interrupting WAV export** + so the output file has a chance to finalize. +5. Optionally select a fresh, non-existing .wav output destination before + pressing Play. The GUI refuses to overwrite an existing WAV path. +6. Classify the listening result, describe the audible fault and reproduction + steps, and **Save listening report** as JSON. The report includes SHA-256 + of song and player, runtime driver/device, the observed process exit code, + notes and a bounded tail of diagnostics. Reports may contain local file + paths and personal notes: review before publishing. + +Configured third-party native/LADSPA plugin paths are **disabled by default**. +Enabling them is a deliberate local opt-in, not a safety certification. +The historical player is not plugin-sandboxed; do not load untrusted songs +or plugins as though they were isolated. + +### First three suggested ear tests + +| Test | Procedure | Tell us | +| --- | --- | --- | +| A — Is sound present? | Try alsa, then compare dummy | Audible/silent, device name, output log | +| B — Pitch | Listen to a known single-note or familiar sample passage | Correct, too high/low, unstable, octave error | +| C — Timing | Play a short repetitive pattern and stop after several loops | Steady, early/late note, drift, dropout, tick irregularity | + +If there is a problem, include a timestamp or pattern position if possible, +the expected sound, the actual sound, and whether it reproduces twice. + +## Evidence boundaries + +This is **candidate-only auditory evidence**. Every report deliberately declares +original_psycle_observed=false and parity_status=UNKNOWN. +A human listening impression is invaluable for finding defects but does not +by itself justify changing the Phase 6C compatibility matrix. + +Current known limitations: + +- No full tracker editor, Machine View, sample keyboard, or instrument UI. +- No automatic song-end detection (the preserved CLI loops). +- No level meter, live waveform, speaker calibration, or automatic audio analysis. +- No isolation of arbitrary third-party plugins. +- No claim that the candidate matches original Psycle's pitch/timing semantics. +- The historical player must be built separately; GUI CI does not rebuild it. + +## Run focused tests + +~~~sh +python3 -m unittest discover -s tests -p 'test_listening_lab.py' -v +python3 -m py_compile ui/listening_lab.py +# In a Linux CI/Xvfb environment: +xvfb-run -a python3 ui/listening_lab.py --smoke-test +~~~ + +The headless subprocess test uses a clearly labeled **fake player**. It checks +command construction, spaces in paths, safe default plugin-path handling, and +graceful stdin shutdown. It does not pretend to render or audibly verify Psycle. diff --git a/tests/test_listening_lab.py b/tests/test_listening_lab.py new file mode 100644 index 00000000..41ba1ed6 --- /dev/null +++ b/tests/test_listening_lab.py @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Headless contract tests for the early Listening Lab controller.""" +import os +from pathlib import Path +import stat +import sys +import tempfile +import time +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "ui")) +from listening_lab import PlaybackConfig, PlayerSession + + +class ListeningLabTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.player = self.root / "fake player" + self.song = self.root / "song with spaces.psy" + self.song.write_bytes(b"PSY3SONG synthetic test input") + self.player.write_text( + "#!" + sys.executable + "\n" + "import os,sys\n" + "print('FAKE_PLAYER_READY', flush=True)\n" + "print('PSYCLE_PATH=' + repr(os.environ.get('PSYCLE_PATH')), flush=True)\n" + "print('ARGS=' + repr(sys.argv[1:]), flush=True)\n" + "sys.stdin.readline()\n" + "print('FAKE_PLAYER_STOPPED', flush=True)\n", + encoding="utf-8", + ) + self.player.chmod(self.player.stat().st_mode | stat.S_IXUSR) + + def config(self, **kwargs): + return PlaybackConfig(player=self.player, song=self.song, **kwargs) + + def test_argv_preserves_spaces_and_waits_for_stop(self): + args = self.config(driver="alsa", device="plughw:0").command() + self.assertEqual(args[0], str(self.player.resolve())) + self.assertEqual(args[-2:], ["--input-file", str(self.song.resolve())]) + self.assertEqual(args[args.index("--output-device") + 1], "plughw:0") + self.assertIn("--wait", args) + + def test_rejects_invalid_driver_and_non_psy_file(self): + with self.assertRaisesRegex(ValueError, "Unsupported"): + self.config(driver="not-a-driver").command() + wav = self.root / "sample.wav" + wav.touch() + with self.assertRaisesRegex(ValueError, r"\.psy"): + PlaybackConfig(self.player, wav).command() + + def test_refuses_overwriting_wav(self): + wav = self.root / "existing.wav" + wav.touch() + with self.assertRaisesRegex(ValueError, "overwrite"): + self.config(wav_output=wav).command() + new = self.root / "new.wav" + args = self.config(wav_output=new).command() + self.assertEqual(args[args.index("--output-file") + 1], str(new.resolve())) + + def test_plugin_paths_opt_in_only(self): + with mock.patch.dict(os.environ, {"PSYCLE_PATH": "/tmp/plugins", "LADSPA_PATH": "/tmp/ladspa"}): + clean = self.config().environment() + self.assertNotIn("PSYCLE_PATH", clean) + self.assertNotIn("LADSPA_PATH", clean) + opted = self.config(allow_plugins=True).environment() + self.assertEqual(opted["PSYCLE_PATH"], "/tmp/plugins") + self.assertEqual(opted["LADSPA_PATH"], "/tmp/ladspa") + + def test_fake_player_launch_and_graceful_shutdown(self): + with mock.patch.dict(os.environ, {"PSYCLE_PATH": "/tmp/ignore"}): + session = PlayerSession(self.config()) + try: + session.start() + deadline = time.monotonic() + 3 + output = "" + while "FAKE_PLAYER_READY" not in output and time.monotonic() < deadline: + output += session.output() + time.sleep(0.02) + self.assertIn("FAKE_PLAYER_READY", output) + self.assertIn("PSYCLE_PATH=None", output) + session.stop() + while session.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + self.assertEqual(session.poll(), 0) + output += session.output() + self.assertIn("FAKE_PLAYER_STOPPED", output) + self.assertTrue(session.started_utc) + self.assertTrue(session.ended_utc) + finally: + session.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/ui/listening_lab.py b/ui/listening_lab.py new file mode 100644 index 00000000..2f2cba42 --- /dev/null +++ b/ui/listening_lab.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Early human listening harness for the historical C++ Psycle player. + +This is a temporary, external GUI; it does not alter the preserved engine or +claim parity with original Psycle. Only the Python standard library is used. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import time +import tkinter as tk +from tkinter import filedialog, messagebox, scrolledtext, ttk +from dataclasses import dataclass +from datetime import datetime, timezone + +REPO = Path(__file__).resolve().parent.parent +DEFAULT_PLAYER = ( + REPO / "psycle-cpp-r12005-sanitized" / "psycle-player" + / "++qmake" / "psycle-player" +) +DRIVERS = ("alsa", "jack", "dummy") +LOG_LIMIT = 65536 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +@dataclass(frozen=True) +class PlaybackConfig: + player: Path + song: Path + driver: str = "alsa" + device: str = "" + wav_output: Path | None = None + allow_plugins: bool = False + + def validate(self) -> None: + if not self.player.is_file() or not os.access(self.player, os.X_OK): + raise ValueError("Build psycle-player first or choose an executable player.") + if not self.song.is_file() or self.song.suffix.lower() != ".psy": + raise ValueError("Select an existing .psy song file.") + if self.driver not in DRIVERS: + raise ValueError("Unsupported output driver selection.") + if "\x00" in self.device or "\n" in self.device: + raise ValueError("Invalid audio-device name.") + if self.wav_output is not None: + if self.wav_output.suffix.lower() != ".wav": + raise ValueError("WAV output needs a .wav file name.") + if not self.wav_output.parent.is_dir(): + raise ValueError("WAV output directory does not exist.") + if self.wav_output.exists(): + raise ValueError("Refusing to overwrite an existing WAV file.") + + def command(self) -> list[str]: + self.validate() + args = [str(self.player.resolve()), "--output-driver", self.driver] + if self.device.strip(): + args.extend(("--output-device", self.device.strip())) + if self.wav_output is not None: + args.extend(("--output-file", str(self.wav_output.resolve()))) + args.extend(("--wait", "--input-file", str(self.song.resolve()))) + return args + + def environment(self) -> dict[str, str]: + env = os.environ.copy() + # Candidate plugin discovery/loading has not yet passed containment + # gates. Do not opt into configured third-party plugin paths by default. + if not self.allow_plugins: + env.pop("PSYCLE_PATH", None) + env.pop("LADSPA_PATH", None) + return env + + +class PlayerSession: + """One subprocess, its isolated log, and bounded nonblocking shutdown.""" + + def __init__(self, config: PlaybackConfig): + self.config = config + self.process: subprocess.Popen[bytes] | None = None + self.started_utc = "" + self.ended_utc = "" + self.stop_at: float | None = None + self._scratch = tempfile.TemporaryDirectory(prefix="psycle-listening-") + self.log_path = Path(self._scratch.name) / "player.log" + self._reader = None + + def start(self) -> None: + if self.process is not None: + raise RuntimeError("Session already started.") + command = self.config.command() + with self.log_path.open("wb") as writer: + self.process = subprocess.Popen( + command, stdin=subprocess.PIPE, stdout=writer, + stderr=subprocess.STDOUT, env=self.config.environment(), + ) + self._reader = self.log_path.open("rb") + self.started_utc = utc_now() + + def output(self) -> str: + if self._reader is None: + return "" + return self._reader.read(32768).decode("utf-8", errors="replace") + + def stop(self) -> None: + proc = self.process + if proc is None or proc.poll() is not None or self.stop_at is not None: + return + self.stop_at = time.monotonic() + try: + if proc.stdin is not None: + proc.stdin.write(b"\n") + proc.stdin.flush() + proc.stdin.close() + except (BrokenPipeError, OSError): + pass + + def poll(self) -> int | None: + proc = self.process + if proc is None: + return None + rc = proc.poll() + if rc is not None: + if not self.ended_utc: + self.ended_utc = utc_now() + return rc + if self.stop_at is not None: + elapsed = time.monotonic() - self.stop_at + if elapsed > 5: + proc.kill() + elif elapsed > 3: + proc.terminate() + return None + + def abort(self) -> None: + proc = self.process + if proc is not None and proc.poll() is None: + proc.kill() + + def log_tail(self) -> str: + with self.log_path.open("rb") as stream: + stream.seek(0, os.SEEK_END) + stream.seek(max(0, stream.tell() - LOG_LIMIT)) + return stream.read().decode("utf-8", errors="replace") + + def close(self) -> None: + self.abort() + if self.process is not None: + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired: + pass + if self.process.stdin is not None: + self.process.stdin.close() + if self._reader is not None: + self._reader.close() + self._scratch.cleanup() + + +class ListeningLab: + def __init__(self, root: tk.Tk, player: Path, song: Path | None = None): + self.root = root + self.root.title("PSYCLE-LINUX — Listening Lab (candidate, not parity)") + self.root.minsize(760, 640) + self.player_var = tk.StringVar(value=str(player)) + self.song_var = tk.StringVar(value=str(song) if song else "") + self.driver_var = tk.StringVar(value="alsa") + self.device_var = tk.StringVar() + self.record_var = tk.BooleanVar(value=False) + self.wav_var = tk.StringVar() + self.plugins_var = tk.BooleanVar(value=False) + self.issue_var = tk.StringVar(value="Sounds correct") + self.status_var = tk.StringVar(value="Ready — lower system volume before Play.") + self.session: PlayerSession | None = None + self._finished_status = "" + self._build() + self.root.protocol("WM_DELETE_WINDOW", self._close) + self.root.after(150, self._tick) + + def _build(self) -> None: + outer = ttk.Frame(self.root, padding=12) + outer.pack(fill="both", expand=True) + outer.columnconfigure(1, weight=1) + + def file_row(row: int, title: str, var: tk.StringVar, action): + ttk.Label(outer, text=title).grid(row=row, column=0, sticky="w", pady=3) + ttk.Entry(outer, textvariable=var).grid(row=row, column=1, sticky="ew", padx=5) + ttk.Button(outer, text="Browse…", command=action).grid(row=row, column=2) + + file_row(0, "Song (.psy)", self.song_var, self._browse_song) + file_row(1, "C++ player", self.player_var, self._browse_player) + ttk.Label(outer, text="Audio driver").grid(row=2, column=0, sticky="w") + ttk.Combobox(outer, values=DRIVERS, textvariable=self.driver_var, state="readonly", width=18).grid( + row=2, column=1, sticky="w", pady=3) + ttk.Label(outer, text="Device (optional)").grid(row=3, column=0, sticky="w") + ttk.Entry(outer, textvariable=self.device_var).grid(row=3, column=1, sticky="ew", padx=5, pady=3) + ttk.Checkbutton(outer, text="Also render a WAV", variable=self.record_var).grid( + row=4, column=0, sticky="w") + ttk.Entry(outer, textvariable=self.wav_var).grid(row=4, column=1, sticky="ew", padx=5) + ttk.Button(outer, text="WAV path…", command=self._browse_wav).grid(row=4, column=2) + ttk.Checkbutton( + outer, text="Allow configured third-party plugin paths (unsafe / optional)", + variable=self.plugins_var, + ).grid(row=5, column=0, columnspan=3, sticky="w", pady=4) + ttk.Label( + outer, + text="Start at low system volume. 'dummy' is silent. No plugins are scanned from configured paths unless opted in.", + wraplength=700, + ).grid(row=6, column=0, columnspan=3, sticky="w", pady=3) + + controls = ttk.Frame(outer) + controls.grid(row=7, column=0, columnspan=3, sticky="ew", pady=7) + self.play_button = ttk.Button(controls, text="▶ Play song", command=self._play) + self.play_button.pack(side="left", padx=(0, 6)) + self.stop_button = ttk.Button(controls, text="■ Stop", command=self._stop, state="disabled") + self.stop_button.pack(side="left") + ttk.Button(controls, text="Save listening report…", command=self._save_report).pack(side="right") + ttk.Label(outer, textvariable=self.status_var, wraplength=700).grid( + row=8, column=0, columnspan=3, sticky="w", pady=3) + ttk.Label(outer, text="Player diagnostics (not a parity verdict)").grid( + row=9, column=0, columnspan=3, sticky="w") + self.log = scrolledtext.ScrolledText(outer, height=11, wrap="word", state="disabled") + self.log.grid(row=10, column=0, columnspan=3, sticky="nsew", pady=4) + outer.rowconfigure(10, weight=1) + ttk.Label(outer, text="What did your ears hear?").grid(row=11, column=0, sticky="w", pady=4) + ttk.Combobox( + outer, textvariable=self.issue_var, state="readonly", + values=("Sounds correct", "Silent", "Wrong pitch", "Timing / rhythm", + "Crackle / clipping", "Dropouts / stutter", "Stereo / balance", "Other"), + ).grid(row=11, column=1, sticky="w") + ttk.Label(outer, text="Notes / steps / timestamps").grid( + row=12, column=0, columnspan=3, sticky="w", pady=3) + self.notes = scrolledtext.ScrolledText(outer, height=5, wrap="word") + self.notes.grid(row=13, column=0, columnspan=3, sticky="nsew") + + def _browse_song(self) -> None: + path = filedialog.askopenfilename(filetypes=[("Psycle songs", "*.psy"), ("All files", "*")]) + if path: + self.song_var.set(path) + + def _browse_player(self) -> None: + path = filedialog.askopenfilename(title="Select compiled historical psycle-player") + if path: + self.player_var.set(path) + + def _browse_wav(self) -> None: + path = filedialog.asksaveasfilename(defaultextension=".wav", filetypes=[("Wave audio", "*.wav")]) + if path: + self.wav_var.set(path) + self.record_var.set(True) + + def _append(self, message: str) -> None: + self.log.configure(state="normal") + self.log.insert("end", message) + # Bound GUI memory independently of the session's full temporary log. + if float(self.log.index("end-1c").split(".")[0]) > 2000: + self.log.delete("1.0", "500.0") + self.log.see("end") + self.log.configure(state="disabled") + + def _play(self) -> None: + if self.session is not None and self.session.process is not None and self.session.poll() is None: + return + cfg = PlaybackConfig( + player=Path(self.player_var.get()).expanduser(), + song=Path(self.song_var.get()).expanduser(), + driver=self.driver_var.get(), + device=self.device_var.get(), + wav_output=Path(self.wav_var.get()).expanduser() if self.record_var.get() else None, + allow_plugins=self.plugins_var.get(), + ) + try: + cfg.validate() + if self.session is not None: + self.session.close() + self.session = None + candidate = PlayerSession(cfg) + try: + candidate.start() + except (OSError, subprocess.SubprocessError): + candidate.close() + raise + self.session = candidate + except (ValueError, OSError, subprocess.SubprocessError) as error: + messagebox.showerror("Cannot start playback", str(error)) + return + self._finished_status = "" + self._append("\n--- Candidate playback session started ---\n") + self.status_var.set("Player started. A successful start does not prove that audio is audible.") + self.play_button.configure(state="disabled") + self.stop_button.configure(state="normal") + + def _stop(self) -> None: + if self.session: + self.session.stop() + self.status_var.set("Stopping (waiting for player to finalize; bounded timeout)…") + self.stop_button.configure(state="disabled") + + def _tick(self) -> None: + if self.session is not None: + content = self.session.output() + if content: + self._append(content) + rc = self.session.poll() + if rc is not None and not self._finished_status: + self._append(self.session.output()) + self._finished_status = f"Player exited with code {rc}" + self.status_var.set(self._finished_status + " — listen, classify, then save report.") + self.play_button.configure(state="normal") + self.stop_button.configure(state="disabled") + self.root.after(150, self._tick) + + def _save_report(self) -> None: + session = self.session + if session is None: + messagebox.showinfo("No session", "Play a song before saving a report.") + return + target = filedialog.asksaveasfilename( + title="Save listening evidence", defaultextension=".json", + filetypes=[("JSON", "*.json")], + ) + if not target: + return + cfg = session.config + try: + report = { + "schema_version": 1, + "scope": "human-listening-candidate-only", + "original_psycle_observed": False, + "parity_status": "UNKNOWN", + "started_utc": session.started_utc, + "ended_utc": session.ended_utc or None, + "saved_utc": utc_now(), + "song": str(cfg.song.resolve()), + "song_sha256": sha256(cfg.song), + "candidate_player": str(cfg.player.resolve()), + "candidate_player_sha256": sha256(cfg.player), + "driver": cfg.driver, + "device": cfg.device, + "wav_output": str(cfg.wav_output.resolve()) if cfg.wav_output else None, + "wav_sha256": ( + sha256(cfg.wav_output) + if cfg.wav_output and session.poll() is not None and cfg.wav_output.is_file() + else None + ), + "configured_plugin_paths_enabled": cfg.allow_plugins, + "player_exit_code": session.process.poll() if session.process else None, + "user_observation": self.issue_var.get(), + "user_notes": self.notes.get("1.0", "end-1c"), + "log_tail": session.log_tail(), + } + path = Path(target) + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=path.parent, + prefix=".psycle-report-", suffix=".tmp", delete=False, + ) as stream: + tmp = Path(stream.name) + json.dump(report, stream, indent=2, ensure_ascii=False) + stream.write("\n") + try: + os.replace(tmp, path) + finally: + tmp.unlink(missing_ok=True) + self.status_var.set(f"Listening report saved: {path}") + except (OSError, ValueError) as error: + messagebox.showerror("Cannot save report", str(error)) + + def _close(self) -> None: + if self.session is not None: + self.session.close() + self.root.destroy() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--player", type=Path, default=Path(os.environ.get("PSYCLE_PLAYER_BIN", DEFAULT_PLAYER))) + parser.add_argument("--song", type=Path) + parser.add_argument("--smoke-test", action="store_true", help="Construct widgets then exit (CI/Xvfb)") + args = parser.parse_args() + root = tk.Tk() + ListeningLab(root, args.player, args.song) + if args.smoke_test: + root.after(200, root.destroy) + root.mainloop() + + +if __name__ == "__main__": + main()