tigrbl_engine_numpy 0.1.1__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,26 @@
1
+ from .engine import NumpyEngine, numpy_capabilities, numpy_engine
2
+ from .session import NumpySession
3
+
4
+
5
+ class _Registration:
6
+ def build(self, *, mapping, spec, dsn):
7
+ return numpy_engine(mapping=mapping, spec=spec, dsn=dsn)
8
+
9
+ def capabilities(self, *, spec, mapping=None):
10
+ return numpy_capabilities()
11
+
12
+
13
+ def register() -> None:
14
+ """Entry-point hook invoked by tigrbl to register this engine."""
15
+ from tigrbl.engine.registry import register_engine
16
+
17
+ register_engine("numpy", _Registration())
18
+
19
+
20
+ __all__ = [
21
+ "NumpyEngine",
22
+ "NumpySession",
23
+ "numpy_engine",
24
+ "numpy_capabilities",
25
+ "register",
26
+ ]
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ import threading
6
+ from typing import Any, Callable
7
+
8
+ import numpy as np
9
+
10
+ from .session import NumpySession
11
+
12
+
13
+ @dataclass
14
+ class NumpyCatalog:
15
+ rows: list[dict[str, Any]] = field(default_factory=list)
16
+ columns: list[str] = field(default_factory=list)
17
+ pk: str = "id"
18
+ table_ver: int = 0
19
+ path: str | None = None
20
+ file_format: str | None = None
21
+ npz_key: str | None = None
22
+ lock: threading.RLock = field(default_factory=threading.RLock)
23
+
24
+ def bump(self) -> None:
25
+ self.table_ver += 1
26
+
27
+
28
+ @dataclass
29
+ class NumpyEngine:
30
+ """Single-table NumPy engine: one ndarray/memmap behaves like one table DB."""
31
+
32
+ array: np.ndarray
33
+ table: str
34
+ pk: str
35
+ columns: list[str]
36
+ catalog: NumpyCatalog
37
+
38
+
39
+ def _rows_from_array(array: np.ndarray, columns: list[str]) -> list[dict[str, Any]]:
40
+ if array.ndim == 0:
41
+ matrix = np.asarray([[array.item()]], dtype=object)
42
+ elif array.ndim == 1:
43
+ matrix = np.asarray(array, dtype=object).reshape(-1, 1)
44
+ else:
45
+ matrix = np.asarray(array, dtype=object)
46
+ return [dict(zip(columns, row, strict=False)) for row in matrix.tolist()]
47
+
48
+
49
+ def _resolve_array(config: dict[str, Any]) -> np.ndarray:
50
+ if (raw_array := config.get("array")) is not None:
51
+ return raw_array if isinstance(raw_array, np.ndarray) else np.asarray(raw_array)
52
+
53
+ if (
54
+ path_value := config.get("path")
55
+ or config.get("load_path")
56
+ or config.get("file")
57
+ ):
58
+ path = Path(path_value)
59
+ loaded = np.load(
60
+ path,
61
+ mmap_mode=config.get("mmap_mode"),
62
+ allow_pickle=True,
63
+ )
64
+ if isinstance(loaded, np.lib.npyio.NpzFile):
65
+ with loaded as archive:
66
+ npz_key = config.get("npz_key")
67
+ if npz_key is None:
68
+ if len(archive.files) != 1:
69
+ raise ValueError(
70
+ "mapping['npz_key'] is required for multi-array .npz files"
71
+ )
72
+ npz_key = archive.files[0]
73
+ return np.asarray(archive[npz_key])
74
+ return loaded
75
+
76
+ if (memmap_path := config.get("memmap_path")) is not None:
77
+ mode = config.get("memmap_mode", "r+")
78
+ valid_modes = {"r", "r+", "w+", "c"}
79
+ if mode not in valid_modes:
80
+ raise ValueError(
81
+ f"mapping['memmap_mode'] must be one of {sorted(valid_modes)}"
82
+ )
83
+ dtype = config.get("dtype", np.float64)
84
+ shape = config.get("shape")
85
+ if mode == "w+" and shape is None:
86
+ raise ValueError("mapping['shape'] is required when memmap_mode='w+'")
87
+ return np.memmap(memmap_path, dtype=dtype, mode=mode, shape=shape)
88
+
89
+ raise TypeError(
90
+ "Provide one of mapping['array'], mapping['path']/['load_path']/['file'], or mapping['memmap_path']"
91
+ )
92
+
93
+
94
+ def numpy_engine(
95
+ *, mapping: dict[str, Any] | None = None, **_: Any
96
+ ) -> tuple[NumpyEngine, Callable[[], NumpySession]]:
97
+ """Build the ``numpy`` engine handle and session factory for tigrbl."""
98
+ config = dict(mapping or {})
99
+ table = config.get("table", "records")
100
+ pk = config.get("pk", "id")
101
+ if not isinstance(table, str) or not table:
102
+ raise TypeError("mapping['table'] must be a non-empty string")
103
+ if not isinstance(pk, str) or not pk:
104
+ raise TypeError("mapping['pk'] must be a non-empty string")
105
+
106
+ array = _resolve_array(config)
107
+ inferred_cols = 1 if array.ndim <= 1 else int(array.shape[1])
108
+ columns = list(
109
+ config.get("columns") or [f"col_{idx}" for idx in range(inferred_cols)]
110
+ )
111
+ if pk not in columns:
112
+ columns = [pk, *columns]
113
+
114
+ storage_path = config.get("path") or config.get("load_path") or config.get("file")
115
+ resolved_path = str(Path(storage_path)) if isinstance(storage_path, str) else None
116
+ npz_key = config.get("npz_key") if isinstance(config.get("npz_key"), str) else None
117
+ file_format: str | None = None
118
+ if resolved_path:
119
+ suffix = Path(resolved_path).suffix.lower()
120
+ if suffix == ".npy":
121
+ file_format = "npy"
122
+ elif suffix == ".npz":
123
+ file_format = "npz"
124
+
125
+ rows = _rows_from_array(array, columns)
126
+ catalog = NumpyCatalog(
127
+ rows=rows,
128
+ columns=columns,
129
+ pk=pk,
130
+ path=resolved_path,
131
+ file_format=file_format,
132
+ npz_key=npz_key,
133
+ )
134
+ engine = NumpyEngine(
135
+ array=array, table=table, pk=pk, columns=columns, catalog=catalog
136
+ )
137
+
138
+ def session_factory() -> NumpySession:
139
+ return NumpySession(engine)
140
+
141
+ return engine, session_factory
142
+
143
+
144
+ def numpy_capabilities() -> dict[str, object]:
145
+ return {
146
+ "ndarray": True,
147
+ "single_table_database": True,
148
+ "file_formats": ["npy", "npz"],
149
+ "numpy_api": ["np.load", "np.memmap", "np.save"],
150
+ "memmap_modes": ["r", "r+", "w+", "c"],
151
+ "transactions": True,
152
+ "dialect": "numpy",
153
+ }
@@ -0,0 +1,580 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import tempfile
6
+
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Callable,
11
+ List,
12
+ Mapping,
13
+ Optional,
14
+ Sequence,
15
+ Tuple,
16
+ )
17
+
18
+ import numpy as np
19
+
20
+ try:
21
+ from tigrbl.session.base import TigrblSessionBase
22
+ except Exception:
23
+ from abc import ABC, abstractmethod
24
+
25
+ class TigrblSessionBase(ABC):
26
+ def __init__(self, spec=None):
27
+ self._spec = spec
28
+
29
+ def apply_spec(self, spec):
30
+ self._spec = spec
31
+
32
+ @abstractmethod
33
+ def _add_impl(self, obj): ...
34
+
35
+ @abstractmethod
36
+ async def _delete_impl(self, obj): ...
37
+
38
+ @abstractmethod
39
+ async def _flush_impl(self): ...
40
+
41
+ @abstractmethod
42
+ async def _refresh_impl(self, obj): ...
43
+
44
+ @abstractmethod
45
+ async def _get_impl(self, model, ident): ...
46
+
47
+ @abstractmethod
48
+ async def _execute_impl(self, stmt): ...
49
+
50
+ @abstractmethod
51
+ async def _tx_begin_impl(self): ...
52
+
53
+ @abstractmethod
54
+ async def _tx_commit_impl(self): ...
55
+
56
+ @abstractmethod
57
+ async def _tx_rollback_impl(self): ...
58
+
59
+ @abstractmethod
60
+ async def _close_impl(self): ...
61
+
62
+
63
+ try:
64
+ from tigrbl.session.spec import SessionSpec
65
+ except Exception:
66
+
67
+ class SessionSpec: # pragma: no cover - fallback
68
+ def __init__(self, isolation=None, read_only=None):
69
+ self.isolation = isolation
70
+ self.read_only = read_only
71
+
72
+
73
+ try:
74
+ from tigrbl.core.crud.helpers.model import _single_pk_name, _model_columns
75
+ except Exception:
76
+
77
+ def _single_pk_name(model): # pragma: no cover - fallback
78
+ return "id"
79
+
80
+ def _model_columns(model): # pragma: no cover - fallback
81
+ return getattr(model, "__annotations__", {}) or {"id": int}
82
+
83
+
84
+ if TYPE_CHECKING:
85
+ from .engine import NumpyEngine
86
+
87
+
88
+ class _ScalarResult:
89
+ def __init__(self, items: Sequence[Any]) -> None:
90
+ self._items = list(items)
91
+
92
+ def scalars(self) -> "_ScalarResult":
93
+ return self
94
+
95
+ def all(self) -> List[Any]:
96
+ return list(self._items)
97
+
98
+
99
+ class _ExecuteResult(_ScalarResult):
100
+ rowcount: int = 0
101
+
102
+
103
+ class NumpySession(TigrblSessionBase):
104
+ """Tigrbl session for a single NumPy-backed table database."""
105
+
106
+ def __init__(self, engine: "NumpyEngine") -> None:
107
+ super().__init__(SessionSpec())
108
+ self._engine = engine
109
+ self._snap: Optional[list[dict[str, Any]]] = None
110
+ self._snap_ver: Optional[int] = None
111
+ self._puts: dict[tuple[type, Any], dict[str, Any]] = {}
112
+ self._dels: set[tuple[type, Any]] = set()
113
+ self._tracked: dict[tuple[type, Any], Any] = {}
114
+ self._tracked: dict[tuple[type, Any], Any] = {}
115
+
116
+ def to_records(self) -> list[dict[str, Any]]:
117
+ pk = self._engine.catalog.pk
118
+ by_id: dict[Any, dict[str, Any]] = {}
119
+ for row in self._engine.catalog.rows:
120
+ ident = row.get(pk)
121
+ if ident is None:
122
+ continue
123
+ by_id[ident] = dict(row)
124
+ for (_, ident), row in self._puts.items():
125
+ by_id[ident] = dict(row)
126
+ for _, ident in self._dels:
127
+ by_id.pop(ident, None)
128
+ return list(by_id.values())
129
+
130
+ def array(self) -> np.ndarray:
131
+ rows = self.to_records()
132
+ values = [[row.get(col) for col in self._engine.columns] for row in rows]
133
+ return np.asarray(values, dtype=object)
134
+
135
+ def load(
136
+ self, file: str, *, mmap_mode: str | None = None, npz_key: str | None = None
137
+ ) -> np.ndarray:
138
+ loaded = np.load(file, mmap_mode=mmap_mode, allow_pickle=True)
139
+ if isinstance(loaded, np.lib.npyio.NpzFile):
140
+ with loaded as archive:
141
+ key = npz_key or (archive.files[0] if len(archive.files) == 1 else None)
142
+ if key is None:
143
+ raise ValueError(
144
+ "npz_key is required when loading multi-array .npz files"
145
+ )
146
+ return np.asarray(archive[key])
147
+ return loaded
148
+
149
+ def memmap(
150
+ self,
151
+ filename: str,
152
+ *,
153
+ dtype: Any = np.float64,
154
+ mode: str = "r+",
155
+ shape: Any = None,
156
+ ) -> np.memmap:
157
+ valid_modes = {"r", "r+", "w+", "c"}
158
+ if mode not in valid_modes:
159
+ raise ValueError(f"mode must be one of {sorted(valid_modes)}")
160
+ if mode == "w+" and shape is None:
161
+ raise ValueError("shape is required when mode='w+'")
162
+ return np.memmap(filename, dtype=dtype, mode=mode, shape=shape)
163
+
164
+ def save(
165
+ self,
166
+ file: str | None = None,
167
+ array: np.ndarray | None = None,
168
+ *,
169
+ npz_key: str | None = None,
170
+ ) -> None:
171
+ target = file or self._engine.catalog.path
172
+ if not target:
173
+ raise ValueError("A target file path is required")
174
+
175
+ payload = self.array() if array is None else np.asarray(array)
176
+ self._atomic_save_numpy(target, payload, npz_key=npz_key)
177
+
178
+ def _atomic_save_numpy(
179
+ self, file: str, array: np.ndarray, *, npz_key: str | None = None
180
+ ) -> None:
181
+ path = Path(file)
182
+ directory = str(path.parent if str(path.parent) else Path("."))
183
+ suffix = path.suffix.lower()
184
+ if suffix not in {".npy", ".npz"}:
185
+ raise ValueError("file must use .npy or .npz suffix")
186
+
187
+ fd, tmp = tempfile.mkstemp(
188
+ dir=directory,
189
+ prefix=".tmp_",
190
+ suffix=suffix,
191
+ )
192
+ os.close(fd)
193
+ try:
194
+ if suffix == ".npz":
195
+ key = npz_key or self._engine.catalog.npz_key or "data"
196
+ np.savez(tmp, **{key: array})
197
+ else:
198
+ np.save(tmp, array)
199
+ os.replace(tmp, str(path))
200
+ finally:
201
+ if os.path.exists(tmp):
202
+ os.remove(tmp)
203
+
204
+ async def run_sync(self, fn: Callable[[Any], Any]) -> Any:
205
+ out = fn(self)
206
+ return await out if hasattr(out, "__await__") else out
207
+
208
+ async def begin(self) -> None:
209
+ await self._tx_begin_impl()
210
+
211
+ async def commit(self) -> None:
212
+ await self._tx_commit_impl()
213
+
214
+ async def rollback(self) -> None:
215
+ await self._tx_rollback_impl()
216
+
217
+ async def flush(self) -> None:
218
+ await self._flush_impl()
219
+
220
+ async def refresh(self, obj: Any) -> None:
221
+ await self._refresh_impl(obj)
222
+
223
+ async def get(self, model: type, ident: Any) -> Any | None:
224
+ return await self._get_impl(model, ident)
225
+
226
+ async def execute(self, stmt: Any) -> Any:
227
+ return await self._execute_impl(stmt)
228
+
229
+ async def close(self) -> None:
230
+ await self._close_impl()
231
+
232
+ async def _tx_begin_impl(self) -> None:
233
+ self._snap = [dict(row) for row in self._engine.catalog.rows]
234
+ self._snap_ver = self._engine.catalog.table_ver
235
+ self._puts.clear()
236
+ self._dels.clear()
237
+ self._tracked.clear()
238
+ self._tracked.clear()
239
+
240
+ async def _tx_commit_impl(self) -> None:
241
+ iso = (self._spec.isolation if self._spec else None) or "read_committed"
242
+ if (
243
+ iso in ("repeatable_read", "snapshot", "serializable")
244
+ and self._snap_ver is not None
245
+ ):
246
+ if self._engine.catalog.table_ver != self._snap_ver:
247
+ raise RuntimeError("transaction conflict on table")
248
+
249
+ with self._engine.catalog.lock:
250
+ live = list(self._engine.catalog.rows)
251
+ for model, ident in self._dels:
252
+ pk = _single_pk_name(model)
253
+ live = [row for row in live if row.get(pk) != ident]
254
+ for (model, ident), row in self._puts.items():
255
+ pk = _single_pk_name(model)
256
+ live = [existing for existing in live if existing.get(pk) != ident]
257
+ live.append(dict(row))
258
+ self._engine.catalog.rows = live
259
+ self._engine.catalog.bump()
260
+ if self._engine.catalog.path:
261
+ self._atomic_save_numpy(
262
+ self._engine.catalog.path,
263
+ self.array(),
264
+ npz_key=self._engine.catalog.npz_key,
265
+ )
266
+ self._puts.clear()
267
+ self._dels.clear()
268
+ self._tracked.clear()
269
+ self._tracked.clear()
270
+
271
+ async def _tx_rollback_impl(self) -> None:
272
+ self._puts.clear()
273
+ self._dels.clear()
274
+ self._tracked.clear()
275
+
276
+ def _add_impl(self, obj: Any) -> Any:
277
+ model = obj.__class__
278
+ pk = _single_pk_name(model)
279
+ ident = getattr(obj, pk)
280
+ if ident is None:
281
+ default = getattr(getattr(model, "__table__", None), "columns", {}).get(pk)
282
+ default = getattr(default, "default", None)
283
+ if default is not None:
284
+ arg = getattr(default, "arg", default)
285
+ if callable(arg):
286
+ try:
287
+ ident = arg()
288
+ except TypeError:
289
+ ident = arg(None)
290
+ else:
291
+ ident = arg
292
+ setattr(obj, pk, ident)
293
+ if ident is None:
294
+ raise ValueError(f"primary key {pk!r} must be set")
295
+ self._tracked[(model, ident)] = obj
296
+ row = {c: getattr(obj, c, None) for c in _model_columns(model)}
297
+ self._puts[(model, ident)] = row
298
+ self._dels.discard((model, ident))
299
+ return None
300
+
301
+ async def _delete_impl(self, obj: Any) -> None:
302
+ model = obj.__class__
303
+ pk = _single_pk_name(model)
304
+ ident = getattr(obj, pk)
305
+ self._puts.pop((model, ident), None)
306
+ self._dels.add((model, ident))
307
+ self._tracked.pop((model, ident), None)
308
+ self._tracked.pop((model, ident), None)
309
+
310
+ async def _flush_impl(self) -> None:
311
+ for (model, ident), obj in list(self._tracked.items()):
312
+ if (model, ident) in self._dels:
313
+ continue
314
+ row = {c: getattr(obj, c, None) for c in _model_columns(model)}
315
+ baseline = self._resolve_row(model, ident)
316
+ if baseline is None:
317
+ continue
318
+ if row == dict(baseline):
319
+ continue
320
+ if self._spec and self._spec.read_only:
321
+ raise RuntimeError("read-only session: writes detected during flush")
322
+ self._puts[(model, ident)] = row
323
+
324
+ async def _refresh_impl(self, obj: Any) -> None:
325
+ pk = _single_pk_name(obj.__class__)
326
+ ident = getattr(obj, pk)
327
+ row = self._resolve_row(obj.__class__, ident)
328
+ if row is None:
329
+ return
330
+ for c in _model_columns(obj.__class__):
331
+ if c in row:
332
+ setattr(obj, c, row[c])
333
+
334
+ async def _get_impl(self, model: type, ident: Any) -> Any | None:
335
+ if (model, ident) in self._dels:
336
+ return None
337
+ tracked = self._tracked.get((model, ident))
338
+ if tracked is not None:
339
+ return tracked
340
+ row = self._resolve_row(model, ident)
341
+ if row is None:
342
+ return None
343
+ return self._hydrate_tracked(model, ident, row)
344
+
345
+ async def _execute_impl(self, stmt: Any) -> Any:
346
+ kind = type(stmt).__name__.lower()
347
+ if "select" in kind:
348
+ model, where, order, limit, offset = self._decompose_select(stmt)
349
+ items = self._scan_model(model)
350
+ items = [o for o in items if self._matches_obj(o, where)]
351
+ return _ExecuteResult(self._order_slice(items, order, limit, offset))
352
+ if "delete" in kind:
353
+ model, where = self._decompose_delete(stmt)
354
+ items = [o for o in self._scan_model(model) if self._matches_obj(o, where)]
355
+ for obj in items:
356
+ pk = _single_pk_name(model)
357
+ ident = getattr(obj, pk)
358
+ self._puts.pop((model, ident), None)
359
+ self._dels.add((model, ident))
360
+ res = _ExecuteResult([])
361
+ res.rowcount = len(items)
362
+ return res
363
+ raise NotImplementedError(f"Unsupported statement: {type(stmt)}")
364
+
365
+ async def _close_impl(self) -> None:
366
+ self._tracked.clear()
367
+ return
368
+
369
+ def _inflate(self, model: type, data: Mapping[str, Any]) -> Any:
370
+ obj = model()
371
+ for c in _model_columns(model):
372
+ if c in data:
373
+ setattr(obj, c, data[c])
374
+ return obj
375
+
376
+ def _scan_model(self, model: type) -> List[Any]:
377
+ pk = _single_pk_name(model)
378
+ by_id: dict[Any, Any] = {}
379
+ for row in self._engine.catalog.rows:
380
+ ident = row.get(pk)
381
+ if ident is None:
382
+ continue
383
+ by_id[ident] = self._hydrate_tracked(model, ident, row)
384
+ for (m, ident), row in self._puts.items():
385
+ if m is model:
386
+ by_id[ident] = self._hydrate_tracked(model, ident, row)
387
+ for m, ident in self._dels:
388
+ if m is model:
389
+ by_id.pop(ident, None)
390
+ self._tracked.pop((model, ident), None)
391
+ return list(by_id.values())
392
+
393
+ def _resolve_row(self, model: type, ident: Any) -> Mapping[str, Any] | None:
394
+ row = self._puts.get((model, ident))
395
+ if row is not None:
396
+ return row
397
+ pk = _single_pk_name(model)
398
+ for record in self._engine.catalog.rows:
399
+ if record.get(pk) == ident:
400
+ return record
401
+ return None
402
+
403
+ def _hydrate_tracked(self, model: type, ident: Any, data: Mapping[str, Any]) -> Any:
404
+ obj = self._tracked.get((model, ident))
405
+ if obj is None:
406
+ obj = self._inflate(model, data)
407
+ self._tracked[(model, ident)] = obj
408
+ return obj
409
+ for c in _model_columns(model):
410
+ if c in data:
411
+ setattr(obj, c, data[c])
412
+ return obj
413
+
414
+ def _decompose_select(
415
+ self, stmt: Any
416
+ ) -> Tuple[
417
+ type,
418
+ list[Tuple[str, str, Any]],
419
+ list[Tuple[str, str]],
420
+ Optional[int],
421
+ Optional[int],
422
+ ]:
423
+ return (
424
+ self._extract_model(stmt),
425
+ self._extract_predicates(stmt),
426
+ self._extract_order_by(stmt),
427
+ self._extract_int(stmt, ["_limit", "_limit_clause", "limit"]),
428
+ self._extract_int(stmt, ["_offset", "_offset_clause", "offset"]),
429
+ )
430
+
431
+ def _decompose_delete(self, stmt: Any) -> Tuple[type, list[Tuple[str, str, Any]]]:
432
+ return self._extract_model(stmt), self._extract_predicates(stmt)
433
+
434
+ def _extract_model(self, stmt: Any) -> type:
435
+ descs = getattr(stmt, "column_descriptions", None) or []
436
+ for desc in descs:
437
+ entity = desc.get("entity") if isinstance(desc, dict) else None
438
+ if isinstance(entity, type):
439
+ return entity
440
+
441
+ def _all_subclasses(base: type) -> list[type]:
442
+ out: list[type] = []
443
+ stack = [base]
444
+ seen: set[type] = set()
445
+ while stack:
446
+ cls = stack.pop()
447
+ try:
448
+ children = cls.__subclasses__()
449
+ except TypeError:
450
+ continue
451
+ for child in children:
452
+ if child in seen:
453
+ continue
454
+ seen.add(child)
455
+ out.append(child)
456
+ stack.append(child)
457
+ return out
458
+
459
+ def _find_by_table(name: str) -> type | None:
460
+ for cls in _all_subclasses(object):
461
+ if getattr(cls, "__tablename__", None) == name:
462
+ return cls
463
+ return None
464
+
465
+ table = getattr(stmt, "table", None)
466
+ name = getattr(table, "name", None)
467
+ if isinstance(name, str):
468
+ found = _find_by_table(name)
469
+ if found is not None:
470
+ return found
471
+
472
+ for attr_name in ("_from_objects", "_froms", "froms"):
473
+ value = getattr(stmt, attr_name, None)
474
+ if value is not None:
475
+ if isinstance(value, (list, tuple)) and not value:
476
+ continue
477
+ table = value[0] if isinstance(value, (list, tuple)) else value
478
+ name = getattr(table, "name", None)
479
+ if isinstance(name, str):
480
+ found = _find_by_table(name)
481
+ if found is not None:
482
+ return found
483
+
484
+ table = getattr(stmt, "table", None)
485
+ name = getattr(table, "name", None)
486
+ if isinstance(name, str):
487
+ found = _find_by_table(name)
488
+ if found is not None:
489
+ return found
490
+
491
+ raw_columns = getattr(stmt, "_raw_columns", None) or getattr(
492
+ stmt, "columns", None
493
+ )
494
+ if raw_columns is not None:
495
+ if isinstance(raw_columns, (list, tuple)) and not raw_columns:
496
+ raise RuntimeError("Cannot resolve model from statement")
497
+ entity = raw_columns[0]
498
+ table = getattr(entity, "table", None)
499
+ name = getattr(table, "name", None)
500
+ if isinstance(name, str):
501
+ found = _find_by_table(name)
502
+ if found is not None:
503
+ return found
504
+ raise RuntimeError("Cannot resolve model from statement")
505
+
506
+ def _extract_predicates(self, stmt: Any) -> list[Tuple[str, str, Any]]:
507
+ where = getattr(stmt, "whereclause", None) or getattr(
508
+ stmt, "_whereclause", None
509
+ )
510
+ if where is None:
511
+ return []
512
+ nodes = list(getattr(where, "clauses", None) or [where])
513
+ out: list[Tuple[str, str, Any]] = []
514
+ for node in nodes:
515
+ left, right, op = (
516
+ getattr(node, "left", None),
517
+ getattr(node, "right", None),
518
+ getattr(node, "operator", None),
519
+ )
520
+ name = getattr(left, "key", None) or getattr(left, "name", None)
521
+ if left is None or right is None or name is None:
522
+ continue
523
+ opname = getattr(op, "__name__", str(op))
524
+ if "eq" in opname:
525
+ out.append((str(name), "eq", getattr(right, "value", None)))
526
+ return out
527
+
528
+ def _extract_order_by(self, stmt: Any) -> list[Tuple[str, str]]:
529
+ order = getattr(stmt, "_order_by_clause", None)
530
+ if order is None:
531
+ order = getattr(stmt, "_order_by_clauses", None)
532
+ if order is None:
533
+ return []
534
+ clauses = getattr(order, "clauses", None) or order
535
+ clauses = clauses if isinstance(clauses, (list, tuple)) else [clauses]
536
+ for clause in clauses:
537
+ col = getattr(clause, "element", None) or getattr(clause, "this", None)
538
+ name = getattr(col, "key", None) or getattr(col, "name", None)
539
+ if name:
540
+ direction = "desc" if "desc" in type(clause).__name__.lower() else "asc"
541
+ return [(str(name), direction)]
542
+ return []
543
+
544
+ def _extract_int(self, stmt: Any, names: Sequence[str]) -> Optional[int]:
545
+ for name in names:
546
+ value = getattr(stmt, name, None)
547
+ if value is None:
548
+ continue
549
+ try:
550
+ return int(value)
551
+ except Exception:
552
+ literal = getattr(value, "value", None)
553
+ if literal is not None:
554
+ return int(literal)
555
+ return None
556
+
557
+ def _matches_obj(self, obj: Any, where: list[Tuple[str, str, Any]]) -> bool:
558
+ for name, op, value in where:
559
+ datum = getattr(obj, name, None)
560
+ if op == "eq" and datum != value:
561
+ return False
562
+ return True
563
+
564
+ def _order_slice(
565
+ self,
566
+ items: List[Any],
567
+ order: list[Tuple[str, str]],
568
+ limit: Optional[int],
569
+ offset: Optional[int],
570
+ ) -> List[Any]:
571
+ if order:
572
+ col, direction = order[0]
573
+ items.sort(
574
+ key=lambda obj: getattr(obj, col, None), reverse=(direction == "desc")
575
+ )
576
+ if isinstance(offset, int):
577
+ items = items[max(0, offset) :]
578
+ if isinstance(limit, int):
579
+ items = items[: max(0, limit)]
580
+ return items
@@ -0,0 +1,279 @@
1
+ Metadata-Version: 2.4
2
+ Name: tigrbl_engine_numpy
3
+ Version: 0.1.1
4
+ Summary: NumPy engine plugin for tigrbl with array-to-table helpers.
5
+ Project-URL: Homepage, https://github.com/swarmauri/swarmauri-sdk
6
+ Author-email: Jacob Stewart <jacob@swarmauri.com>
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "[]"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright [2025] [Swarmauri Team]
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+ License-File: LICENSE
209
+ Keywords: array,engine,experimental,numpy,tigrbl
210
+ Classifier: Development Status :: 1 - Planning
211
+ Classifier: License :: OSI Approved :: Apache Software License
212
+ Classifier: Programming Language :: Python :: 3.10
213
+ Classifier: Programming Language :: Python :: 3.11
214
+ Classifier: Programming Language :: Python :: 3.12
215
+ Requires-Python: <3.13,>=3.10
216
+ Requires-Dist: numpy>=1.26
217
+ Requires-Dist: tigrbl>=0.3.0.dev4
218
+ Description-Content-Type: text/markdown
219
+
220
+ ![Tigrbl Logo](https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/tigrbl_full_logo.png)
221
+
222
+ <p align="center">
223
+ <a href="https://pypi.org/project/tigrbl_engine_numpy/">
224
+ <img src="https://img.shields.io/pypi/v/tigrbl_engine_numpy?label=tigrbl_engine_numpy&color=green" alt="PyPI - tigrbl_engine_numpy"/>
225
+ </a>
226
+ <a href="https://pypi.org/project/tigrbl_engine_numpy/">
227
+ <img src="https://img.shields.io/pypi/dm/tigrbl_engine_numpy" alt="PyPI - Downloads"/>
228
+ </a>
229
+ <a href="https://pypi.org/project/tigrbl_engine_numpy/">
230
+ <img src="https://img.shields.io/pypi/pyversions/tigrbl_engine_numpy" alt="PyPI - Python Version"/>
231
+ </a>
232
+ <a href="https://pypi.org/project/tigrbl_engine_numpy/">
233
+ <img src="https://img.shields.io/pypi/l/tigrbl_engine_numpy" alt="PyPI - License"/>
234
+ </a>
235
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/tigrbl_engine_numpy/">
236
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/experimental/tigrbl_engine_numpy.svg"/>
237
+ </a>
238
+ </p>
239
+
240
+ # tigrbl_engine_numpy
241
+
242
+ A tigrbl engine plugin that registers `kind="numpy"` where each array/matrix is a single-table database-like object.
243
+
244
+ ## Features
245
+
246
+ - Registers a `numpy` engine through the `tigrbl.engine` entry-point group.
247
+ - Treats one NumPy array/matrix as one table.
248
+ - Provides a first-class `NumpySession` (subclass of `TigrblSessionBase`) without pandas dependencies.
249
+ - Supports loading `.npy`/`.npz` via `np.load(...)`, memory-mapped arrays via `np.memmap(...)`, and persistence via `np.save(...)`.
250
+
251
+ ## Installation
252
+
253
+ ### uv
254
+
255
+ ```bash
256
+ uv add tigrbl_engine_numpy
257
+ ```
258
+
259
+ ### pip
260
+
261
+ ```bash
262
+ pip install tigrbl_engine_numpy
263
+ ```
264
+
265
+ ## Usage
266
+
267
+ ```python
268
+ import numpy as np
269
+ from tigrbl.engine import EngineSpec
270
+
271
+ spec = EngineSpec(kind="numpy", mapping={"array": np.array([[1, 2], [3, 4]]), "columns": ["id", "value"], "table": "matrix", "pk": "id"})
272
+ provider = spec.provider()
273
+ engine, session_factory = provider.build()
274
+
275
+ session = session_factory()
276
+ print(session.array())
277
+ print(session.to_records())
278
+ session.close()
279
+ ```
@@ -0,0 +1,8 @@
1
+ tigrbl_engine_numpy/__init__.py,sha256=AwC9E7-M6JejPcB-kOh247YvfpgfPkmRuogWJToIwSc,635
2
+ tigrbl_engine_numpy/engine.py,sha256=UA1CzqX6DLo8Mto7rtUffUuIwPoxYs0e1nE9EQpl_SI,5038
3
+ tigrbl_engine_numpy/session.py,sha256=-WcfVc87AtfIegCa9kw-0sWu9fAx5rUvJolO6VBpdyA,20080
4
+ tigrbl_engine_numpy-0.1.1.dist-info/METADATA,sha256=P9RX43Ed_D1o8mP5CZxuRB_JbGtztiJZ_k8KIxjpS5g,15334
5
+ tigrbl_engine_numpy-0.1.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
6
+ tigrbl_engine_numpy-0.1.1.dist-info/entry_points.txt,sha256=F2yEiEf3u5fb5rzg1epqAM_GBi80I5V5umgd8KiO6CA,53
7
+ tigrbl_engine_numpy-0.1.1.dist-info/licenses/LICENSE,sha256=708mvS2G_dkXGD6DVfUDngIUW4HW-T14Ws-q7shsacA,10880
8
+ tigrbl_engine_numpy-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [tigrbl.engine]
2
+ numpy = tigrbl_engine_numpy:register
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Swarmauri Team]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.