smartwilds_metadata / smartwilds /scripts /build_hf_release.py
jennamk14's picture
Add files using upload-large-folder tool
2a177e4 verified
Raw History Blame Contribute Delete
44.2 kB
#!/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:
<repo>/README.md dataset card (filled in separately)
<repo>/data/events.csv Darwin Core Event table
<repo>/data/occurrences.csv Darwin Core Occurrence table
<repo>/data/... modality-specific per-file tables
<repo>/metadata/ sensor settings, data dictionary, provenance
<repo>/scripts/ generator / georeferencing / this script
<repo>/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/<project>/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):
"""<archive>/<campaign>/<modality>/<rest> -> media/<campaign>/<rest>."""
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 <modality>/ 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": "<video>_<frame>_<k> from the SAM3 run",
"frame_index": "0-based native frame index in the video (SAM3 sampled every 15th frame)",
"bbox_x": "Box left, pixels, in the native frame", "bbox_y": "Box top, pixels", "bbox_w": "Box width, pixels",
"bbox_h": "Box height, pixels", "top1_score": "BioCLIP Tree-of-Life top-1 score",
"georef_status": "Ground-projection status (ok | invalid_altitude | missing_drone_gps | horizon_ray | out_of_range)",
}
def write_dictionary(d, repo):
out = [f"# {repo} data dictionary", "",
"Generated by `scripts/build_hf_release.py`. Darwin Core term definitions: "
"<https://dwc.tdwg.org/terms/>. Columns not listed in a Darwin Core namespace are "
"SmartWilds-specific.", ""]
for p in sorted(d.rglob("*.csv")):
rel = p.relative_to(d)
df = pd.read_csv(p, dtype=str, keep_default_na=False, nrows=1000)
n = sum(1 for _ in open(p)) - 1
out += [f"## `{rel}`", "", f"{n:,} rows.", "", "| Column | Description | Example |", "|---|---|---|"]
for c in df.columns:
ex = next((v for v in df[c] if v), "")
ex = (ex[:60] + "…") if len(ex) > 60 else ex
out.append(f"| `{c}` | {TERMS.get(c, '')} | {ex.replace('|', '/')} |")
out.append("")
atomic_write(d / "metadata/DATA_DICTIONARY.md", lambda t: t.write_text("\n".join(out) + "\n"))
def write_checksums(d):
lines = []
for p in sorted(d.rglob("*")):
if p.is_file() and p.name not in ("CHECKSUMS.sha256", "README.md") and "images" not in p.parts:
lines.append(f"{sha256(p)} {p.relative_to(d)}")
atomic_write(d / "CHECKSUMS.sha256", lambda t: t.write_text("\n".join(lines) + "\n"))
# --------------------------------------------------------------------------
# Camera traps
# --------------------------------------------------------------------------
def scrub_csv_copy(src, dst):
"""Copy a CSV, normalizing provenance tokens of the camera derivative."""
text = Path(src).read_text()
for a, b in ARRIVAL_TOKEN_REWRITES:
text = text.replace(a, b)
Path(dst).write_text(text)
ARRIVAL_TOKEN_REWRITES = [
("_arrival_icde_camera_", "_arrival_camera_"),
("one retained ICDE SAM3-geometry camera Occurrence", "one retained original-SAM3-geometry camera Occurrence"),
("icde_sam3_geometry_only_derivative_20261108", "camera_release_20261108"),
]
def camera_deployments(tables, images):
"""Per-deployment table: sensor configuration joined to the geolocation
config and the number of processed images on disk."""
c1 = tables["Camera Trap Configurations / Campaign 1: June 30 – July 3, 2025"].assign(campaign="thewilds_20250630_20250703")
c2 = tables["Camera Trap Configurations / Campaign 2: August 4 – August 28, 2025"].assign(campaign="thewilds_20250804_20250828")
dep = pd.concat([t for t in (c1, c2) if "Camera" in t.columns], ignore_index=True)
dep.insert(0, "deploymentID", dep.Site.str.extract(r"^(TW\d+)")[0] + "-" + dep.Camera)
geo = read(SNAP / "scripts/georeferencing/camera_geolocation_config.csv")
geo["camera_id"] = geo.camera_id.str.replace("_", "-") # raw dir is TW09_CT02
dep = dep.merge(geo[["collection", "camera_id", "path_contains", "camera_lat", "camera_lon", "hfov_deg", "bearing_deg",
"image_rotation_deg", "target_height_m", "config_source", "notes"]].rename(
columns={"notes": "geolocation_notes"}),
left_on=["campaign", "deploymentID"], right_on=["collection", "camera_id"], how="left"
).drop(columns=["collection", "camera_id"]).fillna({"path_contains": ""})
dep["images_on_disk"] = dep.apply(lambda r: int(((images.dataset == r.campaign) &
(images.camera_id.str.replace("_", "-") == r.deploymentID)
& (images.release_path.str.contains(r.path_contains, regex=False)
if r.path_contains else True)).sum()), axis=1)
# A path-specific override (TW09-CT02 SD23, after the Aug 18 move) takes its
# images away from the deployment's default row.
for (camp, did), g in dep.groupby(["campaign", "deploymentID"]):
if len(g) > 1:
default = g.index[g.path_contains == ""]
dep.loc[default, "images_on_disk"] -= g.loc[g.path_contains != "", "images_on_disk"].sum()
dep["released"] = (dep.deploymentID != "TW07-CT05").map({True: "true", False: "false"})
return dep
def build_camera(out, tables):
"""Camera tables come from the validated post-triage derivative: the final
Event, Occurrence, image-inventory, media-manifest, taxonomy,
annotation-provenance, and arrival-analysis products."""
src = CAMERA_SOURCE / "smartwilds-camera-traps"
ev = read(src / "data/events.csv")
oc = read(src / "data/occurrences.csv")
images = read(src / "data/images.csv")
if len(ev) != 19785 or len(oc) != 72775 or len(images) != 235778:
raise RuntimeError("validated camera source count mismatch")
if set(oc.geometryProvenance) != {"SAM3"}:
raise RuntimeError("validated camera source contains non-SAM3 geometry")
if "behavior" in oc.columns or oc.astype(str).apply(
lambda col: col.str.contains(r"water|shore|aquatic", case=False, regex=True).any()).any():
raise RuntimeError("validated camera source retains water-association data")
if oc.associatedMedia.str.startswith("/").any():
raise RuntimeError("validated camera source contains absolute media paths")
scrubbed = out / REPOS["camera_traps"]
for name in ("camera_image_acquisition_arrivals.csv", "camera_operational_occurrence_arrivals.csv"):
atomic_write(scrubbed / "analysis" / name, lambda t, n=name: scrub_csv_copy(src / "analysis" / n, t))
atomic_write(scrubbed / "metadata/provenance/ANNOTATION_PROVENANCE.md",
lambda t: scrub_text_copy(src / "metadata/provenance/ANNOTATION_PROVENANCE.md", t,
extra=[("# ICDE camera-trap annotation provenance", "# Camera-trap annotation provenance")]))
files = {
"data/events.csv": src / "data/events.csv",
"data/occurrences.csv": src / "data/occurrences.csv",
"data/images.csv": src / "data/images.csv",
"media_manifest.csv": src / "media_manifest.csv",
"analysis/camera_arrival_statistics.json": src / "analysis/camera_arrival_statistics.json",
"metadata/DATA_DICTIONARY.md": src / "metadata/DATA_DICTIONARY.md",
"metadata/taxonomy_mapping.csv": src / "metadata/taxonomy_mapping.csv",
"metadata/deployments.csv": camera_deployments(tables, images),
"metadata/camera_models.csv": tables["Camera Trap Configurations / Camera Models"],
"metadata/camera_geolocation_config.csv": SNAP / "scripts/georeferencing/camera_geolocation_config.csv",
"metadata/timestamp_summary_by_camera.csv": TS_MAP / "camera_timestamp_summary_by_camera.csv",
"metadata/timestamp_summary_by_date.csv": TS_MAP / "camera_timestamp_summary_by_date.csv",
"metadata/provenance/tw07_ct05_sensitive_media_disposition_20261008.json":
SNAP / "tw07_ct05_sensitive_media_disposition_20261008.json",
"scripts/geolocate_camera_trap_treeoflife_predictions.py":
PUBLIC_SCRIPTS / "georeferencing/geolocate_camera_trap_treeoflife_predictions.py",
"scripts/generate_darwin_core.py": PUBLIC_SCRIPTS / "darwin_core/generate_darwin_core.py",
}
return files, {
"events": len(ev), "occurrences": len(oc), "images_total": len(images),
"all_geometry_provenance_is_SAM3": True,
"absolute_media_paths": 0,
"water_association_attributes_absent": True,
"pass": True,
}
# --------------------------------------------------------------------------
# Bioacoustics
# --------------------------------------------------------------------------
def build_bioacoustics(out, tables):
ev = read(SNAP / "bioacoustics_complete/darwin_core_events_bioacoustics_complete.csv")
oc = read(SNAP / "bioacoustics_complete/darwin_core_occurrences_bioacoustics_complete.csv")
rec = read(SNAP / "bioacoustics_complete/RAW_WAV_RECONCILIATION_20261008.csv")
rec.insert(0, "release_path", rec.raw_wav_path.map(lambda p: rel_media(PROJECT_PREFIX + p)))
included = rec.release_disposition.str.startswith("included")
path_by_event = rec[included].set_index("darwin_core_eventID").release_path
# associatedMedia is a bare WAV filename; resolve it through the Event.
oc["associatedMedia"] = oc.eventID.map(path_by_event).fillna(oc.associatedMedia)
ev["associatedMedia"] = ev.eventID.map(path_by_event).fillna("")
disposition = dict(zip(rec.release_path, rec.release_disposition))
def excl(rel):
d = disposition.get(rel)
return None if d is None or d.startswith("included") else d.split(";")[0] + ":" + rec.loc[
rec.release_path == rel, "reconciliation_status"].iloc[0]
manifest = media_inventory("bioacoustics", excl)
t = {k: v for k, v in tables.items() if k.startswith("Bioacoustic Recorder Configurations / Campaign")}
dep = pd.concat([v.assign(campaign=("thewilds_20250630_20250703" if "June" in k else "thewilds_20250804_20250828"))
for k, v in t.items()], ignore_index=True)
dep.insert(0, "deploymentID", dep.Site.str.extract(r"^(TW\d+)")[0] + "-" + dep.Recorder)
dep.insert(1, "model", "Wildlife Acoustics Song Meter Micro 2")
counts = rec.groupby(["source_campaign_directory", "deploymentID"]).release_disposition.agg(
wav_paths="size", wav_released=lambda s: s.str.startswith("included").sum()).reset_index()
counts["campaign"] = counts.source_campaign_directory.map(
{"campaign1": "thewilds_20250630_20250703", "campaign2": "thewilds_20250804_20250828"})
dep = dep.merge(counts.drop(columns="source_campaign_directory"), on=["campaign", "deploymentID"], how="left")
birdnet = pd.DataFrame([{"software": "BirdNET Analyzer", "version": "2.4", "segment_length_s": 3.0,
"sample_rate_hz": 48000, "bandpass_hz": "0-15000",
"occurrence_unit": "one row per recording x species; individualCount = detections"}])
ev, oc = strip_cluster_paths(ev), strip_cluster_paths(oc)
res = check_tables("bioacoustics", ev, oc, manifest, extra_event_ids={"TheWilds_2025"})
files = {
"data/events.csv": ev, "data/occurrences.csv": oc, "data/recordings.csv": rec,
"media_manifest.csv": manifest,
"metadata/deployments.csv": dep, "metadata/birdnet_settings.csv": birdnet,
"metadata/provenance/RAW_WAV_RECONCILIATION_20261008.md":
SNAP / "bioacoustics_complete/RAW_WAV_RECONCILIATION_20261008.md",
"metadata/provenance/bioacoustic_event_repair_20261008.json": SNAP / "bioacoustic_event_repair_20261008.json",
"scripts/reconcile_bioacoustic_raw_wavs.py": PUBLIC_SCRIPTS / "darwin_core/reconcile_bioacoustic_raw_wavs.py",
}
return files, res
# --------------------------------------------------------------------------
# Drones
# --------------------------------------------------------------------------
def build_drones(out, tables):
ev = read(SNAP / "drones/darwin_core_events_drones.csv")
oc = read(SNAP / "drones/darwin_core_occurrences_drones.csv")
manifest = media_inventory("drones")
videos = manifest[manifest.release_path.str.lower().str.endswith((".mp4", ".mov"))]
by_stem = {}
for p in videos.release_path:
flight_dir = p.split("/")[2]
by_stem.setdefault((flight_dir, Path(p).stem), []).append(p)
# Defect 21: the manual starling supplement was appended twice. Drop exact
# duplicate rows so every occurrenceID is unique.
before = len(oc)
oc = oc.drop_duplicates().reset_index(drop=True)
rep = {"exact_duplicate_rows_dropped": before - len(oc),
"duplicate_occurrenceIDs_remaining": int(oc.occurrenceID.duplicated().sum())}
# Frame images (purged scratch frames, or frames exported to an external
# annotation workspace) are not shipped; fall back to the retained video.
frame_re = re.compile(r"/drones/([^/]+)/.*?/([^/]+)_frames/[^/]+$")
def video_for(frame):
m = frame_re.search(frame)
if not m:
return None
hits = by_stem.get((m.group(1), m.group(2)), [])
return hits[0] if len(hits) == 1 else None
frames = oc.associatedMedia.str.startswith("/") & oc.associatedMedia.map(lambda p: rel_media(p) is None)
fallback = oc.loc[frames, "associatedMedia"].map(video_for)
rep.update({"frame_rows": int(frames.sum()),
"frame_rows_unique": int(oc.loc[frames, "associatedMedia"].nunique()),
"frame_rows_unmapped": int(fallback.isna().sum())})
ok = fallback.dropna().index
oc.loc[ok, "associatedMedia"] = fallback[ok]
oc.loc[ok, "occurrenceRemarks"] = oc.loc[ok, "occurrenceRemarks"] + \
"; associated_media_source=original_video_fallback_frame_not_distributed"
oc["associatedMedia"] = oc.associatedMedia.map(lambda p: rel_media(p) or p)
# Defect 15: the 2025-08-11 flights had a date but no time of day. The
# times come from the video container creation times, with each
# airframe's clock convention settled against reference flights and the
# field log (release/scripts/recover_drone_times.py writes the record).
rec = json.loads((CARDS / "provenance/drone_time_recovery_20250811.json").read_text())
vids = {v["eventID"]: v for v in rec["videos"]}
def hms(start, sec):
from datetime import datetime, timedelta
return (datetime.strptime(start, "%H:%M:%S") + timedelta(seconds=float(sec))).strftime("%H:%M:%S")
note_ev = ("eventTime recovered from the video container creation time "
"(release build 2026-11-10; metadata/provenance/drone_time_recovery_20250811.json)")
for eid, v in vids.items():
sel = ev.eventID == eid
ev.loc[sel, "eventTime"] = f"{v['local_start']}/{v['local_end']}"
ev.loc[sel, "fieldNotes"] = ev.loc[sel, "fieldNotes"].str.replace("intra-day timestamp unavailable", note_ev, regex=False)
for fid in sorted({v["flight_eventID"] for v in vids.values()}):
span = [v for v in vids.values() if v["flight_eventID"] == fid]
sel = ev.eventID == fid
ev.loc[sel, "eventTime"] = f"{min(x['local_start'] for x in span)}/{max(x['local_end'] for x in span)}"
ev.loc[sel, "fieldNotes"] = ev.loc[sel, "fieldNotes"].str.replace("intra-day timestamp unavailable", note_ev, regex=False)
frame = pd.to_numeric(oc.occurrenceRemarks.str.extract(r"detection_id=[^;]*_(\d{6})_\d+")[0], errors="coerce")
rep["aug11_occurrences_timed"] = 0
for eid, v in vids.items():
sel = (oc.eventID == eid) & (oc.eventTime == "")
fr = frame[sel]
times = fr.map(lambda f, v=v: hms(v["local_start"], f / v["fps"]) if pd.notna(f) else f"{v['local_start']}/{v['local_end']}")
oc.loc[sel, "eventTime"] = times.values
how = "verified on a reference flight" if v["clock_convention"] == "UTC" else "inferred from the field schedule"
oc.loc[sel, "occurrenceRemarks"] = oc.loc[sel, "occurrenceRemarks"].str.replace(
"intra-day timestamp unavailable",
f"eventTime recovered: video container creation time + frame_index/fps; clock convention {v['clock_convention']}, {how}; "
"see metadata/provenance/drone_time_recovery_20250811.json", regex=False)
rep["aug11_occurrences_timed"] += int(sel.sum())
# Per-detection table for frame extraction from the released raw videos.
# detection_id = <video>_<frame:06d>_<k>; frame is the native frame index
# (frames were sampled every 15th frame for SAM3).
det = pd.DataFrame({
"occurrenceID": oc.occurrenceID, "eventID": oc.eventID, "video_path": oc.associatedMedia,
"detection_id": oc.occurrenceRemarks.str.extract(r"detection_id=([^;]+)")[0]})
det["frame_index"] = det.detection_id.str.extract(r"_(\d{6})_\d+$")[0].astype("Int64")
bbox = oc.identificationRemarks.str.extract(r"bbox xywh\(px\): \[([^\]]+)\]")[0].str.split(",", expand=True)
for i, c in enumerate(["bbox_x", "bbox_y", "bbox_w", "bbox_h"]):
det[c] = pd.to_numeric(bbox[i]).round(2)
det["scientificName"], det["vernacularName"] = oc.scientificName, oc.vernacularName
det["top1_score"] = pd.to_numeric(oc.identificationRemarks.str.extract(r"top1 score: ([0-9.eE-]+)")[0])
det["georef_status"] = oc.occurrenceRemarks.str.extract(r"drone_georef_status=([^;]+)")[0]
det = det[det.detection_id.notna()] # the 644 curated review records carry no frame id
rep["detections_with_frame_index"] = int(det.frame_index.notna().sum())
# Remaining frame PNGs that exist on disk are derived products, not raw media.
flights = ev[ev.eventType == "SensorDeployment"][["eventID", "eventDate", "locationID", "fieldNotes"]].copy()
flights["platform"] = flights.locationID.map(
lambda s: "DJI Air 2" if "djiair" in s else "DJI (unspecified airframe)" if "DJI" in s else "Parrot Anafi 4K")
media_events = ev[ev.eventType == "MediaEvent"]
flights["videos"] = flights.eventID.map(media_events.parentEventID.value_counts()).fillna(0).astype(int)
flights["occurrences"] = flights.eventID.map(
oc.eventID.map(media_events.set_index("eventID").parentEventID).value_counts()).fillna(0).astype(int)
ev, oc = strip_cluster_paths(ev), strip_cluster_paths(oc)
res = check_tables("drones", ev, oc, manifest, extra_event_ids={"TheWilds_2025"})
res.update(rep)
res["pass"] = res["pass"] and rep["duplicate_occurrenceIDs_remaining"] == 0
files = {
"data/events.csv": ev, "data/occurrences.csv": oc, "data/detections.csv": det,
"media_manifest.csv": manifest,
"analysis/bird_water_association_per_box.csv": strip_cluster_paths(read(BIRD_WATER)),
"metadata/flights.csv": flights, "metadata/platforms.csv": tables["Drone Configurations"],
"metadata/drone_projection_config.csv": SNAP / "scripts/georeferencing/drone_projection_config.csv",
"metadata/provenance/invalid_drone_date_repair_20261008.json": SNAP / "invalid_drone_date_repair_20261008.json",
"metadata/provenance/invalid_drone_coordinate_repair_20261009.json":
SNAP / "invalid_drone_coordinate_repair_20261009.json",
"metadata/provenance/drone_missing_media_repair_20261010.json": SNAP / "drone_missing_media_repair_20261010.json",
"metadata/provenance/excluded_drone_media_event_repair_20261008.json":
SNAP / "excluded_drone_media_event_repair_20261008.json",
"metadata/provenance/drone_time_recovery_20250811.json": CARDS / "provenance/drone_time_recovery_20250811.json",
"scripts/geolocate_drone_treeoflife_predictions.py":
PUBLIC_SCRIPTS / "georeferencing/geolocate_drone_treeoflife_predictions.py",
"scripts/generate_darwin_core.py": PUBLIC_SCRIPTS / "darwin_core/generate_darwin_core.py",
}
return files, res
# --------------------------------------------------------------------------
# Citizen science and umbrella (need files that are currently owner-only)
# --------------------------------------------------------------------------
def build_citizen_science(out, tables):
evp = SNAP / "citizen_science/darwin_core_events_citizen_science.csv"
ocp = SNAP / "citizen_science/darwin_core_occurrences_citizen_science.csv"
if not (readable(evp) and readable(ocp)):
raise PermissionError(f"unreadable: {evp.name}, {ocp.name} (owner-only permissions)")
ev, oc = read(evp), read(ocp)
oc["associatedMedia"] = oc.associatedMedia.map(lambda p: rel_media(p) or p)
# The Sep 8 Google Photos album export is not in the project archive, so its
# 50 photos cannot be distributed: keep the Occurrences, clear the link, say why.
album = oc.associatedMedia.str.startswith("Google Photos Takeout/")
oc.loc[album, "occurrenceRemarks"] = oc.loc[album, "occurrenceRemarks"] + \
"; media_not_distributed=Google Photos album export not retained in project archive (was " + \
oc.loc[album, "associatedMedia"] + ")"
oc.loc[album, "associatedMedia"] = ""
manifest = media_inventory("citizen_science")
ev, oc = strip_cluster_paths(ev), strip_cluster_paths(oc)
res = check_tables("citizen_science", ev, oc, manifest, extra_event_ids={"TheWilds_2025"})
res["occurrences_media_not_distributed"] = int(album.sum())
return {"data/events.csv": ev, "data/occurrences.csv": oc, "media_manifest.csv": manifest,
"metadata/provenance/citizen_science_media_reconciliation_20261008.json":
SNAP / "citizen_science_media_reconciliation_20261008.json"}, res
def build_core(out, tables):
"""Study-level dataset: validated merged tables, text records, sensor
configurations, supplement, defect inventory, and the arrival traces."""
src = CAMERA_SOURCE / "smartwilds/data"
ev = read(src / "events_all_modalities.csv")
oc = read(src / "occurrences_all_modalities.csv")
if len(ev) != 22242 or len(oc) != 401602 or oc.occurrenceID.duplicated().any():
raise RuntimeError("validated merged-table integrity check failed")
# The merged table carries the drone and citizen-science rows with their
# archive media paths. Take the release-relative values from the staged
# modality tables (same occurrenceID), then rewrite anything left over.
rep = {}
occurrence_times = None # occurrenceID -> eventTime of the staged drone table (defect-15 recovery)
for repo in ("smartwilds-drones", "smartwilds-citizen-science"):
p = out / repo / "data/occurrences.csv"
if not p.exists():
rep[f"{repo}_not_staged"] = True
continue
m = read(p).drop_duplicates("occurrenceID").set_index("occurrenceID")
if repo == "smartwilds-drones":
occurrence_times = m.eventTime
idx = oc.occurrenceID.isin(m.index)
for c in ("associatedMedia", "occurrenceRemarks", "associatedReferences"):
if c in m.columns and c in oc.columns:
oc.loc[idx, c] = oc.loc[idx, "occurrenceID"].map(m[c]).values
rep[f"{repo}_rows_aligned"] = int(idx.sum())
oc["associatedMedia"] = oc.associatedMedia.map(lambda p: rel_media(p) or p)
ev, oc = strip_cluster_paths(ev), strip_cluster_paths(oc)
res = {"events": len(ev), "occurrences": len(oc),
"absolute_media_paths": int(oc.associatedMedia.str.startswith("/").sum()),
"cells_with_cluster_paths": count_cluster_paths(ev) + count_cluster_paths(oc)}
res.update(rep)
res["pass"] = res["absolute_media_paths"] == 0 and res["cells_with_cluster_paths"] == 0
files = {
"data/events_all_modalities.csv": ev,
"data/occurrences_all_modalities.csv": oc,
"data/text_events.csv": SNAP / "text_data/darwin_core_events_text.csv",
"data/text_occurrences.csv": SNAP / "text_data/darwin_core_occurrences_text.csv",
"data/site_selection_rationale.csv": SNAP / "text_data/site_selection_rationale.csv",
"metadata/sensor_configurations.md": SENSOR_MD,
"SUPPLEMENTAL.md": CARDS / "SUPPLEMENTAL.md",
"metadata/DEFECT_INVENTORY.md": CARDS / "DEFECT_INVENTORY.md",
"metadata/defect_inventory.csv": CARDS / "defect_inventory.csv",
"scripts/refresh_camera_arrival_metadata.py": ROOT / "release/scripts/refresh_camera_arrival_metadata.py",
"scripts/generate_arrival_traces_v2.py": PUBLIC_SCRIPTS / "arrival_traces/generate_arrival_traces_v2.py",
}
# Non-camera arrival traces come from the integration pass; the camera
# streams are refreshed afterwards from the validated derivative. The two
# notes about the first-generation camera trace no longer apply.
atomic_write(out / REPOS["core"] / "metadata/provenance/DARWIN_CORE_AUDIT_20261010_FINAL.json",
lambda t: scrub_text_copy(SNAP / "DARWIN_CORE_AUDIT_20261010_FINAL.json", t))
skip = {"DEPRECATED_LEGACY_PRIMITIVES.md", "UNAVAILABLE_CAMERA_IMAGE_CAPTURE_ACQUISITION.md"}
drone_media = None
for p in sorted((SNAP / "analysis/arrival_traces_v2").iterdir()):
if p.name in skip or p.name.startswith("camera_"):
continue
if p.suffix == ".csv":
tr = read(p)
if tr.associatedMedia.str.startswith("/").any():
if drone_media is None:
drone_media = oc.drop_duplicates("occurrenceID").set_index("occurrenceID").associatedMedia
by_source = tr.sourceID.map(drone_media)
tr["associatedMedia"] = by_source.where(by_source.notna(), tr.associatedMedia.map(lambda x: rel_media(x) or x))
if occurrence_times is not None and "timeEligible" in tr.columns and (tr.timeEligible == "false").any():
need = tr.timeEligible == "false"
t = tr.loc[need, "sourceID"].map(occurrence_times)
ok = t.notna() & t.str.match(r"^\d{2}:\d{2}:\d{2}$")
idx = t[ok].index
tr.loc[idx, "eventTime"] = t[ok].values
tr.loc[idx, "timestamp"] = tr.loc[idx, "eventDate"] + "T" + t[ok].values
tr.loc[idx, "timestampPrecision"] = "second"
tr.loc[idx, "timeEligible"] = "true"
res[f"arrival_trace_times_recovered:{p.name}"] = int(ok.sum())
tr = strip_cluster_paths(tr)
if "sourceSnapshot" in tr.columns:
tr["sourceSnapshot"] = tr.sourceSnapshot.str.replace(SNAP.name, "integration_pass_20261022", regex=False)
res[f"arrival_trace_cluster_paths:{p.name}"] = count_cluster_paths(tr)
res["pass"] = res["pass"] and res[f"arrival_trace_cluster_paths:{p.name}"] == 0
files[f"analysis/arrival_traces_v2/{p.name}"] = tr
else:
files[f"analysis/arrival_traces_v2/{p.name}"] = p
return files, res
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default=str(RELEASE_DIR))
ap.add_argument("--only", nargs="*", choices=list(REPOS))
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
tables = parse_md_tables(SENSOR_MD)
audit["built_utc"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
builders = {"camera_traps": build_camera, "bioacoustics": build_bioacoustics, "drones": build_drones,
"citizen_science": build_citizen_science, "core": build_core}
for key, fn in builders.items():
if args.only and key not in args.only:
continue
repo = REPOS[key]
print(f"[{repo}] building ...", flush=True)
for rel in STALE:
(out / repo / rel).unlink(missing_ok=True)
card = CARDS / f"{repo}.md"
if card.exists():
atomic_write(out / repo / "README.md", lambda t: shutil.copyfile(card, t))
imgs = CARDS / "images" / repo
if imgs.is_dir():
# Release-card images are static assets. Avoid rewriting existing
# owner-managed media assets during an in-place table rebuild.
target_images = out / repo / "images" / repo
if not target_images.exists():
shutil.copytree(imgs, target_images)
try:
files, res = fn(out, tables)
except PermissionError as e:
audit["blocked"].append({"repo": repo, "reason": str(e)})
print(f"[{repo}] BLOCKED: {e}", flush=True)
continue
files[f"scripts/{Path(__file__).name}"] = Path(__file__)
d = write_repo(out, repo, files)
if key != "camera_traps":
write_dictionary(d, repo)
write_checksums(d)
audit["repos"][repo] = res
print(f"[{repo}] {json.dumps({k: v for k, v in res.items() if not isinstance(v, (list, dict))})}",
flush=True)
# The camera arrival streams in the study-level dataset come from the
# validated camera derivative; refresh them once both parts are staged.
requested = set(args.only or REPOS)
if {"camera_traps", "core"}.issubset(requested):
subprocess.run([sys.executable, str(ROOT / "release/scripts/refresh_camera_arrival_metadata.py"),
"--release", str(out), "--snapshot", str(SNAP), "--source", str(CAMERA_SOURCE)], check=True)
write_dictionary(out / REPOS["core"], REPOS["core"])
write_checksums(out / REPOS["core"])
(out / "build_hf_release.py").unlink(missing_ok=True) # stray copy from an earlier build
(out / "RELEASE_BUILD_AUDIT.json").write_text(json.dumps(audit, indent=2, default=str) + "\n")
return 0 if not audit["errors"] else 1
if __name__ == "__main__":
sys.exit(main())