-
Notifications
You must be signed in to change notification settings - Fork 0
/
__main__.py
319 lines (269 loc) · 11.6 KB
/
__main__.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
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
import subprocess
from PyQt6.QtWidgets import QFileDialog
import copy
from PIL.ImageQt import ImageQt
import qrcode
from threading import Thread
from PyQt6 import QtGui, QtCore, QtWidgets
from PyQt6.QtWidgets import QMainWindow, QApplication
from PyQt6.uic import loadUiType
from PyQt6.QtGui import QPixmap
import cv2
import numpy as np
from pyzbar.pyzbar import decode
from PyQt6.QtCore import pyqtSignal, Qt
import time
import os
import pyperclip
import webbrowser
import platform
if __file__ and os.path.exists(__file__):
os.chdir(os.path.dirname(__file__))
def qr_decoder(image):
gray_img = cv2.cvtColor(image, 0)
qr_code = decode(gray_img)
for obj in qr_code:
points = obj.polygon
(x, y, w, h) = obj.rect
pts = np.array(points, np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(image, [pts], True, (0, 255, 0), 3)
cv2.putText(image, obj.data.decode(), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
return {"image": image, "type": obj.type, "data": obj.data}
abs_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)))
if os.path.exists(os.path.join(abs_dir, 'ScanGen.ui')):
os.chdir(abs_dir)
Ui_MainWindow, QMainWindow = loadUiType('ScanGen.ui')
else:
from ScanGen import Ui_MainWindow
class ScanGen(QMainWindow, Ui_MainWindow):
data = ""
update_qr_code_sig = pyqtSignal()
update_text_sig = pyqtSignal()
search_for_cameras_sig = pyqtSignal()
update_camera_list_sig = pyqtSignal(list)
current_camera_info = None
radio_buttons = []
closing = False
def __init__(self, ):
super(ScanGen, self).__init__()
self.setupUi(self)
bundle_dir = getattr(
sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
self.setWindowIcon(QtGui.QIcon(os.path.join(bundle_dir, 'Icon.svg')))
self.setWindowTitle("QR ScanGen")
self.update_text_sig.connect(self.update_text)
self.update_qr_code_sig.connect(self.update_qr_code)
self.search_for_cameras_sig.connect(self.search_for_cameras)
self.update_camera_list_sig.connect(self.udpate_camera_list)
self.qr_code_lbl.mousePressEvent = self.save_qr_file
Thread(target=self.run_scanner, args=()).start()
# self.search_for_cameras_sig.emit()
print("ready")
def update_qr_code(self):
qr_code = self.generate_qr_code(self.data)
image = ImageQt(qr_code)
self.qr_code_lbl.setPixmap(QtGui.QPixmap.fromImage(image))
def update_text(self):
self.text_txbx.setPlainText(self.data)
def list_camera_ports(self):
"""
Test the ports and returns a tuple with the available ports and the ones that are working.
"""
non_working_ports = []
available_cameras = []
# iterate through ports starting at 0.
# if there are more than 5 non working ports stop the testing.
dev_port = 0
while len(non_working_ports) < 6:
if self.current_camera_info and dev_port == self.current_camera_info['port']:
available_cameras.append(self.current_camera_info)
else:
camera = cv2.VideoCapture(dev_port)
if camera.isOpened():
is_reading, img = camera.read()
w = camera.get(3)
h = camera.get(4)
if is_reading:
width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = camera.get(cv2.CAP_PROP_FPS)
camera_name = get_camera_name(dev_port)
camera_info = {
"port": dev_port,
"name": camera_name,
"width": width,
"height": height,
"fps": fps
}
available_cameras.append(camera_info)
else:
non_working_ports.append(dev_port)
camera.release()
dev_port += 1
if not self.current_camera_info: # if Scanner currently doesn't know which camera to use
self.current_camera_info = available_cameras[0]
return available_cameras
def change_camera(self, e):
self.current_camera_info = self.sender().camera_info
testing_camera_ports = False
def search_for_cameras(self):
if self.testing_camera_ports:
return
self.testing_camera_ports = True
def _search_for_cameras():
working_cameras = self.list_camera_ports()
self.update_camera_list_sig.emit(working_cameras)
self.testing_camera_ports = False
Thread(target=_search_for_cameras, args=()).start()
def udpate_camera_list(self, working_cameras: list):
for radio_button in self.radio_buttons:
try:
radio_button.deleteLater()
except:
pass
for cam_info in working_cameras:
label = f"{cam_info['port']} {cam_info['name']}"
radio_button = QtWidgets.QRadioButton(label, self.right_frame)
radio_button.camera_info = cam_info
if cam_info['port'] == self.current_camera_info['port']:
radio_button.setChecked(True)
radio_button.clicked.connect(self.change_camera)
self.right_frame_lyt.addWidget(radio_button)
self.radio_buttons.append(radio_button)
def run_scanner(self):
while True: # camera usage session loop (new iteration only when user changes camera)
if self.closing:
return
self.search_for_cameras_sig.emit()
while self.current_camera_info is None:
time.sleep(0.1)
current_camera_port = copy.deepcopy(self.current_camera_info['port'])
cap = cv2.VideoCapture(current_camera_port)
try:
while True:
if self.closing:
cap.release()
return
if current_camera_port != self.current_camera_info['port']:
cap.release()
break
ret, frame = cap.read()
result = qr_decoder(frame)
if result is not None:
frame = result["image"]
data = result["data"].decode()
if data != self.data:
self.data = data
self.update_text_sig.emit()
self.update_qr_code_sig.emit()
Thread(target=self.analyse_scanned_code, args=()).start()
pyperclip.copy(self.data)
else:
if self.text_txbx.toPlainText() != self.data:
self.data = self.text_txbx.toPlainText()
self.update_qr_code_sig.emit()
self.camera_image = convert_cv_qt(
frame,
self.scanner_video_lbl.width(),
self.scanner_video_lbl.height()
)
self.scanner_video_lbl.setPixmap(self.camera_image)
code = cv2.waitKey(10)
if code == ord('q'):
cap.release()
break
except Exception as error:
print(error)
print(f"Error working with camera {self.current_camera_info['port']}")
cap.release()
self.current_camera_info = None
self.search_for_cameras_sig.emit()
while self.current_camera_info is None:
time.sleep(0.1)
# self.search_for_cameras()
def analyse_scanned_code(self):
# WIFI analysis
elements = [e.split(":") for e in self.data.split(";")]
if len(elements) > 2 and elements[0][0] == "WIFI" and elements[0][1] == "S" and elements[1][0] == "T" and elements[2][0] == "P":
ssid = elements[0][2]
type = elements[1][1]
password = elements[2][1]
import pywifi
profile = pywifi.Profile()
profile.ssid = ssid
profile.auth = pywifi.const.AUTH_ALG_OPEN
if type == "" or type.lower == "none":
profile.akm.append(pywifi.const.AKM_TYPE_NONE)
if type == "WPA":
profile.akm.append(pywifi.const.AKM_TYPE_WPA)
if type == "WPAPSK":
profile.akm.append(pywifi.const.AKM_TYPE_WPAPSK)
if type == "WPA2":
profile.akm.append(pywifi.const.AKM_TYPE_WPA2)
if type == "WPA2PSK":
profile.akm.append(pywifi.const.AKM_TYPE_WPA2PSK)
# profile.cipher = pywifi.const.CIPHER_TYPE_CCMP
profile.key = password
try:
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
profile = iface.add_network_profile(profile)
iface.connect(profile)
except PermissionError:
# handling permission denied error on linux
if platform.system() == 'Linux':
os.system(f"nmcli dev wifi connect '{ssid}' password '{password}'")
if is_website(self.data):
webbrowser.open_new_tab(self.data)
def generate_qr_code(self, text):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=3,
border=4, # number of pixels is this * box_size
)
qr.add_data(text) # give QRCode object our text to encode
qr.make(fit=True) # generate QR code from our text
# we would like our QR code to be about as high as the camera image displayed
desired_height = self.camera_image.height()
# get the number of squares along an edge of the QR code
qr_height_squares = len(qr.get_matrix())
# calculate how many pixels should be used to display one square of the QR code
qr.box_size = int((desired_height)/(qr_height_squares+2*qr.border))
return qr.make_image() # generate and return QR code image
def save_qr_file(self, eventargs):
"""Saves the currently displayed QR-Code to a file,
after opening a file dialog asking the user for the file path"""
filepath, ok = QFileDialog.getSaveFileName(
self, 'Save QR Code', "", ("Images (*.png)"))
if filepath:
if filepath[-4:].lower() != ".png":
print(filepath[-4:].lower())
filepath += ".png"
self.qr_code_lbl.pixmap().save(filepath)
def closeEvent(self, event):
self.closing = True
event.accept()
def convert_cv_qt(cv_img, width, height):
"""Convert from an opencv image to QPixmap"""
rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
h, w, ch = rgb_image.shape
bytes_per_line = ch * w
convert_to_Qt_format = QtGui.QImage(
rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format.Format_RGB888)
p = convert_to_Qt_format.scaled(width, height, Qt.AspectRatioMode.KeepAspectRatio)
return QPixmap.fromImage(p)
def is_website(text):
return text.startswith("https://") or text.startswith("http://")
def get_camera_name(camera_index):
if platform.system() == 'Linux':
return ''
else:
return ''
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = ScanGen()
main.show()
sys.exit(app.exec())