filedgr-pkg-utils 0.8.4__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.
- filedgr_pkg_utils/__init__.py +1 -0
- filedgr_pkg_utils/caching/__init__.py +1 -0
- filedgr_pkg_utils/caching/memoize.py +54 -0
- filedgr_pkg_utils/canonicalization/__init__.py +0 -0
- filedgr_pkg_utils/canonicalization/canonical_json_mixin.py +38 -0
- filedgr_pkg_utils/compression/__init__.py +7 -0
- filedgr_pkg_utils/compression/algorithms/__init__.py +0 -0
- filedgr_pkg_utils/compression/algorithms/compression_algorithm_brotli.py +31 -0
- filedgr_pkg_utils/compression/algorithms/compression_algorithm_zip.py +45 -0
- filedgr_pkg_utils/compression/algorithms/compression_algorithm_zstd.py +35 -0
- filedgr_pkg_utils/compression/algorithms/compression_algortihm_gzip.py +34 -0
- filedgr_pkg_utils/compression/compression_algorithm.py +24 -0
- filedgr_pkg_utils/compression/compression_utils.py +37 -0
- filedgr_pkg_utils/converters/__init__.py +0 -0
- filedgr_pkg_utils/converters/abstract_converter.py +21 -0
- filedgr_pkg_utils/cryptography/__init__.py +0 -0
- filedgr_pkg_utils/cryptography/hashing/__init__.py +0 -0
- filedgr_pkg_utils/cryptography/hashing/conversion_utils.py +4 -0
- filedgr_pkg_utils/cryptography/hashing/hash_algorithm.py +101 -0
- filedgr_pkg_utils/cryptography/hashing/hash_utils.py +18 -0
- filedgr_pkg_utils/cryptography/signing/__init__.py +6 -0
- filedgr_pkg_utils/cryptography/signing/conversion_utils.py +27 -0
- filedgr_pkg_utils/cryptography/signing/hmac_signature_algorithm.py +15 -0
- filedgr_pkg_utils/cryptography/signing/secp256k1_evm_signature_algorithm.py +20 -0
- filedgr_pkg_utils/cryptography/signing/secp256k1_signature_algorithm.py +46 -0
- filedgr_pkg_utils/cryptography/signing/signature_algorithm.py +10 -0
- filedgr_pkg_utils/cryptography/signing/signature_utils.py +31 -0
- filedgr_pkg_utils/evm/__init__.py +8 -0
- filedgr_pkg_utils/evm/hex_utils.py +81 -0
- filedgr_pkg_utils/filesystem/__init__.py +1 -0
- filedgr_pkg_utils/filesystem/atomic.py +124 -0
- filedgr_pkg_utils/filesystem/tar_utils.py +50 -0
- filedgr_pkg_utils/fldgr_logging/__init__.py +1 -0
- filedgr_pkg_utils/fldgr_logging/sanitizer_logger_adapter.py +22 -0
- filedgr_pkg_utils/fldgr_logging/structured_logger.py +78 -0
- filedgr_pkg_utils/hooks/__init__.py +0 -0
- filedgr_pkg_utils/hooks/decorators.py +246 -0
- filedgr_pkg_utils/images/__init__.py +0 -0
- filedgr_pkg_utils/images/hashing/__init__.py +6 -0
- filedgr_pkg_utils/images/hashing/algorithms/__init__.py +0 -0
- filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_ahash.py +33 -0
- filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_dhash.py +33 -0
- filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_phash.py +33 -0
- filedgr_pkg_utils/images/hashing/image_hash_algorithm.py +14 -0
- filedgr_pkg_utils/images/hashing/image_hash_utils.py +31 -0
- filedgr_pkg_utils/mixins/__init__.py +0 -0
- filedgr_pkg_utils/mixins/without_keys_mixin.py +7 -0
- filedgr_pkg_utils/resilience/__init__.py +5 -0
- filedgr_pkg_utils/resilience/decorators.py +192 -0
- filedgr_pkg_utils/security/__init__.py +0 -0
- filedgr_pkg_utils/security/sanitizer.py +60 -0
- filedgr_pkg_utils/security/sanitizer_decorators.py +30 -0
- filedgr_pkg_utils-0.8.4.dist-info/METADATA +171 -0
- filedgr_pkg_utils-0.8.4.dist-info/RECORD +56 -0
- filedgr_pkg_utils-0.8.4.dist-info/WHEEL +5 -0
- filedgr_pkg_utils-0.8.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
try:
|
|
2
|
+
from PIL import Image
|
|
3
|
+
import imagehash
|
|
4
|
+
_HAS_IMAGE_DEPS = True
|
|
5
|
+
except ImportError:
|
|
6
|
+
_HAS_IMAGE_DEPS = False
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _require_image_deps():
|
|
10
|
+
if not _HAS_IMAGE_DEPS:
|
|
11
|
+
raise ImportError(
|
|
12
|
+
"Image hashing dependencies are missing. "
|
|
13
|
+
"To use this feature, install the package with the 'images' extra: "
|
|
14
|
+
"pip install 'filedgr-pkg-utils[images]'"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DHashAlgorithm:
|
|
19
|
+
"""
|
|
20
|
+
Difference Hash (dHash) - Tracks gradients.
|
|
21
|
+
Extremely fast and highly resistant to brightness/contrast changes.
|
|
22
|
+
"""
|
|
23
|
+
name = "dhash"
|
|
24
|
+
|
|
25
|
+
def __init__(self, hash_size: int = 8):
|
|
26
|
+
self.hash_size = hash_size
|
|
27
|
+
|
|
28
|
+
def hash_image(self, image_path: str) -> str:
|
|
29
|
+
with Image.open(image_path) as img:
|
|
30
|
+
return str(imagehash.dhash(img, hash_size=self.hash_size))
|
|
31
|
+
|
|
32
|
+
def compute_distance(self, hash1: str, hash2: str) -> int:
|
|
33
|
+
return imagehash.hex_to_hash(hash1) - imagehash.hex_to_hash(hash2)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
try:
|
|
2
|
+
from PIL import Image
|
|
3
|
+
import imagehash
|
|
4
|
+
_HAS_IMAGE_DEPS = True
|
|
5
|
+
except ImportError:
|
|
6
|
+
_HAS_IMAGE_DEPS = False
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _require_image_deps():
|
|
10
|
+
if not _HAS_IMAGE_DEPS:
|
|
11
|
+
raise ImportError(
|
|
12
|
+
"Image hashing dependencies are missing. "
|
|
13
|
+
"To use this feature, install the package with the 'images' extra: "
|
|
14
|
+
"pip install 'filedgr-pkg-utils[images]'"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PHashAlgorithm:
|
|
19
|
+
"""
|
|
20
|
+
Perceptual Hash (pHash) - Uses Discrete Cosine Transform (DCT).
|
|
21
|
+
Great for general image similarity, highly resistant to compression and resizing.
|
|
22
|
+
"""
|
|
23
|
+
name = "phash"
|
|
24
|
+
|
|
25
|
+
def __init__(self, hash_size: int = 8):
|
|
26
|
+
self.hash_size = hash_size
|
|
27
|
+
|
|
28
|
+
def hash_image(self, image_path: str) -> str:
|
|
29
|
+
with Image.open(image_path) as img:
|
|
30
|
+
return str(imagehash.phash(img, hash_size=self.hash_size))
|
|
31
|
+
|
|
32
|
+
def compute_distance(self, hash1: str, hash2: str) -> int:
|
|
33
|
+
return imagehash.hex_to_hash(hash1) - imagehash.hex_to_hash(hash2)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from typing import Protocol
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ImageHashAlgorithm(Protocol):
|
|
5
|
+
"""Protocol for perceptual image hashing algorithms."""
|
|
6
|
+
name: str
|
|
7
|
+
|
|
8
|
+
def hash_image(self, image_path: str) -> str:
|
|
9
|
+
"""Generates a perceptual hash as a hex string."""
|
|
10
|
+
...
|
|
11
|
+
|
|
12
|
+
def compute_distance(self, hash1: str, hash2: str) -> int:
|
|
13
|
+
"""Computes the Hamming distance between two hex hashes."""
|
|
14
|
+
...
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from filedgr_pkg_utils.images.hashing.image_hash_algorithm import ImageHashAlgorithm
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ImageHashUtils:
|
|
6
|
+
def __init__(self, algorithm: ImageHashAlgorithm):
|
|
7
|
+
self.algorithm = algorithm
|
|
8
|
+
|
|
9
|
+
def hash_image(self, image_path: str) -> str:
|
|
10
|
+
"""
|
|
11
|
+
Generates a perceptual hash for the given image.
|
|
12
|
+
"""
|
|
13
|
+
if not os.path.isfile(image_path):
|
|
14
|
+
raise FileNotFoundError(f"Image not found: {image_path}")
|
|
15
|
+
return self.algorithm.hash_image(image_path)
|
|
16
|
+
|
|
17
|
+
def compute_distance(self, hash1: str, hash2: str) -> int:
|
|
18
|
+
"""
|
|
19
|
+
Computes the Hamming distance between two hashes.
|
|
20
|
+
A distance of 0 means the hashes are identical.
|
|
21
|
+
"""
|
|
22
|
+
# Cast to a native Python int to prevent leaking NumPy integer types
|
|
23
|
+
return int(self.algorithm.compute_distance(hash1, hash2))
|
|
24
|
+
|
|
25
|
+
def is_similar(self, hash1: str, hash2: str, max_distance: int = 5) -> bool:
|
|
26
|
+
"""
|
|
27
|
+
Determines if two hashes are considered "similar".
|
|
28
|
+
"""
|
|
29
|
+
distance = self.compute_distance(hash1, hash2)
|
|
30
|
+
# Cast to a native Python bool to prevent leaking NumPy np.True_ / np.False_
|
|
31
|
+
return bool(distance <= max_distance)
|
|
File without changes
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import asyncio
|
|
3
|
+
import inspect
|
|
4
|
+
from functools import wraps
|
|
5
|
+
from typing import Callable, Tuple, Type
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def retry(
|
|
10
|
+
max_attempts: int = 3,
|
|
11
|
+
backoff_seconds: float = 1.0,
|
|
12
|
+
backoff_multiplier: float = 2.0,
|
|
13
|
+
exceptions: Tuple[Type[Exception], ...] = (Exception,)
|
|
14
|
+
):
|
|
15
|
+
"""Retries a function with exponential backoff on specific exceptions."""
|
|
16
|
+
|
|
17
|
+
def decorator(func: Callable) -> Callable:
|
|
18
|
+
if inspect.iscoroutinefunction(func):
|
|
19
|
+
@wraps(func)
|
|
20
|
+
async def async_wrapper(*args, **kwargs):
|
|
21
|
+
attempts = 0
|
|
22
|
+
current_backoff = backoff_seconds
|
|
23
|
+
while attempts < max_attempts:
|
|
24
|
+
attempts += 1
|
|
25
|
+
try:
|
|
26
|
+
return await func(*args, **kwargs)
|
|
27
|
+
except exceptions as e:
|
|
28
|
+
if attempts == max_attempts:
|
|
29
|
+
raise e
|
|
30
|
+
await asyncio.sleep(current_backoff)
|
|
31
|
+
current_backoff *= backoff_multiplier
|
|
32
|
+
|
|
33
|
+
return async_wrapper
|
|
34
|
+
else:
|
|
35
|
+
@wraps(func)
|
|
36
|
+
def sync_wrapper(*args, **kwargs):
|
|
37
|
+
attempts = 0
|
|
38
|
+
current_backoff = backoff_seconds
|
|
39
|
+
while attempts < max_attempts:
|
|
40
|
+
attempts += 1
|
|
41
|
+
try:
|
|
42
|
+
return func(*args, **kwargs)
|
|
43
|
+
except exceptions as e:
|
|
44
|
+
if attempts == max_attempts:
|
|
45
|
+
raise e
|
|
46
|
+
time.sleep(current_backoff)
|
|
47
|
+
current_backoff *= backoff_multiplier
|
|
48
|
+
|
|
49
|
+
return sync_wrapper
|
|
50
|
+
|
|
51
|
+
return decorator
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def circuit_breaker(failure_threshold: int = 5, recovery_timeout_seconds: float = 30.0):
|
|
55
|
+
"""Trips after N failures, preventing execution until recovery timeout passes."""
|
|
56
|
+
|
|
57
|
+
def decorator(func: Callable) -> Callable:
|
|
58
|
+
# Closure state
|
|
59
|
+
state = {"failures": 0, "last_failure_time": 0.0, "state": "CLOSED"}
|
|
60
|
+
|
|
61
|
+
def check_circuit():
|
|
62
|
+
if state["state"] == "OPEN":
|
|
63
|
+
if time.time() - state["last_failure_time"] > recovery_timeout_seconds:
|
|
64
|
+
state["state"] = "HALF_OPEN"
|
|
65
|
+
else:
|
|
66
|
+
raise RuntimeError("Circuit Breaker is OPEN.")
|
|
67
|
+
|
|
68
|
+
def handle_success():
|
|
69
|
+
state["failures"] = 0
|
|
70
|
+
state["state"] = "CLOSED"
|
|
71
|
+
|
|
72
|
+
def handle_failure():
|
|
73
|
+
state["failures"] += 1
|
|
74
|
+
state["last_failure_time"] = time.time()
|
|
75
|
+
if state["failures"] >= failure_threshold:
|
|
76
|
+
state["state"] = "OPEN"
|
|
77
|
+
|
|
78
|
+
if inspect.iscoroutinefunction(func):
|
|
79
|
+
@wraps(func)
|
|
80
|
+
async def async_wrapper(*args, **kwargs):
|
|
81
|
+
check_circuit()
|
|
82
|
+
try:
|
|
83
|
+
result = await func(*args, **kwargs)
|
|
84
|
+
handle_success()
|
|
85
|
+
return result
|
|
86
|
+
except Exception as e:
|
|
87
|
+
handle_failure()
|
|
88
|
+
raise e
|
|
89
|
+
|
|
90
|
+
return async_wrapper
|
|
91
|
+
else:
|
|
92
|
+
@wraps(func)
|
|
93
|
+
def sync_wrapper(*args, **kwargs):
|
|
94
|
+
check_circuit()
|
|
95
|
+
try:
|
|
96
|
+
result = func(*args, **kwargs)
|
|
97
|
+
handle_success()
|
|
98
|
+
return result
|
|
99
|
+
except Exception as e:
|
|
100
|
+
handle_failure()
|
|
101
|
+
raise e
|
|
102
|
+
|
|
103
|
+
return sync_wrapper
|
|
104
|
+
|
|
105
|
+
return decorator
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def fallback(fallback_function: Callable):
|
|
109
|
+
"""Executes a fallback function if the main function raises an exception."""
|
|
110
|
+
|
|
111
|
+
def decorator(func: Callable) -> Callable:
|
|
112
|
+
if inspect.iscoroutinefunction(func):
|
|
113
|
+
@wraps(func)
|
|
114
|
+
async def async_wrapper(*args, **kwargs):
|
|
115
|
+
try:
|
|
116
|
+
return await func(*args, **kwargs)
|
|
117
|
+
except Exception:
|
|
118
|
+
if inspect.iscoroutinefunction(fallback_function):
|
|
119
|
+
return await fallback_function(*args, **kwargs)
|
|
120
|
+
return fallback_function(*args, **kwargs)
|
|
121
|
+
|
|
122
|
+
return async_wrapper
|
|
123
|
+
else:
|
|
124
|
+
@wraps(func)
|
|
125
|
+
def sync_wrapper(*args, **kwargs):
|
|
126
|
+
try:
|
|
127
|
+
return func(*args, **kwargs)
|
|
128
|
+
except Exception:
|
|
129
|
+
if inspect.iscoroutinefunction(fallback_function):
|
|
130
|
+
raise RuntimeError("Cannot use an async fallback with a sync function.")
|
|
131
|
+
return fallback_function(*args, **kwargs)
|
|
132
|
+
|
|
133
|
+
return sync_wrapper
|
|
134
|
+
|
|
135
|
+
return decorator
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def timeout(seconds: float):
|
|
139
|
+
"""Cancels the execution if it takes longer than `seconds`."""
|
|
140
|
+
|
|
141
|
+
def decorator(func: Callable) -> Callable:
|
|
142
|
+
if inspect.iscoroutinefunction(func):
|
|
143
|
+
@wraps(func)
|
|
144
|
+
async def async_wrapper(*args, **kwargs):
|
|
145
|
+
return await asyncio.wait_for(func(*args, **kwargs), timeout=seconds)
|
|
146
|
+
|
|
147
|
+
return async_wrapper
|
|
148
|
+
else:
|
|
149
|
+
@wraps(func)
|
|
150
|
+
def sync_wrapper(*args, **kwargs):
|
|
151
|
+
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
152
|
+
future = executor.submit(func, *args, **kwargs)
|
|
153
|
+
try:
|
|
154
|
+
return future.result(timeout=seconds)
|
|
155
|
+
except FuturesTimeoutError:
|
|
156
|
+
raise TimeoutError(f"Function timed out after {seconds}s")
|
|
157
|
+
|
|
158
|
+
return sync_wrapper
|
|
159
|
+
|
|
160
|
+
return decorator
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def rate_limit(calls: int = 5, period_seconds: float = 1.0):
|
|
164
|
+
"""Limits the amount of times a function can be called in a given period."""
|
|
165
|
+
|
|
166
|
+
def decorator(func: Callable) -> Callable:
|
|
167
|
+
timestamps = []
|
|
168
|
+
|
|
169
|
+
def check_rate_limit():
|
|
170
|
+
now = time.time()
|
|
171
|
+
# Remove timestamps older than the period
|
|
172
|
+
timestamps[:] = [t for t in timestamps if now - t < period_seconds]
|
|
173
|
+
if len(timestamps) >= calls:
|
|
174
|
+
raise PermissionError("Rate limit exceeded")
|
|
175
|
+
timestamps.append(now)
|
|
176
|
+
|
|
177
|
+
if inspect.iscoroutinefunction(func):
|
|
178
|
+
@wraps(func)
|
|
179
|
+
async def async_wrapper(*args, **kwargs):
|
|
180
|
+
check_rate_limit()
|
|
181
|
+
return await func(*args, **kwargs)
|
|
182
|
+
|
|
183
|
+
return async_wrapper
|
|
184
|
+
else:
|
|
185
|
+
@wraps(func)
|
|
186
|
+
def sync_wrapper(*args, **kwargs):
|
|
187
|
+
check_rate_limit()
|
|
188
|
+
return func(*args, **kwargs)
|
|
189
|
+
|
|
190
|
+
return sync_wrapper
|
|
191
|
+
|
|
192
|
+
return decorator
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from typing import Any, List, Set, Union
|
|
2
|
+
|
|
3
|
+
# A robust default set of keys that should almost always be redacted in logs
|
|
4
|
+
DEFAULT_SENSITIVE_KEYS: Set[str] = {
|
|
5
|
+
"password",
|
|
6
|
+
"secret",
|
|
7
|
+
"token",
|
|
8
|
+
"api_key",
|
|
9
|
+
"apikey",
|
|
10
|
+
"authorization",
|
|
11
|
+
"jwt",
|
|
12
|
+
"bearer",
|
|
13
|
+
"credit_card",
|
|
14
|
+
"ssn",
|
|
15
|
+
"private_key",
|
|
16
|
+
"client_secret"
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sanitize_data(
|
|
21
|
+
data: Any,
|
|
22
|
+
sensitive_keys: Union[Set[str], List[str], None] = None,
|
|
23
|
+
mask: str = "*****"
|
|
24
|
+
) -> Any:
|
|
25
|
+
"""
|
|
26
|
+
Recursively scans dictionaries and lists, replacing the values of sensitive keys
|
|
27
|
+
with a mask string. Safely builds a new object without mutating the original.
|
|
28
|
+
|
|
29
|
+
:param data: The input dictionary, list, or primitive to sanitize.
|
|
30
|
+
:param sensitive_keys: A custom list/set of keys to redact. Defaults to DEFAULT_SENSITIVE_KEYS.
|
|
31
|
+
:param mask: The string used to replace sensitive values.
|
|
32
|
+
:return: A sanitized copy of the data.
|
|
33
|
+
"""
|
|
34
|
+
if sensitive_keys is None:
|
|
35
|
+
target_keys = DEFAULT_SENSITIVE_KEYS
|
|
36
|
+
else:
|
|
37
|
+
target_keys = {k.lower() for k in sensitive_keys}
|
|
38
|
+
|
|
39
|
+
# Handle Dictionaries
|
|
40
|
+
if isinstance(data, dict):
|
|
41
|
+
sanitized_dict = {}
|
|
42
|
+
for key, value in data.items():
|
|
43
|
+
# Check if the key is a string and if its lowercase version matches our sensitive list
|
|
44
|
+
if isinstance(key, str) and key.lower() in target_keys:
|
|
45
|
+
sanitized_dict[key] = mask
|
|
46
|
+
else:
|
|
47
|
+
# Recursively sanitize nested structures
|
|
48
|
+
sanitized_dict[key] = sanitize_data(value, target_keys, mask)
|
|
49
|
+
return sanitized_dict
|
|
50
|
+
|
|
51
|
+
# Handle Lists
|
|
52
|
+
elif isinstance(data, list):
|
|
53
|
+
return [sanitize_data(item, target_keys, mask) for item in data]
|
|
54
|
+
|
|
55
|
+
# Handle Tuples
|
|
56
|
+
elif isinstance(data, tuple):
|
|
57
|
+
return tuple(sanitize_data(item, target_keys, mask) for item in data)
|
|
58
|
+
|
|
59
|
+
# Return primitive types (strings, ints, floats, booleans, None) untouched
|
|
60
|
+
return data
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from functools import wraps
|
|
3
|
+
from typing import Callable, Union, List, Set
|
|
4
|
+
|
|
5
|
+
from filedgr_pkg_utils.security.sanitizer import sanitize_data
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def sanitize_return(
|
|
9
|
+
sensitive_keys: Union[Set[str], List[str], None] = None,
|
|
10
|
+
mask: str = "*****"
|
|
11
|
+
):
|
|
12
|
+
"""
|
|
13
|
+
Decorator that sanitizes the return value of a function.
|
|
14
|
+
WARNING: Use this only at system boundaries (like API endpoints)
|
|
15
|
+
to prevent destroying data needed by downstream internal functions.
|
|
16
|
+
"""
|
|
17
|
+
def decorator(func: Callable) -> Callable:
|
|
18
|
+
if inspect.iscoroutinefunction(func):
|
|
19
|
+
@wraps(func)
|
|
20
|
+
async def async_wrapper(*args, **kwargs):
|
|
21
|
+
result = await func(*args, **kwargs)
|
|
22
|
+
return sanitize_data(result, sensitive_keys, mask)
|
|
23
|
+
return async_wrapper
|
|
24
|
+
else:
|
|
25
|
+
@wraps(func)
|
|
26
|
+
def sync_wrapper(*args, **kwargs):
|
|
27
|
+
result = func(*args, **kwargs)
|
|
28
|
+
return sanitize_data(result, sensitive_keys, mask)
|
|
29
|
+
return sync_wrapper
|
|
30
|
+
return decorator
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: filedgr-pkg-utils
|
|
3
|
+
Version: 0.8.4
|
|
4
|
+
Summary: A library of python based utils needed in the filedgr code stack
|
|
5
|
+
Author-email: Filedgr <code@filedgr.com>
|
|
6
|
+
Project-URL: repository, https://github.com/Filedgr/filedgr-pkg-utils
|
|
7
|
+
Keywords: filedgr,pkg,utils
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: pydantic<3.0.0,>=2.12.5
|
|
14
|
+
Requires-Dist: cryptography<50.0.0,>=49.0.0
|
|
15
|
+
Requires-Dist: orjson<4.0.0,>=3.11.5
|
|
16
|
+
Requires-Dist: web3<8.0.0,>=7.14.0
|
|
17
|
+
Requires-Dist: zstandard<1.0.0,>=0.22.0
|
|
18
|
+
Requires-Dist: Brotli<2.0.0,>=1.1.0
|
|
19
|
+
Requires-Dist: aiofiles<26.0.0,>=25.1.0
|
|
20
|
+
Provides-Extra: build
|
|
21
|
+
Requires-Dist: build; extra == "build"
|
|
22
|
+
Requires-Dist: twine; extra == "build"
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: black; extra == "dev"
|
|
25
|
+
Requires-Dist: bumpver; extra == "dev"
|
|
26
|
+
Requires-Dist: isort; extra == "dev"
|
|
27
|
+
Requires-Dist: mypy; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest; extra == "dev"
|
|
29
|
+
Requires-Dist: flake8; extra == "dev"
|
|
30
|
+
Provides-Extra: images
|
|
31
|
+
Requires-Dist: ImageHash<5.0.0,>=4.3.0; extra == "images"
|
|
32
|
+
Requires-Dist: Pillow<11.0.0,>=10.0.0; extra == "images"
|
|
33
|
+
|
|
34
|
+
# filedgr-pkg-utils
|
|
35
|
+
|
|
36
|
+

|
|
37
|
+

|
|
38
|
+

|
|
39
|
+
[](https://pypi.org/project/filedgr-pkg-utils/)
|
|
40
|
+

|
|
41
|
+
|
|
42
|
+
A comprehensive, production-ready Python utility toolkit for modern distributed systems, Web3 integrations, and data-heavy microservices.
|
|
43
|
+
|
|
44
|
+
`filedgr-pkg-utils` provides a unified, protocol-driven API for cryptography, resilient networking, deterministic data serialization, compression, and structured logging.
|
|
45
|
+
|
|
46
|
+
## 📦 Installation
|
|
47
|
+
|
|
48
|
+
Install the base package (extremely lightweight, ideal for AWS Lambda):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install filedgr-pkg-utils
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Install with optional image perceptual hashing support (includes Pillow and ImageHash):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install "filedgr-pkg-utils[images]"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 🚀 Prominent Features & Examples
|
|
61
|
+
|
|
62
|
+
### 1. Resilience & Aspect-Oriented Hooks
|
|
63
|
+
|
|
64
|
+
Stop writing try/except blocks with `time.sleep()`. Stack our context-aware decorators to build bulletproof network calls and clean up your business logic.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from filedgr_pkg_utils.resilience.decorators import retry, circuit_breaker, fallback
|
|
68
|
+
from filedgr_pkg_utils.hooks.post_action import post_action
|
|
69
|
+
|
|
70
|
+
def audit_log(result, *args, **kwargs):
|
|
71
|
+
print(f"Audit: Successfully fetched data {result}")
|
|
72
|
+
|
|
73
|
+
def serve_stale_data(*args, **kwargs):
|
|
74
|
+
return {"status": "stale", "data": []}
|
|
75
|
+
|
|
76
|
+
@post_action(callback=audit_log)
|
|
77
|
+
@fallback(fallback_function=serve_stale_data)
|
|
78
|
+
@circuit_breaker(failure_threshold=5, recovery_timeout_seconds=30)
|
|
79
|
+
@retry(max_attempts=3, backoff_multiplier=2.0)
|
|
80
|
+
async def fetch_web3_data(node_url: str):
|
|
81
|
+
# This function is completely protected.
|
|
82
|
+
# It will retry on failure, trip a circuit breaker if the node is down,
|
|
83
|
+
# serve stale data if all else fails, and log the result when successful.
|
|
84
|
+
pass
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 2. Unified Compression
|
|
88
|
+
|
|
89
|
+
A single, clean protocol for zip, gzip, zstd, and brotli. Easily swap algorithms without changing your application code.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from filedgr_pkg_utils.compression import CompressionUtils, ZstdAlgorithm, ZipAlgorithm
|
|
93
|
+
|
|
94
|
+
# Swap from standard Zip to high-performance Zstd in one line
|
|
95
|
+
utils = CompressionUtils(ZstdAlgorithm(level=3))
|
|
96
|
+
|
|
97
|
+
# Compress bytes
|
|
98
|
+
compressed_data = utils.compress(b"Hello World")
|
|
99
|
+
|
|
100
|
+
# Compress files and directories
|
|
101
|
+
utils.compress_file("data.json", "data.json.zst")
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 3. Canonical Serialization & Cryptography
|
|
105
|
+
|
|
106
|
+
Generate deterministic, whitespace-free, and alphabetically sorted JSON payloads—perfect for creating verifiable hashes and blockchain signatures.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from filedgr_pkg_utils.canonicalization.canonical_json_mixin import CanonicalJsonMixin
|
|
110
|
+
from datetime import datetime, timezone
|
|
111
|
+
|
|
112
|
+
class BlockchainPayload(CanonicalJsonMixin):
|
|
113
|
+
z_field: str
|
|
114
|
+
a_field: int
|
|
115
|
+
timestamp: datetime
|
|
116
|
+
|
|
117
|
+
payload = BlockchainPayload(
|
|
118
|
+
z_field="last",
|
|
119
|
+
a_field=1,
|
|
120
|
+
timestamp=datetime(2023, 10, 25, 12, 30, 0, tzinfo=timezone.utc)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Output is strictly deterministic: {"a_field":1,"timestamp":"2023-10-25T12:30:00.000Z","z_field":"last"}
|
|
124
|
+
json_string = payload.canonical_json()
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### 4. Zero-Config Structured JSON Logging
|
|
128
|
+
|
|
129
|
+
Output logs as deterministic JSON for flawless Datadog or AWS CloudWatch ingestion. Fully integrates with Python's standard logging library.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from filedgr_pkg_utils.logging import LoggerFactory
|
|
133
|
+
|
|
134
|
+
# Automatically reads FILEDGR_LOGGING_ENABLED env var
|
|
135
|
+
logger = LoggerFactory.get_logger(__name__)
|
|
136
|
+
|
|
137
|
+
logger.info("Processing file", extra={"file_id": "ABC-123", "correlation_id": "999"})
|
|
138
|
+
# Output: {"timestamp": "2026-05-14T12:00:00.000Z", "level": "INFO", "logger": "__main__", "message": "Processing file", "file_id": "ABC-123", "correlation_id": "999"}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### 5. Perceptual Image Hashing (Optional)
|
|
142
|
+
|
|
143
|
+
Detect visually similar images, compression artifacts, and resized duplicates using Hamming distance.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from filedgr_pkg_utils.images.hashing import PHashAlgorithm, ImageHashUtils
|
|
147
|
+
|
|
148
|
+
utils = ImageHashUtils(PHashAlgorithm())
|
|
149
|
+
|
|
150
|
+
hash_orig = utils.hash_image("original.png")
|
|
151
|
+
hash_comp = utils.hash_image("compressed_artifact.jpg")
|
|
152
|
+
|
|
153
|
+
if utils.is_similar(hash_orig, hash_comp, max_distance=5):
|
|
154
|
+
print("These images are visually similar!")
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## 🛠️ Development & Testing
|
|
158
|
+
|
|
159
|
+
This project enforces high coverage and clean coding standards.
|
|
160
|
+
|
|
161
|
+
To run the test suite with coverage:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
make test-coverage
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
To run the linter:
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
make lint
|
|
171
|
+
```
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
filedgr_pkg_utils/__init__.py,sha256=jhHEJFZWhkQDemoZMomBYq-RNrKXknYzUaeIU9A6XsI,22
|
|
2
|
+
filedgr_pkg_utils/caching/__init__.py,sha256=KdqX8zeV-AiON51H4GIgPXIK3qzEwladJRERMWxR9pc,31
|
|
3
|
+
filedgr_pkg_utils/caching/memoize.py,sha256=ecFlgg-mk6Kd8W9MigH38k13AHDBTDx5Cj0sqOsHFHc,1819
|
|
4
|
+
filedgr_pkg_utils/canonicalization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
filedgr_pkg_utils/canonicalization/canonical_json_mixin.py,sha256=4NILt3U0xM7ABNH6IV25YVmA8IU4F8Gsxq0c_yUnMhA,1066
|
|
6
|
+
filedgr_pkg_utils/compression/__init__.py,sha256=0IwAZAXbbAGJ5gCtp47dzObhVVu58YxkKY-3CrXf6tw,367
|
|
7
|
+
filedgr_pkg_utils/compression/compression_algorithm.py,sha256=oLBY8fKJO53Kd1Wf4mOdNFQJSSGCn4kXO7WjmSEaBJM,570
|
|
8
|
+
filedgr_pkg_utils/compression/compression_utils.py,sha256=rI40lOT9oG5-ryQsEYx2A9Vt4qSaRcycmtoDjooJht4,1609
|
|
9
|
+
filedgr_pkg_utils/compression/algorithms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
filedgr_pkg_utils/compression/algorithms/compression_algorithm_brotli.py,sha256=MYsZVBOs0DIw8cVfPsRCb3EEZV0W2nMtWb-kASdDoRU,1169
|
|
11
|
+
filedgr_pkg_utils/compression/algorithms/compression_algorithm_zip.py,sha256=Z5TlhlDtKg4x9-RCwJwcGcSgIFowxI5bvpASNlV222Y,1670
|
|
12
|
+
filedgr_pkg_utils/compression/algorithms/compression_algorithm_zstd.py,sha256=N9vJDmO6e0aliGgGs2jqrEqQThPkah1h5kfau2JUY9o,1301
|
|
13
|
+
filedgr_pkg_utils/compression/algorithms/compression_algortihm_gzip.py,sha256=2rplDmWOKSG5_mzhvAR2P4pR_OhPygD3lPlT1cIfS8c,1244
|
|
14
|
+
filedgr_pkg_utils/converters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
+
filedgr_pkg_utils/converters/abstract_converter.py,sha256=EJVMSUE5__n1o6L8mDb7LHZ_Z7_ndghdzAWRJvxtQj0,476
|
|
16
|
+
filedgr_pkg_utils/cryptography/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
filedgr_pkg_utils/cryptography/hashing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
filedgr_pkg_utils/cryptography/hashing/conversion_utils.py,sha256=Uml7URc4lO07aI3PAKFzMv_WODCXgg1YUgbqvTtnxCU,150
|
|
19
|
+
filedgr_pkg_utils/cryptography/hashing/hash_algorithm.py,sha256=qkhWzoQlvffWN0iZsRu1nC_np7tpPY5uqXSZwPV2ddI,3117
|
|
20
|
+
filedgr_pkg_utils/cryptography/hashing/hash_utils.py,sha256=n_568_b32y6l3yM8sHn1r2XDnas1AZ2Nkmr5bzOr4pI,786
|
|
21
|
+
filedgr_pkg_utils/cryptography/signing/__init__.py,sha256=Q1ubv-ZiSLFVs0O7a_-B08Mqjc59qIqFWozFBWIgQOo,324
|
|
22
|
+
filedgr_pkg_utils/cryptography/signing/conversion_utils.py,sha256=VAMtTc7eFP_aYV2c5JIqE-Wc5LzEDsT9yVoE6NLJ1-k,812
|
|
23
|
+
filedgr_pkg_utils/cryptography/signing/hmac_signature_algorithm.py,sha256=8_jnu1QEA0NZNQqYmjj54E-xSy12u8sxpWR2MnmciS4,415
|
|
24
|
+
filedgr_pkg_utils/cryptography/signing/secp256k1_evm_signature_algorithm.py,sha256=z5ws-2c0Bqt9sZhccMlocJR7cp_gNP5-z55s9hdTEgg,720
|
|
25
|
+
filedgr_pkg_utils/cryptography/signing/secp256k1_signature_algorithm.py,sha256=z4IBKJ4mpmz3lUWjfIfO7e2A-UxSypTnUkCB2aOmy64,1773
|
|
26
|
+
filedgr_pkg_utils/cryptography/signing/signature_algorithm.py,sha256=PHgNqZWu24UaTqwwsxUAGbjR8MKedQx38dNScNoVtro,199
|
|
27
|
+
filedgr_pkg_utils/cryptography/signing/signature_utils.py,sha256=AwOd0EXkwG051cmC5_AAZ8aXgnZ2KF4GOU85ZPjojn0,1004
|
|
28
|
+
filedgr_pkg_utils/evm/__init__.py,sha256=P6us57_I-CRqXwjC7TRO6lESppNFprZXQHjm1kew06A,239
|
|
29
|
+
filedgr_pkg_utils/evm/hex_utils.py,sha256=xngN8_Tk1XPqDbb7U1pRpxyq_qOVXdKvOYZdEo7X3eg,2978
|
|
30
|
+
filedgr_pkg_utils/filesystem/__init__.py,sha256=irc_lUJtuW3qdFPo2xrM9JEnx3l7lE4wqBDLDPFBJzg,32
|
|
31
|
+
filedgr_pkg_utils/filesystem/atomic.py,sha256=lrwrosAjLKzcM_mD1iqVtc3L8KO5UtLWInfaVBgeHHw,4080
|
|
32
|
+
filedgr_pkg_utils/filesystem/tar_utils.py,sha256=lsK8SGWdkNFCswfxanZxbKu-nHTqMsPprXbGola_Ke4,2134
|
|
33
|
+
filedgr_pkg_utils/fldgr_logging/__init__.py,sha256=I2uaELVWbqBtxCchmpgp0vQDKIvDGXoGFdwaWqjcvFU,60
|
|
34
|
+
filedgr_pkg_utils/fldgr_logging/sanitizer_logger_adapter.py,sha256=Otj45j8Nslj5patmh4JF7I7AuY4dq0z6GjT0I1LKaNU,916
|
|
35
|
+
filedgr_pkg_utils/fldgr_logging/structured_logger.py,sha256=Y_XMzRhH4i-gu1_YKVZhOvseKP0nD9bSP0gj5vwn2-Y,3167
|
|
36
|
+
filedgr_pkg_utils/hooks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
37
|
+
filedgr_pkg_utils/hooks/decorators.py,sha256=Ym0yAJh1WB269hRkdu4k5iKoYwDu4bRCW30uK1uiysk,8826
|
|
38
|
+
filedgr_pkg_utils/images/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
39
|
+
filedgr_pkg_utils/images/hashing/__init__.py,sha256=C8XV4GgdVejCW62S9lrW0BpwYhtuy2XNdm8TEt_R8fA,306
|
|
40
|
+
filedgr_pkg_utils/images/hashing/image_hash_algorithm.py,sha256=B0Y1nrIb0lj5PU4C2Ekq3BiCKmp7Rv32nEQXwIjBQB4,406
|
|
41
|
+
filedgr_pkg_utils/images/hashing/image_hash_utils.py,sha256=fqToW12TSz1DL6tjnDWwKOmG1W_KKX8wv2izDm6gIZM,1203
|
|
42
|
+
filedgr_pkg_utils/images/hashing/algorithms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
43
|
+
filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_ahash.py,sha256=ai-S1tiN2qTIh4JgWuQBJmFVzpnoxAWMwG2gFWVU12g,988
|
|
44
|
+
filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_dhash.py,sha256=oBuVr8hqboVk3i7S3_D50qwtDekS4642QjS4wRzeIos,975
|
|
45
|
+
filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_phash.py,sha256=NM036sbAr5jGpkgIsfNQ3aQAZ0uGHQfMvJWRk3oyHYk,1009
|
|
46
|
+
filedgr_pkg_utils/mixins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
47
|
+
filedgr_pkg_utils/mixins/without_keys_mixin.py,sha256=2rFjSgR4ZvAjRj-xknJk18XsnHc8QMMEcMCwJLSXHb8,205
|
|
48
|
+
filedgr_pkg_utils/resilience/__init__.py,sha256=ZvtrRiSgnLirOAjuyn4xsmyuOPDAat9VQ_nDrb_W3fI,170
|
|
49
|
+
filedgr_pkg_utils/resilience/decorators.py,sha256=MQNEVM2ujv6Nqz30d_9T_I9RTnJvTetsBHOOFika2cQ,6629
|
|
50
|
+
filedgr_pkg_utils/security/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
51
|
+
filedgr_pkg_utils/security/sanitizer.py,sha256=ipgftgP4gDPhsET9W2dj8OWPQGmHSUiFdU0ozdQNNFU,1954
|
|
52
|
+
filedgr_pkg_utils/security/sanitizer_decorators.py,sha256=-yVsuG4h4FW9D6wbcJpTV7mewloWQUU9iZjmZ2RA8xU,1060
|
|
53
|
+
filedgr_pkg_utils-0.8.4.dist-info/METADATA,sha256=9fKGeuToexlBGJQgUQa_3AquRggJLHgQZSD_IYq7cv8,5817
|
|
54
|
+
filedgr_pkg_utils-0.8.4.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
55
|
+
filedgr_pkg_utils-0.8.4.dist-info/top_level.txt,sha256=-YM0mdOYG8vF0vKrNhTfuO_91upEGzjU3n93S0VeTuM,18
|
|
56
|
+
filedgr_pkg_utils-0.8.4.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
filedgr_pkg_utils
|