W Pub: Python Renamer EXIF

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Library to extract EXIF information from digital camera image files
  5. # http://sourceforge.net/projects/exif-py-3/
  6. #
  7. # VERSION 1.1.0
  8. #
  9. # To use this library call with:
  10. #    f = open(path_name, 'rb')
  11. #    tags = EXIF.process_file(f)
  12. #
  13. # To ignore MakerNote tags, pass the -q or --quick
  14. # command line arguments, or as
  15. #    tags = EXIF.process_file(f, details=False)
  16. #
  17. # To stop processing after a certain tag is retrieved,
  18. # pass the -t TAG or --stop-tag TAG argument, or as
  19. #    tags = EXIF.process_file(f, stop_tag='TAG')
  20. #
  21. # where TAG is a valid tag name, ex 'DateTimeOriginal'
  22. #
  23. # These 2 are useful when you are retrieving a large list of images
  24. #
  25. #
  26. # To return an error on invalid tags,
  27. # pass the -s or --strict argument, or as
  28. #    tags = EXIF.process_file(f, strict=True)
  29. #
  30. # Otherwise these tags will be ignored
  31. #
  32. # Returned tags will be a dictionary mapping names of EXIF tags to their
  33. # values in the file named by path_name.  You can process the tags
  34. # as you wish.  In particular, you can iterate through all the tags with:
  35. #     for tag in tags.keys():
  36. #         if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename',
  37. #                        'EXIF MakerNote'):
  38. #             print "Key: %s, value %s" % (tag, tags[tag])
  39. # (This code uses the if statement to avoid printing out a few of the
  40. # tags that tend to be long or boring.)
  41. #
  42. # The tags dictionary will include keys for all of the usual EXIF
  43. # tags, and will also include keys for Makernotes used by some
  44. # cameras, for which we have a good specification.
  45. #
  46. # Note that the dictionary keys are the IFD name followed by the
  47. # tag name. For example:
  48. # 'EXIF DateTimeOriginal', 'Image Orientation', 'MakerNote FocusMode'
  49. #
  50. # Copyright (c) 2002-2007 Gene Cash All rights reserved
  51. # Copyright (c) 2007-2008 Ianaré Sévi All rights reserved
  52. #
  53. # Redistribution and use in source and binary forms, with or without
  54. # modification, are permitted provided that the following conditions
  55. # are met:
  56. #
  57. #  1. Redistributions of source code must retain the above copyright
  58. #     notice, this list of conditions and the following disclaimer.
  59. #
  60. #  2. Redistributions in binary form must reproduce the above
  61. #     copyright notice, this list of conditions and the following
  62. #     disclaimer in the documentation and/or other materials provided
  63. #     with the distribution.
  64. #
  65. #  3. Neither the name of the authors nor the names of its contributors
  66. #     may be used to endorse or promote products derived from this
  67. #     software without specific prior written permission.
  68. #
  69. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  70. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  71. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  72. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  73. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  74. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  75. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  76. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  77. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  78. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  79. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  80. #
  81. #
  82. # ----- See 'changes.txt' file for all contributors and changes ----- #
  83. #
  84.  
  85. import collections
  86.  
  87. # Don't throw an exception when given an out of range character.
  88. def make_string(seq):
  89.     str = ''
  90.     for c in seq:
  91.         # Screen out non-printing characters
  92.         if 32 <= c and c < 256:
  93.             str += chr(c)
  94.     # If no printing chars
  95.     if not str:
  96.         return seq
  97.     return str
  98.  
  99. # Special version to deal with the code in the first 8 bytes of a user comment.
  100. # First 8 bytes gives coding system e.g. ASCII vs. JIS vs Unicode
  101. def make_string_uc(seq):
  102.     code = seq[0:8]
  103.     seq = seq[8:]
  104.     # Of course, this is only correct if ASCII, and the standard explicitly
  105.     # allows JIS and Unicode.
  106.     return make_string(seq)
  107.  
  108. # field type descriptions as (length, abbreviation, full name) tuples
  109. FIELD_TYPES = (
  110.     (0, 'X', 'Proprietary'), # no such type
  111.     (1, 'B', 'Byte'),
  112.     (1, 'A', 'ASCII'),
  113.     (2, 'S', 'Short'),
  114.     (4, 'L', 'Long'),
  115.     (8, 'R', 'Ratio'),
  116.     (1, 'SB', 'Signed Byte'),
  117.     (1, 'U', 'Undefined'),
  118.     (2, 'SS', 'Signed Short'),
  119.     (4, 'SL', 'Signed Long'),
  120.     (8, 'SR', 'Signed Ratio'),
  121.     )
  122.  
  123. # dictionary of main EXIF tag names
  124. # first element of tuple is tag name, optional second element is
  125. # another dictionary giving names to values
  126. EXIF_TAGS = {
  127.     0x0100: ('ImageWidth', ),
  128.     0x0101: ('ImageLength', ),
  129.     0x0102: ('BitsPerSample', ),
  130.     0x0103: ('Compression',
  131.              {1: 'Uncompressed',
  132.               2: 'CCITT 1D',
  133.               3: 'T4/Group 3 Fax',
  134.               4: 'T6/Group 4 Fax',
  135.               5: 'LZW',
  136.               6: 'JPEG (old-style)',
  137.               7: 'JPEG',
  138.               8: 'Adobe Deflate',
  139.               9: 'JBIG B&W',
  140.               10: 'JBIG Color',
  141.               32766: 'Next',
  142.               32769: 'Epson ERF Compressed',
  143.               32771: 'CCIRLEW',
  144.               32773: 'PackBits',
  145.               32809: 'Thunderscan',
  146.               32895: 'IT8CTPAD',
  147.               32896: 'IT8LW',
  148.               32897: 'IT8MP',
  149.               32898: 'IT8BL',
  150.               32908: 'PixarFilm',
  151.               32909: 'PixarLog',
  152.               32946: 'Deflate',
  153.               32947: 'DCS',
  154.               34661: 'JBIG',
  155.               34676: 'SGILog',
  156.               34677: 'SGILog24',
  157.               34712: 'JPEG 2000',
  158.               34713: 'Nikon NEF Compressed',
  159.               65000: 'Kodak DCR Compressed',
  160.               65535: 'Pentax PEF Compressed'}),
  161.     0x0106: ('PhotometricInterpretation', ),
  162.     0x0107: ('Thresholding', ),
  163.     0x010A: ('FillOrder', ),
  164.     0x010D: ('DocumentName', ),
  165.     0x010E: ('ImageDescription', ),
  166.     0x010F: ('Make', ),
  167.     0x0110: ('Model', ),
  168.     0x0111: ('StripOffsets', ),
  169.     0x0112: ('Orientation',
  170.              {1: 'Horizontal (normal)',
  171.               2: 'Mirrored horizontal',
  172.               3: 'Rotated 180',
  173.               4: 'Mirrored vertical',
  174.               5: 'Mirrored horizontal then rotated 90 CCW',
  175.               6: 'Rotated 90 CW',
  176.               7: 'Mirrored horizontal then rotated 90 CW',
  177.               8: 'Rotated 90 CCW'}),
  178.     0x0115: ('SamplesPerPixel', ),
  179.     0x0116: ('RowsPerStrip', ),
  180.     0x0117: ('StripByteCounts', ),
  181.     0x011A: ('XResolution', ),
  182.     0x011B: ('YResolution', ),
  183.     0x011C: ('PlanarConfiguration', ),
  184.     0x011D: ('PageName', make_string),
  185.     0x0128: ('ResolutionUnit',
  186.              {1: 'Not Absolute',
  187.               2: 'Pixels/Inch',
  188.               3: 'Pixels/Centimeter'}),
  189.     0x012D: ('TransferFunction', ),
  190.     0x0131: ('Software', ),
  191.     0x0132: ('DateTime', ),
  192.     0x013B: ('Artist', ),
  193.     0x013E: ('WhitePoint', ),
  194.     0x013F: ('PrimaryChromaticities', ),
  195.     0x0156: ('TransferRange', ),
  196.     0x0200: ('JPEGProc', ),
  197.     0x0201: ('JPEGInterchangeFormat', ),
  198.     0x0202: ('JPEGInterchangeFormatLength', ),
  199.     0x0211: ('YCbCrCoefficients', ),
  200.     0x0212: ('YCbCrSubSampling', ),
  201.     0x0213: ('YCbCrPositioning',
  202.              {1: 'Centered',
  203.               2: 'Co-sited'}),
  204.     0x0214: ('ReferenceBlackWhite', ),
  205.  
  206.     0x4746: ('Rating', ),
  207.  
  208.     0x828D: ('CFARepeatPatternDim', ),
  209.     0x828E: ('CFAPattern', ),
  210.     0x828F: ('BatteryLevel', ),
  211.     0x8298: ('Copyright', ),
  212.     0x829A: ('ExposureTime', ),
  213.     0x829D: ('FNumber', ),
  214.     0x83BB: ('IPTC/NAA', ),
  215.     0x8769: ('ExifOffset', ),
  216.     0x8773: ('InterColorProfile', ),
  217.     0x8822: ('ExposureProgram',
  218.              {0: 'Unidentified',
  219.               1: 'Manual',
  220.               2: 'Program Normal',
  221.               3: 'Aperture Priority',
  222.               4: 'Shutter Priority',
  223.               5: 'Program Creative',
  224.               6: 'Program Action',
  225.               7: 'Portrait Mode',
  226.               8: 'Landscape Mode'}),
  227.     0x8824: ('SpectralSensitivity', ),
  228.     0x8825: ('GPSInfo', ),
  229.     0x8827: ('ISOSpeedRatings', ),
  230.     0x8828: ('OECF', ),
  231.     0x9000: ('ExifVersion', make_string),
  232.     0x9003: ('DateTimeOriginal', ),
  233.     0x9004: ('DateTimeDigitized', ),
  234.     0x9101: ('ComponentsConfiguration',
  235.              {0: '',
  236.               1: 'Y',
  237.               2: 'Cb',
  238.               3: 'Cr',
  239.               4: 'Red',
  240.               5: 'Green',
  241.               6: 'Blue'}),
  242.     0x9102: ('CompressedBitsPerPixel', ),
  243.     0x9201: ('ShutterSpeedValue', ),
  244.     0x9202: ('ApertureValue', ),
  245.     0x9203: ('BrightnessValue', ),
  246.     0x9204: ('ExposureBiasValue', ),
  247.     0x9205: ('MaxApertureValue', ),
  248.     0x9206: ('SubjectDistance', ),
  249.     0x9207: ('MeteringMode',
  250.              {0: 'Unidentified',
  251.               1: 'Average',
  252.               2: 'CenterWeightedAverage',
  253.               3: 'Spot',
  254.               4: 'MultiSpot',
  255.               5: 'Pattern'}),
  256.     0x9208: ('LightSource',
  257.              {0: 'Unknown',
  258.               1: 'Daylight',
  259.               2: 'Fluorescent',
  260.               3: 'Tungsten',
  261.               9: 'Fine Weather',
  262.               10: 'Flash',
  263.               11: 'Shade',
  264.               12: 'Daylight Fluorescent',
  265.               13: 'Day White Fluorescent',
  266.               14: 'Cool White Fluorescent',
  267.               15: 'White Fluorescent',
  268.               17: 'Standard Light A',
  269.               18: 'Standard Light B',
  270.               19: 'Standard Light C',
  271.               20: 'D55',
  272.               21: 'D65',
  273.               22: 'D75',
  274.               255: 'Other'}),
  275.     0x9209: ('Flash',
  276.              {0: 'No',
  277.               1: 'Fired',
  278.               5: 'Fired (?)', # no return sensed
  279.               7: 'Fired (!)', # return sensed
  280.               9: 'Fill Fired',
  281.               13: 'Fill Fired (?)',
  282.               15: 'Fill Fired (!)',
  283.               16: 'Off',
  284.               24: 'Auto Off',
  285.               25: 'Auto Fired',
  286.               29: 'Auto Fired (?)',
  287.               31: 'Auto Fired (!)',
  288.               32: 'Not Available'}),
  289.     0x920A: ('FocalLength', ),
  290.     0x9214: ('SubjectArea', ),
  291.     0x927C: ('MakerNote', ),
  292.     0x9286: ('UserComment', make_string_uc),
  293.     0x9290: ('SubSecTime', ),
  294.     0x9291: ('SubSecTimeOriginal', ),
  295.     0x9292: ('SubSecTimeDigitized', ),
  296.  
  297.     # used by Windows Explorer
  298.     0x9C9B: ('XPTitle', ),
  299.     0x9C9C: ('XPComment', ),
  300.     0x9C9D: ('XPAuthor', ), #(ignored by Windows Explorer if Artist exists)
  301.     0x9C9E: ('XPKeywords', ),
  302.     0x9C9F: ('XPSubject', ),
  303.  
  304.     0xA000: ('FlashPixVersion', make_string),
  305.     0xA001: ('ColorSpace',
  306.              {1: 'sRGB',
  307.               2: 'Adobe RGB',
  308.               65535: 'Uncalibrated'}),
  309.     0xA002: ('ExifImageWidth', ),
  310.     0xA003: ('ExifImageLength', ),
  311.     0xA005: ('InteroperabilityOffset', ),
  312.     0xA20B: ('FlashEnergy', ),               # 0x920B in TIFF/EP
  313.     0xA20C: ('SpatialFrequencyResponse', ),  # 0x920C
  314.     0xA20E: ('FocalPlaneXResolution', ),     # 0x920E
  315.     0xA20F: ('FocalPlaneYResolution', ),     # 0x920F
  316.     0xA210: ('FocalPlaneResolutionUnit', ),  # 0x9210
  317.     0xA214: ('SubjectLocation', ),           # 0x9214
  318.     0xA215: ('ExposureIndex', ),             # 0x9215
  319.     0xA217: ('SensingMethod',                # 0x9217
  320.              {1: 'Not defined',
  321.               2: 'One-chip color area',
  322.               3: 'Two-chip color area',
  323.               4: 'Three-chip color area',
  324.               5: 'Color sequential area',
  325.               7: 'Trilinear',
  326.               8: 'Color sequential linear'}),            
  327.     0xA300: ('FileSource',
  328.              {1: 'Film Scanner',
  329.               2: 'Reflection Print Scanner',
  330.               3: 'Digital Camera'}),
  331.     0xA301: ('SceneType',
  332.              {1: 'Directly Photographed'}),
  333.     0xA302: ('CVAPattern', ),
  334.     0xA401: ('CustomRendered',
  335.              {0: 'Normal',
  336.               1: 'Custom'}),
  337.     0xA402: ('ExposureMode',
  338.              {0: 'Auto Exposure',
  339.               1: 'Manual Exposure',
  340.               2: 'Auto Bracket'}),
  341.     0xA403: ('WhiteBalance',
  342.              {0: 'Auto',
  343.               1: 'Manual'}),
  344.     0xA404: ('DigitalZoomRatio', ),
  345.     0xA405: ('FocalLengthIn35mmFilm', ),
  346.     0xA406: ('SceneCaptureType',
  347.              {0: 'Standard',
  348.               1: 'Landscape',
  349.               2: 'Portrait',
  350.               3: 'Night)'}),
  351.     0xA407: ('GainControl',
  352.              {0: 'None',
  353.               1: 'Low gain up',
  354.               2: 'High gain up',
  355.               3: 'Low gain down',
  356.               4: 'High gain down'}),
  357.     0xA408: ('Contrast',
  358.              {0: 'Normal',
  359.               1: 'Soft',
  360.               2: 'Hard'}),
  361.     0xA409: ('Saturation',
  362.              {0: 'Normal',
  363.               1: 'Soft',
  364.               2: 'Hard'}),
  365.     0xA40A: ('Sharpness',
  366.              {0: 'Normal',
  367.               1: 'Soft',
  368.               2: 'Hard'}),
  369.     0xA40B: ('DeviceSettingDescription', ),
  370.     0xA40C: ('SubjectDistanceRange', ),
  371.     0xA500: ('Gamma', ),
  372.     0xC4A5: ('PrintIM', ),
  373.     0xEA1C:     ('Padding', ),
  374.     }
  375.  
  376. # interoperability tags
  377. INTR_TAGS = {
  378.     0x0001: ('InteroperabilityIndex', ),
  379.     0x0002: ('InteroperabilityVersion', ),
  380.     0x1000: ('RelatedImageFileFormat', ),
  381.     0x1001: ('RelatedImageWidth', ),
  382.     0x1002: ('RelatedImageLength', ),
  383.     }
  384.  
  385. # GPS tags (not used yet, haven't seen camera with GPS)
  386. GPS_TAGS = {
  387.     0x0000: ('GPSVersionID', ),
  388.     0x0001: ('GPSLatitudeRef', ),
  389.     0x0002: ('GPSLatitude', ),
  390.     0x0003: ('GPSLongitudeRef', ),
  391.     0x0004: ('GPSLongitude', ),
  392.     0x0005: ('GPSAltitudeRef', ),
  393.     0x0006: ('GPSAltitude', ),
  394.     0x0007: ('GPSTimeStamp', ),
  395.     0x0008: ('GPSSatellites', ),
  396.     0x0009: ('GPSStatus', ),
  397.     0x000A: ('GPSMeasureMode', ),
  398.     0x000B: ('GPSDOP', ),
  399.     0x000C: ('GPSSpeedRef', ),
  400.     0x000D: ('GPSSpeed', ),
  401.     0x000E: ('GPSTrackRef', ),
  402.     0x000F: ('GPSTrack', ),
  403.     0x0010: ('GPSImgDirectionRef', ),
  404.     0x0011: ('GPSImgDirection', ),
  405.     0x0012: ('GPSMapDatum', ),
  406.     0x0013: ('GPSDestLatitudeRef', ),
  407.     0x0014: ('GPSDestLatitude', ),
  408.     0x0015: ('GPSDestLongitudeRef', ),
  409.     0x0016: ('GPSDestLongitude', ),
  410.     0x0017: ('GPSDestBearingRef', ),
  411.     0x0018: ('GPSDestBearing', ),
  412.     0x0019: ('GPSDestDistanceRef', ),
  413.     0x001A: ('GPSDestDistance', ),
  414.     0x001D: ('GPSDate', ),
  415.     }
  416.  
  417. # Ignore these tags when quick processing
  418. # 0x927C is MakerNote Tags
  419. # 0x9286 is user comment
  420. IGNORE_TAGS=(0x9286, 0x927C)
  421.  
  422. # http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp
  423. def nikon_ev_bias(seq):
  424.     # First digit seems to be in steps of 1/6 EV.
  425.     # Does the third value mean the step size?  It is usually 6,
  426.     # but it is 12 for the ExposureDifference.
  427.     #
  428.     # Check for an error condition that could cause a crash.
  429.     # This only happens if something has gone really wrong in
  430.     # reading the Nikon MakerNote.
  431.     if len( seq ) < 4 : return ""
  432.     #
  433.     if seq == [252, 1, 6, 0]:
  434.         return "-2/3 EV"
  435.     if seq == [253, 1, 6, 0]:
  436.         return "-1/2 EV"
  437.     if seq == [254, 1, 6, 0]:
  438.         return "-1/3 EV"
  439.     if seq == [0, 1, 6, 0]:
  440.         return "0 EV"
  441.     if seq == [2, 1, 6, 0]:
  442.         return "+1/3 EV"
  443.     if seq == [3, 1, 6, 0]:
  444.         return "+1/2 EV"
  445.     if seq == [4, 1, 6, 0]:
  446.         return "+2/3 EV"
  447.     # Handle combinations not in the table.
  448.     a = seq[0]
  449.     # Causes headaches for the +/- logic, so special case it.
  450.     if a == 0:
  451.         return "0 EV"
  452.     if a > 127:
  453.         a = 256 - a
  454.         ret_str = "-"
  455.     else:
  456.         ret_str = "+"
  457.     b = seq[2]  # Assume third value means the step size
  458.     whole = a / b
  459.     a = a % b
  460.     if whole != 0:
  461.         ret_str = ret_str + str(whole) + " "
  462.     if a == 0:
  463.         ret_str = ret_str + "EV"
  464.     else:
  465.         r = Ratio(a, b)
  466.         ret_str = ret_str + r.__repr__() + " EV"
  467.     return ret_str
  468.  
  469. # Nikon E99x MakerNote Tags
  470. MAKERNOTE_NIKON_NEWER_TAGS={
  471.     0x0001: ('MakernoteVersion', make_string),  # Sometimes binary
  472.     0x0002: ('ISOSetting', make_string),
  473.     0x0003: ('ColorMode', ),
  474.     0x0004: ('Quality', ),
  475.     0x0005: ('Whitebalance', ),
  476.     0x0006: ('ImageSharpening', ),
  477.     0x0007: ('FocusMode', ),
  478.     0x0008: ('FlashSetting', ),
  479.     0x0009: ('AutoFlashMode', ),
  480.     0x000B: ('WhiteBalanceBias', ),
  481.     0x000C: ('WhiteBalanceRBCoeff', ),
  482.     0x000D: ('ProgramShift', nikon_ev_bias),
  483.     # Nearly the same as the other EV vals, but step size is 1/12 EV (?)
  484.     0x000E: ('ExposureDifference', nikon_ev_bias),
  485.     0x000F: ('ISOSelection', ),
  486.     0x0011: ('NikonPreview', ),
  487.     0x0012: ('FlashCompensation', nikon_ev_bias),
  488.     0x0013: ('ISOSpeedRequested', ),
  489.     0x0016: ('PhotoCornerCoordinates', ),
  490.     # 0x0017: Unknown, but most likely an EV value
  491.     0x0018: ('FlashBracketCompensationApplied', nikon_ev_bias),
  492.     0x0019: ('AEBracketCompensationApplied', ),
  493.     0x001A: ('ImageProcessing', ),
  494.     0x001B: ('CropHiSpeed', ),
  495.     0x001D: ('SerialNumber', ), # Conflict with 0x00A0 ?
  496.     0x001E: ('ColorSpace', ),
  497.     0x001F: ('VRInfo', ),
  498.     0x0020: ('ImageAuthentication', ),
  499.     0x0022: ('ActiveDLighting', ),
  500.     0x0023: ('PictureControl', ),
  501.     0x0024: ('WorldTime', ),
  502.     0x0025: ('ISOInfo', ),
  503.     0x0080: ('ImageAdjustment', ),
  504.     0x0081: ('ToneCompensation', ),
  505.     0x0082: ('AuxiliaryLens', ),
  506.     0x0083: ('LensType', ),
  507.     0x0084: ('LensMinMaxFocalMaxAperture', ),
  508.     0x0085: ('ManualFocusDistance', ),
  509.     0x0086: ('DigitalZoomFactor', ),
  510.     0x0087: ('FlashMode',
  511.              {0x00: 'Did Not Fire',
  512.               0x01: 'Fired, Manual',
  513.               0x07: 'Fired, External',
  514.               0x08: 'Fired, Commander Mode ',
  515.               0x09: 'Fired, TTL Mode'}),
  516.     0x0088: ('AFFocusPosition',
  517.              {0x0000: 'Center',
  518.               0x0100: 'Top',
  519.               0x0200: 'Bottom',
  520.               0x0300: 'Left',
  521.               0x0400: 'Right'}),
  522.     0x0089: ('BracketingMode',
  523.              {0x00: 'Single frame, no bracketing',
  524.               0x01: 'Continuous, no bracketing',
  525.               0x02: 'Timer, no bracketing',
  526.               0x10: 'Single frame, exposure bracketing',
  527.               0x11: 'Continuous, exposure bracketing',
  528.               0x12: 'Timer, exposure bracketing',
  529.               0x40: 'Single frame, white balance bracketing',
  530.               0x41: 'Continuous, white balance bracketing',
  531.               0x42: 'Timer, white balance bracketing'}),
  532.     0x008A: ('AutoBracketRelease', ),
  533.     0x008B: ('LensFStops', ),
  534.     0x008C: ('NEFCurve1', ),    # ExifTool calls this 'ContrastCurve'
  535.     0x008D: ('ColorMode', ),
  536.     0x008F: ('SceneMode', ),
  537.     0x0090: ('LightingType', ),
  538.     0x0091: ('ShotInfo', ),     # First 4 bytes are a version number in ASCII
  539.     0x0092: ('HueAdjustment', ),
  540.     # ExifTool calls this 'NEFCompression', should be 1-4
  541.     0x0093: ('Compression', ),
  542.     0x0094: ('Saturation',
  543.              {-3: 'B&W',
  544.               -2: '-2',
  545.               -1: '-1',
  546.               0: '0',
  547.               1: '1',
  548.               2: '2'}),
  549.     0x0095: ('NoiseReduction', ),
  550.     0x0096: ('NEFCurve2', ),    # ExifTool calls this 'LinearizationTable'
  551.     0x0097: ('ColorBalance', ), # First 4 bytes are a version number in ASCII
  552.     0x0098: ('LensData', ),     # First 4 bytes are a version number in ASCII
  553.     0x0099: ('RawImageCenter', ),
  554.     0x009A: ('SensorPixelSize', ),
  555.     0x009C: ('Scene Assist', ),
  556.     0x009E: ('RetouchHistory', ),
  557.     0x00A0: ('SerialNumber', ),
  558.     0x00A2: ('ImageDataSize', ),
  559.     # 00A3: unknown - a single byte 0
  560.     # 00A4: In NEF, looks like a 4 byte ASCII version number ('0200')
  561.     0x00A5: ('ImageCount', ),
  562.     0x00A6: ('DeletedImageCount', ),
  563.     0x00A7: ('TotalShutterReleases', ),
  564.     # First 4 bytes are a version number in ASCII, with version specific
  565.     # info to follow.  Its hard to treat it as a string due to embedded nulls.
  566.     0x00A8: ('FlashInfo', ),
  567.     0x00A9: ('ImageOptimization', ),
  568.     0x00AA: ('Saturation', ),
  569.     0x00AB: ('DigitalVariProgram', ),
  570.     0x00AC: ('ImageStabilization', ),
  571.     0x00AD: ('Responsive AF', ),        # 'AFResponse'
  572.     0x00B0: ('MultiExposure', ),
  573.     0x00B1: ('HighISONoiseReduction', ),
  574.     0x00B7: ('AFInfo', ),
  575.     0x00B8: ('FileInfo', ),
  576.     # 00B9: unknown
  577.     0x0100: ('DigitalICE', ),
  578.     0x0103: ('PreviewCompression',
  579.              {1: 'Uncompressed',
  580.               2: 'CCITT 1D',
  581.               3: 'T4/Group 3 Fax',
  582.               4: 'T6/Group 4 Fax',
  583.               5: 'LZW',
  584.               6: 'JPEG (old-style)',
  585.               7: 'JPEG',
  586.               8: 'Adobe Deflate',
  587.               9: 'JBIG B&W',
  588.               10: 'JBIG Color',
  589.               32766: 'Next',
  590.               32769: 'Epson ERF Compressed',
  591.               32771: 'CCIRLEW',
  592.               32773: 'PackBits',
  593.               32809: 'Thunderscan',
  594.               32895: 'IT8CTPAD',
  595.               32896: 'IT8LW',
  596.               32897: 'IT8MP',
  597.               32898: 'IT8BL',
  598.               32908: 'PixarFilm',
  599.               32909: 'PixarLog',
  600.               32946: 'Deflate',
  601.               32947: 'DCS',
  602.               34661: 'JBIG',
  603.               34676: 'SGILog',
  604.               34677: 'SGILog24',
  605.               34712: 'JPEG 2000',
  606.               34713: 'Nikon NEF Compressed',
  607.               65000: 'Kodak DCR Compressed',
  608.               65535: 'Pentax PEF Compressed',}),
  609.     0x0201: ('PreviewImageStart', ),
  610.     0x0202: ('PreviewImageLength', ),
  611.     0x0213: ('PreviewYCbCrPositioning',
  612.              {1: 'Centered',
  613.               2: 'Co-sited'}),
  614.     0x0010: ('DataDump', ),
  615.     }
  616.  
  617. MAKERNOTE_NIKON_OLDER_TAGS = {
  618.     0x0003: ('Quality',
  619.              {1: 'VGA Basic',
  620.               2: 'VGA Normal',
  621.               3: 'VGA Fine',
  622.               4: 'SXGA Basic',
  623.               5: 'SXGA Normal',
  624.               6: 'SXGA Fine'}),
  625.     0x0004: ('ColorMode',
  626.              {1: 'Color',
  627.               2: 'Monochrome'}),
  628.     0x0005: ('ImageAdjustment',
  629.              {0: 'Normal',
  630.               1: 'Bright+',
  631.               2: 'Bright-',
  632.               3: 'Contrast+',
  633.               4: 'Contrast-'}),
  634.     0x0006: ('CCDSpeed',
  635.              {0: 'ISO 80',
  636.               2: 'ISO 160',
  637.               4: 'ISO 320',
  638.               5: 'ISO 100'}),
  639.     0x0007: ('WhiteBalance',
  640.              {0: 'Auto',
  641.               1: 'Preset',
  642.               2: 'Daylight',
  643.               3: 'Incandescent',
  644.               4: 'Fluorescent',
  645.               5: 'Cloudy',
  646.               6: 'Speed Light'}),
  647.     }
  648.  
  649. # decode Olympus SpecialMode tag in MakerNote
  650. def olympus_special_mode(v):
  651.     a={
  652.         0: 'Normal',
  653.         1: 'Unknown',
  654.         2: 'Fast',
  655.         3: 'Panorama'}
  656.     b={
  657.         0: 'Non-panoramic',
  658.         1: 'Left to right',
  659.         2: 'Right to left',
  660.         3: 'Bottom to top',
  661.         4: 'Top to bottom'}
  662.     if v[0] not in a or v[2] not in b:
  663.         return v
  664.     return '%s - sequence %d - %s' % (a[v[0]], v[1], b[v[2]])
  665.  
  666. MAKERNOTE_OLYMPUS_TAGS={
  667.     # ah HAH! those sneeeeeaky bastids! this is how they get past the fact
  668.     # that a JPEG thumbnail is not allowed in an uncompressed TIFF file
  669.     0x0100: ('JPEGThumbnail', ),
  670.     0x0200: ('SpecialMode', olympus_special_mode),
  671.     0x0201: ('JPEGQual',
  672.              {1: 'SQ',
  673.               2: 'HQ',
  674.               3: 'SHQ'}),
  675.     0x0202: ('Macro',
  676.              {0: 'Normal',
  677.              1: 'Macro',
  678.              2: 'SuperMacro'}),
  679.     0x0203: ('BWMode',
  680.              {0: 'Off',
  681.              1: 'On'}),
  682.     0x0204: ('DigitalZoom', ),
  683.     0x0205: ('FocalPlaneDiagonal', ),
  684.     0x0206: ('LensDistortionParams', ),
  685.     0x0207: ('SoftwareRelease', ),
  686.     0x0208: ('PictureInfo', ),
  687.     0x0209: ('CameraID', make_string), # print as string
  688.     0x0F00: ('DataDump', ),
  689.     0x0300: ('PreCaptureFrames', ),
  690.     0x0404: ('SerialNumber', ),
  691.     0x1000: ('ShutterSpeedValue', ),
  692.     0x1001: ('ISOValue', ),
  693.     0x1002: ('ApertureValue', ),
  694.     0x1003: ('BrightnessValue', ),
  695.     0x1004: ('FlashMode', ),
  696.     0x1004: ('FlashMode',
  697.        {2: 'On',
  698.         3: 'Off'}),
  699.     0x1005: ('FlashDevice',
  700.        {0: 'None',
  701.         1: 'Internal',
  702.         4: 'External',
  703.         5: 'Internal + External'}),
  704.     0x1006: ('ExposureCompensation', ),
  705.     0x1007: ('SensorTemperature', ),
  706.     0x1008: ('LensTemperature', ),
  707.     0x100b: ('FocusMode',
  708.        {0: 'Auto',
  709.         1: 'Manual'}),
  710.     0x1017: ('RedBalance', ),
  711.     0x1018: ('BlueBalance', ),
  712.     0x101a: ('SerialNumber', ),
  713.     0x1023: ('FlashExposureComp', ),
  714.     0x1026: ('ExternalFlashBounce',
  715.        {0: 'No',
  716.         1: 'Yes'}),
  717.     0x1027: ('ExternalFlashZoom', ),
  718.     0x1028: ('ExternalFlashMode', ),
  719.     0x1029: ('Contrast  int16u',
  720.        {0: 'High',
  721.         1: 'Normal',
  722.         2: 'Low'}),
  723.     0x102a: ('SharpnessFactor', ),
  724.     0x102b: ('ColorControl', ),
  725.     0x102c: ('ValidBits', ),
  726.     0x102d: ('CoringFilter', ),
  727.     0x102e: ('OlympusImageWidth', ),
  728.     0x102f: ('OlympusImageHeight', ),
  729.     0x1034: ('CompressionRatio', ),
  730.     0x1035: ('PreviewImageValid',
  731.        {0: 'No',
  732.         1: 'Yes'}),
  733.     0x1036: ('PreviewImageStart', ),
  734.     0x1037: ('PreviewImageLength', ),
  735.     0x1039: ('CCDScanMode',
  736.        {0: 'Interlaced',
  737.         1: 'Progressive'}),
  738.     0x103a: ('NoiseReduction',
  739.        {0: 'Off',
  740.         1: 'On'}),
  741.     0x103b: ('InfinityLensStep', ),
  742.     0x103c: ('NearLensStep', ),
  743.  
  744.     # TODO - these need extra definitions
  745.     # http://search.cpan.org/src/EXIFTOOL/Image-ExifTool-6.90/html/TagNames/Olympus.html
  746.     0x2010: ('Equipment', ),
  747.     0x2020: ('CameraSettings', ),
  748.     0x2030: ('RawDevelopment', ),
  749.     0x2040: ('ImageProcessing', ),
  750.     0x2050: ('FocusInfo', ),
  751.     0x3000: ('RawInfo ', ),
  752.     }
  753.  
  754. # 0x2020 CameraSettings
  755. MAKERNOTE_OLYMPUS_TAG_0x2020={
  756.     0x0100: ('PreviewImageValid',
  757.              {0: 'No',
  758.               1: 'Yes'}),
  759.     0x0101: ('PreviewImageStart', ),
  760.     0x0102: ('PreviewImageLength', ),
  761.     0x0200: ('ExposureMode',
  762.              {1: 'Manual',
  763.               2: 'Program',
  764.               3: 'Aperture-priority AE',
  765.               4: 'Shutter speed priority AE',
  766.               5: 'Program-shift'}),
  767.     0x0201: ('AELock',
  768.              {0: 'Off',
  769.               1: 'On'}),
  770.     0x0202: ('MeteringMode',
  771.              {2: 'Center Weighted',
  772.               3: 'Spot',
  773.               5: 'ESP',
  774.               261: 'Pattern+AF',
  775.               515: 'Spot+Highlight control',
  776.               1027: 'Spot+Shadow control'}),
  777.     0x0300: ('MacroMode',
  778.              {0: 'Off',
  779.               1: 'On'}),
  780.     0x0301: ('FocusMode',
  781.              {0: 'Single AF',
  782.               1: 'Sequential shooting AF',
  783.               2: 'Continuous AF',
  784.               3: 'Multi AF',
  785.               10: 'MF'}),
  786.     0x0302: ('FocusProcess',
  787.              {0: 'AF Not Used',
  788.               1: 'AF Used'}),
  789.     0x0303: ('AFSearch',
  790.              {0: 'Not Ready',
  791.               1: 'Ready'}),
  792.     0x0304: ('AFAreas', ),
  793.     0x0401: ('FlashExposureCompensation', ),
  794.     0x0500: ('WhiteBalance2',
  795.              {0: 'Auto',
  796.              16: '7500K (Fine Weather with Shade)',
  797.              17: '6000K (Cloudy)',
  798.              18: '5300K (Fine Weather)',
  799.              20: '3000K (Tungsten light)',
  800.              21: '3600K (Tungsten light-like)',
  801.              33: '6600K (Daylight fluorescent)',
  802.              34: '4500K (Neutral white fluorescent)',
  803.              35: '4000K (Cool white fluorescent)',
  804.              48: '3600K (Tungsten light-like)',
  805.              256: 'Custom WB 1',
  806.              257: 'Custom WB 2',
  807.              258: 'Custom WB 3',
  808.              259: 'Custom WB 4',
  809.              512: 'Custom WB 5400K',
  810.              513: 'Custom WB 2900K',
  811.              514: 'Custom WB 8000K', }),
  812.     0x0501: ('WhiteBalanceTemperature', ),
  813.     0x0502: ('WhiteBalanceBracket', ),
  814.     0x0503: ('CustomSaturation', ), # (3 numbers: 1. CS Value, 2. Min, 3. Max)
  815.     0x0504: ('ModifiedSaturation',
  816.              {0: 'Off',
  817.               1: 'CM1 (Red Enhance)',
  818.               2: 'CM2 (Green Enhance)',
  819.               3: 'CM3 (Blue Enhance)',
  820.               4: 'CM4 (Skin Tones)'}),
  821.     0x0505: ('ContrastSetting', ), # (3 numbers: 1. Contrast, 2. Min, 3. Max)
  822.     0x0506: ('SharpnessSetting', ), # (3 numbers: 1. Sharpness, 2. Min, 3. Max)
  823.     0x0507: ('ColorSpace',
  824.              {0: 'sRGB',
  825.               1: 'Adobe RGB',
  826.               2: 'Pro Photo RGB'}),
  827.     0x0509: ('SceneMode',
  828.              {0: 'Standard',
  829.               6: 'Auto',
  830.               7: 'Sport',
  831.               8: 'Portrait',
  832.               9: 'Landscape+Portrait',
  833.              10: 'Landscape',
  834.              11: 'Night scene',
  835.              13: 'Panorama',
  836.              16: 'Landscape+Portrait',
  837.              17: 'Night+Portrait',
  838.              19: 'Fireworks',
  839.              20: 'Sunset',
  840.              22: 'Macro',
  841.              25: 'Documents',
  842.              26: 'Museum',
  843.              28: 'Beach&Snow',
  844.              30: 'Candle',
  845.              35: 'Underwater Wide1',
  846.              36: 'Underwater Macro',
  847.              39: 'High Key',
  848.              40: 'Digital Image Stabilization',
  849.              44: 'Underwater Wide2',
  850.              45: 'Low Key',
  851.              46: 'Children',
  852.              48: 'Nature Macro'}),
  853.     0x050a: ('NoiseReduction',
  854.              {0: 'Off',
  855.               1: 'Noise Reduction',
  856.               2: 'Noise Filter',
  857.               3: 'Noise Reduction + Noise Filter',
  858.               4: 'Noise Filter (ISO Boost)',
  859.               5: 'Noise Reduction + Noise Filter (ISO Boost)'}),
  860.     0x050b: ('DistortionCorrection',
  861.              {0: 'Off',
  862.               1: 'On'}),
  863.     0x050c: ('ShadingCompensation',
  864.              {0: 'Off',
  865.               1: 'On'}),
  866.     0x050d: ('CompressionFactor', ),
  867.     0x050f: ('Gradation',
  868.              {'-1 -1 1': 'Low Key',
  869.               '0 -1 1': 'Normal',
  870.               '1 -1 1': 'High Key'}),
  871.     0x0520: ('PictureMode',
  872.              {1: 'Vivid',
  873.               2: 'Natural',
  874.               3: 'Muted',
  875.               256: 'Monotone',
  876.               512: 'Sepia'}),
  877.     0x0521: ('PictureModeSaturation', ),
  878.     0x0522: ('PictureModeHue?', ),
  879.     0x0523: ('PictureModeContrast', ),
  880.     0x0524: ('PictureModeSharpness', ),
  881.     0x0525: ('PictureModeBWFilter',
  882.              {0: 'n/a',
  883.               1: 'Neutral',
  884.               2: 'Yellow',
  885.               3: 'Orange',
  886.               4: 'Red',
  887.               5: 'Green'}),
  888.     0x0526: ('PictureModeTone',
  889.              {0: 'n/a',
  890.               1: 'Neutral',
  891.               2: 'Sepia',
  892.               3: 'Blue',
  893.               4: 'Purple',
  894.               5: 'Green'}),
  895.     0x0600: ('Sequence', ), # 2 or 3 numbers: 1. Mode, 2. Shot number, 3. Mode bits
  896.     0x0601: ('PanoramaMode', ), # (2 numbers: 1. Mode, 2. Shot number)
  897.     0x0603: ('ImageQuality2',
  898.              {1: 'SQ',
  899.               2: 'HQ',
  900.               3: 'SHQ',
  901.               4: 'RAW'}),
  902.     0x0901: ('ManometerReading', ),
  903.     }
  904.  
  905.  
  906. MAKERNOTE_CASIO_TAGS={
  907.     0x0001: ('RecordingMode',
  908.              {1: 'Single Shutter',
  909.               2: 'Panorama',
  910.               3: 'Night Scene',
  911.               4: 'Portrait',
  912.               5: 'Landscape'}),
  913.     0x0002: ('Quality',
  914.              {1: 'Economy',
  915.               2: 'Normal',
  916.               3: 'Fine'}),
  917.     0x0003: ('FocusingMode',
  918.              {2: 'Macro',
  919.               3: 'Auto Focus',
  920.               4: 'Manual Focus',
  921.               5: 'Infinity'}),
  922.     0x0004: ('FlashMode',
  923.              {1: 'Auto',
  924.               2: 'On',
  925.               3: 'Off',
  926.               4: 'Red Eye Reduction'}),
  927.     0x0005: ('FlashIntensity',
  928.              {11: 'Weak',
  929.               13: 'Normal',
  930.               15: 'Strong'}),
  931.     0x0006: ('Object Distance', ),
  932.     0x0007: ('WhiteBalance',
  933.              {1: 'Auto',
  934.               2: 'Tungsten',
  935.               3: 'Daylight',
  936.               4: 'Fluorescent',
  937.               5: 'Shade',
  938.               129: 'Manual'}),
  939.     0x000B: ('Sharpness',
  940.              {0: 'Normal',
  941.               1: 'Soft',
  942.               2: 'Hard'}),
  943.     0x000C: ('Contrast',
  944.              {0: 'Normal',
  945.               1: 'Low',
  946.               2: 'High'}),
  947.     0x000D: ('Saturation',
  948.              {0: 'Normal',
  949.               1: 'Low',
  950.               2: 'High'}),
  951.     0x0014: ('CCDSpeed',
  952.              {64: 'Normal',
  953.               80: 'Normal',
  954.               100: 'High',
  955.               125: '+1.0',
  956.               244: '+3.0',
  957.               250: '+2.0'}),
  958.     }
  959.  
  960. MAKERNOTE_FUJIFILM_TAGS={
  961.     0x0000: ('NoteVersion', make_string),
  962.     0x1000: ('Quality', ),
  963.     0x1001: ('Sharpness',
  964.              {1: 'Soft',
  965.               2: 'Soft',
  966.               3: 'Normal',
  967.               4: 'Hard',
  968.               5: 'Hard'}),
  969.     0x1002: ('WhiteBalance',
  970.              {0: 'Auto',
  971.               256: 'Daylight',
  972.               512: 'Cloudy',
  973.               768: 'DaylightColor-Fluorescent',
  974.               769: 'DaywhiteColor-Fluorescent',
  975.               770: 'White-Fluorescent',
  976.               1024: 'Incandescent',
  977.               3840: 'Custom'}),
  978.     0x1003: ('Color',
  979.              {0: 'Normal',
  980.               256: 'High',
  981.               512: 'Low'}),
  982.     0x1004: ('Tone',
  983.              {0: 'Normal',
  984.               256: 'High',
  985.               512: 'Low'}),
  986.     0x1010: ('FlashMode',
  987.              {0: 'Auto',
  988.               1: 'On',
  989.               2: 'Off',
  990.               3: 'Red Eye Reduction'}),
  991.     0x1011: ('FlashStrength', ),
  992.     0x1020: ('Macro',
  993.              {0: 'Off',
  994.               1: 'On'}),
  995.     0x1021: ('FocusMode',
  996.              {0: 'Auto',
  997.               1: 'Manual'}),
  998.     0x1030: ('SlowSync',
  999.              {0: 'Off',
  1000.               1: 'On'}),
  1001.     0x1031: ('PictureMode',
  1002.              {0: 'Auto',
  1003.               1: 'Portrait',
  1004.               2: 'Landscape',
  1005.               4: 'Sports',
  1006.               5: 'Night',
  1007.               6: 'Program AE',
  1008.               256: 'Aperture Priority AE',
  1009.               512: 'Shutter Priority AE',
  1010.               768: 'Manual Exposure'}),
  1011.     0x1100: ('MotorOrBracket',
  1012.              {0: 'Off',
  1013.               1: 'On'}),
  1014.     0x1300: ('BlurWarning',
  1015.              {0: 'Off',
  1016.               1: 'On'}),
  1017.     0x1301: ('FocusWarning',
  1018.              {0: 'Off',
  1019.               1: 'On'}),
  1020.     0x1302: ('AEWarning',
  1021.              {0: 'Off',
  1022.               1: 'On'}),
  1023.     }
  1024.  
  1025. MAKERNOTE_CANON_TAGS = {
  1026.     0x0006: ('ImageType', ),
  1027.     0x0007: ('FirmwareVersion', ),
  1028.     0x0008: ('ImageNumber', ),
  1029.     0x0009: ('OwnerName', ),
  1030.     }
  1031.  
  1032. # this is in element offset, name, optional value dictionary format
  1033. MAKERNOTE_CANON_TAG_0x001 = {
  1034.     1: ('Macromode',
  1035.         {1: 'Macro',
  1036.          2: 'Normal'}),
  1037.     2: ('SelfTimer', ),
  1038.     3: ('Quality',
  1039.         {2: 'Normal',
  1040.          3: 'Fine',
  1041.          5: 'Superfine'}),
  1042.     4: ('FlashMode',
  1043.         {0: 'Flash Not Fired',
  1044.          1: 'Auto',
  1045.          2: 'On',
  1046.          3: 'Red-Eye Reduction',
  1047.          4: 'Slow Synchro',
  1048.          5: 'Auto + Red-Eye Reduction',
  1049.          6: 'On + Red-Eye Reduction',
  1050.          16: 'external flash'}),
  1051.     5: ('ContinuousDriveMode',
  1052.         {0: 'Single Or Timer',
  1053.          1: 'Continuous'}),
  1054.     7: ('FocusMode',
  1055.         {0: 'One-Shot',
  1056.          1: 'AI Servo',
  1057.          2: 'AI Focus',
  1058.          3: 'MF',
  1059.          4: 'Single',
  1060.          5: 'Continuous',
  1061.          6: 'MF'}),
  1062.     10: ('ImageSize',
  1063.          {0: 'Large',
  1064.           1: 'Medium',
  1065.           2: 'Small'}),
  1066.     11: ('EasyShootingMode',
  1067.          {0: 'Full Auto',
  1068.           1: 'Manual',
  1069.           2: 'Landscape',
  1070.           3: 'Fast Shutter',
  1071.           4: 'Slow Shutter',
  1072.           5: 'Night',
  1073.           6: 'B&W',
  1074.           7: 'Sepia',
  1075.           8: 'Portrait',
  1076.           9: 'Sports',
  1077.           10: 'Macro/Close-Up',
  1078.           11: 'Pan Focus'}),
  1079.     12: ('DigitalZoom',
  1080.          {0: 'None',
  1081.           1: '2x',
  1082.           2: '4x'}),
  1083.     13: ('Contrast',
  1084.          {0xFFFF: 'Low',
  1085.           0: 'Normal',
  1086.           1: 'High'}),
  1087.     14: ('Saturation',
  1088.          {0xFFFF: 'Low',
  1089.           0: 'Normal',
  1090.           1: 'High'}),
  1091.     15: ('Sharpness',
  1092.          {0xFFFF: 'Low',
  1093.           0: 'Normal',
  1094.           1: 'High'}),
  1095.     16: ('ISO',
  1096.          {0: 'See ISOSpeedRatings Tag',
  1097.           15: 'Auto',
  1098.           16: '50',
  1099.           17: '100',
  1100.           18: '200',
  1101.           19: '400'}),
  1102.     17: ('MeteringMode',
  1103.          {3: 'Evaluative',
  1104.           4: 'Partial',
  1105.           5: 'Center-weighted'}),
  1106.     18: ('FocusType',
  1107.          {0: 'Manual',
  1108.           1: 'Auto',
  1109.           3: 'Close-Up (Macro)',
  1110.           8: 'Locked (Pan Mode)'}),
  1111.     19: ('AFPointSelected',
  1112.          {0x3000: 'None (MF)',
  1113.           0x3001: 'Auto-Selected',
  1114.           0x3002: 'Right',
  1115.           0x3003: 'Center',
  1116.           0x3004: 'Left'}),
  1117.     20: ('ExposureMode',
  1118.          {0: 'Easy Shooting',
  1119.           1: 'Program',
  1120.           2: 'Tv-priority',
  1121.           3: 'Av-priority',
  1122.           4: 'Manual',
  1123.           5: 'A-DEP'}),
  1124.     23: ('LongFocalLengthOfLensInFocalUnits', ),
  1125.     24: ('ShortFocalLengthOfLensInFocalUnits', ),
  1126.     25: ('FocalUnitsPerMM', ),
  1127.     28: ('FlashActivity',
  1128.          {0: 'Did Not Fire',
  1129.           1: 'Fired'}),
  1130.     29: ('FlashDetails',
  1131.          {14: 'External E-TTL',
  1132.           13: 'Internal Flash',
  1133.           11: 'FP Sync Used',
  1134.           7: '2nd("Rear")-Curtain Sync Used',
  1135.           4: 'FP Sync Enabled'}),
  1136.     32: ('FocusMode',
  1137.          {0: 'Single',
  1138.           1: 'Continuous'}),
  1139.     }
  1140.  
  1141. MAKERNOTE_CANON_TAG_0x004 = {
  1142.     7: ('WhiteBalance',
  1143.         {0: 'Auto',
  1144.          1: 'Sunny',
  1145.          2: 'Cloudy',
  1146.          3: 'Tungsten',
  1147.          4: 'Fluorescent',
  1148.          5: 'Flash',
  1149.          6: 'Custom'}),
  1150.     9: ('SequenceNumber', ),
  1151.     14: ('AFPointUsed', ),
  1152.     15: ('FlashBias',
  1153.          {0xFFC0: '-2 EV',
  1154.           0xFFCC: '-1.67 EV',
  1155.           0xFFD0: '-1.50 EV',
  1156.           0xFFD4: '-1.33 EV',
  1157.           0xFFE0: '-1 EV',
  1158.           0xFFEC: '-0.67 EV',
  1159.           0xFFF0: '-0.50 EV',
  1160.           0xFFF4: '-0.33 EV',
  1161.           0x0000: '0 EV',
  1162.           0x000C: '0.33 EV',
  1163.           0x0010: '0.50 EV',
  1164.           0x0014: '0.67 EV',
  1165.           0x0020: '1 EV',
  1166.           0x002C: '1.33 EV',
  1167.           0x0030: '1.50 EV',
  1168.           0x0034: '1.67 EV',
  1169.           0x0040: '2 EV'}),
  1170.     19: ('SubjectDistance', ),
  1171.     }
  1172.  
  1173. # extract multibyte integer in Motorola format (little endian)
  1174. def s2n_motorola(str):
  1175.     x = 0
  1176.     for c in str:
  1177.         x = (x << 8) | c
  1178.     return x
  1179.  
  1180. # extract multibyte integer in Intel format (big endian)
  1181. def s2n_intel(str):
  1182.     x = 0
  1183.     y = 0
  1184.     for c in str:
  1185.         x = x | (c << y)
  1186.         y = y + 8
  1187.     return x
  1188.  
  1189. # ratio object that eventually will be able to reduce itself to lowest
  1190. # common denominator for printing
  1191. def gcd(a, b):
  1192.     if b == 0:
  1193.         return a
  1194.     else:
  1195.         return gcd(b, a % b)
  1196.  
  1197. class Ratio:
  1198.     def __init__(self, num, den):
  1199.         self.num = num
  1200.         self.den = den
  1201.  
  1202.     def __repr__(self):
  1203.         self.reduce()
  1204.         if self.den == 1:
  1205.             return str(self.num)
  1206.         return '%d/%d' % (self.num, self.den)
  1207.  
  1208.     def reduce(self):
  1209.         div = gcd(self.num, self.den)
  1210.         if div > 1:
  1211.             self.num = self.num / div
  1212.             self.den = self.den / div
  1213.  
  1214. # for ease of dealing with tags
  1215. class IFD_Tag:
  1216.     def __init__(self, printable, tag, field_type, values, field_offset,
  1217.                  field_length):
  1218.         # printable version of data
  1219.         self.printable = printable
  1220.         # tag ID number
  1221.         self.tag = tag
  1222.         # field type as index into FIELD_TYPES
  1223.         self.field_type = field_type
  1224.         # offset of start of field in bytes from beginning of IFD
  1225.         self.field_offset = field_offset
  1226.         # length of data field in bytes
  1227.         self.field_length = field_length
  1228.         # either a string or array of data items
  1229.         self.values = values
  1230.  
  1231.     def __str__(self):
  1232.         return self.printable
  1233.  
  1234.     def __repr__(self):
  1235.         return '(0x%04X) %s=%s @ %d' % (self.tag,
  1236.                                         FIELD_TYPES[self.field_type][2],
  1237.                                         self.printable,
  1238.                                         self.field_offset)
  1239.  
  1240. # class that handles an EXIF header
  1241. class EXIF_header:
  1242.     def __init__(self, file, endian, offset, fake_exif, strict, debug=0):
  1243.         self.file = file
  1244.         self.endian = endian
  1245.         self.offset = offset
  1246.         self.fake_exif = fake_exif
  1247.         self.strict = strict
  1248.         self.debug = debug
  1249.         self.tags = {}
  1250.  
  1251.     # convert slice to integer, based on sign and endian flags
  1252.     # usually this offset is assumed to be relative to the beginning of the
  1253.     # start of the EXIF information.  For some cameras that use relative tags,
  1254.     # this offset may be relative to some other starting point.
  1255.     def s2n(self, offset, length, signed=0):
  1256.         self.file.seek(self.offset+offset)
  1257.         slice=self.file.read(length)
  1258.         if self.endian == 'I':
  1259.             val=s2n_intel(slice)
  1260.         else:
  1261.             val=s2n_motorola(slice)
  1262.         # Sign extension ?
  1263.         if signed:
  1264.             msb=1 << (8*length-1)
  1265.             if val & msb:
  1266.                 val=val-(msb << 1)
  1267.         return val
  1268.  
  1269.     # convert offset to string
  1270.     def n2s(self, offset, length):
  1271.         s = ''
  1272.         for dummy in range(length):
  1273.             if self.endian == 'I':
  1274.                 s = s + chr(offset & 0xFF)
  1275.             else:
  1276.                 s = chr(offset & 0xFF) + s
  1277.             offset = offset >> 8
  1278.         return s
  1279.  
  1280.     # return first IFD
  1281.     def first_IFD(self):
  1282.         return self.s2n(4, 4)
  1283.  
  1284.     # return pointer to next IFD
  1285.     def next_IFD(self, ifd):
  1286.         entries=self.s2n(ifd, 2)
  1287.         return self.s2n(ifd+2+12*entries, 4)
  1288.  
  1289.     # return list of IFDs in header
  1290.     def list_IFDs(self):
  1291.         i=self.first_IFD()
  1292.         a=[]
  1293.         while i:
  1294.             a.append(i)
  1295.             i=self.next_IFD(i)
  1296.         return a
  1297.  
  1298.     # return list of entries in this IFD
  1299.     def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0, stop_tag='UNDEF'):
  1300.         entries=self.s2n(ifd, 2)
  1301.         for i in range(entries):
  1302.             # entry is index of start of this IFD in the file
  1303.             entry = ifd + 2 + 12 * i
  1304.             tag = self.s2n(entry, 2)
  1305.  
  1306.             # get tag name early to avoid errors, help debug
  1307.             tag_entry = dict.get(tag)
  1308.             if tag_entry:
  1309.                 tag_name = tag_entry[0]
  1310.             else:
  1311.                 tag_name = 'Tag 0x%04X' % tag
  1312.  
  1313.             # ignore certain tags for faster processing
  1314.             if not (not detailed and tag in IGNORE_TAGS):
  1315.                 field_type = self.s2n(entry + 2, 2)
  1316.  
  1317.                 # unknown field type
  1318.                 if not 0 < field_type < len(FIELD_TYPES):
  1319.                     if not self.strict:
  1320.                         continue
  1321.                     else:
  1322.                         raise ValueError('unknown type %d in tag 0x%04X' % (field_type, tag))
  1323.  
  1324.                 typelen = FIELD_TYPES[field_type][0]
  1325.                 count = self.s2n(entry + 4, 4)
  1326.                 # Adjust for tag id/type/count (2+2+4 bytes)
  1327.                 # Now we point at either the data or the 2nd level offset
  1328.                 offset = entry + 8
  1329.  
  1330.                 # If the value fits in 4 bytes, it is inlined, else we
  1331.                 # need to jump ahead again.
  1332.                 if count * typelen > 4:
  1333.                     # offset is not the value; it's a pointer to the value
  1334.                     # if relative we set things up so s2n will seek to the right
  1335.                     # place when it adds self.offset.  Note that this 'relative'
  1336.                     # is for the Nikon type 3 makernote.  Other cameras may use
  1337.                     # other relative offsets, which would have to be computed here
  1338.                     # slightly differently.
  1339.                     if relative:
  1340.                         tmp_offset = self.s2n(offset, 4)
  1341.                         offset = tmp_offset + ifd - 8
  1342.                         if self.fake_exif:
  1343.                             offset = offset + 18
  1344.                     else:
  1345.                         offset = self.s2n(offset, 4)
  1346.  
  1347.                 field_offset = offset
  1348.                 if field_type == 2:
  1349.                     # special case: null-terminated ASCII string
  1350.                     # XXX investigate
  1351.                     # sometimes gets too big to fit in int value
  1352.                     if count != 0 and count < (2**31):
  1353.                         self.file.seek(self.offset + offset)
  1354.                         values = self.file.read(count)
  1355.                         #print values
  1356.                         # Drop any garbage after a null.
  1357.                         values = values.split(b'\x00', 1)[0]
  1358.                     else:
  1359.                         values = ''
  1360.                 else:
  1361.                     values = []
  1362.                     signed = (field_type in [6, 8, 9, 10])
  1363.  
  1364.                     # XXX investigate
  1365.                     # some entries get too big to handle could be malformed
  1366.                     # file or problem with self.s2n
  1367.                     if count < 1000:
  1368.                         for dummy in range(count):
  1369.                             if field_type in (5, 10):
  1370.                                 # a ratio
  1371.                                 value = Ratio(self.s2n(offset, 4, signed),
  1372.                                               self.s2n(offset + 4, 4, signed))
  1373.                             else:
  1374.                                 value = self.s2n(offset, typelen, signed)
  1375.                             values.append(value)
  1376.                             offset = offset + typelen
  1377.                     # The test above causes problems with tags that are
  1378.                     # supposed to have long values!  Fix up one important case.
  1379.                     elif tag_name == 'MakerNote' :
  1380.                         for dummy in range(count):
  1381.                             value = self.s2n(offset, typelen, signed)
  1382.                             values.append(value)
  1383.                             offset = offset + typelen
  1384.                     #else :
  1385.                     #    print "Warning: dropping large tag:", tag, tag_name
  1386.  
  1387.                 # now 'values' is either a string or an array
  1388.                 if count == 1 and field_type != 2:
  1389.                     printable=str(values[0])
  1390.                 elif count > 50 and len(values) > 20 :
  1391.                     printable=str( values[0:20] )[0:-1] + ", ... ]"
  1392.                 else:
  1393.                     printable=str(values)
  1394.  
  1395.                 # compute printable version of values
  1396.                 if tag_entry:
  1397.                     if len(tag_entry) != 1:
  1398.                         # optional 2nd tag element is present
  1399.                         if isinstance(tag_entry[1], collections.Callable):
  1400.                             # call mapping function
  1401.                             printable = tag_entry[1](values)
  1402.                         else:
  1403.                             printable = ''
  1404.                             for i in values:
  1405.                                 # use lookup table for this tag
  1406.                                 printable += tag_entry[1].get(i, repr(i))
  1407.  
  1408.                 self.tags[ifd_name + ' ' + tag_name] = IFD_Tag(printable, tag,
  1409.                                                           field_type,
  1410.                                                           values, field_offset,
  1411.                                                           count * typelen)
  1412.                 if self.debug:
  1413.                     print(' debug:   %s: %s' % (tag_name,
  1414.                                                 repr(self.tags[ifd_name + ' ' + tag_name])))
  1415.  
  1416.             if tag_name == stop_tag:
  1417.                 break
  1418.  
  1419.     # extract uncompressed TIFF thumbnail (like pulling teeth)
  1420.     # we take advantage of the pre-existing layout in the thumbnail IFD as
  1421.     # much as possible
  1422.     def extract_TIFF_thumbnail(self, thumb_ifd):
  1423.         entries = self.s2n(thumb_ifd, 2)
  1424.         # this is header plus offset to IFD ...
  1425.         if self.endian == 'M':
  1426.             tiff = 'MM\x00*\x00\x00\x00\x08'
  1427.         else:
  1428.             tiff = 'II*\x00\x08\x00\x00\x00'
  1429.         # ... plus thumbnail IFD data plus a null "next IFD" pointer
  1430.         self.file.seek(self.offset+thumb_ifd)
  1431.         tiff += self.file.read(entries*12+2)+'\x00\x00\x00\x00'
  1432.  
  1433.         # fix up large value offset pointers into data area
  1434.         for i in range(entries):
  1435.             entry = thumb_ifd + 2 + 12 * i
  1436.             tag = self.s2n(entry, 2)
  1437.             field_type = self.s2n(entry+2, 2)
  1438.             typelen = FIELD_TYPES[field_type][0]
  1439.             count = self.s2n(entry+4, 4)
  1440.             oldoff = self.s2n(entry+8, 4)
  1441.             # start of the 4-byte pointer area in entry
  1442.             ptr = i * 12 + 18
  1443.             # remember strip offsets location
  1444.             if tag == 0x0111:
  1445.                 strip_off = ptr
  1446.                 strip_len = count * typelen
  1447.             # is it in the data area?
  1448.             if count * typelen > 4:
  1449.                 # update offset pointer (nasty "strings are immutable" crap)
  1450.                 # should be able to say "tiff[ptr:ptr+4]=newoff"
  1451.                 newoff = len(tiff)
  1452.                 tiff = tiff[:ptr] + self.n2s(newoff, 4) + tiff[ptr+4:]
  1453.                 # remember strip offsets location
  1454.                 if tag == 0x0111:
  1455.                     strip_off = newoff
  1456.                     strip_len = 4
  1457.                 # get original data and store it
  1458.                 self.file.seek(self.offset + oldoff)
  1459.                 tiff += self.file.read(count * typelen)
  1460.  
  1461.         # add pixel strips and update strip offset info
  1462.         old_offsets = self.tags['Thumbnail StripOffsets'].values
  1463.         old_counts = self.tags['Thumbnail StripByteCounts'].values
  1464.         for i in range(len(old_offsets)):
  1465.             # update offset pointer (more nasty "strings are immutable" crap)
  1466.             offset = self.n2s(len(tiff), strip_len)
  1467.             tiff = tiff[:strip_off] + offset + tiff[strip_off + strip_len:]
  1468.             strip_off += strip_len
  1469.             # add pixel strip to end
  1470.             self.file.seek(self.offset + old_offsets[i])
  1471.             tiff += self.file.read(old_counts[i])
  1472.  
  1473.         self.tags['TIFFThumbnail'] = tiff
  1474.  
  1475.     # decode all the camera-specific MakerNote formats
  1476.  
  1477.     # Note is the data that comprises this MakerNote.  The MakerNote will
  1478.     # likely have pointers in it that point to other parts of the file.  We'll
  1479.     # use self.offset as the starting point for most of those pointers, since
  1480.     # they are relative to the beginning of the file.
  1481.     #
  1482.     # If the MakerNote is in a newer format, it may use relative addressing
  1483.     # within the MakerNote.  In that case we'll use relative addresses for the
  1484.     # pointers.
  1485.     #
  1486.     # As an aside: it's not just to be annoying that the manufacturers use
  1487.     # relative offsets.  It's so that if the makernote has to be moved by the
  1488.     # picture software all of the offsets don't have to be adjusted.  Overall,
  1489.     # this is probably the right strategy for makernotes, though the spec is
  1490.     # ambiguous.  (The spec does not appear to imagine that makernotes would
  1491.     # follow EXIF format internally.  Once they did, it's ambiguous whether
  1492.     # the offsets should be from the header at the start of all the EXIF info,
  1493.     # or from the header at the start of the makernote.)
  1494.     def decode_maker_note(self):
  1495.         note = self.tags['EXIF MakerNote']
  1496.  
  1497.         # Some apps use MakerNote tags but do not use a format for which we
  1498.         # have a description, so just do a raw dump for these.
  1499.         #if self.tags.has_key('Image Make'):
  1500.         make = self.tags['Image Make'].printable
  1501.         #else:
  1502.         #    make = ''
  1503.  
  1504.         # model = self.tags['Image Model'].printable # unused
  1505.  
  1506.         # Nikon
  1507.         # The maker note usually starts with the word Nikon, followed by the
  1508.         # type of the makernote (1 or 2, as a short).  If the word Nikon is
  1509.         # not at the start of the makernote, it's probably type 2, since some
  1510.         # cameras work that way.
  1511.         if 'NIKON' in make:
  1512.             if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]:
  1513.                 if self.debug:
  1514.                     print("Looks like a type 1 Nikon MakerNote.")
  1515.                 self.dump_IFD(note.field_offset+8, 'MakerNote',
  1516.                               dict=MAKERNOTE_NIKON_OLDER_TAGS)
  1517.             elif note.values[0:7] == [78, 105, 107, 111, 110, 0, 2]:
  1518.                 if self.debug:
  1519.                     print("Looks like a labeled type 2 Nikon MakerNote")
  1520.                 if note.values[12:14] != [0, 42] and note.values[12:14] != [42, 0]:
  1521.                     raise ValueError("Missing marker tag '42' in MakerNote.")
  1522.                 # skip the Makernote label and the TIFF header
  1523.                 self.dump_IFD(note.field_offset+10+8, 'MakerNote',
  1524.                               dict=MAKERNOTE_NIKON_NEWER_TAGS, relative=1)
  1525.             else:
  1526.                 # E99x or D1
  1527.                 if self.debug:
  1528.                     print("Looks like an unlabeled type 2 Nikon MakerNote")
  1529.                 self.dump_IFD(note.field_offset, 'MakerNote',
  1530.                               dict=MAKERNOTE_NIKON_NEWER_TAGS)
  1531.             return
  1532.  
  1533.         # Olympus
  1534.         if make.startswith('OLYMPUS'):
  1535.             self.dump_IFD(note.field_offset+8, 'MakerNote',
  1536.                           dict=MAKERNOTE_OLYMPUS_TAGS)
  1537.             # XXX TODO
  1538.             #for i in (('MakerNote Tag 0x2020', MAKERNOTE_OLYMPUS_TAG_0x2020),):
  1539.             #    self.decode_olympus_tag(self.tags[i[0]].values, i[1])
  1540.             #return
  1541.  
  1542.         # Casio
  1543.         if 'CASIO' in make or 'Casio' in make:
  1544.             self.dump_IFD(note.field_offset, 'MakerNote',
  1545.                           dict=MAKERNOTE_CASIO_TAGS)
  1546.             return
  1547.  
  1548.         # Fujifilm
  1549.         if make == 'FUJIFILM':
  1550.             # bug: everything else is "Motorola" endian, but the MakerNote
  1551.             # is "Intel" endian
  1552.             endian = self.endian
  1553.             self.endian = 'I'
  1554.             # bug: IFD offsets are from beginning of MakerNote, not
  1555.             # beginning of file header
  1556.             offset = self.offset
  1557.             self.offset += note.field_offset
  1558.             # process note with bogus values (note is actually at offset 12)
  1559.             self.dump_IFD(12, 'MakerNote', dict=MAKERNOTE_FUJIFILM_TAGS)
  1560.             # reset to correct values
  1561.             self.endian = endian
  1562.             self.offset = offset
  1563.             return
  1564.  
  1565.         # Canon
  1566.         if make == 'Canon':
  1567.             self.dump_IFD(note.field_offset, 'MakerNote',
  1568.                           dict=MAKERNOTE_CANON_TAGS)
  1569.             for i in (('MakerNote Tag 0x0001', MAKERNOTE_CANON_TAG_0x001),
  1570.                       ('MakerNote Tag 0x0004', MAKERNOTE_CANON_TAG_0x004)):
  1571.                 self.canon_decode_tag(self.tags[i[0]].values, i[1])
  1572.             return
  1573.  
  1574.  
  1575.     # XXX TODO decode Olympus MakerNote tag based on offset within tag
  1576.     def olympus_decode_tag(self, value, dict):
  1577.         pass
  1578.  
  1579.     # decode Canon MakerNote tag based on offset within tag
  1580.     # see http://www.burren.cx/david/canon.html by David Burren
  1581.     def canon_decode_tag(self, value, dict):
  1582.         for i in range(1, len(value)):
  1583.             x=dict.get(i, ('Unknown', ))
  1584.             if self.debug:
  1585.                 print(i, x)
  1586.             name=x[0]
  1587.             if len(x) > 1:
  1588.                 val=x[1].get(value[i], 'Unknown')
  1589.             else:
  1590.                 val=value[i]
  1591.             # it's not a real IFD Tag but we fake one to make everybody
  1592.             # happy. this will have a "proprietary" type
  1593.             self.tags['MakerNote '+name]=IFD_Tag(str(val), None, 0, None,
  1594.                                                  None, None)
  1595.  
  1596. # process an image file (expects an open file object)
  1597. # this is the function that has to deal with all the arbitrary nasty bits
  1598. # of the EXIF standard
  1599. def process_file(f, stop_tag='UNDEF', details=True, strict=False, debug=False):
  1600.     # yah it's cheesy...
  1601.     global detailed
  1602.     detailed = details
  1603.  
  1604.     # by default do not fake an EXIF beginning
  1605.     fake_exif = 0
  1606.  
  1607.     # determine whether it's a JPEG or TIFF
  1608.     data = f.read(12)
  1609.     if data[0:4] in [b'II*\x00', b'MM\x00*']:
  1610.         # it's a TIFF file
  1611.         f.seek(0)
  1612.         endian = f.read(1)
  1613.         f.read(1)
  1614.         offset = 0
  1615.     elif data[0:2] == b'\xff\xd8':
  1616.         # it's a JPEG file
  1617.         while data[2:3] == b'\xff' and data[6:10] in (b'JFIF', b'JFXX', b'OLYM', b'Phot'):
  1618.             length = data[4]*256+data[5]
  1619.             f.read(length-8)
  1620.             # fake an EXIF beginning of file
  1621.             data = b'\xff\x00'+f.read(10)
  1622.             fake_exif = 1
  1623.         if data[2:3] == b'\xff' and data[6:10] == b'Exif':
  1624.             # detected EXIF header
  1625.             offset = f.tell()
  1626.             endian = f.read(1)
  1627.         else:
  1628.             # no EXIF information
  1629.             return {}
  1630.     else:
  1631.         # file format not recognized
  1632.         return {}
  1633.  
  1634.     # deal with the EXIF info we found
  1635.     if debug:
  1636.         print({'I': 'Intel', 'M': 'Motorola'}[endian], 'format')
  1637.     hdr = EXIF_header(f, endian, offset, fake_exif, strict, debug)
  1638.     ifd_list = hdr.list_IFDs()
  1639.     ctr = 0
  1640.     for i in ifd_list:
  1641.         if ctr == 0:
  1642.             IFD_name = 'Image'
  1643.         elif ctr == 1:
  1644.             IFD_name = 'Thumbnail'
  1645.             thumb_ifd = i
  1646.         else:
  1647.             IFD_name = 'IFD %d' % ctr
  1648.         if debug:
  1649.             print(' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i))
  1650.         hdr.dump_IFD(i, IFD_name, stop_tag=stop_tag)
  1651.         # EXIF IFD
  1652.         exif_off = hdr.tags.get(IFD_name+' ExifOffset')
  1653.         if exif_off:
  1654.             if debug:
  1655.                 print(' EXIF SubIFD at offset %d:' % exif_off.values[0])
  1656.             hdr.dump_IFD(exif_off.values[0], 'EXIF', stop_tag=stop_tag)
  1657.             # Interoperability IFD contained in EXIF IFD
  1658.             intr_off = hdr.tags.get('EXIF SubIFD InteroperabilityOffset')
  1659.             if intr_off:
  1660.                 if debug:
  1661.                     print(' EXIF Interoperability SubSubIFD at offset %d:' \
  1662.                           % intr_off.values[0])
  1663.                 hdr.dump_IFD(intr_off.values[0], 'EXIF Interoperability',
  1664.                              dict=INTR_TAGS, stop_tag=stop_tag)
  1665.         # GPS IFD
  1666.         gps_off = hdr.tags.get(IFD_name+' GPSInfo')
  1667.         if gps_off:
  1668.             if debug:
  1669.                 print(' GPS SubIFD at offset %d:' % gps_off.values[0])
  1670.             hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS, stop_tag=stop_tag)
  1671.         ctr += 1
  1672.  
  1673.     # extract uncompressed TIFF thumbnail
  1674.     thumb = hdr.tags.get('Thumbnail Compression')
  1675.     if thumb and thumb.printable == 'Uncompressed TIFF':
  1676.         hdr.extract_TIFF_thumbnail(thumb_ifd)
  1677.  
  1678.     # JPEG thumbnail (thankfully the JPEG data is stored as a unit)
  1679.     thumb_off = hdr.tags.get('Thumbnail JPEGInterchangeFormat')
  1680.     if thumb_off:
  1681.         f.seek(offset+thumb_off.values[0])
  1682.         size = hdr.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]
  1683.         hdr.tags['JPEGThumbnail'] = f.read(size)
  1684.  
  1685.     # deal with MakerNote contained in EXIF IFD
  1686.     # (Some apps use MakerNote tags but do not use a format for which we
  1687.     # have a description, do not process these).
  1688.     if 'EXIF MakerNote' in hdr.tags and 'Image Make' in hdr.tags and detailed:
  1689.         hdr.decode_maker_note()
  1690.  
  1691.     # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote
  1692.     # since it's not allowed in a uncompressed TIFF IFD
  1693.     if 'JPEGThumbnail' not in hdr.tags:
  1694.         thumb_off=hdr.tags.get('MakerNote JPEGThumbnail')
  1695.         if thumb_off:
  1696.             f.seek(offset+thumb_off.values[0])
  1697.             hdr.tags['JPEGThumbnail']=file.read(thumb_off.field_length)
  1698.  
  1699.     return hdr.tags
  1700.  
  1701.  
  1702. # show command line usage
  1703. def usage(exit_status):
  1704.     msg = 'Usage: EXIF.py [OPTIONS] file1 [file2 ...]\n'
  1705.     msg += 'Extract EXIF information from digital camera image files.\n\nOptions:\n'
  1706.     msg += '-q --quick   Do not process MakerNotes.\n'
  1707.     msg += '-t TAG --stop-tag TAG   Stop processing when this tag is retrieved.\n'
  1708.     msg += '-s --strict   Run in strict mode (stop on errors).\n'
  1709.     msg += '-d --debug   Run in debug mode (display extra info).\n'
  1710.     print(msg)
  1711.     sys.exit(exit_status)
  1712.  
  1713. # library test/debug function (dump given files)
  1714. if __name__ == '__main__':
  1715.     import sys
  1716.     import getopt
  1717.  
  1718.     # parse command line options/arguments
  1719.     try:
  1720.         opts, args = getopt.getopt(sys.argv[1:], "hqsdt:v", ["help", "quick", "strict", "debug", "stop-tag="])
  1721.     except getopt.GetoptError:
  1722.         usage(2)
  1723.     if args == []:
  1724.         usage(2)
  1725.     detailed = True
  1726.     stop_tag = 'UNDEF'
  1727.     debug = False
  1728.     strict = False
  1729.     for o, a in opts:
  1730.         if o in ("-h", "--help"):
  1731.             usage(0)
  1732.         if o in ("-q", "--quick"):
  1733.             detailed = False
  1734.         if o in ("-t", "--stop-tag"):
  1735.             stop_tag = a
  1736.         if o in ("-s", "--strict"):
  1737.             strict = True
  1738.         if o in ("-d", "--debug"):
  1739.             debug = True
  1740.  
  1741.     # output info for each file
  1742.     for filename in args:
  1743.         try:
  1744.             file=open(filename, 'rb')
  1745.         except:
  1746.             print("'%s' is unreadable\n"%filename)
  1747.             continue
  1748.         print(filename + ':')
  1749.         # get the tags
  1750.         data = process_file(file, stop_tag=stop_tag, details=detailed, strict=strict, debug=debug)
  1751.         if not data:
  1752.             print('No EXIF information found')
  1753.             continue
  1754.  
  1755.         x=list(data.keys())
  1756.         x.sort()
  1757.         for i in x:
  1758.             if i in ('JPEGThumbnail', 'TIFFThumbnail'):
  1759.                 continue
  1760.             try:
  1761.                 print('   %s (%s): %s' % \
  1762.                       (i, FIELD_TYPES[data[i].field_type][2], data[i].printable))
  1763.             except:
  1764.                 print('error', i, '"', data[i], '"')
  1765.         if 'JPEGThumbnail' in data:
  1766.             print('File has JPEG thumbnail')
  1767.         print()
  1768.  
Strong