vayulib 0.0.1__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.

Potentially problematic release.


This version of vayulib might be problematic. Click here for more details.

vayulib-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.3
2
+ Name: vayulib
3
+ Version: 0.0.1
4
+ Summary:
5
+ License: MIT
6
+ Author: Alok
7
+ Author-email: alokrant@gmail.com
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Provides-Extra: data
14
+ Requires-Dist: aiohttp (>=3.11.13,<4.0.0)
15
+ Requires-Dist: numpy (>=2.1.3,<3.0.0) ; extra == "data"
16
+ Requires-Dist: pandas (>=2.2.3,<3.0.0) ; extra == "data"
17
+ Requires-Dist: plotly (>=6.0.0,<7.0.0) ; extra == "data"
18
+ Requires-Dist: pytest (>=8.3.5,<9.0.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+
File without changes
@@ -0,0 +1,47 @@
1
+ [tool.poetry]
2
+ name = "vayulib"
3
+ version = "0.0.1"
4
+ description = ""
5
+ authors = ["Alok <alokrant@gmail.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ packages = [{ include = "vayu" }]
9
+
10
+ [tool.poetry.dependencies]
11
+ python = "^3.12"
12
+ pytest = "^8.3.5"
13
+ aiohttp = {version = "^3.11.13"}
14
+ numpy = { version = "^2.1.3", optional = true }
15
+ pandas = { version = "^2.2.3", optional = true }
16
+ plotly = {version = "^6.0.0", optional = true }
17
+ #scikit-learn = {version = "^1.6.1", optional = true }
18
+ #numba = {version = "^0.61.0", optional = true }
19
+ #scipy = {version = "^1.15.2", optional = true }
20
+
21
+ [tool.poetry.extras]
22
+ data = ["numpy", "pandas", "plotly"]
23
+
24
+ [tool.pytest.ini_options]
25
+ asyncio_mode = "auto"
26
+
27
+ [tool.poetry.group.dev.dependencies]
28
+ black = "^25.1.0"
29
+ pytest = "^8.3.5"
30
+ pytest-asyncio = "^0.25.3"
31
+
32
+ [tool.black]
33
+ line-length = 100
34
+ target-version = ['py311']
35
+ include = '\.pyi?$'
36
+ extend-exclude = '''
37
+ /(
38
+ # The following are specific to Black, you probably don't want those.
39
+ | blib2to3
40
+ | tests/data
41
+ | profiling
42
+ )/
43
+ '''
44
+
45
+ [build-system]
46
+ requires = ["poetry-core"]
47
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,11 @@
1
+ import pandas as pd
2
+
3
+ try:
4
+ import pandas as _pd
5
+ from vayu.pandas_utils import select_series, select_frame
6
+ if not hasattr(_pd.DataFrame, "select"):
7
+ _pd.DataFrame.select = select_frame
8
+ if not hasattr(pd.Series, "select"):
9
+ _pd.Series.select = select_series
10
+ except ImportError:
11
+ pass
@@ -0,0 +1,64 @@
1
+ import asyncio
2
+ from datetime import timedelta
3
+ from numbers import Number
4
+ from signal import SIGTERM, SIGINT
5
+ from typing import Union, Coroutine, Optional, List, Dict, Any
6
+
7
+ import aiohttp
8
+ from aiohttp import TCPConnector
9
+
10
+
11
+ async def get_first_and_cancel_rest(*tasks: Union[asyncio.Task, Coroutine]) -> asyncio.Task:
12
+ done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
13
+ for task in pending:
14
+ task.cancel()
15
+
16
+ return done.pop()
17
+
18
+
19
+ async def sleep_until_signal(duration: Union[timedelta, Number], signal: asyncio.Event) -> bool:
20
+ """Sleep until duration unless signal fires. Returns True if signal fired first."""
21
+ if isinstance(duration, (int, float)):
22
+ duration = timedelta(seconds=duration)
23
+
24
+ sleep_task = asyncio.create_task(asyncio.sleep(duration.total_seconds()))
25
+ signal_task = asyncio.create_task(signal.wait())
26
+ done = await get_first_and_cancel_rest(sleep_task, signal_task)
27
+ return done is signal_task
28
+
29
+
30
+ def attach_shutdown_signals(shutdown: asyncio.Event, signals: Optional[List] = None):
31
+ signals = signals or [SIGINT, SIGTERM]
32
+ loop = asyncio.get_running_loop()
33
+
34
+ def set_signal():
35
+ shutdown.set()
36
+
37
+ for signal in signals:
38
+ loop.add_signal_handler(signal, set_signal)
39
+
40
+
41
+ async def grab_all_urls(key_url_map: Dict[Any, str], concurrency=100, timeout=15, print_progress=True) -> Dict[Any, Any]:
42
+ results = {}
43
+ tasks = []
44
+ semaphore = asyncio.Semaphore(concurrency)
45
+
46
+ async def fetch_url(session, url, key, results: Dict[Any, Any], timeout):
47
+ async with semaphore:
48
+ try:
49
+ async with session.get(url, timeout=timeout) as response:
50
+ results[key] = (response.status, await response.read())
51
+ except Exception as e:
52
+ results[key] = None, str(e)
53
+
54
+ async with aiohttp.ClientSession(connector=TCPConnector(ssl=False)) as session:
55
+ for key, url in key_url_map.items():
56
+ task = fetch_url(session, url, key, results, timeout)
57
+ tasks.append(task)
58
+
59
+ for i, task in enumerate(asyncio.as_completed(tasks)):
60
+ await task
61
+ if print_progress:
62
+ print(f'Progress: {i+1}/{len(tasks)}', end="\r")
63
+
64
+ return results
@@ -0,0 +1,246 @@
1
+ import json
2
+ import os
3
+ from abc import ABC, abstractmethod
4
+ from datetime import timedelta
5
+ from functools import wraps
6
+ from hashlib import sha256
7
+ from pathlib import Path
8
+ from time import time
9
+ from typing import Callable, Any, Union, Dict, Tuple, Optional
10
+ import pickle
11
+
12
+ from vayu.log import L
13
+ from vayu.time import time_now, from_timestamp
14
+
15
+
16
+ class _MethodDecoratorAdaptor(object):
17
+ def __init__(self, decorator, func):
18
+ self.decorator = decorator
19
+ self.func = func
20
+
21
+ def __call__(self, *args, **kwargs):
22
+ return self.decorator(self.func)(*args, **kwargs)
23
+
24
+ def __get__(self, instance, owner):
25
+ return self.decorator(self.func.__get__(instance, owner))
26
+
27
+
28
+ def auto_adapt_to_methods(decorator):
29
+ """Allows you to use the same decorator on methods and functions,
30
+ hiding the self argument from the decorator."""
31
+
32
+ def adapt(func):
33
+ return _MethodDecoratorAdaptor(decorator, func)
34
+
35
+ return adapt
36
+
37
+
38
+ class Serializer(ABC):
39
+ @abstractmethod
40
+ def serialize(self, obj: Any) -> bytes:
41
+ pass
42
+
43
+ @abstractmethod
44
+ def deserialize(self, bts: bytes) -> Any:
45
+ pass
46
+
47
+
48
+ class NoOpSerializer(Serializer):
49
+ def serialize(self, obj: Any) -> bytes:
50
+ return obj
51
+
52
+ def deserialize(self, bts: bytes) -> Any:
53
+ return bts
54
+
55
+
56
+ class Pickler(Serializer):
57
+ def serialize(self, obj: Any) -> bytes:
58
+ return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
59
+
60
+ def deserialize(self, bts: bytes) -> Any:
61
+ return pickle.loads(bts)
62
+
63
+
64
+ class Jsoner(Serializer):
65
+ def serialize(self, obj: Any) -> bytes:
66
+ return json.dumps(obj).encode()
67
+
68
+ def deserialize(self, bts: bytes) -> Any:
69
+ return json.loads(bts)
70
+
71
+
72
+ class Cache(ABC):
73
+ def __init__(self, serializer: Serializer):
74
+ self._serializer = serializer
75
+
76
+ def cached(
77
+ self,
78
+ ttl: Union[timedelta, float] = None,
79
+ prefix: str = None,
80
+ key: Union[str, Callable] = None,
81
+ serializer: Serializer = None,
82
+ log: bool = True,
83
+ ):
84
+ """Used as decorator to cache function calls.
85
+
86
+ Args:
87
+ ttl: cache expiry ttl
88
+ prefix: If set, gets prepended to the rest of the cache key, otherwise uses function,
89
+ class, and module name to create prefix.
90
+ key:
91
+ - None: Use SHA256 digest of *args & **kwargs to construct cache key
92
+ - str: Use the specified string and ignore function arguments
93
+ - Callable: Calls it with *args * **kwargs which returns a str key.
94
+ serializer: If not specified, default pickler serializer is used
95
+ log: If True, logs reports such as cache hit, miss etc.
96
+
97
+ """
98
+ serializer = serializer or self._serializer
99
+ ttl = ttl or timedelta(days=365 * 10)
100
+ if not isinstance(ttl, timedelta):
101
+ ttl = timedelta(seconds=ttl)
102
+ if ttl.total_seconds() <= 0:
103
+ raise ValueError("ttl must be positive")
104
+
105
+ @auto_adapt_to_methods
106
+ def decorator(func):
107
+ f_name = func.__name__
108
+
109
+ @wraps(func)
110
+ def inner(*args, **kwargs):
111
+ t = time()
112
+ k = self._key(func, prefix=prefix, key=key, args=args, kwargs=kwargs)
113
+ t_del = time() - t
114
+ if 0.001 < t_del and log:
115
+ L.warn(f"Key construction for cached fn `{f_name}` took too long: {t_del:.6f}s")
116
+
117
+ got = self._read(k)
118
+ if got is not None:
119
+ return serializer.deserialize(got)
120
+ t = time()
121
+ result = func(*args, **kwargs)
122
+ t_del = time() - t
123
+ if log:
124
+ L.info(f"@cached({f_name}) - CACHE MISS | took: {t_del:.6}s")
125
+ self._write(k, serializer.serialize(result), ttl)
126
+ return result
127
+
128
+ @wraps(func)
129
+ def evict(*args, **kwargs):
130
+ k = self._key(func, prefix=prefix, key=key, args=args, kwargs=kwargs)
131
+ self._delete(k)
132
+
133
+ inner.evict = evict
134
+
135
+ return inner
136
+
137
+ return decorator
138
+
139
+ def read(self, key: str) -> Any:
140
+ got = self._read(key)
141
+ return None if got is None else self._serializer.deserialize(got)
142
+
143
+ def write(self, key: str, value: Any, ttl: timedelta):
144
+ return self._write(key, self._serializer.serialize(value), ttl)
145
+
146
+ @abstractmethod
147
+ def _read(self, key: str) -> Any:
148
+ raise NotImplementedError
149
+
150
+ @abstractmethod
151
+ def _write(self, key: str, value: Any, ttl: timedelta):
152
+ raise NotImplementedError
153
+
154
+ @abstractmethod
155
+ def _delete(self, key: str):
156
+ raise NotImplementedError
157
+
158
+ @staticmethod
159
+ def _key(
160
+ fn: Callable,
161
+ prefix: str = None,
162
+ key: Union[str, Callable] = None,
163
+ args: Tuple = None,
164
+ kwargs: Dict = None,
165
+ ) -> str:
166
+ is_method = hasattr(fn, "__self__")
167
+
168
+ if isinstance(key, str):
169
+ return key
170
+
171
+ parts = []
172
+ if prefix:
173
+ parts.append(prefix)
174
+ else:
175
+ parts.append(fn.__module__)
176
+ parts.append(fn.__qualname__)
177
+ parts = [".".join(parts)]
178
+ if callable(key):
179
+ parts.append(key(*args, **kwargs))
180
+ else:
181
+ arg_key = ",".join([str(a) for a in args] + [f"{k}={v}" for k, v in kwargs.items()])
182
+ parts.append(sha256(arg_key.encode()).hexdigest())
183
+ return ":".join(parts)
184
+
185
+
186
+ class InMemCache(Cache):
187
+ def __init__(self, serializer: Serializer = None):
188
+ super().__init__(serializer or NoOpSerializer())
189
+ self._d = dict()
190
+
191
+ def _write(self, key: str, value: bytes, ttl: timedelta):
192
+ self._d[key] = (value, time_now(with_ms=True) + ttl)
193
+
194
+ def _read(self, key: str) -> Optional[bytes]:
195
+ got = self._d.get(key)
196
+ if got is None:
197
+ return None
198
+ value, expiry_time = got
199
+ if expiry_time < time_now(with_ms=True):
200
+ self._delete(key)
201
+ return None
202
+ return value
203
+
204
+ def _delete(self, key: str):
205
+ self._d.pop(key, None)
206
+
207
+
208
+ class FileCache(Cache):
209
+ def __init__(self, path: str, serializer: Serializer = None):
210
+ super().__init__(serializer or Pickler())
211
+ self._path = Path(path)
212
+ self._ttl_bytes_length = 8
213
+
214
+ def _write(self, key: str, value: bytes, ttl: timedelta):
215
+ expiry_time = time_now(with_ms=True) + ttl
216
+ ttl_bytes = int(expiry_time.timestamp() * 1e6).to_bytes(
217
+ length=self._ttl_bytes_length, byteorder="big"
218
+ )
219
+ bts = ttl_bytes + value
220
+ with open(self._path / key, "wb") as f:
221
+ f.write(bts)
222
+
223
+ def _read(self, key: str) -> Optional[bytes]:
224
+ try:
225
+ with open(self._path / key, "rb") as f:
226
+ ttl_bytes = f.read(self._ttl_bytes_length)
227
+ ttl = from_timestamp(int.from_bytes(ttl_bytes, "big") / 1e6)
228
+ if ttl < time_now(with_ms=True):
229
+ bts = None
230
+ else:
231
+ bts = f.read()
232
+ except FileNotFoundError:
233
+ return None
234
+
235
+ if bts is None:
236
+ self._delete(key)
237
+ return bts
238
+
239
+ def _delete(self, key: str):
240
+ os.remove(self._path / key)
241
+
242
+
243
+ # file_cache = FileCache(Config.CACHE_DIR, serializer=Pickler())
244
+ # file_cached = file_cache.cached
245
+ # in_mem_cache = InMemCache(serializer=NoOpSerializer())
246
+ # in_mem_cached = in_mem_cache.cached
@@ -0,0 +1,175 @@
1
+ import asyncio
2
+ import datetime as dt
3
+ import os
4
+ from dataclasses import dataclass, replace
5
+ from logging import Logger
6
+ from typing import Dict, Callable, Tuple, List, Union, Type, Sequence, Iterable
7
+ import time
8
+ from functools import wraps
9
+ from operator import attrgetter
10
+ import random
11
+ from zoneinfo import ZoneInfo
12
+
13
+
14
+ MIN_FLOAT = float("-inf")
15
+ MAX_FLOAT = float("inf")
16
+ TZ = ZoneInfo(os.getenv("TZ")) if os.getenv("TZ") else dt.datetime.now().astimezone().tzinfo
17
+ TypeException = Type[Exception]
18
+
19
+ TaskType = Tuple[Callable, List, Dict]
20
+ Comparable = Union[None, dt.date, dt.datetime, int, float]
21
+
22
+
23
+ def camel_or_space_to_snake(s):
24
+ s = s.replace(" ", "_")
25
+ return "".join(["_" + c.lower() if c.isupper() else c for c in s]).lstrip("_")
26
+
27
+
28
+ @dataclass
29
+ class Interval:
30
+ start: Comparable
31
+ end: Comparable
32
+
33
+ def intersects(self, other: "Interval") -> bool:
34
+ return self.start <= other.end and other.start <= self.end
35
+
36
+ def intersection(self, other: "Interval") -> "Interval":
37
+ if not self.intersects(other):
38
+ raise ValueError("No intersection possible")
39
+
40
+ return replace(self, start=max(self.start, other.start), end=min(self.end, other.end))
41
+
42
+ @classmethod
43
+ def union(cls, intervals: Sequence["Interval"], allow_gaps: bool = False) -> "Interval":
44
+ # TODO: Fix this: should have a signature same as intersection.
45
+ if len(intervals) == 0:
46
+ raise AssertionError("Length of intervals should at least be 1")
47
+ if len(intervals) == 1:
48
+ return intervals[0]
49
+
50
+ intervals = sorted(intervals, key=attrgetter("start"))
51
+ if not allow_gaps:
52
+ for i in range(len(intervals) - 1):
53
+ first = intervals[i]
54
+ second = intervals[i + 1]
55
+ if first.end < second.start:
56
+ raise ValueError(f"Gaps not supported in interval union")
57
+
58
+ return cls(start=intervals[0].start, end=intervals[-1].end)
59
+
60
+ @property
61
+ def range(self) -> Comparable:
62
+ return self.end - self.start
63
+
64
+ def _validate(self):
65
+ assert self.start < self.end, "start value should be less than equal to end"
66
+
67
+ def __post_init__(self):
68
+ self._validate()
69
+
70
+ def __or__(self, other) -> "Interval":
71
+ return self.__class__.union([self, other])
72
+
73
+ def __and__(self, other) -> "Interval":
74
+ return self.intersection(other)
75
+
76
+ def __sub__(self, other: Comparable) -> "Interval":
77
+ return self.__class__(start=self.start - other, end=self.end - other)
78
+
79
+ def __add__(self, other: Comparable) -> "Interval":
80
+ return self.__class__(start=self.start + other, end=self.end + other)
81
+
82
+ def __contains__(self, item: Union[Comparable, "Interval"]):
83
+ if isinstance(item, Interval):
84
+ return item.start in self and item.end in self
85
+ return self.start <= item <= self.end
86
+
87
+ def __str__(self):
88
+ return f"[{self.start} — {self.end}]"
89
+
90
+
91
+ class retry: # noqa
92
+ """Retry calling the decorated function using an exponential backoff. Asyncio compatible."""
93
+
94
+ def __init__(
95
+ self,
96
+ exception_to_check: Union[TypeException, Tuple[TypeException]],
97
+ tries: int = 4,
98
+ delay: float = 1,
99
+ backoff: float = 2,
100
+ logger: Logger = None,
101
+ ):
102
+ """
103
+ Args:
104
+ exception_to_check: the exception to check. Maybe a tuple of exceptions to check.
105
+ tries: number of times to try (not retry) before giving up
106
+ delay: initial delay between retries in seconds
107
+ backoff: backoff multiplier e.g. value of 2 will double the delay for each retry
108
+ logger: logger to use. If None, print.
109
+ """
110
+ self._tries = tries
111
+ self._delay = delay
112
+ self._backoff = backoff
113
+ self._ignore_exc_types = exception_to_check
114
+ self._log_fn = logger.warning if logger else print
115
+
116
+ def __call__(self, fn):
117
+ is_async = asyncio.iscoroutinefunction(fn)
118
+ if not is_async:
119
+
120
+ @wraps(fn)
121
+ def decorated(*a, **k):
122
+ last_exception = None
123
+ delay = self._delay
124
+ for attempt in range(self._tries):
125
+ try: # noqa
126
+ return fn(*a, **k)
127
+ except self._ignore_exc_types as e:
128
+ last_exception = e
129
+ msg = f"Error {e.__class__.__name__}: retrying {fn.__name__} - in {delay}s - attempt {attempt + 1}/{self._tries}"
130
+ self._log_fn(msg)
131
+ time.sleep(delay)
132
+ delay *= self._backoff
133
+ if last_exception is not None:
134
+ raise last_exception
135
+
136
+ return decorated
137
+
138
+ else:
139
+
140
+ @wraps(fn)
141
+ async def decorated(*a, **k):
142
+ last_exception = None
143
+ delay = self._delay
144
+ for attempt in range(self._tries):
145
+ try: # noqa
146
+ return await fn(*a, **k)
147
+ except self._ignore_exc_types as e:
148
+ last_exception = e
149
+ msg = f"{str(e.__class__.__name__)}: retrying {fn.__name__} - in {delay}s - attempt {attempt + 1}/{self._tries}"
150
+ self._log_fn(msg)
151
+ await asyncio.sleep(delay)
152
+ delay *= self._backoff
153
+ if last_exception is not None:
154
+ raise last_exception
155
+
156
+ return decorated
157
+
158
+
159
+ JitterT = Union[float, int, dt.timedelta]
160
+
161
+
162
+ def add_jitter(n: JitterT, jitter_percentage: int = 20) -> JitterT:
163
+ """Add jitter to seconds."""
164
+ return n * (1 + random.randint(-jitter_percentage, jitter_percentage) / 100)
165
+
166
+
167
+ def group(iterable: Iterable, key: Callable) -> Dict:
168
+ """Group elements of an iterable by a key function."""
169
+ groups = {}
170
+ for item in iterable:
171
+ k = key(item)
172
+ if k not in groups:
173
+ groups[k] = []
174
+ groups[k].append(item)
175
+ return groups