hyperstudy 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """HyperStudy Python SDK — access experiment data from notebooks and scripts.
2
+
3
+ Usage::
4
+
5
+ import hyperstudy
6
+
7
+ hs = hyperstudy.HyperStudy(api_key="hst_live_...")
8
+ events = hs.get_events("experiment_id")
9
+ """
10
+
11
+ from ._types import DataType, RatingKind, Scope
12
+ from .client import HyperStudy
13
+ from .exceptions import (
14
+ AuthenticationError,
15
+ ForbiddenError,
16
+ HyperStudyError,
17
+ NotFoundError,
18
+ ServerError,
19
+ ValidationError,
20
+ )
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "HyperStudy",
26
+ "__version__",
27
+ # Exceptions
28
+ "HyperStudyError",
29
+ "AuthenticationError",
30
+ "ForbiddenError",
31
+ "NotFoundError",
32
+ "ServerError",
33
+ "ValidationError",
34
+ # Enums
35
+ "Scope",
36
+ "DataType",
37
+ "RatingKind",
38
+ ]
@@ -0,0 +1,68 @@
1
+ """DataFrame conversion for API response data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+
9
+
10
+ def _post_process(df: pd.DataFrame) -> pd.DataFrame:
11
+ """Shared post-processing for pandas DataFrames.
12
+
13
+ * Parses timestamp columns to datetime.
14
+ * Computes ``onset_sec`` from ``onset`` (ms -> s).
15
+ """
16
+ if df.empty:
17
+ return df
18
+
19
+ # Parse common timestamp columns
20
+ for col in ("timestamp", "startTime", "endTime", "createdAt", "updatedAt"):
21
+ if col in df.columns:
22
+ df[col] = pd.to_datetime(df[col], errors="coerce")
23
+
24
+ # Compute onset in seconds
25
+ if "onset" in df.columns:
26
+ df["onset_sec"] = pd.to_numeric(df["onset"], errors="coerce") / 1000.0
27
+
28
+ return df
29
+
30
+
31
+ def to_pandas(data: list[dict[str, Any]]) -> pd.DataFrame:
32
+ """Convert API response data to a pandas DataFrame with post-processing."""
33
+ if not data:
34
+ return pd.DataFrame()
35
+ df = pd.DataFrame(data)
36
+ return _post_process(df)
37
+
38
+
39
+ def to_polars(data: list[dict[str, Any]]):
40
+ """Convert API response data to a polars DataFrame.
41
+
42
+ Raises ImportError with a helpful message if polars is not installed.
43
+ """
44
+ try:
45
+ import polars as pl
46
+ except ImportError:
47
+ raise ImportError(
48
+ "polars is not installed. Install it with: pip install hyperstudy[polars]"
49
+ ) from None
50
+
51
+ if not data:
52
+ return pl.DataFrame()
53
+
54
+ df = pl.DataFrame(data)
55
+
56
+ # Parse timestamps
57
+ for col in ("timestamp", "startTime", "endTime", "createdAt", "updatedAt"):
58
+ if col in df.columns:
59
+ try:
60
+ df = df.with_columns(pl.col(col).str.to_datetime(strict=False).alias(col))
61
+ except Exception:
62
+ pass # Column may already be datetime or have unexpected format
63
+
64
+ # Compute onset_sec
65
+ if "onset" in df.columns:
66
+ df = df.with_columns((pl.col("onset").cast(pl.Float64) / 1000.0).alias("onset_sec"))
67
+
68
+ return df
hyperstudy/_display.py ADDED
@@ -0,0 +1,64 @@
1
+ """Rich display helpers for Jupyter and marimo notebooks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class ExperimentInfo:
9
+ """Wrapper around an experiment dict with ``_repr_html_`` for notebooks."""
10
+
11
+ def __init__(self, data: dict[str, Any]):
12
+ self._data = data
13
+
14
+ def __getitem__(self, key):
15
+ return self._data[key]
16
+
17
+ def __contains__(self, key):
18
+ return key in self._data
19
+
20
+ def get(self, key, default=None):
21
+ return self._data.get(key, default)
22
+
23
+ def keys(self):
24
+ return self._data.keys()
25
+
26
+ def values(self):
27
+ return self._data.values()
28
+
29
+ def items(self):
30
+ return self._data.items()
31
+
32
+ def to_dict(self) -> dict[str, Any]:
33
+ return dict(self._data)
34
+
35
+ def __repr__(self):
36
+ name = self._data.get("name", "Unknown")
37
+ eid = self._data.get("id", "?")
38
+ return f"Experiment({eid!r}, name={name!r})"
39
+
40
+ def _repr_html_(self) -> str:
41
+ d = self._data
42
+ rows = ""
43
+ display_fields = [
44
+ ("ID", "id"),
45
+ ("Name", "name"),
46
+ ("Description", "description"),
47
+ ("Owner", "ownerEmail"),
48
+ ("Rooms", "roomCount"),
49
+ ("Participants", "participantCount"),
50
+ ("Created", "createdAt"),
51
+ ("Updated", "updatedAt"),
52
+ ]
53
+ for label, key in display_fields:
54
+ val = d.get(key)
55
+ if val is not None:
56
+ rows += (
57
+ f"<tr><th style='text-align:left;padding:4px 12px 4px 0'>"
58
+ f"{label}</th><td style='padding:4px 0'>{val}</td></tr>"
59
+ )
60
+ return (
61
+ "<div style='font-family:system-ui,sans-serif;max-width:600px'>"
62
+ f"<h4 style='margin:0 0 8px'>Experiment: {d.get('name', '?')}</h4>"
63
+ f"<table style='border-collapse:collapse'>{rows}</table></div>"
64
+ )
hyperstudy/_http.py ADDED
@@ -0,0 +1,128 @@
1
+ """Low-level HTTP transport wrapping requests.Session."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import requests
9
+
10
+ from .exceptions import (
11
+ AuthenticationError,
12
+ ForbiddenError,
13
+ HyperStudyError,
14
+ NotFoundError,
15
+ ServerError,
16
+ ValidationError,
17
+ )
18
+
19
+ _STATUS_MAP = {
20
+ 400: ValidationError,
21
+ 401: AuthenticationError,
22
+ 403: ForbiddenError,
23
+ 404: NotFoundError,
24
+ }
25
+
26
+
27
+ class HttpTransport:
28
+ """Thin wrapper around ``requests.Session`` for the HyperStudy API.
29
+
30
+ * Sets ``X-API-Key`` header on every request.
31
+ * Parses the standard ``{status, metadata, data}`` response envelope.
32
+ * Maps HTTP error codes to typed exceptions.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ api_key: str | None = None,
38
+ base_url: str = "https://api.hyperstudy.io/api/v3",
39
+ timeout: int = 30,
40
+ ):
41
+ resolved_key = api_key or os.environ.get("HYPERSTUDY_API_KEY")
42
+ if not resolved_key:
43
+ raise AuthenticationError(
44
+ "No API key provided. Pass api_key= or set the HYPERSTUDY_API_KEY "
45
+ "environment variable.",
46
+ code="MISSING_API_KEY",
47
+ status_code=401,
48
+ )
49
+
50
+ self.base_url = base_url.rstrip("/")
51
+ self.timeout = timeout
52
+
53
+ self._session = requests.Session()
54
+ self._session.headers.update(
55
+ {
56
+ "X-API-Key": resolved_key,
57
+ "Accept": "application/json",
58
+ }
59
+ )
60
+
61
+ # ------------------------------------------------------------------
62
+ # Public helpers
63
+ # ------------------------------------------------------------------
64
+
65
+ def get(self, path: str, params: dict[str, Any] | None = None) -> dict:
66
+ return self._request("GET", path, params=params)
67
+
68
+ def post(self, path: str, json: dict[str, Any] | None = None) -> dict:
69
+ return self._request("POST", path, json=json)
70
+
71
+ def put(self, path: str, json: dict[str, Any] | None = None) -> dict:
72
+ return self._request("PUT", path, json=json)
73
+
74
+ def delete(self, path: str, params: dict[str, Any] | None = None) -> dict:
75
+ return self._request("DELETE", path, params=params)
76
+
77
+ # ------------------------------------------------------------------
78
+ # Internal
79
+ # ------------------------------------------------------------------
80
+
81
+ def _request(self, method: str, path: str, **kwargs) -> dict:
82
+ url = f"{self.base_url}/{path.lstrip('/')}"
83
+ kwargs.setdefault("timeout", self.timeout)
84
+
85
+ resp = self._session.request(method, url, **kwargs)
86
+ return self._handle_response(resp)
87
+
88
+ @staticmethod
89
+ def _handle_response(resp: requests.Response) -> dict:
90
+ """Parse the JSON envelope and raise on errors."""
91
+ try:
92
+ body = resp.json()
93
+ except ValueError:
94
+ if resp.status_code >= 500:
95
+ raise ServerError(
96
+ f"Server returned {resp.status_code} with non-JSON body",
97
+ code="SERVER_ERROR",
98
+ status_code=resp.status_code,
99
+ )
100
+ raise HyperStudyError(
101
+ f"Unexpected non-JSON response ({resp.status_code})",
102
+ status_code=resp.status_code,
103
+ )
104
+
105
+ # API-level error envelope: {"status": "error", "error": {...}}
106
+ if body.get("status") == "error":
107
+ err = body.get("error", {})
108
+ message = err.get("message", resp.reason or "Unknown error")
109
+ code = err.get("code", "UNKNOWN")
110
+ details = err.get("details")
111
+ exc_cls = _STATUS_MAP.get(resp.status_code, HyperStudyError)
112
+ if resp.status_code >= 500:
113
+ exc_cls = ServerError
114
+ raise exc_cls(
115
+ message, code=code, status_code=resp.status_code, details=details
116
+ )
117
+
118
+ # Non-2xx without error envelope
119
+ if not resp.ok:
120
+ exc_cls = _STATUS_MAP.get(resp.status_code, HyperStudyError)
121
+ if resp.status_code >= 500:
122
+ exc_cls = ServerError
123
+ raise exc_cls(
124
+ resp.reason or f"HTTP {resp.status_code}",
125
+ status_code=resp.status_code,
126
+ )
127
+
128
+ return body
@@ -0,0 +1,61 @@
1
+ """Auto-pagination with progress bars for multi-page fetches."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from tqdm.auto import tqdm
8
+
9
+ from ._http import HttpTransport
10
+
11
+
12
+ def fetch_all_pages(
13
+ transport: HttpTransport,
14
+ path: str,
15
+ params: dict[str, Any] | None = None,
16
+ *,
17
+ page_size: int = 1000,
18
+ progress: bool = True,
19
+ ) -> tuple[list[dict], dict]:
20
+ """Fetch every page of a paginated endpoint.
21
+
22
+ Returns:
23
+ (all_data, last_metadata) — the combined list plus the metadata
24
+ dict from the final page (useful for inspecting total counts, etc.).
25
+ """
26
+ params = dict(params or {})
27
+ params["limit"] = page_size
28
+ params.setdefault("offset", 0)
29
+
30
+ # First request to learn total
31
+ body = transport.get(path, params=params)
32
+ metadata = body.get("metadata", {})
33
+ pagination = metadata.get("pagination", {})
34
+ total = pagination.get("total", 0)
35
+ all_data: list[dict] = body.get("data", [])
36
+
37
+ has_more = pagination.get("hasMore", False)
38
+
39
+ bar = None
40
+ if progress and total > page_size:
41
+ bar = tqdm(total=total, desc="Fetching", unit=" rows", initial=len(all_data))
42
+
43
+ while has_more:
44
+ params["offset"] = pagination.get("nextOffset", params["offset"] + page_size)
45
+
46
+ body = transport.get(path, params=params)
47
+ metadata = body.get("metadata", {})
48
+ pagination = metadata.get("pagination", {})
49
+
50
+ page_data = body.get("data", [])
51
+ all_data.extend(page_data)
52
+ has_more = pagination.get("hasMore", False)
53
+
54
+ if bar is not None:
55
+ bar.update(len(page_data))
56
+
57
+ if bar is not None:
58
+ bar.update(bar.total - bar.n) # snap to 100 %
59
+ bar.close()
60
+
61
+ return all_data, metadata
hyperstudy/_types.py ADDED
@@ -0,0 +1,30 @@
1
+ """Enums for the HyperStudy API.
2
+
3
+ All enums inherit from (str, Enum) so users can pass either
4
+ Scope.EXPERIMENT or the plain string "experiment".
5
+ """
6
+
7
+ from enum import Enum
8
+
9
+
10
+ class Scope(str, Enum):
11
+ EXPERIMENT = "experiment"
12
+ ROOM = "room"
13
+ PARTICIPANT = "participant"
14
+
15
+
16
+ class DataType(str, Enum):
17
+ EVENTS = "events"
18
+ RECORDINGS = "recordings"
19
+ CHAT = "chat"
20
+ VIDEOCHAT = "videochat"
21
+ SYNC = "sync"
22
+ RATINGS = "ratings"
23
+ COMPONENTS = "components"
24
+ PARTICIPANTS = "participants"
25
+ ROOMS = "rooms"
26
+
27
+
28
+ class RatingKind(str, Enum):
29
+ CONTINUOUS = "continuous"
30
+ SPARSE = "sparse"
hyperstudy/client.py ADDED
@@ -0,0 +1,368 @@
1
+ """Main HyperStudy client — the primary entry point for the SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ._dataframe import to_pandas, to_polars
8
+ from ._http import HttpTransport
9
+ from ._pagination import fetch_all_pages
10
+ from ._types import Scope
11
+ from .experiments import ExperimentMixin
12
+
13
+
14
+ class HyperStudy(ExperimentMixin):
15
+ """Client for the HyperStudy API v3.
16
+
17
+ Args:
18
+ api_key: Your API key (``hst_live_...`` or ``hst_test_...``).
19
+ Also reads the ``HYPERSTUDY_API_KEY`` environment variable.
20
+ base_url: API base URL. Defaults to the production endpoint.
21
+ timeout: Request timeout in seconds.
22
+
23
+ Example::
24
+
25
+ import hyperstudy
26
+
27
+ hs = hyperstudy.HyperStudy(api_key="hst_live_...")
28
+ events = hs.get_events("experiment_id")
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ api_key: str | None = None,
34
+ base_url: str = "https://api.hyperstudy.io/api/v3",
35
+ timeout: int = 30,
36
+ ):
37
+ self._transport = HttpTransport(
38
+ api_key=api_key, base_url=base_url, timeout=timeout
39
+ )
40
+
41
+ # ------------------------------------------------------------------
42
+ # Health
43
+ # ------------------------------------------------------------------
44
+
45
+ def health(self) -> dict[str, Any]:
46
+ """Check API connectivity and version."""
47
+ return self._transport.get("health")
48
+
49
+ # ------------------------------------------------------------------
50
+ # Data retrieval — one method per data type
51
+ # ------------------------------------------------------------------
52
+
53
+ def get_events(
54
+ self,
55
+ scope_id: str,
56
+ *,
57
+ scope: str = "experiment",
58
+ room_id: str | None = None,
59
+ start_time: str | None = None,
60
+ end_time: str | None = None,
61
+ category: str | None = None,
62
+ sort: str | None = None,
63
+ order: str | None = None,
64
+ limit: int | None = None,
65
+ offset: int = 0,
66
+ output: str = "pandas",
67
+ progress: bool = True,
68
+ ):
69
+ """Fetch experiment events.
70
+
71
+ Args:
72
+ scope_id: ID of the experiment, room, or participant.
73
+ scope: ``"experiment"``, ``"room"``, or ``"participant"``.
74
+ room_id: Required when ``scope="participant"``.
75
+ start_time: ISO 8601 start filter.
76
+ end_time: ISO 8601 end filter.
77
+ category: Event category filter.
78
+ sort: Sort field (e.g. ``"onset"``, ``"timestamp"``).
79
+ order: ``"asc"`` or ``"desc"``.
80
+ limit: Max records. ``None`` fetches all pages.
81
+ offset: Starting offset.
82
+ output: ``"pandas"`` (default), ``"polars"``, or ``"dict"``.
83
+ progress: Show progress bar when paginating.
84
+ """
85
+ return self._fetch_data(
86
+ "events", scope_id,
87
+ scope=scope, room_id=room_id,
88
+ start_time=start_time, end_time=end_time,
89
+ category=category, sort=sort, order=order,
90
+ limit=limit, offset=offset,
91
+ output=output, progress=progress,
92
+ )
93
+
94
+ def get_recordings(
95
+ self,
96
+ scope_id: str,
97
+ *,
98
+ scope: str = "experiment",
99
+ room_id: str | None = None,
100
+ limit: int | None = None,
101
+ offset: int = 0,
102
+ output: str = "pandas",
103
+ progress: bool = True,
104
+ ):
105
+ """Fetch video/audio recording metadata."""
106
+ return self._fetch_data(
107
+ "recordings", scope_id,
108
+ scope=scope, room_id=room_id,
109
+ limit=limit, offset=offset,
110
+ output=output, progress=progress,
111
+ )
112
+
113
+ def get_chat(
114
+ self,
115
+ scope_id: str,
116
+ *,
117
+ scope: str = "experiment",
118
+ room_id: str | None = None,
119
+ start_time: str | None = None,
120
+ end_time: str | None = None,
121
+ sort: str | None = None,
122
+ order: str | None = None,
123
+ limit: int | None = None,
124
+ offset: int = 0,
125
+ output: str = "pandas",
126
+ progress: bool = True,
127
+ ):
128
+ """Fetch text chat messages."""
129
+ return self._fetch_data(
130
+ "chat", scope_id,
131
+ scope=scope, room_id=room_id,
132
+ start_time=start_time, end_time=end_time,
133
+ sort=sort, order=order,
134
+ limit=limit, offset=offset,
135
+ output=output, progress=progress,
136
+ )
137
+
138
+ def get_videochat(
139
+ self,
140
+ scope_id: str,
141
+ *,
142
+ scope: str = "experiment",
143
+ room_id: str | None = None,
144
+ start_time: str | None = None,
145
+ end_time: str | None = None,
146
+ sort: str | None = None,
147
+ order: str | None = None,
148
+ limit: int | None = None,
149
+ offset: int = 0,
150
+ output: str = "pandas",
151
+ progress: bool = True,
152
+ ):
153
+ """Fetch LiveKit video chat connection data."""
154
+ return self._fetch_data(
155
+ "videochat", scope_id,
156
+ scope=scope, room_id=room_id,
157
+ start_time=start_time, end_time=end_time,
158
+ sort=sort, order=order,
159
+ limit=limit, offset=offset,
160
+ output=output, progress=progress,
161
+ )
162
+
163
+ def get_sync(
164
+ self,
165
+ scope_id: str,
166
+ *,
167
+ scope: str = "experiment",
168
+ room_id: str | None = None,
169
+ start_time: str | None = None,
170
+ end_time: str | None = None,
171
+ aggregation_window: int | None = None,
172
+ sort: str | None = None,
173
+ order: str | None = None,
174
+ limit: int | None = None,
175
+ offset: int = 0,
176
+ output: str = "pandas",
177
+ progress: bool = True,
178
+ ):
179
+ """Fetch media synchronization metrics."""
180
+ extra: dict[str, Any] = {}
181
+ if aggregation_window is not None:
182
+ extra["aggregationWindow"] = aggregation_window
183
+ return self._fetch_data(
184
+ "sync", scope_id,
185
+ scope=scope, room_id=room_id,
186
+ start_time=start_time, end_time=end_time,
187
+ sort=sort, order=order,
188
+ limit=limit, offset=offset,
189
+ output=output, progress=progress,
190
+ **extra,
191
+ )
192
+
193
+ def get_ratings(
194
+ self,
195
+ scope_id: str,
196
+ *,
197
+ kind: str = "continuous",
198
+ scope: str = "experiment",
199
+ room_id: str | None = None,
200
+ start_time: str | None = None,
201
+ end_time: str | None = None,
202
+ sort: str | None = None,
203
+ order: str | None = None,
204
+ limit: int | None = None,
205
+ offset: int = 0,
206
+ output: str = "pandas",
207
+ progress: bool = True,
208
+ ):
209
+ """Fetch rating data.
210
+
211
+ Args:
212
+ kind: ``"continuous"`` (slider) or ``"sparse"`` (button-press).
213
+ *: All other args are the same as :meth:`get_events`.
214
+ """
215
+ return self._fetch_data(
216
+ f"ratings/{kind}", scope_id,
217
+ scope=scope, room_id=room_id,
218
+ start_time=start_time, end_time=end_time,
219
+ sort=sort, order=order,
220
+ limit=limit, offset=offset,
221
+ output=output, progress=progress,
222
+ )
223
+
224
+ def get_components(
225
+ self,
226
+ scope_id: str,
227
+ *,
228
+ scope: str = "experiment",
229
+ room_id: str | None = None,
230
+ limit: int | None = None,
231
+ offset: int = 0,
232
+ output: str = "pandas",
233
+ progress: bool = True,
234
+ ):
235
+ """Fetch component response data."""
236
+ return self._fetch_data(
237
+ "components", scope_id,
238
+ scope=scope, room_id=room_id,
239
+ limit=limit, offset=offset,
240
+ output=output, progress=progress,
241
+ )
242
+
243
+ def get_participants(
244
+ self,
245
+ scope_id: str,
246
+ *,
247
+ scope: str = "experiment",
248
+ room_id: str | None = None,
249
+ limit: int | None = None,
250
+ offset: int = 0,
251
+ output: str = "pandas",
252
+ progress: bool = True,
253
+ ):
254
+ """Fetch participant data."""
255
+ return self._fetch_data(
256
+ "participants", scope_id,
257
+ scope=scope, room_id=room_id,
258
+ limit=limit, offset=offset,
259
+ output=output, progress=progress,
260
+ )
261
+
262
+ def get_rooms(
263
+ self,
264
+ scope_id: str,
265
+ *,
266
+ scope: str = "experiment",
267
+ limit: int | None = None,
268
+ offset: int = 0,
269
+ output: str = "pandas",
270
+ progress: bool = True,
271
+ ):
272
+ """Fetch room/session data."""
273
+ return self._fetch_data(
274
+ "rooms", scope_id,
275
+ scope=scope,
276
+ limit=limit, offset=offset,
277
+ output=output, progress=progress,
278
+ )
279
+
280
+ # ------------------------------------------------------------------
281
+ # Convenience: all data for a participant
282
+ # ------------------------------------------------------------------
283
+
284
+ def get_all_data(
285
+ self,
286
+ participant_id: str,
287
+ *,
288
+ room_id: str,
289
+ output: str = "pandas",
290
+ ) -> dict:
291
+ """Fetch all data types for one participant in a room.
292
+
293
+ Returns:
294
+ Dict mapping data type names to DataFrames (or dicts).
295
+ """
296
+ common = dict(scope="participant", room_id=room_id, output=output, progress=False)
297
+ return {
298
+ "events": self.get_events(participant_id, **common),
299
+ "recordings": self.get_recordings(participant_id, **common),
300
+ "chat": self.get_chat(participant_id, **common),
301
+ "videochat": self.get_videochat(participant_id, **common),
302
+ "sync": self.get_sync(participant_id, **common),
303
+ "ratings": self.get_ratings(participant_id, kind="continuous", **common),
304
+ "components": self.get_components(participant_id, **common),
305
+ }
306
+
307
+ # ------------------------------------------------------------------
308
+ # Internal helpers
309
+ # ------------------------------------------------------------------
310
+
311
+ def _fetch_data(
312
+ self,
313
+ data_type: str,
314
+ scope_id: str,
315
+ *,
316
+ scope: str = "experiment",
317
+ room_id: str | None = None,
318
+ start_time: str | None = None,
319
+ end_time: str | None = None,
320
+ category: str | None = None,
321
+ sort: str | None = None,
322
+ order: str | None = None,
323
+ limit: int | None = None,
324
+ offset: int = 0,
325
+ output: str = "pandas",
326
+ progress: bool = True,
327
+ **extra_params,
328
+ ):
329
+ """Generic data-fetching logic shared by all ``get_*`` methods."""
330
+ scope_val = Scope(scope)
331
+ path = f"data/{data_type}/{scope_val.value}/{scope_id}"
332
+
333
+ params: dict[str, Any] = {"offset": offset}
334
+ if room_id:
335
+ params["roomId"] = room_id
336
+ if start_time:
337
+ params["startTime"] = start_time
338
+ if end_time:
339
+ params["endTime"] = end_time
340
+ if category:
341
+ params["category"] = category
342
+ if sort:
343
+ params["sort"] = sort
344
+ if order:
345
+ params["order"] = order
346
+ params.update(extra_params)
347
+
348
+ # Single page or all pages
349
+ if limit is not None:
350
+ params["limit"] = limit
351
+ body = self._transport.get(path, params=params)
352
+ data = body.get("data", [])
353
+ else:
354
+ data, _ = fetch_all_pages(
355
+ self._transport, path, params=params, progress=progress
356
+ )
357
+
358
+ return self._convert_output(data, output)
359
+
360
+ @staticmethod
361
+ def _convert_output(data: list[dict], output: str):
362
+ """Convert raw dicts to the requested output format."""
363
+ if output == "dict":
364
+ return data
365
+ if output == "polars":
366
+ return to_polars(data)
367
+ # Default: pandas
368
+ return to_pandas(data)
@@ -0,0 +1,58 @@
1
+ """Typed exceptions for HyperStudy API errors."""
2
+
3
+
4
+ class HyperStudyError(Exception):
5
+ """Base exception for all HyperStudy API errors.
6
+
7
+ Attributes:
8
+ message: Human-readable error description.
9
+ code: Machine-readable error code from the API (e.g. 'VALIDATION_ERROR').
10
+ status_code: HTTP status code.
11
+ details: Optional dict with additional error context.
12
+ """
13
+
14
+ def __init__(self, message, *, code=None, status_code=None, details=None):
15
+ super().__init__(message)
16
+ self.message = message
17
+ self.code = code
18
+ self.status_code = status_code
19
+ self.details = details or {}
20
+
21
+ def __repr__(self):
22
+ parts = [f"HyperStudyError({self.message!r}"]
23
+ if self.code:
24
+ parts[0] = f"{type(self).__name__}({self.message!r}"
25
+ parts.append(f"code={self.code!r}")
26
+ if self.status_code:
27
+ parts.append(f"status_code={self.status_code}")
28
+ return ", ".join(parts) + ")"
29
+
30
+
31
+ class AuthenticationError(HyperStudyError):
32
+ """Raised on 401 — invalid or missing API key."""
33
+
34
+ pass
35
+
36
+
37
+ class ForbiddenError(HyperStudyError):
38
+ """Raised on 403 — valid key but insufficient scopes or access."""
39
+
40
+ pass
41
+
42
+
43
+ class NotFoundError(HyperStudyError):
44
+ """Raised on 404 — resource does not exist."""
45
+
46
+ pass
47
+
48
+
49
+ class ValidationError(HyperStudyError):
50
+ """Raised on 400 — invalid request parameters."""
51
+
52
+ pass
53
+
54
+
55
+ class ServerError(HyperStudyError):
56
+ """Raised on 5xx — server-side failure."""
57
+
58
+ pass
@@ -0,0 +1,125 @@
1
+ """Experiment CRUD methods (mixed into HyperStudy via inheritance)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ._display import ExperimentInfo
8
+ from ._http import HttpTransport
9
+ from ._pagination import fetch_all_pages
10
+
11
+
12
+ class ExperimentMixin:
13
+ """Methods for experiment management. Mixed into the main client."""
14
+
15
+ _transport: HttpTransport
16
+
17
+ # ------------------------------------------------------------------
18
+ # Read
19
+ # ------------------------------------------------------------------
20
+
21
+ def list_experiments(
22
+ self,
23
+ *,
24
+ search: str | None = None,
25
+ limit: int | None = None,
26
+ offset: int = 0,
27
+ output: str = "pandas",
28
+ progress: bool = True,
29
+ ):
30
+ """List experiments accessible to the authenticated user.
31
+
32
+ Args:
33
+ search: Filter experiments by name/description substring.
34
+ limit: Max experiments to return. ``None`` fetches all pages.
35
+ offset: Starting offset for pagination.
36
+ output: ``"pandas"`` (default), ``"polars"``, or ``"dict"``.
37
+ progress: Show progress bar when paginating.
38
+
39
+ Returns:
40
+ DataFrame or list of dicts depending on *output*.
41
+ """
42
+ params: dict[str, Any] = {"offset": offset}
43
+ if search:
44
+ params["search"] = search
45
+
46
+ if limit is not None:
47
+ params["limit"] = limit
48
+ body = self._transport.get("experiments", params=params)
49
+ data = body.get("data", [])
50
+ else:
51
+ data, _ = fetch_all_pages(
52
+ self._transport,
53
+ "experiments",
54
+ params=params,
55
+ page_size=50,
56
+ progress=progress,
57
+ )
58
+
59
+ return self._convert_output(data, output)
60
+
61
+ def get_experiment(self, experiment_id: str) -> ExperimentInfo:
62
+ """Get a single experiment with enriched metadata.
63
+
64
+ Returns:
65
+ An :class:`ExperimentInfo` object (dict-like, with ``_repr_html_``).
66
+ """
67
+ body = self._transport.get(f"experiments/{experiment_id}")
68
+ data = body.get("data", [])
69
+ record = data[0] if isinstance(data, list) and data else data
70
+ return ExperimentInfo(record)
71
+
72
+ def get_experiment_config(self, experiment_id: str) -> dict[str, Any]:
73
+ """Get raw experiment config (lightweight, no enrichment)."""
74
+ body = self._transport.get(f"experiments/{experiment_id}/config")
75
+ data = body.get("data", [])
76
+ return data[0] if isinstance(data, list) and data else data
77
+
78
+ # ------------------------------------------------------------------
79
+ # Write
80
+ # ------------------------------------------------------------------
81
+
82
+ def create_experiment(self, *, name: str, **kwargs) -> ExperimentInfo:
83
+ """Create a new experiment.
84
+
85
+ Args:
86
+ name: Experiment name (required).
87
+ **kwargs: Additional fields (config, states, roles, description, etc.).
88
+
89
+ Returns:
90
+ The created :class:`ExperimentInfo`.
91
+ """
92
+ payload = {"name": name, **kwargs}
93
+ body = self._transport.post("experiments", json=payload)
94
+ data = body.get("data", [])
95
+ record = data[0] if isinstance(data, list) and data else data
96
+ return ExperimentInfo(record)
97
+
98
+ def update_experiment(self, experiment_id: str, **kwargs) -> dict[str, Any]:
99
+ """Update an experiment.
100
+
101
+ Args:
102
+ experiment_id: ID of the experiment to update.
103
+ **kwargs: Fields to update (name, config, states, etc.).
104
+
105
+ Returns:
106
+ Update confirmation dict.
107
+ """
108
+ body = self._transport.put(f"experiments/{experiment_id}", json=kwargs)
109
+ data = body.get("data", [])
110
+ return data[0] if isinstance(data, list) and data else data
111
+
112
+ def delete_experiment(
113
+ self, experiment_id: str, *, skip_data_check: bool = False
114
+ ) -> None:
115
+ """Delete (soft-delete) an experiment.
116
+
117
+ Args:
118
+ experiment_id: ID of the experiment to delete.
119
+ skip_data_check: If True, skip the confirmation check for experiments
120
+ with collected data.
121
+ """
122
+ params = {}
123
+ if skip_data_check:
124
+ params["skipDataCheck"] = "true"
125
+ self._transport.delete(f"experiments/{experiment_id}", params=params)
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: hyperstudy
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the HyperStudy experiment platform API
5
+ Project-URL: Homepage, https://hyperstudy.io
6
+ Project-URL: Documentation, https://docs.hyperstudy.io/developers/python-sdk
7
+ Project-URL: Repository, https://github.com/ljchang/hyperstudy-pythonsdk
8
+ Project-URL: Issues, https://github.com/ljchang/hyperstudy-pythonsdk/issues
9
+ Author-email: Luke Chang <luke.j.chang@dartmouth.edu>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: pandas>=1.5.0
23
+ Requires-Dist: requests>=2.28.0
24
+ Requires-Dist: tqdm>=4.60.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest-cov; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: responses>=0.23.0; extra == 'dev'
29
+ Requires-Dist: ruff; extra == 'dev'
30
+ Provides-Extra: polars
31
+ Requires-Dist: polars>=0.20.0; extra == 'polars'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # hyperstudy
35
+
36
+ Python SDK for the [HyperStudy](https://hyperstudy.io) experiment platform API. Designed for researchers working in Jupyter, marimo, or Python scripts.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install hyperstudy
42
+ ```
43
+
44
+ For polars support:
45
+
46
+ ```bash
47
+ pip install hyperstudy[polars]
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ```python
53
+ import hyperstudy
54
+
55
+ hs = hyperstudy.HyperStudy(api_key="hst_live_...")
56
+ # Or set the HYPERSTUDY_API_KEY environment variable
57
+
58
+ # Fetch events as a pandas DataFrame
59
+ events = hs.get_events("your_experiment_id")
60
+
61
+ # Room-scoped data
62
+ events = hs.get_events("room_id", scope="room")
63
+
64
+ # Participant-scoped data
65
+ events = hs.get_events("participant_id", scope="participant", room_id="room_id")
66
+ ```
67
+
68
+ ## Data Types
69
+
70
+ All data retrieval methods follow the same pattern:
71
+
72
+ ```python
73
+ events = hs.get_events("exp_id")
74
+ recordings = hs.get_recordings("exp_id")
75
+ chat = hs.get_chat("exp_id")
76
+ videochat = hs.get_videochat("exp_id")
77
+ sync = hs.get_sync("exp_id")
78
+ ratings = hs.get_ratings("exp_id", kind="continuous")
79
+ components = hs.get_components("exp_id")
80
+ participants = hs.get_participants("exp_id")
81
+ rooms = hs.get_rooms("exp_id")
82
+ ```
83
+
84
+ ### Output Formats
85
+
86
+ ```python
87
+ df_pandas = hs.get_events("exp_id") # pandas (default)
88
+ df_polars = hs.get_events("exp_id", output="polars") # polars
89
+ raw = hs.get_events("exp_id", output="dict") # list[dict]
90
+ ```
91
+
92
+ ### Filtering
93
+
94
+ ```python
95
+ events = hs.get_events(
96
+ "exp_id",
97
+ start_time="2024-01-01T10:00:00Z",
98
+ end_time="2024-01-01T12:00:00Z",
99
+ category="component",
100
+ sort="onset",
101
+ limit=100,
102
+ )
103
+ ```
104
+
105
+ ### Auto-Pagination
106
+
107
+ When `limit` is not set, all pages are fetched automatically with a progress bar:
108
+
109
+ ```python
110
+ all_events = hs.get_events("exp_id") # fetches all pages
111
+ ```
112
+
113
+ ## Experiment Management
114
+
115
+ ```python
116
+ # List experiments
117
+ experiments = hs.list_experiments()
118
+
119
+ # Get details (with rich display in notebooks)
120
+ exp = hs.get_experiment("exp_id")
121
+
122
+ # Create / update / delete
123
+ new_exp = hs.create_experiment(name="My Study", description="...")
124
+ hs.update_experiment("exp_id", name="Updated Name")
125
+ hs.delete_experiment("exp_id")
126
+ ```
127
+
128
+ ## All Data for a Participant
129
+
130
+ ```python
131
+ data = hs.get_all_data("participant_id", room_id="room_id")
132
+ # Returns: {"events": DataFrame, "recordings": DataFrame, "chat": DataFrame, ...}
133
+ ```
134
+
135
+ ## API Key
136
+
137
+ Generate an API key from the HyperStudy dashboard under Settings. Keys follow the format `hst_{environment}_{key}` and are passed via the `X-API-Key` header.
138
+
139
+ ## Documentation
140
+
141
+ Full documentation: [docs.hyperstudy.io/developers/python-sdk](https://docs.hyperstudy.io/developers/python-sdk)
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ git clone https://github.com/ljchang/hyperstudy-pythonsdk.git
147
+ cd hyperstudy-pythonsdk
148
+ pip install -e ".[dev,polars]"
149
+ pytest --cov=hyperstudy
150
+ ruff check src/
151
+ ```
152
+
153
+ ## License
154
+
155
+ MIT
@@ -0,0 +1,13 @@
1
+ hyperstudy/__init__.py,sha256=HG3ZO_xJEDLMDvmAdv4DtADVxph7yWCPS1LqJUs9ebQ,733
2
+ hyperstudy/_dataframe.py,sha256=gOHPE6RRoZ_a4Qkdl9XykkGTqH6I7P6pedKoFuAvKek,1966
3
+ hyperstudy/_display.py,sha256=5svr4NFOUJkVif57-xJzrXNOSdA5O9tKesu8UhE_jYo,1896
4
+ hyperstudy/_http.py,sha256=PjDaS1gMENJFUk2WxzN9yyEppO-tITkQnUVGHAj3ocU,4242
5
+ hyperstudy/_pagination.py,sha256=Fdr2nW84r6NtXiYQs5jyJEUOjFvXl-RclpDIi-SPDlM,1738
6
+ hyperstudy/_types.py,sha256=22JTOlM68eGJ4hg4OH-oT-hmARG2CgbhnERJ5hGxHk8,614
7
+ hyperstudy/client.py,sha256=0dw7dfFQ7bv1rIdSa7STFX4VHJpuFZ6h7HOWGO5uiU0,11633
8
+ hyperstudy/exceptions.py,sha256=z_1Ngiq-RU-1yyDI_JqvQ5CvYm2jQ_lyJ9TUbqUKKv8,1529
9
+ hyperstudy/experiments.py,sha256=BHNf-ctKUA9uzy8Kya11nIyHPrsmOslqC_IJ5t4LxKA,4372
10
+ hyperstudy-0.1.0.dist-info/METADATA,sha256=sQ4zPFcGv1tMruM37yMLXWkqfF9IORAJClVwxmtyrY0,4176
11
+ hyperstudy-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
12
+ hyperstudy-0.1.0.dist-info/licenses/LICENSE,sha256=WJdwRhBIOiiQ6lyK4l95u5IJYuuT-XxzwYRraS31NME,1067
13
+ hyperstudy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Luke Chang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.