Hydrofon wikiThe manual of an underwater listening app 文A eesti

Manual:Architecture

Other languages: eesti English

Hydrofon is a Windows desktop application written in Python and PySide6 that keeps graphical code separated from signal processing and machine learning. MainWindow hosts three suites — Recording, Training and Clip analysis — any of which can be detached into its own SuiteWindow. Every core computational component (feature extraction, stream contract, event engine, splits, manifest and metrics) lives in Qt-free modules, so the GUI, the command-line tools and the tests execute the exact same logic.

Clip analysis detached into its own window: any suite can be moved out via the button or by double-clicking its tab, and closing the window re-attaches it.
Clip analysis detached into its own window: any suite can be moved out via the button or by double-clicking its tab, and closing the window re-attaches it.

Module map (app/)

All application code lives in the app/ package. The tables below list all 20 Python modules and their responsibilities.

Entry point, UI and settings

Module Responsibility
__main__.py Entry point (python -m app). Quiets TensorFlow startup chatter (TF_CPP_MIN_LOG_LEVEL=2, TF_ENABLE_ONEDNN_OPTS=0), enforces a single running instance via QLockFile (hydrofon.lock) and QLocalServer / QLocalSocket (Hydrofon-<user>) so a second launch transfers focus (AllowSetForegroundWindow) and raises the existing window before heavy imports run, sets Windows AppUserModelID (Hydrofon.App) for taskbar icon identity, and installs sys.excepthook to log unhandled exceptions.
ui.py MainWindow, SuiteWindow, SettingsDialog, UiLogHandler and setup_logging. Implements tab 1 · Listen & record (spectrogram, engine score plot, level meter, events list, live marker shortcuts 1–3 scoped to tab 1), runs the 30 ms drain() timer, and manages app.log, events.jsonl and optional scores.csv.
settings.py DEFAULTS, type-checked _merge() (user-defined dicts like labels replace defaults rather than merging), backup of corrupt settings.json to settings.json.bad, and data folder path helpers.
i18n.py All UI text in Estonian (et, default) and English (en, fallback): tr(), marker display names label_name() and tooltip helpers tip().

Recording and review

Module Responsibility
audio.py MicSource (sounddevice.InputStream) and FileSource (soundfile.SoundFile + real-time sounddevice.OutputStream, with a silent timed thread fallback if the output device rejects the file's sample rate). Both push mono float32 blocks into queue.Queue.
recorder.py Recorder writes a new recording to data/unsaved/<YYYY-MM-DD_HH-MM-SS>.wav plus a draft .json, flushes the WAV header every 5 s and rewrites the draft JSON on every marker.
session.py Recording format (hydrofon-recording v1): notes template rendering (render) and typed parsing (parse), marker-to-segment conversion (segments), atomic JSON writes (.json.tmp + os.replace), and finalize() moving WAV + JSON into data/recordings/.
review.py Tab 2 · Mark & save (ReviewTab): whole-file spectrogram overview() (up to 2000 columns), Player (channel 0 playback with latency-compensated position and seek), draggable marker lines, marker table and debounced draft autosave.

Live detection and events

Module Responsibility
detector.py Pure-Python StreamProcessor cutting incoming audio blocks into the exact windows offline model.predict computes (grid-aligned FIR resampling context for YAMNet, explicit gap records on discontinuity/overload/close, sample-rate check >= min_sr), Detector (QThread running StreamProcessor, calling warm_up() only for YAMNet at 16 kHz and skipping windows as overload gaps above MAX_BACKLOG = 20), plus the legacy Alarm class.
events.py Pure-Python event engine (EventRule, EventEngine, Event, LegacyAlarmRule, LegacyAlarmEngine, replay()) separating detection events (event_started / event_ended with hysteresis, confirmation, release, causal smoothing and gap/reset handling) from user notifications (notify).
replay.py CLI that feeds score CSVs or mono WAVs through events.py and outputs JSON lines.

Models, data and training

Module Responsibility
models.py Model contract (Prediction), built-in YamnetModel (thread-safe lazy TF-Hub load cached in models/tfhub_cache/, 60 s chunked inference), band_features() (30 gain-free one-third-octave bands 18 Hz – 17.9 kHz + flatness + crest factor; refuses sample rates below BANDS_MIN_SR = 35919 Hz), feature_spec() + SHA-256 check_spec(), and TrainedModel (model.json v2 + weights.npz, atomic folder swap, legacy v1 loading with warning).
dataset.py Loads saved recordings (data/recordings/) and Wolfset (data/wolfset/), attaches provenance to every Segment (filename, index, heuristic, manual), assigns window labels without silently overwriting conflicting overlaps (window_labels), implements the shared channel policy read_mono() (mono mean with a −20 dB anti-phase cancellation guard), manages the feature cache (data/cache/features/*.npz) and deterministic group split().
manifest.py Builds deterministic manifest.jsonl and qc.json (file SHA-256 hashes, WAV headers, Wolfset codes, provenance IDs and validate_segments()).
splits.py Saved split records (split.json, hydrofon-split v1) with order-independent SHA-256 hashes and overlap checks (check_disjoint, check_no_overlap across recording ID, group, SHA-256 and parent_recording_id) for holdout-legacy, group-kfold, loeo and custom.
train.py Training and evaluation CLI (data, split, train, evaluate): standardisation + LogisticRegression(class_weight="balanced", max_iter=5000), atomic save of model.json + weights.npz + split.json, and overlap refusal on evaluation.
training_tab.py Training suite (TrainingTab): spawns python -m app.train in a QProcess with --data-dir, parses chunked JSON lines from stdout, displays progress, confusion matrix and model details, and safely deletes model folders (refusing junctions/symlinks or paths outside models/).

Analysis, evaluation and manual review

Module Responsibility
analysis.py Clip analysis suite (AnalysisTab): reads audio via dataset.read_mono, runs all checked models concurrently in a ThreadPoolExecutor, caches predictions in memory per file and model version, draws linked timeline lanes and hands off back to tab 2 to fix markers.
evaluation.py Pure-Python four-layer metrics core (multiclass, binary, match_events, notifications), interval algebra (union, intersect, subtract) so overlapping windows never double-count negative time, explicit null + reason for undefined metrics, predictions.csv I/O, and legacy reproduction functions (legacy_train_metrics, legacy_analysis_metrics).
annotation.py Standalone blind manual review CLI (export / import) with vendored frozen label rules from baseline commit 91121a7, stratified clip export without model predictions, Excel-compatible CSV import and Cohen's kappa reporting.

Known integration gaps

  • The live alarm in app/ui.py still uses the legacy detector.Alarm rule (threshold + consecutive windows + cooldown). The new event engine in app/events.py is implemented and tested, but not yet wired to the live view.
  • Clip analysis (app/analysis.py) and app/train.py still compute metrics inline; the shared metrics core in app/evaluation.py exists and is tested, but is not yet wired into the GUI.
  • Live WAV playback (audio.FileSource) reads a single configured channel (audio.channel), whereas training and clip analysis downmix multichannel files using the shared channel policy (dataset.read_mono, mono mean).

Data flow: microphone to alarm

Live listening coordinates three execution contexts: the audio callback thread produces blocks, the Qt main thread drains the queue every 30 ms, and the detector background thread scores analysis windows.

MicSource / FileSource (audio thread)
  └── mono float32 blocks ──► source.q (queue.Queue)
                                  │
                     MainWindow.drain() (30 ms QTimer, UI thread)
                     ├──► signal level + FFT spectrogram (ui.py)
                     ├──► Recorder.write() ──► data/unsaved/*.wav + .json
                     └──► Detector.feed() ──► Detector (QThread)
                                                  │
                                           StreamProcessor
                                           └── YamnetModel / TrainedModel
                                                  │
                                     result / gap Qt signals
                                                  │
                     MainWindow.on_result() / on_gap() (UI thread)
                     ├──► score plot + model output + scores.csv (optional)
                     └──► Alarm.update() ──► raise_event()
                                               ├── events list + app.log
                                               ├── data/logs/events.jsonl
                                               └── Windows tray notification

When MicSource reports an input overflow, drain() forwards discontinuity() to the detector so dropped audio becomes an explicit gap record rather than fake silence. Receiving a gap signal in on_gap() resets the alarm's consecutive-window counter (alarm.run = 0).

Data flow: recordings to a trained model

Training runs out-of-process so the graphical suite and the CLI follow the exact same pipeline.

data/recordings/*.wav + *.json   &   data/wolfset/*.wav + Wolfset_Index.csv
                              │
              TrainingTab ──► QProcess: python -m app.train --data-dir ...
                                  │
                  dataset.recordings() + splits (holdout / k-fold / loeo)
                                  │
                  dataset.read_mono() ──► dataset.cached()
                                              └── data/cache/features/*.npz
                                  │
                  standardisation + LogisticRegression (balanced)
                                  │
                  TrainedModel.save() (atomic temp-folder swap)
                  └── data/models/<name>/{model.json, weights.npz, split.json}
                                  │
                  stdout JSON lines (progress, split, done) ──► TrainingTab
                                  │
                  models_changed signal ──► AnalysisTab + SettingsDialog

Design rules

Five core conventions shape the codebase so data stays portable and experiments remain reproducible.

  • Estonian UI, English files. Every user-facing label lives in app/i18n.py (Estonian by default, English available), while on-disk JSON keys, marker codes (engine, background, interference), model and split schemas, and CLI flags are always English. Recordings and scripts therefore work identically regardless of UI language.
  • Everything is logged. app.log (rotating, 5 MB max, 5 backups) records startup, settings issues, detector gaps and unhandled exceptions caught by sys.excepthook. Detections are appended to events.jsonl and, when enabled, per-window scores to scores.csv.
  • WAV, never MP3. Recordings are saved uncompressed (default PCM_24, selectable PCM_16, PCM_32 or FLOAT). Lossy audio codecs discard frequencies tuned for human speech and music, which can alter low-frequency engine tonals and high-frequency cavitation.
  • Models as model.json + weights.npz, never pickle. Weights are plain NumPy arrays loaded with allow_pickle=False, so opening a shared model can never execute arbitrary code. Format v2 model.json binds the weights by SHA-256 and records the full feature_spec and its hash; saving swaps a temporary folder atomically so a crash never leaves a half-written model. Older v1 models still load as legacy with a warning.
  • Training in a separate process. Training drives app.train via QProcess and newline-delimited JSON instead of running training inside the GUI process. The window stays responsive, cancelling (kill()) terminates heavy work cleanly, TensorFlow memory is reclaimed when the subprocess exits, and CLI and GUI behaviour cannot drift apart.

See also

This page has not been saved yet.

The Hydrofon project · volli.page