pyBiocFileCache 0.6.2__py3-none-any.whl → 0.7.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.
pybiocfilecache/cache.py CHANGED
@@ -5,6 +5,7 @@ from pathlib import Path
5
5
  from time import sleep, time
6
6
  from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
7
7
 
8
+ from biocframe import BiocFrame
8
9
  from sqlalchemy import create_engine, func, text
9
10
  from sqlalchemy.orm import Session, sessionmaker
10
11
  from sqlalchemy.pool import QueuePool
@@ -14,6 +15,7 @@ from .const import SCHEMA_VERSION
14
15
  from .models import Base, Metadata, Resource
15
16
  from .utils import (
16
17
  calculate_file_hash,
18
+ convert_to_columnar,
17
19
  copy_or_move,
18
20
  create_tmp_dir,
19
21
  download_web_file,
@@ -104,15 +106,19 @@ class BiocFileCache:
104
106
 
105
107
  return SCHEMA_VERSION
106
108
 
107
- def _get_detached_resource(
108
- self, session: Session, obj: Union[Resource, Metadata]
109
- ) -> Optional[Union[Resource, Metadata]]:
109
+ def _get_detached_resource(self, session: Session, obj: Union[Resource, Metadata]) -> Optional[dict]:
110
110
  """Get a detached copy of a resource."""
111
111
  if obj is None:
112
112
  return None
113
113
  session.refresh(obj)
114
114
  session.expunge(obj)
115
- return obj
115
+ obj_dict = obj.to_dict()
116
+
117
+ if isinstance(obj, Resource):
118
+ if obj_dict["rtype"] == "relative":
119
+ obj_dict["rpath"] = f"{self.config.cache_dir}/{obj_dict['rpath']}"
120
+
121
+ return obj_dict
116
122
 
117
123
  def __enter__(self) -> "BiocFileCache":
118
124
  return self
@@ -137,6 +143,10 @@ class BiocFileCache:
137
143
  finally:
138
144
  session.close()
139
145
 
146
+ #########################
147
+ ######>> cleanup <<######
148
+ #########################
149
+
140
150
  # def _validate_rname(self, rname: str) -> None:
141
151
  # """Validate resource name format."""
142
152
  # if not validate_rname(rname, self.config.rname_pattern):
@@ -191,7 +201,11 @@ class BiocFileCache:
191
201
  self._last_cleanup = datetime.now()
192
202
  return removed
193
203
 
194
- def get(self, rname: str = None, rid: str = None) -> Optional[Resource]:
204
+ ###############################
205
+ ######>> get resources <<######
206
+ ###############################
207
+
208
+ def get(self, rname: str = None, rid: str = None) -> Optional[dict]:
195
209
  """Get resource by name from cache.
196
210
 
197
211
  Args:
@@ -215,11 +229,9 @@ class BiocFileCache:
215
229
  # Check if path exists with timeout
216
230
  start = time()
217
231
  timeout = 30
218
- while not Path(str(resource.rpath)).exists():
232
+ while not Path(str(self.config.cache_dir / resource.rpath)).exists():
219
233
  if time() - start >= timeout:
220
- raise TimeoutError(
221
- f"For resource: '{rname}' the rpath does not exist " f"after {timeout} seconds."
222
- )
234
+ raise TimeoutError(f"For resource: '{rname}' the rpath does not exist after {timeout} seconds.")
223
235
  sleep(0.1)
224
236
 
225
237
  # Update access time
@@ -238,7 +250,7 @@ class BiocFileCache:
238
250
  expires: Optional[datetime] = None,
239
251
  download: bool = True,
240
252
  ext: bool = True,
241
- ) -> Resource:
253
+ ) -> dict:
242
254
  """Add a resource to the cache.
243
255
 
244
256
  Args:
@@ -270,7 +282,7 @@ class BiocFileCache:
270
282
  Defaults to `True`.
271
283
 
272
284
  Returns:
273
- The `Resource` object added to the cache.
285
+ The `Resource` object added to the cache as dictionary.
274
286
  """
275
287
  # self._validate_rname(rname)
276
288
  fpath = Path(fpath) if rtype != "web" else fpath
@@ -291,7 +303,7 @@ class BiocFileCache:
291
303
  # Generate paths and check size
292
304
  rid = generate_id(size=len(self))
293
305
  uuid = generate_uuid()
294
- rpath = self.config.cache_dir / f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath
306
+ rpath = f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath
295
307
 
296
308
  # Create resource record
297
309
  resource = Resource(
@@ -309,10 +321,10 @@ class BiocFileCache:
309
321
  session.commit()
310
322
 
311
323
  try:
312
- copy_or_move(outpath, rpath, rname, action, False)
324
+ copy_or_move(outpath, self.config.cache_dir / rpath, rname, action, False)
313
325
 
314
326
  # Calculate and store checksum
315
- resource.etag = calculate_file_hash(rpath, self.config.hash_algorithm)
327
+ resource.etag = calculate_file_hash(self.config.cache_dir / rpath, self.config.hash_algorithm)
316
328
  session.commit()
317
329
  result = self._get_detached_resource(session, resource)
318
330
  return result
@@ -322,7 +334,7 @@ class BiocFileCache:
322
334
  session.commit()
323
335
  raise Exception("Failed to add resource") from e
324
336
 
325
- def add_batch(self, resources: List[Dict[str, Any]]) -> List[Resource]:
337
+ def add_batch(self, resources: List[Dict[str, Any]]) -> BiocFrame:
326
338
  """Add multiple resources in a single transaction.
327
339
 
328
340
  Args:
@@ -346,7 +358,7 @@ class BiocFileCache:
346
358
  rname: str,
347
359
  fpath: Union[str, Path],
348
360
  action: Literal["copy", "move", "asis"] = "copy",
349
- ) -> Resource:
361
+ ) -> dict:
350
362
  """Update an existing resource.
351
363
 
352
364
  Args:
@@ -361,7 +373,7 @@ class BiocFileCache:
361
373
  Defaults to ``copy``.
362
374
 
363
375
  Returns:
364
- Updated `Resource` object.
376
+ Updated `Resource` object as dictionary.
365
377
 
366
378
  """
367
379
  fpath = Path(fpath)
@@ -418,7 +430,7 @@ class BiocFileCache:
418
430
  session.rollback()
419
431
  raise Exception(f"Failed to remove resource '{rname}'") from e
420
432
 
421
- def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
433
+ def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> BiocFrame:
422
434
  """List resources in the cache with optional filtering.
423
435
 
424
436
  Args:
@@ -434,7 +446,7 @@ class BiocFileCache:
434
446
  Note: Resources with no expiration are always considered non-expired.
435
447
 
436
448
  Returns:
437
- List of Resource objects matching the filters
449
+ List of Resource objects matching the filters.
438
450
  """
439
451
  with self.get_session() as session:
440
452
  query = session.query(Resource)
@@ -454,7 +466,7 @@ class BiocFileCache:
454
466
  )
455
467
 
456
468
  resources = query.all()
457
- return [self._get_detached_resource(session, r) for r in resources]
469
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
458
470
 
459
471
  def validate_resource(self, resource: Resource) -> bool:
460
472
  """Validate resource integrity.
@@ -523,7 +535,7 @@ class BiocFileCache:
523
535
  invalid += 1
524
536
  return valid, invalid
525
537
 
526
- def search(self, query: str, field: str = "rname", exact: bool = False) -> List[Resource]:
538
+ def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame:
527
539
  """Search for resources by field value.
528
540
 
529
541
  Args:
@@ -545,7 +557,7 @@ class BiocFileCache:
545
557
  else:
546
558
  resources = session.query(Resource).filter(Resource[field].ilike(f"%{query}%")).all()
547
559
 
548
- return [self._get_detached_resource(session, r) for r in resources]
560
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
549
561
 
550
562
  def get_stats(self) -> Dict[str, Any]:
551
563
  """Get statistics about the cache."""
@@ -671,7 +683,7 @@ class BiocFileCache:
671
683
  except Exception as e:
672
684
  session.delete(meta)
673
685
  session.commit()
674
- raise Exception("Failed to add metadata") from e
686
+ raise Exception("Failed to add metadata", str(e)) from e
675
687
  else:
676
688
  raise Exception(f"'key'={key} already exists in metadata.")
677
689
 
pybiocfilecache/models.py CHANGED
@@ -19,6 +19,9 @@ class Metadata(Base):
19
19
  def __repr__(self) -> str:
20
20
  return f"<Metadata(key='{self.key}', value='{self.value}')>"
21
21
 
22
+ def to_dict(self) -> dict:
23
+ return {"key": self.key, "value": self.value}
24
+
22
25
 
23
26
  class Resource(Base):
24
27
  """Resource information stored in cache.
@@ -74,3 +77,18 @@ class Resource(Base):
74
77
 
75
78
  def __repr__(self) -> str:
76
79
  return f"<Resource(rid='{self.rid}', rname='{self.rname}', rpath='{self.rpath}')>"
80
+
81
+ def to_dict(self) -> dict:
82
+ return {
83
+ "id": self.id,
84
+ "rid": self.rid,
85
+ "rname": self.rname,
86
+ "create_time": self.create_time,
87
+ "access_time": self.access_time,
88
+ "rpath": self.rpath,
89
+ "rtype": self.rtype,
90
+ "fpath": self.fpath,
91
+ "last_modified_time": self.last_modified_time,
92
+ "etag": self.etag,
93
+ "expires": self.expires,
94
+ }
pybiocfilecache/utils.py CHANGED
@@ -7,7 +7,7 @@ import uuid
7
7
  import zlib
8
8
  from pathlib import Path
9
9
  from shutil import copy2, move
10
- from typing import Literal
10
+ from typing import List, Literal
11
11
 
12
12
  __author__ = "Jayaram Kancherla"
13
13
  __copyright__ = "Jayaram Kancherla"
@@ -97,3 +97,16 @@ def download_web_file(url: str, filename: str, download: bool):
97
97
  open(str(outpath), "a").close()
98
98
 
99
99
  return outpath
100
+
101
+
102
+ def convert_to_columnar(list_of_dicts: List[dict]):
103
+ if not list_of_dicts:
104
+ return {}
105
+
106
+ column_names = list_of_dicts[0].keys()
107
+ result = {col: [] for col in column_names}
108
+
109
+ for row in list_of_dicts:
110
+ for col in column_names:
111
+ result[col].append(row.get(col))
112
+ return result
@@ -1,12 +1,12 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: pyBiocFileCache
3
- Version: 0.6.2
3
+ Version: 0.7.0
4
4
  Summary: File based cache for resources and metadata
5
- Home-page: https://github.com/epiviz/pyBiocFileCache
5
+ Home-page: https://github.com/biocpy/pyBiocFileCache
6
6
  Author: jkanche
7
7
  Author-email: jayaram.kancherla@gmail.com
8
8
  License: MIT
9
- Project-URL: Documentation, https://pyscaffold.org/
9
+ Project-URL: Documentation, https://github.com/biocpy/pyBiocFileCache
10
10
  Platform: any
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Programming Language :: Python
@@ -16,10 +16,12 @@ License-File: LICENSE.txt
16
16
  License-File: AUTHORS.md
17
17
  Requires-Dist: importlib-metadata; python_version < "3.8"
18
18
  Requires-Dist: sqlalchemy
19
+ Requires-Dist: biocframe
19
20
  Provides-Extra: testing
20
21
  Requires-Dist: setuptools; extra == "testing"
21
22
  Requires-Dist: pytest; extra == "testing"
22
23
  Requires-Dist: pytest-cov; extra == "testing"
24
+ Dynamic: license-file
23
25
 
24
26
  [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
25
27
  [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
@@ -52,7 +54,7 @@ resource = cache.add("myfile", "path/to/file.txt")
52
54
  resource = cache.get("myfile")
53
55
 
54
56
  # Use the cached file
55
- print(resource.rpath) # Path to cached file
57
+ print(resource["rpath"]) # Path to cached file
56
58
  ```
57
59
 
58
60
  ## Advanced Usage
@@ -0,0 +1,12 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=VELZ8Ao_9clIUvKXjkCSFsXwf8KK2s4yLOJWT4xxneo,23666
3
+ pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
4
+ pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
+ pybiocfilecache/models.py,sha256=ahnGpEhoZzXzvzb9lphs45uU2wts-_q26LOA_P3URKo,2517
6
+ pybiocfilecache/utils.py,sha256=M59NG_oMVvVw03t1hDNaaKtcBZWY4U0KSfpQx_L5U1Y,2981
7
+ pybiocfilecache-0.7.0.dist-info/licenses/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
8
+ pybiocfilecache-0.7.0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
9
+ pybiocfilecache-0.7.0.dist-info/METADATA,sha256=4qvcDLIDVooC3kNk-38vk2ETPgRC9XoDeSvqHns0gR4,3015
10
+ pybiocfilecache-0.7.0.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
11
+ pybiocfilecache-0.7.0.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
12
+ pybiocfilecache-0.7.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.7.0)
2
+ Generator: setuptools (77.0.3)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,12 +0,0 @@
1
- pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
- pybiocfilecache/cache.py,sha256=CW_jjF2lIbUf-ZpNe3LXhNxrtLnLoeMRzTYxgigTwps,23171
3
- pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
4
- pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
- pybiocfilecache/models.py,sha256=qxOZqmvKLloNygiQgr2ECtgXCZbvxOA_JoLLeM18mRA,1967
6
- pybiocfilecache/utils.py,sha256=z0WSk9vSk3ivMJ4dRICQbbDj8JtgpeGzNMImyKPdROc,2659
7
- pyBiocFileCache-0.6.2.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
8
- pyBiocFileCache-0.6.2.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
9
- pyBiocFileCache-0.6.2.dist-info/METADATA,sha256=BEoKhTG5v4h8d0CS5C2VynWnN41SW7dDWo94w-Ob-Vw,2947
10
- pyBiocFileCache-0.6.2.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
11
- pyBiocFileCache-0.6.2.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
12
- pyBiocFileCache-0.6.2.dist-info/RECORD,,