Skip to content

Commit 124c06d

Browse files
authored
Merge pull request #4550 from radarhere/logging
2 parents 3cc030e + 13dcab0 commit 124c06d

1 file changed

Lines changed: 54 additions & 79 deletions

File tree

src/PIL/TiffImagePlugin.py

Lines changed: 54 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
#
4141
import io
4242
import itertools
43+
import logging
4344
import os
4445
import struct
4546
import warnings
@@ -51,7 +52,7 @@
5152
from ._binary import i8, o8
5253
from .TiffTags import TYPES
5354

54-
DEBUG = False # Needs to be merged with the new logging approach.
55+
logger = logging.getLogger(__name__)
5556

5657
# Set these to true to force use of libtiff for reading or writing.
5758
READ_LIBTIFF = False
@@ -734,29 +735,21 @@ def load(self, fp):
734735
try:
735736
for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]):
736737
tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12))
737-
if DEBUG:
738-
tagname = TiffTags.lookup(tag).name
739-
typname = TYPES.get(typ, "unknown")
740-
print(
741-
"tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ),
742-
end=" ",
743-
)
738+
739+
tagname = TiffTags.lookup(tag).name
740+
typname = TYPES.get(typ, "unknown")
741+
msg = "tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
744742

745743
try:
746744
unit_size, handler = self._load_dispatch[typ]
747745
except KeyError:
748-
if DEBUG:
749-
print("- unsupported type", typ)
746+
logger.debug(msg + " - unsupported type {}".format(typ))
750747
continue # ignore unsupported type
751748
size = count * unit_size
752749
if size > 4:
753750
here = fp.tell()
754751
(offset,) = self._unpack("L", data)
755-
if DEBUG:
756-
print(
757-
"Tag Location: {} - Data Location: {}".format(here, offset),
758-
end=" ",
759-
)
752+
msg += " Tag Location: {} - Data Location: {}".format(here, offset)
760753
fp.seek(offset)
761754
data = ImageFile._safe_read(fp, size)
762755
fp.seek(here)
@@ -769,19 +762,20 @@ def load(self, fp):
769762
"Expecting to read %d bytes but only got %d."
770763
" Skipping tag %s" % (size, len(data), tag)
771764
)
765+
logger.debug(msg)
772766
continue
773767

774768
if not data:
769+
logger.debug(msg)
775770
continue
776771

777772
self._tagdata[tag] = data
778773
self.tagtype[tag] = typ
779774

780-
if DEBUG:
781-
if size > 32:
782-
print("- value: <table: %d bytes>" % size)
783-
else:
784-
print("- value:", self[tag])
775+
msg += " - value: " + (
776+
"<table: %d bytes>" % size if size > 32 else str(data)
777+
)
778+
logger.debug(msg)
785779

786780
(self.next,) = self._unpack("L", self._ensure_read(fp, 4))
787781
except OSError as msg:
@@ -802,21 +796,17 @@ def tobytes(self, offset=0):
802796
if tag == STRIPOFFSETS:
803797
stripoffsets = len(entries)
804798
typ = self.tagtype.get(tag)
805-
if DEBUG:
806-
print("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
799+
logger.debug("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
807800
values = value if isinstance(value, tuple) else (value,)
808801
data = self._write_dispatch[typ](self, *values)
809-
if DEBUG:
810-
tagname = TiffTags.lookup(tag).name
811-
typname = TYPES.get(typ, "unknown")
812-
print(
813-
"save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ),
814-
end=" ",
815-
)
816-
if len(data) >= 16:
817-
print("- value: <table: %d bytes>" % len(data))
818-
else:
819-
print("- value:", values)
802+
803+
tagname = TiffTags.lookup(tag).name
804+
typname = TYPES.get(typ, "unknown")
805+
msg = "save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
806+
msg += " - value: " + (
807+
"<table: %d bytes>" % len(data) if len(data) >= 16 else str(values)
808+
)
809+
logger.debug(msg)
820810

821811
# count is sum of lengths for string and arbitrary data
822812
if typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
@@ -840,8 +830,9 @@ def tobytes(self, offset=0):
840830

841831
# pass 2: write entries to file
842832
for tag, typ, count, value, data in entries:
843-
if DEBUG:
844-
print(tag, typ, count, repr(value), repr(data))
833+
logger.debug(
834+
"{} {} {} {} {}".format(tag, typ, count, repr(value), repr(data))
835+
)
845836
result += self._pack("HHL4s", tag, typ, count, value)
846837

847838
# -- overwrite here for multi-page --
@@ -997,10 +988,9 @@ def _open(self):
997988
self._frame_pos = []
998989
self._n_frames = None
999990

1000-
if DEBUG:
1001-
print("*** TiffImageFile._open ***")
1002-
print("- __first:", self.__first)
1003-
print("- ifh: ", ifh)
991+
logger.debug("*** TiffImageFile._open ***")
992+
logger.debug("- __first: {}".format(self.__first))
993+
logger.debug("- ifh: {}".format(ifh))
1004994

1005995
# and load the first frame
1006996
self._seek(0)
@@ -1031,18 +1021,16 @@ def _seek(self, frame):
10311021
while len(self._frame_pos) <= frame:
10321022
if not self.__next:
10331023
raise EOFError("no more images in TIFF file")
1034-
if DEBUG:
1035-
print(
1036-
"Seeking to frame %s, on frame %s, __next %s, location: %s"
1037-
% (frame, self.__frame, self.__next, self.fp.tell())
1038-
)
1024+
logger.debug(
1025+
"Seeking to frame %s, on frame %s, __next %s, location: %s"
1026+
% (frame, self.__frame, self.__next, self.fp.tell())
1027+
)
10391028
# reset buffered io handle in case fp
10401029
# was passed to libtiff, invalidating the buffer
10411030
self.fp.tell()
10421031
self.fp.seek(self.__next)
10431032
self._frame_pos.append(self.__next)
1044-
if DEBUG:
1045-
print("Loading tags, location: %s" % self.fp.tell())
1033+
logger.debug("Loading tags, location: %s" % self.fp.tell())
10461034
self.tag_v2.load(self.fp)
10471035
self.__next = self.tag_v2.next
10481036
if self.__next == 0:
@@ -1140,21 +1128,18 @@ def _load_libtiff(self):
11401128
# Rearranging for supporting byteio items, since they have a fileno
11411129
# that returns an OSError if there's no underlying fp. Easier to
11421130
# deal with here by reordering.
1143-
if DEBUG:
1144-
print("have getvalue. just sending in a string from getvalue")
1131+
logger.debug("have getvalue. just sending in a string from getvalue")
11451132
n, err = decoder.decode(self.fp.getvalue())
11461133
elif fp:
11471134
# we've got a actual file on disk, pass in the fp.
1148-
if DEBUG:
1149-
print("have fileno, calling fileno version of the decoder.")
1135+
logger.debug("have fileno, calling fileno version of the decoder.")
11501136
if not close_self_fp:
11511137
self.fp.seek(0)
11521138
# 4 bytes, otherwise the trace might error out
11531139
n, err = decoder.decode(b"fpfp")
11541140
else:
11551141
# we have something else.
1156-
if DEBUG:
1157-
print("don't have fileno or getvalue. just reading")
1142+
logger.debug("don't have fileno or getvalue. just reading")
11581143
self.fp.seek(0)
11591144
# UNDONE -- so much for that buffer size thing.
11601145
n, err = decoder.decode(self.fp.read())
@@ -1194,21 +1179,19 @@ def _setup(self):
11941179

11951180
fillorder = self.tag_v2.get(FILLORDER, 1)
11961181

1197-
if DEBUG:
1198-
print("*** Summary ***")
1199-
print("- compression:", self._compression)
1200-
print("- photometric_interpretation:", photo)
1201-
print("- planar_configuration:", self._planar_configuration)
1202-
print("- fill_order:", fillorder)
1203-
print("- YCbCr subsampling:", self.tag.get(530))
1182+
logger.debug("*** Summary ***")
1183+
logger.debug("- compression: {}".format(self._compression))
1184+
logger.debug("- photometric_interpretation: {}".format(photo))
1185+
logger.debug("- planar_configuration: {}".format(self._planar_configuration))
1186+
logger.debug("- fill_order: {}".format(fillorder))
1187+
logger.debug("- YCbCr subsampling: {}".format(self.tag.get(530)))
12041188

12051189
# size
12061190
xsize = int(self.tag_v2.get(IMAGEWIDTH))
12071191
ysize = int(self.tag_v2.get(IMAGELENGTH))
12081192
self._size = xsize, ysize
12091193

1210-
if DEBUG:
1211-
print("- size:", self.size)
1194+
logger.debug("- size: {}".format(self.size))
12121195

12131196
sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
12141197
if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1:
@@ -1242,18 +1225,15 @@ def _setup(self):
12421225
bps_tuple,
12431226
extra_tuple,
12441227
)
1245-
if DEBUG:
1246-
print("format key:", key)
1228+
logger.debug("format key: {}".format(key))
12471229
try:
12481230
self.mode, rawmode = OPEN_INFO[key]
12491231
except KeyError:
1250-
if DEBUG:
1251-
print("- unsupported format")
1232+
logger.debug("- unsupported format")
12521233
raise SyntaxError("unknown pixel mode")
12531234

1254-
if DEBUG:
1255-
print("- raw mode:", rawmode)
1256-
print("- pil mode:", self.mode)
1235+
logger.debug("- raw mode: {}".format(rawmode))
1236+
logger.debug("- pil mode: {}".format(self.mode))
12571237

12581238
self.info["compression"] = self._compression
12591239

@@ -1294,8 +1274,7 @@ def _setup(self):
12941274
if fillorder == 2:
12951275
# Replace fillorder with fillorder=1
12961276
key = key[:3] + (1,) + key[4:]
1297-
if DEBUG:
1298-
print("format key:", key)
1277+
logger.debug("format key: {}".format(key))
12991278
# this should always work, since all the
13001279
# fillorder==2 modes have a corresponding
13011280
# fillorder=1 mode
@@ -1357,8 +1336,7 @@ def _setup(self):
13571336
x = y = 0
13581337
layer += 1
13591338
else:
1360-
if DEBUG:
1361-
print("- unsupported data organization")
1339+
logger.debug("- unsupported data organization")
13621340
raise SyntaxError("unknown data organization")
13631341

13641342
# Fix up info.
@@ -1438,8 +1416,7 @@ def _save(im, fp, filename):
14381416

14391417
# write any arbitrary tags passed in as an ImageFileDirectory
14401418
info = im.encoderinfo.get("tiffinfo", {})
1441-
if DEBUG:
1442-
print("Tiffinfo Keys: %s" % list(info))
1419+
logger.debug("Tiffinfo Keys: %s" % list(info))
14431420
if isinstance(info, ImageFileDirectory_v1):
14441421
info = info.to_v2()
14451422
for key in info:
@@ -1524,9 +1501,8 @@ def _save(im, fp, filename):
15241501
)
15251502
ifd[JPEGQUALITY] = quality
15261503

1527-
if DEBUG:
1528-
print("Saving using libtiff encoder")
1529-
print("Items: %s" % sorted(ifd.items()))
1504+
logger.debug("Saving using libtiff encoder")
1505+
logger.debug("Items: %s" % sorted(ifd.items()))
15301506
_fp = 0
15311507
if hasattr(fp, "fileno"):
15321508
try:
@@ -1588,8 +1564,7 @@ def _save(im, fp, filename):
15881564
else:
15891565
atts[tag] = value
15901566

1591-
if DEBUG:
1592-
print("Converted items: %s" % sorted(atts.items()))
1567+
logger.debug("Converted items: %s" % sorted(atts.items()))
15931568

15941569
# libtiff always expects the bytes in native order.
15951570
# we're storing image byte order. So, if the rawmode

0 commit comments

Comments
 (0)