-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbarcode_decoder.py
79 lines (68 loc) · 2.95 KB
/
barcode_decoder.py
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
"""Module for reading barcodes."""
import pandas as pd
import string
import collections
class Decoder:
"""Decode and encode barcodes with csv."""
def __init__(this, csv_file):
"""Construct the class."""
this.df = pd.read_csv(csv_file, dtype=str)
this._color = 'Farbe'
this._keys = this._get_keys()
def _get_keys(this):
"""Get all named column names."""
keys = this.df.columns
keys = [key for key in keys if not key.startswith('Unnamed:')]
keys.append(this._color)
return keys
def _split_barcode(this, barcode):
"""Split the barcode into a dictionary."""
barcode_dict = {}
for key, index in zip(this._keys, range(0, 8, 2)):
barcode_dict[key] = barcode[index:index+2]
return barcode_dict
def decode(this, barcode):
"""Decode the barcode."""
if not isinstance(barcode, str):
raise TypeError("Barcode must be passed as a string!")
if len(barcode) != 14:
raise ValueError("Barcode must be of length 14!")
if not all(c in string.hexdigits for c in barcode):
raise ValueError(f'Barcode "{barcode}" contains non hex digits!')
barcode = barcode.lower()
barcode_dict = this._split_barcode(barcode)
item_dict = {}
for key, code in barcode_dict.items():
idx = this.df.columns.get_indexer([key]) + 1
mask = (this.df.iloc[:, idx] == code).iloc[:, 0]
try:
item_dict[key] = this.df.loc[mask][key].values[0]
except IndexError:
raise ItemNotFoundError(f'Code "{code}" not found for "{key}"!')
try:
assert isinstance(item_dict[key], str)
except AssertionError:
raise ItemNotFoundError(f'No item found in column "{key}" for code "{code}"!')
item_dict[this._color] = barcode[8:]
return item_dict
def encode(this, item_dict):
"""Encode dictionary into barcode."""
if not collections.Counter(item_dict.keys()) == collections.Counter(this._keys):
raise ValueError("Dictionary contains wrong keys!")
if not all(c in string.hexdigits for c in item_dict[this._color]):
raise ValueError(f'Color "{item_dict[this._color]}" contains non hex digits!')
barcode = ''
for key in this._keys[:-1]:
value = item_dict[key]
idx = this.df.columns.get_indexer([key]) + 1
try:
barcode += this.df.loc[this.df[key] == value].iloc[:, idx].values[0][0]
except IndexError:
raise ItemNotFoundError(f'Item "{key}:{value}" not found!')
except TypeError:
raise ItemNotFoundError(f'No code found for item "{key}:{value}"!')
barcode += item_dict[this._color].lower()
return barcode
class ItemNotFoundError(Exception):
"""Throw this if item is not found in dataframe."""
pass