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,81 @@
|
|
|
1
|
+
"""Hex-string normalization helpers for EVM logs / topics / data fields.
|
|
2
|
+
|
|
3
|
+
web3.py returns topic / data / address values as a mix of native ``bytes``,
|
|
4
|
+
``HexBytes``, and 0x-prefixed strings depending on the call path and the
|
|
5
|
+
provider. Downstream code that compares these against ABI-derived topic0
|
|
6
|
+
values or stores them in DynamoDB consistently needs a normalized form:
|
|
7
|
+
lowercase, 0x-prefixed hex.
|
|
8
|
+
|
|
9
|
+
These helpers do exactly that — nothing more. No web3 dependency; only
|
|
10
|
+
duck-typing on ``.hex()`` for objects that quack like ``HexBytes``.
|
|
11
|
+
"""
|
|
12
|
+
# Standard library imports
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_hex(value: Any) -> Optional[str]:
|
|
17
|
+
"""Coerce ``value`` to a lowercase 0x-prefixed hex string.
|
|
18
|
+
|
|
19
|
+
Accepts:
|
|
20
|
+
* ``None`` → returns ``None``
|
|
21
|
+
* ``str`` (with or without ``0x`` prefix) → returns lowercase 0x-prefixed
|
|
22
|
+
* ``bytes`` / ``bytearray`` → ``"0x" + value.hex().lower()``
|
|
23
|
+
* Anything with a ``.hex()`` method (e.g. web3's ``HexBytes``) → uses it
|
|
24
|
+
* Falls back to ``str(value).lower()`` for the rare degenerate case
|
|
25
|
+
"""
|
|
26
|
+
if value is None:
|
|
27
|
+
return None
|
|
28
|
+
if isinstance(value, str):
|
|
29
|
+
s = value.lower()
|
|
30
|
+
elif isinstance(value, (bytes, bytearray)):
|
|
31
|
+
s = "0x" + value.hex().lower()
|
|
32
|
+
else:
|
|
33
|
+
try:
|
|
34
|
+
s = value.hex().lower()
|
|
35
|
+
except AttributeError:
|
|
36
|
+
s = str(value).lower()
|
|
37
|
+
if not s.startswith("0x"):
|
|
38
|
+
s = "0x" + s
|
|
39
|
+
return s
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def normalize_topic(topic: Any) -> str:
|
|
43
|
+
"""Same as :func:`normalize_hex` but never returns ``None``.
|
|
44
|
+
|
|
45
|
+
Topic0 + indexed topics are always present in a valid EVM log; treating
|
|
46
|
+
them as ``None``-able would mask a producer bug. Callers that legitimately
|
|
47
|
+
need an optional form should use :func:`normalize_hex` directly.
|
|
48
|
+
"""
|
|
49
|
+
out = normalize_hex(topic)
|
|
50
|
+
if out is None:
|
|
51
|
+
raise ValueError("topic value cannot be None")
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def normalize_log(log_entry: Any) -> Dict[str, Any]:
|
|
56
|
+
"""Project an arbitrary web3 log object into a plain JSON-safe dict.
|
|
57
|
+
|
|
58
|
+
Returned shape::
|
|
59
|
+
|
|
60
|
+
{
|
|
61
|
+
"address": "0x..." | None,
|
|
62
|
+
"topics": ["0x...", ...],
|
|
63
|
+
"data": "0x..." | None,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
Useful as the input to ABI decoders that operate on plain dicts.
|
|
67
|
+
"""
|
|
68
|
+
if hasattr(log_entry, "get"):
|
|
69
|
+
topics_raw: List[Any] = list(log_entry.get("topics", []) or [])
|
|
70
|
+
return {
|
|
71
|
+
"address": normalize_hex(log_entry.get("address")),
|
|
72
|
+
"topics": [normalize_topic(t) for t in topics_raw],
|
|
73
|
+
"data": normalize_hex(log_entry.get("data")) or "0x",
|
|
74
|
+
}
|
|
75
|
+
# AttributeDict-style fallback: getattr-only access.
|
|
76
|
+
topics_attr: List[Any] = list(getattr(log_entry, "topics", []) or [])
|
|
77
|
+
return {
|
|
78
|
+
"address": normalize_hex(getattr(log_entry, "address", None)),
|
|
79
|
+
"topics": [normalize_topic(t) for t in topics_attr],
|
|
80
|
+
"data": normalize_hex(getattr(log_entry, "data", None)) or "0x",
|
|
81
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .tar_utils import TarUtils
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import asyncio
|
|
3
|
+
import tempfile
|
|
4
|
+
from contextlib import contextmanager, asynccontextmanager
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Generator, AsyncGenerator, Union, IO, Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@contextmanager
|
|
10
|
+
def atomic_write(
|
|
11
|
+
file_path: Union[str, Path], mode: str = "w", encoding: str = "utf-8", **kwargs
|
|
12
|
+
) -> Generator[IO[Any], None, None]:
|
|
13
|
+
"""
|
|
14
|
+
Context manager for atomic file writes.
|
|
15
|
+
Prevents partial file writes in case of application crashes or power failures.
|
|
16
|
+
|
|
17
|
+
:param file_path: The target file path.
|
|
18
|
+
:param mode: 'w' for text, 'wb' for binary.
|
|
19
|
+
:param encoding: Default is 'utf-8'. Ignored if mode is binary.
|
|
20
|
+
"""
|
|
21
|
+
path = Path(file_path)
|
|
22
|
+
|
|
23
|
+
# Ensure the target directory exists
|
|
24
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
|
|
26
|
+
# 1. Create a temp file in the SAME directory.
|
|
27
|
+
# This is critical! If the temp file is on a different hard drive or mount point,
|
|
28
|
+
# os.replace will not be atomic.
|
|
29
|
+
fd, temp_path_str = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".tmp-")
|
|
30
|
+
temp_path = Path(temp_path_str)
|
|
31
|
+
|
|
32
|
+
# Prepare open() arguments based on binary vs text mode
|
|
33
|
+
open_kwargs = kwargs.copy()
|
|
34
|
+
if "b" not in mode:
|
|
35
|
+
open_kwargs["encoding"] = encoding
|
|
36
|
+
|
|
37
|
+
f = open(fd, mode, **open_kwargs)
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
# 2. Yield the file object back to the developer to write their data
|
|
41
|
+
yield f
|
|
42
|
+
|
|
43
|
+
# 3. Ensure Python's internal buffers are flushed to the OS
|
|
44
|
+
f.flush()
|
|
45
|
+
|
|
46
|
+
# 4. Ensure the OS flushes its buffers to the physical disk platter
|
|
47
|
+
os.fsync(f.fileno())
|
|
48
|
+
|
|
49
|
+
except Exception:
|
|
50
|
+
# If the developer's code crashes while writing, close and delete the temp file.
|
|
51
|
+
# The original target file remains 100% untouched and uncorrupted!
|
|
52
|
+
f.close()
|
|
53
|
+
if temp_path.exists():
|
|
54
|
+
temp_path.unlink()
|
|
55
|
+
raise
|
|
56
|
+
|
|
57
|
+
else:
|
|
58
|
+
# 5. Close the file and perform the atomic pointer swap
|
|
59
|
+
f.close()
|
|
60
|
+
os.replace(temp_path, path)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# We import aiofiles inside a try/except so the library doesn't crash
|
|
64
|
+
# if a developer is only using the synchronous parts and didn't install it.
|
|
65
|
+
try:
|
|
66
|
+
import aiofiles
|
|
67
|
+
from aiofiles.threadpool.text import AsyncTextIOWrapper
|
|
68
|
+
from aiofiles.threadpool.binary import AsyncBufferedIOBase
|
|
69
|
+
|
|
70
|
+
AIOFILES_AVAILABLE = True
|
|
71
|
+
except ImportError:
|
|
72
|
+
AIOFILES_AVAILABLE = False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@asynccontextmanager
|
|
76
|
+
async def async_atomic_write(
|
|
77
|
+
file_path: Union[str, Path],
|
|
78
|
+
mode: str = "w",
|
|
79
|
+
encoding: str = "utf-8",
|
|
80
|
+
**kwargs
|
|
81
|
+
) -> AsyncGenerator[Union['AsyncTextIOWrapper', 'AsyncBufferedIOBase', Any], None]:
|
|
82
|
+
"""
|
|
83
|
+
Async context manager for atomic file writes.
|
|
84
|
+
Prevents event loop blocking and partial file writes.
|
|
85
|
+
"""
|
|
86
|
+
if not AIOFILES_AVAILABLE:
|
|
87
|
+
raise ImportError("The 'aiofiles' package is required to use async_atomic_write. Run: pip install aiofiles")
|
|
88
|
+
|
|
89
|
+
path = Path(file_path)
|
|
90
|
+
|
|
91
|
+
# 1. Offload directory creation to a thread to prevent blocking
|
|
92
|
+
await asyncio.to_thread(path.parent.mkdir, parents=True, exist_ok=True)
|
|
93
|
+
|
|
94
|
+
# 2. mkstemp interacts with the OS and blocks, so we thread it
|
|
95
|
+
def _create_temp():
|
|
96
|
+
return tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".tmp-")
|
|
97
|
+
|
|
98
|
+
fd, temp_path_str = await asyncio.to_thread(_create_temp)
|
|
99
|
+
temp_path = Path(temp_path_str)
|
|
100
|
+
|
|
101
|
+
open_kwargs = kwargs.copy()
|
|
102
|
+
if "b" not in mode:
|
|
103
|
+
open_kwargs["encoding"] = encoding
|
|
104
|
+
|
|
105
|
+
# 3. Yield the async file object
|
|
106
|
+
try:
|
|
107
|
+
async with aiofiles.open(fd, mode=mode, **open_kwargs) as f:
|
|
108
|
+
yield f
|
|
109
|
+
|
|
110
|
+
# Flush aiofiles buffer
|
|
111
|
+
await f.flush()
|
|
112
|
+
|
|
113
|
+
# fsync physically flushes to the disk platter (highly blocking!)
|
|
114
|
+
await asyncio.to_thread(os.fsync, fd)
|
|
115
|
+
|
|
116
|
+
except Exception:
|
|
117
|
+
# Cleanup temp file on failure
|
|
118
|
+
if await asyncio.to_thread(temp_path.exists):
|
|
119
|
+
await asyncio.to_thread(temp_path.unlink)
|
|
120
|
+
raise
|
|
121
|
+
|
|
122
|
+
else:
|
|
123
|
+
# 4. Atomic pointer swap (blocking OS call, offloaded to thread)
|
|
124
|
+
await asyncio.to_thread(os.replace, temp_path, path)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tarfile
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class TarUtils:
|
|
6
|
+
|
|
7
|
+
@staticmethod
|
|
8
|
+
def create_tarball(source_path: str, dest_path: str, compression: str = "gz") -> None:
|
|
9
|
+
"""
|
|
10
|
+
Creates a tarball from a file or directory.
|
|
11
|
+
|
|
12
|
+
:param source_path: Path to the file or directory to archive.
|
|
13
|
+
:param dest_path: Path where the tarball will be saved.
|
|
14
|
+
:param compression: Compression type: 'gz' (default for .tar.gz), 'bz2', 'xz',
|
|
15
|
+
or '' (empty string for an uncompressed .tar).
|
|
16
|
+
"""
|
|
17
|
+
if not os.path.exists(source_path):
|
|
18
|
+
raise FileNotFoundError(f"Source path not found: {source_path}")
|
|
19
|
+
|
|
20
|
+
# Construct the mode string (e.g., 'w:gz' or 'w')
|
|
21
|
+
mode = f"w:{compression}" if compression else "w"
|
|
22
|
+
|
|
23
|
+
with tarfile.open(dest_path, mode) as tar:
|
|
24
|
+
# Using os.path.basename for arcname ensures we don't store absolute
|
|
25
|
+
# paths in the archive, which makes extraction much cleaner.
|
|
26
|
+
tar.add(source_path, arcname=os.path.basename(source_path))
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def extract_tarball(archive_path: str, dest_path: str) -> None:
|
|
30
|
+
"""
|
|
31
|
+
Extracts a tarball to a specified directory.
|
|
32
|
+
|
|
33
|
+
:param archive_path: Path to the tar archive.
|
|
34
|
+
:param dest_path: Directory where the contents will be extracted.
|
|
35
|
+
"""
|
|
36
|
+
if not os.path.isfile(archive_path):
|
|
37
|
+
raise FileNotFoundError(f"Archive file not found: {archive_path}")
|
|
38
|
+
|
|
39
|
+
# Ensure the destination directory exists
|
|
40
|
+
os.makedirs(dest_path, exist_ok=True)
|
|
41
|
+
|
|
42
|
+
# 'r:*' tells tarfile to automatically determine the compression method
|
|
43
|
+
# (uncompressed, gzip, bzip2, or xz) by inspecting the file headers.
|
|
44
|
+
with tarfile.open(archive_path, "r:*") as tar:
|
|
45
|
+
# Note: In Python 3.12+, a 'filter' argument was added for extraction security.
|
|
46
|
+
# Since your pyproject.toml specifies Python >= 3.11, we use the standard extractall.
|
|
47
|
+
if hasattr(tarfile, 'data_filter'):
|
|
48
|
+
tar.extractall(path=dest_path, filter='data')
|
|
49
|
+
else:
|
|
50
|
+
tar.extractall(path=dest_path)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .structured_logger import LoggerFactory, JsonFormatter
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, MutableMapping, Tuple
|
|
3
|
+
from filedgr_pkg_utils.security.sanitizer import sanitize_data
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SanitizerLoggerAdapter(logging.LoggerAdapter):
|
|
7
|
+
"""
|
|
8
|
+
A LoggerAdapter that automatically intercepts the 'extra' dictionary
|
|
9
|
+
and sanitizes any PII or sensitive keys before the log is formatted and emitted.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]:
|
|
13
|
+
# Check if the developer passed an 'extra' dictionary
|
|
14
|
+
if 'extra' in kwargs and isinstance(kwargs['extra'], dict):
|
|
15
|
+
# Run the entire 'extra' dictionary through our PII sanitizer
|
|
16
|
+
kwargs['extra'] = sanitize_data(kwargs['extra'])
|
|
17
|
+
|
|
18
|
+
# You could also sanitize the main message here if it happens to be a dictionary!
|
|
19
|
+
if isinstance(msg, dict):
|
|
20
|
+
msg = sanitize_data(msg)
|
|
21
|
+
|
|
22
|
+
return msg, kwargs
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
from filedgr_pkg_utils.fldgr_logging.sanitizer_logger_adapter import SanitizerLoggerAdapter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class JsonFormatter(logging.Formatter):
|
|
11
|
+
"""
|
|
12
|
+
Formats standard Python log records into a deterministic JSON structure.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
16
|
+
log_obj = {
|
|
17
|
+
"timestamp": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat() + "Z",
|
|
18
|
+
"level": record.levelname,
|
|
19
|
+
"logger": record.name,
|
|
20
|
+
"message": record.getMessage(),
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
# Inject any extra contextual data passed to the logger
|
|
24
|
+
# e.g., logger.info("User logged in", extra={"user_id": "123"})
|
|
25
|
+
for key, value in record.__dict__.items():
|
|
26
|
+
if key not in ["args", "asctime", "created", "exc_info", "exc_text", "filename",
|
|
27
|
+
"funcName", "levelname", "levelno", "lineno", "module",
|
|
28
|
+
"msecs", "message", "msg", "name", "pathname", "process",
|
|
29
|
+
"processName", "relativeCreated", "stack_info", "thread", "threadName"]:
|
|
30
|
+
log_obj[key] = value
|
|
31
|
+
|
|
32
|
+
# Handle Exception traces safely
|
|
33
|
+
if record.exc_info:
|
|
34
|
+
log_obj["exception"] = self.formatException(record.exc_info)
|
|
35
|
+
|
|
36
|
+
return json.dumps(log_obj)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class LoggerFactory:
|
|
40
|
+
@staticmethod
|
|
41
|
+
def get_logger(
|
|
42
|
+
name: str,
|
|
43
|
+
sanitize_pii: Union[bool, None] = None
|
|
44
|
+
) -> Union[logging.Logger, logging.LoggerAdapter]:
|
|
45
|
+
"""
|
|
46
|
+
Creates and configures a logger for the application.
|
|
47
|
+
|
|
48
|
+
:param name: The name of the logger (usually __name__).
|
|
49
|
+
:param sanitize_pii: If True, wraps the logger in a PII Sanitizer.
|
|
50
|
+
If None, defaults to the 'FILEDGR_SANITIZE_LOGS' env variable (default: True).
|
|
51
|
+
"""
|
|
52
|
+
# 1. Determine if we should sanitize based on param or environment variable
|
|
53
|
+
if sanitize_pii is None:
|
|
54
|
+
# Default to True for safety, unless explicitly disabled in the environment
|
|
55
|
+
env_sanitize = os.getenv("FILEDGR_SANITIZE_LOGS", "true").lower()
|
|
56
|
+
should_sanitize = env_sanitize in ("true", "1", "yes")
|
|
57
|
+
else:
|
|
58
|
+
should_sanitize = sanitize_pii
|
|
59
|
+
|
|
60
|
+
# 2. Get the base logger
|
|
61
|
+
base_logger = logging.getLogger(name)
|
|
62
|
+
|
|
63
|
+
# Configure handlers, formatters, and log levels if not already set up
|
|
64
|
+
if not base_logger.handlers:
|
|
65
|
+
handler = logging.StreamHandler()
|
|
66
|
+
# (Assuming you attach your custom JSON formatter here)
|
|
67
|
+
# formatter = JsonFormatter()
|
|
68
|
+
# handler.setFormatter(formatter)
|
|
69
|
+
base_logger.addHandler(handler)
|
|
70
|
+
base_logger.setLevel(logging.INFO)
|
|
71
|
+
|
|
72
|
+
# 3. Return the Secure Adapter or the raw Base Logger
|
|
73
|
+
if should_sanitize:
|
|
74
|
+
# Secure mode: Intercepts and masks sensitive data
|
|
75
|
+
return SanitizerLoggerAdapter(base_logger, extra={})
|
|
76
|
+
else:
|
|
77
|
+
# Raw mode: Highly dangerous for production, great for local debugging
|
|
78
|
+
return base_logger
|
|
File without changes
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import time
|
|
3
|
+
import asyncio
|
|
4
|
+
import threading
|
|
5
|
+
from functools import wraps
|
|
6
|
+
from typing import Callable, Any, Optional, Tuple, Type
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def post_action(
|
|
10
|
+
callback: Callable[..., Any],
|
|
11
|
+
condition: Optional[Callable[..., bool]] = None
|
|
12
|
+
):
|
|
13
|
+
"""
|
|
14
|
+
Executes a callback action after the decorated function returns.
|
|
15
|
+
Seamlessly supports both synchronous and asynchronous functions.
|
|
16
|
+
|
|
17
|
+
:param callback: The function to execute after the main function. (Can be sync or async)
|
|
18
|
+
:param condition: An optional synchronous function that evaluates the result and inputs.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def decorator(func: Callable) -> Callable:
|
|
22
|
+
|
|
23
|
+
if inspect.iscoroutinefunction(func):
|
|
24
|
+
@wraps(func)
|
|
25
|
+
async def async_wrapper(*args, **kwargs):
|
|
26
|
+
# Await the actual result of the coroutine
|
|
27
|
+
result = await func(*args, **kwargs)
|
|
28
|
+
|
|
29
|
+
if condition is None or condition(result, *args, **kwargs):
|
|
30
|
+
if inspect.iscoroutinefunction(callback):
|
|
31
|
+
await callback(result, *args, **kwargs)
|
|
32
|
+
else:
|
|
33
|
+
# Plain callable: could be sync, or a sync wrapper (e.g., lambda)
|
|
34
|
+
# that returns a coroutine. If we get a coroutine back, await it
|
|
35
|
+
# so async side effects actually run.
|
|
36
|
+
maybe_coro = callback(result, *args, **kwargs)
|
|
37
|
+
if inspect.iscoroutine(maybe_coro):
|
|
38
|
+
await maybe_coro
|
|
39
|
+
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
return async_wrapper
|
|
43
|
+
|
|
44
|
+
else:
|
|
45
|
+
@wraps(func)
|
|
46
|
+
def sync_wrapper(*args, **kwargs):
|
|
47
|
+
result = func(*args, **kwargs)
|
|
48
|
+
|
|
49
|
+
if condition is None or condition(result, *args, **kwargs):
|
|
50
|
+
if inspect.iscoroutinefunction(callback):
|
|
51
|
+
raise RuntimeError("Cannot use an async callback with a synchronous function.")
|
|
52
|
+
callback(result, *args, **kwargs)
|
|
53
|
+
|
|
54
|
+
return result
|
|
55
|
+
|
|
56
|
+
return sync_wrapper
|
|
57
|
+
|
|
58
|
+
return decorator
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pre_action(callback: Callable[..., Any]):
|
|
62
|
+
"""
|
|
63
|
+
Executes a callback action before the decorated function runs.
|
|
64
|
+
The callback receives the exact *args and **kwargs the main function will receive.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def decorator(func: Callable) -> Callable:
|
|
68
|
+
if inspect.iscoroutinefunction(func):
|
|
69
|
+
@wraps(func)
|
|
70
|
+
async def async_wrapper(*args, **kwargs):
|
|
71
|
+
if inspect.iscoroutinefunction(callback):
|
|
72
|
+
await callback(*args, **kwargs)
|
|
73
|
+
else:
|
|
74
|
+
callback(*args, **kwargs)
|
|
75
|
+
return await func(*args, **kwargs)
|
|
76
|
+
|
|
77
|
+
return async_wrapper
|
|
78
|
+
else:
|
|
79
|
+
@wraps(func)
|
|
80
|
+
def sync_wrapper(*args, **kwargs):
|
|
81
|
+
if inspect.iscoroutinefunction(callback):
|
|
82
|
+
raise RuntimeError("Cannot use an async callback with a sync function.")
|
|
83
|
+
callback(*args, **kwargs)
|
|
84
|
+
return func(*args, **kwargs)
|
|
85
|
+
|
|
86
|
+
return sync_wrapper
|
|
87
|
+
|
|
88
|
+
return decorator
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def on_failure(callback: Callable[..., Any], exceptions: Tuple[Type[Exception], ...] = (Exception,)):
|
|
92
|
+
"""
|
|
93
|
+
Executes a callback if the main function raises specific exceptions.
|
|
94
|
+
The callback receives (exception_instance, *args, **kwargs).
|
|
95
|
+
The exception is re-raised after the callback finishes.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def decorator(func: Callable) -> Callable:
|
|
99
|
+
if inspect.iscoroutinefunction(func):
|
|
100
|
+
@wraps(func)
|
|
101
|
+
async def async_wrapper(*args, **kwargs):
|
|
102
|
+
try:
|
|
103
|
+
return await func(*args, **kwargs)
|
|
104
|
+
except exceptions as e:
|
|
105
|
+
if inspect.iscoroutinefunction(callback):
|
|
106
|
+
await callback(e, *args, **kwargs)
|
|
107
|
+
else:
|
|
108
|
+
callback(e, *args, **kwargs)
|
|
109
|
+
raise e
|
|
110
|
+
|
|
111
|
+
return async_wrapper
|
|
112
|
+
else:
|
|
113
|
+
@wraps(func)
|
|
114
|
+
def sync_wrapper(*args, **kwargs):
|
|
115
|
+
try:
|
|
116
|
+
return func(*args, **kwargs)
|
|
117
|
+
except exceptions as e:
|
|
118
|
+
if inspect.iscoroutinefunction(callback):
|
|
119
|
+
raise RuntimeError("Cannot use an async callback with a sync function.")
|
|
120
|
+
callback(e, *args, **kwargs)
|
|
121
|
+
raise e
|
|
122
|
+
|
|
123
|
+
return sync_wrapper
|
|
124
|
+
|
|
125
|
+
return decorator
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def measure_time(callback: Callable[..., Any]):
|
|
129
|
+
"""
|
|
130
|
+
Measures the execution time of the main function in milliseconds.
|
|
131
|
+
The callback receives (execution_time_ms, result, *args, **kwargs).
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def decorator(func: Callable) -> Callable:
|
|
135
|
+
if inspect.iscoroutinefunction(func):
|
|
136
|
+
@wraps(func)
|
|
137
|
+
async def async_wrapper(*args, **kwargs):
|
|
138
|
+
start = time.perf_counter()
|
|
139
|
+
result = await func(*args, **kwargs)
|
|
140
|
+
duration_ms = (time.perf_counter() - start) * 1000
|
|
141
|
+
|
|
142
|
+
if inspect.iscoroutinefunction(callback):
|
|
143
|
+
await callback(duration_ms, result, *args, **kwargs)
|
|
144
|
+
else:
|
|
145
|
+
callback(duration_ms, result, *args, **kwargs)
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
return async_wrapper
|
|
149
|
+
else:
|
|
150
|
+
@wraps(func)
|
|
151
|
+
def sync_wrapper(*args, **kwargs):
|
|
152
|
+
start = time.perf_counter()
|
|
153
|
+
result = func(*args, **kwargs)
|
|
154
|
+
duration_ms = (time.perf_counter() - start) * 1000
|
|
155
|
+
|
|
156
|
+
if inspect.iscoroutinefunction(callback):
|
|
157
|
+
raise RuntimeError("Cannot use an async callback with a sync function.")
|
|
158
|
+
callback(duration_ms, result, *args, **kwargs)
|
|
159
|
+
return result
|
|
160
|
+
|
|
161
|
+
return sync_wrapper
|
|
162
|
+
|
|
163
|
+
return decorator
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def fire_and_forget(func: Callable) -> Callable:
|
|
167
|
+
"""
|
|
168
|
+
Runs the function in the background.
|
|
169
|
+
Returns None immediately, unblocking the caller.
|
|
170
|
+
"""
|
|
171
|
+
if inspect.iscoroutinefunction(func):
|
|
172
|
+
@wraps(func)
|
|
173
|
+
async def async_wrapper(*args, **kwargs):
|
|
174
|
+
# Schedules the coroutine to run on the event loop
|
|
175
|
+
asyncio.create_task(func(*args, **kwargs))
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
return async_wrapper
|
|
179
|
+
else:
|
|
180
|
+
@wraps(func)
|
|
181
|
+
def sync_wrapper(*args, **kwargs):
|
|
182
|
+
# Spawns a background thread for the sync function
|
|
183
|
+
t = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
|
|
184
|
+
t.start()
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
return sync_wrapper
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def transform_input(transformer: Callable[..., Tuple[Tuple, dict]]):
|
|
191
|
+
"""
|
|
192
|
+
Modifies the inputs before they reach the main function.
|
|
193
|
+
The transformer must return (new_args_tuple, new_kwargs_dict).
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def decorator(func: Callable) -> Callable:
|
|
197
|
+
if inspect.iscoroutinefunction(func):
|
|
198
|
+
@wraps(func)
|
|
199
|
+
async def async_wrapper(*args, **kwargs):
|
|
200
|
+
if inspect.iscoroutinefunction(transformer):
|
|
201
|
+
new_args, new_kwargs = await transformer(*args, **kwargs)
|
|
202
|
+
else:
|
|
203
|
+
new_args, new_kwargs = transformer(*args, **kwargs)
|
|
204
|
+
return await func(*new_args, **new_kwargs)
|
|
205
|
+
|
|
206
|
+
return async_wrapper
|
|
207
|
+
else:
|
|
208
|
+
@wraps(func)
|
|
209
|
+
def sync_wrapper(*args, **kwargs):
|
|
210
|
+
if inspect.iscoroutinefunction(transformer):
|
|
211
|
+
raise RuntimeError("Cannot use an async transformer with a sync function.")
|
|
212
|
+
new_args, new_kwargs = transformer(*args, **kwargs)
|
|
213
|
+
return func(*new_args, **new_kwargs)
|
|
214
|
+
|
|
215
|
+
return sync_wrapper
|
|
216
|
+
|
|
217
|
+
return decorator
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def transform_output(transformer: Callable[..., Any]):
|
|
221
|
+
"""
|
|
222
|
+
Modifies the return value of the main function.
|
|
223
|
+
The transformer receives (original_result, *args, **kwargs) and returns the new result.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
def decorator(func: Callable) -> Callable:
|
|
227
|
+
if inspect.iscoroutinefunction(func):
|
|
228
|
+
@wraps(func)
|
|
229
|
+
async def async_wrapper(*args, **kwargs):
|
|
230
|
+
result = await func(*args, **kwargs)
|
|
231
|
+
if inspect.iscoroutinefunction(transformer):
|
|
232
|
+
return await transformer(result, *args, **kwargs)
|
|
233
|
+
return transformer(result, *args, **kwargs)
|
|
234
|
+
|
|
235
|
+
return async_wrapper
|
|
236
|
+
else:
|
|
237
|
+
@wraps(func)
|
|
238
|
+
def sync_wrapper(*args, **kwargs):
|
|
239
|
+
result = func(*args, **kwargs)
|
|
240
|
+
if inspect.iscoroutinefunction(transformer):
|
|
241
|
+
raise RuntimeError("Cannot use an async transformer with a sync function.")
|
|
242
|
+
return transformer(result, *args, **kwargs)
|
|
243
|
+
|
|
244
|
+
return sync_wrapper
|
|
245
|
+
|
|
246
|
+
return decorator
|
|
File without changes
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from .algorithms.image_hashing_algorithm_ahash import AHashAlgorithm
|
|
2
|
+
from .algorithms.image_hashing_algorithm_dhash import DHashAlgorithm
|
|
3
|
+
from .algorithms.image_hashing_algorithm_phash import PHashAlgorithm
|
|
4
|
+
|
|
5
|
+
from .image_hash_algorithm import ImageHashAlgorithm
|
|
6
|
+
from .image_hash_utils import ImageHashUtils
|
|
File without changes
|
|
@@ -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 AHashAlgorithm:
|
|
19
|
+
"""
|
|
20
|
+
Average Hash (aHash) - Fast but less accurate.
|
|
21
|
+
Good for finding exact duplicates that might have slight color shifts.
|
|
22
|
+
"""
|
|
23
|
+
name = "ahash"
|
|
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.average_hash(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)
|