File size: 10,224 Bytes
7a87926
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# API Models Documentation

This document describes the Pydantic models used throughout the YLFF API. All models are rigorously defined with comprehensive validation, documentation, and examples.

## Overview

All API request/response models are defined in `ylff/api_models.py` with:

- **Comprehensive field validation** (ranges, types, constraints)
- **Detailed descriptions** for all fields
- **Examples** for every field and model
- **Type safety** with enums where appropriate
- **Custom validators** for complex validation logic
- **JSON schema generation** support

## Model Organization

Models are organized into:

- **Enums**: Type-safe enumerations for common values
- **Request Models**: Input validation for API endpoints
- **Response Models**: Structured response data

## Enums

### `JobStatus`

Job execution status values:

- `queued`: Job is queued for execution
- `running`: Job is currently executing
- `completed`: Job completed successfully
- `failed`: Job failed
- `cancelled`: Job was cancelled

### `DeviceType`

Device type for model inference/training:

- `cpu`: CPU execution
- `cuda`: CUDA GPU execution
- `mps`: Apple Metal Performance Shaders

### `UseCase`

Use case for model selection:

- `ba_validation`: Bundle Adjustment validation
- `mono_depth`: Monocular depth estimation
- `multi_view`: Multi-view depth estimation
- `pose_conditioned`: Pose-conditioned depth
- `training`: Training use case
- `inference`: General inference

## Request Models

### `ValidateSequenceRequest`

Request model for sequence validation endpoint.

**Fields:**

- `sequence_dir` (str, required): Directory containing image sequence
- `model_name` (str, optional): DA3 model name (default: auto-select)
- `use_case` (UseCase): Use case for model selection (default: `ba_validation`)
- `accept_threshold` (float): Accept threshold in degrees (default: 2.0, range: 0-180)
- `reject_threshold` (float): Reject threshold in degrees (default: 30.0, range: 0-180)
- `output` (str, optional): Output JSON path for results

**Validation:**

- `reject_threshold` must be greater than `accept_threshold`
- `sequence_dir` cannot be empty

**Example:**

```json
{
  "sequence_dir": "data/sequences/sequence_001",
  "model_name": "depth-anything/DA3-LARGE",
  "use_case": "ba_validation",
  "accept_threshold": 2.0,
  "reject_threshold": 30.0,
  "output": "data/results/validation.json"
}
```

### `ValidateARKitRequest`

Request model for ARKit validation endpoint.

**Fields:**

- `arkit_dir` (str, required): Directory containing ARKit video and JSON metadata
- `output_dir` (str): Output directory (default: `"data/arkit_validation"`)
- `model_name` (str, optional): DA3 model name
- `max_frames` (int, optional): Maximum frames to process (≥1)
- `frame_interval` (int): Extract every Nth frame (default: 1, ≥1)
- `device` (DeviceType): Device for DA3 inference (default: `cpu`)
- `gui` (bool): Show real-time GUI visualization (default: `False`)

**Validation:**

- `arkit_dir` cannot be empty

### `BuildDatasetRequest`

Request model for building training dataset.

**Fields:**

- `sequences_dir` (str, required): Directory containing sequence directories
- `output_dir` (str): Output directory (default: `"data/training"`)
- `model_name` (str, optional): DA3 model name for validation
- `max_samples` (int, optional): Maximum training samples (≥1)
- `accept_threshold` (float): Accept threshold in degrees (default: 2.0)
- `reject_threshold` (float): Reject threshold in degrees (default: 30.0)
- `use_wandb` (bool): Enable W&B logging (default: `True`)
- `wandb_project` (str): W&B project name (default: `"ylff"`)
- `wandb_name` (str, optional): W&B run name

**Validation:**

- `reject_threshold` must be greater than `accept_threshold`

### `TrainRequest`

Request model for model fine-tuning.

**Fields:**

- `training_data_dir` (str, required): Directory containing training samples
- `model_name` (str, optional): DA3 model name to fine-tune
- `epochs` (int): Number of epochs (default: 10, range: 1-1000)
- `lr` (float): Learning rate (default: 1e-5, >0)
- `batch_size` (int): Batch size (default: 1, ≥1)
- `checkpoint_dir` (str): Checkpoint directory (default: `"checkpoints"`)
- `device` (DeviceType): Device for training (default: `cuda`)
- `use_wandb` (bool): Enable W&B logging (default: `True`)
- `wandb_project` (str): W&B project name (default: `"ylff"`)
- `wandb_name` (str, optional): W&B run name

### `PretrainRequest`

Request model for model pre-training on ARKit sequences.

**Fields:**

- `arkit_sequences_dir` (str, required): Directory containing ARKit sequence directories
- `model_name` (str, optional): DA3 model name to pre-train
- `epochs` (int): Number of epochs (default: 10, range: 1-1000)
- `lr` (float): Learning rate (default: 1e-4, >0)
- `batch_size` (int): Batch size (default: 1, ≥1)
- `checkpoint_dir` (str): Checkpoint directory (default: `"checkpoints/pretrain"`)
- `device` (DeviceType): Device for training (default: `cuda`)
- `max_sequences` (int, optional): Maximum sequences to process (≥1)
- `max_frames_per_sequence` (int, optional): Maximum frames per sequence (≥1)
- `frame_interval` (int): Extract every Nth frame (default: 1, ≥1)
- `use_lidar` (bool): Use ARKit LiDAR depth as supervision (default: `False`)
- `use_ba_depth` (bool): Use BA depth maps as supervision (default: `False`)
- `min_ba_quality` (float): Minimum BA quality threshold (default: 0.0, range: 0.0-1.0)
- `use_wandb` (bool): Enable W&B logging (default: `True`)
- `wandb_project` (str): W&B project name (default: `"ylff"`)
- `wandb_name` (str, optional): W&B run name

### `EvaluateBAAgreementRequest`

Request model for BA agreement evaluation.

**Fields:**

- `test_data_dir` (str, required): Directory containing test sequences
- `model_name` (str): DA3 model name (default: `"depth-anything/DA3-LARGE"`)
- `checkpoint` (str, optional): Path to model checkpoint
- `threshold` (float): Agreement threshold in degrees (default: 2.0, range: 0-180)
- `device` (DeviceType): Device for inference (default: `cuda`)
- `use_wandb` (bool): Enable W&B logging (default: `True`)
- `wandb_project` (str): W&B project name (default: `"ylff"`)
- `wandb_name` (str, optional): W&B run name

### `VisualizeRequest`

Request model for result visualization.

**Fields:**

- `results_dir` (str, required): Directory containing validation results
- `output_dir` (str, optional): Output directory for visualizations
- `use_plotly` (bool): Use Plotly for interactive plots (default: `True`)

## Response Models

### `JobResponse`

Standard response for job-based endpoints.

**Fields:**

- `job_id` (str, required): Unique job identifier
- `status` (JobStatus, required): Current job status
- `message` (str, optional): Status message or error description
- `result` (dict, optional): Job result data (only when completed/failed)

### `ValidationStats`

Statistics from BA validation.

**Fields:**

- `total_frames` (int): Total frames processed (≥0)
- `accepted` (int): Accepted frames count (≥0)
- `rejected_learnable` (int): Rejected-learnable frames count (≥0)
- `rejected_outlier` (int): Rejected-outlier frames count (≥0)
- `accepted_percentage` (float): Percentage accepted (0-100)
- `rejected_learnable_percentage` (float): Percentage rejected-learnable (0-100)
- `rejected_outlier_percentage` (float): Percentage rejected-outlier (0-100)
- `ba_status` (str, optional): BA validation status
- `max_error_deg` (float, optional): Maximum rotation error in degrees (≥0)

### `HealthResponse`

Health check response.

**Fields:**

- `status` (str): Health status (`"healthy"`, `"degraded"`, `"unhealthy"`)
- `timestamp` (float): Unix timestamp
- `request_id` (str): Request ID
- `profiling` (dict, optional): Profiling status if available

### `ModelsResponse`

Response for models list endpoint.

**Fields:**

- `models` (dict): Dictionary of available models with metadata
- `recommended` (str, optional): Recommended model for requested use case

### `ErrorResponse`

Standard error response.

**Fields:**

- `error` (str): Error type/name
- `message` (str): Human-readable error message
- `request_id` (str): Request ID for log correlation
- `details` (dict, optional): Additional error details
- `endpoint` (str, optional): Endpoint where error occurred

## Validation Features

### Field Validators

1. **Range Validation**: Numeric fields have `ge` (≥), `le` (≤), `gt` (>), `lt` (<) constraints
2. **String Validation**: String fields have `min_length` constraints
3. **Custom Validators**:
   - `reject_threshold > accept_threshold` validation
   - Path format validation
   - Non-empty string validation

### Type Safety

- Enums for status values, device types, and use cases
- Optional fields clearly marked with `Optional[Type]`
- Required fields use `...` in Field definition

### Examples

All models include `model_config` with JSON schema examples for:

- API documentation generation
- Client SDK generation
- Testing and validation

## Usage

### In API Endpoints

```python
from .api_models import ValidateSequenceRequest, JobResponse

@app.post("/api/v1/validate/sequence", response_model=JobResponse)
async def validate_sequence(request: ValidateSequenceRequest):
    # request is automatically validated
    # Invalid requests return 422 with detailed error messages
    ...
```

### Model Validation

Pydantic automatically validates:

- Type checking
- Range constraints
- Custom validators
- Required fields
- Enum values

### Error Handling

Validation errors are automatically handled by FastAPI and return:

```json
{
  "error": "ValidationError",
  "message": "Invalid request data",
  "details": [
    {
      "field": "reject_threshold",
      "error": "reject_threshold (20.0) must be greater than accept_threshold (30.0)"
    }
  ],
  "request_id": "..."
}
```

## Benefits

1. **Type Safety**: Catch errors at request time, not runtime
2. **Documentation**: Auto-generated API docs with examples
3. **Validation**: Comprehensive input validation before processing
4. **Consistency**: Standardized request/response formats
5. **Maintainability**: Centralized model definitions
6. **Developer Experience**: Clear error messages and examples