Metadata-Version: 2.4
Name: szl-seismic-review
Version: 0.3.0
Summary: Evidence-bound seismic catalogue review pilot with blinded human review and calibrated Japan-panel research baseline
Author-email: Stephen Lutar <stephen@szlholdings.com>
License-Expression: Apache-2.0 AND CC-BY-4.0
Project-URL: Homepage, https://huggingface.co/spaces/SZLHOLDINGS/szl-seismic-review
Project-URL: Live application, https://szlholdings-szl-seismic-review.hf.space/live
Project-URL: Release evidence, https://szlholdings-szl-seismic-review.hf.space/api/evidence
Project-URL: Repository, https://github.com/szl-holdings/szl-seismic-review
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
License-File: data/SOURCE_LICENSE.md
License-File: frontend/szl/SOURCE.json
Requires-Dist: fastapi==0.165.0
Requires-Dist: uvicorn==0.54.0
Requires-Dist: huggingface-hub==2.5.0
Dynamic: license-file

---
title: SZL Seismic Review
emoji: 🌐
colorFrom: blue
colorTo: gray
sdk: docker
app_port: 7860
license: apache-2.0
short_description: Live 3D earthquake observatory and research review desk
---

# SZL Seismic Review

<!-- szl:header v1 -->
<!-- Native identity: szl-brand@4309f6fce89179331b0b3ed8c99494e76c5be256; Orbit v2 icon. -->
<p>
  <a href="https://github.com/szl-holdings">
    <img src="https://raw.githubusercontent.com/szl-holdings/szl-brand/4309f6fce89179331b0b3ed8c99494e76c5be256/kit/logos/orbit-v2/suite/szl-icon-32.svg" alt="SZL Holdings — Orbit v2" width="32" height="32" />
  </a>
</p>

**Control before action. Evidence after.**

[Product](https://a-11-oy.com) · [Proof](https://a11oy.net) · [GitHub organization](https://github.com/szl-holdings)
<!-- /szl:header -->

<p><small>Orbit v2 artwork © SZL Holdings · <a href="https://github.com/szl-holdings/szl-brand/blob/4309f6fce89179331b0b3ed8c99494e76c5be256/kit/LICENSE">CC BY 4.0</a>. The SZL name and mark remain trademarks; source-code and scientific-data licenses remain as declared below.</small></p>

An original SZL Holdings Python service and browser dashboard for studying **human confirmability of machine-catalogue earthquake detections**. The layout takes visual cues from the user-provided [BOb dashboard](https://bob.bzzzbx.com/dashboard.html); no BOb code or assets are included. The model and data path are based on a pinned, attributed [Meng et al. EarthArXiv preprint](https://eartharxiv.org/repository/view/14864/) and its [Zenodo dataset, version 1.1.0](https://doi.org/10.5281/zenodo.22059219).

This is a **research pilot**. It does not determine whether an earthquake physically occurred, predict earthquakes, issue a hazard forecast, or validate a model for another region. The existing [a11oy seismic module](https://github.com/szl-holdings/a11oy/blob/main/a11oy_seismic.py) forecasts aftershock rates from USGS data; this repository handles a separate catalogue-quality question. `szl-lambda-gate` is not a scientific scoring dependency.

## Live earthquake observatory

[Open the live globe](https://szlholdings-szl-seismic-review.hf.space/live) to rotate the Earth, view reported depths, and inspect an agency's event list. Choose the USGS worldwide feed (M2.5+, past seven days), Japan's latest JMA provisional daily list, or Peru's latest 100 IGP/CENSIS reports. Each view shows its own reporting window, retrieval status and source links. The source can revise a report. The globe plots epicentres at the surface, and depth is measured in kilometres.

The read-only JSON endpoints are [/api/live/usgs](https://szlholdings-szl-seismic-review.hf.space/api/live/usgs), [/api/live/jma](https://szlholdings-szl-seismic-review.hf.space/api/live/jma), and [/api/live/igp](https://szlholdings-szl-seismic-review.hf.space/api/live/igp). Stale responses identify their last retrieval, and an unavailable feed returns HTTP 503. These external reports have no SZL human verdict or model score.

## Explore the catalogue

[Open the interactive review desk](https://szlholdings-szl-seismic-review.hf.space/#catalogue). Under **Published verdict**, choose **Unresolved** and open one of the 36 matching detections to see how the four reviewers voted. The reference panel contains 200 earthquake detections from the NE Japan forearc and 800 verdicts published by Meng and colleagues. The **SAMPLE** events and waveforms used to test the review workflow are synthetic.

The [November 30, 2026 release run](https://github.com/szl-holdings/szl-seismic-review/actions/runs/46532107441) verified the deployed application at GitHub commit [`88ac1a73`](https://github.com/szl-holdings/szl-seismic-review/commit/88ac1a73d7b335624b84a29d1dba8c5bc816fb53), including catalogue search and export in a browser. The [live evidence endpoint](https://szlholdings-szl-seismic-review.hf.space/api/evidence) reports the source data checksums, model evaluation and running revision.

To report a discrepancy, include the public detection ID, the filter you used and the running revision in a [GitHub issue](https://github.com/szl-holdings/szl-seismic-review/issues).

## What works

- A checksum-verified, 200-event NE Japan forearc panel with 800 published reviewer verdicts, displayed with attribution and a three-state consensus.
- A seven-feature logistic model trained on the 164 panel cases with a resolved plurality (139 confirmed, 25 rejected). Thirty-six cases stay unresolved. Five-fold out-of-fold AUC is **0.850** (bootstrap interval **0.771–0.912**) and Brier score **0.102** on the *same panel*. A three-feature baseline yields AUC **0.839** and Brier **0.101**; the seven-feature fit does not show a clear gain in this pilot.
- A FastAPI backend, responsive dashboard, read-only model-scoring endpoint, source manifest, and reproducible training script.
- A source-custodian CSV import and reviewer-scoped blind workflow. Each reviewer has a distinct bearer credential; their identity comes from that credential, never a request field. Event metadata and the waveform source stay hidden from each reviewer until their own verdict is locked. The custodian can attach five station traces in the browser, and duplicate reviewer submissions are blocked. These traces are **operator-supplied and not independently authenticated by the service**.
- An atomic hash-chained receipt for every import, waveform attachment, and verdict. The optional private Hub store acknowledges a write only after its snapshot commit and exact byte readback. Receipts are **UNSIGNED**; administrator resistance is **UNVERIFIED**. They are not Khipu or independent authorization proofs.
- A public read-only mode by default, with explicit private-store activation and separate custodian/reviewer credentials for retained review transactions.
- A searchable review desk with catalogue and published-verdict filters, filtered JSON export, keyboard-accessible case details, and an evidence panel tied to the bytes loaded by the service. Imports remain blind in public search and export, including after a reviewer's private reveal.

The published archive does **not** contain continuous waveform traces, so the 200 source-panel cases cannot be freshly reviewed here. Their published verdicts are shown as source data, never as a new SZL adjudication.

## Run locally

Python 3.12 or newer is required by the pinned scientific dependencies in `requirements-dev.txt`. From this directory:

```bash
python -m venv .venv
python -m pip install -r requirements-dev.txt
python -m pytest -q tests
python -m uvicorn app:app --host 127.0.0.1 --port 7860
```

Open `http://127.0.0.1:7860`. The service is read-only unless credentials are configured. Set `SZL_REVIEW_WRITE_TOKEN` for the source custodian's import and waveform attachment actions, and `SZL_REVIEWER_TOKENS_JSON` to a JSON object mapping each reviewer ID to a **distinct** bearer token. The service refuses duplicate reviewer tokens or a reviewer token equal to the custodian token. Set `SZL_REVIEW_DB_PATH` to controlled, durable storage before retaining real reviews. Keep credentials in a secret manager; do not put them in this repository, a URL, or browser storage. The UI holds entered tokens only in current page memory. A custodian who sees the source CSV is not an independent blind reviewer; use separate people and stronger identity and storage controls before a formal multi-person study.

An acknowledged import, waveform attachment or verdict stays recorded as successful in the UI if a later read refresh fails. Refresh controls retry only reads; they do not resubmit the write. A successful import clears the selected file before another import can be submitted.

Generate each bearer credential with a cryptographic secret manager (for example, Python `secrets.token_urlsafe(32)`). Configured tokens must be distinct, 32–512 ASCII bearer characters; the format check does not measure entropy. Reviewer identifiers must start with an ASCII letter or digit and contain only letters, digits, `.`, `_` and `-` (100 characters maximum). Duplicate JSON identities, shared tokens, and malformed credentials fail closed at startup. Malformed request credentials are rejected without an application error.

### Custody and blind review

1. The custodian imports a CSV, then explicitly loads **Private source custody** using the custodian credential. This private list maps each source event to its opaque case ID, so multi-event imports can receive the correct traces. Source checksums, attachment checksums, search, and pagination remain available after reopening the service with the same database.
2. The custodian selects the intended source event and attaches its five blinded station traces. An attachment is immutable. This view cannot submit reviewer verdicts, even if another reviewer token remains in the page.
3. A reviewer uses the public blind case ID with their own credential, examines the traces, and locks a verdict. Only that reviewer's locked case reveals event metadata, source reference, retained notes, timestamps and waveform hashes. Another reviewer stays blind until locking their own verdict. Use separate people and browser profiles for an actual blind study.
4. Clearing/changing the custodian credential immediately clears private custody rows and invalidates pending reads. Public discovery and export never include this mapping. The custodian can read `/api/receipts` to check the local unsigned chain; reads do not add receipts.

Hosted writes require the private Hub store described in [OPERATIONS.md](OPERATIONS.md), named access credentials, and explicit activation. Without that store, hosted custody and writes remain blocked even if a local SQLite path is configured. In remote `read-only` mode, authenticated recovery reads remain available and writes are blocked. Local research mode still labels storage durability unverified. Configuration is **DECLARED**; provider qualification, accepted transactions, and restart recovery require separate measured reports.

The import CSV header is:

```text
event_id,n_pha_total,n_sta,moveout_rms,az_gap,sec_az_gap,dist_nearest_sta_km,mag
```

Optional `time,lat,lon,dep` fields are hidden during blind review. Azimuth gaps are in degrees, nearest-station distance in kilometres, and move-out RMS in seconds. Imports from outside the fitted Japan region abstain; values beyond the training feature ranges also abstain. Any score on a new import is labelled **unvalidated import** until a suitable independent panel and local calibration exist.

### Input contract v1 (opt-in)

`/api/score` accepts an optional `input_contract` object. Without it, requests and responses are unchanged. With it, the service checks the features against `INPUT_CONTRACT_V1` in `app.py` before scoring:

```json
{
  "region": "japan_forearc",
  "features": {"n_pha_total": 27, "n_sta": 20, "moveout_rms": 0.5594, "az_gap": 214.0,
               "sec_az_gap": 50.8, "dist_nearest_sta_km": 39.455, "mag": 0.87},
  "input_contract": {
    "version": "szl.seismic-input/v1",
    "units": {"n_pha_total": "count", "n_sta": "count", "moveout_rms": "s", "az_gap": "deg",
              "sec_az_gap": "deg", "dist_nearest_sta_km": "km", "mag": "magnitude"}
  }
}
```

| Feature | Unit token | Accepted values |
|---|---|---|
| `n_pha_total`, `n_sta` | `count` | integer, at least 0 |
| `moveout_rms` | `s` | real, at least 0 |
| `az_gap`, `sec_az_gap` | `deg` | real, 0 to 360 |
| `dist_nearest_sta_km` | `km` | real, at least 0 |
| `mag` | `magnitude` | real; the magnitude scale is undeclared in the source fixture |

- Each declared unit must equal its token exactly. A missing unit is `UNIT_UNDECLARED`; any other value, such as `ms`, `mi`, `rad`, `seconds` or `Mw`, is `UNIT_MISMATCH`. The service refuses mismatches and never converts units.
- Values must be finite JSON numbers (not booleans) or plain decimal strings: an optional leading minus, ASCII digits and an optional fraction, with no exponent, whitespace, underscore, `inf` or `nan`. Other forms are `NON_NUMERIC`, a fractional count is `NON_INTEGER_COUNT`, and a value outside the range above is `DOMAIN`.
- Plain decimal strings are limited to 4,096 characters and are checked exactly, as are JSON integers, before conversion to the unchanged binary64 scorer. Values that cannot be represented as a finite scorer input are `DOMAIN`; advisory arithmetic is exact and does not use ambient Decimal-context rounding. Already-decoded JSON floats cannot recover the sender's original decimal precision: use a plain decimal string when that precision must be checked. Negative decimal underflow is rejected against the exact domain; signed zero remains valid.
- Any violation returns `score_status` `INPUT_CONTRACT_VIOLATION` with `confirmability_score: null` and the list of violations. A conforming request is scored exactly as it would be without the key, and the response gains an `input_contract` block. An unknown `version` or a non-object `input_contract` is rejected with HTTP 422.
- Three relations hold in all 200 published rows: `n_pha_total <= 2 * n_sta`, `sec_az_gap <= az_gap`, and `az_gap + sec_az_gap <= 360`. A request that breaks one gets an advisory (`PHASES_EXCEED_TWO_PER_STATION`, `SECONDARY_GAP_EXCEEDS_PRIMARY` or `GAPS_SUM_EXCEEDS_360`) that never changes the status. These relations are data-observed, not physical law. The `sec_az_gap` relations match a "second-largest gap" reading, which is **UNVERIFIED** against the source pipeline's code; the common secondary-gap definition (the largest gap after removing one station) is never smaller than the primary gap.
- The `input_contract` block also carries an advisory joint-support proxy, `joint_support_proxy`. Once every feature parses, it gives the Mahalanobis distance of the scorer's transformed feature vector (`log1p` counts) from the 164 resolved training rows, using their own mean and covariance. The service computes this in pure Python at startup and adds no data file, and `/api/evidence` publishes the method and threshold under `input_contract.joint_support_proxy`. The threshold is the largest distance among those same rows (in-sample, 6.05289), so no training row is flagged. A strictly greater distance, compared exactly before rounding, adds the advisory `OUTSIDE_TRAINING_JOINT_SUPPORT_PROXY` and sets `distance_status` to `ABOVE_TRAINING_MAXIMUM`. If a feature fails to parse, the status is `UNAVAILABLE`. None of the 200 published rows is flagged, the three that abstain included. Take 213 phases from 4 stations at the corner of every other training range, with `sec_az_gap` at the fixture's stored minimum `9.300000000000011`. That point is flagged and still scored. The proxy never changes `score_status` or `confirmability_score`, and it never causes an abstention. It is an advisory proxy, not joint-support certification and not scientific qualification.
- Contract conformance is not scientific qualification. A conforming input can still fall outside the training support (three published rows conform and still abstain), and the per-feature training box is not joint support. `/api/catalogues/import` and requests without the key do not use the contract.

## Rebuild the research fixture and model

The committed small CSV fixture and model artifact are enough to run the app. To independently rebuild the fixture, download the three named archives from [Zenodo record 22059219](https://zenodo.org/records/22059219) into a local archive directory, then run:

```bash
python scripts/build_reference_data.py --archive-dir path/to/archives
python scripts/train_model.py
```

The extraction script checks each archive's MD5 against the pinned Zenodo record. `data/source_manifest.json` holds the resulting SHA-256 checksums. The model script verifies those checksums before fitting and emits a chained, **UNSIGNED** training receipt in `models/receipts/` with dataset, model, harness, seed, observed CPU, training loss, and same-panel evaluation. The service checks the committed receipt's hashes at startup. Re-running the script emits another receipt, so do it only when intentionally recording a new run. Archive files are not committed or uploaded to the Space. See [RESEARCH.md](RESEARCH.md) for method, limitations, and primary-source comparisons.

## API and deployment

`/healthz`, `/api/meta`, `/api/summary`, `/api/detections`, `/api/detections/{id}`, `/api/export`, `/api/evidence` and `/api/score` provide read access. Imported case detail requires either the source-custodian token or that reviewer's token. `/api/catalogues/import` and `/api/detections/{id}/waveform` require the custodian token; `/api/reviews` requires a reviewer token and derives the reviewer ID from it. `/api/receipts` lets the custodian check the complete receipt chain without writing on GET. `/api/access` reads the caller's identity and role. `/api/storage/status` validates the configured snapshot without exposing its records. `/healthz` and remote storage status include a process boot ID to distinguish restarts. `/api/docs` is the interactive API reference.

`GET /api/custody/detections` requires the custodian token and supports bounded `q`, `limit` (1–200), and `offset`. It returns only the custodian's source-event mapping and attachment readiness; reviewers cannot use it. It uses `Cache-Control: no-store` and never mints a receipt.

### Discovery, export and evidence

- `/api/detections` and `/api/export` accept `q` (up to 100 characters), `catalogue`, `origin` (`published` or `imported`), and `consensus` (`confirmed`, `rejected` or `unresolved`). Search covers public case identifiers and published catalogue names. Imported events are searchable only by their opaque public ID; private event names, metadata, scores, source catalogue and waveform provenance are excluded. The published-consensus filter excludes imports.
- Export returns the same public card fields as discovery, with attribution, evidence class, filters and pagination metadata. Its limit is 10,000 cards per request; `truncated` and `next_offset` describe a partial export. This is a catalogue export, not a waveform or private-review export.
- `/api/evidence` identifies the loaded model and source bytes, the training receipt file hash and chain head, the unchanged same-panel evaluation, and runtime source-binding state. Same-panel results remain **REPORTED** and independent replay remains **UNAVAILABLE**. Hash agreement does not authenticate the unsigned receipt or validate supplied traces. These GET routes never mint a receipt; API responses use `Cache-Control: no-store`.

Browser regressions run in CI against a temporary read-only service. To run them locally where loopback networking and Chromium are available:

```bash
python -m pip install -r requirements-browser.txt
python -m playwright install chromium
python tests/browser_smoke.py
python tests/browser_write_outcomes.py
python tests/browser_operator_workflows.py
```

The catalogue browser checks cover pagination boundaries, combined search and filters, filtered and empty JSON downloads, evidence views, and keyboard/mobile behavior. Local export and evidence failure/retry cases are explicitly **SIMULATED**. Reports include the application JavaScript hash. Use `--browser-channel msedge` to exercise an installed Edge browser when bundled Chromium is unavailable.

The write-outcome browser regressions use **SIMULATED** intercepted write responses and read failures against an isolated read-only service. They verify UI recovery and duplicate-submission prevention, not a real operator transaction or scientific result.

The operator browser harness performs actual loopback HTTP transactions and SQLite writes using two **SAMPLE** events/traces and independently generated custodian/reviewer credentials. It accepts no remote target, uses no mocked responses, checks role denials and per-reviewer blindness, and restarts the process against the same isolated database. Its measured result establishes local workflow behavior and process-restart persistence only; it does not establish provider-volume durability, human independence, or scientific validation. Credentials are excluded from retained artifacts.

`Dockerfile` serves port 7860 for Hugging Face Spaces. No application credential is required to use the public read-only viewer. The local operator database is excluded from Git and the Docker build. Publication requires a separate Hugging Face publisher credential.

### Source-bound Space publication

[`.github/workflows/hf-sync.yml`](.github/workflows/hf-sync.yml) is the sole application-file writer for `SZLHOLDINGS/szl-seismic-review`. It runs only by manual dispatch on this repository's `main` branch and calls the dedicated SHA-pinned seismic publisher from `szl-holdings/.github`. The publisher receives the exact dispatch commit, refuses a commit that is no longer the current default-branch tip, derives the payload from Dockerfile `COPY` sources, and retains the deployment manifest and verification reports as run artifacts. Pruning and forced restarts are disabled. The workflow does not select or upgrade hardware.

Before the first dispatch, provision a **public Docker Space on CPU Basic** named `SZLHOLDINGS/szl-seismic-review` and make a target-scoped `HF_TOKEN` available to this repository's Actions through a repository or selected-organization secret. The central publisher requires an existing Space; it does not create one. Local CLI login does not establish Actions access. Provision review access separately through the [activation runbook](OPERATIONS.md).

After the exact merged source has passed CI and CodeQL, dispatch **Publish Seismic Review to Hugging Face** on `main`. Its readiness job verifies the current main SHA, the latest successful push runs and required jobs for that SHA, any separate trusted CodeQL result checks, and a readable zero-open-alert CodeQL inventory for main. A failed or pending check, unresolved alert, unreadable API, incomplete inventory or moved source blocks publication. The pinned CodeQL analysis action waits for SARIF processing before completing. A successful analysis upload alone is insufficient.

The publisher then generates an untracked `SOURCE_REVISION` file, mirrors the exact source bytes, sets and reads back `SZL_SOURCE_REVISION`, and checks the immutable Hub revision, running revision, payload hashes, and the declared application routes, including `/api/evidence`. `/api/build-info` reports a source match only when the baked file and runtime variable agree; it does not mint a receipt on GET. Keep the resulting GitHub run, source SHA, Hub SHA, deployment manifest, and runtime probe together in the release record. A workflow definition or a successful source test alone does not establish publication or runtime verification.

After publication, a separate `verify-runtime` job performs credential-free public GETs with `scripts/verify_deployment.py`. It checks the running Hub revision, GitHub source binding, frontend bytes, model/data/receipt identities, retained scientific limits, public search and export behavior, and the explicit dispatch `mode` (`read-only` by default, or `active`). Source and Hub revisions are read again at the end to detect a deployment changing during verification. The job retains its JSON report on success and failure. A failed check makes the workflow fail; publication may already have happened, so inspect both jobs before deciding the release state. This is a separate observation from the uploader by the same operator, not independent-party replication or certification.

Run the same check from the exact published checkout:

```bash
python scripts/verify_deployment.py --sha <full-published-GitHub-SHA> --output artifacts/runtime-verification.json
python tests/browser_smoke.py --live --sha <full-published-GitHub-SHA> --output-dir artifacts/live-browser
python scripts/verify_write_guards.py --sha <full-published-GitHub-SHA> --output artifacts/write-guards.json
```

The publication job also runs the live browser command and retains its screenshots, downloaded JSON exports and result report. Live mode targets only the canonical Space, blocks browser write requests, uses no response mocks, and verifies source/Hub identity before and after the UI checks. It requires the exact published checkout with clean application source files. A failed live browser check fails the publication workflow even when uploading has succeeded.

The separate access verifier checks source identity before and after five credential-free denial probes: custody/receipt reads and empty invalid requests to the three write routes. It requires hosted storage denial in `read-only` mode or authentication denial in `active` mode, and retains `write-guards.json`. Add `--mode active` to all three commands above for an activated store. Credential-free checks establish denial and public behavior; the separate live operator harness measures successful SAMPLE transactions and restart readback.

For a local Docker build from a clean checkout, create the same untracked ASCII source file explicitly before building:

```bash
python -c "import pathlib,subprocess; pathlib.Path('SOURCE_REVISION').write_bytes(subprocess.check_output(['git','rev-parse','HEAD']).strip()+b'\n')"
docker build -t szl-seismic-review .
```

The generated file is ignored by Git. A local build without a matching `SZL_SOURCE_REVISION` environment variable reports its source binding as **UNKNOWN**. Local development with `python -m uvicorn` does not require this file.

## Attribution and licenses

Project code and original UI are Apache-2.0 under [LICENSE](LICENSE). The derived panel and verdict CSVs in `data/` are attributed to Lingsen Meng, Hui Huang, Jinzhi Ma, and Yang Ma under the source deposition's **CC BY 4.0** terms; see [data/SOURCE_LICENSE.md](data/SOURCE_LICENSE.md) and the source manifest. The study is a preprint and its authors' performance figures are not SZL validation results.

Estate on Hugging Face: models, datasets and Spaces are published under the [SZLHOLDINGS](https://huggingface.co/SZLHOLDINGS) org.
