streetshots / workflow /SOURCE_EXPORT.md
loffenauer's picture
Embed JPEG previews in native Parquet for the hosted Dataset Viewer
310b05b verified
|
Raw History Blame Contribute Delete
13.8 kB
# Monthly PostgreSQL and Panoramax export
`source_export.py` is a one-shot, read-only exporter. It neither uploads to HF
nor starts training, schedules jobs, changes retention or writes source data.
Its output is a staging copy of `data/YYYY-MM/` for the private
`loffenauer/streetshots` dataset.
## Dependencies
Python 3.11+, `psycopg[binary]` 3.x for `snapshot`, Pillow for `materialize`.
Local tests used Python 3.12, psycopg 3.3.9 and Pillow 12.3.0. The source-host
metadata snapshot completed on Python 3.14.4 with the same database/image package versions.
`requirements-source-export.txt` pins the supported HF CLI stack as well; the
installed source-host dependency lock is in `validation/volz-db-python-lock.txt`.
No application repository import is required. Capture dependency versions in
the monthly publication receipt when running the exporter.
## Freeze metadata
Use the existing `youspeed_report` credential (private file mode 0600) and
read-only access to the existing PostgreSQL schema. Credentials must not be
placed in HF or command-line connection strings.
```sh
python source_export.py snapshot \
--output-root /staging/streetshots \
--month 2026-11 \
--database-file /run/secrets/database-report.txt \
--mapping-file /readonly/panoramax-reverse-v1.json
```
`--db-host` and `--db-port` can select an existing SSH tunnel. For execution
on the source host, `--database-stdin` accepts the existing report DSN through
SSH standard input and never writes the credential to disk. It is mutually
exclusive with `--database-file`. The exporter
asserts database user `youspeed_report`, a `REPEATABLE READ` transaction and
read-only mode. It preserves all historical capture dates: the month is the
export month, not a filter on recording dates.
The adapter reads the existing imported dataset objects and memberships,
phone media and corresponding sightings/reviews, current Panoramax crops,
source annotations, labels, suppressions and full picture metadata. It keeps
one record per logical source sample. Duplicate upstream train/validation
memberships are preserved on a single image record. An inactive or withdrawn
record retains metadata but its pixels are not copied.
Metadata is frozen in `source-plan.jsonl`, with its hash in
`source-snapshot.json`. `source-controls.json` independently snapshots
tombstones and current metadata/crop-storage authorizations. This is required
because a revoked phone record may already have been deleted from the live
media table: the model resolver applies the latest controls to every selected
historical month, preventing resurrection through an older snapshot. These contain source object keys and source provenance,
not credentials. The database transaction closes before media copying. A
snapshot cannot overwrite an existing source plan; use a new staging folder
for a new source cutoff. Publishing a second revision for the same month is a
separate, explicit operation.
## Copy and verify actual image bytes
Prefer read-only media mounts on the source server, using a dedicated writable
staging directory. `--dataset-root` and `--panoramax-root` normally refer to the
same permanent corpus root: their keys begin with `datasets/objects/` and
`panoramax/crop-objects/`. `--mobile-root` is the management-media root.
`--frame-root` is the Panoramax processed HD media root.
```sh
python source_export.py materialize \
--output-root /staging/streetshots --month 2026-11 \
--dataset-root /readonly/corpus \
--panoramax-root /readonly/corpus \
--mobile-root /readonly/management-media \
--frame-root /readonly/panoramax-hd \
--workers 4
```
Optional existing private image bridges can replace mobile/Panoramax crop
mounts: `--mobile-proxy http://127.0.0.1:18080` and
`--panoramax-proxy http://127.0.0.1:PORT`. These must be private loopback SSH
forwards. `--public-frames` permits public full-image retrieval for records
whose source visibility is `anyone`; it never retrieves owner-only frames
through a public endpoint. Owner-only frames require the authorized source
mount. Imported-dataset objects require their corpus mount or a separately
restored byte-identical corpus tree.
Every copied image is checked against the frozen source SHA-256, decoded
image dimensions and image-format validity. The copy uses a temporary file
and atomic rename. Retrying `materialize` reuses already verified files and
retries failed objects. It never changes the frozen source plan. Source
changes that produce different bytes are errors, not silent substitutions.
Some source picture rows have no existing asset hash. For these only,
`--bind-unhashed-frames` uses the mounted registered HD tree and the exact
existing UUID-to-path function from `panoramax_source.py`. It records the first
observed bytes, hash, dimensions and timestamp in an immutable
`source-bindings/` ledger. The original source plan remains unchanged; metadata
distinguishes its database cutoff from the later byte observation. A retry
must match the first binding. This option never downloads an unhashed public
URL or assumes that original EXIF dimensions describe the registered raster.
Detector sidecars use verified raster dimensions for geometry bounds, retain
the original metadata and bind the image hash.
`--reconstruct-panoramax` uses the unmodified existing
`panoramax_geometry.py` renderer on the verified archived parent image.
All frames finish before crop workers start. The resulting crop must match
the frozen original encoded PNG SHA-256 and geometry; it is never accepted
merely because it looks equivalent. Owner-only reconstruction requires an
authorized mounted frame source. Missing source frames remain explicit errors.
`restore_dataset_objects.py` can restore the imported native PNG corpus from
the retained original import package (preferred) or pinned upstream ZIPs using
the copied `native_dataset_image.py` function. The original JPEG, pixel and PNG
hashes are distinct checks. Identical Pillow versions on different builds do
not guarantee identical compressed PNG bytes; a mismatch is rejected. For the
initial export, all 19,709 exact stored PNGs were recovered from the retained
package rather than substituting re-encoded images:
```sh
python restore_dataset_objects.py \
--snapshot /home/raphael/streetshots-export/staging/data/2026-11 \
--support-root /home/raphael/streetshots-export/support \
--original-package /home/raphael/youspeed-hf-import-20261021/hf-de-import-20261020
```
The resulting `support/corpus` is supplied as `--dataset-root`. Support
archives and package copies live outside the HF dataset staging root.
Outputs include `metadata.jsonl`, same-stem detector annotation JSON files,
`errors.jsonl`, and `manifest.json`. The manifest is `partial` until every
admitted source image has been verified. A partial run exits 1. Missing expected images
remain explicitly pending and ineligible. Known source annotations whose state
is not ready (for example an image-level tag with missing crop geometry) are
retained as metadata-only pending records; they do not claim image availability
and are counted separately from failed transfers. Transfer completeness does not
mean annotation completeness or suitability for training.
While running, atomic `progress.json` updates report processed rows, verified
bytes and error counts; incomplete metadata/error streams use `.part` suffixes.
Final metadata and the manifest are written only after both phases finish.
## Labels and groups
- Imported HF memberships retain their original class, dataset revision,
path and checksum. Conflicting labels are preserved but ineligible.
- Phone classifications are model predictions unless an exact-byte-bound
crop review confirms/corrects them. Review evidence is kept.
- Panoramax classification-model qualifiers establish prediction origin.
Missing qualifiers are labelled `source_annotation`, never automatically
`manual`. An exact source national code is retained even when the current
model has no such output.
- Detector JSON retains original annotations and produces bounding boxes for
recognized sign / plate / face tags. Annotation completeness defaults to
false for all three classes. Empty source annotation arrays never imply
verified negative scenes. Review must establish complete-scene labels
before ordinary fully supervised detector training.
- Country/class folder names are reversibly URL-encoded; metadata always
retains the exact label. `_unknown` and `_unresolved` are storage names,
not training classes.
- Picture/session grouping is provisional. The shared model workflow requires
explicit reviewed group assignments before freezing splits; physical signs
seen across sources and repeated drives must be joined there.
## Operational scope and checks
No production scheduler is installed by this implementation. Run the one-shot
export from the existing monthly job runner once source mounts and staging
storage are available. Verify source retention before enabling it: the phone
media code defaults to 30 days, which is shorter than some calendar months.
Do not automatically extend that setting or resurrect withdrawn media.
The November 12 source-host check found the deployed 30-day default, no
retention override in the accessible configuration, and cleanup cron launches
every five minutes. Job completion and the live-eu intake process were not
inspected. The sanitized evidence is in
[`validation/volz-db-retention-check.json`](validation/volz-db-retention-check.json).
Calendar-month coverage therefore needs a confirmed retention or earlier
archival arrangement before a recurring schedule is enabled.
Full images can dominate storage. Size the destination before materializing;
the first source inventory contains approximately 35,000 Panoramax pictures.
The local Mac should be used for metadata and control, not a full-frame copy.
```sh
python -m unittest discover -s . -p tests_source_export.py -v
```
Tests cover path confinement, source membership preservation, label conflicts,
source-vs-manual label distinction, incomplete annotations, corrupt-media
rejection, withdrawn-media exclusion, and resumable verified copies.
They also cover strict reconstructed-crop identity, private-source gating,
first observed frame bindings and rejection of changed bytes on retry.
## Copied implementation provenance
`native_dataset_image.py` copies `sha` and `native_image` directly from
`Woladen.de-analytics/commercial_backend/youspeed/crop_datasets.py`; its header
records the source file SHA-256. `panoramax_geometry.py` is copied unchanged from
the same backend directory. `source_export.py` copies the semantic-json-v1
canonicalizer from `contracts.py` and the UUID path function from
`panoramax_source.py`. These are existing project implementations. See the
[repository license](../LICENSE) for CC BY-SA 4.0 coverage. Preserve applicable
source terms and file-specific notices. The data manifest retains available
upstream image licenses and attribution.
## Monthly JPEG viewer files
After verifying a local snapshot, build JPEG copies of its PNG crop collections:
```sh
python workflow/build_viewer_jpegs.py data/2026-10
python workflow/build_viewer_jpegs.py data/2026-11
```
The script writes one ZIP of JPEGs per viewer split into
`data/YYYY-MM/viewer-jpeg/`. The compressed `manifest.jsonl.gz` records source
paths, archive members, checksums, encoding and dimensions. Verify its output
counts and source checksums against the complete snapshot metadata.
Use the optional `datasets` and `pyarrow` packages to embed the verified JPEGs
in the Parquet files used by the hosted viewer:
```sh
python workflow/embed_viewer_jpegs.py data/2026-11/viewer-jpeg/classifier.zip
python workflow/embed_viewer_jpegs.py data/2026-11/viewer-jpeg/context.zip
```
For already archived JPEGs, use an `Image` column containing pinned
`hf://datasets/loffenauer/streetshots@COMMIT/data/YYYY-MM/...` image paths.
Add the Parquet paths to the month's explicit viewer configuration. Training
and evaluation continue to use pinned archive bytes and source controls.
## Panoramax classifier crop policy (annotated-sign-1)
Panoramax source objects are context crops (`downward-1`): one sign height is
added below the annotation. Preserve their original PNG bytes under
`data/YYYY-MM/context/panoramax/<country>/<class>/panoramax-<id>.png`.
They are not classifier inputs. After verifying the source hash and annotation
geometry, `panoramax_classifier_crop.py` extracts exactly the annotated bounding
rectangle into the existing `classificator/` path, without resizing. Fractional
bounds use floor/ceil to include annotated pixels; seam wrapping and bottom-edge
context clipping retain their recorded geometry.
Metadata records tight image dimensions/hashes plus `source_context` (original
path, hash and geometry) and `derivation`. The class label and sample identity
stay unchanged. Missing or inconsistent geometry fails the export; never fall
back to using the context crop as classifier input. Context images are additional
provenance assets, not additional training samples. The manifest counts them
separately and archives the extraction implementation.
`correct_panoramax_crops.py` applies this policy to a previously complete monthly
snapshot, preserving its original metadata and manifest under
`provenance/crop-correction-v1/`. `publish_crop_correction.py` verifies every tight
image against its source context pixels, rejects unrelated record changes, and
inherits untouched files from a verified HF base commit with parent-commit checks.
It marks the snapshot partial during publication and commits the complete marker
only after all changed files pass remote hash verification. Earlier HF revisions
and the frozen original source plan remain available unchanged.