1# ean.py - functions for handling EANs
2#
3# Copyright (C) 2011-2017 Arthur de Jong
4#
5# This library is free software; you can redistribute it and/or
6# modify it under the terms of the GNU Lesser General Public
7# License as published by the Free Software Foundation; either
8# version 2.1 of the License, or (at your option) any later version.
9#
10# This library is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13# Lesser General Public License for more details.
14#
15# You should have received a copy of the GNU Lesser General Public
16# License along with this library; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18# 02110-1301 USA
19
20"""EAN (International Article Number).
21
22Module for handling EAN (International Article Number) codes. This
23module handles numbers EAN-13, EAN-8, UPC (12-digit) and GTIN (EAN-14) format.
24
25>>> validate('73513537')
26'73513537'
27>>> validate('978-0-471-11709-4') # EAN-13 format
28'9780471117094'
29>>> validate('98412345678908') # GTIN format
30'98412345678908'
31"""
32
33from stdnum.exceptions import *
34from stdnum.util import clean, isdigits
35
36
37def compact(number):
38    """Convert the EAN to the minimal representation. This strips the number
39    of any valid separators and removes surrounding whitespace."""
40    return clean(number, ' -').strip()
41
42
43def calc_check_digit(number):
44    """Calculate the EAN check digit for 13-digit numbers. The number passed
45    should not have the check bit included."""
46    return str((10 - sum((3, 1)[i % 2] * int(n)
47                         for i, n in enumerate(reversed(number)))) % 10)
48
49
50def validate(number):
51    """Check if the number provided is a valid EAN-13. This checks the length
52    and the check bit but does not check whether a known GS1 Prefix and
53    company identifier are referenced."""
54    number = compact(number)
55    if not isdigits(number):
56        raise InvalidFormat()
57    if len(number) not in (14, 13, 12, 8):
58        raise InvalidLength()
59    if calc_check_digit(number[:-1]) != number[-1]:
60        raise InvalidChecksum()
61    return number
62
63
64def is_valid(number):
65    """Check if the number provided is a valid EAN-13. This checks the length
66    and the check bit but does not check whether a known GS1 Prefix and
67    company identifier are referenced."""
68    try:
69        return bool(validate(number))
70    except ValidationError:
71        return False
72