oasis-data-manager 0.2.2__tar.gz → 0.2.4__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.
Files changed (46) hide show
  1. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/MANIFEST.in +1 -2
  2. oasis_data_manager-0.2.4/PKG-INFO +413 -0
  3. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/README.md +28 -0
  4. oasis_data_manager-0.2.4/oasis_data_manager/__init__.py +1 -0
  5. oasis_data_manager-0.2.4/oasis_data_manager/filestore/archive.py +113 -0
  6. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/aws.py +9 -3
  7. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/base.py +55 -20
  8. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/config.py +1 -0
  9. oasis_data_manager-0.2.4/oasis_data_manager.egg-info/PKG-INFO +413 -0
  10. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager.egg-info/SOURCES.txt +2 -3
  11. oasis_data_manager-0.2.4/oasis_data_manager.egg-info/requires.txt +34 -0
  12. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager.egg-info/top_level.txt +1 -0
  13. oasis_data_manager-0.2.4/pyproject.toml +77 -0
  14. oasis_data_manager-0.2.4/setup.cfg +4 -0
  15. oasis_data_manager-0.2.2/PKG-INFO +0 -38
  16. oasis_data_manager-0.2.2/oasis_data_manager/__init__.py +0 -1
  17. oasis_data_manager-0.2.2/oasis_data_manager.egg-info/PKG-INFO +0 -38
  18. oasis_data_manager-0.2.2/oasis_data_manager.egg-info/requires.txt +0 -16
  19. oasis_data_manager-0.2.2/requirements-package.in +0 -5
  20. oasis_data_manager-0.2.2/setup.cfg +0 -29
  21. oasis_data_manager-0.2.2/setup.py +0 -64
  22. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/CHANGELOG.rst +0 -0
  23. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/LICENSE +0 -0
  24. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/complex/__init__.py +0 -0
  25. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/complex/complex.py +0 -0
  26. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/complex/examples.py +0 -0
  27. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/config.py +0 -0
  28. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/__init__.py +0 -0
  29. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/backends/__init__.py +0 -0
  30. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/backends/base.py +0 -0
  31. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/backends/dask.py +0 -0
  32. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/backends/pandas.py +0 -0
  33. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/backends/pyarrow.py +0 -0
  34. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/config.py +0 -0
  35. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/exceptions.py +0 -0
  36. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/df_reader/reader.py +0 -0
  37. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/errors/__init__.py +0 -0
  38. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/__init__.py +0 -0
  39. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/__init__.py +0 -0
  40. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/aws_s3.py +0 -0
  41. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/azure.py +0 -0
  42. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/azure_abfs.py +0 -0
  43. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/backends/local.py +0 -0
  44. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/filestore.py +0 -0
  45. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager/filestore/log.py +0 -0
  46. {oasis_data_manager-0.2.2 → oasis_data_manager-0.2.4}/oasis_data_manager.egg-info/dependency_links.txt +0 -0
@@ -1,7 +1,6 @@
1
1
  include README.md
2
2
  include LICENSE
3
3
  include CHANGELOG.rst
4
- include setup.cfg
5
- include requirements-package.in
4
+ include pyproject.toml
6
5
  recursive-exclude * __pycache__
7
6
  recursive-exclude * *.py[co]
@@ -0,0 +1,413 @@
1
+ Metadata-Version: 2.4
2
+ Name: oasis-data-manager
3
+ Version: 0.2.4
4
+ Author-email: Oasis LMF <support@oasislmf.org>
5
+ License: BSD-3-Clause
6
+ Project-URL: Homepage, https://github.com/OasisLMF/OasisDataManager
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: fastparquet
10
+ Requires-Dist: fsspec>=2023.12.2
11
+ Requires-Dist: pandas
12
+ Requires-Dist: typing_extensions
13
+ Requires-Dist: xxhash
14
+ Provides-Extra: geo
15
+ Requires-Dist: geopandas==0.14.4; extra == "geo"
16
+ Requires-Dist: pyogrio; extra == "geo"
17
+ Provides-Extra: dask
18
+ Requires-Dist: oasis-data-manager[geo]; extra == "dask"
19
+ Requires-Dist: dask>2024.1.1; extra == "dask"
20
+ Requires-Dist: dask-geopandas; extra == "dask"
21
+ Requires-Dist: dask-sql; extra == "dask"
22
+ Requires-Dist: distributed; extra == "dask"
23
+ Provides-Extra: s3
24
+ Requires-Dist: s3fs>=2023.12.2; extra == "s3"
25
+ Provides-Extra: azure
26
+ Requires-Dist: adlfs; extra == "azure"
27
+ Provides-Extra: zstd
28
+ Requires-Dist: zstandard; python_version < "3.14" and extra == "zstd"
29
+ Provides-Extra: extra
30
+ Requires-Dist: oasis-data-manager[geo]; extra == "extra"
31
+ Requires-Dist: oasis-data-manager[dask]; extra == "extra"
32
+ Requires-Dist: oasis-data-manager[s3]; extra == "extra"
33
+ Requires-Dist: oasis-data-manager[azure]; extra == "extra"
34
+ Requires-Dist: oasis-data-manager[zstd]; extra == "extra"
35
+
36
+ # OasisDataManager
37
+
38
+ A Python library providing unified data access patterns across different storage backends and DataFrame engines, as part of the [OasisLMF](https://github.com/OasisLMF) catastrophe modelling platform.
39
+
40
+ It abstracts:
41
+ - **File I/O** — local filesystem, AWS S3, Azure Blob Storage
42
+ - **DataFrame reading** — pandas, Dask, PyArrow
43
+ - **Data pipelines** — fetch → filter → SQL → transform, composable via a fluent API
44
+
45
+ ---
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ # Core install (pandas + local storage only)
51
+ pip install oasis-data-manager
52
+
53
+ # Development install
54
+ pip install -e .
55
+ pip install -r requirements.txt
56
+
57
+ # With optional cloud and distributed features (Dask, S3, Azure, PyArrow)
58
+ pip install -e ".[extra]"
59
+ ```
60
+
61
+ ### Optional dependencies
62
+
63
+ The package ships several optional extras. Install any combination with `pip install oasis-data-manager[<extra>,...]`.
64
+
65
+ | Extra | What it adds | Key packages |
66
+ |---|---|---|
67
+ | `s3` | AWS S3 storage backend (`AwsS3Storage`) | `s3fs` |
68
+ | `azure` | Azure Blob Storage backend (`AzureABFSStorage`) | `adlfs` |
69
+ | `geo` | Geospatial DataFrame support (GeoDataFrame read/write) | `geopandas`, `pyogrio` |
70
+ | `dask` | Dask reader, distributed execution, and geospatial Dask support | `dask`, `dask-sql`, `distributed`, `dask-geopandas` (includes `geo`) |
71
+ | `extra` | Everything above bundled together | all of the above |
72
+
73
+ **Examples**
74
+
75
+ ```bash
76
+ # S3 support only
77
+ pip install "oasis-data-manager[s3]"
78
+
79
+ # Both cloud backends
80
+ pip install "oasis-data-manager[s3,azure]"
81
+
82
+ # Dask reader (also installs geo)
83
+ pip install "oasis-data-manager[dask]"
84
+
85
+ # Everything
86
+ pip install "oasis-data-manager[extra]"
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Quick start
92
+
93
+ ```python
94
+ from oasis_data_manager.df_reader.backends.pandas import OasisPandasReader
95
+ from oasis_data_manager.filestore.backends.local import LocalStorage
96
+
97
+ storage = LocalStorage("/data")
98
+
99
+ # Read a CSV and get a pandas DataFrame
100
+ df = OasisPandasReader("accounts.csv", storage).as_pandas()
101
+
102
+ # Chain filters
103
+ df = (
104
+ OasisPandasReader("accounts.csv", storage)
105
+ .filter([lambda x: x[x["PortNumber"] == "1"]])
106
+ .as_pandas()
107
+ )
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Storage backends
113
+
114
+ Three backends are provided. All share the same interface.
115
+
116
+ ### Local
117
+
118
+ ```python
119
+ from oasis_data_manager.filestore.backends.local import LocalStorage
120
+
121
+ storage = LocalStorage(root_dir="/data")
122
+ ```
123
+
124
+ ### AWS S3
125
+
126
+ ```python
127
+ from oasis_data_manager.filestore.backends.aws import AwsS3Storage
128
+
129
+ storage = AwsS3Storage(
130
+ bucket_name="my-bucket",
131
+ access_key="AKIA...",
132
+ secret_key="...",
133
+ root_dir="models/", # optional sub-path within the bucket
134
+ )
135
+ ```
136
+
137
+ ### Azure Blob Storage
138
+
139
+ ```python
140
+ from oasis_data_manager.filestore.backends.azure import AzureABFSStorage
141
+
142
+ storage = AzureABFSStorage(
143
+ account_name="myaccount",
144
+ account_key="...",
145
+ azure_container="my-container",
146
+ root_dir="models/", # optional sub-path within the container
147
+ )
148
+ ```
149
+
150
+ ### Configuration dict pattern
151
+
152
+ Used throughout the OasisLMF platform to configure storage from serialisable dicts:
153
+
154
+ ```python
155
+ from oasis_data_manager.filestore.config import get_storage_from_config
156
+
157
+ config = {
158
+ "storage_class": "AwsS3Storage",
159
+ "options": {
160
+ "bucket_name": "my-bucket",
161
+ "access_key": "AKIA...",
162
+ "secret_key": "...",
163
+ }
164
+ }
165
+ storage = get_storage_from_config(config)
166
+ ```
167
+
168
+ ### Common storage operations
169
+
170
+ ```python
171
+ # Open a file (context manager, like built-in open)
172
+ with storage.open("path/to/file.csv") as f:
173
+ data = f.read()
174
+
175
+ # Copy a file to a local temp directory
176
+ local_path = storage.get("remote/file.parquet", "/tmp/")
177
+
178
+ # Upload a file
179
+ storage.put("/tmp/output.csv", "remote/output.csv")
180
+
181
+ # Delete
182
+ storage.delete_file("remote/old.csv")
183
+ ```
184
+
185
+ ---
186
+
187
+ ## DataFrame readers
188
+
189
+ ### Reader backends
190
+
191
+ | Class | Engine | Formats | Filter behaviour |
192
+ |---|---|---|---|
193
+ | `OasisPandasReader` | pandas | CSV, Parquet | In-memory (post-load) |
194
+ | `OasisDaskReader` | Dask | CSV, Parquet | In-memory via dask-sql |
195
+ | `OasisPyarrowReader` | PyArrow | Parquet only | Predicate pushdown (pre-load) |
196
+
197
+ Format-specific subclasses (`OasisPandasReaderCSV`, `OasisDaskReaderParquet`, etc.) are available for Pandas and Dask, but only base OasisPyarrowReader is available and uses parquet.
198
+
199
+ ### Fluent API
200
+
201
+ All readers share the same chainable interface. The actual file read is **lazy** — it happens on the first access to `.df` or when `.as_pandas()` is called.
202
+
203
+ ```python
204
+ from oasis_data_manager.df_reader.backends.pandas import OasisPandasReader
205
+ from oasis_data_manager.df_reader.backends.dask import OasisDaskReader
206
+ from oasis_data_manager.filestore.backends.local import LocalStorage
207
+
208
+ storage = LocalStorage("/data")
209
+
210
+ # Pandas — CSV
211
+ df = OasisPandasReader("losses.csv", storage).as_pandas()
212
+
213
+ # Pandas — Parquet (detected automatically from extension)
214
+ df = OasisPandasReader("losses.parquet", storage).as_pandas()
215
+
216
+ # Dask
217
+ df = OasisDaskReader("losses.csv", storage).as_pandas()
218
+ ```
219
+
220
+ ### Filtering
221
+
222
+ Pass a list of callables; each receives the DataFrame and must return a (filtered) DataFrame.
223
+
224
+ ```python
225
+ df = (
226
+ OasisPandasReader("locations.csv", storage)
227
+ .filter([
228
+ lambda x: x[x["CountryCode"] == "US"],
229
+ lambda x: x[x["LocNumber"].notna()],
230
+ ])
231
+ .as_pandas()
232
+ )
233
+ ```
234
+
235
+ `OasisPandasReader` and `OasisDaskReader` apply filters **after** loading the full file into memory. `OasisPyarrowReader` accepts a `filters` kwarg (list of tuples or list of lists) that is pushed down into the Parquet engine before any data is read into memory — use this for large Parquet files where row-group skipping matters.
236
+
237
+ ```python
238
+ from oasis_data_manager.df_reader.backends.pyarrow import OasisPyarrowReader
239
+
240
+ # AND of conditions — list of tuples
241
+ df = (
242
+ OasisPyarrowReader("losses.parquet", storage)
243
+ .read(filters=[("CountryCode", "==", "US"), ("TIV", ">=", 1_000_000)])
244
+ .as_pandas()
245
+ )
246
+
247
+ # OR of AND-groups — list of lists
248
+ df = (
249
+ OasisPyarrowReader("losses.parquet", storage)
250
+ .read(filters=[[("CountryCode", "==", "US")], [("CountryCode", "==", "GB")]])
251
+ .as_pandas()
252
+ )
253
+ ```
254
+
255
+ Supported operators: `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not in`.
256
+
257
+ ### SQL (Dask only)
258
+
259
+ Requires `dask-sql`. The reserved table name is `table`.
260
+
261
+ ```python
262
+ from oasis_data_manager.df_reader.backends.dask import OasisDaskReader
263
+
264
+ df = (
265
+ OasisDaskReader("locations.csv", storage)
266
+ .sql("SELECT LocNumber, Latitude, Longitude FROM table WHERE CountryCode = 'US'")
267
+ .as_pandas()
268
+ )
269
+ ```
270
+
271
+ ### Arbitrary queries
272
+
273
+ `.query(fn)` passes the raw DataFrame to any callable and returns the result directly (not a reader).
274
+
275
+ ```python
276
+ count = OasisPandasReader("losses.csv", storage).query(lambda df: len(df))
277
+ ```
278
+
279
+ ### Configuration dict pattern
280
+
281
+ ```python
282
+ from oasis_data_manager.df_reader.config import get_df_reader
283
+
284
+ config = {
285
+ "path": "accounts.csv",
286
+ "storage": storage,
287
+ "options": {"dtype": {"LocNumber": str}},
288
+ "engine": "OasisPandasReaderCSV",
289
+ }
290
+ reader = get_df_reader(config)
291
+ df = reader.as_pandas()
292
+ ```
293
+
294
+ ---
295
+
296
+ ## Complex data pipelines
297
+
298
+ `ComplexData` composes storage fetch, SQL filtering, and post-read transformations into a single reusable class.
299
+
300
+ ### `FileStoreComplexData` — files not handled by the df_reader (e.g. HDF5)
301
+
302
+ ```python
303
+ from oasis_data_manager.complex import FileStoreComplexData, Adjustment
304
+ import h5py
305
+ import pandas as pd
306
+
307
+ class NormaliseAdjustment(Adjustment):
308
+ @classmethod
309
+ def apply(cls, df):
310
+ df["loss"] = df["loss"] / df["loss"].max()
311
+ return df
312
+
313
+ class EventLossData(FileStoreComplexData):
314
+ filename = "event_losses.hdf5"
315
+ sql = "SELECT * FROM table WHERE event_id > 1000"
316
+ adjustments = [NormaliseAdjustment]
317
+
318
+ def to_dataframe(self, result) -> pd.DataFrame:
319
+ f = h5py.File(result)
320
+ return pd.DataFrame({"event_id": list(f["event_id"]), "loss": list(f["loss"])})
321
+
322
+ # Run the pipeline
323
+ df = EventLossData(storage=storage).run().as_pandas()
324
+ ```
325
+
326
+ ### `RestComplexData` — HTTP endpoints
327
+
328
+ ```python
329
+ from oasis_data_manager.complex import RestComplexData
330
+
331
+ class ExposureAPI(RestComplexData):
332
+ url = "https://api.example.com/exposures"
333
+ timeout = 30
334
+
335
+ def get_headers(self):
336
+ return {"Authorization": "Bearer my-token"}
337
+
338
+ def handle_response(self, response):
339
+ return response.json()["data"]
340
+
341
+ df = ExposureAPI().run().as_pandas()
342
+ ```
343
+
344
+ ---
345
+
346
+ ## Exceptions
347
+
348
+ | Exception | Description |
349
+ |---|---|
350
+ | `OasisDataManagerException` | Base exception for this library |
351
+ | `OasisException` | Backward-compatible alias for the above |
352
+ | `MissingInputsException` | Raised when a required input file is not found |
353
+
354
+ ```python
355
+ from oasis_data_manager.errors import OasisDataManagerException, MissingInputsException
356
+ ```
357
+
358
+ ---
359
+
360
+ ## Import paths
361
+
362
+ ```python
363
+ # Storage backends
364
+ from oasis_data_manager.filestore.backends.local import LocalStorage
365
+ from oasis_data_manager.filestore.backends.aws import AwsS3Storage
366
+ from oasis_data_manager.filestore.backends.azure import AzureABFSStorage
367
+ from oasis_data_manager.filestore.config import get_storage_from_config
368
+
369
+ # DataFrame readers
370
+ from oasis_data_manager.df_reader.backends.pandas import OasisPandasReader, OasisPandasReaderCSV, OasisPandasReaderParquet
371
+ from oasis_data_manager.df_reader.backends.dask import OasisDaskReader, OasisDaskReaderCSV, OasisDaskReaderParquet
372
+ from oasis_data_manager.df_reader.backends.pyarrow import OasisPyarrowReader
373
+ from oasis_data_manager.df_reader.config import get_df_reader
374
+
375
+ # Exceptions
376
+ from oasis_data_manager.errors import OasisDataManagerException, OasisException
377
+ ```
378
+
379
+ Deprecated module paths (`filestore/backends/aws_s3.py`, `filestore/backends/azure_abfs.py`) still work but emit a `DeprecationWarning`.
380
+
381
+ ---
382
+
383
+ ## Development
384
+
385
+ ```bash
386
+ # Install dev dependencies
387
+ pip install -e .
388
+ pip install -r requirements.txt
389
+
390
+ # Run tests
391
+ pytest
392
+
393
+ # Skip type checking and import sorting for faster iteration
394
+ pytest --no-header -p no:mypy -p no:isort tests/df_reader/
395
+
396
+ # Cloud integration tests (requires Docker)
397
+ docker compose up -d
398
+ pytest tests/filestorage/test_aws.py tests/filestorage/test_azure.py
399
+ docker compose down
400
+
401
+ # Linting
402
+ flake8 --select F401,F522,F524,F541 --show-source ./
403
+ autopep8 --diff --exit-code --recursive --max-line-length 150 --ignore E402 .
404
+
405
+ # Build
406
+ python setup.py sdist && python setup.py bdist_wheel
407
+ ```
408
+
409
+ ---
410
+
411
+ ## License
412
+
413
+ Part of the [OasisLMF](https://github.com/OasisLMF) platform. See repository for licence details.
@@ -23,6 +23,34 @@ pip install -r requirements.txt
23
23
  pip install -e ".[extra]"
24
24
  ```
25
25
 
26
+ ### Optional dependencies
27
+
28
+ The package ships several optional extras. Install any combination with `pip install oasis-data-manager[<extra>,...]`.
29
+
30
+ | Extra | What it adds | Key packages |
31
+ |---|---|---|
32
+ | `s3` | AWS S3 storage backend (`AwsS3Storage`) | `s3fs` |
33
+ | `azure` | Azure Blob Storage backend (`AzureABFSStorage`) | `adlfs` |
34
+ | `geo` | Geospatial DataFrame support (GeoDataFrame read/write) | `geopandas`, `pyogrio` |
35
+ | `dask` | Dask reader, distributed execution, and geospatial Dask support | `dask`, `dask-sql`, `distributed`, `dask-geopandas` (includes `geo`) |
36
+ | `extra` | Everything above bundled together | all of the above |
37
+
38
+ **Examples**
39
+
40
+ ```bash
41
+ # S3 support only
42
+ pip install "oasis-data-manager[s3]"
43
+
44
+ # Both cloud backends
45
+ pip install "oasis-data-manager[s3,azure]"
46
+
47
+ # Dask reader (also installs geo)
48
+ pip install "oasis-data-manager[dask]"
49
+
50
+ # Everything
51
+ pip install "oasis-data-manager[extra]"
52
+ ```
53
+
26
54
  ---
27
55
 
28
56
  ## Quick start
@@ -0,0 +1 @@
1
+ __version__ = '0.2.4'
@@ -0,0 +1,113 @@
1
+ """Tar archive helpers used by the storage backends to `put` and `extract` directories
2
+
3
+ Archives are written as gzip (``tar.gz``, the default) or zstandard (``tar.zst``).
4
+ zstd uses the standard library ``compression.zstd`` module on Python 3.14+, or the
5
+ ``zstandard`` package (``pip install oasis-data-manager[zstd]``) on older versions.
6
+ """
7
+ import contextlib
8
+ import os
9
+ import tarfile
10
+
11
+ from oasis_data_manager.errors import OasisDataManagerException
12
+
13
+ GZIP = "gz"
14
+ ZSTD = "zst"
15
+ ARCHIVE_SUFFIXES = {GZIP: "tar.gz", ZSTD: "tar.zst"}
16
+
17
+ # Speed over size: on Oasis inputs gzip level 1 is ~11x faster than level 9 for a ~10% larger archive
18
+ DEFAULT_COMPRESSLEVEL = {GZIP: 1, ZSTD: 3}
19
+
20
+ ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
21
+
22
+
23
+ def validate_compression(compression):
24
+ if compression not in ARCHIVE_SUFFIXES:
25
+ raise OasisDataManagerException(
26
+ f"Unsupported archive compression '{compression}', expected one of {list(ARCHIVE_SUFFIXES)}"
27
+ )
28
+ return compression
29
+
30
+
31
+ def _zstd_threads(threads):
32
+ """-1 uses every available core, 0 compresses in the calling thread"""
33
+ if threads is None or threads < 0:
34
+ return os.cpu_count() or 1
35
+ return threads
36
+
37
+
38
+ def _stdlib_zstd():
39
+ try:
40
+ from compression import zstd
41
+ except ImportError:
42
+ return None
43
+ return zstd
44
+
45
+
46
+ def _zstandard():
47
+ try:
48
+ import zstandard
49
+ except ImportError:
50
+ raise OasisDataManagerException(
51
+ "zstd archives need Python 3.14+ or the 'zstandard' package, install with 'pip install oasis-data-manager[zstd]'"
52
+ )
53
+ return zstandard
54
+
55
+
56
+ def is_zstd(archive_fp):
57
+ with open(archive_fp, "rb") as f:
58
+ return f.read(4) == ZSTD_MAGIC
59
+
60
+
61
+ def compress_dir(archive_fp, directory, arcname="/", compression=GZIP, compresslevel=None, threads=-1):
62
+ """Write `directory` to a tar archive at `archive_fp`
63
+
64
+ :param compression: `gz` or `zst`
65
+ :param compresslevel: compression level, defaults to `DEFAULT_COMPRESSLEVEL` for the format
66
+ :param threads: zstd worker threads, -1 for every core (ignored for gzip)
67
+ """
68
+ validate_compression(compression)
69
+ level = DEFAULT_COMPRESSLEVEL[compression] if compresslevel is None else int(compresslevel)
70
+
71
+ if compression == GZIP:
72
+ with tarfile.open(archive_fp, "w:gz", compresslevel=level) as tar:
73
+ tar.add(directory, arcname=arcname)
74
+ return
75
+
76
+ threads = _zstd_threads(threads)
77
+ zstd = _stdlib_zstd()
78
+ if zstd:
79
+ options = {zstd.CompressionParameter.compression_level: level}
80
+ if threads and zstd.CompressionParameter.nb_workers.bounds()[1] > 0:
81
+ options[zstd.CompressionParameter.nb_workers] = threads
82
+ with tarfile.open(archive_fp, "w:zst", options=options) as tar:
83
+ tar.add(directory, arcname=arcname)
84
+ return
85
+
86
+ cctx = _zstandard().ZstdCompressor(level=level, threads=threads)
87
+ with open(archive_fp, "wb") as fh, cctx.stream_writer(fh, closefd=False) as writer, \
88
+ tarfile.open(fileobj=writer, mode="w|") as tar:
89
+ tar.add(directory, arcname=arcname)
90
+
91
+
92
+ @contextlib.contextmanager
93
+ def open_archive(archive_fp):
94
+ """Open a gzip, zstd or uncompressed tar archive for reading
95
+
96
+ zstd archives read with the `zstandard` package are opened as a stream: iterate or `extractall`,
97
+ don't seek back to earlier members.
98
+ """
99
+ # tarfile detects zstd itself when compression.zstd is available
100
+ if _stdlib_zstd() or not is_zstd(archive_fp):
101
+ with tarfile.open(archive_fp) as tar:
102
+ yield tar
103
+ return
104
+
105
+ dctx = _zstandard().ZstdDecompressor()
106
+ with open(archive_fp, "rb") as fh, dctx.stream_reader(fh) as reader, tarfile.open(fileobj=reader, mode="r|") as tar:
107
+ yield tar
108
+
109
+
110
+ def extract_archive(archive_fp, directory):
111
+ with open_archive(archive_fp) as tar:
112
+ os.makedirs(directory, exist_ok=True)
113
+ tar.extractall(directory)
@@ -19,6 +19,7 @@ class AwsS3Storage(BaseStorage):
19
19
  access_key: Optional[str] = None,
20
20
  secret_key: Optional[str] = None,
21
21
  endpoint_url: Optional[str] = None,
22
+ public_bucket: bool = False,
22
23
  file_overwrite=True,
23
24
  object_parameters: Optional[dict] = None,
24
25
  auto_create_bucket=False,
@@ -92,6 +93,7 @@ class AwsS3Storage(BaseStorage):
92
93
  self.access_key = access_key
93
94
  self.secret_key = secret_key
94
95
  self.endpoint_url = endpoint_url
96
+ self.public_bucket = public_bucket
95
97
  self.file_overwrite = file_overwrite
96
98
  self.object_parameters = object_parameters
97
99
  self.auto_create_bucket = auto_create_bucket
@@ -128,6 +130,7 @@ class AwsS3Storage(BaseStorage):
128
130
  "access_key": self.access_key,
129
131
  "secret_key": self.secret_key,
130
132
  "endpoint_url": self.endpoint_url,
133
+ "public_bucket": self.public_bucket,
131
134
  "file_overwrite": self.file_overwrite,
132
135
  "object_parameters": self.object_parameters,
133
136
  "auto_create_bucket": self.auto_create_bucket,
@@ -163,7 +166,7 @@ class AwsS3Storage(BaseStorage):
163
166
  if self.reduced_redundancy:
164
167
  s3_additional_kwargs["StorageClass"] = "REDUCED_REDUNDANCY"
165
168
 
166
- return {
169
+ options = {
167
170
  "key": self.access_key,
168
171
  "secret": self.secret_key,
169
172
  "token": self.security_token,
@@ -174,6 +177,9 @@ class AwsS3Storage(BaseStorage):
174
177
  "region_name": self.region_name,
175
178
  },
176
179
  }
180
+ if self.public_bucket:
181
+ options["anon"] = True
182
+ return options
177
183
 
178
184
  def _strip_signing_parameters(self, url):
179
185
  """Duplicated Unsiged URLs from Django-Stroage
@@ -255,12 +261,12 @@ class AwsS3Storage(BaseStorage):
255
261
  else:
256
262
  return self._strip_signing_parameters(url)
257
263
 
258
- def put(self, reference, filename=None, subdir="", suffix=None, arcname=None):
264
+ def put(self, reference, filename=None, subdir="", suffix=None, arcname=None, compression=None):
259
265
  # Prepend location so the returned key is bucket-relative (location/subdir/file).
260
266
  # The server's CopyObject and is_in_bucket() both use the raw bucket key, so the
261
267
  # returned value must include the location prefix, not be relative to it.
262
268
  effective_subdir = os.path.join(self.location, subdir) if self.location else subdir
263
- return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname)
269
+ return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname, compression=compression)
264
270
 
265
271
  def get_storage_url(self, filename=None, suffix="tar.gz", encode_params=True):
266
272
  filename = (