File size: 8,051 Bytes
8d7b4b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Feature specification and validation system for training/inference consistency.

This module defines strict feature specifications for each modality to ensure
training and inference produce identical feature representations.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Optional
import numpy as np


@dataclass
class ModalitySpec:
    """Specification for a single modality's features."""

    name: str
    expected_dim: int
    temporal: bool = True
    preprocessor_class: Optional[str] = None
    extractor_class: Optional[str] = None
    pca_enabled: bool = False
    pca_target_dim: Optional[int] = None
    normalizer_type: str = "standard"  # "standard", "robust", "minmax", "none"

    def validate_features(self, features: np.ndarray) -> bool:
        """Validate that features match specification."""
        if not isinstance(features, np.ndarray):
            return False
        if features.dtype != np.float32:
            return False
        if self.temporal:
            if features.ndim != 2:
                return False
            if features.shape[1] != self.expected_dim:
                return False
        else:
            if features.ndim != 1:
                return False
            if features.shape[0] != self.expected_dim:
                return False
        return not (np.isnan(features).any() or np.isinf(features).any())

    def to_dict(self) -> Dict:
        """Serialize spec to dict."""
        return {
            "name": self.name,
            "expected_dim": self.expected_dim,
            "temporal": self.temporal,
            "preprocessor_class": self.preprocessor_class,
            "extractor_class": self.extractor_class,
            "pca_enabled": self.pca_enabled,
            "pca_target_dim": self.pca_target_dim,
            "normalizer_type": self.normalizer_type,
        }

    @classmethod
    def from_dict(cls, data: Dict) -> ModalitySpec:
        """Deserialize spec from dict."""
        return cls(**data)


class AudioSpec:
    """Audio modality specifications."""

    # MFCC-based audio: 13 MFCC + 13 delta + 13 delta2 = 39
    MFCC_DIM = 39

    # HuBERT-base embeddings
    HUBERT_DIM = 768

    # Combined features: MFCC (39) + HuBERT (768) = 807
    COMBINED_DIM = MFCC_DIM + HUBERT_DIM

    # Standard specification: use MFCC features for training
    STANDARD = ModalitySpec(
        name="audio",
        expected_dim=MFCC_DIM,  # 39: 13 MFCC + 13 delta + 13 delta2
        temporal=True,
        preprocessor_class="AudioPreprocessor",
        extractor_class="AudioFeatureExtractor",
        pca_enabled=False,
        normalizer_type="standard",
    )

    # Optional: HuBERT embeddings
    HUBERT = ModalitySpec(
        name="audio_hubert",
        expected_dim=HUBERT_DIM,  # 768
        temporal=True,
        preprocessor_class="AudioPreprocessor",
        extractor_class="AudioFeatureExtractor",
        pca_enabled=True,
        pca_target_dim=128,
        normalizer_type="standard",
    )

    # Optional: Combined MFCC + HuBERT
    COMBINED = ModalitySpec(
        name="audio_combined",
        expected_dim=COMBINED_DIM,  # 807
        temporal=True,
        preprocessor_class="AudioPreprocessor",
        extractor_class="AudioFeatureExtractor",
        pca_enabled=True,
        pca_target_dim=128,
        normalizer_type="standard",
    )


class VideoSpec:
    """Video modality specifications."""

    # OpenFace features: AU (17) + gaze (3) + head pose (3) + landmarks dynamics (many)
    OPENFACE_DIM = 38  # Conservative estimate for behavioral features

    # ResNet50 embeddings: 2048D, typically PCA-reduced
    RESNET_RAW_DIM = 2048
    RESNET_PCA_DIM = 128  # Standard reduction for ResNet

    # Specification: behavioral features + visual embeddings
    BEHAVIORAL = ModalitySpec(
        name="video_behavior",
        expected_dim=OPENFACE_DIM,  # 38: OpenFace AU + gaze + pose
        temporal=True,
        preprocessor_class="VideoPreprocessor",
        extractor_class="VideoFeatureExtractor",
        pca_enabled=False,
        normalizer_type="standard",
    )

    VISUAL_EMBEDDING = ModalitySpec(
        name="video_embedding",
        expected_dim=RESNET_PCA_DIM,  # 128: ResNet50 PCA-reduced
        temporal=True,
        preprocessor_class="VideoPreprocessor",
        extractor_class="VideoFeatureExtractor",
        pca_enabled=True,  # PCA is applied during extraction
        pca_target_dim=RESNET_PCA_DIM,
        normalizer_type="standard",
    )

    # Combined: behavioral + visual
    COMBINED = ModalitySpec(
        name="video_combined",
        expected_dim=OPENFACE_DIM + RESNET_PCA_DIM,  # 166: behavioral + visual
        temporal=True,
        preprocessor_class="VideoPreprocessor",
        extractor_class="VideoFeatureExtractor",
        pca_enabled=False,
        normalizer_type="standard",
    )

    # Standard: behavioral features only (recommended for small datasets)
    STANDARD = BEHAVIORAL


class TextSpec:
    """Text modality specifications."""

    # SBERT all-mpnet-base-v2 embeddings
    SBERT_DIM = 384

    # Standard specification
    STANDARD = ModalitySpec(
        name="text",
        expected_dim=SBERT_DIM,  # 384: SBERT embeddings
        temporal=True,  # Multiple chunks per session
        preprocessor_class="TextPreprocessor",
        extractor_class="TextFeatureExtractor",
        pca_enabled=False,
        normalizer_type="standard",
    )


class FeatureSpecification:
    """Complete multimodal feature specification for training/inference consistency."""

    def __init__(
        self,
        audio_spec: ModalitySpec = AudioSpec.STANDARD,
        video_spec: ModalitySpec = VideoSpec.STANDARD,
        text_spec: ModalitySpec = TextSpec.STANDARD,
    ):
        self.audio_spec = audio_spec
        self.video_spec = video_spec
        self.text_spec = text_spec
        self._specs = {
            "audio": audio_spec,
            "video": video_spec,
            "text": text_spec,
        }

    @property
    def audio_dim(self) -> int:
        return self.audio_spec.expected_dim

    @property
    def video_dim(self) -> int:
        return self.video_spec.expected_dim

    @property
    def text_dim(self) -> int:
        return self.text_spec.expected_dim

    def get_spec(self, modality: str) -> ModalitySpec:
        """Get specification for a modality."""
        if modality not in self._specs:
            raise ValueError(f"Unknown modality: {modality}")
        return self._specs[modality]

    def validate(self, features: Dict[str, np.ndarray]) -> bool:
        """Validate all feature modalities match specification."""
        for modality, feature_array in features.items():
            if modality in self._specs:
                if not self._specs[modality].validate_features(feature_array):
                    return False
        return True

    def to_dict(self) -> Dict:
        """Serialize specification."""
        return {
            "audio": self.audio_spec.to_dict(),
            "video": self.video_spec.to_dict(),
            "text": self.text_spec.to_dict(),
        }

    @classmethod
    def default(cls) -> FeatureSpecification:
        """Create default specification: MFCC audio + behavioral video + SBERT text."""
        return cls(
            audio_spec=AudioSpec.STANDARD,
            video_spec=VideoSpec.STANDARD,
            text_spec=TextSpec.STANDARD,
        )

    @classmethod
    def with_hubert(cls) -> FeatureSpecification:
        """Create specification with HuBERT audio embeddings."""
        return cls(
            audio_spec=AudioSpec.HUBERT,
            video_spec=VideoSpec.STANDARD,
            text_spec=TextSpec.STANDARD,
        )

    @classmethod
    def multimodal_combined(cls) -> FeatureSpecification:
        """Create specification with all combined features."""
        return cls(
            audio_spec=AudioSpec.COMBINED,
            video_spec=VideoSpec.COMBINED,
            text_spec=TextSpec.STANDARD,
        )