forked from pythcoiner/SeedQReader
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathseedqreader.py
More file actions
1384 lines (1102 loc) · 49.1 KB
/
Copy pathseedqreader.py
File metadata and controls
1384 lines (1102 loc) · 49.1 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import re
from dataclasses import dataclass, field
from pathlib import Path
from yaml import load, dump
from yaml.loader import SafeLoader as Loader
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtGui import QImage, QPixmap, QPalette, QColor, QColorConstants, QIcon
from PySide6.QtCore import Qt, QFile, QThread, Signal, QEvent
from PySide6.QtUiTools import QUiLoader
from PySide6.QtGui import QTextOption, QFontDatabase
from PIL import ImageQt
from pyzbar import pyzbar
import zxingcpp
import qrcode
import cv2
import qr_type
from foundation.ur_decoder import URDecoder
from foundation.ur_encoder import UREncoder
from foundation.ur import UR
from urtypes.crypto import PSBT as UR_PSBT
from urtypes.crypto import Account, Output, HDKey, ECKey, MultiKey, Keypath, PathComponent, SCRIPT_EXPRESSION_TAG_MAP
from urtypes.bytes import Bytes
from embit.psbt import PSBT
from embit.descriptor import Descriptor as EmbitDescriptor
from mss import mss
import numpy as np
import base64
import assets_rc
VERSION="1.5.0"
MAX_LEN = 100
FILL_COLOR = "#434343"
STOP_QR_TXT = 'Remove QR'
STOP_READ_TXT = ' Stop'
START_READ_TXT = ' Scan'
GENERATE_TXT = 'Generate QR'
USE_ARROWS_TXT = '(← / → to change)'
ANIMATED_QR_FIRST_FRAME_DELAY = 900 #ms
FORMAT_UR = 'UR'
FORMAT_SPECTER = 'Simple / pMofN (Specter)'
FORMAT_BBQR = 'BBQR'
COMBO_TYPE_DESCRIPTOR = 'Descriptor'
COMBO_TYPE_PSBT = 'PSBT'
COMBO_TYPE_KEY = 'Key'
COMBO_TYPE_BYTES = 'Bytes'
ECC_L = 'ECC L 7%'
ECC_M = 'ECC M 15%'
ECC_Q = 'ECC Q 25%'
ECC_H = 'ECC H 30%'
NO_SPLIT_MAX_CHARS = 999999
PYZBAR_SYMBOLS = (pyzbar.ZBarSymbol.QRCODE, pyzbar.ZBarSymbol.SQCODE)
# helper obj to handle bbqr encoding and file_type
bbqr_obj = None
sequence_reader = 0
def descriptor_to_output(descriptor_str):
"""Convert a descriptor string to a urtypes Output object."""
from embit.networks import NETWORKS
# Parse descriptor using embit
embit_desc = EmbitDescriptor.from_string(descriptor_str)
# Check for advanced miniscript - crypto-output only supports basic descriptors
if hasattr(embit_desc, 'miniscript') and embit_desc.miniscript and not embit_desc.is_basic_multisig:
# Check if it's an advanced miniscript (not just pk/pkh/wpkh)
miniscript_str = str(embit_desc.miniscript)
advanced_operators = ['or_d', 'or_c', 'or_i', 'or_b', 'and_v', 'and_b', 'and_n',
'andor', 'thresh', 'older', 'after', 'sha256', 'hash256',
'ripemd160', 'hash160']
if any(op in miniscript_str for op in advanced_operators):
raise ValueError(f"crypto-output does not support advanced miniscript: {miniscript_str}")
# Check for taproot miniscripts
if hasattr(embit_desc, 'is_taproot') and embit_desc.is_taproot and embit_desc.taptree:
def check_taptree_for_advanced_miniscript(tree_obj):
"""Recursively check taptree for advanced miniscripts."""
advanced_operators = ['or_d', 'or_c', 'or_i', 'or_b', 'and_v', 'and_b', 'and_n',
'andor', 'thresh', 'older', 'after', 'sha256', 'hash256',
'ripemd160', 'hash160']
if hasattr(tree_obj, 'miniscript') and tree_obj.miniscript is not None:
miniscript_str = str(tree_obj.miniscript)
if any(op in miniscript_str for op in advanced_operators):
raise ValueError(f"crypto-output does not support advanced miniscript: {miniscript_str}")
if hasattr(tree_obj, 'tree') and tree_obj.tree is not None:
if isinstance(tree_obj.tree, (list, tuple)):
for item in tree_obj.tree:
check_taptree_for_advanced_miniscript(item)
else:
check_taptree_for_advanced_miniscript(tree_obj.tree)
check_taptree_for_advanced_miniscript(embit_desc.taptree)
# Build script expressions list based on descriptor type
script_expressions = []
script_type = embit_desc.scriptpubkey_type()
# Map embit script types to urtypes script expressions
# sh = 400, wsh = 401, pk = 402, pkh = 403, wpkh = 404, multi = 406, sortedmulti = 407
if embit_desc.is_wrapped:
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[400]) # sh
if script_type == "p2wsh":
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[401]) # wsh
if embit_desc.is_basic_multisig:
if embit_desc.is_sorted:
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[407]) # sortedmulti
else:
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[406]) # multi
elif script_type == "p2wpkh":
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[404]) # wpkh
elif script_type == "p2pkh":
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[403]) # pkh
elif script_type == "p2pk":
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[402]) # pk
elif script_type == "p2tr":
script_expressions.append(SCRIPT_EXPRESSION_TAG_MAP[409]) # tr
# Convert keys
embit_keys = embit_desc.keys
# Handle multisig
if embit_desc.is_basic_multisig:
# Get threshold from the miniscript args
threshold = 1 # default
if hasattr(embit_desc, 'miniscript') and embit_desc.miniscript:
# The first argument is a Number object with the threshold
threshold = embit_desc.miniscript.args[0].num
ec_keys = []
hd_keys = []
for embit_key in embit_keys:
if embit_key.is_extended:
hd_keys.append(_convert_hd_key(embit_key))
else:
ec_keys.append(_convert_ec_key(embit_key))
crypto_key = MultiKey(threshold, ec_keys, hd_keys)
else:
# Single key
embit_key = embit_keys[0]
if embit_key.is_extended:
crypto_key = _convert_hd_key(embit_key)
else:
crypto_key = _convert_ec_key(embit_key)
return Output(script_expressions, crypto_key)
def _convert_ec_key(embit_key):
"""Convert embit Key to urtypes ECKey."""
# Get the public key bytes
pubkey_bytes = embit_key.key.sec()
# ECKey(data, origin=None, name=None)
return ECKey(pubkey_bytes, None, None)
def _convert_hd_key(embit_key):
"""Convert embit extended Key to urtypes HDKey."""
from urtypes.crypto import CoinInfo
xpub = embit_key.key
# Build HDKey dict
hd_dict = {
"private_key": False, # Explicitly mark as public key (required for proper CBOR encoding)
"key": xpub.key.sec(),
"chain_code": xpub.chain_code,
}
# Handle origin (derivation path)
if embit_key.origin:
origin_components = []
for component in embit_key.origin.derivation:
is_hardened = component >= 0x80000000
index = component - 0x80000000 if is_hardened else component
origin_components.append(PathComponent(index, is_hardened))
origin_fingerprint = embit_key.origin.fingerprint
# Set depth to the number of components in the origin path
origin_depth = len(origin_components)
hd_dict["origin"] = Keypath(
origin_components,
origin_fingerprint,
origin_depth
)
# Add use_info for Bitcoin (type=0, network=0 for mainnet, 1 for testnet)
# Determine network from coin type in origin path (coin_type 0 = mainnet, 1 = testnet)
network = 0 # Default to mainnet
if embit_key.origin and len(embit_key.origin.derivation) >= 2:
coin_type = embit_key.origin.derivation[1]
# Remove hardened bit to get coin type value
coin_type_val = coin_type - 0x80000000 if coin_type >= 0x80000000 else coin_type
network = 1 if coin_type_val == 1 else 0
hd_dict["use_info"] = CoinInfo(0, network)
# Parent fingerprint
if hasattr(xpub, 'fingerprint'):
hd_dict["parent_fingerprint"] = xpub.fingerprint
return HDKey(hd_dict)
@dataclass
class QRCode:
data: str = ''
total_sequences: int = 0
sequences_count: int = 0
is_completed: bool = False
qr_type = None
def append(self, data: str):
self.data_init(1)
self.data = data
self.sequences_count += 1
self.is_completed = True
def data_init(self, sequences: int):
self.total_sequences = sequences
self.sequences_count = 0
@dataclass
class MultiQRCode(QRCode):
data_stack: list = field(default_factory=list)
is_init: bool = False
current: int = -1
last_index = current
total_sequences = None
qr_type = None
data_type = None
decoder = None
encoder = None
qr_steps = {}
def step(self):
if self.qr_type in (qr_type.SPECTER, qr_type.BBQR):
self.total_sequences = len(self.data_stack)
return f"{self.current + 1}/{self.total_sequences} {USE_ARROWS_TXT}"
def append(self, data: tuple):
if self.qr_type == qr_type.SPECTER:
self.append_specter(data)
elif self.qr_type == qr_type.UR:
self.append_ur(data)
elif self.qr_type == qr_type.BBQR:
self.append_bbqr(data)
def append_bbqr(self, data: tuple):
data, sequence, total_sequences = data
if not self.is_init:
self.data_init(total_sequences)
self.is_init = True
if not self.data_stack[sequence]:
self.data_stack[sequence] = data
else:
if data != self.data_stack[sequence]:
raise ValueError('Same sequences have different data!')
self.check_complete_bbrq()
def check_complete_bbrq(self):
global bbqr_obj
fill_sequences = 0
for i in self.data_stack:
if i:
fill_sequences += 1
self.sequences_count = fill_sequences
if fill_sequences == self.total_sequences:
from bbqr import decode_bbqr
my_dict = {}
for i, val in enumerate(self.data_stack):
my_dict[i] = val
self.data = decode_bbqr(my_dict, bbqr_obj.encoding, bbqr_obj.file_type)
self.is_completed = True
def append_specter(self, data: tuple):
# print(f'MultiQRCode.append({data})')
sequence = data[0]
total_sequences = data[1]
data = data[2]
if not self.is_init:
self.data_init(total_sequences)
self.is_init = True
if not self.data_stack[sequence-1]:
self.data_stack[sequence-1] = data
else:
if data != self.data_stack[sequence-1]:
print(f"{data} != {self.data_stack[sequence-1]}")
raise ValueError('Same sequences have different data!')
self.check_complete_specter()
def append_ur(self, data: tuple):
if not self.decoder:
self.decoder = URDecoder()
self.decoder.receive_part(data)
self.check_complete_ur()
def data_init(self, sequences: int):
super().data_init(sequences)
self.data_stack = [None] * sequences
def check_complete_specter(self):
fill_sequences = 0
for i in self.data_stack:
if i:
fill_sequences += 1
self.sequences_count = fill_sequences
if fill_sequences == self.total_sequences:
self.is_completed = True
data = ''
for i in self.data_stack:
data += i
self.data = data
def check_complete_ur(self):
if self.decoder.is_complete():
if self.decoder.is_success():
self.is_completed = True
cbor = self.decoder.result_message().cbor
_type = self.decoder.result_message().type
# XPub
if _type == 'crypto-account':
self.data = Account.from_cbor(cbor).output_descriptors[0].descriptor()
# PSBT
elif _type == 'crypto-psbt':
self.data = UR_PSBT.from_cbor(cbor).data
if type(self.data) is bytes:
self.data = PSBT.parse(self.data).to_string()
# Descriptor
elif _type == 'crypto-output':
self.data = Output.from_cbor(cbor).descriptor()
# bytes
elif _type == 'bytes':
self.data = Bytes.from_cbor(cbor).data
if isinstance(self.data, bytes):
try:
self.data = self.data.decode('utf-8')
except:
self.data = self.data.hex()
# unknown
else:
print(f"\nUR type not yet implemented: {_type}")
return
# print(f"\nUR type: {_type}")
# decodef fail!
else:
print("fail to complete UR parsing: ", end='')
print(self.decoder.result_error())
@staticmethod
def from_string(data, _max=MAX_LEN, type=None, format=None):
if (_max and len(data) > _max) or format == FORMAT_UR or format == FORMAT_BBQR:
out = MultiQRCode()
out.data = data
if format == FORMAT_UR:
out.qr_type = qr_type.UR
elif format == FORMAT_SPECTER:
out.qr_type = qr_type.SPECTER
elif format == FORMAT_BBQR:
out.qr_type = qr_type.BBQR
if format == FORMAT_SPECTER:
while len(data) > _max:
sequence = data[:_max]
data = data[_max:]
out.data_stack.append(sequence)
if len(data):
out.data_stack.append(data)
out.total_sequences = len(out.data_stack)
out.sequences_count = out.total_sequences
out.is_completed = True
elif format == FORMAT_BBQR:
from bbqr import encode_bbqr
try:
# print(data)
data_bytes = base64.b64decode(data)
except:
print("Error executing b64decode for BBQR, will encode as utf-8")
data_bytes = bytes(data, "utf-8")
pass
bb = encode_bbqr(data_bytes)
if (_max < NO_SPLIT_MAX_CHARS):
# adjust BBQR size from 10-500 to 23-200
old_min, old_max = 10, 500
new_min, new_max = 23, 100
scaled_value = new_min + ((_max - old_min) * (new_max - new_min)) / (old_max - old_min)
_max = int(round(scaled_value))
count = 1
for sequence, total in bb.to_qr_code(_max):
out.data_stack.append(sequence)
count += 1
if count > total:
break
out.total_sequences = total
out.sequences_count = out.total_sequences
out.is_completed = True
if total == 1:
out.data = sequence
elif format == FORMAT_UR:
if not _max:
_max = 100000
if type == COMBO_TYPE_PSBT:
out.data_type = 'crypto-psbt'
data = PSBT.from_string(data).serialize()
ur = UR(out.data_type, UR_PSBT(data).to_cbor())
elif type == COMBO_TYPE_DESCRIPTOR:
# Try to encode as crypto-output, fall back to bytes for complex descriptors
try:
out.data_type = 'crypto-output'
output_obj = descriptor_to_output(data)
ur = UR(out.data_type, output_obj.to_cbor())
except Exception as e:
print(f"Cannot encode as crypto-output ({e}), encoding as bytes instead")
out.data_type = 'bytes'
ur = UR(out.data_type, Bytes(data).to_cbor())
elif type == COMBO_TYPE_KEY:
out.data_type = 'bytes'
ur = UR(out.data_type, Bytes(data).to_cbor())
elif type == COMBO_TYPE_BYTES:
out.data_type = 'bytes'
ur = UR(out.data_type, Bytes(data).to_cbor())
else:
return
out.encoder = UREncoder(ur, _max)
out.total_sequences = out.encoder.fountain_encoder.seq_len()
else:
# SINGLE NORMAL QR CODE
out = QRCode()
out.data = data
out.data_init(1)
return out
def next(self, is_prev = False) -> str:
data = None
if self.qr_type in (qr_type.SPECTER, qr_type.BBQR):
if is_prev:
self.current -= 1
if self.current < 0:
self.current = self.total_sequences - 1
else:
self.current += 1
if self.current >= self.total_sequences:
self.current = 0
data = self.data_stack[self.current]
if self.qr_type == qr_type.SPECTER:
digit_a = self.current + 1
digit_b = self.total_sequences
data = f"p{digit_a}of{digit_b} {data}"
elif self.qr_type == qr_type.UR:
if not is_prev:
if self.current == self.last_index:
self.current = self.encoder.fountain_encoder.seq_num
data = self.encoder.next_part().upper()
self.qr_steps[self.current] = data # store new value to dict
self.last_index = self.current # store last known index
else:
self.current += 1
data = self.qr_steps[self.current] # get store val on dict
else: # get prev value on dict
self.current -= 1
if self.current < 0:
self.current = 0
data = self.qr_steps.get(self.current)
return data
class ReadQR(QThread):
data = Signal(object)
video_stream = Signal(object)
def __init__(self, parent):
QThread.__init__(self)
self.parent = parent
self.finished.connect(self.on_finnish)
self.qr_data: QRCode | MultiQRCode = None
self.capture = None
self.ecc_read = None
self.version_read = []
self.len_read = 0
self.end = False
self.viaCamera = True
def run(self):
self.qr_data: QRCode | MultiQRCode = None
self.ecc_read = None
self.version_read = []
self.len_read = 0
global sequence_reader
if self.viaCamera:
# Initialize the camera
camera_id = self.parent.get_camera_id()
if camera_id is None:
return
self.capture = cv2.VideoCapture(camera_id)
self.parent.ui.btn_start_read.setText(' '.join(self.parent.ui.btn_start_read.text().split(' ')[:-1]) + STOP_READ_TXT)
self.parent.ui.monitor_group.setDisabled(True)
else:
# Initialize the monitor
monitor_id = self.parent.get_monitor_id()
if monitor_id is None:
return
else:
monitor_id += 1
self.parent.ui.btn_start_read_monitor.setText(' '.join(self.parent.ui.btn_start_read_monitor.text().split(' ')[:-1]) + STOP_READ_TXT)
self.parent.ui.camera_group.setDisabled(True)
while not self.end:
self.msleep(30)
if self.viaCamera:
ret, frame = self.capture.read()
else:
ret = True
with mss() as sct:
# Get a screenshot of the monitor
monitor = sct.monitors[monitor_id]
width = monitor['width']
height = monitor['height']
screenshot = sct.grab(sct.monitors[monitor_id])
if ret:
if self.viaCamera:
# Convert the frame to RGB format
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Create a QImage from the frame data
height, width, _ = frame.shape
image = QImage(frame.data, width, height, QImage.Format_RGB888)
else:
# Convert to numpy array (BGRA format)
img_data = np.frombuffer(screenshot.rgb, dtype=np.uint8)
frame = img_data.reshape((screenshot.height, screenshot.width, 3))
frame = np.ascontiguousarray(frame)
# Add an alpha channel to convert RGB to RGBA
alpha_channel = np.full((height, width, 1), 255, dtype=np.uint8) # Fully opaque
img_data = np.concatenate([frame, alpha_channel], axis=2) # Append alpha
# Convert RGB to RGBA (ensure correct channel order for QImage)
img_data = img_data[:, :, [0, 1, 2, 3]] # Already in correct order, but explicit for clarity
img_data = np.ascontiguousarray(img_data)
# Create QImage from the data
image = QImage(
img_data.data,
screenshot.width,
screenshot.height,
screenshot.width * 4, # Bytes per line
QImage.Format_RGBA8888
)
# Ensure the data is not garbage-collected
image.ndarray = img_data
# Create a QPixmap from the QImage
pixmap = QPixmap.fromImage(image)
# Scale the QPixmap to fit the label dimensions
scaled_pixmap = pixmap.scaled(self.parent.ui.video_in.size(), Qt.KeepAspectRatio)
# Set the pixmap to the label
self.video_stream.emit(scaled_pixmap)
data = pyzbar.decode(frame, PYZBAR_SYMBOLS, binary=True)
str_data = ""
results = None
# data = None
if not data:
# Try other lib
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = zxingcpp.read_barcodes(rgb)
if not results:
# Try to invert colors
frame = cv2.bitwise_not(frame)
data = pyzbar.decode(frame, PYZBAR_SYMBOLS)
if not data:
# Try other lib
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = zxingcpp.read_barcodes(rgb)
if data or results:
# print(data)
# print(results)
try:
if data:
data = data[0].data
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = zxingcpp.read_barcodes(rgb)
if results:
# print(results[0].bytes)
ecc = results[0].ec_level
self._parse_ecc_and_version(data, ecc)
elif results:
data = results[0].bytes
ecc = results[0].ec_level
self._parse_ecc_and_version(data, ecc)
sequence_reader += 1
if isinstance(data, bytes):
print(f"\n#{sequence_reader} BYTES in HEX (raw data):")
print(data.hex())
print(f"\n#{sequence_reader} RAW data:")
try:
print(data)
except Exception as e:
print("\nException trying to print data:", e)
if isinstance(data, bytes):
try:
str_data = data.decode("utf-8")
except:
str_data = data.hex()
else:
str_data = data
# Try to decode
try:
self.decode(str_data)
except Exception as e:
import traceback
traceback.print_exc()
print("Can't decode str_data", e)
except Exception as e:
print("Another Exception:", e)
if self.qr_data:
if self.qr_data.is_completed:
self.video_stream.emit(None)
self.data.emit(self.qr_data.data)
print(f"\n#{sequence_reader} PARSED str data:")
print(self.qr_data.data)
break
if self.end:
self.video_stream.emit(None)
return
def _parse_ecc_and_version(self, data, ecc):
if ecc == "L":
self.ecc_read = ECC_L
level = qrcode.constants.ERROR_CORRECT_L
elif ecc == "M":
self.ecc_read = ECC_M
level = qrcode.constants.ERROR_CORRECT_M
elif ecc == "Q":
self.ecc_read = ECC_Q
level = qrcode.constants.ERROR_CORRECT_Q
elif ecc == "H":
self.ecc_read = ECC_H
level = qrcode.constants.ERROR_CORRECT_H
else:
return
qr = qrcode.QRCode(error_correction=level)
qr.add_data(data)
qr.make(fit=False)
# print(data, qr.version, self.version_read)
self.version_read.append(qr.version)
self.len_read += len(data)
def decode(self, data):
'''Multipart QR Code case'''
# specter format
if re.match(r'^p\d+of\d+\s', data, re.IGNORECASE):
if not self.qr_data:
self.qr_data = MultiQRCode()
self.qr_data.qr_type = qr_type.SPECTER
header = data.split(' ')[0][1:].split('of')
data = ' '.join(data.split(' ')[1:])
digit_a = header[0]
digit_b = header[1]
self.qr_data.append((int(digit_a), int(digit_b), data))
progress = round(self.qr_data.sequences_count / self.qr_data.total_sequences * 100)
self.parent.ui.read_progress.setValue(progress)
self.parent.ui.read_progress.setFormat(f"{self.qr_data.sequences_count}/{self.qr_data.total_sequences}")
self.parent.ui.read_progress.setVisible(True)
# UR format
elif re.match(r'^UR:', data, re.IGNORECASE):
# single/multi QR UR
if not self.qr_data:
self.qr_data = MultiQRCode()
self.qr_data.qr_type = qr_type.UR
self.qr_data.append(data)
try:
self.qr_data.total_sequences = self.qr_data.decoder.expected_part_count()
self.qr_data.sequences_count = len(self.qr_data.decoder.received_part_indexes())
progress = round(self.qr_data.sequences_count / self.qr_data.total_sequences * 100) # self.qr_data.decoder.estimated_percent_complete() * 100
self.parent.ui.read_progress.setValue(progress)
self.parent.ui.read_progress.setFormat(f"{self.qr_data.sequences_count}/{self.qr_data.total_sequences}")
self.parent.ui.read_progress.setVisible(True)
except:
self.qr_data.sequences_count = 0
self.qr_data.total_sequences = 0
elif data.startswith("B$"):
global bbqr_obj
if bbqr_obj is None:
from bbqr import BBQrCode, KNOWN_ENCODINGS, KNOWN_FILETYPES
if data[3] in KNOWN_FILETYPES:
bbqr_file_type = data[3]
if data[2] in KNOWN_ENCODINGS:
bbqr_encoding = data[2]
bbqr_obj = BBQrCode(None, bbqr_encoding, bbqr_file_type)
from bbqr import parse_bbqr
parsed_data = parse_bbqr(data)
if not self.qr_data:
self.qr_data = MultiQRCode()
self.qr_data.qr_type = qr_type.BBQR
self.qr_data.append(parsed_data)
progress = round(self.qr_data.sequences_count / self.qr_data.total_sequences * 100)
self.parent.ui.read_progress.setValue(progress)
self.parent.ui.read_progress.setFormat(f"{self.qr_data.sequences_count}/{self.qr_data.total_sequences}")
self.parent.ui.read_progress.setVisible(True)
# Other format
else:
self.qr_data = QRCode()
self.qr_data.append(data)
if self.version_read:
self.version_read = self.version_read[-1]
def on_finnish(self):
if self.capture:
self.capture.release()
self.parent.ui.read_progress.setValue(0)
self.parent.ui.read_progress.setVisible(False)
self.parent.ui.read_progress.setFormat('')
self.parent.ui.btn_start_read.setText(' '.join(self.parent.ui.btn_start_read.text().split(' ')[:-1]) + START_READ_TXT)
self.parent.ui.btn_start_read_monitor.setText(' '.join(self.parent.ui.btn_start_read_monitor.text().split(' ')[:-1]) + START_READ_TXT)
self.parent.ui.monitor_group.setDisabled(False)
self.parent.ui.camera_group.setDisabled(False)
class DisplayQR(QThread):
video_stream = Signal(object)
def __init__(self, parent, delay):
QThread.__init__(self)
self.parent = parent
self.set_delay(delay)
self.qr_data: QRCode | MultiQRCode = None
self.stop = True
def set_delay(self, delay):
self.delay = delay
def process_run(self, sleep_delay=0, is_prev = False):
data = self.qr_data.next(is_prev)
if self.qr_data.total_sequences > 1:
self.parent.ui.steps.setText(self.qr_data.step())
self.display_qr(data)
self.msleep(sleep_delay)
def run(self):
self.stop = False
if self.qr_data.total_sequences > 1:
remove_qr = True
self.process_run(self.delay + ANIMATED_QR_FIRST_FRAME_DELAY)
while not (self.stop or self.parent.arrow_pressed):
self.process_run(self.delay)
if self.stop and remove_qr:
self.video_stream.emit(None)
elif self.qr_data.total_sequences == 1:
if self.qr_data.qr_type == qr_type.UR:
self.process_run(self.delay)
else:
data = self.qr_data.data
self.display_qr(data)
def mode_to_str(self, mode):
if mode == qrcode.util.MODE_NUMBER:
return "numeric"
if mode == qrcode.util.MODE_ALPHA_NUM:
return "alphanumeric"
if mode == qrcode.util.MODE_8BIT_BYTE:
return "byte"
return "kanji"
def display_qr(self, data):
try:
level = qrcode.constants.ERROR_CORRECT_L
if self.parent.error_correction == ECC_M:
level = qrcode.constants.ERROR_CORRECT_M
elif self.parent.error_correction == ECC_Q:
level = qrcode.constants.ERROR_CORRECT_Q
elif self.parent.error_correction == ECC_H:
level = qrcode.constants.ERROR_CORRECT_H
qr = qrcode.QRCode(error_correction=level)
qr.add_data(data)
qr.make(fit=False)
modes = set()
for element in qr.data_list:
modes.add(self.mode_to_str(element.mode))
original_data: str = self.parent.ui.data_out.toPlainText()
original_data.replace(' ', '').replace('\n', '')
self.parent.ui.info_send.setText(f"Version {qr.version} - {len(data)} chars ({', '.join(modes)}) - Source: {len(original_data)} chars")
img = qr.make_image()
pil_image = img.convert("RGB")
qimage = ImageQt.ImageQt(pil_image)
# invert QR colors
if self.parent.ui.inverted.isChecked():
qimage.invertPixels()
qimage = qimage.convertToFormat(QImage.Format_RGB888)
# Create a QPixmap from the QImage
pixmap = QPixmap.fromImage(qimage)
scaled_pixmap = pixmap.scaled(self.parent.ui.video_out.size(), Qt.KeepAspectRatio)
self.video_stream.emit(scaled_pixmap)
except Exception as e:
print("error making QR", e)
class MainWindow(QMainWindow):
def __init__(self, loader):
super().__init__()
# Set up the main window
path = os.fspath(Path(__file__).resolve().parent / "form.ui")
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
self.ui = loader.load(ui_file, self)
# Disable tabWidget capture of arrow left/right
self.ui.tabWidget.tabBar().setFocusPolicy(Qt.NoFocus)
self.arrow_pressed = False
ui_file.close()
self.setWindowTitle("SeedQReader " + VERSION)
self.setWindowIcon(QIcon(':/assets/icon.png'))
self.setFixedSize(self.ui.tabWidget.width(),self.ui.tabWidget.height())
self.setCentralWidget(self.ui)
self.load_config()
self.ui.btn_start_read.clicked.connect(self.on_qr_read_camera)
self.ui.btn_start_read_monitor.clicked.connect(self.on_qr_read_monitor)
self.ui.btn_generate.clicked.connect(self.on_btn_generate)
self.ui.btn_clear.clicked.connect(self.on_btn_clear)
self.ui.send_slider.valueChanged.connect(self.on_slider_move)
self.ui.delay_slider.valueChanged.connect(self.on_delay_slider_move)
self.ui.no_split.stateChanged.connect(self.on_no_split_change)
QApplication.instance().installEventFilter(self)
# use monospace font for data in/out boxes
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
self.ui.data_out.setFont(font)
self.ui.data_in.setFont(font)
self.ui.steps.setFont(font)
self.ui.info_send.setFont(font)
self.ui.info_read.setFont(font)
self.ui.data_out.setWordWrapMode(QTextOption.WrapAnywhere)
self.ui.data_in.setWordWrapMode(QTextOption.WrapAnywhere)
# init radio button
self.ui.desc_1.toggled.connect(self.on_radio_toggled)
self.ui.desc_2.toggled.connect(self.on_radio_toggled)
self.ui.desc_3.toggled.connect(self.on_radio_toggled)
self.ui.psbt_1.toggled.connect(self.on_radio_toggled)
self.ui.psbt_2.toggled.connect(self.on_radio_toggled)
self.ui.psbt_3.toggled.connect(self.on_radio_toggled)
self.ui.psbt_4.toggled.connect(self.on_radio_toggled)
self.ui.psbt_5.toggled.connect(self.on_radio_toggled)
self.ui.key_1.toggled.connect(self.on_radio_toggled)
self.ui.key_2.toggled.connect(self.on_radio_toggled)
self.ui.key_3.toggled.connect(self.on_radio_toggled)
self.ui.key_4.toggled.connect(self.on_radio_toggled)
self.ui.key_5.toggled.connect(self.on_radio_toggled)
self.ui.desc_1.setChecked(True)
self.radio_selected = 'desc_1'
self.on_radio_toggled()
self.ui.btn_save.clicked.connect(self.on_btn_save)
self.ui.combo_format.addItems([FORMAT_SPECTER, FORMAT_UR, FORMAT_BBQR])
self.format = self.ui.combo_format.currentText()
self.ui.combo_format.currentIndexChanged.connect(self.on_format_change)
self.ui.combo_type.currentIndexChanged.connect(self.on_data_type_change)
self.ui.combo_error.addItems([ECC_L, ECC_M, ECC_Q, ECC_H])
self.error_correction = self.ui.combo_error.currentText()
self.ui.combo_error.currentIndexChanged.connect(self.on_error_change)
self.ui.steps.setAlignment(Qt.AlignHCenter)
self.ui.combo_type.addItems([COMBO_TYPE_DESCRIPTOR, COMBO_TYPE_PSBT, COMBO_TYPE_KEY, COMBO_TYPE_BYTES])
self.ui.combo_type.hide()
self.data_type = None
self.ui.btn_camera_update.clicked.connect(self.on_camera_update)
self.ui.btn_monitor_update.clicked.connect(self.on_monitor_update)
self.on_slider_move()
self.on_delay_slider_move()
self.on_camera_update()