#!/usr/bin/env python3 """Stage the SmartWilds per-modality Hugging Face dataset directories. One directory per modality (camera traps, bioacoustics, drones, citizen science) plus the umbrella ``smartwilds`` dataset, each laid out like imageomics/kabr-behavior-telemetry: /README.md dataset card (filled in separately) /data/events.csv Darwin Core Event table /data/occurrences.csv Darwin Core Occurrence table /data/... modality-specific per-file tables /metadata/ sensor settings, data dictionary, provenance /scripts/ generator / georeferencing / this script /media_manifest.csv one row per raw file: release path, bytes, include flag, exclusion reason Inputs are the frozen Darwin Core tables of the integration pass (``SMARTWILDS_DWC_SNAPSHOT``) and the validated post-triage camera derivative (``SMARTWILDS_CAMERA_SOURCE``). Neither is modified. The staged copies get one release repair, audited in ``RELEASE_BUILD_AUDIT.json``: ``associatedMedia`` is rewritten from absolute archive paths to release-relative ``media/...`` paths, and drone frames in the purged scratch workspace fall back to their retained original video. Media files are NOT copied here. ``media_manifest.csv`` is the packaging input. Locations are read from environment variables, all optional: SMARTWILDS_ARCHIVE field archive root (default: this repository) SMARTWILDS_DWC_SNAPSHOT frozen Darwin Core tables SMARTWILDS_CAMERA_SOURCE validated camera derivative SMARTWILDS_RELEASE output directory (also ``--out``) SMARTWILDS_PUBLIC_SCRIPTS the public scripts shipped inside each dataset SMARTWILDS_SCRATCH_PREFIX prefix of purged scratch frame paths in the tables SMARTWILDS_DETECTIONS prefix of the external detection workspace Usage: python release/scripts/build_hf_release.py [--out DIR] [--only REPO ...] """ import argparse import hashlib import json import os import re import shutil import subprocess import sys from datetime import datetime, timezone from pathlib import Path import pandas as pd def env_path(name, default): return Path(os.environ.get(name, default)).resolve() ROOT = env_path("SMARTWILDS_ARCHIVE", Path(__file__).resolve().parents[2]) SNAP = env_path("SMARTWILDS_DWC_SNAPSHOT", ROOT / "processing_output/darwin_core_latest_20261008") CAMERA_SOURCE = env_path("SMARTWILDS_CAMERA_SOURCE", ROOT / "archive/camera_traps_validated_20261108") RELEASE_DIR = env_path("SMARTWILDS_RELEASE", ROOT / "release/hf_smartwilds_20261022") PUBLIC_SCRIPTS = env_path("SMARTWILDS_PUBLIC_SCRIPTS", ROOT / "public/smartwilds/scripts") TS_MAP = ROOT / "processing_output/detections/drone_camera_analysis/camera_time_mapping" SENSOR_MD = ROOT / "documentation/sensor_configurations.md" CARDS = ROOT / "release/cards" CAMPAIGNS = ["thewilds_20250630_20250703", "thewilds_20250804_20250828", "thewilds_20250908_20250908"] PROJECT_PREFIX = str(ROOT) + "/" # Prefixes of absolute paths that may still appear inside the frozen tables. SCRATCH_PREFIX = os.environ.get("SMARTWILDS_SCRATCH_PREFIX", "") # purged drone frame workspace DETECTIONS_PREFIX = os.environ.get("SMARTWILDS_DETECTIONS", "") # external detection workspaces if DETECTIONS_PREFIX and not DETECTIONS_PREFIX.endswith("/"): DETECTIONS_PREFIX += "/" # Anything under the same filesystem roots as the known prefixes counts as an # archive path (e.g. "/fs/ess/" for "/fs/ess//TheWilds2025/"). CLUSTER_MARKERS = sorted({"/".join(m.split("/")[:3]) + "/" for m in (PROJECT_PREFIX, SCRATCH_PREFIX, DETECTIONS_PREFIX) if m and m.startswith("/")}) STUDY_START, STUDY_END = "2025-06-30", "2025-09-08" REPOS = { "camera_traps": "smartwilds-camera-traps", "bioacoustics": "smartwilds-bioacoustics", "drones": "smartwilds-drones", "citizen_science": "smartwilds-citizen-science", "core": "smartwilds", } audit = {"inputs": {"snapshot": str(SNAP), "camera_source": str(CAMERA_SOURCE)}, "built_utc": None, "repos": {}, "blocked": [], "errors": []} def read(path, **kw): return pd.read_csv(path, dtype=str, keep_default_na=False, **kw) def readable(path): return os.access(path, os.R_OK) def sha256(path, buf=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(buf), b""): h.update(chunk) return h.hexdigest() def rel_media(abs_path): """/// -> media//.""" if not abs_path.startswith(PROJECT_PREFIX): return None parts = abs_path[len(PROJECT_PREFIX):].split("/") if parts[0] not in CAMPAIGNS or len(parts) < 3: return None return "/".join(["media", parts[0]] + parts[2:]) BIRD_WATER = ROOT / "processing_output/detections/drone_camera_analysis/aquatic_bird_analysis/bird_water_association_per_box.csv" PATH_REWRITES = [(str(BIRD_WATER), "analysis/bird_water_association_per_box.csv")] if DETECTIONS_PREFIX: PATH_REWRITES.append((DETECTIONS_PREFIX, "external_detections/")) PATH_REWRITES.append((PROJECT_PREFIX, "TheWilds2025/")) def has_cluster_path(col): return any(col.str.contains(m, regex=False).any() for m in CLUSTER_MARKERS) def count_cluster_paths(df): return int(sum(df[c].str.contains(m, regex=False).sum() for c in df.columns for m in CLUSTER_MARKERS)) def strip_cluster_paths(df): """Rewrite remaining absolute archive paths in free-text columns to release-relative (shipped) or project-relative (provenance-only) forms.""" for c in df.columns: col = df[c] if has_cluster_path(col): for a, b in PATH_REWRITES: col = col.str.replace(a, b, regex=False) df[c] = col return df def scrub_text_copy(src, dst, extra=()): """Copy a text file (JSON, Markdown), rewriting archive paths and the provenance tokens of the camera derivative.""" text = Path(src).read_text() rewrites = list(PATH_REWRITES) + list(ARRIVAL_TOKEN_REWRITES) + [(SNAP.name, "integration_pass_20261022")] + list(extra) for a, b in rewrites: text = text.replace(a, b) Path(dst).write_text(text) # Files written by earlier builds that the current build no longer produces. STALE = ["scripts/generate_darwin_core_latest_20261008.py", "scripts/refresh_icde_camera_arrival_metadata.py", "analysis/arrival_traces_v2/DEPRECATED_LEGACY_PRIMITIVES.md", "analysis/arrival_traces_v2/UNAVAILABLE_CAMERA_IMAGE_CAPTURE_ACQUISITION.md", "analysis/bird_water_association_per_box.csv"] def atomic_write(path, writer): """Write through a temp file and rename, so files owned by another team member (and read-only to us) are replaced rather than opened for writing.""" path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_name(f".{path.name}.tmp") try: writer(temp) temp.replace(path) finally: temp.unlink(missing_ok=True) def parse_md_tables(md_path): """Return {"## section / ### heading": DataFrame} for every pipe table.""" tables, section, heading, rows = {}, "", None, [] for line in Path(md_path).read_text().splitlines() + [""]: if line.startswith("## "): section = heading = line[3:].strip() elif line.startswith("### "): heading = section + " / " + line[4:].strip() if line.startswith("|"): cells = [c.strip() for c in line.strip().strip("|").split("|")] if not all(re.fullmatch(r":?-+:?", c) for c in cells): rows.append(cells) elif rows: tables[heading] = pd.DataFrame(rows[1:], columns=rows[0]) rows = [] return tables def media_inventory(modality, exclude=lambda rel: None): """One row per raw file under every campaign's / directory.""" rows = [] for camp in CAMPAIGNS: base = ROOT / camp / modality if not base.is_dir(): continue for dirpath, _, files in os.walk(base): for fn in files: src = Path(dirpath) / fn rel = rel_media(str(src)) reason = exclude(rel) or "" try: size = src.stat().st_size except OSError: size, reason = "", reason or "unreadable_source" rows.append({"release_path": rel, "source_path": str(src.relative_to(ROOT)), "bytes": size, "include": "false" if reason else "true", "exclusion_reason": reason}) return pd.DataFrame(rows).sort_values("release_path").reset_index(drop=True) def check_tables(name, ev, oc, manifest, extra_event_ids=()): """Release checks the snapshot audit lacked: dates inside parent spans, sentinel strings, and every associatedMedia resolving to an included file.""" res = {} ids = set(ev.eventID) | set(extra_event_ids) res["events"], res["occurrences"] = len(ev), len(oc) res["dangling_parentEventID"] = sorted({p for p in ev.parentEventID if p and p not in ids}) res["occurrences_without_event"] = int((~oc.eventID.isin(ids)).sum()) sentinel = re.compile(r"^(nan|none|null|-1|1970-01-01)$", re.I) res["sentinel_cells"] = {f"{t}.{c}": int(df[c].str.match(sentinel).sum()) for t, df in (("events", ev), ("occurrences", oc)) for c in df.columns if df[c].str.match(sentinel).any()} span = ev.set_index("eventID").eventDate.str.split("/", expand=True) span.columns = ["a", "b"][: span.shape[1]] if "b" not in span: span["b"] = None span["b"] = span.b.fillna(span.a) single = oc[~oc.eventDate.str.contains("/")] j = single.join(span, on="eventID") res["occurrence_date_outside_event_span"] = int(((j.eventDate < j.a) | (j.eventDate > j.b)).sum()) res["occurrence_date_outside_study"] = int(((single.eventDate < STUDY_START) | (single.eventDate > STUDY_END)).sum()) res["occurrence_interval_dates"] = int(oc.eventDate.str.contains("/").sum()) media = oc.associatedMedia[oc.associatedMedia != ""] res["absolute_media_paths"] = int(media.str.startswith("/").sum()) res["cells_with_cluster_paths"] = count_cluster_paths(ev) + count_cluster_paths(oc) if manifest is not None: included = set(manifest.release_path[manifest.include == "true"]) unresolved = media[~media.isin(included)] res["media_paths_not_in_included_manifest"] = int(len(unresolved)) res["media_unresolved_examples"] = unresolved.drop_duplicates().head(5).tolist() res["pass"] = (not res["dangling_parentEventID"] and res["occurrences_without_event"] == 0 and not res["sentinel_cells"] and res["occurrence_date_outside_event_span"] == 0 and res["occurrence_date_outside_study"] == 0 and res["absolute_media_paths"] == 0 and res["cells_with_cluster_paths"] == 0 and res.get("media_paths_not_in_included_manifest", 0) == 0) return res def write_repo(out, repo, files): d = out / repo for rel, obj in files.items(): p = d / rel p.parent.mkdir(parents=True, exist_ok=True) if isinstance(obj, pd.DataFrame): atomic_write(p, lambda t: obj.to_csv(t, index=False)) elif isinstance(obj, (dict, list)): atomic_write(p, lambda t: t.write_text(json.dumps(obj, indent=2) + "\n")) elif isinstance(obj, Path) and obj.suffix in (".json", ".md"): atomic_write(p, lambda t: scrub_text_copy(obj, t)) # provenance records: no archive paths or snapshot names elif isinstance(obj, Path): atomic_write(p, lambda t: shutil.copyfile(obj, t)) else: atomic_write(p, lambda t: t.write_text(obj)) return d TERMS = { # Darwin Core / Humboldt terms (https://dwc.tdwg.org/terms/) "eventID": "Darwin Core: unique Event identifier", "parentEventID": "Darwin Core: eventID of the parent Event", "eventType": "Darwin Core: Project, SensorDeployment, AudioRecording, MediaEvent, or ObservationSession", "eventDate": "Darwin Core: ISO 8601 date or date interval (start/end)", "eventTime": "Darwin Core: local time (or interval); blank when not recoverable", "samplingProtocol": "Darwin Core: sensor, schedule, and processing chain", "sampleSizeValue": "Darwin Core: sample size", "sampleSizeUnit": "Darwin Core: unit of sampleSizeValue", "fieldNotes": "Darwin Core: provenance and field notes", "occurrenceID": "Darwin Core: unique Occurrence identifier", "catalogNumber": "Darwin Core: source record identifier", "scientificName": "Darwin Core: top-1 model or annotator taxon", "taxonRank": "Darwin Core: rank of scientificName", "vernacularName": "Darwin Core: common name", "kingdom": "Darwin Core: rank", "phylum": "Darwin Core: rank", "class": "Darwin Core: rank", "order": "Darwin Core: rank", "family": "Darwin Core: rank", "genus": "Darwin Core: rank", "specificEpithet": "Darwin Core: rank", "occurrenceStatus": "Darwin Core: present", "individualCount": "Darwin Core: 1 per visual crop; number of BirdNET detections for acoustic rows", "basisOfRecord": "Darwin Core: MachineObservation or HumanObservation", "recordedBy": "Darwin Core: device or team", "identifiedBy": "Darwin Core: model (and version) or annotator", "identificationVerificationStatus": "Darwin Core: verification status; the vocabulary differs by table (SUPPLEMENTAL.md S9.3)", "identificationRemarks": "Darwin Core: rank, top-1 score, bbox xywh (px), detector label", "decimalLatitude": "Darwin Core: WGS84; see dataGeneralizations for what the point represents", "decimalLongitude": "Darwin Core: WGS84", "coordinateUncertaintyInMeters": "Darwin Core: meters", "geodeticDatum": "Darwin Core: WGS84", "locality": "Darwin Core: named place", "locationID": "Darwin Core: site (TWxx) for fixed sensors; flight ID for drones", "occurrenceRemarks": "Darwin Core: projection status, timestamp method, repair notes (key=value; ...)", "associatedMedia": "Darwin Core: release-relative path to the source media file", "associatedReferences": "Darwin Core: release-relative supporting analysis file", "dataGeneralizations": "Darwin Core: what the coordinate represents", "informationWithheld": "Darwin Core", "datasetID": "Darwin Core: modality dataset identifier", "datasetName": "Darwin Core", "release_path": "Path of the file inside this dataset", "source_path": "Path in the project archive", "bytes": "File size", "include": "true if the file is distributed in media/", "exclusion_reason": "Why a file is not distributed", "has_human_detection": "true if any Occurrence on this image is labeled Homo sapiens", "occurrence_count": "Occurrences derived from this image", "video_path": "Release-relative path of the raw video", "detection_id": "