Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ Signals are written as int16 with a calibration that reproduces every Zarr
sample exactly. The [H5 export guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/bids-zarr/H5_EXPORT.md)
lists what the split format does not carry.

## The bdsp.io website API and the `bdsp` command

The package also includes a client for the bdsp.io API (`bdsp.web`) and the `bdsp` command: `bdsp login`
(with a personal token from Settings → API on bdsp.io), `bdsp ls` (the releases you can read), `bdsp files`,
`bdsp where` (where a release's data are, with an `aws s3 ls` line for S3) and `bdsp get`. It uses only Python's
standard library. See [docs/bdsp-io-client.md](docs/bdsp-io-client.md).

## Further help

The [getting started guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/README.md) covers signals, annotations, features,
Expand Down
39 changes: 39 additions & 0 deletions docs/bdsp-io-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# The bdsp.io API client and the `bdsp` command

For the bdsp.io API v2 (3.2). It uses only Python's standard library (3.9 or later).

## Start

1. On bdsp.io, open **Settings → API** and create a token. It's shown once.
2. `pip install bdsp` (this package), then `bdsp login` and paste the token. It's checked, then saved in
`~/.config/bdsp/token`, readable by you only. Or set `BDSP_TOKEN`.

## Commands

| Command | What it does |
|---|---|
| `bdsp me` | your account: credentialed or not, signed agreements, the token's expiry |
| `bdsp ls` | releases you can read (`--all` for every release, with access; `--modality EEG`, `-q title`) |
| `bdsp files SLUG VERSION [PATH]` | one folder of a release you can read |
| `bdsp where SLUG VERSION` | where its data are: S3 for your account (with an `aws s3 ls` line), GitHub, the website |
| `bdsp get SLUG VERSION PATH [-o OUT] [-r]` | download a file, or a folder with `-r`, from the website's copy |

Large datasets live in S3, not on the website. Use `bdsp where` and the AWS CLI for those, after setting up cloud
access (Settings → Cloud).

The API allows 120 requests a minute per account. The tool waits when it's told to slow down. `get -r` makes one
request per file, so a folder of thousands of small files takes a while.

## In Python

```python
from bdsp.web import Client
client = Client()
for release in client.releases(accessible=True):
print(release['slug'], release['version'], release['title'])
print(client.location('hsp', '3.0'))
```

## Tests

`PYTHONPATH=src python -m unittest discover -s tests`. They run against a small fake of the API, with no network.
6 changes: 4 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ build-backend = "hatchling.build"

[project]
name = "bdsp"
version = "0.5.0"
description = "Python reader for standardized BDSP sleep/PSG Zarr recordings, with a local H5 writer."
version = "0.6.0"
description = "Python reader for standardized BDSP sleep/PSG Zarr recordings, with a local H5 writer, and the bdsp.io API client and command-line tool."
readme = "README.md"
requires-python = ">=3.11"
license = "Apache-2.0"
Expand Down Expand Up @@ -43,6 +43,8 @@ validation = [

[project.scripts]
bdsp-zarr-to-h5 = "bdsp.zarr_to_h5:main"
# the bdsp.io website API client (bdsp.web): bdsp login / me / ls / files / where / get
bdsp = "bdsp.web.cli:main"

[project.urls]
Homepage = "https://bdsp.io/"
Expand Down
2 changes: 1 addition & 1 deletion src/bdsp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
"read_h5",
]

__version__ = "0.5.0"
__version__ = "0.6.0"
7 changes: 7 additions & 0 deletions src/bdsp/web/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Client for the bdsp.io website API (v2): what you can read, its files, and where its data are.

Standard library only. The `bdsp` command (bdsp.web.cli) wraps it. See docs/bdsp-io-client.md.
"""
from bdsp.web.client import ApiError, Client

__all__ = ['ApiError', 'Client']
167 changes: 167 additions & 0 deletions src/bdsp/web/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""bdsp: the bdsp.io command-line tool.

bdsp login store your API token (from bdsp.io, Settings → API)
bdsp me your account and signed agreements
bdsp ls [--all] [--modality EEG] releases you can read (--all: every release, with access)
bdsp files SLUG VERSION [PATH] a folder of a release you can read
bdsp where SLUG VERSION where its data are (S3 locations for your account, GitHub, the website)
bdsp get SLUG VERSION PATH [-o OUT] [-r]
download a file, or a folder with -r (from the website's copy)
"""
import argparse
import getpass
import os
import sys

from bdsp.web.client import ApiError, Client, redirects_elsewhere, save_token


def _print_table(rows, columns):
widths = [max([len(str(c))] + [len(str(r.get(c, ''))) for r in rows]) for c in columns]
print(' '.join(c.upper().ljust(w) for c, w in zip(columns, widths)))
for row in rows:
print(' '.join(str(row.get(c, '')).ljust(w) for c, w in zip(columns, widths)))


def _components(api_path):
"""An API path ('a/b/c.edf') as its names. Refuses anything that could point outside the target folder: empty
names, '.', '..', a leading '/', and backslashes or ':' (a separator or a drive on Windows)."""
parts = api_path.split('/')
if not api_path or any(p in ('', '.', '..') or '\\' in p or ':' in p or '\x00' in p for p in parts):
raise ApiError(400, f'Refusing an unsafe path from the server: {api_path!r}')
return parts


def _safe_target(root, relative_parts):
"""root/relative_parts, creating folders as needed and refusing any step that is (or becomes) a link, so an
existing link inside the target folder can't send a write elsewhere."""
path = root
for part in relative_parts[:-1]:
path = os.path.join(path, part)
if redirects_elsewhere(path):
raise ApiError(400, f'Refusing to write through a link: {path}')
os.makedirs(path, exist_ok=True)
if redirects_elsewhere(path) or not os.path.isdir(path):
raise ApiError(400, f'Refusing to write through a link: {path}')
target = os.path.join(path, relative_parts[-1])
if redirects_elsewhere(target):
raise ApiError(400, f'Refusing to write through a link: {target}')
return target


def cmd_login(args):
token = (sys.stdin.readline() if not sys.stdin.isatty() else getpass.getpass('API token: ')).strip()
if not token.startswith('bdsp_'):
raise ApiError(400, 'That does not look like a bdsp.io API token (they start with "bdsp_").')
account = Client(token=token, url=args.url).me() # check it before saving
print(f'Signed in as {account["username"]}; token saved to {save_token(token)}')


def cmd_me(args):
account = Client(url=args.url).me()
print(f'{account["username"]} credentialed: {"yes" if account["credentialed"] else "no"} '
f'token expires: {account["token_expires"][:10]}')
for agreement in account['signed_agreements']:
print(f' signed: {agreement["release"]} {agreement["signed"][:10]}')


def cmd_ls(args):
rows = list(Client(url=args.url).releases(accessible=not args.all, latest=args.latest, q=args.q,
modality=args.modality, recording_type=args.recording_type))
for row in rows:
row['readable'] = 'yes' if row['can_read'] else 'no'
_print_table(rows, ['slug', 'version', 'access', 'readable', 'title'] if args.all
else ['slug', 'version', 'access', 'title'])


def cmd_files(args):
rows = list(Client(url=args.url).files(args.slug, args.version, args.path or ''))
for row in rows:
row['size'] = '' if row['type'] == 'folder' else row.get('bytes')
_print_table(rows, ['type', 'size', 'path'])


def cmd_where(args):
body = Client(url=args.url).location(args.slug, args.version)
for entry in body['locations']:
print(f'{entry["platform"]}: {entry["s3_uri"]}')
if entry.get('note'):
print(f' note: {entry["note"]}')
print(f' try: aws s3 ls {entry["s3_uri"]}')
if body.get('github'):
print(f'github: {body["github"]}')
if not body['aws_account_on_file']:
print(f'No AWS account on file for you yet: {body["how_to_get_access"]}')
print(f'website files: bdsp files {args.slug} {args.version}')


def cmd_get(args):
client = Client(url=args.url)
if not args.recursive:
name = _components(args.path.strip('/'))[-1]
out = args.output or name
print(f'{args.path} -> {client.download(args.slug, args.version, args.path, out)}')
return
top = args.path.strip('/')
top_parts = _components(top) if top else []
root = os.path.abspath(args.output or (top_parts[-1] if top_parts else f'{args.slug}-{args.version}'))
if redirects_elsewhere(root):
raise ApiError(400, f'Refusing to write through a link: {root}')
os.makedirs(root, exist_ok=True)
pending = [top]
while pending:
folder = pending.pop()
for entry in client.files(args.slug, args.version, folder):
parts = _components(entry['path'])
if parts[:len(top_parts)] != top_parts or len(parts) <= len(top_parts):
raise ApiError(400, f'Refusing a path outside {top or "the release"}: {entry["path"]!r}')
if entry['type'] == 'folder':
pending.append(entry['path'])
continue
target = _safe_target(root, parts[len(top_parts):])
if os.path.isfile(target) and os.path.getsize(target) == entry.get('bytes'):
print(f'{entry["path"]}: already here')
continue
client.download(args.slug, args.version, entry['path'], target)
print(f'{entry["path"]} -> {target}')


def main(argv=None):
parser = argparse.ArgumentParser(prog='bdsp', description='The bdsp.io command-line tool (API v2).')
parser.add_argument('--url', help='the site (default https://bdsp.io, or BDSP_URL)')
commands = parser.add_subparsers(dest='command', required=True)
commands.add_parser('login', help='store your API token').set_defaults(run=cmd_login)
commands.add_parser('me', help='your account').set_defaults(run=cmd_me)
ls = commands.add_parser('ls', help='releases you can read')
ls.add_argument('--all', action='store_true', help='every release, with whether you can read it')
ls.add_argument('--latest', action='store_true', help='latest versions only')
ls.add_argument('-q', help='title contains')
ls.add_argument('--modality')
ls.add_argument('--recording-type', dest='recording_type')
ls.set_defaults(run=cmd_ls)
for name, run, extra in (('files', cmd_files, True), ('where', cmd_where, False)):
sub = commands.add_parser(name)
sub.add_argument('slug')
sub.add_argument('version')
if extra:
sub.add_argument('path', nargs='?', default='')
sub.set_defaults(run=run)
get = commands.add_parser('get', help='download a file, or a folder with -r')
get.add_argument('slug')
get.add_argument('version')
get.add_argument('path')
get.add_argument('-o', '--output')
get.add_argument('-r', '--recursive', action='store_true')
get.set_defaults(run=cmd_get)
args = parser.parse_args(argv)
try:
args.run(args)
except ApiError as error:
print(f'bdsp: {error.message}' + (f' (HTTP {error.status})' if error.status not in (400, 401) else ''),
file=sys.stderr)
return 1
return 0


if __name__ == '__main__':
sys.exit(main())
Loading
Loading