-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathean.py
More file actions
executable file
·337 lines (262 loc) · 10 KB
/
ean.py
File metadata and controls
executable file
·337 lines (262 loc) · 10 KB
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
"""Module: barcode.ean
:Provided barcodes: EAN-14, EAN-13, EAN-8, JAN
"""
from __future__ import annotations
__docformat__ = "restructuredtext en"
from barcode.base import Barcode
from barcode.charsets import ean as _ean
from barcode.errors import IllegalCharacterError
from barcode.errors import NumberOfDigitsError
from barcode.errors import WrongCountryCodeError
# EAN13 Specs (all sizes in mm)
SIZES = {
"SC0": 0.27,
"SC1": 0.297,
"SC2": 0.33,
"SC3": 0.363,
"SC4": 0.396,
"SC5": 0.445,
"SC6": 0.495,
"SC7": 0.544,
"SC8": 0.61,
"SC9": 0.66,
}
class EuropeanArticleNumber13(Barcode):
"""Initializes EAN13 object.
:param ean: The ean number as string. If the value is too long, it is trimmed.
:param writer: The writer to render the barcode (default: SVGWriter).
:param no_checksum: Don't calculate the checksum. Use the provided input instead.
:param guardbar: If True, use guard bar markers in the output.
:param addon: Optional 2 or 5 digit addon (EAN-2 or EAN-5).
"""
name = "EAN-13"
digits = 12
def __init__(
self,
ean: str,
writer=None,
no_checksum: bool = False,
guardbar: bool = False,
addon: str | None = None,
) -> None:
if not ean[: self.digits].isdigit():
raise IllegalCharacterError(f"EAN code can only contain numbers {ean}.")
if len(ean) < self.digits:
raise NumberOfDigitsError(
f"EAN must have {self.digits} digits, received {len(ean)}."
)
base = ean[: self.digits]
if no_checksum:
# Use the thirteenth digit if given in parameter, otherwise pad with zero
if len(ean) > self.digits and ean[self.digits].isdigit():
last = int(ean[self.digits])
else:
last = 0
else:
last = self.calculate_checksum(base)
self.ean = f"{base}{last}"
# Validate and store addon
self.addon = None
if addon is not None:
addon = addon.strip()
if addon:
if not addon.isdigit():
raise IllegalCharacterError(
f"Addon can only contain numbers, got {addon}."
)
if len(addon) not in (2, 5):
raise NumberOfDigitsError(
f"Addon must be 2 or 5 digits, received {len(addon)}."
)
self.addon = addon
self.guardbar = guardbar
if guardbar:
self.EDGE = _ean.EDGE.replace("1", "G")
self.MIDDLE = _ean.MIDDLE.replace("1", "G")
else:
self.EDGE = _ean.EDGE
self.MIDDLE = _ean.MIDDLE
self.writer = writer or self.default_writer()
def __str__(self) -> str:
if self.addon:
return f"{self.ean} {self.addon}"
return self.ean
def get_fullcode(self) -> str:
if self.guardbar:
base = self.ean[0] + " " + self.ean[1:7] + " " + self.ean[7:] + " >"
else:
base = self.ean
if self.addon:
return f"{base} {self.addon}"
return base
def calculate_checksum(self, value: str | None = None) -> int:
"""Calculates and returns the checksum for EAN13-Code.
Calculates the checksum for the supplied `value` (if any) or for this barcode's
internal ``self.ean`` property.
"""
ean_without_checksum = value or self.ean[: self.digits]
evensum = sum(int(x) for x in ean_without_checksum[-2::-2])
oddsum = sum(int(x) for x in ean_without_checksum[-1::-2])
return (10 - ((evensum + oddsum * 3) % 10)) % 10
def build(self) -> list[str]:
"""Builds the barcode pattern from `self.ean`.
:returns: The pattern as string
:rtype: List containing the string as a single element
"""
code = self.EDGE[:]
pattern = _ean.LEFT_PATTERN[int(self.ean[0])]
for i, number in enumerate(self.ean[1:7]):
code += _ean.CODES[pattern[i]][int(number)]
code += self.MIDDLE
for number in self.ean[7:]:
code += _ean.CODES["C"][int(number)]
code += self.EDGE
# Add addon if present
if self.addon:
code += self._build_addon()
return [code]
def _build_addon(self) -> str:
"""Builds the addon barcode pattern (EAN-2 or EAN-5).
:returns: The addon pattern as string (including quiet zone separator)
"""
if not self.addon:
return ""
# Add quiet zone (9 modules) before addon per GS1 specification
code = _ean.ADDON_QUIET_ZONE
if len(self.addon) == 2:
code += self._build_addon2()
else:
code += self._build_addon5()
return code
def _build_addon2(self) -> str:
"""Builds EAN-2 addon pattern.
Parity is determined by the 2-digit value mod 4.
"""
value = int(self.addon)
parity = _ean.ADDON2_PARITY[value % 4]
code = _ean.ADDON_START
for i, digit in enumerate(self.addon):
if i > 0:
code += _ean.ADDON_SEPARATOR
code += _ean.CODES[parity[i]][int(digit)]
return code
def _build_addon5(self) -> str:
"""Builds EAN-5 addon pattern.
Parity is determined by a checksum calculation.
"""
# Calculate checksum for parity pattern
checksum = 0
for i, digit in enumerate(self.addon):
weight = 3 if i % 2 == 0 else 9
checksum += int(digit) * weight
checksum %= 10
parity = _ean.ADDON5_PARITY[checksum]
code = _ean.ADDON_START
for i, digit in enumerate(self.addon):
if i > 0:
code += _ean.ADDON_SEPARATOR
code += _ean.CODES[parity[i]][int(digit)]
return code
def to_ascii(self) -> str:
"""Returns an ascii representation of the barcode.
:rtype: String
"""
code_list = self.build()
if not len(code_list) == 1:
raise RuntimeError("Code list must contain a single element.")
code = code_list[0]
return code.replace("G", "|").replace("1", "|").replace("0", " ")
def render(self, writer_options: dict | None = None, text: str | None = None):
options = {"module_width": SIZES["SC2"]}
options.update(writer_options or {})
return super().render(options, text)
class EuropeanArticleNumber13WithGuard(EuropeanArticleNumber13):
"""A shortcut to EAN-13 with ``guardbar=True``."""
name = "EAN-13 with guards"
def __init__(
self, ean, writer=None, no_checksum=False, guardbar=True, addon=None
) -> None:
super().__init__(ean, writer, no_checksum, guardbar, addon)
class JapanArticleNumber(EuropeanArticleNumber13):
"""Initializes JAN barcode.
:parameters:
jan : String
The jan number as string.
writer : barcode.writer Instance
The writer to render the barcode (default: SVGWriter).
"""
name = "JAN"
valid_country_codes = list(range(450, 460)) + list(range(490, 500))
def __init__(self, jan, *args, **kwargs) -> None:
if int(jan[:3]) not in self.valid_country_codes:
raise WrongCountryCodeError(
"Country code isn't between 450-460 or 490-500."
)
super().__init__(jan, *args, **kwargs)
class EuropeanArticleNumber8(EuropeanArticleNumber13):
"""Represents an EAN-8 barcode. See EAN13's __init__ for details.
:param ean: The ean number as string.
:param writer: The writer to render the barcode (default: SVGWriter).
:param addon: Optional 2 or 5 digit addon (EAN-2 or EAN-5).
"""
name = "EAN-8"
digits = 7
def build(self) -> list[str]:
"""Builds the barcode pattern from `self.ean`.
:returns: A list containing the string as a single element
"""
code = self.EDGE[:]
for number in self.ean[:4]:
code += _ean.CODES["A"][int(number)]
code += self.MIDDLE
for number in self.ean[4:]:
code += _ean.CODES["C"][int(number)]
code += self.EDGE
# Add addon if present
if self.addon:
code += self._build_addon()
return [code]
def get_fullcode(self):
if self.guardbar:
base = "< " + self.ean[:4] + " " + self.ean[4:] + " >"
else:
base = self.ean
if self.addon:
return f"{base} {self.addon}"
return base
class EuropeanArticleNumber8WithGuard(EuropeanArticleNumber8):
"""A shortcut to EAN-8 with ``guardbar=True``."""
name = "EAN-8 with guards"
def __init__(
self,
ean: str,
writer=None,
no_checksum: bool = False,
guardbar: bool = True,
addon: str | None = None,
) -> None:
super().__init__(ean, writer, no_checksum, guardbar, addon)
class EuropeanArticleNumber14(EuropeanArticleNumber13):
"""Represents an EAN-14 barcode. See EAN13's __init__ for details.
:param ean: The ean number as string.
:param writer: The writer to render the barcode (default: SVGWriter).
:param no_checksum: Don't calculate the checksum. Use the provided input instead.
"""
name = "EAN-14"
digits = 13
def calculate_checksum(self, value: str | None = None) -> int:
"""Calculates and returns the checksum for EAN14-Code.
Calculates the checksum for the supplied `value` (if any) or for this barcode's
internal ``self.ean`` property.
"""
ean_without_checksum = value or self.ean[: self.digits]
evensum = sum(int(x) for x in ean_without_checksum[::2])
oddsum = sum(int(x) for x in ean_without_checksum[1::2])
return (10 - (((evensum * 3) + oddsum) % 10)) % 10
# Shortcuts
EAN14 = EuropeanArticleNumber14
EAN13 = EuropeanArticleNumber13
EAN13_GUARD = EuropeanArticleNumber13WithGuard
EAN8 = EuropeanArticleNumber8
EAN8_GUARD = EuropeanArticleNumber8WithGuard
JAN = JapanArticleNumber