zombie-squirrel 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.
@@ -0,0 +1,4 @@
1
+ """Init package"""
2
+ __version__ = "0.1.0"
3
+
4
+ from zombie_squirrel.squirrels import unique_project_names
@@ -0,0 +1,60 @@
1
+ # forest_cache/acorns.py
2
+ from abc import ABC, abstractmethod
3
+ import pandas as pd
4
+ import os
5
+
6
+ from aind_data_access_api.rds_tables import Client, RDSCredentials
7
+
8
+
9
+ def prefix_table_name(table_name: str) -> str:
10
+ return "zs_" + table_name
11
+
12
+
13
+ class Acorn(ABC):
14
+ """Base class for a storage backend (the cache)."""
15
+
16
+ def __init__(self) -> None:
17
+ super().__init__()
18
+
19
+ @abstractmethod
20
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
21
+ """Store records in the cache."""
22
+ pass
23
+
24
+ @abstractmethod
25
+ def scurry(self, table_name: str) -> pd.DataFrame:
26
+ """Fetch records from the cache."""
27
+ pass
28
+
29
+
30
+ class RedshiftAcorn(Acorn):
31
+ """Stores and retrieves caches using aind-data-access-api
32
+ Redshift Client"""
33
+
34
+ def __init__(self) -> None:
35
+ REDSHIFT_SECRETS = os.getenv("REDSHIFT_SECRETS", "/aind/prod/redshift/credentials/readwrite")
36
+ self.rds_client = Client(
37
+ credentials=RDSCredentials(aws_secrets_name=REDSHIFT_SECRETS),
38
+ )
39
+
40
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
41
+ self.rds_client.overwrite_table_with_df(
42
+ df=data,
43
+ table_name=prefix_table_name(table_name),
44
+ )
45
+
46
+ def scurry(self, table_name: str) -> pd.DataFrame:
47
+ return self.rds_client.read_table(table_name=prefix_table_name(table_name))
48
+
49
+
50
+ class MemoryAcorn(Acorn):
51
+ """A simple in-memory backend for testing or local development."""
52
+ def __init__(self) -> None:
53
+ super().__init__()
54
+ self._store: dict[str, pd.DataFrame] = {}
55
+
56
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
57
+ self._store[table_name] = data
58
+
59
+ def scurry(self, table_name: str) -> pd.DataFrame:
60
+ return self._store.get(table_name, pd.DataFrame())
@@ -0,0 +1,76 @@
1
+ """Squirrels: functions to fetch and cache data from MongoDB."""
2
+ import pandas as pd
3
+ from typing import Any, Callable, Optional
4
+ from zombie_squirrel.acorns import RedshiftAcorn, MemoryAcorn
5
+ from aind_data_access_api.document_db import MetadataDbClient
6
+ import os
7
+
8
+ # --- Backend setup ---------------------------------------------------
9
+
10
+ API_GATEWAY_HOST = "api.allenneuraldynamics.org"
11
+
12
+ tree_type = os.getenv("TREE_SPECIES", "memory").lower()
13
+
14
+ if tree_type == "redshift":
15
+ ACORN = RedshiftAcorn()
16
+ else:
17
+ ACORN = MemoryAcorn()
18
+
19
+ # --- Squirrel registry -----------------------------------------------------
20
+
21
+ SQUIRREL_REGISTRY: dict[str, Callable[[], Any]] = {}
22
+
23
+
24
+ def register_squirrel(name: str):
25
+ """Decorator for registering new squirrels."""
26
+ def decorator(func):
27
+ SQUIRREL_REGISTRY[name] = func
28
+ return func
29
+ return decorator
30
+
31
+
32
+ # --- Squirrels -----------------------------------------------------
33
+
34
+
35
+ @register_squirrel("unique-project-names")
36
+ def unique_project_names(force_update: bool = False) -> list[str]:
37
+ df = ACORN.scurry("unique-project-names")
38
+
39
+ if df.empty or force_update:
40
+ # If cache is missing, fetch data
41
+ client = MetadataDbClient(
42
+ host=API_GATEWAY_HOST,
43
+ version="v2",
44
+ )
45
+ unique_project_names = client.aggregate_docdb_records(
46
+ pipeline=[
47
+ {"$group": {"_id": "$data_description.project_name"}},
48
+ {"$project": {"project_name": "$_id", "_id": 0}},
49
+ ]
50
+ )
51
+ df = pd.DataFrame(unique_project_names)
52
+ ACORN.hide("unique-project-names", df)
53
+
54
+ return df["project_name"].tolist()
55
+
56
+
57
+ @register_squirrel("unique-subject-ids")
58
+ def unique_subject_ids(force_update: bool = False) -> list[str]:
59
+ df = ACORN.scurry("unique-subject-ids")
60
+
61
+ if df.empty or force_update:
62
+ # If cache is missing, fetch data
63
+ client = MetadataDbClient(
64
+ host=API_GATEWAY_HOST,
65
+ version="v2",
66
+ )
67
+ unique_subject_ids = client.aggregate_docdb_records(
68
+ pipeline=[
69
+ {"$group": {"_id": "$subject.subject_id"}},
70
+ {"$project": {"subject_id": "$_id", "_id": 0}},
71
+ ]
72
+ )
73
+ df = pd.DataFrame(unique_subject_ids)
74
+ ACORN.hide("unique-subject-ids", df)
75
+
76
+ return df["subject_id"].tolist()
@@ -0,0 +1,7 @@
1
+ """Sync all acorns"""
2
+ from .squirrels import SQUIRREL_REGISTRY
3
+
4
+
5
+ def hide_acorns():
6
+ for squirrel in SQUIRREL_REGISTRY.values():
7
+ squirrel(force_update=True)
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: zombie-squirrel
3
+ Version: 0.1.0
4
+ Summary: Generated from aind-library-template
5
+ Author: Allen Institute for Neural Dynamics
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: aind-data-access-api[docdb,rds]
12
+ Dynamic: license-file
13
+
14
+ # zombie-squirrel
15
+
16
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
17
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
18
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
19
+ ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
20
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)
21
+ ![Python](https://img.shields.io/badge/python->=3.10-blue?logo=python)
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install zombie-squirrel
27
+
28
+ ```bash
29
+ uv sync
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ### Set backend
35
+
36
+ ```bash
37
+ export REDSHIFT_SECRETS='/aind/prod/redshift/credentials/readwrite'
38
+ export TREE_SPECIES='REDSHIFT'
39
+ ```
40
+
41
+ Options are 'REDSHIFT', 'MEMORY'.
42
+
43
+ ### Scurry (fetch) data
44
+
45
+ ```python
46
+ import zombie_squirrel as zs
47
+
48
+ unique_project_names = zs.scurry_project_names()
49
+ ```
50
+
51
+ ### Hide the acorns
52
+
53
+ ```python
54
+ from zombie_squirrel.sync import hide_acorns
55
+ hide_acorns()
56
+ ```
@@ -0,0 +1,9 @@
1
+ zombie_squirrel/__init__.py,sha256=H8ylm8tAcxCbApkNWTsAt5kGs1AgPxrxrob-4n2ADpg,100
2
+ zombie_squirrel/acorns.py,sha256=3wiZE5RYzoSgUdnan6lCVlE7Xn5VeNDmDiIXHl0YQfA,1785
3
+ zombie_squirrel/squirrels.py,sha256=PTDw5DeRoLhdDwuKHAZsLnIAQulYc-A5b8021WaM0BI,2345
4
+ zombie_squirrel/sync.py,sha256=jslTVIend5Z-sLJuNXKkhn-nqmKK_P0FAiRuFFYRnto,168
5
+ zombie_squirrel-0.1.0.dist-info/licenses/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
6
+ zombie_squirrel-0.1.0.dist-info/METADATA,sha256=5LYlpZBrXyjcCPvZ3J62_E_SVzNeAQ94nHEDXAslxzk,1382
7
+ zombie_squirrel-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ zombie_squirrel-0.1.0.dist-info/top_level.txt,sha256=FmM0coe4AangURZLjM4JwwRv2B8H6oINYCoZLKLDCKA,16
9
+ zombie_squirrel-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Allen Institute for Neural Dynamics
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
+ zombie_squirrel