hammad-python 0.0.14__py3-none-any.whl → 0.0.15__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.
Files changed (101) hide show
  1. hammad_python-0.0.15.dist-info/METADATA +184 -0
  2. hammad_python-0.0.15.dist-info/RECORD +4 -0
  3. hammad/__init__.py +0 -1
  4. hammad/ai/__init__.py +0 -1
  5. hammad/ai/_utils.py +0 -142
  6. hammad/ai/completions/__init__.py +0 -45
  7. hammad/ai/completions/client.py +0 -684
  8. hammad/ai/completions/create.py +0 -710
  9. hammad/ai/completions/settings.py +0 -100
  10. hammad/ai/completions/types.py +0 -792
  11. hammad/ai/completions/utils.py +0 -486
  12. hammad/ai/embeddings/__init__.py +0 -35
  13. hammad/ai/embeddings/client/__init__.py +0 -1
  14. hammad/ai/embeddings/client/base_embeddings_client.py +0 -26
  15. hammad/ai/embeddings/client/fastembed_text_embeddings_client.py +0 -200
  16. hammad/ai/embeddings/client/litellm_embeddings_client.py +0 -288
  17. hammad/ai/embeddings/create.py +0 -159
  18. hammad/ai/embeddings/types.py +0 -69
  19. hammad/cache/__init__.py +0 -40
  20. hammad/cache/base_cache.py +0 -181
  21. hammad/cache/cache.py +0 -169
  22. hammad/cache/decorators.py +0 -261
  23. hammad/cache/file_cache.py +0 -80
  24. hammad/cache/ttl_cache.py +0 -74
  25. hammad/cli/__init__.py +0 -33
  26. hammad/cli/animations.py +0 -573
  27. hammad/cli/plugins.py +0 -781
  28. hammad/cli/styles/__init__.py +0 -55
  29. hammad/cli/styles/settings.py +0 -139
  30. hammad/cli/styles/types.py +0 -358
  31. hammad/cli/styles/utils.py +0 -480
  32. hammad/data/__init__.py +0 -56
  33. hammad/data/collections/__init__.py +0 -34
  34. hammad/data/collections/base_collection.py +0 -58
  35. hammad/data/collections/collection.py +0 -452
  36. hammad/data/collections/searchable_collection.py +0 -556
  37. hammad/data/collections/vector_collection.py +0 -596
  38. hammad/data/configurations/__init__.py +0 -35
  39. hammad/data/configurations/configuration.py +0 -564
  40. hammad/data/databases/__init__.py +0 -21
  41. hammad/data/databases/database.py +0 -902
  42. hammad/data/models/__init__.py +0 -44
  43. hammad/data/models/base/__init__.py +0 -35
  44. hammad/data/models/base/fields.py +0 -546
  45. hammad/data/models/base/model.py +0 -1078
  46. hammad/data/models/base/utils.py +0 -280
  47. hammad/data/models/pydantic/__init__.py +0 -55
  48. hammad/data/models/pydantic/converters.py +0 -632
  49. hammad/data/models/pydantic/models/__init__.py +0 -28
  50. hammad/data/models/pydantic/models/arbitrary_model.py +0 -46
  51. hammad/data/models/pydantic/models/cacheable_model.py +0 -79
  52. hammad/data/models/pydantic/models/fast_model.py +0 -318
  53. hammad/data/models/pydantic/models/function_model.py +0 -176
  54. hammad/data/models/pydantic/models/subscriptable_model.py +0 -63
  55. hammad/data/types/__init__.py +0 -41
  56. hammad/data/types/file.py +0 -358
  57. hammad/data/types/multimodal/__init__.py +0 -24
  58. hammad/data/types/multimodal/audio.py +0 -96
  59. hammad/data/types/multimodal/image.py +0 -80
  60. hammad/data/types/text.py +0 -1066
  61. hammad/formatting/__init__.py +0 -38
  62. hammad/formatting/json/__init__.py +0 -21
  63. hammad/formatting/json/converters.py +0 -152
  64. hammad/formatting/text/__init__.py +0 -63
  65. hammad/formatting/text/converters.py +0 -723
  66. hammad/formatting/text/markdown.py +0 -131
  67. hammad/formatting/yaml/__init__.py +0 -26
  68. hammad/formatting/yaml/converters.py +0 -5
  69. hammad/logging/__init__.py +0 -35
  70. hammad/logging/decorators.py +0 -834
  71. hammad/logging/logger.py +0 -954
  72. hammad/mcp/__init__.py +0 -50
  73. hammad/mcp/client/__init__.py +0 -1
  74. hammad/mcp/client/client.py +0 -523
  75. hammad/mcp/client/client_service.py +0 -393
  76. hammad/mcp/client/settings.py +0 -178
  77. hammad/mcp/servers/__init__.py +0 -1
  78. hammad/mcp/servers/launcher.py +0 -1161
  79. hammad/performance/__init__.py +0 -36
  80. hammad/performance/imports.py +0 -231
  81. hammad/performance/runtime/__init__.py +0 -32
  82. hammad/performance/runtime/decorators.py +0 -142
  83. hammad/performance/runtime/run.py +0 -299
  84. hammad/py.typed +0 -0
  85. hammad/service/__init__.py +0 -49
  86. hammad/service/create.py +0 -532
  87. hammad/service/decorators.py +0 -285
  88. hammad/typing/__init__.py +0 -407
  89. hammad/web/__init__.py +0 -43
  90. hammad/web/http/__init__.py +0 -1
  91. hammad/web/http/client.py +0 -944
  92. hammad/web/models.py +0 -245
  93. hammad/web/openapi/__init__.py +0 -1
  94. hammad/web/openapi/client.py +0 -740
  95. hammad/web/search/__init__.py +0 -1
  96. hammad/web/search/client.py +0 -988
  97. hammad/web/utils.py +0 -472
  98. hammad_python-0.0.14.dist-info/METADATA +0 -70
  99. hammad_python-0.0.14.dist-info/RECORD +0 -99
  100. {hammad_python-0.0.14.dist-info → hammad_python-0.0.15.dist-info}/WHEEL +0 -0
  101. {hammad_python-0.0.14.dist-info → hammad_python-0.0.15.dist-info}/licenses/LICENSE +0 -0
@@ -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
@@ -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 ..performance.imports 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__)