Skip to content

File: Broken/Loaders.py

Broken.Loaders

BrokenLoader

Bases: ABC

Source code in Broken/Loaders.py
21
22
23
24
25
26
27
28
29
30
@define
class BrokenLoader(ABC):

    def __new__(cls, *args, **kwargs) -> Optional[type]:
        return cls.load(*args, **kwargs)

    @staticmethod
    @abstractmethod
    def load(value: Any=None, **kwargs) -> Optional[type]:
        ...

__new__

__new__(*args, **kwargs) -> Optional[type]
Source code in Broken/Loaders.py
24
25
def __new__(cls, *args, **kwargs) -> Optional[type]:
    return cls.load(*args, **kwargs)

load

load(value: Any = None, **kwargs) -> Optional[type]
Source code in Broken/Loaders.py
27
28
29
30
@staticmethod
@abstractmethod
def load(value: Any=None, **kwargs) -> Optional[type]:
    ...

LoadString

Bases: BrokenLoader

Source code in Broken/Loaders.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@define
class LoadString(BrokenLoader):

    @staticmethod
    def load(value: Any=None) -> Optional[str]:
        if (not value):
            return ""

        if isinstance(value, str):
            return value

        if isinstance(value, bytes):
            return value.decode()

        if (path := Path(value)).exists():
            return path.read_text(encoding="utf-8")

        return None

load

load(value: Any = None) -> Optional[str]
Source code in Broken/Loaders.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@staticmethod
def load(value: Any=None) -> Optional[str]:
    if (not value):
        return ""

    if isinstance(value, str):
        return value

    if isinstance(value, bytes):
        return value.decode()

    if (path := Path(value)).exists():
        return path.read_text(encoding="utf-8")

    return None

LoadableString

LoadableString: TypeAlias = Union[str, bytes, Path]

LoadBytes

Bases: BrokenLoader

Source code in Broken/Loaders.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@define
class LoadBytes(BrokenLoader):

    @staticmethod
    def load(value: Any=None) -> Optional[bytes]:
        if (value is None):
            return None

        if isinstance(value, bytes):
            return value

        if isinstance(value, str):
            return value.encode()

        if (path := Path(value)).exists():
            return path.read_bytes()

        return None

load

load(value: Any = None) -> Optional[bytes]
Source code in Broken/Loaders.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@staticmethod
def load(value: Any=None) -> Optional[bytes]:
    if (value is None):
        return None

    if isinstance(value, bytes):
        return value

    if isinstance(value, str):
        return value.encode()

    if (path := Path(value)).exists():
        return path.read_bytes()

    return None

LoadableBytes

LoadableBytes: TypeAlias = Union[bytes, str, Path, None]

LoadImage

Bases: BrokenLoader

Source code in Broken/Loaders.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@define
class LoadImage(BrokenLoader):
    _cache = None

    @staticmethod
    def cache() -> Any:
        with contextlib.suppress(ImportError):
            LoadImage._cache = (LoadImage._cache or BrokenCache.requests(
                cache_name=Broken.BROKEN.DIRECTORIES.CACHE/"LoadImage.sqlite",
                expire_after=1800))
        return LoadImage._cache

    @staticmethod
    def load(value: Any=None) -> Optional[ImageType]:

        # No value to load
        if (value is None):
            return None

        # Passthrough image class
        if (value is ImageType):
            return value

        # Already an instance of Image
        if isinstance(value, ImageType):
            return value

        # Attempt to load from path
        if isinstance(value, Path):
            if (value.exists()):
                return Image.open(value)
            return None

        if isinstance(value, str):

            # Load from base64 generic type
            if (value.startswith(prefix := "base64:")):
                return Image.open(BytesIO(b64decode(value[len(prefix):])))

            # Attempt to load from URL
            if validators.url(value):
                import requests
                get = getattr(LoadImage.cache(), "get", requests.get)
                return Image.open(BytesIO(get(value).content))

            # Load from path, ignore too
            try:
                if (path := Path(value)).exists():
                    return Image.open(path)
            except OSError as error:
                if (error.errno != 36):
                    raise error

            return None

        # Load from bytes
        if isinstance(value, bytes):
            return Image.open(BytesIO(value))

        # Load from numpy array
        if ("numpy" in str(type(value))):
            return Image.fromarray(value)

        return None

cache

cache() -> Any
Source code in Broken/Loaders.py
84
85
86
87
88
89
90
@staticmethod
def cache() -> Any:
    with contextlib.suppress(ImportError):
        LoadImage._cache = (LoadImage._cache or BrokenCache.requests(
            cache_name=Broken.BROKEN.DIRECTORIES.CACHE/"LoadImage.sqlite",
            expire_after=1800))
    return LoadImage._cache

load

load(value: Any = None) -> Optional[ImageType]
Source code in Broken/Loaders.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@staticmethod
def load(value: Any=None) -> Optional[ImageType]:

    # No value to load
    if (value is None):
        return None

    # Passthrough image class
    if (value is ImageType):
        return value

    # Already an instance of Image
    if isinstance(value, ImageType):
        return value

    # Attempt to load from path
    if isinstance(value, Path):
        if (value.exists()):
            return Image.open(value)
        return None

    if isinstance(value, str):

        # Load from base64 generic type
        if (value.startswith(prefix := "base64:")):
            return Image.open(BytesIO(b64decode(value[len(prefix):])))

        # Attempt to load from URL
        if validators.url(value):
            import requests
            get = getattr(LoadImage.cache(), "get", requests.get)
            return Image.open(BytesIO(get(value).content))

        # Load from path, ignore too
        try:
            if (path := Path(value)).exists():
                return Image.open(path)
        except OSError as error:
            if (error.errno != 36):
                raise error

        return None

    # Load from bytes
    if isinstance(value, bytes):
        return Image.open(BytesIO(value))

    # Load from numpy array
    if ("numpy" in str(type(value))):
        return Image.fromarray(value)

    return None

LoadableImage

LoadableImage: TypeAlias = Union[
    ImageType, Path, "numpy.ndarray", bytes, str
]