tensorferry 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.
tensorferry/store.py ADDED
@@ -0,0 +1,361 @@
1
+ import mmap
2
+ import os
3
+ import posixpath
4
+ from collections.abc import Buffer, Callable, Mapping
5
+ from dataclasses import dataclass
6
+ from functools import cache
7
+ from pathlib import Path
8
+ from typing import Any, Protocol, runtime_checkable
9
+ from urllib.parse import quote, unquote
10
+
11
+ import numpy as np
12
+ import obstore.store
13
+
14
+ from tensorferry.progress import _record_read
15
+
16
+ __all__ = [
17
+ "Blob",
18
+ "CallbackStore",
19
+ "FsspecStore",
20
+ "LocalStore",
21
+ "MemoryStore",
22
+ "ObjectStore",
23
+ "Store",
24
+ "StoreLike",
25
+ "as_store",
26
+ "exists",
27
+ "hub_token",
28
+ "hub_url",
29
+ "is_url",
30
+ "join",
31
+ "resolve",
32
+ ]
33
+
34
+
35
+ @runtime_checkable
36
+ class Store(Protocol):
37
+ """Reads use half-open byte ranges. A short read is valid only at end of file."""
38
+
39
+ def fetch(self, name: str, start: int, stop: int) -> Buffer: ...
40
+
41
+ def size(self, name: str) -> int: ...
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class Blob:
46
+ store: Store
47
+ name: str
48
+
49
+ def __str__(self) -> str:
50
+ return self.name
51
+
52
+ def size(self) -> int:
53
+ return int(self.store.size(self.name))
54
+
55
+ def fetch(self, start: int, stop: int) -> np.ndarray:
56
+ if stop <= start:
57
+ return np.empty(0, np.uint8)
58
+ return np.frombuffer(self.store.fetch(self.name, start, stop), np.uint8)
59
+
60
+ def fetch_exact(self, start: int, stop: int) -> np.ndarray:
61
+ data = self.fetch(start, stop)
62
+ if data.size != max(0, stop - start):
63
+ raise EOFError(f"{self}: wanted bytes [{start}, {stop}), the file ends at {start + data.size}")
64
+ return data
65
+
66
+ def can(self, method: str) -> bool:
67
+ if not hasattr(self.store, method):
68
+ return False
69
+ offers = getattr(self.store, "offers", None)
70
+ return offers is None or bool(offers(self.name, method))
71
+
72
+ def read_into(self, start: int, out: np.ndarray) -> None:
73
+ if self.can("fetch_into"):
74
+ getattr(self.store, "fetch_into")(self.name, start, memoryview(out)) # noqa: B009
75
+ else:
76
+ out[...] = self.fetch_exact(start, start + out.size)
77
+
78
+ def tail(self, length: int) -> tuple[np.ndarray, int]:
79
+ """The file's last `length` bytes (all of it, if shorter) and its size."""
80
+ if self.can("fetch_tail"):
81
+ data, size = getattr(self.store, "fetch_tail")(self.name, length) # noqa: B009
82
+ return np.frombuffer(data, np.uint8), int(size)
83
+ size = self.size()
84
+ return self.fetch(max(0, size - length), size), size
85
+
86
+ def sibling(self, name: str) -> "Blob":
87
+ return Blob(self.store, posixpath.normpath(posixpath.join(posixpath.dirname(self.name), name)))
88
+
89
+ def _remote_bytes(self, start: int, stop: int) -> int:
90
+ fn = getattr(self.store, "_remote_bytes", None)
91
+ return fn(self.name, start, stop) if fn is not None else 0
92
+
93
+
94
+ class LocalStore:
95
+ """Reads use independent file offsets. Replacing a file takes effect on the next open."""
96
+
97
+ def __init__(self, root: str | os.PathLike[str] = ".") -> None:
98
+ self.root = Path(root).expanduser().resolve()
99
+
100
+ def __repr__(self) -> str:
101
+ return f"LocalStore({str(self.root)!r})"
102
+
103
+ @property
104
+ def url(self) -> str:
105
+ return self.root.as_uri()
106
+
107
+ def stat(self, name: str) -> tuple[int, str]:
108
+ st = self.path(name).stat()
109
+ return st.st_size, f"{st.st_mtime_ns}-{st.st_ino}"
110
+
111
+ def path(self, name: str) -> Path:
112
+ path = (self.root / name).resolve()
113
+ if not path.is_relative_to(self.root):
114
+ raise ValueError(f"{name!r} is outside {self.root}")
115
+ return path
116
+
117
+ def size(self, name: str) -> int:
118
+ return self.path(name).stat().st_size
119
+
120
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
121
+ out = np.empty(max(0, stop - start), np.uint8)
122
+ return out[: self._read(name, start, memoryview(out))]
123
+
124
+ def fetch_into(self, name: str, start: int, out: memoryview) -> None:
125
+ done = self._read(name, start, out)
126
+ if done != out.nbytes:
127
+ raise EOFError(f"{self.path(name)}: wanted {out.nbytes} bytes at {start}, got {done}")
128
+
129
+ def map(self, name: str) -> mmap.mmap:
130
+ with self.path(name).open("rb") as handle:
131
+ return mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_COPY)
132
+
133
+ def _read(self, name: str, start: int, out: memoryview) -> int:
134
+ out = out.cast("B")
135
+ if not hasattr(os, "preadv"): # Windows: no positioned reads
136
+ with self.path(name).open("rb", buffering=0) as handle:
137
+ handle.seek(start)
138
+ return handle.readinto(out) or 0
139
+ fd, done = os.open(self.path(name), os.O_RDONLY), 0
140
+ try:
141
+ while done < len(out):
142
+ n = os.preadv(fd, [out[done:]], start + done)
143
+ if n == 0:
144
+ break
145
+ done += n
146
+ finally:
147
+ os.close(fd)
148
+ return done
149
+
150
+
151
+ class MemoryStore:
152
+ def __init__(self, files: Mapping[str, Buffer] | None = None) -> None:
153
+ self.files: dict[str, Buffer] = dict(files or {})
154
+
155
+ def _view(self, name: str) -> memoryview:
156
+ if name not in self.files:
157
+ raise FileNotFoundError(name)
158
+ return memoryview(self.files[name]).cast("B")
159
+
160
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
161
+ return self._view(name)[start:stop]
162
+
163
+ def size(self, name: str) -> int:
164
+ return self._view(name).nbytes
165
+
166
+
167
+ @dataclass(frozen=True, slots=True)
168
+ class CallbackStore:
169
+ fetch_fn: Callable[[str, int, int], Buffer]
170
+ size_fn: Callable[[str], int] | None = None
171
+
172
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
173
+ return self.fetch_fn(name, start, stop)
174
+
175
+ def size(self, name: str) -> int:
176
+ if self.size_fn is None:
177
+ raise TypeError(f"{name}: this store has no size function, which npz files need")
178
+ return self.size_fn(name)
179
+
180
+
181
+ class ObjectStore:
182
+ """Hub authentication uses the supplied token or the locally configured Hugging Face token."""
183
+
184
+ def __init__(self, store: Any, *, token: str | None = None, **config: Any) -> None:
185
+ # A store built from a URL is named by it, which is what a cache keys on.
186
+ self.url: str | None = None
187
+ if isinstance(store, str):
188
+ self.url = store.rstrip("/")
189
+ options = dict(config.pop("client_options", None) or {})
190
+ if store.startswith("hf://"):
191
+ if token := token or hub_token():
192
+ headers = dict(options.get("default_headers") or {})
193
+ headers.setdefault("authorization", f"Bearer {token}")
194
+ options["default_headers"] = headers
195
+ store = hub_url(store)
196
+ elif token is not None:
197
+ raise TypeError("token applies to hf:// URLs")
198
+ if options:
199
+ config["client_options"] = options
200
+ store = obstore.store.from_url(store, **config)
201
+ elif config or token is not None:
202
+ raise TypeError("configuration only applies when `store` is a URL")
203
+ self.store = store
204
+ self._is_remote = not isinstance(store, (obstore.store.LocalStore, obstore.store.MemoryStore))
205
+
206
+ def __repr__(self) -> str:
207
+ # By its URL: the underlying store's options may hold a token.
208
+ return f"ObjectStore({self.url!r})" if self.url else f"ObjectStore({self.store!r})"
209
+
210
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
211
+ if stop <= start:
212
+ return b""
213
+ data = obstore.get_range(self.store, name, start=start, end=stop)
214
+ if self._is_remote:
215
+ _record_read(data)
216
+ return data
217
+
218
+ def fetch_tail(self, name: str, length: int) -> tuple[Buffer, int]:
219
+ result = obstore.get(self.store, name, options={"range": {"suffix": length}})
220
+ data = result.bytes()
221
+ if self._is_remote:
222
+ _record_read(data)
223
+ return data, int(result.meta["size"])
224
+
225
+ def size(self, name: str) -> int:
226
+ return self.stat(name)[0]
227
+
228
+ def stat(self, name: str) -> tuple[int, str | None]:
229
+ meta = obstore.head(self.store, name)
230
+ version = meta.get("version") or meta.get("e_tag")
231
+ return int(meta["size"]), None if version is None else str(version)
232
+
233
+ def _remote_bytes(self, name: str, start: int, stop: int) -> int:
234
+ return max(0, stop - start) if self._is_remote else 0
235
+
236
+
237
+ class FsspecStore:
238
+ def __init__(self, fs: Any, root: str = "") -> None:
239
+ self.fs = fs
240
+ self.root = root.rstrip("/")
241
+ protocol = fs.protocol
242
+ self._scheme = protocol if isinstance(protocol, str) else protocol[0]
243
+ self._is_remote = self._scheme not in ("file", "local", "memory")
244
+
245
+ def _path(self, name: str) -> str:
246
+ return f"{self.root}/{name}" if self.root else name
247
+
248
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
249
+ data = self.fs.cat_file(self._path(name), start=start, end=stop)
250
+ if self._is_remote:
251
+ _record_read(data)
252
+ return data
253
+
254
+ def size(self, name: str) -> int:
255
+ return int(self.fs.size(self._path(name)))
256
+
257
+ @property
258
+ def url(self) -> str:
259
+ return f"{self._scheme}://{self.root}"
260
+
261
+ def _remote_bytes(self, name: str, start: int, stop: int) -> int:
262
+ return max(0, stop - start) if self._is_remote else 0
263
+
264
+ def stat(self, name: str) -> tuple[int, str | None]:
265
+ info = self.fs.info(self._path(name))
266
+ for key in _FSSPEC_VERSIONS:
267
+ if info.get(key):
268
+ return int(info["size"]), str(info[key])
269
+ return int(info["size"]), None
270
+
271
+
272
+ # Where fsspec filesystems report a version, most specific first.
273
+ _FSSPEC_VERSIONS = ("generation", "version_id", "VersionId", "etag", "ETag", "md5Hash", "mtime")
274
+
275
+
276
+ # huggingface_hub's URL prefixes for repositories that are not models.
277
+ _HUB_KINDS = ("datasets/", "spaces/")
278
+
279
+
280
+ def hub_url(url: str) -> str:
281
+ path = url.removeprefix("hf://").strip("/")
282
+ kind = next((prefix for prefix in _HUB_KINDS if path.startswith(prefix)), "")
283
+ parts = path.removeprefix(kind).split("/")
284
+ if len(parts) < 2 or not parts[0] or not parts[1].partition("@")[0]:
285
+ raise ValueError(
286
+ f"{url!r}: an hf:// URL names a repository as <namespace>/<repo>, "
287
+ "e.g. hf://facebook/esm2_t6_8M_UR50D/model.safetensors"
288
+ )
289
+ repo, _, revision = parts[1].partition("@")
290
+ endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
291
+ revision = quote(unquote(revision or "main"), safe="")
292
+ return "/".join([endpoint, f"{kind}{parts[0]}/{repo}", "resolve", revision, *parts[2:]])
293
+
294
+
295
+ def hub_token() -> str | None:
296
+ if token := os.environ.get("HF_TOKEN", "").strip():
297
+ return token
298
+ cache_home = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
299
+ home = Path(os.environ.get("HF_HOME") or cache_home / "huggingface")
300
+ try:
301
+ return Path(os.environ.get("HF_TOKEN_PATH") or home / "token").read_text().strip() or None
302
+ except OSError:
303
+ return None
304
+
305
+
306
+ # A store, or a bare ``fetch(name, start, stop)`` function to wrap as one.
307
+ type StoreLike = Store | Callable[[str, int, int], Buffer]
308
+
309
+
310
+ def as_store(store: StoreLike) -> Store:
311
+ """`store` itself, or a bare ``fetch(name, start, stop)`` function wrapped as one."""
312
+ if isinstance(store, Store):
313
+ return store
314
+ if callable(store):
315
+ return CallbackStore(store)
316
+ raise TypeError(f"expected a Store or a fetch(name, start, stop) function, got {store!r}")
317
+
318
+
319
+ def is_url(location: str | os.PathLike[str]) -> bool:
320
+ text = os.fspath(location)
321
+ return "://" in text and not text.startswith("file://")
322
+
323
+
324
+ def join(base: str | os.PathLike[str], *names: str) -> str | Path:
325
+ text = os.fspath(base)
326
+ if "://" in text:
327
+ return "/".join([text.rstrip("/"), *names])
328
+ return Path(base, *names)
329
+
330
+
331
+ def exists(source: str | os.PathLike[str], *, store: StoreLike | None = None) -> bool:
332
+ """Check a local path or stored object without reading its contents."""
333
+ blob = resolve(source, store)
334
+ try:
335
+ blob.size()
336
+ except FileNotFoundError:
337
+ return False
338
+ return True
339
+
340
+
341
+ def resolve(source: str | os.PathLike[str], store: StoreLike | None = None) -> Blob:
342
+ text = os.fspath(source)
343
+ if store is not None:
344
+ return Blob(as_store(store), text)
345
+ if is_url(text):
346
+ parent, _, name = text.rpartition("/")
347
+ if not name or parent.endswith(":/"):
348
+ raise ValueError(f"{text!r} does not name a file")
349
+ return Blob(_object_store(parent), name)
350
+ path = Path(text.removeprefix("file://")).expanduser().absolute()
351
+ return Blob(_local_store(str(path.parent)), path.name)
352
+
353
+
354
+ @cache
355
+ def _object_store(parent: str) -> ObjectStore:
356
+ return ObjectStore(parent)
357
+
358
+
359
+ @cache
360
+ def _local_store(parent: str) -> LocalStore:
361
+ return LocalStore(parent)