readdata 0.1.0__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.
readdata-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcos Duarte
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.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: readdata
3
+ Version: 0.1.0
4
+ Summary: Read files and structured data releases locally, over HTTP, from GitHub/Zenodo, or in the browser
5
+ Author-email: Marcos Duarte <duartexyz@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/demotu/readdata
8
+ Project-URL: Documentation, https://github.com/demotu/readdata#readme
9
+ Project-URL: Issues, https://github.com/demotu/readdata/issues
10
+ Keywords: data,datasets,zenodo,github,duckdb,parquet,marimo,pyodide,reproducibility
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: urllib3>=2
19
+ Provides-Extra: http
20
+ Requires-Dist: fsspec[http]; sys_platform != "emscripten" and extra == "http"
21
+ Requires-Dist: fsspec; sys_platform == "emscripten" and extra == "http"
22
+ Provides-Extra: release
23
+ Requires-Dist: fsspec[http]; sys_platform != "emscripten" and extra == "release"
24
+ Requires-Dist: fsspec; sys_platform == "emscripten" and extra == "release"
25
+ Requires-Dist: duckdb; extra == "release"
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest; extra == "test"
28
+ Requires-Dist: duckdb; extra == "test"
29
+ Requires-Dist: fsspec[http]; extra == "test"
30
+ Dynamic: license-file
31
+
32
+ # [readdata](https://pypi.org/project/readdata/)
33
+
34
+ Read repository files and structured data releases transparently—locally, over HTTP(S), from GitHub or Zenodo, or in the browser (Pyodide / marimo WebAssembly).
35
+
36
+ `readdata` provides two small, complementary APIs with isolated dependencies:
37
+
38
+ 1. **`Repo` / `repo_file`** *(core — `urllib3` only)*: resolve individual repository files (`.csv`, `.trc`, `.c3d`, `.txt`, images, archives) locally first, falling back to an atomic cached HTTP(S) download with optional SHA-256 verification.
39
+ 2. **`Release`** *(optional `[release]` extra — `duckdb` + `fsspec`)*: open manifest-backed data releases (`metadata.json`) from a local directory, an HTTP mirror, or a numbered Zenodo record with lazy DuckDB SQL views over Parquet and seekable binary streams (including byte-range reads in Pyodide).
40
+
41
+ ## Installation
42
+
43
+ For repository/notebook file access (lightweight, pure Python):
44
+
45
+ ```bash
46
+ pip install readdata
47
+ ```
48
+
49
+ For manifest-backed Parquet/DuckDB releases and remote streaming:
50
+
51
+ ```bash
52
+ pip install "readdata[release]"
53
+ ```
54
+
55
+ For remote binary streaming without DuckDB:
56
+
57
+ ```bash
58
+ pip install "readdata[http]"
59
+ ```
60
+
61
+ ## 1. Repository files (`Repo` & `repo_file`)
62
+
63
+ Designed for notebooks and scripts that should read a local checkout when present and automatically fetch a temporary cached copy when opened standalone (e.g., in `molab`, `marimo.app`, Google Colab, or GitHub Pages WebAssembly):
64
+
65
+ ```python
66
+ from readdata import Repo, repo_file
67
+
68
+ # Configure a GitHub repository once (e.g., in a BMC tutorial notebook)
69
+ bmc = Repo.github("BMClab/BMC", ref="master")
70
+ walk = bmc.file("data/walk.trc")
71
+
72
+ # Optional SHA-256 verification
73
+ sample = bmc.file("data/walk.trc", sha256="...")
74
+
75
+ # Or resolve a single file directly from any HTTP(S) base URL
76
+ path = repo_file(
77
+ "data/walk.trc",
78
+ base_url="https://raw.githubusercontent.com/BMClab/BMC/master/",
79
+ )
80
+ ```
81
+
82
+ Local lookup walks upward from `start_dir` (defaulting to `marimo.notebook_dir()` when running inside marimo, otherwise the current working directory). Pass `local=False` to force fetching from the remote URL.
83
+
84
+ ## 2. Structured data releases (`Release`)
85
+
86
+ Designed for versioned datasets whose root directory contains a `metadata.json` file mapping resource names to relative paths (and optional `bytes` and `zenodo_filename` fields):
87
+
88
+ ```json
89
+ {
90
+ "resources": {
91
+ "trials": {"path": "trials.parquet", "bytes": 41200},
92
+ "features": {"path": "features/pressure.parquet", "zenodo_filename": "features_pressure.parquet"},
93
+ "scans": {"path": "scans.zip", "bytes": 182400120}
94
+ }
95
+ }
96
+ ```
97
+
98
+ Open a local directory, HTTP(S) mirror, Zenodo record, or resolve automatically (environment variable → local directory → remote fallback):
99
+
100
+ ```python
101
+ from zipfile import ZipFile
102
+ from readdata import Release
103
+
104
+ # Local first (env var or local directory with metadata.json), else Zenodo
105
+ rel = Release.auto("data", env="PPDS_DATA", fallback=Release.zenodo(24544934))
106
+
107
+ # Query Parquet resources lazily with DuckDB
108
+ with rel.connect(["trials", "features"]) as con:
109
+ rows = con.sql("SELECT * FROM trials LIMIT 5").fetchall()
110
+
111
+ # Stream a binary archive using byte ranges without downloading the whole file
112
+ with rel.open_resource("scans") as stream, ZipFile(stream) as archive:
113
+ mesh = archive.read("scans/s001l_foot.stl")
114
+ ```
115
+
116
+ In Pyodide/WebAssembly, `Release` automatically uses synchronous Web Worker `XMLHttpRequest` byte-range reads registered as an `fsspec` filesystem for DuckDB—no `httpfs` extension required.
117
+
118
+ ## License
119
+
120
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,89 @@
1
+ # [readdata](https://pypi.org/project/readdata/)
2
+
3
+ Read repository files and structured data releases transparently—locally, over HTTP(S), from GitHub or Zenodo, or in the browser (Pyodide / marimo WebAssembly).
4
+
5
+ `readdata` provides two small, complementary APIs with isolated dependencies:
6
+
7
+ 1. **`Repo` / `repo_file`** *(core — `urllib3` only)*: resolve individual repository files (`.csv`, `.trc`, `.c3d`, `.txt`, images, archives) locally first, falling back to an atomic cached HTTP(S) download with optional SHA-256 verification.
8
+ 2. **`Release`** *(optional `[release]` extra — `duckdb` + `fsspec`)*: open manifest-backed data releases (`metadata.json`) from a local directory, an HTTP mirror, or a numbered Zenodo record with lazy DuckDB SQL views over Parquet and seekable binary streams (including byte-range reads in Pyodide).
9
+
10
+ ## Installation
11
+
12
+ For repository/notebook file access (lightweight, pure Python):
13
+
14
+ ```bash
15
+ pip install readdata
16
+ ```
17
+
18
+ For manifest-backed Parquet/DuckDB releases and remote streaming:
19
+
20
+ ```bash
21
+ pip install "readdata[release]"
22
+ ```
23
+
24
+ For remote binary streaming without DuckDB:
25
+
26
+ ```bash
27
+ pip install "readdata[http]"
28
+ ```
29
+
30
+ ## 1. Repository files (`Repo` & `repo_file`)
31
+
32
+ Designed for notebooks and scripts that should read a local checkout when present and automatically fetch a temporary cached copy when opened standalone (e.g., in `molab`, `marimo.app`, Google Colab, or GitHub Pages WebAssembly):
33
+
34
+ ```python
35
+ from readdata import Repo, repo_file
36
+
37
+ # Configure a GitHub repository once (e.g., in a BMC tutorial notebook)
38
+ bmc = Repo.github("BMClab/BMC", ref="master")
39
+ walk = bmc.file("data/walk.trc")
40
+
41
+ # Optional SHA-256 verification
42
+ sample = bmc.file("data/walk.trc", sha256="...")
43
+
44
+ # Or resolve a single file directly from any HTTP(S) base URL
45
+ path = repo_file(
46
+ "data/walk.trc",
47
+ base_url="https://raw.githubusercontent.com/BMClab/BMC/master/",
48
+ )
49
+ ```
50
+
51
+ Local lookup walks upward from `start_dir` (defaulting to `marimo.notebook_dir()` when running inside marimo, otherwise the current working directory). Pass `local=False` to force fetching from the remote URL.
52
+
53
+ ## 2. Structured data releases (`Release`)
54
+
55
+ Designed for versioned datasets whose root directory contains a `metadata.json` file mapping resource names to relative paths (and optional `bytes` and `zenodo_filename` fields):
56
+
57
+ ```json
58
+ {
59
+ "resources": {
60
+ "trials": {"path": "trials.parquet", "bytes": 41200},
61
+ "features": {"path": "features/pressure.parquet", "zenodo_filename": "features_pressure.parquet"},
62
+ "scans": {"path": "scans.zip", "bytes": 182400120}
63
+ }
64
+ }
65
+ ```
66
+
67
+ Open a local directory, HTTP(S) mirror, Zenodo record, or resolve automatically (environment variable → local directory → remote fallback):
68
+
69
+ ```python
70
+ from zipfile import ZipFile
71
+ from readdata import Release
72
+
73
+ # Local first (env var or local directory with metadata.json), else Zenodo
74
+ rel = Release.auto("data", env="PPDS_DATA", fallback=Release.zenodo(24544934))
75
+
76
+ # Query Parquet resources lazily with DuckDB
77
+ with rel.connect(["trials", "features"]) as con:
78
+ rows = con.sql("SELECT * FROM trials LIMIT 5").fetchall()
79
+
80
+ # Stream a binary archive using byte ranges without downloading the whole file
81
+ with rel.open_resource("scans") as stream, ZipFile(stream) as archive:
82
+ mesh = archive.read("scans/s001l_foot.stl")
83
+ ```
84
+
85
+ In Pyodide/WebAssembly, `Release` automatically uses synchronous Web Worker `XMLHttpRequest` byte-range reads registered as an `fsspec` filesystem for DuckDB—no `httpfs` extension required.
86
+
87
+ ## License
88
+
89
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "readdata"
7
+ dynamic = ["version"]
8
+ description = "Read files and structured data releases locally, over HTTP, from GitHub/Zenodo, or in the browser"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Marcos Duarte", email = "duartexyz@gmail.com" }]
13
+ requires-python = ">=3.10"
14
+ dependencies = ["urllib3>=2"]
15
+ keywords = ["data", "datasets", "zenodo", "github", "duckdb", "parquet", "marimo", "pyodide", "reproducibility"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Intended Audience :: Science/Research",
20
+ "Topic :: Scientific/Engineering",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ http = [
25
+ "fsspec[http]; sys_platform != 'emscripten'",
26
+ "fsspec; sys_platform == 'emscripten'",
27
+ ]
28
+ release = [
29
+ "fsspec[http]; sys_platform != 'emscripten'",
30
+ "fsspec; sys_platform == 'emscripten'",
31
+ "duckdb",
32
+ ]
33
+ test = ["pytest", "duckdb", "fsspec[http]"]
34
+
35
+ [dependency-groups]
36
+ dev = ["build", "pytest", "ruff>=0.15", "twine"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/demotu/readdata"
40
+ Documentation = "https://github.com/demotu/readdata#readme"
41
+ Issues = "https://github.com/demotu/readdata/issues"
42
+
43
+ [tool.setuptools]
44
+ packages = ["readdata"]
45
+
46
+ [tool.setuptools.dynamic]
47
+ version = { attr = "readdata.__version__" }
48
+
49
+ [tool.ruff]
50
+ target-version = "py310"
51
+ line-length = 110
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "UP", "B"]
55
+
56
+ [tool.pytest.ini_options]
57
+ testpaths = ["tests"]
58
+ filterwarnings = ["error::DeprecationWarning:readdata"]
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ from .release import Release
4
+ from .repo import Repo, repo_file
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["Release", "Repo", "__version__", "repo_file"]
@@ -0,0 +1,118 @@
1
+ """Seekable HTTP reads in a Pyodide worker, including DuckDB's Python filesystem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import OrderedDict
6
+ from datetime import datetime, timezone
7
+ from functools import lru_cache
8
+ from io import BytesIO
9
+ from urllib.parse import quote, unquote
10
+
11
+ from fsspec import AbstractFileSystem
12
+ from fsspec.spec import AbstractBufferedFile
13
+
14
+ BLOCK_SIZE = 512 * 1024
15
+ # At most 24 MiB shared across short-lived DuckDB connections in this worker.
16
+ _blocks: OrderedDict[tuple[str, int, int], bytes] = OrderedDict()
17
+ # A mirror that ignores Range returns whole files. Keep the latest one for every
18
+ # reader of the same resource, so new DuckDB handles do not download it again.
19
+ _full_files: dict[tuple[str, int], bytes] = {}
20
+
21
+
22
+ def _request(url: str, start: int | None = None, stop: int | None = None) -> tuple[int, bytes]:
23
+ # The marimo kernel runs in a Web Worker. A synchronous request here gives
24
+ # DuckDB and zipfile their normal seek/read interface without blocking the UI.
25
+ from js import Uint8Array, XMLHttpRequest
26
+
27
+ request = XMLHttpRequest.new()
28
+ request.open("GET", url, False)
29
+ request.responseType = "arraybuffer"
30
+ if start is not None and stop is not None:
31
+ request.setRequestHeader("Range", f"bytes={start}-{stop - 1}")
32
+ request.send()
33
+ if request.status != 200 and not (start is not None and request.status == 206):
34
+ raise OSError(f"HTTP {request.status} reading {url}")
35
+ data = Uint8Array.new(request.response).to_py().tobytes()
36
+ if request.status == 206 and start is not None and stop is not None:
37
+ if len(data) != stop - start:
38
+ raise OSError(f"Incomplete byte range from {url}")
39
+ # Browsers hide Content-Range unless CORS exposes it; check it when visible.
40
+ served = request.getResponseHeader("Content-Range")
41
+ if served is not None and not str(served).startswith(f"bytes {start}-{stop - 1}/"):
42
+ raise OSError(f"Unexpected byte range {served} from {url}")
43
+ return request.status, data
44
+
45
+
46
+ def _fetch(url: str) -> bytes:
47
+ return _request(url)[1]
48
+
49
+
50
+ class RangeFile(AbstractBufferedFile):
51
+ def _fetch_range(self, start: int, end: int) -> bytes:
52
+ end = min(end, self.size)
53
+ if start >= end:
54
+ return b""
55
+ whole = _full_files.get((self.path, self.size))
56
+ if whole is not None:
57
+ return whole[start:end]
58
+ first = start // BLOCK_SIZE * BLOCK_SIZE
59
+ blocks = []
60
+ for offset in range(first, end, BLOCK_SIZE):
61
+ key = (self.path, self.size, offset)
62
+ if key in _blocks:
63
+ _blocks.move_to_end(key)
64
+ else:
65
+ status, data = _request(self.path, offset, min(offset + BLOCK_SIZE, self.size))
66
+ if status == 200:
67
+ if len(data) != self.size:
68
+ raise OSError(f"Unexpected full response size from {self.path}")
69
+ if self.size > BLOCK_SIZE:
70
+ _full_files.clear()
71
+ _full_files[self.path, self.size] = data
72
+ return data[start:end]
73
+ _blocks[key] = data
74
+ if len(_blocks) > 48:
75
+ _blocks.popitem(last=False)
76
+ blocks.append(_blocks[key])
77
+ return b"".join(blocks)[start - first:end - first]
78
+
79
+
80
+ def open_http(url: str, size: int | None):
81
+ if size is None:
82
+ return BytesIO(_fetch(url))
83
+ return RangeFile(None, url, size=size, cache_type="none")
84
+
85
+
86
+ class ReleaseFileSystem(AbstractFileSystem):
87
+ """Make named remote Parquet resources visible to DuckDB without httpfs."""
88
+
89
+ protocol = "readdatarelease"
90
+ cachable = False
91
+
92
+ def __init__(self, **kwargs):
93
+ super().__init__(**kwargs)
94
+ # DuckDB can ask for the size before opening an unsized resource.
95
+ self._whole_file = lru_cache(maxsize=1)(_fetch)
96
+
97
+ @classmethod
98
+ def resource(cls, url: str, size: int | None) -> str:
99
+ length = "unknown" if size is None else str(size)
100
+ return f"{cls.protocol}://{length}/{quote(url, safe='')}"
101
+
102
+ def info(self, path: str, **kwargs):
103
+ name = self._strip_protocol(path)
104
+ size, url = name.split("/", 1)
105
+ length = len(self._whole_file(unquote(url))) if size == "unknown" else int(size)
106
+ return {"name": name, "size": length, "type": "file"}
107
+
108
+ def modified(self, path: str):
109
+ # The pinned resources are immutable.
110
+ return datetime(1970, 1, 1, tzinfo=timezone.utc)
111
+
112
+ def _open(self, path: str, mode: str = "rb", **kwargs):
113
+ if mode != "rb":
114
+ raise ValueError("Release files are read-only")
115
+ size, url = self._strip_protocol(path).split("/", 1)
116
+ if size == "unknown":
117
+ return BytesIO(self._whole_file(unquote(url)))
118
+ return open_http(unquote(url), int(size))
@@ -0,0 +1,25 @@
1
+ """Shared relative POSIX path validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import PurePosixPath
6
+ from urllib.parse import urlsplit
7
+
8
+
9
+ def relative_posix_path(
10
+ path: str | PurePosixPath,
11
+ *,
12
+ label: str = "relative",
13
+ ) -> PurePosixPath:
14
+ """Validate and return a safe relative POSIX path without parent traversal."""
15
+ text = str(path)
16
+ relative = PurePosixPath(text)
17
+ if (
18
+ not relative.parts
19
+ or relative.is_absolute()
20
+ or ".." in relative.parts
21
+ or "\\" in text
22
+ or urlsplit(text).scheme
23
+ ):
24
+ raise ValueError(f"Expected a {label} path such as 'data/file.csv', got {path!r}")
25
+ return relative
@@ -0,0 +1,219 @@
1
+ """Manifest-backed access to named Parquet and binary resources in a local or hosted release."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from collections.abc import Iterable, Sequence
9
+ from dataclasses import dataclass
10
+ from functools import cached_property
11
+ from pathlib import Path, PurePosixPath
12
+ from urllib.parse import quote, urlsplit
13
+
14
+ from ._paths import relative_posix_path
15
+
16
+ ZENODO_FILES = "https://zenodo.org/api/records/{record}/files/"
17
+
18
+
19
+ def _import_duckdb():
20
+ try:
21
+ import duckdb
22
+ except ImportError as exc:
23
+ raise ImportError(
24
+ "DuckDB is required for Release.table() and Release.connect(). "
25
+ "Install it with: pip install 'readdata[release]'"
26
+ ) from exc
27
+ return duckdb
28
+
29
+
30
+ def _import_fsspec():
31
+ try:
32
+ import fsspec
33
+ except ImportError as exc:
34
+ raise ImportError(
35
+ "fsspec is required to stream remote Release files. "
36
+ "Install it with: pip install 'readdata[release]' (or 'readdata[http]')"
37
+ ) from exc
38
+ return fsspec
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Release:
43
+ """A release root with a ``metadata.json`` file declaring resources by name and path.
44
+
45
+ Use ``local()``, ``http()``, ``zenodo()``, or ``auto()`` to select the source.
46
+ Metadata is fetched on first use. ``connect()`` returns an independent DuckDB connection.
47
+ """
48
+
49
+ root: Path | str
50
+ suffix: str = ""
51
+ flat: bool = False
52
+
53
+ @classmethod
54
+ def local(cls, directory: Path | str) -> Release:
55
+ """Open a directory containing ``metadata.json`` and its release resources."""
56
+ return cls(Path(directory).expanduser().resolve())
57
+
58
+ @classmethod
59
+ def http(cls, base: str, *, suffix: str = "", flat: bool = False) -> Release:
60
+ """Open an HTTP(S) directory. Flat servers replace path separators with '_'."""
61
+ url = urlsplit(base)
62
+ if url.scheme not in ("http", "https") or not url.netloc or url.query or url.fragment:
63
+ raise ValueError("Expected an HTTP(S) base directory URL")
64
+ return cls(base.rstrip("/") + "/", suffix, flat)
65
+
66
+ @classmethod
67
+ def zenodo(cls, record: int | str) -> Release:
68
+ """Open the public files in a numbered Zenodo record."""
69
+ if not str(record).isascii() or not str(record).isdecimal():
70
+ raise ValueError("Expected a numeric Zenodo record ID")
71
+ return cls.http(ZENODO_FILES.format(record=record), suffix="/content", flat=True)
72
+
73
+ @classmethod
74
+ def auto(
75
+ cls,
76
+ local: Path | str | Sequence[Path | str] | None = None,
77
+ *,
78
+ env: str | None = None,
79
+ fallback: Release | None = None,
80
+ ) -> Release:
81
+ """Select a local release first (via ``env`` or ``local``), else ``fallback``.
82
+
83
+ 1. If ``env`` names an environment variable set to a non-blank path, open it with
84
+ :meth:`local`.
85
+ 2. Otherwise inspect ``local`` (a directory or sequence of directories) and open the
86
+ first one containing ``metadata.json``.
87
+ 3. Otherwise return ``fallback`` (e.g. ``Release.zenodo(...)`` or ``Release.http(...)``).
88
+ """
89
+ if fallback is not None and not isinstance(fallback, cls):
90
+ raise TypeError(
91
+ "Expected fallback to be a Release instance (e.g. Release.zenodo(...)), "
92
+ f"got {type(fallback).__name__}"
93
+ )
94
+ if env is not None:
95
+ configured = os.environ.get(env, "").strip()
96
+ if configured:
97
+ return cls.local(configured)
98
+ if local is not None:
99
+ candidates = (local,) if isinstance(local, (str, Path)) else local
100
+ for candidate in candidates:
101
+ directory = Path(candidate).expanduser()
102
+ if (directory / "metadata.json").is_file():
103
+ return cls.local(directory)
104
+ if fallback is not None:
105
+ return fallback
106
+ raise FileNotFoundError(
107
+ "No local release (metadata.json) found and no fallback Release was provided."
108
+ )
109
+
110
+ def location(self, path: str | PurePosixPath) -> str:
111
+ """Resolve a release-relative POSIX file path to a local path or encoded URL."""
112
+ relative = relative_posix_path(path, label="release-relative")
113
+ if isinstance(self.root, Path):
114
+ nested = self.root / relative
115
+ # Downloading all files from a Zenodo record yields a flat directory.
116
+ if len(relative.parts) > 1 and not nested.is_file():
117
+ flat = self.root / "_".join(relative.parts)
118
+ if flat.is_file():
119
+ return str(flat)
120
+ return str(nested)
121
+ name = relative.as_posix()
122
+ if self.flat:
123
+ name = name.replace("/", "_")
124
+ return self.root + quote(name, safe="/") + self.suffix
125
+
126
+ def open_file(self, path: str | PurePosixPath, *, size: int | None = None):
127
+ """Open a binary stream. Known byte size permits seeking even with a chunked HTTP HEAD."""
128
+ return self._open(self.location(path), size)
129
+
130
+ def _open(self, target: str, size: int | None):
131
+ if isinstance(self.root, Path):
132
+ return open(target, "rb")
133
+ if sys.platform == "emscripten":
134
+ _import_fsspec()
135
+ from ._browser import open_http
136
+
137
+ return open_http(target, size)
138
+ fsspec = _import_fsspec()
139
+ http = fsspec.filesystem("http")
140
+ return http.open(target, "rb", block_size=64 * 1024, cache_type="readahead", size=size)
141
+
142
+ def open_resource(self, name: str):
143
+ """Open a named resource, using its manifest size for remote byte ranges."""
144
+ return self._open(self.resource_location(name), self.metadata["resources"][name].get("bytes"))
145
+
146
+ @cached_property
147
+ def metadata(self) -> dict:
148
+ """The decoded ``metadata.json`` document."""
149
+ try:
150
+ with self.open_file("metadata.json") as stream:
151
+ return json.load(stream)
152
+ except FileNotFoundError as exc:
153
+ raise FileNotFoundError(
154
+ f"Release metadata missing at {self.location('metadata.json')}. "
155
+ "Select the directory containing the downloaded metadata.json or configure a hosted release."
156
+ ) from exc
157
+
158
+ def resource_path(self, name: str) -> str:
159
+ """Return the named resource's path for the selected source layout."""
160
+ spec = self.metadata["resources"][name]
161
+ path = spec["path"]
162
+ deposit_name = spec.get("zenodo_filename", path.replace("/", "_"))
163
+ if self.flat:
164
+ return deposit_name
165
+ if (
166
+ isinstance(self.root, Path)
167
+ and not (self.root / relative_posix_path(path, label="release-relative")).is_file()
168
+ and (self.root / relative_posix_path(deposit_name, label="release-relative")).is_file()
169
+ ):
170
+ return deposit_name
171
+ return path
172
+
173
+ def resource_location(self, name: str) -> str:
174
+ """Resolve a named resource using the paths declared in the manifest."""
175
+ path = self.resource_path(name)
176
+ if isinstance(self.root, Path):
177
+ return str(self.root / relative_posix_path(path, label="release-relative"))
178
+ return self.location(path)
179
+
180
+ def table(self, name: str, *, connection=None):
181
+ """Return a lazy DuckDB relation, optionally in an existing SQL session."""
182
+ if PurePosixPath(self.metadata["resources"][name]["path"]).suffix.lower() != ".parquet":
183
+ raise ValueError(f"Resource {name!r} is not a Parquet table")
184
+ duckdb = _import_duckdb()
185
+ con = connection if connection is not None else duckdb.connect()
186
+ if sys.platform == "emscripten" and isinstance(self.root, str):
187
+ _import_fsspec()
188
+ from ._browser import ReleaseFileSystem
189
+
190
+ fs = ReleaseFileSystem()
191
+ if not con.filesystem_is_registered(fs.protocol):
192
+ con.register_filesystem(fs)
193
+ path = fs.resource(self.resource_location(name), self.metadata["resources"][name].get("bytes"))
194
+ else:
195
+ path = self.resource_location(name)
196
+ return con.read_parquet(path, hive_partitioning=False)
197
+
198
+ def connect(self, names: str | Iterable[str] | None = None):
199
+ """Open a SQL session with views for the requested (default: all) Parquet resources.
200
+
201
+ Use as a context manager or close the connection after your queries.
202
+ """
203
+ if names is None:
204
+ names = [
205
+ name
206
+ for name, spec in self.metadata["resources"].items()
207
+ if PurePosixPath(spec["path"]).suffix.lower() == ".parquet"
208
+ ]
209
+ elif isinstance(names, str):
210
+ names = [names]
211
+ duckdb = _import_duckdb()
212
+ con = duckdb.connect()
213
+ try:
214
+ for name in names:
215
+ self.table(name, connection=con).create_view(name)
216
+ except BaseException:
217
+ con.close()
218
+ raise
219
+ return con