From 693a27d76c91c2cb0423cb9af365fee41987b394 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Wed, 26 Oct 2016 14:44:41 -0700 Subject: [PATCH] leptonica: add iPython display hook and equality test --- ocrmypdf/leptonica.py | 30 +++++++++++++++++++++++++++--- ocrmypdf/lib/compile_leptonica.py | 6 ++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/ocrmypdf/leptonica.py b/ocrmypdf/leptonica.py index 570ef697..43b696e3 100644 --- a/ocrmypdf/leptonica.py +++ b/ocrmypdf/leptonica.py @@ -41,16 +41,21 @@ class LeptonicaErrorTrap(object): """ def __enter__(self): + from io import UnsupportedOperation self.tmpfile = TemporaryFile() # Save the old stderr, and redirect stderr to temporary file - self.old_stderr_fileno = os.dup(sys.stderr.fileno()) - os.dup2(self.tmpfile.fileno(), sys.stderr.fileno()) + try: + self.old_stderr_fileno = os.dup(sys.stderr.fileno()) + os.dup2(self.tmpfile.fileno(), sys.stderr.fileno()) + except UnsupportedOperation: + self.old_stderr_fileno = None return def __exit__(self, exc_type, exc_value, traceback): # Restore old stderr - os.dup2(self.old_stderr_fileno, sys.stderr.fileno()) + if self.old_stderr_fileno is not None: + os.dup2(self.old_stderr_fileno, sys.stderr.fileno()) # Get data from tmpfile (in with block to ensure it is closed) with self.tmpfile as tmpfile: @@ -120,6 +125,22 @@ class Pix: else: return "" + def _repr_png_(self): + """iPython display hook + + returns png version of image + """ + + data = ffi.new('l_uint8 **') + size = ffi.new('size_t *') + + err = lept.pixWriteMemPng(data, size, self._pix, 0) + if err != 0: + raise LeptonicaIOError("pixWriteMemPng") + + char_data = ffi.cast('char *', data[0]) + return ffi.buffer(char_data, size[0])[:] + def __getstate__(self): data = ffi.new('l_uint32 **') size = ffi.new('size_t *') @@ -145,6 +166,9 @@ class Pix: cdata_uint32, len(state['data'])) Pix.__init__(self, pix) + def __eq__(self, other): + return self.__getstate__() == other.__getstate__() + @property def width(self): return self._pix.w diff --git a/ocrmypdf/lib/compile_leptonica.py b/ocrmypdf/lib/compile_leptonica.py index 23a9e924..acbb64f8 100644 --- a/ocrmypdf/lib/compile_leptonica.py +++ b/ocrmypdf/lib/compile_leptonica.py @@ -61,6 +61,12 @@ PIX * pixRead ( const char *filename ); PIX * pixScale ( PIX *pixs, l_float32 scalex, l_float32 scaley ); l_int32 pixFindSkew ( PIX *pixs, l_float32 *pangle, l_float32 *pconf ); l_int32 pixWriteImpliedFormat ( const char *filename, PIX *pix, l_int32 quality, l_int32 progressive ); +l_int32 +pixWriteMemPng(l_uint8 **pdata, + size_t *psize, + PIX *pix, + l_float32 gamma); + void pixDestroy ( PIX **ppix ); PIX *