Ejemplo n.º 1
0
 def test_decode_filelike(self):
     """Test passing a filelike to decode."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     with open(fpath, 'rb') as f:
         msg = r"No decoders are available"
         with pytest.raises(RuntimeError, match=msg):
             decode(f)
Ejemplo n.º 2
0
 def test_decode_pathlike(self):
     """Test passing a pathlike to decode."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     p = Path(fpath)
     assert isinstance(p, os.PathLike)
     with pytest.raises(RuntimeError, match=r"No decoders are available"):
         decode(p)
Ejemplo n.º 3
0
    def test_decode_bytes(self):
        """Test passing bytes to decode."""
        fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
        with open(fpath, 'rb') as f:
            data = f.read()

        assert isinstance(data, bytes)
        msg = r"No decoders are available"
        with pytest.raises(RuntimeError, match=msg):
            decode(data)
Ejemplo n.º 4
0
    def test_decode_filelike(self):
        """Test passing a filelike to decode."""
        bs = BytesIO()

        fpath = os.path.join(self.basedir, '693.j2k')
        with open(fpath, 'rb') as f:
            arr = decode(f)

        with open(fpath, 'rb') as f:
            bs.write(f.read())

        bs.seek(0)
        arr = decode(bs)
Ejemplo n.º 5
0
    def test_decode_filelike(self):
        """Test passing a filelike to decode."""
        bs = BytesIO()

        fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
        with open(fpath, 'rb') as f:
            arr = decode(f)

        with open(fpath, 'rb') as f:
            bs.write(f.read())

        bs.seek(0)
        arr = decode(bs)
Ejemplo n.º 6
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """

        if b'@IMG_JPEG' not in self.chunk_dict:
            raise ValueError(
                'Could not find OCT header @IMG_JPEG in chunk list')
        with open(self.filepath, 'rb') as f:
            chunk_location, chunk_size = self.chunk_dict[b'@IMG_JPEG']
            f.seek(chunk_location)  # Set the chunk’s current position.
            raw = f.read(25)
            oct_header = self.oct_header.parse(raw)
            volume = np.zeros((oct_header.height, oct_header.width,
                               oct_header.number_slices))
            for i in range(oct_header.number_slices):
                size = np.frombuffer(f.read(4), dtype=np.int32)[0]
                raw_slice = f.read(size)
                slice = decode(raw_slice)
                volume[:, :, i] = slice
        oct_volume = OCTVolumeWithMetaData(
            [volume[:, :, i] for i in range(volume.shape[2])])
        return oct_volume
Ejemplo n.º 7
0
    def test_decode_bytes(self):
        """Test passing bytes to decode."""
        fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
        with open(fpath, 'rb') as f:
            data = f.read()

        assert isinstance(data, bytes)
        arr = decode(data)
Ejemplo n.º 8
0
    def test_decode_bytes(self):
        """Test passing bytes to decode."""
        fpath = os.path.join(self.basedir, '693.j2k')
        with open(fpath, 'rb') as f:
            data = f.read()

        assert isinstance(data, bytes)
        arr = decode(data)
Ejemplo n.º 9
0
    def read_fundus_image(self):
        """ Reads fundus image.

            Returns:
                obj:FundusImageWithMetaData
        """
        if b'@IMG_FUNDUS' not in self.chunk_dict:
            raise ValueError('Could not find fundus header @IMG_FUNDUS in chunk list')
        with open(self.filepath, 'rb') as f:
            chunk_location, chunk_size = self.chunk_dict[b'@IMG_FUNDUS']
            f.seek(chunk_location)# Set the chunk’s current position.
            raw = f.read(24)# skip 24 is important
            fundus_header = self.fundus_header.parse(raw)
            number_pixels = fundus_header.width * fundus_header.height * 3
            raw_image = f.read(fundus_header.size)
            image = decode(raw_image)
        fundus_image = FundusImageWithMetaData(image)
        return fundus_image
Ejemplo n.º 10
0
 def test_specify_unknown_decoder(self):
     """Test specifying an unknown decoder."""
     fpath = os.path.join(self.basedir, '693.j2k')
     with pytest.raises(ValueError, match=r"The 'libjpeg' decoder"):
         decode(fpath, decoder='libjpeg')
Ejemplo n.º 11
0
 def test_specify_decoder(self):
     """Test specifying the decoder."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     assert isinstance(fpath, str)
     arr = decode(fpath, decoder='libjpeg')
Ejemplo n.º 12
0
def generateFile(file):
    collectedErrors = []
    merger = PdfFileMerger()
    ios = file
    lf = LhaFile(ios)
    appended = False
    loextensions = ('.odt', '.ods')
    for name in lf.namelist():
        content = lf.read(name)
        _, extension = os.path.splitext(name)
        if content[0:5] == b'%PDF-':
            merger.append(io.BytesIO(content))
            appended = True
        elif content[0:5] == b'{\\rtf' or (content[0:4]
                                           == bytes.fromhex('504B0304')
                                           and extension in loextensions):
            with tempdir() as tmpdir:
                tmpfile = os.sep.join([tmpdir, "temp" + extension])
                pdffile = tmpdir + os.sep + "temp.pdf"
                with open(tmpfile, "wb") as f:
                    f.write(content)
                command = '"' + " ".join([
                    '"' + self._librepath + '"', "--convert-to pdf",
                    "--outdir", '"' + tmpdir + '"', '"' + tmpfile + '"'
                ]) + '"'
                if os.system(command) == 0:
                    try:
                        with open(pdffile, "rb") as f:
                            merger.append(io.BytesIO(f.read()))

                        appended = True
                    except:
                        err = "%s: Fehler beim Öffnen der konvertierten PDF-Datei '%s' (konvertiert aus '%s')" % (
                            file['beschreibung'], pdffile, tmpfile)
                        collectedErrors.append(err)
                else:
                    err = "%s: Fehler beim Ausführen des Kommandos: '%s'" % (
                        file['beschreibung'], command)
                    collectedErrors.append(err)
        elif name == "message.eml":
            # eArztbrief
            eml = email.message_from_bytes(content)
            errors = []
            for part in eml.get_payload():
                fnam = part.get_filename()
                partcont = part.get_payload(decode=True)
                if partcont[0:5] == b'%PDF-':
                    merger.append(io.BytesIO(partcont))
                    appended = True
                else:
                    errors.append(
                        "%s: eArztbrief: nicht unterstütztes Anhangsformat in Anhang '%s'"
                        % (file["beschreibung"], fnam))

            if not appended and len(errors) > 0:
                err = '\n'.join(errors)
                collectedErrors.append(err)
        else:
            try:
                if content[0:4] == bytes.fromhex('FFD8FFE0'):
                    img = Image.fromarray(pylibjpeg.decode(content))
                    outbuffer = io.BytesIO()
                    img.save(outbuffer, 'PDF')
                    merger.append(outbuffer)
                    appended = True
                #elif self._config.getValue('useImg2pdf', True):
                #    LOGGER.debug("Using img2pdf for file conversion")
                #    merger.append(io.BytesIO(img2pdf.convert(content)))
                #    appended = True
                else:
                    if content[0:3] == b'II*':
                        #with open('tmp.tif', 'wb') as f:
                        #    f.write(content)
                        infile = 'tmp.tif'
                        outfile = 'tmp.pdf'
                        batchscript = '(let* ((image (car (gimp-file-load RUN-NONINTERACTIVE "{infile}" "{infile}")))(drawable (car (gimp-image-get-active-layer image))))\
                            (file-pdf-save2 RUN-NONINTERACTIVE image drawable "{outfile}" "{outfile}" FALSE TRUE TRUE TRUE FALSE)(gimp-image-delete image) (gimp-quit 0))'.format(
                            infile=infile, outfile=outfile)
                        gimp_path = 'C:\\Program Files\\GIMP 2\\bin\\gimp-2.10.exe'
                        subprocess.run([gimp_path, '-i', '-b', batchscript],
                                       check=True,
                                       stdout=PIPE,
                                       stderr=PIPE)
                        merger.append(outfile)
                        appended = True
            except Exception as e:
                err = "Dateiinhalt '%s' ist kein unterstützter Dateityp -> wird nicht an PDF angehängt (%s)" % (
                    name, type(e))
                collectedErrors.append(err)
                traceback.print_exc(e)

    #if appended:
    #    try:
    #        merger.write(filename)
    #    except Exception as e:
    #        err = "{}: Fehler beim Schreiben der Ausgabedatei '{}': {}".format(file["beschreibung"], filename, e)
    #        if errorSlot:
    #            errorSlot.emit(err)
    #        else:
    #            self._av.displayErrorMessage(err)
    print('\n'.join(collectedErrors))

    merger.close()
Ejemplo n.º 13
0
 def test_decode_pathlike(self):
     """Test passing a pathlike to decode."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     p = Path(fpath)
     assert isinstance(p, os.PathLike)
     arr = decode(p)
Ejemplo n.º 14
0
 def test_specify_unknown_decoder(self):
     """Test specifying an unknown decoder."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     assert isinstance(fpath, str)
     with pytest.raises(ValueError, match=r"The 'openjpeg' decoder"):
         decode(fpath, decoder='openjpeg')
Ejemplo n.º 15
0
 def test_specify_decoder(self):
     """Test specifying the decoder."""
     fpath = os.path.join(self.basedir, 'T8C0E0.JLS')
     arr = decode(fpath, decoder='libjpeg')
Ejemplo n.º 16
0
 def test_decode_str(self):
     """Test passing a str to decode."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     assert isinstance(fpath, str)
     arr = decode(fpath)
Ejemplo n.º 17
0
 def test_decode_str(self):
     """Test passing a str to decode."""
     fpath = os.path.join(self.basedir, '693.j2k')
     assert isinstance(fpath, str)
     arr = decode(fpath)
Ejemplo n.º 18
0
 def test_decode_pathlike(self):
     """Test passing a pathlike to decode."""
     fpath = os.path.join(self.basedir, '693.j2k')
     p = Path(fpath)
     assert isinstance(p, os.PathLike)
     arr = decode(p)
Ejemplo n.º 19
0
 def test_decode_str(self):
     """Test passing a str to decode."""
     fpath = os.path.join(JPEG_DIRECTORY, '10918', 'p1', 'A1.JPG')
     assert isinstance(fpath, str)
     with pytest.raises(RuntimeError, match=r"No decoders are available"):
         decode(fpath)
Ejemplo n.º 20
0
 def test_decode_failure(self):
     """Test failure to decode."""
     with pytest.raises(ValueError, match=r"Unable to decode"):
         decode(b'\x00\x00')
Ejemplo n.º 21
0
 def test_specify_decoder(self):
     """Test specifying the decoder."""
     fpath = os.path.join(self.basedir, '693.j2k')
     arr = decode(fpath, decoder='openjpeg')