HotSight / scripts /filter_junk.py
hotsight's picture
Super-squash branch 'main' using huggingface_hub
4e6a175
Raw History Blame Contribute Delete
5.19 kB
#!/usr/bin/env python3
"""Remove junk RGB/IR frame pairs from sampled datasets in-place.
The intervals come from ``markdown/junk.md`` and refer to RGB timestamps.
Each dataset root must contain a ``samples.csv`` produced by
``sample_dataset.py`` and the frame paths recorded in that manifest.
Usage:
python scripts/filter_junk.py Data
"""
import argparse
import csv
import os
import tempfile
from decimal import Decimal, InvalidOperation
from pathlib import Path
# Inclusive intervals on rgb_time_s. None means the end of the video.
JUNK_INTERVALS = {
"Canopy-05": [(Decimal("110"), Decimal("143")),
(Decimal("148"), None)],
"Canopy-09": [(Decimal("520"), None)],
"Canopy-22": [(Decimal("175"), None)],
"Graminoid-06": [(Decimal("552"), None)],
}
FRAME_COLUMNS = ("rgb_path", "ir_path")
REQUIRED_COLUMNS = {"pair_id", "rgb_time_s", *FRAME_COLUMNS}
def is_junk(pair_id, timestamp):
return any(
start <= timestamp and (end is None or timestamp <= end)
for start, end in JUNK_INTERVALS.get(pair_id, ())
)
def frame_path(dataset_root, relative_path):
relative = Path(relative_path)
if relative.is_absolute() or ".." in relative.parts:
raise RuntimeError(f"unsafe frame path in samples.csv: {relative_path!r}")
path = dataset_root.joinpath(relative)
if not path.is_file() or path.is_symlink():
raise RuntimeError(f"missing or invalid frame: {path}")
return path
def load_manifest(dataset_root):
manifest = dataset_root / "samples.csv"
if not manifest.is_file() or manifest.is_symlink():
raise RuntimeError(f"missing or invalid manifest: {manifest}")
with manifest.open(newline="") as file:
reader = csv.DictReader(file)
if not reader.fieldnames or not REQUIRED_COLUMNS.issubset(reader.fieldnames):
raise RuntimeError(f"invalid samples.csv header: {manifest}")
rows = list(reader)
return manifest, reader.fieldnames, rows
def select_removals(dataset_root, rows):
kept = []
removed = []
removal_paths = []
for line_number, row in enumerate(rows, start=2):
try:
timestamp = Decimal(row["rgb_time_s"])
except (InvalidOperation, TypeError):
raise RuntimeError(
f"invalid rgb_time_s on samples.csv line {line_number}"
) from None
if timestamp.is_nan() or timestamp.is_infinite():
raise RuntimeError(
f"non-finite rgb_time_s on samples.csv line {line_number}"
)
if is_junk(row["pair_id"], timestamp):
removed.append(row)
removal_paths.extend(
frame_path(dataset_root, row[column]) for column in FRAME_COLUMNS
)
else:
kept.append(row)
if len(removal_paths) != len(set(removal_paths)):
raise RuntimeError(f"duplicate removal path in {dataset_root / 'samples.csv'}")
kept_paths = {
dataset_root / row[column]
for row in kept
for column in FRAME_COLUMNS
}
overlap = kept_paths.intersection(removal_paths)
if overlap:
raise RuntimeError(f"frame is referenced by both kept and removed rows: {overlap.pop()}")
return kept, removed, removal_paths
def write_manifest(manifest, fieldnames, rows):
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{manifest.name}.", suffix=".tmp", dir=manifest.parent
)
try:
with os.fdopen(descriptor, "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
file.flush()
os.fsync(file.fileno())
os.replace(temporary_name, manifest)
except Exception:
if os.path.exists(temporary_name):
os.unlink(temporary_name)
raise
def filter_dataset(dataset_root):
dataset_root = dataset_root.resolve()
manifest, fieldnames, rows = load_manifest(dataset_root)
kept, removed, removal_paths = select_removals(dataset_root, rows)
if not removed:
print(f"{dataset_root}: no junk frames found")
return
# Commit the kept manifest first. If a later unlink fails, any remaining
# junk images are harmless unreferenced files rather than missing samples.
write_manifest(manifest, fieldnames, kept)
for path in removal_paths:
path.unlink()
print(
f"{dataset_root}: removed {len(removed)} pairs "
f"({len(removal_paths)} files); kept {len(kept)} pairs"
)
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"dataset_roots",
type=Path,
nargs="+",
help="sampled dataset directories containing samples.csv",
)
return parser.parse_args()
def main():
args = parse_args()
answer = input("This will change the dataset in place! Continue? [y/N] ")
if answer.strip().lower() not in {"y", "yes"}:
print("Cancelled")
return
for dataset_root in args.dataset_roots:
filter_dataset(dataset_root)
if __name__ == "__main__":
main()