Skip to content
This repository was archived by the owner on Apr 11, 2025. It is now read-only.

Commit 855fea0

Browse files
foarsitterbosd
authored andcommitted
Add typing for camelot/backends
1 parent 40fa8df commit 855fea0

File tree

4 files changed

+51
-26
lines changed

4 files changed

+51
-26
lines changed

camelot/backends/base.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""Classes and functions for the ImageConversionBackend backends."""
2+
3+
4+
class ConversionBackend: # noqa D101
5+
6+
def installed(self) -> bool: # noqa D102
7+
raise NotImplementedError
8+
9+
def convert( # noqa D102
10+
self, pdf_path: str, png_path: str, resolution: int = 300
11+
) -> None: # noqa D102
12+
raise NotImplementedError

camelot/backends/ghostscript_backend.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
"""Creates a ghostscript backend class to convert a pdf to a png file."""
22

3+
from camelot.backends.base import ConversionBackend
34

4-
class GhostscriptBackend:
5+
6+
class GhostscriptBackend(ConversionBackend):
57
"""Classmethod to create GhostscriptScriptBackend."""
68

7-
def convert(self, pdf_path, png_path, resolution=300):
9+
def convert(self, pdf_path: str, png_path: str, resolution: int = 300) -> None:
810
"""Convert a PDF to a PNG image using Ghostscript .
911
1012
Parameters
@@ -22,7 +24,7 @@ def convert(self, pdf_path, png_path, resolution=300):
2224
[description]
2325
"""
2426
try:
25-
import ghostscript
27+
import ghostscript # type: ignore[import-untyped]
2628
except RuntimeError:
2729
raise OSError(
2830
"Ghostscript is not installed. You can install it using the instructions"
Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,52 @@
1-
"""Classes tand functions for the ImageConversionBackend backends."""
1+
"""Classes and functions for the ImageConversionBackend backends."""
22

3+
from typing import Dict
4+
from typing import List
5+
from typing import Type
6+
7+
from .base import ConversionBackend
38
from .ghostscript_backend import GhostscriptBackend
49
from .poppler_backend import PopplerBackend
510

611

7-
BACKENDS = {"poppler": PopplerBackend, "ghostscript": GhostscriptBackend}
12+
BACKENDS: Dict[str, Type[ConversionBackend]] = {
13+
"poppler": PopplerBackend,
14+
"ghostscript": GhostscriptBackend,
15+
}
16+
17+
18+
class ImageConversionError(ValueError): # noqa D101
19+
pass
820

921

1022
class ImageConversionBackend:
1123
"""Classes the ImageConversionBackend backend."""
1224

13-
def __init__(self, backend="poppler", use_fallback=True):
25+
def __init__(self, backend: str = "poppler", use_fallback: bool = True) -> None:
1426
"""Initialize the conversion backend .
1527
1628
Parameters
1729
----------
1830
backend : str, optional
19-
[description], by default "poppler"
31+
Backend for image conversion, by default "poppler"
2032
use_fallback : bool, optional
21-
[description], by default True
33+
Fallback to another backend if unavailable, by default True
2234
2335
Raises
2436
------
2537
ValueError
26-
[description]
38+
Raise an error if the backend is not supported.
2739
"""
2840
if backend not in BACKENDS.keys():
2941
raise ValueError(f"Image conversion backend {backend!r} not supported")
3042

31-
self.backend = backend
32-
self.use_fallback = use_fallback
33-
self.fallbacks = list(filter(lambda x: x != backend, BACKENDS.keys()))
43+
self.backend: str = backend
44+
self.use_fallback: bool = use_fallback
45+
self.fallbacks: List[str] = list(
46+
filter(lambda x: x != backend, BACKENDS.keys())
47+
)
3448

35-
def convert(self, pdf_path, png_path):
49+
def convert(self, pdf_path: str, png_path: str) -> None:
3650
"""Convert PDF to png_path.
3751
3852
Parameters
@@ -52,22 +66,17 @@ def convert(self, pdf_path, png_path):
5266
try:
5367
converter = BACKENDS[self.backend]()
5468
converter.convert(pdf_path, png_path)
55-
except Exception as e:
56-
import sys
57-
69+
except Exception as f:
5870
if self.use_fallback:
5971
for fallback in self.fallbacks:
6072
try:
6173
converter = BACKENDS[fallback]()
6274
converter.convert(pdf_path, png_path)
6375
except Exception as e:
64-
raise type(e)(
65-
str(e) + f" with image conversion backend {fallback!r}"
66-
).with_traceback(sys.exc_info()[2])
67-
continue
76+
msg = f"Image conversion failed with image conversion backend {fallback!r}"
77+
raise ImageConversionError(msg) from e
6878
else:
6979
break
7080
else:
71-
raise type(e)(
72-
str(e) + f" with image conversion backend {self.backend!r}"
73-
).with_traceback(sys.exc_info()[2])
81+
msg = f"Image conversion failed with image conversion backend {self.backend!r}"
82+
raise ImageConversionError(msg) from f

camelot/backends/poppler_backend.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,16 @@
1313
import subprocess
1414
import sys
1515

16+
from camelot.backends.base import ConversionBackend
17+
1618

1719
path = os.path.dirname(sys.executable) + os.pathsep + os.environ["PATH"]
1820

1921

20-
class PopplerBackend:
22+
class PopplerBackend(ConversionBackend):
2123
"""Classmethod to create a poplerBackendBackend class."""
2224

23-
def convert(self, pdf_path, png_path):
25+
def convert(self, pdf_path: str, png_path: str, resolution: int = 300) -> None:
2426
"""Convert PDF to png.
2527
2628
Parameters
@@ -50,4 +52,4 @@ def convert(self, pdf_path, png_path):
5052
" ".join(pdftopng_command), stderr=subprocess.STDOUT, shell=False
5153
)
5254
except subprocess.CalledProcessError as e:
53-
raise ValueError(e.output)
55+
raise ValueError(e.output) from e

0 commit comments

Comments
 (0)