-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqr_code.py
More file actions
342 lines (277 loc) Β· 13.8 KB
/
Copy pathqr_code.py
File metadata and controls
342 lines (277 loc) Β· 13.8 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
import tkinter as tk
from tkinter import filedialog, colorchooser, messagebox, simpledialog
import qrcode
from PIL import Image, ImageTk
import cv2
import numpy as np
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import os
import base64
from fpdf import FPDF
import ttkbootstrap as tb
from ttkbootstrap.scrolled import ScrolledFrame
import pandas as pd
import os
import csv
class QRApp:
def __init__(self, root):
self.root = root
self.root.title("VeriCode")
self.root.geometry("900x800")
self.style = tb.Style("cosmo")
self.notebook = tb.Notebook(root, bootstyle="primary")
self.notebook.pack(fill="both", expand=True, padx=20, pady=20)
self.is_dark_mode = False
self.dark_bg_color = "#1c1c1c"
self.light_bg_color = "#f9f9f9"
self.gen_tab = tk.Frame(self.notebook, bg=self.light_bg_color)
self.scan_tab = tk.Frame(self.notebook, bg=self.light_bg_color)
self.notebook.add(self.gen_tab, text="β Generate QR")
self.notebook.add(self.scan_tab, text="π· Scan QR")
self.fg_color = "black"
self.bg_color = "white"
self.qr_img = None
self.logo_path = None
self.build_generate_tab()
self.build_scan_tab()
self.toggle_btn = tb.Button(root, text="π Dark Mode", command=self.toggle_dark_mode)
self.toggle_btn.pack(pady=10)
def toggle_dark_mode(self):
self.is_dark_mode = not self.is_dark_mode
if self.is_dark_mode:
self.style.theme_use("darkly")
bg_color = self.dark_bg_color
self.toggle_btn.config(text="βοΈ Light Mode")
else:
self.style.theme_use("cosmo")
bg_color = self.light_bg_color
self.toggle_btn.config(text="π Dark Mode")
self.gen_tab.config(bg=bg_color)
self.scan_tab.config(bg=bg_color)
for widget in self.gen_tab.winfo_children():
if isinstance(widget, ScrolledFrame):
for child in widget.winfo_children():
if isinstance(child, tk.Label):
child.config(bg=bg_color)
if isinstance(widget, tk.Label):
widget.config(bg=bg_color)
for widget in self.scan_tab.winfo_children():
if isinstance(widget, tk.Label):
widget.config(bg=bg_color)
def build_generate_tab(self):
scrolled_frame = ScrolledFrame(self.gen_tab)
scrolled_frame.pack(fill="both", expand=True)
tk.Label(scrolled_frame, text="Generate QR Code", font=("Arial", 20, "bold"), bg=self.light_bg_color).pack(pady=15)
self.data_entry = tb.Entry(scrolled_frame, width=60)
self.data_entry.pack(pady=10)
btn_frame = tk.Frame(scrolled_frame, bg=self.light_bg_color)
btn_frame.pack(pady=5)
tb.Button(btn_frame, text="π¨ Foreground", command=self.choose_fg).pack(side="left", padx=5)
tb.Button(btn_frame, text="π¨ Background", command=self.choose_bg).pack(side="left", padx=5)
self.pass_var = tk.BooleanVar()
tb.Checkbutton(scrolled_frame, text="Password Protect", variable=self.pass_var, bootstyle="info").pack(pady=5)
self.pass_entry = tb.Entry(scrolled_frame, width=30, show="*")
self.pass_entry.pack(pady=5)
file_frame = tk.Frame(scrolled_frame, bg=self.light_bg_color)
file_frame.pack(pady=5)
tb.Button(file_frame, text="π Upload File", bootstyle="secondary", command=self.upload_file).pack(side="left", padx=5)
tb.Button(file_frame, text="πΌοΈ Upload Logo", bootstyle="info", command=self.upload_logo).pack(side="left", padx=5)
generate_btn_frame = tk.Frame(scrolled_frame, bg=self.light_bg_color)
generate_btn_frame.pack(pady=15)
tb.Button(generate_btn_frame, text="Generate QR", bootstyle="success", command=self.generate_qr).pack(side="left", padx=5)
tb.Button(generate_btn_frame, text="Generate from File", bootstyle="primary", command=self.generate_batch_qr).pack(side="left", padx=5)
self.qr_label = tk.Label(scrolled_frame, bg=self.light_bg_color)
self.qr_label.pack(pady=10)
save_frame = tk.Frame(scrolled_frame, bg=self.light_bg_color)
save_frame.pack(pady=5)
tb.Button(save_frame, text="Save as PNG", command=lambda: self.save_qr("png")).pack(side="left", padx=5)
tb.Button(save_frame, text="Save as JPG", command=lambda: self.save_qr("jpg")).pack(side="left", padx=5)
tb.Button(save_frame, text="Save as PDF", command=lambda: self.save_qr("pdf")).pack(side="left", padx=5)
def _generate_and_save_qr(self, data, file_path):
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color=self.fg_color, back_color=self.bg_color).convert("RGB")
if self.logo_path:
try:
logo = Image.open(self.logo_path)
qr_width, qr_height = img.size
logo_size = int(qr_width * 0.2)
logo.thumbnail((logo_size, logo_size), Image.LANCZOS)
box = Image.new('RGB', (logo_size + 20, logo_size + 20), 'white')
box.paste(logo, (10, 10))
pos = ((qr_width - box.size[0]) // 2, (qr_height - box.size[1]) // 2)
img.paste(box, pos)
except Exception as e:
messagebox.showerror("Error", f"Could not embed logo: {e}")
self.logo_path = None
img.save(file_path)
def generate_batch_qr(self):
file_path = filedialog.askopenfilename(
filetypes=[("Excel Files", "*.xlsx *.xls"), ("CSV Files", "*.csv")]
)
if not file_path:
return
column_letter = simpledialog.askstring("Roll No Column", "Enter the letter of the column with Roll Numbers (e.g., 'A', 'B'):")
if not column_letter or len(column_letter) != 1 or not column_letter.isalpha():
messagebox.showerror("Invalid Input", "Please enter a single letter (e.g., A, B).")
return
column_index = ord(column_letter.upper()) - ord('A')
save_dir = filedialog.askdirectory(title="Select a folder to save QR codes")
if not save_dir:
return
try:
if file_path.endswith('.csv'):
df = pd.read_csv(file_path)
else:
df = pd.read_excel(file_path)
if column_index >= len(df.columns):
messagebox.showerror("Error", f"Column '{column_letter.upper()}' does not exist in the file.")
return
qr_count = 0
for index, row in df.iterrows():
roll_no = row.iloc[column_index]
if pd.isna(roll_no):
continue
qr_data_parts = [f"{col}: {row[col]}" for col in df.columns]
qr_data_string = " | ".join(qr_data_parts)
file_name = f"{roll_no}.png"
output_path = os.path.join(save_dir, file_name)
self._generate_and_save_qr(qr_data_string, output_path)
qr_count += 1
messagebox.showinfo("Success", f"Successfully generated {qr_count} QR codes in '{save_dir}'")
except FileNotFoundError:
messagebox.showerror("Error", "File not found.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def build_scan_tab(self):
frame = self.scan_tab
tk.Label(frame, text="Scan QR Code", font=("Arial", 20, "bold"), bg=self.light_bg_color).pack(pady=15)
tb.Button(frame, text="Upload QR Image", bootstyle="primary", command=self.scan_upload).pack(pady=10)
self.scan_result = tk.Text(frame, height=10, width=70, wrap="word")
self.scan_result.pack(pady=10)
def choose_fg(self):
color = colorchooser.askcolor()[1]
if color: self.fg_color = color
def choose_bg(self):
color = colorchooser.askcolor()[1]
if color: self.bg_color = color
def generate_qr(self):
data = self.data_entry.get()
if not data:
messagebox.showerror("Error", "Please enter some data")
return
if self.pass_var.get():
password = self.pass_entry.get()
if not password:
messagebox.showerror("Error", "Password required")
return
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
cipher = Fernet(key)
encrypted = cipher.encrypt(data.encode())
data_to_encode = base64.urlsafe_b64encode(salt).decode() + "|" + encrypted.decode()
else:
data_to_encode = data
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
qr.add_data(data_to_encode)
qr.make(fit=True)
img = qr.make_image(fill_color=self.fg_color, back_color=self.bg_color).convert("RGB")
if self.logo_path:
try:
logo = Image.open(self.logo_path)
qr_width, qr_height = img.size
logo_size = int(qr_width * 0.2)
logo.thumbnail((logo_size, logo_size), Image.LANCZOS)
box = Image.new('RGB', (logo_size + 20, logo_size + 20), 'white')
box.paste(logo, (10, 10))
pos = ((qr_width - box.size[0]) // 2, (qr_height - box.size[1]) // 2)
img.paste(box, pos)
except Exception as e:
messagebox.showerror("Error", f"Could not embed logo: {e}")
self.logo_path = None
self.qr_img = img
tk_img = ImageTk.PhotoImage(img)
self.qr_label.config(image=tk_img)
self.qr_label.image = tk_img
def save_qr(self, fmt):
if not self.qr_img:
messagebox.showerror("Error", "No QR generated")
return
path = filedialog.asksaveasfilename(defaultextension=f".{fmt}")
if path:
if fmt in ["png", "jpg"]:
self.qr_img.save(path, fmt.upper())
else:
pdf = FPDF()
pdf.add_page()
temp = path.replace(".pdf", ".png")
self.qr_img.save(temp, "PNG")
pdf.image(temp, x=50, y=50, w=100)
pdf.output(path)
messagebox.showinfo("Saved", f"QR saved as {path}")
def scan_upload(self):
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png *.jpg")])
if file_path:
img = cv2.imread(file_path)
detector = cv2.QRCodeDetector()
data, _, _ = detector.detectAndDecode(img)
if data:
if "|" in data:
salt_b64, encrypted_b64 = data.rsplit("|", 1)
password = simpledialog.askstring("Password", "Enter password:", show="*")
if not password:
return
try:
salt = base64.urlsafe_b64decode(salt_b64.encode())
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
cipher = Fernet(key)
decrypted_text = cipher.decrypt(encrypted_b64.encode()).decode()
self.scan_result.delete("1.0", tk.END)
self.scan_result.insert(tk.END, decrypted_text)
except Exception as e:
messagebox.showerror("Error", f"Invalid password or decryption failed: {e}")
else:
self.scan_result.delete("1.0", tk.END)
self.scan_result.insert(tk.END, data)
else:
messagebox.showerror("Error", "No QR found")
def upload_file(self):
file_path = filedialog.askopenfilename(
filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
self.data_entry.delete(0, tk.END)
self.data_entry.insert(0, content.strip())
except Exception as e:
messagebox.showerror("Error", f"Failed to read file: {e}")
def upload_logo(self):
file_path = filedialog.askopenfilename(
filetypes=[("Image files", "*.png *.jpg *.jpeg")]
)
if file_path:
self.logo_path = file_path
messagebox.showinfo("Success", "Logo image uploaded successfully!")
else:
self.logo_path = None
if __name__ == "__main__":
root = tb.Window(themename="cosmo")
app = QRApp(root)
root.mainloop()