hammad-python 0.0.30__py3-none-any.whl → 0.0.32__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.
- ham/__init__.py +200 -0
- {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/METADATA +6 -32
- hammad_python-0.0.32.dist-info/RECORD +6 -0
- hammad/__init__.py +0 -84
- hammad/_internal.py +0 -256
- hammad/_main.py +0 -226
- hammad/cache/__init__.py +0 -40
- hammad/cache/base_cache.py +0 -181
- hammad/cache/cache.py +0 -169
- hammad/cache/decorators.py +0 -261
- hammad/cache/file_cache.py +0 -80
- hammad/cache/ttl_cache.py +0 -74
- hammad/cli/__init__.py +0 -33
- hammad/cli/animations.py +0 -573
- hammad/cli/plugins.py +0 -867
- hammad/cli/styles/__init__.py +0 -55
- hammad/cli/styles/settings.py +0 -139
- hammad/cli/styles/types.py +0 -358
- hammad/cli/styles/utils.py +0 -634
- hammad/data/__init__.py +0 -90
- hammad/data/collections/__init__.py +0 -49
- hammad/data/collections/collection.py +0 -326
- hammad/data/collections/indexes/__init__.py +0 -37
- hammad/data/collections/indexes/qdrant/__init__.py +0 -1
- hammad/data/collections/indexes/qdrant/index.py +0 -723
- hammad/data/collections/indexes/qdrant/settings.py +0 -94
- hammad/data/collections/indexes/qdrant/utils.py +0 -210
- hammad/data/collections/indexes/tantivy/__init__.py +0 -1
- hammad/data/collections/indexes/tantivy/index.py +0 -426
- hammad/data/collections/indexes/tantivy/settings.py +0 -40
- hammad/data/collections/indexes/tantivy/utils.py +0 -176
- hammad/data/configurations/__init__.py +0 -35
- hammad/data/configurations/configuration.py +0 -564
- hammad/data/models/__init__.py +0 -50
- hammad/data/models/extensions/__init__.py +0 -4
- hammad/data/models/extensions/pydantic/__init__.py +0 -42
- hammad/data/models/extensions/pydantic/converters.py +0 -759
- hammad/data/models/fields.py +0 -546
- hammad/data/models/model.py +0 -1078
- hammad/data/models/utils.py +0 -280
- hammad/data/sql/__init__.py +0 -24
- hammad/data/sql/database.py +0 -576
- hammad/data/sql/types.py +0 -127
- hammad/data/types/__init__.py +0 -75
- hammad/data/types/file.py +0 -431
- hammad/data/types/multimodal/__init__.py +0 -36
- hammad/data/types/multimodal/audio.py +0 -200
- hammad/data/types/multimodal/image.py +0 -182
- hammad/data/types/text.py +0 -1308
- hammad/formatting/__init__.py +0 -33
- hammad/formatting/json/__init__.py +0 -27
- hammad/formatting/json/converters.py +0 -158
- hammad/formatting/text/__init__.py +0 -63
- hammad/formatting/text/converters.py +0 -723
- hammad/formatting/text/markdown.py +0 -131
- hammad/formatting/yaml/__init__.py +0 -26
- hammad/formatting/yaml/converters.py +0 -5
- hammad/genai/__init__.py +0 -217
- hammad/genai/a2a/__init__.py +0 -32
- hammad/genai/a2a/workers.py +0 -552
- hammad/genai/agents/__init__.py +0 -59
- hammad/genai/agents/agent.py +0 -1973
- hammad/genai/agents/run.py +0 -1024
- hammad/genai/agents/types/__init__.py +0 -42
- hammad/genai/agents/types/agent_context.py +0 -13
- hammad/genai/agents/types/agent_event.py +0 -128
- hammad/genai/agents/types/agent_hooks.py +0 -220
- hammad/genai/agents/types/agent_messages.py +0 -31
- hammad/genai/agents/types/agent_response.py +0 -125
- hammad/genai/agents/types/agent_stream.py +0 -327
- hammad/genai/graphs/__init__.py +0 -125
- hammad/genai/graphs/_utils.py +0 -190
- hammad/genai/graphs/base.py +0 -1828
- hammad/genai/graphs/plugins.py +0 -316
- hammad/genai/graphs/types.py +0 -638
- hammad/genai/models/__init__.py +0 -1
- hammad/genai/models/embeddings/__init__.py +0 -43
- hammad/genai/models/embeddings/model.py +0 -226
- hammad/genai/models/embeddings/run.py +0 -163
- hammad/genai/models/embeddings/types/__init__.py +0 -37
- hammad/genai/models/embeddings/types/embedding_model_name.py +0 -75
- hammad/genai/models/embeddings/types/embedding_model_response.py +0 -76
- hammad/genai/models/embeddings/types/embedding_model_run_params.py +0 -66
- hammad/genai/models/embeddings/types/embedding_model_settings.py +0 -47
- hammad/genai/models/language/__init__.py +0 -57
- hammad/genai/models/language/model.py +0 -1098
- hammad/genai/models/language/run.py +0 -878
- hammad/genai/models/language/types/__init__.py +0 -40
- hammad/genai/models/language/types/language_model_instructor_mode.py +0 -47
- hammad/genai/models/language/types/language_model_messages.py +0 -28
- hammad/genai/models/language/types/language_model_name.py +0 -239
- hammad/genai/models/language/types/language_model_request.py +0 -127
- hammad/genai/models/language/types/language_model_response.py +0 -217
- hammad/genai/models/language/types/language_model_response_chunk.py +0 -56
- hammad/genai/models/language/types/language_model_settings.py +0 -89
- hammad/genai/models/language/types/language_model_stream.py +0 -600
- hammad/genai/models/language/utils/__init__.py +0 -28
- hammad/genai/models/language/utils/requests.py +0 -421
- hammad/genai/models/language/utils/structured_outputs.py +0 -135
- hammad/genai/models/model_provider.py +0 -4
- hammad/genai/models/multimodal.py +0 -47
- hammad/genai/models/reranking.py +0 -26
- hammad/genai/types/__init__.py +0 -1
- hammad/genai/types/base.py +0 -215
- hammad/genai/types/history.py +0 -290
- hammad/genai/types/tools.py +0 -507
- hammad/logging/__init__.py +0 -35
- hammad/logging/decorators.py +0 -834
- hammad/logging/logger.py +0 -1018
- hammad/mcp/__init__.py +0 -53
- hammad/mcp/client/__init__.py +0 -35
- hammad/mcp/client/client.py +0 -624
- hammad/mcp/client/client_service.py +0 -400
- hammad/mcp/client/settings.py +0 -178
- hammad/mcp/servers/__init__.py +0 -26
- hammad/mcp/servers/launcher.py +0 -1161
- hammad/runtime/__init__.py +0 -32
- hammad/runtime/decorators.py +0 -142
- hammad/runtime/run.py +0 -299
- hammad/service/__init__.py +0 -49
- hammad/service/create.py +0 -527
- hammad/service/decorators.py +0 -283
- hammad/types.py +0 -288
- hammad/typing/__init__.py +0 -435
- hammad/web/__init__.py +0 -43
- hammad/web/http/__init__.py +0 -1
- hammad/web/http/client.py +0 -944
- hammad/web/models.py +0 -275
- hammad/web/openapi/__init__.py +0 -1
- hammad/web/openapi/client.py +0 -740
- hammad/web/search/__init__.py +0 -1
- hammad/web/search/client.py +0 -1023
- hammad/web/utils.py +0 -472
- hammad_python-0.0.30.dist-info/RECORD +0 -135
- {hammad → ham}/py.typed +0 -0
- {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/WHEEL +0 -0
- {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/licenses/LICENSE +0 -0
hammad/cache/decorators.py
DELETED
@@ -1,261 +0,0 @@
|
|
1
|
-
"""hammad.cache.decorators"""
|
2
|
-
|
3
|
-
from typing import Callable, Optional, Tuple, Union, overload, TYPE_CHECKING
|
4
|
-
import inspect
|
5
|
-
from functools import wraps
|
6
|
-
|
7
|
-
from .base_cache import BaseCache, CacheParams, CacheReturn
|
8
|
-
from .ttl_cache import TTLCache
|
9
|
-
|
10
|
-
__all__ = (
|
11
|
-
"get_decorator_cache",
|
12
|
-
"clear_decorator_cache",
|
13
|
-
"cached",
|
14
|
-
"auto_cached",
|
15
|
-
)
|
16
|
-
|
17
|
-
|
18
|
-
# INTERNAL SINGLETON CACHE FOR DECORATORS
|
19
|
-
_DECORATOR_CACHE: BaseCache | None = None
|
20
|
-
"""Internal singleton cache for decorators."""
|
21
|
-
|
22
|
-
|
23
|
-
def get_decorator_cache() -> BaseCache:
|
24
|
-
"""Get the internal singleton cache for decorators."""
|
25
|
-
global _DECORATOR_CACHE
|
26
|
-
if _DECORATOR_CACHE is None:
|
27
|
-
_DECORATOR_CACHE = TTLCache(type="ttl", maxsize=1000, ttl=3600)
|
28
|
-
return _DECORATOR_CACHE
|
29
|
-
|
30
|
-
|
31
|
-
def clear_decorator_cache() -> None:
|
32
|
-
"""Clear the internal singleton cache for decorators."""
|
33
|
-
global _DECORATOR_CACHE
|
34
|
-
if _DECORATOR_CACHE is not None:
|
35
|
-
_DECORATOR_CACHE.clear()
|
36
|
-
_DECORATOR_CACHE = None
|
37
|
-
|
38
|
-
|
39
|
-
@overload
|
40
|
-
def cached(
|
41
|
-
func: "Callable[CacheParams, CacheReturn]",
|
42
|
-
) -> "Callable[CacheParams, CacheReturn]":
|
43
|
-
"""Decorator with automatic key generation, using the global CACHE."""
|
44
|
-
...
|
45
|
-
|
46
|
-
|
47
|
-
@overload
|
48
|
-
def cached(
|
49
|
-
*,
|
50
|
-
key: Optional["Callable[..., str]"] = None,
|
51
|
-
ttl: Optional[int] = None,
|
52
|
-
maxsize: Optional[int] = None,
|
53
|
-
cache: Optional["BaseCache"] = None,
|
54
|
-
) -> (
|
55
|
-
"Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]]"
|
56
|
-
):
|
57
|
-
"""Decorator with custom key function and/or cache settings."""
|
58
|
-
...
|
59
|
-
|
60
|
-
|
61
|
-
def cached(
|
62
|
-
func: Optional["Callable[CacheParams, CacheReturn]"] = None,
|
63
|
-
*,
|
64
|
-
key: Optional[Callable[..., str]] = None,
|
65
|
-
ttl: Optional[int] = None,
|
66
|
-
maxsize: Optional[int] = None,
|
67
|
-
cache: Optional["BaseCache"] = None,
|
68
|
-
) -> Union[
|
69
|
-
"Callable[CacheParams, CacheReturn]",
|
70
|
-
"Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]]",
|
71
|
-
]:
|
72
|
-
"""
|
73
|
-
Flexible caching decorator that preserves type hints and signatures.
|
74
|
-
|
75
|
-
Can be used with or without arguments:
|
76
|
-
- `@cached`: Uses automatic key generation with the global `hammad.cache.CACHE`.
|
77
|
-
- `@cached(key=custom_key_func)`: Uses a custom key generation function.
|
78
|
-
- `@cached(ttl=300, maxsize=50)`: Creates a new `TTLCache` instance specifically
|
79
|
-
for the decorated function with the given TTL and maxsize.
|
80
|
-
- `@cached(cache=my_cache_instance)`: Uses a user-provided cache instance.
|
81
|
-
|
82
|
-
Args:
|
83
|
-
func: The function to be cached (implicitly passed when used as `@cached`).
|
84
|
-
key: An optional function that takes the same arguments as `func` and
|
85
|
-
returns a string key. If `None`, a key is automatically generated.
|
86
|
-
ttl: Optional. Time-to-live in seconds. If `cache` is not provided and `ttl`
|
87
|
-
or `maxsize` is set, a new `TTLCache` is created for this function using
|
88
|
-
these settings.
|
89
|
-
maxsize: Optional. Maximum number of items in the cache. See `ttl`.
|
90
|
-
cache: Optional. A specific cache instance (conforming to `BaseCache`)
|
91
|
-
to use. If provided, `ttl` and `maxsize` arguments (intended for
|
92
|
-
creating a new per-function cache) are ignored, as the provided
|
93
|
-
cache instance manages its own lifecycle and capacity.
|
94
|
-
|
95
|
-
Returns:
|
96
|
-
The decorated function with caching capabilities.
|
97
|
-
"""
|
98
|
-
|
99
|
-
effective_cache: BaseCache = get_decorator_cache()
|
100
|
-
|
101
|
-
if cache is not None:
|
102
|
-
effective_cache = cache
|
103
|
-
elif ttl is not None or maxsize is not None:
|
104
|
-
default_maxsize = get_decorator_cache().maxsize
|
105
|
-
default_ttl = get_decorator_cache().ttl
|
106
|
-
|
107
|
-
effective_cache = TTLCache(
|
108
|
-
type="ttl",
|
109
|
-
maxsize=maxsize if maxsize is not None else default_maxsize,
|
110
|
-
ttl=ttl if ttl is not None else default_ttl,
|
111
|
-
)
|
112
|
-
else:
|
113
|
-
effective_cache = get_decorator_cache()
|
114
|
-
|
115
|
-
def decorator(
|
116
|
-
f_to_decorate: "Callable[CacheParams, CacheReturn]",
|
117
|
-
) -> "Callable[CacheParams, CacheReturn]":
|
118
|
-
key_func_to_use: "Callable[..., str]"
|
119
|
-
if key is None:
|
120
|
-
sig = inspect.signature(f_to_decorate)
|
121
|
-
|
122
|
-
def auto_key_func(
|
123
|
-
*args: CacheParams.args, **kwargs: CacheParams.kwargs
|
124
|
-
) -> str:
|
125
|
-
bound_args = sig.bind(*args, **kwargs)
|
126
|
-
bound_args.apply_defaults()
|
127
|
-
|
128
|
-
key_parts = []
|
129
|
-
for param_name, param_value in bound_args.arguments.items():
|
130
|
-
key_parts.append(
|
131
|
-
f"{param_name}={effective_cache.make_hashable(param_value)}"
|
132
|
-
)
|
133
|
-
|
134
|
-
return f"{f_to_decorate.__module__}.{f_to_decorate.__qualname__}({','.join(key_parts)})"
|
135
|
-
|
136
|
-
key_func_to_use = auto_key_func
|
137
|
-
else:
|
138
|
-
key_func_to_use = key
|
139
|
-
|
140
|
-
@wraps(f_to_decorate)
|
141
|
-
def wrapper(
|
142
|
-
*args: CacheParams.args, **kwargs: CacheParams.kwargs
|
143
|
-
) -> CacheReturn:
|
144
|
-
try:
|
145
|
-
cache_key_value = key_func_to_use(*args, **kwargs)
|
146
|
-
|
147
|
-
if cache_key_value in effective_cache:
|
148
|
-
return effective_cache[cache_key_value]
|
149
|
-
|
150
|
-
result = f_to_decorate(*args, **kwargs)
|
151
|
-
effective_cache[cache_key_value] = result
|
152
|
-
return result
|
153
|
-
|
154
|
-
except Exception:
|
155
|
-
return f_to_decorate(*args, **kwargs)
|
156
|
-
|
157
|
-
setattr(wrapper, "__wrapped__", f_to_decorate)
|
158
|
-
return wrapper
|
159
|
-
|
160
|
-
if func is None:
|
161
|
-
return decorator
|
162
|
-
else:
|
163
|
-
return decorator(func)
|
164
|
-
|
165
|
-
|
166
|
-
def auto_cached(
|
167
|
-
*,
|
168
|
-
ignore: Optional[Tuple[str, ...]] = None,
|
169
|
-
include: Optional[Tuple[str, ...]] = None,
|
170
|
-
ttl: Optional[int] = None,
|
171
|
-
maxsize: Optional[int] = None,
|
172
|
-
cache: Optional["BaseCache"] = None,
|
173
|
-
) -> (
|
174
|
-
"Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]]"
|
175
|
-
):
|
176
|
-
"""
|
177
|
-
Advanced caching decorator with automatic parameter selection for key generation.
|
178
|
-
|
179
|
-
Automatically generates cache keys based on a selection of the function's
|
180
|
-
parameters. This decorator internally uses the `cached` decorator.
|
181
|
-
|
182
|
-
Args:
|
183
|
-
ignore: A tuple of parameter names to exclude from cache key generation.
|
184
|
-
Cannot be used with `include`.
|
185
|
-
include: A tuple of parameter names to exclusively include in cache key
|
186
|
-
generation. All other parameters will be ignored. Cannot be used
|
187
|
-
with `ignore`.
|
188
|
-
ttl: Optional. Time-to-live in seconds. Passed to the underlying `cached`
|
189
|
-
decorator. If `cache` is not provided, this can lead to the creation
|
190
|
-
of a new `TTLCache` for the decorated function.
|
191
|
-
maxsize: Optional. Max cache size. Passed to `cached`. See `ttl`.
|
192
|
-
cache: Optional. A specific cache instance (conforming to `BaseCache`)
|
193
|
-
to use. This is passed directly to the underlying `cached` decorator.
|
194
|
-
If provided, `ttl` and `maxsize` arguments might be interpreted
|
195
|
-
differently by `cached` (see `cached` docstring).
|
196
|
-
|
197
|
-
Returns:
|
198
|
-
A decorator function that, when applied, will cache the results of
|
199
|
-
the decorated function.
|
200
|
-
|
201
|
-
Example:
|
202
|
-
```python
|
203
|
-
from hammad.cache import auto_cached, create_cache
|
204
|
-
|
205
|
-
# Example of using a custom cache instance
|
206
|
-
my_user_cache = create_cache(cache_type="ttl", ttl=600, maxsize=50)
|
207
|
-
|
208
|
-
@auto_cached(ignore=('debug_mode', 'logger'), cache=my_user_cache)
|
209
|
-
def fetch_user_data(user_id: int, debug_mode: bool = False, logger: Any = None):
|
210
|
-
# ... expensive operation to fetch data ...
|
211
|
-
print(f"Fetching data for user {user_id}")
|
212
|
-
return {"id": user_id, "data": "some_data"}
|
213
|
-
|
214
|
-
# Example of per-function TTL without a pre-defined cache
|
215
|
-
@auto_cached(include=('url',), ttl=30)
|
216
|
-
def fetch_url_content(url: str, timeout: int = 10):
|
217
|
-
# ... expensive operation to fetch URL ...
|
218
|
-
print(f"Fetching content from {url}")
|
219
|
-
return f"Content from {url}"
|
220
|
-
```
|
221
|
-
"""
|
222
|
-
|
223
|
-
if ignore and include:
|
224
|
-
raise ValueError("Cannot specify both 'ignore' and 'include' in auto_cached")
|
225
|
-
|
226
|
-
def actual_decorator(
|
227
|
-
func_to_decorate: "Callable[CacheParams, CacheReturn]",
|
228
|
-
) -> "Callable[CacheParams, CacheReturn]":
|
229
|
-
sig = inspect.signature(func_to_decorate)
|
230
|
-
|
231
|
-
def auto_key_generator(
|
232
|
-
*args: CacheParams.args, **kwargs: CacheParams.kwargs
|
233
|
-
) -> str:
|
234
|
-
bound_args = sig.bind(*args, **kwargs)
|
235
|
-
bound_args.apply_defaults()
|
236
|
-
|
237
|
-
params_for_key = bound_args.arguments.copy()
|
238
|
-
|
239
|
-
if include is not None:
|
240
|
-
params_for_key = {
|
241
|
-
k: v for k, v in params_for_key.items() if k in include
|
242
|
-
}
|
243
|
-
elif ignore is not None:
|
244
|
-
params_for_key = {
|
245
|
-
k: v for k, v in params_for_key.items() if k not in ignore
|
246
|
-
}
|
247
|
-
|
248
|
-
# Use the effective cache's make_hashable method
|
249
|
-
effective_cache = cache if cache is not None else get_decorator_cache()
|
250
|
-
key_parts = [
|
251
|
-
f"{k}={effective_cache.make_hashable(v)}"
|
252
|
-
for k, v in sorted(params_for_key.items())
|
253
|
-
]
|
254
|
-
return f"{func_to_decorate.__module__}.{func_to_decorate.__qualname__}({','.join(key_parts)})"
|
255
|
-
|
256
|
-
configured_cached_decorator = cached(
|
257
|
-
key=auto_key_generator, ttl=ttl, maxsize=maxsize, cache=cache
|
258
|
-
)
|
259
|
-
return configured_cached_decorator(func_to_decorate)
|
260
|
-
|
261
|
-
return actual_decorator
|
hammad/cache/file_cache.py
DELETED
@@ -1,80 +0,0 @@
|
|
1
|
-
"""hammad.cache.file_cache"""
|
2
|
-
|
3
|
-
from dataclasses import dataclass
|
4
|
-
from typing import Any, Literal, Optional, TypeAlias, Union
|
5
|
-
import os
|
6
|
-
import hashlib
|
7
|
-
import pickle
|
8
|
-
from pathlib import Path
|
9
|
-
|
10
|
-
from .base_cache import BaseCache
|
11
|
-
|
12
|
-
__all__ = ("FileCache", "FileCacheLocation")
|
13
|
-
|
14
|
-
|
15
|
-
FileCacheLocation: TypeAlias = Union[
|
16
|
-
# Example .pkl route
|
17
|
-
Literal["cache.pkl"], Literal["cache/"], str, Path
|
18
|
-
]
|
19
|
-
|
20
|
-
|
21
|
-
@dataclass
|
22
|
-
class FileCache(BaseCache):
|
23
|
-
"""
|
24
|
-
Persistent disk-based cache that stores data in a directory.
|
25
|
-
|
26
|
-
Uses pickle for serialization and automatically uses __pycache__ directory
|
27
|
-
if no cache directory is specified.
|
28
|
-
"""
|
29
|
-
|
30
|
-
location: Optional[str] = None
|
31
|
-
type: Literal["file"] = "file"
|
32
|
-
|
33
|
-
def __post_init__(self):
|
34
|
-
"""Initialize disk cache after dataclass initialization."""
|
35
|
-
super().__post_init__()
|
36
|
-
if self.location is None:
|
37
|
-
self.location = os.path.join(os.getcwd(), "__pycache__")
|
38
|
-
|
39
|
-
self.location_path = Path(self.location)
|
40
|
-
self.location_path.mkdir(exist_ok=True)
|
41
|
-
|
42
|
-
def _get_cache_path(self, key: str) -> Path:
|
43
|
-
"""Get the file path for a cache key."""
|
44
|
-
safe_key = hashlib.sha256(key.encode("utf-8")).hexdigest()
|
45
|
-
return self.location_path / f"cache_{safe_key}.pkl"
|
46
|
-
|
47
|
-
def __contains__(self, key: str) -> bool:
|
48
|
-
"""Check if key exists in cache."""
|
49
|
-
return self._get_cache_path(key).exists()
|
50
|
-
|
51
|
-
def __getitem__(self, key: str) -> Any:
|
52
|
-
"""Get value for key."""
|
53
|
-
cache_path = self._get_cache_path(key)
|
54
|
-
if not cache_path.exists():
|
55
|
-
raise KeyError(key)
|
56
|
-
|
57
|
-
try:
|
58
|
-
with open(cache_path, "rb") as f:
|
59
|
-
return pickle.load(f)
|
60
|
-
except (pickle.PickleError, OSError) as e:
|
61
|
-
cache_path.unlink(missing_ok=True)
|
62
|
-
raise KeyError(key) from e
|
63
|
-
|
64
|
-
def __setitem__(self, key: str, value: Any) -> None:
|
65
|
-
"""Set value for key."""
|
66
|
-
cache_path = self._get_cache_path(key)
|
67
|
-
try:
|
68
|
-
with open(cache_path, "wb") as f:
|
69
|
-
pickle.dump(value, f)
|
70
|
-
except (pickle.PickleError, OSError) as e:
|
71
|
-
cache_path.unlink(missing_ok=True)
|
72
|
-
raise RuntimeError(f"Failed to cache value for key '{key}': {e}") from e
|
73
|
-
|
74
|
-
def clear(self) -> None:
|
75
|
-
"""Clear all cached items."""
|
76
|
-
for cache_file in self.location_path.glob("cache_*.pkl"):
|
77
|
-
try:
|
78
|
-
cache_file.unlink()
|
79
|
-
except OSError:
|
80
|
-
pass
|
hammad/cache/ttl_cache.py
DELETED
@@ -1,74 +0,0 @@
|
|
1
|
-
"""hammad.cache.ttl_cache"""
|
2
|
-
|
3
|
-
from dataclasses import dataclass
|
4
|
-
from typing import Any, Literal, OrderedDict, Tuple
|
5
|
-
import time
|
6
|
-
|
7
|
-
from .base_cache import BaseCache
|
8
|
-
|
9
|
-
__all__ = ("TTLCache",)
|
10
|
-
|
11
|
-
|
12
|
-
@dataclass
|
13
|
-
class TTLCache(BaseCache):
|
14
|
-
"""
|
15
|
-
Thread-safe TTL cache implementation with LRU eviction.
|
16
|
-
|
17
|
-
Uses OrderedDict for efficient LRU tracking and automatic cleanup
|
18
|
-
of expired entries on access.
|
19
|
-
"""
|
20
|
-
|
21
|
-
maxsize: int = 1000
|
22
|
-
ttl: int = 3600
|
23
|
-
type: Literal["ttl"] = "ttl"
|
24
|
-
|
25
|
-
def __post_init__(self):
|
26
|
-
"""Initialize TTL cache after dataclass initialization."""
|
27
|
-
super().__post_init__()
|
28
|
-
self._cache: OrderedDict[str, Tuple[Any, float]] = OrderedDict()
|
29
|
-
|
30
|
-
def __contains__(self, key: str) -> bool:
|
31
|
-
"""Check if key exists and is not expired."""
|
32
|
-
if key in self._cache:
|
33
|
-
_value, timestamp = self._cache[key]
|
34
|
-
if time.time() - timestamp <= self.ttl:
|
35
|
-
self._cache.move_to_end(key)
|
36
|
-
return True
|
37
|
-
else:
|
38
|
-
# Expired, remove it
|
39
|
-
del self._cache[key]
|
40
|
-
return False
|
41
|
-
|
42
|
-
def __getitem__(self, key: str) -> Any:
|
43
|
-
"""Get value for key if not expired."""
|
44
|
-
if key in self:
|
45
|
-
return self._cache[key][0]
|
46
|
-
raise KeyError(key)
|
47
|
-
|
48
|
-
def __setitem__(self, key: str, value: Any) -> None:
|
49
|
-
"""Set value with current timestamp."""
|
50
|
-
if len(self._cache) >= self.maxsize and key not in self._cache:
|
51
|
-
self._cleanup_expired()
|
52
|
-
|
53
|
-
if len(self._cache) >= self.maxsize:
|
54
|
-
self._cache.popitem(last=False)
|
55
|
-
|
56
|
-
self._cache[key] = (value, time.time())
|
57
|
-
self._cache.move_to_end(key)
|
58
|
-
|
59
|
-
def _cleanup_expired(self) -> None:
|
60
|
-
"""Remove all expired entries."""
|
61
|
-
current_time = time.time()
|
62
|
-
|
63
|
-
expired_keys = [
|
64
|
-
k
|
65
|
-
for k, (_, ts) in list(self._cache.items())
|
66
|
-
if current_time - ts > self.ttl
|
67
|
-
]
|
68
|
-
for k in expired_keys:
|
69
|
-
if k in self._cache:
|
70
|
-
del self._cache[k]
|
71
|
-
|
72
|
-
def clear(self) -> None:
|
73
|
-
"""Clear all cached items."""
|
74
|
-
self._cache.clear()
|
hammad/cli/__init__.py
DELETED
@@ -1,33 +0,0 @@
|
|
1
|
-
"""hammad.cli
|
2
|
-
|
3
|
-
Contains resources for styling rendered CLI content as well
|
4
|
-
as extensions / utilities for creating CLI interfaces."""
|
5
|
-
|
6
|
-
from typing import TYPE_CHECKING
|
7
|
-
from .._internal import create_getattr_importer
|
8
|
-
|
9
|
-
if TYPE_CHECKING:
|
10
|
-
from .plugins import print, input, animate
|
11
|
-
from .styles.settings import (
|
12
|
-
CLIStyleRenderableSettings,
|
13
|
-
CLIStyleBackgroundSettings,
|
14
|
-
CLIStyleLiveSettings,
|
15
|
-
)
|
16
|
-
|
17
|
-
|
18
|
-
__all__ = (
|
19
|
-
"print",
|
20
|
-
"input",
|
21
|
-
"animate",
|
22
|
-
"CLIStyleRenderableSettings",
|
23
|
-
"CLIStyleBackgroundSettings",
|
24
|
-
"CLIStyleLiveSettings",
|
25
|
-
)
|
26
|
-
|
27
|
-
|
28
|
-
__getattr__ = create_getattr_importer(__all__)
|
29
|
-
|
30
|
-
|
31
|
-
def __dir__() -> list[str]:
|
32
|
-
"""Get the attributes of the plugins module."""
|
33
|
-
return list(__all__)
|