aboutsummaryrefslogtreecommitdiffstats
path: root/src/pyexiv2/iptc.py
blob: f92e883925f96cf9c542e69b4015f7815b6c400a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# -*- coding: utf-8 -*-

# ******************************************************************************
#
# Copyright (C) 2006-2010 Olivier Tilloy <olivier@tilloy.net>
#
# This file is part of the pyexiv2 distribution.
#
# pyexiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# pyexiv2 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyexiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Author: Olivier Tilloy <olivier@tilloy.net>
#
# ******************************************************************************

"""
IPTC specific code.
"""

import libexiv2python

from pyexiv2.utils import ListenerInterface, NotifyingList, FixedOffset

import time
import datetime
import re


class IptcValueError(ValueError):

    """
    Exception raised when failing to parse the *value* of an IPTC tag.

    :attribute value: the value that fails to be parsed
    :type value: string
    :attribute type: the IPTC type of the tag
    :type type: string
    """

    def __init__(self, value, type):
        self.value = value
        self.type = type

    def __str__(self):
        return 'Invalid value for IPTC type [%s]: [%s]' % \
               (self.type, self.value)


class IptcTag(ListenerInterface):

    """
    An IPTC tag.

    This tag can have several values (tags that have the *repeatable* property).

    Here is a correspondance table between the IPTC types and the possible
    python types the value of a tag may take:

    - Short: int
    - String: string
    - Date: :class:`datetime.date`
    - Time: :class:`datetime.time`
    - Undefined: string

    :attribute metadata: the parent metadata if any, or None
    :type metadata: :class:`pyexiv2.metadata.ImageMetadata`
    """

    # strptime is not flexible enough to handle all valid Time formats, we use a
    # custom regular expression
    _time_zone_re = r'(?P<sign>\+|-)(?P<ohours>\d{2}):(?P<ominutes>\d{2})'
    _time_re = re.compile(r'(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})(?P<tzd>%s)' % _time_zone_re)

    def __init__(self, key, values=None, _tag=None):
        """
        The tag can be initialized with an optional list of values which
        expected type depends on the IPTC type of the tag.

        :param key: the key of the tag
        :type key: string
        :param values: the values of the tag
        """
        super(IptcTag, self).__init__()
        if _tag is not None:
            self._tag = _tag
        else:
            self._tag = libexiv2python._IptcTag(key)
        self.metadata = None
        self._raw_values = None
        self._values = None
        self._values_cookie = False
        if values is not None:
            self._set_values(values)

    @staticmethod
    def _from_existing_tag(_tag):
        # Build a tag from an already existing libexiv2python._IptcTag
        tag = IptcTag(_tag._getKey(), _tag=_tag)
        # Do not set the raw_values property, as it would call
        # _tag._setRawValues
        # (see https://bugs.launchpad.net/pyexiv2/+bug/582445).
        tag._raw_values = _tag._getRawValues()
        tag._values_cookie = True
        return tag

    @property
    def key(self):
        """The key of the tag in the dotted form
        ``familyName.groupName.tagName`` where ``familyName`` = ``iptc``."""
        return self._tag._getKey()

    @property
    def type(self):
        """The IPTC type of the tag (one of Short, String, Date, Time,
        Undefined)."""
        return self._tag._getType()

    @property
    def name(self):
        """The name of the tag (this is also the third part of the key)."""
        return self._tag._getName()

    @property
    def title(self):
        """The title (label) of the tag."""
        return self._tag._getTitle()

    @property
    def description(self):
        """The description of the tag."""
        return self._tag._getDescription()

    @property
    def photoshop_name(self):
        """The Photoshop name of the tag."""
        return self._tag._getPhotoshopName()

    @property
    def repeatable(self):
        """Whether the tag is repeatable (accepts several values)."""
        return self._tag._isRepeatable()

    @property
    def record_name(self):
        """The name of the tag's record."""
        return self._tag._getRecordName()

    @property
    def record_description(self):
        """The description of the tag's record."""
        return self._tag._getRecordDescription()

    def _get_raw_values(self):
        return self._raw_values

    def _set_raw_values(self, values):
        if not isinstance(values, (list, tuple)):
            raise TypeError('Expecting a list of values')
        self._tag._setRawValues(values)
        if self.metadata is not None:
            self.metadata._set_iptc_tag_values(self.key, values)
        self._raw_values = values
        self._values_cookie = True

    raw_values = property(fget=_get_raw_values, fset=_set_raw_values,
                          doc='The raw values of the tag as a list of strings.')

    def _compute_values(self):
        # Lazy computation of the values from the raw values
        self._values = \
            NotifyingList(map(self._convert_to_python, self._raw_values))
        self._values.register_listener(self)
        self._values_cookie = False

    def _get_values(self):
        if self._values_cookie:
            self._compute_values()
        return self._values

    def _set_values(self, values):
        if not isinstance(values, (list, tuple)):
            raise TypeError('Expecting a list of values')
        self.raw_values = map(self._convert_to_string, values)

        if isinstance(self._values, NotifyingList):
            self._values.unregister_listener(self)

        if isinstance(values, NotifyingList):
            # Already a notifying list
            self._values = values
        else:
            # Make the values a notifying list 
            self._values = NotifyingList(values)

        self._values.register_listener(self)
        self._values_cookie = False

    values = property(fget=_get_values, fset=_set_values,
                      doc='The values of the tag as a list of python objects.')

    def contents_changed(self):
        # Implementation of the ListenerInterface.
        # React on changes to the list of values of the tag.
        # The contents of self._values was changed.
        # The following is a quick, non optimal solution.
        self._set_values(self._values)

    def _convert_to_python(self, value):
        """
        Convert one raw value to its corresponding python type.

        :param value: the raw value to be converted
        :type value: string

        :return: the value converted to its corresponding python type

        :raise IptcValueError: if the conversion fails
        """
        if self.type == 'Short':
            try:
                return int(value)
            except ValueError:
                raise IptcValueError(value, self.type)

        elif self.type == 'String':
            # There is currently no charset conversion.
            # TODO: guess the encoding and decode accordingly into unicode
            # where relevant.
            return value

        elif self.type == 'Date':
            # According to the IPTC specification, the format for a string field
            # representing a date is '%Y%m%d'. However, the string returned by
            # exiv2 using method DateValue::toString() is formatted using
            # pattern '%Y-%m-%d'.
            format = '%Y-%m-%d'
            try:
                t = time.strptime(value, format)
                return datetime.date(*t[:3])
            except ValueError:
                raise IptcValueError(value, self.type)

        elif self.type == 'Time':
            # According to the IPTC specification, the format for a string field
            # representing a time is '%H%M%S±%H%M'. However, the string returned
            # by exiv2 using method TimeValue::toString() is formatted using
            # pattern '%H:%M:%S±%H:%M'.
            match = IptcTag._time_re.match(value)
            if match is None:
                raise IptcValueError(value, self.type)
            gd = match.groupdict()
            try:
                tzinfo = FixedOffset(gd['sign'], int(gd['ohours']),
                                     int(gd['ominutes']))
            except TypeError:
                raise IptcValueError(value, self.type)
            try:
                return datetime.time(int(gd['hours']), int(gd['minutes']),
                                     int(gd['seconds']), tzinfo=tzinfo)
            except (TypeError, ValueError):
                raise IptcValueError(value, self.type)

        elif self.type == 'Undefined':
            # Binary data, return it unmodified
            return value

        raise IptcValueError(value, self.type)

    def _convert_to_string(self, value):
        """
        Convert one value to its corresponding string representation, suitable
        to pass to libexiv2.

        :param value: the value to be converted

        :return: the value converted to its corresponding string representation
        :rtype: string

        :raise IptcValueError: if the conversion fails
        """
        if self.type == 'Short':
            if type(value) is int:
                return str(value)
            else:
                raise IptcValueError(value, self.type)

        elif self.type == 'String':
            if type(value) is unicode:
                try:
                    return value.encode('utf-8')
                except UnicodeEncodeError:
                    raise IptcValueError(value, self.type)
            elif type(value) is str:
                return value
            else:
                raise IptcValueError(value, self.type)

        elif self.type == 'Date':
            if type(value) in (datetime.date, datetime.datetime):
                # ISO 8601 date format.
                # According to the IPTC specification, the format for a string
                # field representing a date is '%Y%m%d'. However, the string
                # expected by exiv2's DateValue::read(string) should be
                # formatted using pattern '%Y-%m-%d'.
                return value.strftime('%Y-%m-%d')
            else:
                raise IptcValueError(value, self.type)

        elif self.type == 'Time':
            if type(value) in (datetime.time, datetime.datetime):
                r = value.strftime('%H%M%S')
                if value.tzinfo is not None:
                    r += value.strftime('%z')
                else:
                    r += '+0000'
                return r
            else:
                raise IptcValueError(value, self.type)

        elif self.type == 'Undefined':
            if type(value) is str:
                return value
            else:
                raise IptcValueError(value, self.type)

        raise IptcValueError(value, self.type)

    def __str__(self):
        """
        :return: a string representation of the IPTC tag for debugging purposes
        :rtype: string
        """
        left = '%s [%s]' % (self.key, self.type)
        if self._raw_values is None:
            right = '(No values)'
        else:
             right = self._raw_values
        return '<%s = %s>' % (left, right)