File size: 5,629 Bytes
ae419ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import pickle
import random
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
import torch
from torch.utils.data import Dataset

from .features import bone_features, dynamics_features, mask_keypoints


@dataclass
class ClipSample:
    video_id: str
    label: int
    joint: np.ndarray


def load_pickle(path: str | Path) -> Any:
    with open(path, "rb") as f:
        return pickle.load(f)


def save_pickle(obj: Any, path: str | Path) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "wb") as f:
        pickle.dump(obj, f)


class FallClipDataset(Dataset):
    def __init__(
        self,
        pkl_path: str | Path,
        robustness: str = "clean",
        missing_amount: float = 0.0,
        train: bool = False,
        confidence_dropout: bool = False,
        random_dropout: bool = False,
        random_dropout_prob: float = 0.1,
        high_conf_prob: float = 0.1,
        low_conf_prob: float = 0.5,
        low_conf_threshold: float = 0.3,
        seed: int = 7,
    ) -> None:
        self.samples = load_pickle(pkl_path)
        self.robustness = robustness
        self.missing_amount = missing_amount
        self.train = train
        self.confidence_dropout = confidence_dropout
        self.random_dropout = random_dropout
        self.random_dropout_prob = random_dropout_prob
        self.high_conf_prob = high_conf_prob
        self.low_conf_prob = low_conf_prob
        self.low_conf_threshold = low_conf_threshold
        self.rng = np.random.default_rng(seed)

    def __len__(self) -> int:
        return len(self.samples)

    def __getitem__(self, idx: int) -> dict[str, torch.Tensor | str]:
        sample = self.samples[idx]
        joint = np.asarray(sample["joint"], dtype=np.float32)
        if self.train and self.random_dropout:
            joint = self._random_dropout(joint)
        if self.train and self.confidence_dropout:
            joint = self._confidence_dropout(joint)
        if self.robustness != "clean":
            joint = mask_keypoints(joint, self.robustness, self.missing_amount, self.rng)
        bone = bone_features(joint)
        dyn = dynamics_features(joint)
        return {
            "video_id": sample["video_id"],
            "joint": torch.from_numpy(joint),
            "bone": torch.from_numpy(bone),
            "dyn": torch.from_numpy(dyn),
            "label": torch.tensor(sample["label"], dtype=torch.long),
        }

    def _confidence_dropout(self, joint: np.ndarray) -> np.ndarray:
        conf = joint[..., 2]
        probs = np.where(conf < self.low_conf_threshold, self.low_conf_prob, self.high_conf_prob)
        mask = self.rng.random(conf.shape) < probs
        out = joint.copy()
        out[mask] = 0
        return out.astype(np.float32)

    def _random_dropout(self, joint: np.ndarray) -> np.ndarray:
        mask = self.rng.random(joint.shape[:2]) < self.random_dropout_prob
        out = joint.copy()
        out[mask] = 0
        return out.astype(np.float32)


def split_video_ids(video_ids: list[str], ratios: dict[str, float], seed: int) -> dict[str, set[str]]:
    ids = sorted(set(video_ids))
    random.Random(seed).shuffle(ids)
    n = len(ids)
    n_train = max(1, int(round(n * ratios["train"])))
    n_val = max(1, int(round(n * ratios["val"]))) if n >= 3 else 0
    if n_train + n_val >= n:
        n_train = max(1, n - 2)
        n_val = 1 if n >= 3 else 0
    return {
        "train": set(ids[:n_train]),
        "val": set(ids[n_train:n_train + n_val]),
        "test": set(ids[n_train + n_val:]),
    }


def split_video_records(
    records: list[dict[str, Any]],
    ratios: dict[str, float],
    seed: int,
    group_key: str = "video",
) -> dict[str, set[str]]:
    """Stratified split over video ids or higher-level scenario groups."""
    rng = random.Random(seed)
    group_labels: dict[str, int] = {}
    for rec in records:
        gid = record_group_id(rec, group_key)
        label = int(rec["label"])
        if gid in group_labels and group_labels[gid] != label:
            raise ValueError(f"Mixed labels inside group {gid}")
        group_labels[gid] = label
    by_label: dict[int, list[str]] = {}
    for gid, label in group_labels.items():
        by_label.setdefault(label, []).append(gid)
    group_buckets = {"train": set(), "val": set(), "test": set()}
    for groups in by_label.values():
        groups = sorted(set(groups))
        rng.shuffle(groups)
        n = len(groups)
        n_train = max(1, int(round(n * ratios["train"])))
        n_val = max(1, int(round(n * ratios["val"]))) if n >= 3 else 0
        if n_train + n_val >= n:
            n_train = max(1, n - 2)
            n_val = 1 if n >= 3 else 0
        group_buckets["train"].update(groups[:n_train])
        group_buckets["val"].update(groups[n_train:n_train + n_val])
        group_buckets["test"].update(groups[n_train + n_val:])
    video_buckets = {"train": set(), "val": set(), "test": set()}
    for rec in records:
        gid = record_group_id(rec, group_key)
        split = next(k for k, groups in group_buckets.items() if gid in groups)
        video_buckets[split].add(str(rec["video_id"]))
    return video_buckets


def record_group_id(rec: dict[str, Any], group_key: str) -> str:
    video_id = str(rec["video_id"])
    if group_key == "video":
        return video_id
    if group_key == "scenario":
        parts = video_id.split("/")
        return "/".join(parts[:2]) if len(parts) >= 2 else video_id
    raise ValueError(f"Unknown group_key: {group_key}")