readdata 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.
- readdata/__init__.py +7 -0
- readdata/_browser.py +118 -0
- readdata/_paths.py +25 -0
- readdata/release.py +219 -0
- readdata/repo.py +216 -0
- readdata-0.1.0.dist-info/METADATA +120 -0
- readdata-0.1.0.dist-info/RECORD +10 -0
- readdata-0.1.0.dist-info/WHEEL +5 -0
- readdata-0.1.0.dist-info/licenses/LICENSE +21 -0
- readdata-0.1.0.dist-info/top_level.txt +1 -0
readdata/__init__.py
ADDED
readdata/_browser.py
ADDED
|
@@ -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))
|
readdata/_paths.py
ADDED
|
@@ -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
|
readdata/release.py
ADDED
|
@@ -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
|
readdata/repo.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Local-first repository and HTTP file resolution with atomic temp caching."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import tempfile
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path, PurePosixPath
|
|
9
|
+
from urllib.parse import quote, urlsplit
|
|
10
|
+
|
|
11
|
+
from ._paths import relative_posix_path
|
|
12
|
+
|
|
13
|
+
DEFAULT_CACHE_DIR_NAME = "readdata-cache"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _normalize_base_url(base_url: str) -> str:
|
|
17
|
+
url = urlsplit(base_url)
|
|
18
|
+
if url.scheme not in ("http", "https") or not url.netloc or url.query or url.fragment:
|
|
19
|
+
raise ValueError(f"Expected an HTTP(S) base directory URL, got {base_url!r}")
|
|
20
|
+
return base_url.rstrip("/") + "/"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _normalize_sha256(digest: str) -> str:
|
|
24
|
+
normalized = digest.strip().lower()
|
|
25
|
+
if normalized.startswith("sha256:"):
|
|
26
|
+
normalized = normalized[len("sha256:"):]
|
|
27
|
+
if len(normalized) != 64 or any(c not in "0123456789abcdef" for c in normalized):
|
|
28
|
+
raise ValueError(f"Expected a 64-character hexadecimal SHA-256 digest, got {digest!r}")
|
|
29
|
+
return normalized
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _file_sha256(path: Path) -> str:
|
|
33
|
+
hasher = hashlib.sha256()
|
|
34
|
+
with path.open("rb") as stream:
|
|
35
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
36
|
+
hasher.update(chunk)
|
|
37
|
+
return hasher.hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _default_start_dir() -> Path | None:
|
|
41
|
+
try:
|
|
42
|
+
import marimo as mo
|
|
43
|
+
except ImportError:
|
|
44
|
+
mo = None
|
|
45
|
+
if mo is not None:
|
|
46
|
+
location = mo.notebook_dir()
|
|
47
|
+
if location is not None:
|
|
48
|
+
return Path(location).resolve()
|
|
49
|
+
try:
|
|
50
|
+
return Path.cwd().resolve()
|
|
51
|
+
except OSError:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _find_local_file(relative: PurePosixPath, start_dir: Path | str | None) -> Path | None:
|
|
56
|
+
directory = Path(start_dir).expanduser().resolve() if start_dir is not None else _default_start_dir()
|
|
57
|
+
if directory is None:
|
|
58
|
+
return None
|
|
59
|
+
if directory.is_file():
|
|
60
|
+
directory = directory.parent
|
|
61
|
+
for base in (directory, *directory.parents):
|
|
62
|
+
candidate = base.joinpath(*relative.parts)
|
|
63
|
+
if candidate.is_file():
|
|
64
|
+
return candidate
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def repo_file(
|
|
69
|
+
path: str | PurePosixPath,
|
|
70
|
+
*,
|
|
71
|
+
base_url: str,
|
|
72
|
+
start_dir: Path | str | None = None,
|
|
73
|
+
local: bool = True,
|
|
74
|
+
cache_dir: Path | str | None = None,
|
|
75
|
+
sha256: str | None = None,
|
|
76
|
+
timeout: float = 30.0,
|
|
77
|
+
retries: int = 2,
|
|
78
|
+
) -> Path:
|
|
79
|
+
"""Resolve a repository-relative file locally, or fetch and cache a copy over HTTP(S).
|
|
80
|
+
|
|
81
|
+
When ``local=True`` (the default), local files found by walking up from ``start_dir``
|
|
82
|
+
(or ``marimo.notebook_dir()`` / current working directory) take precedence over remote
|
|
83
|
+
downloads. Set ``local=False`` to always fetch from ``base_url``. When fetching
|
|
84
|
+
remotely, ``urllib3`` automatically selects its browser transport in Pyodide.
|
|
85
|
+
"""
|
|
86
|
+
relative = relative_posix_path(path, label="repository-relative")
|
|
87
|
+
normalized_base = _normalize_base_url(base_url)
|
|
88
|
+
expected_sha256 = _normalize_sha256(sha256) if sha256 is not None else None
|
|
89
|
+
|
|
90
|
+
if local:
|
|
91
|
+
found = _find_local_file(relative, start_dir)
|
|
92
|
+
if found is not None:
|
|
93
|
+
if expected_sha256 is not None:
|
|
94
|
+
actual = _file_sha256(found)
|
|
95
|
+
if actual != expected_sha256:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"SHA-256 mismatch for local file {found}: expected {expected_sha256}, got {actual}"
|
|
98
|
+
)
|
|
99
|
+
return found
|
|
100
|
+
|
|
101
|
+
cache_root = (
|
|
102
|
+
Path(cache_dir).expanduser().resolve()
|
|
103
|
+
if cache_dir is not None
|
|
104
|
+
else Path(tempfile.gettempdir()) / DEFAULT_CACHE_DIR_NAME
|
|
105
|
+
)
|
|
106
|
+
key = hashlib.sha256(normalized_base.rstrip("/").encode()).hexdigest()[:16]
|
|
107
|
+
cached = (cache_root / key).joinpath(*relative.parts)
|
|
108
|
+
|
|
109
|
+
if cached.is_file():
|
|
110
|
+
if expected_sha256 is None or _file_sha256(cached) == expected_sha256:
|
|
111
|
+
return cached
|
|
112
|
+
|
|
113
|
+
import urllib3
|
|
114
|
+
|
|
115
|
+
url = normalized_base + quote(relative.as_posix(), safe="/")
|
|
116
|
+
response = urllib3.request("GET", url, timeout=timeout, retries=retries)
|
|
117
|
+
if response.status != 200:
|
|
118
|
+
raise OSError(f"Cannot load {relative.as_posix()}: HTTP {response.status} from {url}")
|
|
119
|
+
if expected_sha256 is not None:
|
|
120
|
+
actual = hashlib.sha256(response.data).hexdigest()
|
|
121
|
+
if actual != expected_sha256:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"SHA-256 mismatch for {url}: expected {expected_sha256}, got {actual}"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
cached.parent.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
with tempfile.NamedTemporaryFile(dir=cached.parent, delete=False) as download:
|
|
128
|
+
temporary = Path(download.name)
|
|
129
|
+
download.write(response.data)
|
|
130
|
+
try:
|
|
131
|
+
temporary.replace(cached)
|
|
132
|
+
finally:
|
|
133
|
+
temporary.unlink(missing_ok=True)
|
|
134
|
+
return cached
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class Repo:
|
|
139
|
+
"""A repository or HTTP directory resolved locally first, then cached over HTTP(S).
|
|
140
|
+
|
|
141
|
+
Example:
|
|
142
|
+
>>> bmc = Repo.github("BMClab/BMC", ref="master")
|
|
143
|
+
>>> path = bmc.file("data/walk.trc")
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
base_url: str
|
|
147
|
+
start_dir: Path | None = None
|
|
148
|
+
local: bool = True
|
|
149
|
+
cache_dir: Path | None = None
|
|
150
|
+
timeout: float = 30.0
|
|
151
|
+
retries: int = 2
|
|
152
|
+
|
|
153
|
+
def __post_init__(self) -> None:
|
|
154
|
+
object.__setattr__(self, "base_url", _normalize_base_url(self.base_url))
|
|
155
|
+
if self.start_dir is not None:
|
|
156
|
+
object.__setattr__(self, "start_dir", Path(self.start_dir).expanduser().resolve())
|
|
157
|
+
if self.cache_dir is not None:
|
|
158
|
+
object.__setattr__(self, "cache_dir", Path(self.cache_dir).expanduser().resolve())
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def github(
|
|
162
|
+
cls,
|
|
163
|
+
repo: str,
|
|
164
|
+
*,
|
|
165
|
+
ref: str = "main",
|
|
166
|
+
start_dir: Path | str | None = None,
|
|
167
|
+
local: bool = True,
|
|
168
|
+
cache_dir: Path | str | None = None,
|
|
169
|
+
timeout: float = 30.0,
|
|
170
|
+
retries: int = 2,
|
|
171
|
+
) -> Repo:
|
|
172
|
+
"""Create a Repo backed by ``raw.githubusercontent.com`` for ``owner/name`` at ``ref``."""
|
|
173
|
+
parts = [part for part in repo.strip("/").split("/") if part]
|
|
174
|
+
if len(parts) != 2 or any(".." in part or "\\" in part for part in parts):
|
|
175
|
+
raise ValueError(f"Expected GitHub repository as 'owner/name', got {repo!r}")
|
|
176
|
+
ref_clean = str(ref).strip().strip("/")
|
|
177
|
+
if not ref_clean or ".." in ref_clean.split("/") or "\\" in ref_clean:
|
|
178
|
+
raise ValueError(f"Expected a valid git ref (branch, tag, or commit SHA), got {ref!r}")
|
|
179
|
+
owner, name = parts
|
|
180
|
+
base = (
|
|
181
|
+
f"https://raw.githubusercontent.com/"
|
|
182
|
+
f"{quote(owner, safe='')}/{quote(name, safe='')}/{quote(ref_clean, safe='/')}/"
|
|
183
|
+
)
|
|
184
|
+
return cls(
|
|
185
|
+
base,
|
|
186
|
+
start_dir=Path(start_dir) if start_dir is not None else None,
|
|
187
|
+
local=local,
|
|
188
|
+
cache_dir=Path(cache_dir) if cache_dir is not None else None,
|
|
189
|
+
timeout=timeout,
|
|
190
|
+
retries=retries,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def url(self, path: str | PurePosixPath) -> str:
|
|
194
|
+
"""Return the remote HTTP(S) URL for a repository-relative POSIX path."""
|
|
195
|
+
relative = relative_posix_path(path, label="repository-relative")
|
|
196
|
+
return self.base_url + quote(relative.as_posix(), safe="/")
|
|
197
|
+
|
|
198
|
+
def file(
|
|
199
|
+
self,
|
|
200
|
+
path: str | PurePosixPath,
|
|
201
|
+
*,
|
|
202
|
+
sha256: str | None = None,
|
|
203
|
+
start_dir: Path | str | None = None,
|
|
204
|
+
local: bool | None = None,
|
|
205
|
+
) -> Path:
|
|
206
|
+
"""Resolve a repository-relative file locally, or fetch and cache a copy."""
|
|
207
|
+
return repo_file(
|
|
208
|
+
path,
|
|
209
|
+
base_url=self.base_url,
|
|
210
|
+
start_dir=self.start_dir if start_dir is None else start_dir,
|
|
211
|
+
local=self.local if local is None else local,
|
|
212
|
+
cache_dir=self.cache_dir,
|
|
213
|
+
sha256=sha256,
|
|
214
|
+
timeout=self.timeout,
|
|
215
|
+
retries=self.retries,
|
|
216
|
+
)
|
|
@@ -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,10 @@
|
|
|
1
|
+
readdata/__init__.py,sha256=FCKj0D1afG2T6QjGMUf5KddomzPnx2w17zJ-FJ0utpc,180
|
|
2
|
+
readdata/_browser.py,sha256=K3RZMJRq0mFRi-pFkji87db3GXs97ARx6vxNOhfK8NQ,4853
|
|
3
|
+
readdata/_paths.py,sha256=NR821_vSp9oHAo6AElSqs0cQKpDvCCZvEv-iArcdW7E,682
|
|
4
|
+
readdata/release.py,sha256=HHI4QcvVigjuhMLsekdIG9kh3aDgwIyaJxkeSzBzQCg,8995
|
|
5
|
+
readdata/repo.py,sha256=82rcVfHdaMpEF1aY0qmi_qZMjXN8zLuS85mAJdBgIPs,7816
|
|
6
|
+
readdata-0.1.0.dist-info/licenses/LICENSE,sha256=FaQSgp6Od_o8K2z2eWKd0s-jergKmASjMMhKo3j1_rI,1070
|
|
7
|
+
readdata-0.1.0.dist-info/METADATA,sha256=UP8uJh_xVrCZ4m2iJRtuLpd6HRXp8DsRQ6qnXRqTSMI,4922
|
|
8
|
+
readdata-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
readdata-0.1.0.dist-info/top_level.txt,sha256=eWKkhOZpDpwRnOxuOQdvtu3N89cKFtWdM8VU1on32vs,9
|
|
10
|
+
readdata-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
readdata
|