Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Add persistent local upload jobs, CLI and inspectable browser interface (#10, #11)
Cinna Daviscd68aa774202
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdnew file mode 100644index 0000000..65ac052--- /dev/null+++ b/docs/PRODUCT.md@@ -0,0 +1,66 @@+# Local upload workflow++The automatic product path is separate from the historical research `run` and+`measure` commands. Uploads supply audio, an optional defensible UTC window for+**sample zero**, and declared CONUS search coverage. Event windows, frequency+bands, flight IDs and ground-truth coordinates are not upload inputs.++Launch the local interface after installing the project:++```bash+aircraft-geoloc serve --jobs jobs --config operator.json --port 8765+```++Open `http://127.0.0.1:8765`. The same persistent directory must be supplied after+restarting. Each upload gets a new job ID and its own original file, normalized+request, provenance, intermediate diagnostics, result and worker log. Completed+jobs are read back without rerunning. Interrupted jobs are explicitly failed;+they are never silently replayed. Cancelling preserves partial artifacts.++The server binds to loopback. It runs one analysis process at a time, accepts up+to four pending jobs, limits uploads to 100 MiB by default, and limits analysis+to one hour by default. Set `--max-upload-mb` and `--max-runtime` to change these+operator limits. Cancellation terminates the analysis process group, including+decoders. No API credentials or paid service are required by the local service.+Flight/terrain provider configuration and scientific integration are described+below as their producing modules land; an unconfigured backend must report+missing data rather than invent a location.++CLI equivalents:++```bash+aircraft-geoloc analyze recording.mp3 --jobs jobs --config operator.json \+ --start-utc 2026-09-08T20:00:00Z --end-utc 2026-09-08T20:05:00Z \+ --time-source 'Recorder clock and recording log'+aircraft-geoloc job JOB_ID --jobs jobs+```++The UTC window bounds the recording start, not the event occurrence or upload.+Missing time is a required-input result. Scores are ranking statistics, not+probabilities. Sensitivity radii must not be described as calibrated confidence.+An inconclusive result may retain candidate hypotheses for inspection.++## HTTP surface++- `GET /api/capabilities`: declared coverage and upload/work limits.+- `POST /api/jobs`: raw audio bytes with `Content-Type: application/octet-stream`,+ `Content-Length`, optional `X-Filename`, and `X-Dopplergeist-Request` containing+ the shared request JSON **without** `audio_path`. The server saves the upload+ and sets that path. Returns HTTP 202 and a shared queued `JobResult`.+- `GET /api/jobs/{id}`: the current shared `JobResult`.+- `POST /api/jobs/{id}/cancel`: cancel a queued/running job; terminal jobs remain.+- `GET /api/jobs/{id}/artifacts`: relative file paths and byte counts.+- `GET /api/jobs/{id}/artifacts/{path}`: download one artifact. Private operator+ configuration is excluded. Paths cannot escape the job directory.++Upload example (header metadata uses actual JSON, not a string-encoded file):++```bash+curl -H 'Content-Type: application/octet-stream' \+ -H 'X-Dopplergeist-Request: {"schema_version":1,"search":{"coverage":"conus"}}' \+ --data-binary @recording.mp3 http://127.0.0.1:8765/api/jobs+```++`tests/test_service.py` checks HTTP transport, original preservation, state+readback, cancellation, interrupted jobs, path restrictions and input validation.+These transport tests do not establish scientific localization accuracy.diff --git a/src/aircraft_geoloc/cli.py b/src/aircraft_geoloc/cli.pyindex 97b0470..a28c8bb 100644--- a/src/aircraft_geoloc/cli.py+++ b/src/aircraft_geoloc/cli.py@@ -14,6 +14,23 @@ def main():measure.add_argument("--end",type=float,required=True)measure.add_argument("--band",type=float,nargs=2,required=True)measure.add_argument("--output",required=True)+ analyze=sub.add_parser("analyze",help="Automatically locate aircraft audio, or explain insufficient evidence")+ analyze.add_argument("audio")+ analyze.add_argument("--start-utc",help="Earliest UTC recording start, including explicit timezone")+ analyze.add_argument("--end-utc",help="Latest UTC recording start; defaults to earliest")+ analyze.add_argument("--time-source",help="How the recording start window was established")+ analyze.add_argument("--jobs",default="jobs",help="Persistent job directory")+ analyze.add_argument("--config",help="Operator provider/cache/search configuration JSON")+ analyze.add_argument("--max-runtime",type=float,default=3600,help="Wall-time limit in seconds")+ serve=sub.add_parser("serve",help="Launch the local MP3 upload interface and job API")+ serve.add_argument("--jobs",default="jobs")+ serve.add_argument("--config",help="Operator provider/cache/search configuration JSON")+ serve.add_argument("--port",type=int,default=8765)+ serve.add_argument("--max-runtime",type=float,default=3600)+ serve.add_argument("--max-upload-mb",type=int,default=100)+ job=sub.add_parser("job",help="Read a persisted job result without rerunning it")+ job.add_argument("job_id")+ job.add_argument("--jobs",default="jobs")args=parser.parse_args()if args.command=="run":from .pipeline import run@@ -22,6 +39,40 @@ def main():from .audio import measureresult=measure(args.audio,{"start_s":args.start,"end_s":args.end,"band_hz":args.band},args.output)print(json.dumps(result[-1],indent=2))+ elif args.command=="serve":+ from pathlib import Path+ from .service import serve+ config=json.loads(Path(args.config).read_text()) if args.config else {}+ serve(args.jobs,config,port=args.port,max_runtime_s=args.max_runtime,max_upload_bytes=args.max_upload_mb*1024*1024)+ elif args.command=="analyze":+ from pathlib import Path+ from .jobs import JobManager+ if args.end_utc and not args.start_utc:+ parser.error("--end-utc requires --start-utc")+ request={"schema_version":1,"search":{"coverage":"conus"}}+ if args.start_utc:+ request["time_window"]={"start_utc":args.start_utc,"end_utc":args.end_utc or args.start_utc,"source":"user"}+ if args.time_source:+ request["time_window"]["source_detail"]=args.time_source+ config=json.loads(Path(args.config).read_text()) if args.config else {}+ manager=JobManager(args.jobs,config,max_runtime_s=args.max_runtime)+ try:+ audio=Path(args.audio)+ with audio.open("rb") as source:+ queued=manager.submit(request,source,audio.stat().st_size,suffix=audio.suffix)+ print(json.dumps(manager.wait(queued["job_id"]),indent=2))+ finally:+ manager.close()+ elif args.command=="job":+ from pathlib import Path+ from .jobs import read_json+ import uuid+ try:+ if uuid.UUID(args.job_id).hex!=args.job_id:+ raise ValueError+ except ValueError:+ parser.error("job_id must be the 32-character job identifier")+ print(json.dumps(read_json(Path(args.jobs)/args.job_id/"result.json"),indent=2))if __name__=="__main__":diff --git a/src/aircraft_geoloc/jobs.py b/src/aircraft_geoloc/jobs.pynew file mode 100644index 0000000..b546193--- /dev/null+++ b/src/aircraft_geoloc/jobs.py@@ -0,0 +1,226 @@+"""Persistent local jobs; each analysis has its own cancellable process group."""+import argparse+import fcntl+import hashlib+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import threading+import uuid++from .contracts import validate_request, validate_result++TERMINAL = {"needs_input", "succeeded", "inconclusive", "failed", "cancelled"}+++def write_json(path, value):+ path = Path(path)+ temporary = path.with_suffix(path.suffix + ".tmp")+ temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")+ temporary.replace(path)+++def read_json(path):+ return json.loads(Path(path).read_text())+++def result(job_dir, status, **fields):+ value = validate_result(dict(schema_version=1, job_id=Path(job_dir).name, status=status, **fields))+ write_json(Path(job_dir) / "result.json", value)+ return value+++class JobManager:+ def __init__(self, root, config=None, *, max_pending=4, max_runtime_s=3600, max_upload_bytes=100*1024*1024):+ self.root = Path(root).resolve()+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)+ self.config = config or {}+ self.max_pending = max_pending+ self.max_runtime_s = max_runtime_s+ self.max_upload_bytes = max_upload_bytes+ if min(max_pending, max_runtime_s, max_upload_bytes) <= 0:+ raise ValueError("Job limits must be positive")+ self._lockfile = (self.root / ".manager.lock").open("a")+ try:+ fcntl.flock(self._lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ self._lockfile.close()+ raise ValueError("Another job manager is using this directory") from None+ self._mutex = threading.RLock()+ self._serial = threading.Semaphore(1)+ self._threads = {}+ self._processes = {}+ self._closed = False+ # Preserve terminal outputs. An interrupted process is never silently replayed.+ for path in self.root.glob("*/result.json"):+ old = read_json(path)+ if old["status"] not in TERMINAL:+ result(path.parent, "failed", reason_code="interrupted", message="Service stopped before completion; submit a new job to retry.")++ def directory(self, job_id):+ try:+ if uuid.UUID(job_id).hex != job_id:+ raise ValueError+ except (ValueError, AttributeError):+ raise KeyError("Unknown job") from None+ path = self.root / job_id+ if not (path / "result.json").is_file():+ raise KeyError("Unknown job")+ return path++ def get(self, job_id):+ return read_json(self.directory(job_id) / "result.json")++ def submit(self, metadata, source, size, *, suffix=".mp3"):+ """Copy exactly size bytes from a binary stream before launching analysis."""+ if size <= 0 or size > self.max_upload_bytes:+ raise ValueError(f"Audio size must be 1..{self.max_upload_bytes} bytes")+ request = validate_request(dict(metadata, audio_path="pending"))+ with self._mutex:+ if self._closed:+ raise ValueError("Service is shutting down")+ if sum(thread.is_alive() for thread in self._threads.values()) >= self.max_pending:+ raise OverflowError("Job queue is full; try again after a job finishes")+ job_id = uuid.uuid4().hex+ directory = self.root / job_id+ directory.mkdir(mode=0o700)+ suffix = suffix.lower() if suffix.lower() in {".mp3", ".wav", ".flac", ".m4a", ".ogg"} else ".mp3"+ audio = directory / ("input" + suffix)+ digest = hashlib.sha256()+ with audio.open("xb") as target:+ remaining = size+ while remaining:+ block = source.read(min(1024*1024, remaining))+ if not block:+ result(directory, "failed", reason_code="incomplete_upload", message="Upload ended before its declared length.")+ raise ValueError("Incomplete upload")+ target.write(block)+ digest.update(block)+ remaining -= len(block)+ request["audio_path"] = str(audio)+ write_json(directory / "request.json", request)+ write_json(directory / "operator.json", self.config)+ write_json(directory / "input.json", {"sha256": digest.hexdigest(), "bytes": size, "path": audio.name})+ queued = result(directory, "queued", stage="queued", progress=0)+ thread = threading.Thread(target=self._run, args=(directory,), daemon=True)+ self._threads[job_id] = thread+ thread.start()+ return queued++ def _run(self, directory):+ try:+ with self._serial:+ with self._mutex:+ if self.get(directory.name)["status"] in TERMINAL:+ return+ env = dict(os.environ)+ env["PYTHONPATH"] = str(Path(__file__).resolve().parents[1]) + os.pathsep + env.get("PYTHONPATH", "")+ with (directory / "worker.log").open("ab") as log:+ process = subprocess.Popen([sys.executable, "-m", "aircraft_geoloc.jobs", "--execute", str(directory),+ "--parent-pid", str(os.getpid())],+ stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)+ self._processes[directory.name] = process+ try:+ process.wait(timeout=self.max_runtime_s)+ except subprocess.TimeoutExpired:+ self._stop(process)+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "inconclusive", reason_code="work_limit", message="Analysis exceeded the configured wall-time budget; inspect partial artifacts.")+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "failed", reason_code="worker_exit", message=f"Analysis process exited ({process.returncode}); inspect worker.log.")+ except Exception as exc:+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "failed", reason_code="worker_launch", message=f"Could not run analysis: {exc}")+ finally:+ with self._mutex:+ self._processes.pop(directory.name, None)+ self._threads.pop(directory.name, None)++ @staticmethod+ def _stop(process):+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait()++ def cancel(self, job_id):+ with self._mutex:+ directory = self.directory(job_id)+ current = self.get(job_id)+ if current["status"] in TERMINAL:+ return current+ (directory / "cancel").touch()+ process = self._processes.get(job_id)+ if process:+ self._stop(process)+ return result(directory, "cancelled", message="Cancelled by the user; partial artifacts are preserved.")++ def wait(self, job_id):+ thread = self._threads.get(job_id)+ if thread:+ thread.join()+ return self.get(job_id)++ def close(self):+ with self._mutex:+ self._closed = True+ for job_id, thread in list(self._threads.items()):+ if thread.is_alive():+ self.cancel(job_id)+ for thread in list(self._threads.values()):+ thread.join()+ self._lockfile.close()+++def execute(directory, parent_pid=None):+ # On Linux, an abruptly killed server must not leave an orphan analysis or+ # decoder consuming resources and later overwriting an interrupted result.+ if parent_pid is not None and sys.platform == "linux":+ import ctypes+ def terminate_group(signum, frame):+ signal.signal(signal.SIGTERM, signal.SIG_DFL)+ os.killpg(os.getpgrp(), signal.SIGTERM)+ signal.signal(signal.SIGTERM, terminate_group)+ ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)+ if os.getppid() != parent_pid:+ terminate_group(signal.SIGTERM, None)+ from .automatic import analyze+ directory = Path(directory)+ request = read_json(directory / "request.json")+ config = read_json(directory / "operator.json")++ def progress(stage, fraction, **fields):+ if (directory / "cancel").exists():+ raise InterruptedError("Job cancelled")+ return result(directory, "running", stage=stage, progress=fraction, **fields)++ try:+ progress("intake", 0.02)+ final = analyze(request, directory, config, progress)+ if (directory / "cancel").exists():+ result(directory, "cancelled", message="Cancelled by the user.")+ else:+ result(directory, **final)+ except InterruptedError:+ result(directory, "cancelled", message="Cancelled by the user.")+ except Exception as exc:+ import traceback+ traceback.print_exc()+ result(directory, "failed", reason_code="processing_error", message=f"{type(exc).__name__}: {exc}")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("--execute", required=True)+ parser.add_argument("--parent-pid", type=int)+ args = parser.parse_args()+ execute(args.execute, args.parent_pid)diff --git a/src/aircraft_geoloc/service.py b/src/aircraft_geoloc/service.pynew file mode 100644index 0000000..67b5418--- /dev/null+++ b/src/aircraft_geoloc/service.py@@ -0,0 +1,130 @@+"""Loopback upload/job API, sharing the automatic CLI's persistent job manager."""+import json+import mimetypes+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from importlib.resources import files+from pathlib import Path+from urllib.parse import unquote, urlsplit++from .jobs import JobManager+++class JobServer(ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, address, manager):+ if address[0] not in {"127.0.0.1", "localhost"}:+ raise ValueError("This unauthenticated local service binds to loopback only")+ self.manager = manager+ super().__init__(address, Handler)+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, format, *args):+ pass++ def _reply(self, value, code=200):+ body = json.dumps(value, allow_nan=False).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.send_header("X-Content-Type-Options", "nosniff")+ self.end_headers()+ self.wfile.write(body)++ def _check_origin(self):+ allowed = {f"127.0.0.1:{self.server.server_port}", f"localhost:{self.server.server_port}"}+ if self.headers.get("Host") not in allowed:+ raise PermissionError("Invalid local Host header")+ origin = self.headers.get("Origin")+ if origin and origin not in {"http://" + host for host in allowed}:+ raise PermissionError("Requests must originate from this local interface")++ def _route(self):+ self._check_origin()+ parts = [unquote(p) for p in urlsplit(self.path).path.strip("/").split("/")]+ manager = self.server.manager+ if self.command == "GET" and parts == ["api", "capabilities"]:+ return self._reply({"schema_version": 1, "coverage": "conus", "max_upload_bytes": manager.max_upload_bytes,+ "max_runtime_s": manager.max_runtime_s, "max_pending": manager.max_pending})+ if self.command == "POST" and parts == ["api", "jobs"]:+ if self.headers.get("Transfer-Encoding"):+ raise ValueError("Use a Content-Length upload")+ if self.headers.get_content_type() != "application/octet-stream":+ raise ValueError("Upload raw audio as application/octet-stream")+ metadata = json.loads(self.headers.get("X-Dopplergeist-Request", "{}"))+ if not isinstance(metadata, dict) or "audio_path" in metadata:+ raise ValueError("Upload metadata must be a request object without audio_path")+ size = int(self.headers.get("Content-Length", "0"))+ suffix = Path(self.headers.get("X-Filename", "input.mp3")).suffix+ self.connection.settimeout(30)+ return self._reply(manager.submit(metadata, self.rfile, size, suffix=suffix), 202)+ if len(parts) >= 3 and parts[:2] == ["api", "jobs"]:+ job_id = parts[2]+ if self.command == "GET" and len(parts) == 3:+ return self._reply(manager.get(job_id))+ if self.command == "POST" and parts[3:] == ["cancel"]:+ return self._reply(manager.cancel(job_id))+ if self.command == "GET" and parts[3:] == ["artifacts"]:+ directory = manager.directory(job_id)+ artifacts = []+ for path in sorted(directory.rglob("*")):+ if path.is_file() and not path.is_symlink() and path.name not in {"operator.json", "cancel"} and not path.name.endswith(".tmp"):+ artifacts.append({"path": path.relative_to(directory).as_posix(), "bytes": path.stat().st_size})+ return self._reply({"artifacts": artifacts})+ if self.command == "GET" and len(parts) > 4 and parts[3] == "artifacts":+ directory = manager.directory(job_id)+ relative = Path(*parts[4:])+ path = (directory / relative).resolve()+ if path == directory or directory not in path.parents or not path.is_file() or "operator.json" in relative.parts:+ raise KeyError("Unknown artifact")+ return self._file(path, download=path.suffix not in {".png", ".svg"})+ if self.command == "GET":+ asset = {"/": "index.html", "/app.js": "app.js", "/style.css": "style.css"}.get(urlsplit(self.path).path)+ if asset:+ return self._file(files("aircraft_geoloc.web").joinpath(asset))+ raise KeyError("Unknown endpoint")++ def _file(self, path, download=False):+ self.send_response(200)+ self.send_header("Content-Type", mimetypes.guess_type(str(path))[0] or "application/octet-stream")+ self.send_header("Content-Length", str(path.stat().st_size))+ self.send_header("X-Content-Type-Options", "nosniff")+ self.send_header("Content-Security-Policy", "default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'")+ if download:+ self.send_header("Content-Disposition", f'attachment; filename="{path.name.replace(chr(34), "")}"')+ self.end_headers()+ with path.open("rb") as source:+ while block := source.read(1024*1024):+ self.wfile.write(block)++ def _handle(self):+ try:+ self._route()+ except PermissionError as exc:+ self._reply({"error": str(exc)}, 403)+ except KeyError as exc:+ self._reply({"error": str(exc)}, 404)+ except OverflowError as exc:+ self._reply({"error": str(exc)}, 429)+ except (ValueError, TimeoutError) as exc:+ self._reply({"error": str(exc)}, 400)+ except (BrokenPipeError, ConnectionResetError):+ pass++ do_GET = _handle+ do_POST = _handle+++def serve(root, config=None, *, port=8765, max_runtime_s=3600, max_upload_bytes=100*1024*1024):+ manager = JobManager(root, config, max_runtime_s=max_runtime_s, max_upload_bytes=max_upload_bytes)+ try:+ with JobServer(("127.0.0.1", port), manager) as server:+ print(f"DOPPLERGEIST: http://127.0.0.1:{server.server_port} (jobs: {manager.root})", flush=True)+ try:+ server.serve_forever()+ except KeyboardInterrupt:+ pass+ finally:+ manager.close()diff --git a/src/aircraft_geoloc/web/__init__.py b/src/aircraft_geoloc/web/__init__.pynew file mode 100644index 0000000..5d6a00f--- /dev/null+++ b/src/aircraft_geoloc/web/__init__.py@@ -0,0 +1 @@+"""Bundled local upload interface."""diff --git a/src/aircraft_geoloc/web/app.js b/src/aircraft_geoloc/web/app.jsnew file mode 100644index 0000000..17d149f--- /dev/null+++ b/src/aircraft_geoloc/web/app.js@@ -0,0 +1,126 @@+'use strict';+const $ = id => document.getElementById(id);+const terminal = new Set(['needs_input', 'succeeded', 'inconclusive', 'failed', 'cancelled']);+let activeJob = null, timer = null, maxBytes = 100 * 1024 * 1024;+const node = (tag, text, cls) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; if (cls) n.className = cls; return n; };+async function api(path, options) {+ const response = await fetch(path, options);+ const value = await response.json();+ if (!response.ok) throw new Error(value.error || `Request failed (${response.status})`);+ return value;+}+function remember(id) {+ try {+ const recent = JSON.parse(localStorage.getItem('dopplergeist-jobs') || '[]');+ localStorage.setItem('dopplergeist-jobs', JSON.stringify([id, ...recent.filter(x => x !== id)].slice(0, 8)));+ renderRecent();+ } catch (_) { /* Private browser storage may be disabled. */ }+}+function renderRecent() {+ try {+ const ids = JSON.parse(localStorage.getItem('dopplergeist-jobs') || '[]');+ $('recent').replaceChildren();+ for (const id of ids) {+ if (!/^[0-9a-f]{32}$/.test(id)) continue;+ const li = node('li'); const a = node('a', id.slice(0, 12)); a.href = `/?job=${id}`;+ li.append(a); $('recent').append(li);+ }+ $('recent-panel').hidden = !$('recent').children.length;+ } catch (_) { /* Optional recent-job links. */ }+}+async function artifacts(id) {+ const response = await api(`/api/jobs/${id}/artifacts`);+ if (id !== activeJob) return;+ $('artifacts').replaceChildren(); $('diagnostics').replaceChildren();+ for (const item of response.artifacts) {+ const href = `/api/jobs/${id}/artifacts/${item.path.split('/').map(encodeURIComponent).join('/')}`;+ const li = node('li'); const a = node('a', item.path); a.href = href; a.download = '';+ li.append(a, node('span', ` · ${(item.bytes / 1024).toFixed(1)} KB`, 'muted')); $('artifacts').append(li);+ if (/\.png$/i.test(item.path) && /event|spectro|discovery|model|location/i.test(item.path)) {+ const figure = node('figure', undefined, 'diagnostic'); const img = node('img');+ img.src = href; img.alt = `Analysis evidence: ${item.path}`; img.loading = 'lazy';+ figure.append(img, node('figcaption', item.path)); $('diagnostics').append(figure);+ }+ }+}+function render(value) {+ $('empty').hidden = true; $('job').hidden = false;+ $('job-id').textContent = `JOB ${value.job_id}`;+ $('status').textContent = value.status.replaceAll('_', ' ');+ $('stage').textContent = value.stage || '';+ $('progress').value = value.progress || (terminal.has(value.status) ? 1 : 0);+ $('cancel').hidden = terminal.has(value.status);+ $('message').textContent = value.message || 'Analysis is running. You can return to this job using its saved link.';+ $('required').hidden = !value.required_fields?.length;+ $('required').textContent = value.required_fields?.length ? `Required input: ${value.required_fields.join(', ')}. Add the evidence to a new analysis; this run is preserved.` : '';+ $('candidates').replaceChildren();+ if (value.candidates?.length) {+ $('candidates').append(node('h3', value.status === 'succeeded' ? 'Supported location & alternatives' : 'Location hypotheses · result remains inconclusive'));+ value.candidates.forEach((candidate, i) => {+ const card = node('div', undefined, 'candidate');+ card.append(node('strong', `${i + 1}. ${candidate.lat.toFixed(6)}, ${candidate.lon.toFixed(6)}`));+ if (candidate.uncertainty) {+ const u = candidate.uncertainty;+ card.append(node('p', `${u.kind === 'calibrated' ? 'Calibrated uncertainty' : 'Sensitivity radius'}: ${u.radius_m.toFixed(0)} m · ${u.method}`));+ if (u.coverage_probability !== undefined) card.append(node('p', `Calibrated coverage: ${(100 * u.coverage_probability).toFixed(0)}% · ${u.calibration_reference}`));+ } else card.append(node('p', 'Location uncertainty was not established.'));+ card.append(node('p', `Score ${candidate.score.toPrecision(5)} (${candidate.score_kind}); not a probability.`));+ card.append(node('p', `Flights: ${candidate.flight_ids.join(', ')} · Recording start: ${candidate.recording_start_utc}`));+ const map = node('a', 'View coordinate on OpenStreetMap');+ map.href = `https://www.openstreetmap.org/?mlat=${candidate.lat}&mlon=${candidate.lon}#map=14/${candidate.lat}/${candidate.lon}`;+ map.target = '_blank'; map.rel = 'noopener noreferrer'; card.append(map); $('candidates').append(card);+ });+ }+ $('events').replaceChildren();+ if (value.events?.length) {+ $('events').append(node('h3', `${value.events.length} detected Doppler curves`));+ for (const event of value.events) $('events').append(node('div', `${event.event_id} · ${event.start_s.toFixed(1)}–${event.end_s.toFixed(1)} s · ${event.band_hz.map(x => x.toFixed(0)).join('–')} Hz${event.harmonic_group_id ? ` · group ${event.harmonic_group_id}` : ''}`, 'event'));+ }+}+async function poll(id) {+ clearTimeout(timer);+ try {+ const value = await api(`/api/jobs/${id}`);+ if (id !== activeJob) return;+ $('connection').textContent = ''; render(value);+ if (terminal.has(value.status)) await artifacts(id);+ else timer = setTimeout(() => poll(id), 1000);+ } catch (error) {+ if (id !== activeJob) return;+ $('connection').textContent = `Could not read this job: ${error.message}. Start the service with the same jobs directory to reconnect.`;+ timer = setTimeout(() => poll(id), 5000);+ }+}+function selectJob(id) {+ activeJob = id;+ history.replaceState(null, '', `/?job=${encodeURIComponent(id)}`);+ remember(id); poll(id);+}+$('audio').addEventListener('change', () => { $('file-label').textContent = $('audio').files[0]?.name || 'Your original file is preserved with the job.'; });+$('upload-form').addEventListener('submit', async event => {+ event.preventDefault(); $('upload-error').textContent = '';+ const file = $('audio').files[0];+ if (!file || file.size <= 0 || file.size > maxBytes) { $('upload-error').textContent = `Choose a nonempty recording up to ${(maxBytes / 1024 / 1024).toFixed(0)} MB.`; return; }+ const start = $('start').value, end = $('end').value;+ if (end && !start) { $('upload-error').textContent = 'Enter the earliest recording start as well.'; return; }+ if (start && end && end < start) { $('upload-error').textContent = 'The latest start must be at or after the earliest start.'; return; }+ const request = {schema_version: 1, search: {coverage: 'conus'}};+ if (start) {+ request.time_window = {start_utc: start + 'Z', end_utc: (end || start) + 'Z', source: 'user'};+ if ($('time-source').value.trim()) request.time_window.source_detail = $('time-source').value.trim();+ }+ $('submit').disabled = true;+ try {+ const value = await api('/api/jobs', {method: 'POST', headers: {'Content-Type': 'application/octet-stream', 'X-Dopplergeist-Request': JSON.stringify(request), 'X-Filename': 'input.' + (file.name.split('.').pop() || 'mp3').replace(/[^a-z0-9]/gi, '')}, body: file});+ render(value); selectJob(value.job_id);+ } catch (error) { $('upload-error').textContent = error.message; }+ finally { $('submit').disabled = false; }+});+$('cancel').addEventListener('click', async () => {+ try { const value = await api(`/api/jobs/${activeJob}/cancel`, {method: 'POST'}); render(value); await artifacts(activeJob); }+ catch (error) { $('connection').textContent = error.message; }+});+api('/api/capabilities').then(value => { maxBytes = value.max_upload_bytes; $('limits').textContent = `Up to ${(maxBytes / 1024 / 1024).toFixed(0)} MB per file. Analysis budget: ${(value.max_runtime_s / 60).toFixed(0)} minutes per job.`; }).catch(error => { $('upload-error').textContent = error.message; });+renderRecent();+const savedJob = new URLSearchParams(location.search).get('job');+if (savedJob && /^[0-9a-f]{32}$/.test(savedJob)) selectJob(savedJob);diff --git a/src/aircraft_geoloc/web/index.html b/src/aircraft_geoloc/web/index.htmlnew file mode 100644index 0000000..131d117--- /dev/null+++ b/src/aircraft_geoloc/web/index.html@@ -0,0 +1,18 @@+<!doctype html>+<html lang="en">+<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DOPPLERGEIST · Aircraft sound locator</title><link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script></head>+<body>+<header><a href="/" class="brand">DOPPLER<span>GEIST</span></a><span class="tag">Aircraft sound → location evidence</span></header>+<main>+<section class="intro"><p class="eyebrow">ACOUSTIC GEOLOCATION</p><h1>Find the flights.<br>Test the location.</h1><p>Upload a recording to discover aircraft Doppler curves, search historical flight tracks, and inspect the evidence. When the evidence cannot support a location, the result is inconclusive.</p><p class="scope">Search coverage: <strong>contiguous United States (CONUS)</strong>. Automatic nationwide accuracy is under evaluation; the approximately 100 m target is not guaranteed.</p></section>+<div class="layout">+<section class="panel" aria-labelledby="upload-heading"><h2 id="upload-heading">New analysis</h2><form id="upload-form">+<label class="drop" for="audio"><span class="upload-symbol" aria-hidden="true">↑</span><strong>Choose an MP3 recording</strong><span id="file-label">Your original file is preserved with the job.</span><input id="audio" name="audio" type="file" accept=".mp3,audio/mpeg,.wav,.flac,.m4a,.ogg" required></label>+<fieldset><legend>When did the recording start?</legend><p class="help">Enter UTC, including the date. A window is allowed. File creation and upload times do not establish recording time. Leave blank if unknown; analysis will request this evidence before searching.</p><label for="start">Earliest start (UTC)</label><input id="start" type="datetime-local" step="1"><label for="end">Latest start (UTC)</label><input id="end" type="datetime-local" step="1"><label for="time-source">How is this time known? <span class="muted">Optional</span></label><input id="time-source" type="text" maxlength="500" placeholder="For example, recorder clock synchronized before recording"></fieldset>+<p id="limits" class="help"></p><button id="submit" type="submit">Upload & analyze <span aria-hidden="true">→</span></button><p id="upload-error" role="alert"></p>+</form></section>+<section class="panel results" aria-labelledby="results-heading"><div class="section-row"><h2 id="results-heading">Analysis</h2><button id="cancel" class="secondary" hidden>Cancel job</button></div><div id="empty"><div class="wave" aria-hidden="true">∿∿∿</div><h3>Your evidence will appear here</h3><p>Detected curves, location hypotheses, uncertainty, and downloadable artifacts stay attached to each job.</p></div><div id="job" hidden><p id="job-id" class="mono"></p><div class="section-row"><strong id="status" role="status" aria-live="polite"></strong><span id="stage" class="muted"></span></div><progress id="progress" max="1" value="0" aria-label="Analysis progress"></progress><p id="message"></p><p id="required" class="notice" hidden></p><div id="candidates"></div><div id="events"></div><div id="diagnostics"></div><details id="downloads"><summary>Download run artifacts</summary><ul id="artifacts"></ul></details><p id="connection" role="alert"></p></div></section>+</div>+<section id="recent-panel" class="recent" hidden><h2>Recent jobs on this browser</h2><ul id="recent"></ul></section>+<footer>Scores rank hypotheses; they are not probabilities. An inconclusive result can include alternatives without supporting a precise location.</footer>+</main></body></html>diff --git a/src/aircraft_geoloc/web/style.css b/src/aircraft_geoloc/web/style.cssnew file mode 100644index 0000000..efe8a38--- /dev/null+++ b/src/aircraft_geoloc/web/style.css@@ -0,0 +1 @@+:root{color-scheme:dark;--bg:#101719;--panel:#192326;--edge:#334247;--muted:#a6b8bd;--accent:#baf078;--ink:#f3f8f5;font-family:Inter,ui-sans-serif,system-ui,sans-serif;font-size:15px}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}header{min-height:85px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--edge);padding:20px max(6vw,24px)}a{color:var(--accent);text-underline-offset:3px}.brand{font-weight:850;font-size:21px;letter-spacing:.04em;text-decoration:none;color:var(--ink)}.brand span{color:var(--accent)}.tag,.muted,.help,footer{color:var(--muted)}.tag{font-size:13px}main{max-width:1350px;margin:auto;padding:52px max(6vw,24px) 24px}.intro{max-width:820px;margin-bottom:36px}.eyebrow{color:var(--accent);font-size:11px;font-weight:700;letter-spacing:.18em}h1{font-size:clamp(34px,5vw,58px);line-height:1.04;letter-spacing:-.045em;margin:18px 0 22px}.intro>p:not(.eyebrow){font-size:16px;line-height:1.65;color:#bccbd0}.intro .scope{font-size:13px!important;border-left:2px solid var(--accent);padding-left:14px}.layout{display:grid;grid-template-columns:minmax(300px,1fr) minmax(320px,1.3fr);gap:22px;align-items:start}.panel{border:1px solid var(--edge);background:var(--panel);border-radius:14px;padding:26px;min-width:0}h2{font-size:18px;letter-spacing:-.02em;margin:0 0 24px}h3{font-size:16px;margin:25px 0 12px}.drop{display:flex;align-items:center;text-align:center;gap:10px;flex-direction:column;padding:22px;border:1px dashed #72898e;border-radius:10px;cursor:pointer;background:#142023}.drop span:last-of-type{font-size:12px;color:var(--muted)}.upload-symbol{color:var(--accent);font-size:28px}.drop input{font-size:12px;width:100%;max-width:290px;margin-top:5px}fieldset{padding:0;margin:30px 0 20px;border:0}legend{font-size:15px;font-weight:650;padding:0}.help{font-size:12px;line-height:1.6}label:not(.drop){display:block;font-size:12px;font-weight:600;margin:16px 0 7px}input:not([type=file]){width:100%;border:1px solid #52666c;border-radius:6px;background:#111c1f;color:var(--ink);padding:11px;font:inherit;font-size:13px}input:focus,button:focus,a:focus{outline:2px solid var(--accent);outline-offset:3px}button{font:inherit;font-size:13px;font-weight:700;border:0;border-radius:7px;padding:13px 17px;color:#1b2916;background:var(--accent);cursor:pointer}button:disabled{opacity:.5;cursor:wait}button[type=submit]{width:100%;display:flex;justify-content:space-between}.secondary{border:1px solid var(--edge);background:transparent;color:var(--ink);padding:8px 11px;font-size:11px}.section-row{display:flex;justify-content:space-between;align-items:center;gap:12px}.section-row h2{margin:0}.results>.section-row{margin-bottom:24px}.results{min-height:400px}.mono{font-family:ui-monospace,monospace;font-size:11px;color:var(--muted);overflow-wrap:anywhere}.wave{font-size:65px;color:#739b64;letter-spacing:6px;margin-bottom:20px}#empty{text-align:center;padding:50px 18px}#empty p{font-size:13px;line-height:1.7;color:var(--muted)}progress{display:block;width:100%;height:7px;margin:18px 0;accent-color:var(--accent)}#message{font-size:14px;line-height:1.65}#status{text-transform:capitalize;color:var(--accent)}#stage{font-size:11px}.notice{background:#393222;border:1px solid #72613b;color:#f1dfaf;border-radius:7px;padding:13px;font-size:13px}.candidate{padding:15px;background:#111b1e;border:1px solid var(--edge);border-radius:8px;margin:10px 0;font-size:13px;line-height:1.7}.candidate strong{font-size:16px;display:block}.candidate p{margin:5px 0;color:var(--muted)}.event{border-top:1px solid var(--edge);padding:12px 0;font-size:12px;color:var(--muted)}.diagnostic{margin:15px 0}.diagnostic img{display:block;width:100%;border-radius:5px;background:#111}.diagnostic figcaption{font-size:11px;margin-top:7px;color:var(--muted)}details{border-top:1px solid var(--edge);padding-top:18px;margin-top:24px;font-size:12px}summary{cursor:pointer;color:var(--accent)}ul{padding-left:20px}li{margin:9px 0;overflow-wrap:anywhere}#upload-error,#connection{color:#ffb9ac;font-size:13px}.recent{margin-top:30px}.recent h2{font-size:14px}.recent ul{display:flex;flex-wrap:wrap;gap:15px;list-style:none;padding:0;font-size:12px}footer{border-top:1px solid var(--edge);margin-top:42px;padding-top:22px;font-size:11px;line-height:1.7}[hidden]{display:none!important}@media(max-width:760px){header{padding:20px 22px}.tag{display:none}main{padding:30px 18px}.layout{grid-template-columns:1fr}.panel{padding:22px}h1{font-size:42px}.results{min-height:300px}#empty{padding:20px 8px}}diff --git a/tests/test_service.py b/tests/test_service.pynew file mode 100644index 0000000..a34d92b--- /dev/null+++ b/tests/test_service.py@@ -0,0 +1,123 @@+"""Transport/lifecycle checks. Scientific end-to-end checks live separately."""+from contextlib import contextmanager+import io+import json+from pathlib import Path+import threading+import urllib.error+import urllib.request++import pytest++from aircraft_geoloc.jobs import JobManager, read_json, result+from aircraft_geoloc.service import JobServer+++@contextmanager+def running_server(tmp_path, monkeypatch):+ # Hold queued analyses to test HTTP and persistence independently of DSP.+ monkeypatch.setattr(JobManager, "_run", lambda self, directory: None)+ manager = JobManager(tmp_path)+ server = JobServer(("127.0.0.1", 0), manager)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield manager, f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ manager.close()+ thread.join()+++def request(url, data=None, metadata=None, **headers):+ if metadata is not None:+ headers.update({"Content-Type": "application/octet-stream", "X-Dopplergeist-Request": json.dumps(metadata)})+ req = urllib.request.Request(url, data=data, headers=headers)+ with urllib.request.urlopen(req, timeout=5) as response:+ body = response.read()+ return response.status, json.loads(body) if response.headers.get_content_type() == "application/json" else body+++def test_upload_readback_cancel_and_original_preservation(tmp_path, monkeypatch):+ with running_server(tmp_path, monkeypatch) as (manager, url):+ code, job = request(url + "/api/jobs", b"encoded audio payload", {"schema_version": 1})+ assert code == 202 and job["status"] == "queued"+ job_id = job["job_id"]+ assert request(url + f"/api/jobs/{job_id}")[1] == job+ assert request(url + f"/api/jobs/{job_id}/cancel", b"")[1]["status"] == "cancelled"+ assert request(url + f"/api/jobs/{job_id}/artifacts/input.mp3")[1] == b"encoded audio payload"+ items = request(url + f"/api/jobs/{job_id}/artifacts")[1]["artifacts"]+ assert "input.json" in [p["path"] for p in items]+ assert "operator.json" not in [p["path"] for p in items]+ restarted = JobManager(tmp_path)+ try:+ assert restarted.get(job_id)["status"] == "cancelled"+ assert (restarted.directory(job_id) / "input.mp3").read_bytes() == b"encoded audio payload"+ finally:+ restarted.close()+++def test_terminal_result_survives_restart_and_interrupted_job_is_explicit(tmp_path, monkeypatch):+ monkeypatch.setattr(JobManager, "_run", lambda self, directory: None)+ manager = JobManager(tmp_path)+ complete = manager.submit({"schema_version": 1}, io.BytesIO(b"first"), 5)+ result(manager.directory(complete["job_id"]), "inconclusive", reason_code="no_events", message="No events.")+ pending = manager.submit({"schema_version": 1}, io.BytesIO(b"second"), 6)+ manager.close()+ # Simulate abrupt shutdown rather than the normal graceful cancellation.+ result(tmp_path / pending["job_id"], "running", stage="search")+ restarted = JobManager(tmp_path)+ try:+ assert restarted.get(complete["job_id"])["reason_code"] == "no_events"+ assert restarted.get(pending["job_id"])["reason_code"] == "interrupted"+ assert (tmp_path / complete["job_id"] / "input.mp3").read_bytes() == b"first"+ finally:+ restarted.close()+++def test_request_validation_upload_limits_and_paths(tmp_path, monkeypatch):+ with running_server(tmp_path, monkeypatch) as (manager, url):+ for metadata in ({"schema_version": 1, "events": []}, {"schema_version": 1, "audio_path": "/etc/passwd"}):+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + "/api/jobs", b"x", metadata)+ assert error.value.code == 400+ with pytest.raises(ValueError):+ manager.submit({"schema_version": 1}, io.BytesIO(b"x"), manager.max_upload_bytes + 1)+ job = request(url + "/api/jobs", b"x", {"schema_version": 1})[1]+ for suffix in ("operator.json", "%2e%2e/%2e%2e/.manager.lock", "%2Fetc%2Fpasswd"):+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + f"/api/jobs/{job['job_id']}/artifacts/" + suffix)+ assert error.value.code == 404+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + "/api/jobs", b"x", {"schema_version": 1}, Origin="https://unrelated.example")+ assert error.value.code == 403+ assert b"DOPPLERGEIST" in request(url + "/")[1]+ assert b"upload-form" in request(url + "/app.js")[1]+++def test_lock_and_queued_cancellation(tmp_path):+ manager = JobManager(tmp_path)+ manager._serial.acquire()+ try:+ with pytest.raises(ValueError, match="Another job manager"):+ JobManager(tmp_path)+ queued = manager.submit({"schema_version": 1}, io.BytesIO(b"x"), 1)+ assert manager.cancel(queued["job_id"])["status"] == "cancelled"+ finally:+ manager._serial.release()+ manager.close()+++def test_analysis_wall_time_budget_is_terminal_and_persistent(tmp_path):+ # A real subprocess is stopped before importing the scientific stack. This+ # tests resource/lifecycle enforcement, not a simulated search result.+ manager = JobManager(tmp_path, max_runtime_s=0.001)+ try:+ job = manager.submit({"schema_version": 1}, io.BytesIO(b"x"), 1)+ final = manager.wait(job["job_id"])+ assert final["status"] == "inconclusive" and final["reason_code"] == "work_limit"+ assert manager.get(job["job_id"]) == final+ assert not manager._processes+ finally:+ manager.close()