hyperstudy 0.2.1__tar.gz → 0.2.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/PKG-INFO +1 -1
- hyperstudy-0.2.3/docs/superpowers/specs/2026-04-10-recording-downloads-design.md +128 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/pyproject.toml +1 -1
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/__init__.py +1 -1
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/_dataframe.py +47 -0
- hyperstudy-0.2.3/src/hyperstudy/_downloads.py +76 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/_http.py +10 -3
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/_pagination.py +3 -2
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/client.py +152 -2
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/conftest.py +10 -0
- hyperstudy-0.2.3/tests/fixtures/recordings_response.json +71 -0
- hyperstudy-0.2.3/tests/fixtures/sparse_ratings_response.json +108 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/test_client.py +275 -0
- hyperstudy-0.2.3/tests/test_dataframe.py +182 -0
- hyperstudy-0.2.3/tests/test_downloads.py +188 -0
- hyperstudy-0.2.3/tests/test_http.py +54 -0
- hyperstudy-0.2.1/tests/test_dataframe.py +0 -78
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/.github/workflows/publish.yml +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/.github/workflows/sync-release-notes.yml +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/.github/workflows/test.yml +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/.gitignore +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/CHANGELOG.md +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/LICENSE +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/README.md +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/_display.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/_types.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/exceptions.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/src/hyperstudy/experiments.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/__init__.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/deployment_sessions_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/deployment_single_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/deployments_list_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/error_401.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/error_403.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/events_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/experiment_single_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/experiments_list_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/paginated_page1.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/paginated_page2.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/pre_experiment_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/fixtures/warnings_response.json +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/test_experiments.py +0 -0
- {hyperstudy-0.2.1 → hyperstudy-0.2.3}/tests/test_pagination.py +0 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# Recording Downloads via Python SDK
|
|
2
|
+
|
|
3
|
+
## Problem
|
|
4
|
+
|
|
5
|
+
The Python SDK's `get_recordings()` returns metadata only. Users need the actual audio/video files for offline analysis (ML models, manual review, archival). Currently they must manually extract `downloadUrl` from each record and fetch files themselves.
|
|
6
|
+
|
|
7
|
+
## Decision: SDK-only, no backend changes
|
|
8
|
+
|
|
9
|
+
The V3 API already returns signed GCS download URLs (7-day expiry) in the recording metadata. The SDK will fetch metadata and download files in the same call, so URL expiry is not a practical concern. This matches how the frontend downloads recordings.
|
|
10
|
+
|
|
11
|
+
## API Surface
|
|
12
|
+
|
|
13
|
+
### `download_recordings()` — Bulk download
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
df = hs.download_recordings(
|
|
17
|
+
"exp_abc123",
|
|
18
|
+
output_dir="./data/recordings",
|
|
19
|
+
scope="experiment", # "experiment" | "room" | "participant"
|
|
20
|
+
deployment_id=None, # optional filter
|
|
21
|
+
room_id=None, # optional filter
|
|
22
|
+
recording_type=None, # "audio" | "video" | None (both)
|
|
23
|
+
progress=True, # tqdm progress bar
|
|
24
|
+
skip_existing=True, # skip files already on disk with matching size
|
|
25
|
+
)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**Returns**: `pandas.DataFrame` with all recording metadata columns plus:
|
|
29
|
+
- `local_path` — absolute path to the downloaded file on disk
|
|
30
|
+
- `download_status` — `"downloaded"`, `"skipped"`, or `"failed"`
|
|
31
|
+
|
|
32
|
+
**Side effects**:
|
|
33
|
+
- Writes media files to `output_dir`
|
|
34
|
+
- Writes `recordings_metadata.csv` to `output_dir`
|
|
35
|
+
|
|
36
|
+
### `download_recording()` — Single recording
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
path = hs.download_recording(
|
|
40
|
+
recording, # dict from get_recordings(output="dict")
|
|
41
|
+
output_dir="./data/recordings",
|
|
42
|
+
)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
**Returns**: `pathlib.Path` to downloaded file.
|
|
46
|
+
|
|
47
|
+
## Directory Structure
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
output_dir/
|
|
51
|
+
recordings_metadata.csv
|
|
52
|
+
user1_video_EG_abc123.mp4
|
|
53
|
+
user1_audio_EG_def456.webm
|
|
54
|
+
user2_video_EG_ghi789.mp4
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Filename pattern**: `{participantName}_{recordingType}_{recordingId}.{ext}`
|
|
58
|
+
|
|
59
|
+
- `participantName`: from recording metadata, sanitized for filesystem safety
|
|
60
|
+
- `recordingType`: `"video"` or `"audio"` from `metadata.type`
|
|
61
|
+
- `recordingId`: egressId or recordingId
|
|
62
|
+
- `ext`: from `format` field, falling back to `mp4` (video) or `webm` (audio)
|
|
63
|
+
|
|
64
|
+
## Internal Design
|
|
65
|
+
|
|
66
|
+
### Download flow (`download_recordings`)
|
|
67
|
+
|
|
68
|
+
1. Call `self.get_recordings(scope_id, scope=scope, output="dict")` to get metadata
|
|
69
|
+
2. Filter by `recording_type` if specified (via `metadata.type`)
|
|
70
|
+
3. Create `output_dir` via `os.makedirs(exist_ok=True)`
|
|
71
|
+
4. For each recording:
|
|
72
|
+
- Build filename using pattern above
|
|
73
|
+
- If `skip_existing=True` and file exists with size matching `fileSize` metadata, mark as `"skipped"`
|
|
74
|
+
- Otherwise, fetch from `downloadUrl` (fallback: `url`) using streaming HTTP GET
|
|
75
|
+
- Write to disk in 8KB chunks
|
|
76
|
+
- Mark as `"downloaded"` or `"failed"` (with warning logged)
|
|
77
|
+
5. Build DataFrame from metadata, add `local_path` and `download_status` columns
|
|
78
|
+
6. Write `recordings_metadata.csv` to `output_dir`
|
|
79
|
+
7. Return DataFrame
|
|
80
|
+
|
|
81
|
+
### Streaming downloads
|
|
82
|
+
|
|
83
|
+
Use `requests.get(url, stream=True)` with chunked iteration to avoid loading large video files into memory. The SDK's existing `HttpTransport` handles JSON responses only, so file downloads use a standalone `requests.get()` — the signed GCS URLs don't need API key auth.
|
|
84
|
+
|
|
85
|
+
### Error handling
|
|
86
|
+
|
|
87
|
+
- Per-file failure tolerance: if one recording fails (404, timeout, network error), log a warning, set `download_status="failed"`, continue with remaining files
|
|
88
|
+
- If the metadata API call itself fails, raise normally (same as `get_recordings()`)
|
|
89
|
+
- Invalid/missing `downloadUrl`: set `download_status="failed"`, log warning
|
|
90
|
+
|
|
91
|
+
### Skip-existing logic
|
|
92
|
+
|
|
93
|
+
Compare `os.path.getsize(local_path)` against `fileSize` from metadata. If `fileSize` is `None` (metadata missing), fall back to checking file existence only (any existing file is considered complete).
|
|
94
|
+
|
|
95
|
+
## File Layout
|
|
96
|
+
|
|
97
|
+
| File | Change |
|
|
98
|
+
|------|--------|
|
|
99
|
+
| `src/hyperstudy/_downloads.py` | **New.** `build_filename()`, `download_file()` streaming helper |
|
|
100
|
+
| `src/hyperstudy/client.py` | Add `download_recordings()` and `download_recording()` methods |
|
|
101
|
+
| `tests/test_downloads.py` | **New.** Unit tests for filename building, skip logic, status tracking |
|
|
102
|
+
| `tests/test_client.py` | Integration test: mock API + GCS, verify files + DataFrame |
|
|
103
|
+
| `tests/fixtures/sparse_ratings_response.json` | Already exists (from prior work) |
|
|
104
|
+
|
|
105
|
+
## Testing
|
|
106
|
+
|
|
107
|
+
### Unit tests (`tests/test_downloads.py`)
|
|
108
|
+
- `test_build_filename` — video, audio, missing fields, filesystem-unsafe characters
|
|
109
|
+
- `test_build_filename_dedup` — duplicate names get numeric suffix
|
|
110
|
+
- `test_skip_existing_matching_size` — file with correct size is skipped
|
|
111
|
+
- `test_skip_existing_wrong_size` — file with wrong size is re-downloaded
|
|
112
|
+
|
|
113
|
+
### Integration tests (`tests/test_client.py`)
|
|
114
|
+
- `test_download_recordings` — mock API + GCS fetch, verify files on disk, CSV sidecar, DataFrame with `local_path` + `download_status`
|
|
115
|
+
- `test_download_recordings_filter_type` — `recording_type="audio"` only downloads audio
|
|
116
|
+
- `test_download_recording_single` — single recording download
|
|
117
|
+
|
|
118
|
+
### Mocking strategy
|
|
119
|
+
- V3 API: `responses` library (existing pattern)
|
|
120
|
+
- GCS signed URL: also `responses` (it's just an HTTP GET to a URL)
|
|
121
|
+
- File I/O: real writes to `pytest` `tmp_path`
|
|
122
|
+
|
|
123
|
+
## No Backend Changes Required
|
|
124
|
+
|
|
125
|
+
The existing V3 API endpoints return all necessary data:
|
|
126
|
+
- `GET /api/v3/data/recordings/{scope}/{scopeId}` returns metadata with `downloadUrl`
|
|
127
|
+
- Signed GCS URLs are valid for 7 days
|
|
128
|
+
- SDK downloads immediately after fetching metadata, so expiry is not an issue
|
|
@@ -6,6 +6,51 @@ from typing import Any
|
|
|
6
6
|
|
|
7
7
|
import pandas as pd
|
|
8
8
|
|
|
9
|
+
# Nested dict fields to flatten into top-level columns.
|
|
10
|
+
# Mapping of {field_name: prefix} — sub-keys become ``{prefix}_{sub_key}``.
|
|
11
|
+
FLATTEN_FIELDS: dict[str, str] = {
|
|
12
|
+
"sparseRatingData": "sparseRatingData",
|
|
13
|
+
"metadata": "metadata",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _flatten_nested_dicts(
|
|
18
|
+
data: list[dict[str, Any]],
|
|
19
|
+
fields: dict[str, str] | None = None,
|
|
20
|
+
) -> list[dict[str, Any]]:
|
|
21
|
+
"""Promote sub-keys of nested dict fields to top-level keys.
|
|
22
|
+
|
|
23
|
+
For each *field* present in a record whose value is a ``dict``, every
|
|
24
|
+
sub-key is copied to ``{prefix}_{sub_key}``. The original nested dict
|
|
25
|
+
is preserved for backward compatibility.
|
|
26
|
+
|
|
27
|
+
Records where the target field is ``None`` or missing are left
|
|
28
|
+
untouched — downstream DataFrame construction fills those columns
|
|
29
|
+
with ``NaN`` / ``null``.
|
|
30
|
+
"""
|
|
31
|
+
if not data:
|
|
32
|
+
return data
|
|
33
|
+
|
|
34
|
+
fields = fields if fields is not None else FLATTEN_FIELDS
|
|
35
|
+
|
|
36
|
+
# Quick check on first record — skip work when no target fields exist.
|
|
37
|
+
sample = data[0]
|
|
38
|
+
targets = [f for f in fields if f in sample and isinstance(sample[f], dict)]
|
|
39
|
+
if not targets:
|
|
40
|
+
return data
|
|
41
|
+
|
|
42
|
+
out: list[dict[str, Any]] = []
|
|
43
|
+
for record in data:
|
|
44
|
+
record = dict(record) # shallow copy to avoid mutating caller's data
|
|
45
|
+
for field in targets:
|
|
46
|
+
nested = record.get(field)
|
|
47
|
+
if isinstance(nested, dict):
|
|
48
|
+
prefix = fields[field]
|
|
49
|
+
for sub_key, sub_val in nested.items():
|
|
50
|
+
record[f"{prefix}_{sub_key}"] = sub_val
|
|
51
|
+
out.append(record)
|
|
52
|
+
return out
|
|
53
|
+
|
|
9
54
|
|
|
10
55
|
def _post_process(df: pd.DataFrame) -> pd.DataFrame:
|
|
11
56
|
"""Shared post-processing for pandas DataFrames.
|
|
@@ -32,6 +77,7 @@ def to_pandas(data: list[dict[str, Any]]) -> pd.DataFrame:
|
|
|
32
77
|
"""Convert API response data to a pandas DataFrame with post-processing."""
|
|
33
78
|
if not data:
|
|
34
79
|
return pd.DataFrame()
|
|
80
|
+
data = _flatten_nested_dicts(data)
|
|
35
81
|
df = pd.DataFrame(data)
|
|
36
82
|
return _post_process(df)
|
|
37
83
|
|
|
@@ -51,6 +97,7 @@ def to_polars(data: list[dict[str, Any]]):
|
|
|
51
97
|
if not data:
|
|
52
98
|
return pl.DataFrame()
|
|
53
99
|
|
|
100
|
+
data = _flatten_nested_dicts(data)
|
|
54
101
|
df = pl.DataFrame(data)
|
|
55
102
|
|
|
56
103
|
# Parse timestamps
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Helpers for downloading recording files from signed URLs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
_CHUNK_SIZE = 65536 # 64 KB — good balance for large video files
|
|
12
|
+
_UNSAFE_RE = re.compile(r"[^\w\-]")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_download_url(recording: dict[str, Any]) -> str | None:
|
|
16
|
+
"""Return the best download URL from a recording dict, or ``None``."""
|
|
17
|
+
return recording.get("downloadUrl") or recording.get("url") or None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_filename(recording: dict[str, Any]) -> str:
|
|
21
|
+
"""Build a filesystem-safe filename from recording metadata.
|
|
22
|
+
|
|
23
|
+
Pattern: ``{participantName}_{type}_{recordingId}.{ext}``
|
|
24
|
+
"""
|
|
25
|
+
name = recording.get("participantName") or recording.get("participantId") or "unknown"
|
|
26
|
+
name = _UNSAFE_RE.sub("_", name)
|
|
27
|
+
|
|
28
|
+
meta = recording.get("metadata") or {}
|
|
29
|
+
rec_type = meta.get("type") or "recording"
|
|
30
|
+
|
|
31
|
+
rec_id = recording.get("recordingId") or recording.get("egressId") or "unknown"
|
|
32
|
+
|
|
33
|
+
fmt = recording.get("format")
|
|
34
|
+
if not fmt:
|
|
35
|
+
fmt = "webm" if rec_type == "audio" else "mp4"
|
|
36
|
+
|
|
37
|
+
return f"{name}_{rec_type}_{rec_id}.{fmt}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def download_file(url: str, dest: Path, timeout: int = 300) -> int:
|
|
41
|
+
"""Stream-download *url* to *dest* and return bytes written.
|
|
42
|
+
|
|
43
|
+
Verifies ``Content-Length`` (when the server provides it) against bytes
|
|
44
|
+
actually written. On any error — HTTP, mid-stream disconnect, or length
|
|
45
|
+
mismatch — the partial file on disk is removed so ``skip_existing``
|
|
46
|
+
logic won't mistake it for a complete download on retry.
|
|
47
|
+
"""
|
|
48
|
+
resp = requests.get(url, stream=True, timeout=timeout)
|
|
49
|
+
resp.raise_for_status()
|
|
50
|
+
|
|
51
|
+
expected: int | None
|
|
52
|
+
if "Content-Length" in resp.headers:
|
|
53
|
+
try:
|
|
54
|
+
expected = int(resp.headers["Content-Length"])
|
|
55
|
+
except (TypeError, ValueError):
|
|
56
|
+
expected = None
|
|
57
|
+
else:
|
|
58
|
+
expected = None
|
|
59
|
+
|
|
60
|
+
written = 0
|
|
61
|
+
# BaseException so Ctrl-C also cleans up, not just exceptions.
|
|
62
|
+
try:
|
|
63
|
+
with open(dest, "wb") as fh:
|
|
64
|
+
for chunk in resp.iter_content(chunk_size=_CHUNK_SIZE):
|
|
65
|
+
fh.write(chunk)
|
|
66
|
+
written += len(chunk)
|
|
67
|
+
|
|
68
|
+
if expected is not None and written != expected:
|
|
69
|
+
raise IOError(
|
|
70
|
+
f"Truncated download: wrote {written} of {expected} bytes for {dest.name}"
|
|
71
|
+
)
|
|
72
|
+
except BaseException:
|
|
73
|
+
dest.unlink(missing_ok=True)
|
|
74
|
+
raise
|
|
75
|
+
|
|
76
|
+
return written
|
|
@@ -63,8 +63,14 @@ class HttpTransport:
|
|
|
63
63
|
# Public helpers
|
|
64
64
|
# ------------------------------------------------------------------
|
|
65
65
|
|
|
66
|
-
def get(
|
|
67
|
-
|
|
66
|
+
def get(
|
|
67
|
+
self,
|
|
68
|
+
path: str,
|
|
69
|
+
params: dict[str, Any] | None = None,
|
|
70
|
+
*,
|
|
71
|
+
timeout: int | float | None = None,
|
|
72
|
+
) -> dict:
|
|
73
|
+
return self._request("GET", path, params=params, timeout=timeout)
|
|
68
74
|
|
|
69
75
|
def post(self, path: str, json: dict[str, Any] | None = None) -> dict:
|
|
70
76
|
return self._request("POST", path, json=json)
|
|
@@ -81,7 +87,8 @@ class HttpTransport:
|
|
|
81
87
|
|
|
82
88
|
def _request(self, method: str, path: str, **kwargs) -> dict:
|
|
83
89
|
url = f"{self.base_url}/{path.lstrip('/')}"
|
|
84
|
-
kwargs.
|
|
90
|
+
if kwargs.get("timeout") is None:
|
|
91
|
+
kwargs["timeout"] = self.timeout
|
|
85
92
|
|
|
86
93
|
resp = self._session.request(method, url, **kwargs)
|
|
87
94
|
return self._handle_response(resp)
|
|
@@ -16,6 +16,7 @@ def fetch_all_pages(
|
|
|
16
16
|
*,
|
|
17
17
|
page_size: int = 1000,
|
|
18
18
|
progress: bool = True,
|
|
19
|
+
timeout: int | float | None = None,
|
|
19
20
|
) -> tuple[list[dict], dict]:
|
|
20
21
|
"""Fetch every page of a paginated endpoint.
|
|
21
22
|
|
|
@@ -28,7 +29,7 @@ def fetch_all_pages(
|
|
|
28
29
|
params.setdefault("offset", 0)
|
|
29
30
|
|
|
30
31
|
# First request to learn total
|
|
31
|
-
body = transport.get(path, params=params)
|
|
32
|
+
body = transport.get(path, params=params, timeout=timeout)
|
|
32
33
|
metadata = body.get("metadata", {})
|
|
33
34
|
pagination = metadata.get("pagination", {})
|
|
34
35
|
total = pagination.get("total", 0)
|
|
@@ -43,7 +44,7 @@ def fetch_all_pages(
|
|
|
43
44
|
while has_more:
|
|
44
45
|
params["offset"] = pagination.get("nextOffset", params["offset"] + page_size)
|
|
45
46
|
|
|
46
|
-
body = transport.get(path, params=params)
|
|
47
|
+
body = transport.get(path, params=params, timeout=timeout)
|
|
47
48
|
metadata = body.get("metadata", {})
|
|
48
49
|
pagination = metadata.get("pagination", {})
|
|
49
50
|
|
|
@@ -2,12 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import warnings
|
|
6
|
+
from pathlib import Path
|
|
5
7
|
from typing import Any
|
|
6
8
|
|
|
9
|
+
from tqdm.auto import tqdm
|
|
10
|
+
|
|
7
11
|
from ._dataframe import to_pandas, to_polars
|
|
12
|
+
from ._downloads import build_filename, download_file, get_download_url
|
|
8
13
|
from ._http import HttpTransport
|
|
9
14
|
from ._pagination import fetch_all_pages
|
|
10
15
|
from ._types import Scope
|
|
16
|
+
from .exceptions import HyperStudyError
|
|
11
17
|
from .experiments import ExperimentMixin
|
|
12
18
|
|
|
13
19
|
|
|
@@ -466,6 +472,145 @@ class HyperStudy(ExperimentMixin):
|
|
|
466
472
|
"consent": self.get_consent(participant_id, **common),
|
|
467
473
|
}
|
|
468
474
|
|
|
475
|
+
# ------------------------------------------------------------------
|
|
476
|
+
# Recording downloads
|
|
477
|
+
# ------------------------------------------------------------------
|
|
478
|
+
|
|
479
|
+
def download_recording(
|
|
480
|
+
self,
|
|
481
|
+
recording: dict[str, Any],
|
|
482
|
+
output_dir: str = ".",
|
|
483
|
+
) -> Path:
|
|
484
|
+
"""Download a single recording file to disk.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
recording: A recording dict (from ``get_recordings(output="dict")``).
|
|
488
|
+
output_dir: Directory to save the file.
|
|
489
|
+
|
|
490
|
+
Returns:
|
|
491
|
+
Path to the downloaded file.
|
|
492
|
+
"""
|
|
493
|
+
url = get_download_url(recording)
|
|
494
|
+
if not url:
|
|
495
|
+
raise ValueError("Recording has no downloadUrl or url field")
|
|
496
|
+
|
|
497
|
+
dest_dir = Path(output_dir)
|
|
498
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
499
|
+
|
|
500
|
+
filename = build_filename(recording)
|
|
501
|
+
dest = dest_dir / filename
|
|
502
|
+
download_file(url, dest)
|
|
503
|
+
return dest
|
|
504
|
+
|
|
505
|
+
def download_recordings(
|
|
506
|
+
self,
|
|
507
|
+
scope_id: str,
|
|
508
|
+
*,
|
|
509
|
+
output_dir: str,
|
|
510
|
+
scope: str = "experiment",
|
|
511
|
+
deployment_id: str | None = None,
|
|
512
|
+
room_id: str | None = None,
|
|
513
|
+
recording_type: str | None = None,
|
|
514
|
+
progress: bool = True,
|
|
515
|
+
skip_existing: bool = True,
|
|
516
|
+
):
|
|
517
|
+
"""Download recording files to disk.
|
|
518
|
+
|
|
519
|
+
Fetches recording metadata, downloads each file from its signed
|
|
520
|
+
URL, writes a ``recordings_metadata.csv`` sidecar, and returns a
|
|
521
|
+
DataFrame with a ``local_path`` column.
|
|
522
|
+
|
|
523
|
+
Args:
|
|
524
|
+
scope_id: Experiment, room, or participant ID.
|
|
525
|
+
output_dir: Directory to save files.
|
|
526
|
+
scope: ``"experiment"``, ``"room"``, or ``"participant"``.
|
|
527
|
+
deployment_id: Filter by deployment (experiment scope only).
|
|
528
|
+
room_id: Filter by room.
|
|
529
|
+
recording_type: ``"audio"``, ``"video"``, or ``None`` (both).
|
|
530
|
+
progress: Show progress bar.
|
|
531
|
+
skip_existing: Skip files already on disk with matching size.
|
|
532
|
+
|
|
533
|
+
Returns:
|
|
534
|
+
pandas DataFrame with recording metadata plus ``local_path``
|
|
535
|
+
and ``download_status`` columns.
|
|
536
|
+
"""
|
|
537
|
+
try:
|
|
538
|
+
# Signing per-recording GCS URLs scales with count; 30s default is too short.
|
|
539
|
+
recordings = self._fetch_data(
|
|
540
|
+
"recordings",
|
|
541
|
+
scope_id,
|
|
542
|
+
scope=scope,
|
|
543
|
+
deployment_id=deployment_id,
|
|
544
|
+
room_id=room_id,
|
|
545
|
+
output="dict",
|
|
546
|
+
timeout=300,
|
|
547
|
+
)
|
|
548
|
+
except Exception as exc:
|
|
549
|
+
raise HyperStudyError(
|
|
550
|
+
f"Failed to list recordings for {scope}={scope_id!r}: {exc}",
|
|
551
|
+
code=getattr(exc, "code", "LIST_RECORDINGS_FAILED"),
|
|
552
|
+
status_code=getattr(exc, "status_code", None),
|
|
553
|
+
details=getattr(exc, "details", None),
|
|
554
|
+
) from exc
|
|
555
|
+
|
|
556
|
+
if recording_type:
|
|
557
|
+
recordings = [
|
|
558
|
+
r for r in recordings
|
|
559
|
+
if (r.get("metadata") or {}).get("type") == recording_type
|
|
560
|
+
]
|
|
561
|
+
|
|
562
|
+
dest_dir = Path(output_dir)
|
|
563
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
564
|
+
|
|
565
|
+
local_paths: list[str | None] = []
|
|
566
|
+
statuses: list[str] = []
|
|
567
|
+
|
|
568
|
+
for rec in tqdm(recordings, desc="Downloading recordings", disable=not progress):
|
|
569
|
+
filename = build_filename(rec)
|
|
570
|
+
dest = dest_dir / filename
|
|
571
|
+
|
|
572
|
+
url = get_download_url(rec)
|
|
573
|
+
if not url:
|
|
574
|
+
local_paths.append(None)
|
|
575
|
+
statuses.append("failed")
|
|
576
|
+
warnings.warn(f"Recording {rec.get('recordingId')} has no download URL")
|
|
577
|
+
continue
|
|
578
|
+
|
|
579
|
+
if skip_existing and dest.exists():
|
|
580
|
+
expected_size = rec.get("fileSize")
|
|
581
|
+
# Require positive size match; missing size → re-download to
|
|
582
|
+
# avoid trusting a truncated file from a prior failed run.
|
|
583
|
+
if expected_size is not None and dest.stat().st_size == expected_size:
|
|
584
|
+
local_paths.append(str(dest.resolve()))
|
|
585
|
+
statuses.append("skipped")
|
|
586
|
+
continue
|
|
587
|
+
|
|
588
|
+
try:
|
|
589
|
+
download_file(url, dest)
|
|
590
|
+
local_paths.append(str(dest.resolve()))
|
|
591
|
+
statuses.append("downloaded")
|
|
592
|
+
except Exception as exc:
|
|
593
|
+
local_paths.append(None)
|
|
594
|
+
statuses.append("failed")
|
|
595
|
+
warnings.warn(
|
|
596
|
+
f"Failed to download recording {rec.get('recordingId')}: {exc}"
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
failed_count = sum(1 for s in statuses if s == "failed")
|
|
600
|
+
if failed_count:
|
|
601
|
+
warnings.warn(
|
|
602
|
+
f"{failed_count}/{len(recordings)} recordings failed to download; "
|
|
603
|
+
"see the 'download_status' column for per-file results."
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
df = to_pandas(recordings)
|
|
607
|
+
if not df.empty:
|
|
608
|
+
df["local_path"] = local_paths
|
|
609
|
+
df["download_status"] = statuses
|
|
610
|
+
df.to_csv(dest_dir / "recordings_metadata.csv", index=False)
|
|
611
|
+
|
|
612
|
+
return df
|
|
613
|
+
|
|
469
614
|
# ------------------------------------------------------------------
|
|
470
615
|
# Internal helpers
|
|
471
616
|
# ------------------------------------------------------------------
|
|
@@ -525,6 +670,7 @@ class HyperStudy(ExperimentMixin):
|
|
|
525
670
|
offset: int = 0,
|
|
526
671
|
output: str = "pandas",
|
|
527
672
|
progress: bool = True,
|
|
673
|
+
timeout: int | float | None = None,
|
|
528
674
|
**extra_params,
|
|
529
675
|
):
|
|
530
676
|
"""Generic data-fetching logic shared by all ``get_*`` methods."""
|
|
@@ -551,11 +697,15 @@ class HyperStudy(ExperimentMixin):
|
|
|
551
697
|
# Single page or all pages
|
|
552
698
|
if limit is not None:
|
|
553
699
|
params["limit"] = limit
|
|
554
|
-
body = self._transport.get(path, params=params)
|
|
700
|
+
body = self._transport.get(path, params=params, timeout=timeout)
|
|
555
701
|
data = body.get("data", [])
|
|
556
702
|
else:
|
|
557
703
|
data, _ = fetch_all_pages(
|
|
558
|
-
self._transport,
|
|
704
|
+
self._transport,
|
|
705
|
+
path,
|
|
706
|
+
params=params,
|
|
707
|
+
progress=progress,
|
|
708
|
+
timeout=timeout,
|
|
559
709
|
)
|
|
560
710
|
|
|
561
711
|
return self._convert_output(data, output)
|
|
@@ -71,6 +71,16 @@ def deployment_sessions_response():
|
|
|
71
71
|
return load_fixture("deployment_sessions_response.json")
|
|
72
72
|
|
|
73
73
|
|
|
74
|
+
@pytest.fixture
|
|
75
|
+
def sparse_ratings_response():
|
|
76
|
+
return load_fixture("sparse_ratings_response.json")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@pytest.fixture
|
|
80
|
+
def recordings_response():
|
|
81
|
+
return load_fixture("recordings_response.json")
|
|
82
|
+
|
|
83
|
+
|
|
74
84
|
@pytest.fixture
|
|
75
85
|
def warnings_response():
|
|
76
86
|
return load_fixture("warnings_response.json")
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"status": "success",
|
|
3
|
+
"metadata": {
|
|
4
|
+
"dataType": "recordings",
|
|
5
|
+
"scope": "experiment",
|
|
6
|
+
"scopeId": "exp_abc123",
|
|
7
|
+
"timestamp": "2024-06-15T10:00:00.000Z",
|
|
8
|
+
"query": {
|
|
9
|
+
"limit": 1000,
|
|
10
|
+
"offset": 0,
|
|
11
|
+
"sort": "startTime",
|
|
12
|
+
"order": "asc"
|
|
13
|
+
},
|
|
14
|
+
"pagination": {
|
|
15
|
+
"total": 2,
|
|
16
|
+
"returned": 2,
|
|
17
|
+
"hasMore": false,
|
|
18
|
+
"limit": 1000,
|
|
19
|
+
"offset": 0
|
|
20
|
+
},
|
|
21
|
+
"processing": {
|
|
22
|
+
"processingTimeMs": 35,
|
|
23
|
+
"enriched": true,
|
|
24
|
+
"version": "3.0.0"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"data": [
|
|
28
|
+
{
|
|
29
|
+
"recordingId": "EG_video_001",
|
|
30
|
+
"egressId": "EG_video_001",
|
|
31
|
+
"participantId": "user_1",
|
|
32
|
+
"participantName": "Alice",
|
|
33
|
+
"startTime": "2024-06-15T10:00:05.000Z",
|
|
34
|
+
"endTime": "2024-06-15T10:05:05.000Z",
|
|
35
|
+
"duration": 300000,
|
|
36
|
+
"videoOffset": 500,
|
|
37
|
+
"url": "https://storage.googleapis.com/bucket/recordings/video1.mp4",
|
|
38
|
+
"downloadUrl": "https://storage.googleapis.com/bucket/recordings/video1.mp4?X-Goog-Signature=abc",
|
|
39
|
+
"fileSize": 1024,
|
|
40
|
+
"format": "mp4",
|
|
41
|
+
"status": "complete",
|
|
42
|
+
"metadata": {
|
|
43
|
+
"type": "video",
|
|
44
|
+
"recordingType": "individual",
|
|
45
|
+
"roomName": "room_1",
|
|
46
|
+
"experimentId": "exp_abc123"
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"recordingId": "EG_audio_002",
|
|
51
|
+
"egressId": "EG_audio_002",
|
|
52
|
+
"participantId": "user_1",
|
|
53
|
+
"participantName": "Alice",
|
|
54
|
+
"startTime": "2024-06-15T10:00:05.000Z",
|
|
55
|
+
"endTime": "2024-06-15T10:05:05.000Z",
|
|
56
|
+
"duration": 300000,
|
|
57
|
+
"videoOffset": 500,
|
|
58
|
+
"url": "https://storage.googleapis.com/bucket/recordings/audio1.webm",
|
|
59
|
+
"downloadUrl": "https://storage.googleapis.com/bucket/recordings/audio1.webm?X-Goog-Signature=def",
|
|
60
|
+
"fileSize": 512,
|
|
61
|
+
"format": "webm",
|
|
62
|
+
"status": "complete",
|
|
63
|
+
"metadata": {
|
|
64
|
+
"type": "audio",
|
|
65
|
+
"recordingType": "audio",
|
|
66
|
+
"roomName": "room_1",
|
|
67
|
+
"experimentId": "exp_abc123"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
}
|