File size: 5,187 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/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()