Also switch TIFFImagePlugin to logging.

Just some mechanical changes.  The remaining file using print is OLEFile,
which has its own logic, but I noticed that @decalage's bitbucket repo has now
switched to using logging as well.
This commit is contained in:
Antony Lee 2015-12-09 07:10:02 -08:00
parent 3b3b559d9e
commit 647ad14ca5

View File

@ -49,6 +49,7 @@ import collections
from fractions import Fraction from fractions import Fraction
import io import io
import itertools import itertools
import logging
from numbers import Number from numbers import Number
import os import os
import struct import struct
@ -58,7 +59,8 @@ import warnings
from .TiffTags import TAGS_V2, TYPES, TagInfo from .TiffTags import TAGS_V2, TYPES, TagInfo
__version__ = "1.3.5" __version__ = "1.3.5"
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
@ -522,25 +524,20 @@ class ImageFileDirectory_v2(collections.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: logger.debug("tag: %s (%d) - type: %s (%d)",
tagname = TAGS_V2.get(tag, TagInfo()).name TAGS_V2.get(tag, TagInfo()).name, tag,
typname = TYPES.get(typ, "unknown") TYPES.get(typ, "unknown"), typ)
print("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("- unsupported type")
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: logger.debug("Tag Location: %s - Data Location: %s",
print("Tag Location: %s - Data Location: %s" % here, offset)
(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)
@ -556,11 +553,10 @@ class ImageFileDirectory_v2(collections.MutableMapping):
self._tagdata[tag] = data self._tagdata[tag] = data
self.tagtype[tag] = typ self.tagtype[tag] = typ
if DEBUG: if size > 32:
if size > 32: logger.debug("- value: <table: %d bytes>", size)
print("- value: <table: %d bytes>" % size) else:
else: logger.debug("- value: %s", self[tag])
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 IOError as msg: except IOError as msg:
@ -586,19 +582,16 @@ class ImageFileDirectory_v2(collections.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 %s, Type: %s, Value: %s", tag, typ, value)
print("Tag %s, Type: %s, Value: %s" % (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: logger.debug("save: %s (%d) - type: %s (%d)",
tagname = TAGS_V2.get(tag, TagInfo()).name TAGS_V2.get(tag, TagInfo()).name, tag,
typname = TYPES.get(typ, "unknown") TYPES.get(typ, "unknown"), typ)
print("save: %s (%d) - type: %s (%d)" % if len(data) >= 16:
(tagname, tag, typname, typ), end=" ") logger.debug("- value: <table: %d bytes>", len(data))
if len(data) >= 16: else:
print("- value: <table: %d bytes>" % len(data)) logger.debug("- value: %s", values)
else:
print("- value:", values)
# count is sum of lengths for string and arbitrary data # count is sum of lengths for string and arbitrary data
count = len(data) if typ in [2, 7] else len(values) count = len(data) if typ in [2, 7] else len(values)
@ -620,8 +613,7 @@ class ImageFileDirectory_v2(collections.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 > 1: logger.debug("%s %s %s %r %r", tag, typ, count, value, data)
print(tag, typ, count, repr(value), repr(data))
fp.write(self._pack("HHL4s", tag, typ, count, value)) fp.write(self._pack("HHL4s", tag, typ, count, value))
# -- overwrite here for multi-page -- # -- overwrite here for multi-page --
@ -763,10 +755,9 @@ class TiffImageFile(ImageFile.ImageFile):
self._n_frames = None self._n_frames = None
self._is_animated = None self._is_animated = None
if DEBUG: logger.debug("*** TiffImageFile._open ***")
print("*** TiffImageFile._open ***") logger.debug("- __first: %s", self.__first)
print("- __first:", self.__first) logger.debug("- ifh: %s", ifh)
print("- ifh: ", ifh)
# and load the first frame # and load the first frame
self._seek(0) self._seek(0)
@ -811,17 +802,15 @@ 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, " "Seeking to frame %s, on frame %s, __next %s, location: %s",
"__next %s, location: %s" % frame, self.__frame, self.__next, self.fp.tell())
(frame, self.__frame, self.__next, self.fp.tell()))
# reset python3 buffered io handle in case fp # reset python3 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
self.__frame += 1 self.__frame += 1
@ -901,20 +890,17 @@ 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 IOError if there's no underlying fp. Easier to # that returns an IOError 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 hasattr(self.fp, "fileno"): elif hasattr(self.fp, "fileno"):
# 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.")
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")
# 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())
@ -949,20 +935,18 @@ 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: %s", self._compression)
print("- compression:", self._compression) logger.debug("- photometric_interpretation: %s", photo)
print("- photometric_interpretation:", photo) logger.debug("- planar_configuration: %s", self._planar_configuration)
print("- planar_configuration:", self._planar_configuration) logger.debug("- fill_order: %s", fillorder)
print("- fill_order:", fillorder)
# size # size
xsize = self.tag_v2.get(IMAGEWIDTH) xsize = self.tag_v2.get(IMAGEWIDTH)
ysize = self.tag_v2.get(IMAGELENGTH) ysize = self.tag_v2.get(IMAGELENGTH)
self.size = xsize, ysize self.size = xsize, ysize
if DEBUG: logger.debug("- size: %s", self.size)
print("- size:", self.size)
format = self.tag_v2.get(SAMPLEFORMAT, (1,)) format = self.tag_v2.get(SAMPLEFORMAT, (1,))
if len(format) > 1 and max(format) == min(format) == 1: if len(format) > 1 and max(format) == min(format) == 1:
@ -979,18 +963,15 @@ class TiffImageFile(ImageFile.ImageFile):
self.tag_v2.get(BITSPERSAMPLE, (1,)), self.tag_v2.get(BITSPERSAMPLE, (1,)),
self.tag_v2.get(EXTRASAMPLES, ()) self.tag_v2.get(EXTRASAMPLES, ())
) )
if DEBUG: logger.debug("format key: %s", 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: %s", rawmode)
print("- raw mode:", rawmode) logger.debug("- pil mode: %s", self.mode)
print("- pil mode:", self.mode)
self.info["compression"] = self._compression self.info["compression"] = self._compression
@ -1065,13 +1046,10 @@ class TiffImageFile(ImageFile.ImageFile):
# bits, so stripes of the image are reversed. See # bits, so stripes of the image are reversed. See
# https://github.com/python-pillow/Pillow/issues/279 # https://github.com/python-pillow/Pillow/issues/279
if fillorder == 2: if fillorder == 2:
key = ( key = (self.tag_v2.prefix, photo, format, 1,
self.tag_v2.prefix, photo, format, 1, self.tag_v2.get(BITSPERSAMPLE, (1,)),
self.tag_v2.get(BITSPERSAMPLE, (1,)), self.tag_v2.get(EXTRASAMPLES, ()))
self.tag_v2.get(EXTRASAMPLES, ()) logger.debug("format key: %s", key)
)
if DEBUG:
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
@ -1099,8 +1077,7 @@ class TiffImageFile(ImageFile.ImageFile):
(self._compression, (self._compression,
(0, min(y, ysize), w, min(y+h, ysize)), (0, min(y, ysize), w, min(y+h, ysize)),
offsets[i], a)) offsets[i], a))
if DEBUG: logger.debug("tiles: %s", self.tile)
print("tiles: ", self.tile)
y = y + h y = y + h
if y >= self.size[1]: if y >= self.size[1]:
x = y = 0 x = y = 0
@ -1128,8 +1105,7 @@ class TiffImageFile(ImageFile.ImageFile):
l += 1 l += 1
a = None a = None
else: else:
if DEBUG: logger.debug("- unsupported data organization")
print("- unsupported data organization")
raise SyntaxError("unknown data organization") raise SyntaxError("unknown data organization")
# fixup palette descriptor # fixup palette descriptor
@ -1192,8 +1168,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:
@ -1266,9 +1241,8 @@ def _save(im, fp, filename):
ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1) ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
if libtiff: if libtiff:
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:
@ -1297,8 +1271,7 @@ def _save(im, fp, filename):
else: else:
atts[k] = v atts[k] = v
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