-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.py
More file actions
60 lines (47 loc) · 1.75 KB
/
Copy pathdecode.py
File metadata and controls
60 lines (47 loc) · 1.75 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
#! /usr/bin/env python3
import argparse
import cv2
import base64
import hashlib
import json
import os
from pyzbar.pyzbar import decode, ZBarSymbol
def find_free_name(location, name):
while os.path.exists(os.path.join(location, name)):
name = f'copy-{name}'
return name
def main():
parser = argparse.ArgumentParser(
description="Decode a QR-code sequence into a file")
parser.add_argument("input_dir", help="Directory with pics to decode")
parser.add_argument("--output_dir", "-o", default=".",
help="Directory for output file, default is the current one")
args = parser.parse_args()
split_content = list()
first = True
output_name = 'UNKNOWN_FILENAME'
checksum = None
for fname in os.listdir(args.input_dir):
img = cv2.imread(os.path.join(args.input_dir, fname))
scanned = decode(img, symbols=[ZBarSymbol.QRCODE])
if len(scanned) != 1:
print(f"ERROR: couldn't detect a QR-code in {fname}")
exit(1)
descriptor = json.loads(scanned[0].data)
if first:
first = False
output_name = descriptor['filename']
checksum = descriptor['checksum']
continue
split_content.append(base64.b64decode(descriptor['data'].encode('utf-8')))
content = b''.join(split_content)
os.makedirs(args.output_dir, exist_ok=True)
output_name = find_free_name(args.output_dir, output_name)
with open(os.path.join(args.output_dir, output_name), 'wb') as f:
f.write(content)
print(f"Stored to {os.path.join(args.output_dir, output_name)}")
if checksum != hashlib.sha256(content).hexdigest():
print("ERROR: invalid checksum!")
exit(1)
if __name__ == "__main__":
main()