Replaced DEBUG with logging

This commit is contained in:
Andrew Murray 2020-04-13 07:16:46 +10:00
parent 97280a045c
commit 13dcab0fb7

View File

@ -40,6 +40,7 @@
# #
import io import io
import itertools import itertools
import logging
import os import os
import struct import struct
import warnings import warnings
@ -51,7 +52,7 @@ from . import Image, ImageFile, ImagePalette, TiffTags
from ._binary import i8, o8 from ._binary import i8, o8
from .TiffTags import TYPES from .TiffTags import TYPES
DEBUG = False # Needs to be merged with the new logging approach. logger = logging.getLogger(__name__)
# Set these to true to force use of libtiff for reading or writing. # Set these to true to force use of libtiff for reading or writing.
READ_LIBTIFF = False READ_LIBTIFF = False
@ -734,29 +735,21 @@ class ImageFileDirectory_v2(MutableMapping):
try: try:
for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]): for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]):
tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12)) tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12))
if DEBUG:
tagname = TiffTags.lookup(tag).name tagname = TiffTags.lookup(tag).name
typname = TYPES.get(typ, "unknown") typname = TYPES.get(typ, "unknown")
print( msg = "tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
"tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ),
end=" ",
)
try: try:
unit_size, handler = self._load_dispatch[typ] unit_size, handler = self._load_dispatch[typ]
except KeyError: except KeyError:
if DEBUG: logger.debug(msg + " - unsupported type {}".format(typ))
print("- unsupported type", typ)
continue # ignore unsupported type continue # ignore unsupported type
size = count * unit_size size = count * unit_size
if size > 4: if size > 4:
here = fp.tell() here = fp.tell()
(offset,) = self._unpack("L", data) (offset,) = self._unpack("L", data)
if DEBUG: msg += " Tag Location: {} - Data Location: {}".format(here, offset)
print(
"Tag Location: {} - Data Location: {}".format(here, offset),
end=" ",
)
fp.seek(offset) fp.seek(offset)
data = ImageFile._safe_read(fp, size) data = ImageFile._safe_read(fp, size)
fp.seek(here) fp.seek(here)
@ -769,19 +762,20 @@ class ImageFileDirectory_v2(MutableMapping):
"Expecting to read %d bytes but only got %d." "Expecting to read %d bytes but only got %d."
" Skipping tag %s" % (size, len(data), tag) " Skipping tag %s" % (size, len(data), tag)
) )
logger.debug(msg)
continue continue
if not data: if not data:
logger.debug(msg)
continue continue
self._tagdata[tag] = data self._tagdata[tag] = data
self.tagtype[tag] = typ self.tagtype[tag] = typ
if DEBUG: msg += " - value: " + (
if size > 32: "<table: %d bytes>" % size if size > 32 else str(data)
print("- value: <table: %d bytes>" % size) )
else: logger.debug(msg)
print("- value:", self[tag])
(self.next,) = self._unpack("L", self._ensure_read(fp, 4)) (self.next,) = self._unpack("L", self._ensure_read(fp, 4))
except OSError as msg: except OSError as msg:
@ -802,21 +796,17 @@ class ImageFileDirectory_v2(MutableMapping):
if tag == STRIPOFFSETS: if tag == STRIPOFFSETS:
stripoffsets = len(entries) stripoffsets = len(entries)
typ = self.tagtype.get(tag) typ = self.tagtype.get(tag)
if DEBUG: logger.debug("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
print("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
values = value if isinstance(value, tuple) else (value,) values = value if isinstance(value, tuple) else (value,)
data = self._write_dispatch[typ](self, *values) data = self._write_dispatch[typ](self, *values)
if DEBUG:
tagname = TiffTags.lookup(tag).name tagname = TiffTags.lookup(tag).name
typname = TYPES.get(typ, "unknown") typname = TYPES.get(typ, "unknown")
print( msg = "save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
"save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ), msg += " - value: " + (
end=" ", "<table: %d bytes>" % len(data) if len(data) >= 16 else str(values)
) )
if len(data) >= 16: logger.debug(msg)
print("- value: <table: %d bytes>" % len(data))
else:
print("- value:", values)
# count is sum of lengths for string and arbitrary data # count is sum of lengths for string and arbitrary data
if typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]: if typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
@ -840,8 +830,9 @@ class ImageFileDirectory_v2(MutableMapping):
# pass 2: write entries to file # pass 2: write entries to file
for tag, typ, count, value, data in entries: for tag, typ, count, value, data in entries:
if DEBUG: logger.debug(
print(tag, typ, count, repr(value), repr(data)) "{} {} {} {} {}".format(tag, typ, count, repr(value), repr(data))
)
result += self._pack("HHL4s", tag, typ, count, value) result += self._pack("HHL4s", tag, typ, count, value)
# -- overwrite here for multi-page -- # -- overwrite here for multi-page --
@ -997,10 +988,9 @@ class TiffImageFile(ImageFile.ImageFile):
self._frame_pos = [] self._frame_pos = []
self._n_frames = None self._n_frames = None
if DEBUG: logger.debug("*** TiffImageFile._open ***")
print("*** TiffImageFile._open ***") logger.debug("- __first: {}".format(self.__first))
print("- __first:", self.__first) logger.debug("- ifh: {}".format(ifh))
print("- ifh: ", ifh)
# and load the first frame # and load the first frame
self._seek(0) self._seek(0)
@ -1035,18 +1025,16 @@ class TiffImageFile(ImageFile.ImageFile):
while len(self._frame_pos) <= frame: while len(self._frame_pos) <= frame:
if not self.__next: if not self.__next:
raise EOFError("no more images in TIFF file") raise EOFError("no more images in TIFF file")
if DEBUG: logger.debug(
print( "Seeking to frame %s, on frame %s, __next %s, location: %s"
"Seeking to frame %s, on frame %s, __next %s, location: %s" % (frame, self.__frame, self.__next, self.fp.tell())
% (frame, self.__frame, self.__next, self.fp.tell()) )
)
# reset buffered io handle in case fp # reset buffered io handle in case fp
# was passed to libtiff, invalidating the buffer # was passed to libtiff, invalidating the buffer
self.fp.tell() self.fp.tell()
self.fp.seek(self.__next) self.fp.seek(self.__next)
self._frame_pos.append(self.__next) self._frame_pos.append(self.__next)
if DEBUG: logger.debug("Loading tags, location: %s" % self.fp.tell())
print("Loading tags, location: %s" % self.fp.tell())
self.tag_v2.load(self.fp) self.tag_v2.load(self.fp)
self.__next = self.tag_v2.next self.__next = self.tag_v2.next
if self.__next == 0: if self.__next == 0:
@ -1149,21 +1137,18 @@ class TiffImageFile(ImageFile.ImageFile):
# Rearranging for supporting byteio items, since they have a fileno # Rearranging for supporting byteio items, since they have a fileno
# that returns an OSError if there's no underlying fp. Easier to # that returns an OSError if there's no underlying fp. Easier to
# deal with here by reordering. # deal with here by reordering.
if DEBUG: logger.debug("have getvalue. just sending in a string from getvalue")
print("have getvalue. just sending in a string from getvalue")
n, err = decoder.decode(self.fp.getvalue()) n, err = decoder.decode(self.fp.getvalue())
elif fp: elif fp:
# we've got a actual file on disk, pass in the fp. # we've got a actual file on disk, pass in the fp.
if DEBUG: logger.debug("have fileno, calling fileno version of the decoder.")
print("have fileno, calling fileno version of the decoder.")
if not close_self_fp: if not close_self_fp:
self.fp.seek(0) self.fp.seek(0)
# 4 bytes, otherwise the trace might error out # 4 bytes, otherwise the trace might error out
n, err = decoder.decode(b"fpfp") n, err = decoder.decode(b"fpfp")
else: else:
# we have something else. # we have something else.
if DEBUG: logger.debug("don't have fileno or getvalue. just reading")
print("don't have fileno or getvalue. just reading")
self.fp.seek(0) self.fp.seek(0)
# UNDONE -- so much for that buffer size thing. # UNDONE -- so much for that buffer size thing.
n, err = decoder.decode(self.fp.read()) n, err = decoder.decode(self.fp.read())
@ -1203,21 +1188,19 @@ class TiffImageFile(ImageFile.ImageFile):
fillorder = self.tag_v2.get(FILLORDER, 1) fillorder = self.tag_v2.get(FILLORDER, 1)
if DEBUG: logger.debug("*** Summary ***")
print("*** Summary ***") logger.debug("- compression: {}".format(self._compression))
print("- compression:", self._compression) logger.debug("- photometric_interpretation: {}".format(photo))
print("- photometric_interpretation:", photo) logger.debug("- planar_configuration: {}".format(self._planar_configuration))
print("- planar_configuration:", self._planar_configuration) logger.debug("- fill_order: {}".format(fillorder))
print("- fill_order:", fillorder) logger.debug("- YCbCr subsampling: {}".format(self.tag.get(530)))
print("- YCbCr subsampling:", self.tag.get(530))
# size # size
xsize = int(self.tag_v2.get(IMAGEWIDTH)) xsize = int(self.tag_v2.get(IMAGEWIDTH))
ysize = int(self.tag_v2.get(IMAGELENGTH)) ysize = int(self.tag_v2.get(IMAGELENGTH))
self._size = xsize, ysize self._size = xsize, ysize
if DEBUG: logger.debug("- size: {}".format(self.size))
print("- size:", self.size)
sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,)) sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1: if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1:
@ -1251,18 +1234,15 @@ class TiffImageFile(ImageFile.ImageFile):
bps_tuple, bps_tuple,
extra_tuple, extra_tuple,
) )
if DEBUG: logger.debug("format key: {}".format(key))
print("format key:", key)
try: try:
self.mode, rawmode = OPEN_INFO[key] self.mode, rawmode = OPEN_INFO[key]
except KeyError: except KeyError:
if DEBUG: logger.debug("- unsupported format")
print("- unsupported format")
raise SyntaxError("unknown pixel mode") raise SyntaxError("unknown pixel mode")
if DEBUG: logger.debug("- raw mode: {}".format(rawmode))
print("- raw mode:", rawmode) logger.debug("- pil mode: {}".format(self.mode))
print("- pil mode:", self.mode)
self.info["compression"] = self._compression self.info["compression"] = self._compression
@ -1303,8 +1283,7 @@ class TiffImageFile(ImageFile.ImageFile):
if fillorder == 2: if fillorder == 2:
# Replace fillorder with fillorder=1 # Replace fillorder with fillorder=1
key = key[:3] + (1,) + key[4:] key = key[:3] + (1,) + key[4:]
if DEBUG: logger.debug("format key: {}".format(key))
print("format key:", key)
# this should always work, since all the # this should always work, since all the
# fillorder==2 modes have a corresponding # fillorder==2 modes have a corresponding
# fillorder=1 mode # fillorder=1 mode
@ -1366,8 +1345,7 @@ class TiffImageFile(ImageFile.ImageFile):
x = y = 0 x = y = 0
layer += 1 layer += 1
else: else:
if DEBUG: logger.debug("- unsupported data organization")
print("- unsupported data organization")
raise SyntaxError("unknown data organization") raise SyntaxError("unknown data organization")
# Fix up info. # Fix up info.
@ -1447,8 +1425,7 @@ def _save(im, fp, filename):
# write any arbitrary tags passed in as an ImageFileDirectory # write any arbitrary tags passed in as an ImageFileDirectory
info = im.encoderinfo.get("tiffinfo", {}) info = im.encoderinfo.get("tiffinfo", {})
if DEBUG: logger.debug("Tiffinfo Keys: %s" % list(info))
print("Tiffinfo Keys: %s" % list(info))
if isinstance(info, ImageFileDirectory_v1): if isinstance(info, ImageFileDirectory_v1):
info = info.to_v2() info = info.to_v2()
for key in info: for key in info:
@ -1533,9 +1510,8 @@ def _save(im, fp, filename):
) )
ifd[JPEGQUALITY] = quality ifd[JPEGQUALITY] = quality
if DEBUG: logger.debug("Saving using libtiff encoder")
print("Saving using libtiff encoder") logger.debug("Items: %s" % sorted(ifd.items()))
print("Items: %s" % sorted(ifd.items()))
_fp = 0 _fp = 0
if hasattr(fp, "fileno"): if hasattr(fp, "fileno"):
try: try:
@ -1597,8 +1573,7 @@ def _save(im, fp, filename):
else: else:
atts[tag] = value atts[tag] = value
if DEBUG: logger.debug("Converted items: %s" % sorted(atts.items()))
print("Converted items: %s" % sorted(atts.items()))
# libtiff always expects the bytes in native order. # libtiff always expects the bytes in native order.
# we're storing image byte order. So, if the rawmode # we're storing image byte order. So, if the rawmode