aboutsummaryrefslogtreecommitdiffstats
path: root/bsie
diff options
context:
space:
mode:
authorMatthias Baumgartner <dev@igsor.net>2022-12-24 16:06:16 +0100
committerMatthias Baumgartner <dev@igsor.net>2022-12-24 16:06:16 +0100
commit17f03ae3d3dc53fe973f37fe4dea4a831b4f97d7 (patch)
tree9fee9f0eb5206dda42143d544c1d66e9cede99df /bsie
parent07219685d01f803dc46c8d5465fa542c1d822cb4 (diff)
downloadbsie-17f03ae3d3dc53fe973f37fe4dea4a831b4f97d7.tar.gz
bsie-17f03ae3d3dc53fe973f37fe4dea4a831b4f97d7.tar.bz2
bsie-17f03ae3d3dc53fe973f37fe4dea4a831b4f97d7.zip
ReaderChain and image reader
Diffstat (limited to 'bsie')
-rw-r--r--bsie/reader/base.py2
-rw-r--r--bsie/reader/chain.py85
-rw-r--r--bsie/reader/image/__init__.py36
-rw-r--r--bsie/reader/image/_pillow.py37
-rw-r--r--bsie/reader/image/_raw.py61
5 files changed, 220 insertions, 1 deletions
diff --git a/bsie/reader/base.py b/bsie/reader/base.py
index 08d6cc6..099a327 100644
--- a/bsie/reader/base.py
+++ b/bsie/reader/base.py
@@ -39,7 +39,7 @@ class Reader(abc.ABC):
return hash(type(self))
@abc.abstractmethod
- def __call__(self, path: bsfs.URI) -> typing.Any:
+ def __call__(self, path: str) -> typing.Any:
"""Return some content of the file at *path*.
Raises a `ReaderError` if the reader cannot make sense of the file format.
"""
diff --git a/bsie/reader/chain.py b/bsie/reader/chain.py
new file mode 100644
index 0000000..8e900e1
--- /dev/null
+++ b/bsie/reader/chain.py
@@ -0,0 +1,85 @@
+"""
+
+Part of the bsie module.
+A copy of the license is provided with the project.
+Author: Matthias Baumgartner, 2022
+"""
+# standard imports
+import logging
+import typing
+
+# bsie imports
+from bsie.utils import bsfs, errors
+
+# inner-module imports
+from . import base
+from . import builder
+
+# exports
+__all__: typing.Sequence[str] = (
+ 'ReaderChain',
+ )
+
+
+## code ##
+
+logger = logging.getLogger(__name__)
+
+# Content type.
+T_CONTENT = typing.TypeVar('T_CONTENT') # pylint: disable=invalid-name
+
+class ReaderChain(base.Reader, typing.Generic[T_CONTENT]):
+ """Read an image."""
+
+ # sub-readers for specific file formats.
+ _children: typing.Tuple[base.Reader, ...]
+
+ def __init__(
+ self,
+ subreader_names: typing.Iterable[str],
+ cfg: typing.Any,
+ ):
+ rbuild = builder.ReaderBuilder(cfg)
+ children = []
+ for name in subreader_names:
+ try:
+ # build sub-reader
+ children.append(rbuild.build(name))
+ except (ValueError,
+ TypeError,
+ errors.LoaderError,
+ errors.BuilderError) as err:
+ # failed to build a child; skip and notify
+ logger.warning('failed to load reader: %s', err)
+
+ if len(children) == 0:
+ logger.warning('%s failed to load any sub-readers.', bsfs.typename(self))
+
+ # copy children to member
+ self._children = tuple(children)
+
+ def __str__(self) -> str:
+ substr = ', '.join(str(child) for child in self._children)
+ return f'{bsfs.typename(self)}({substr})'
+
+ def __repr__(self) -> str:
+ return f'{bsfs.typename(self)}({self._children})'
+
+ def __eq__(self, other: typing.Any) -> bool:
+ return super().__eq__(other) \
+ and self._children == other._children
+
+ def __hash__(self) -> int:
+ return hash((super().__hash__(), self._children))
+
+ def __call__(self, path: str) -> T_CONTENT:
+ for child in self._children:
+ try:
+ return child(path)
+ except errors.ReaderError:
+ # child cannot read the file, skip.
+ pass
+
+ raise errors.ReaderError(path)
+
+## EOF ##
diff --git a/bsie/reader/image/__init__.py b/bsie/reader/image/__init__.py
new file mode 100644
index 0000000..85dad85
--- /dev/null
+++ b/bsie/reader/image/__init__.py
@@ -0,0 +1,36 @@
+"""
+
+Part of the bsie module.
+A copy of the license is provided with the project.
+Author: Matthias Baumgartner, 2022
+"""
+# standard imports
+import typing
+
+# external imports
+import PIL.Image
+
+# inner-module imports
+from .. import chain
+
+# constants
+_FILE_FORMAT_READERS: typing.Sequence[str] = (
+ __package__ + '._raw.RawImage',
+ __package__ + '._pillow.PillowImage',
+ )
+
+# exports
+__all__: typing.Sequence[str] = (
+ 'Image',
+ )
+
+
+## code ##
+
+class Image(chain.ReaderChain[PIL.Image]): # pylint: disable=too-few-public-methods
+ """Read an image file."""
+
+ def __init__(self, cfg):
+ super().__init__(_FILE_FORMAT_READERS, cfg)
+
+## EOF ##
diff --git a/bsie/reader/image/_pillow.py b/bsie/reader/image/_pillow.py
new file mode 100644
index 0000000..ee0662d
--- /dev/null
+++ b/bsie/reader/image/_pillow.py
@@ -0,0 +1,37 @@
+"""
+
+Part of the bsie module.
+A copy of the license is provided with the project.
+Author: Matthias Baumgartner, 2022
+"""
+# standard imports
+import typing
+
+# external imports
+import PIL.Image
+
+# bsie imports
+from bsie.utils import errors
+
+# inner-module imports
+from .. import base
+
+# exports
+__all__: typing.Sequence[str] = (
+ 'PillowImage',
+ )
+
+
+## code ##
+
+class PillowImage(base.Reader):
+ """Use PIL to read content of a variety of image file types."""
+
+ def __call__(self, path: str) -> PIL.Image:
+ try:
+ # open file with PIL
+ return PIL.Image.open(path)
+ except IOError as err:
+ raise errors.ReaderError(path) from err
+
+# EOF ##
diff --git a/bsie/reader/image/_raw.py b/bsie/reader/image/_raw.py
new file mode 100644
index 0000000..77be357
--- /dev/null
+++ b/bsie/reader/image/_raw.py
@@ -0,0 +1,61 @@
+"""
+
+Part of the bsie module.
+A copy of the license is provided with the project.
+Author: Matthias Baumgartner, 2022
+"""
+# standard imports
+import typing
+
+# external imports
+import PIL.Image
+import rawpy
+
+# bsie imports
+from bsie.utils import errors, filematcher
+
+# inner-module imports
+from .. import base
+
+# constants
+MATCH_RULE = 'mime={image/x-nikon-nef} | extension={nef}'
+
+# exports
+__all__: typing.Sequence[str] = (
+ 'RawImage',
+ )
+
+
+## code ##
+
+class RawImage(base.Reader):
+ """Use rawpy to read content of raw image file types."""
+
+ # file matcher
+ match: filematcher.Matcher
+
+ # additional kwargs to rawpy's postprocess
+ rawpy_kwargs: typing.Dict[str, typing.Any]
+
+ def __init__(self, **rawpy_kwargs):
+ match_rule = rawpy_kwargs.pop('file_match_rule', MATCH_RULE)
+ self._match = filematcher.parse(match_rule)
+ self._rawpy_kwargs = rawpy_kwargs
+
+ def __call__(self, path: str) -> PIL.Image:
+ # perform quick checks first
+ if not self._match(path):
+ raise errors.ReaderError(path)
+
+ try:
+ # open file with rawpy
+ ary = rawpy.imread(path).postprocess(**self._rawpy_kwargs)
+ # convert to PIL.Image
+ return PIL.Image.fromarray(ary)
+ except (rawpy.LibRawFatalError, # pylint: disable=no-member # pylint doesn't find the errors
+ rawpy.NotSupportedError, # pylint: disable=no-member
+ rawpy.LibRawNonFatalError, # pylint: disable=no-member
+ ) as err:
+ raise errors.ReaderError(path) from err
+
+## EOF ##