-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqrcode_generator.py
More file actions
160 lines (116 loc) · 4.74 KB
/
Copy pathqrcode_generator.py
File metadata and controls
160 lines (116 loc) · 4.74 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
try:
import qrcode
except ImportError:
print("This script requires the 'qrcode' module.\nPlease install it using 'pip install qrcode' and try again.")
exit(1)
import os
import re
## ===========================================================================
### Functions
# Function to input QR text
def get_text():
print("\nEnter the text to encode as QR (Press Enter \'Thrice\' to finish):\n")
text_lines = []
enter_pressed = 0
while True:
line = input()
if not line:
enter_pressed += 1
if enter_pressed > 2:
break
text_lines.append("")
continue
else:
enter_pressed = 0
text_lines.append(line.rstrip())
input_text = '\n'.join(text_lines).strip()
if input_text.strip() == "":
print("No Input!!!\nCan't generate QR without input text\n")
exit(1)
return input_text
## --------------------------------------------------------------------------
# Function to generate QR
def qr_gen(input_text, error_correction):
qr = qrcode.QRCode(
version=1,
error_correction=getattr(qrcode.constants, f"ERROR_CORRECT_{error_correction}"),
box_size=10,
border=4,
)
qr.add_data(input_text)
qr.make(fit=True)
qr_image = qr.make_image(fill_color="black", back_color="white")
return qr_image
## --------------------------------------------------------------------------
# Function to get QR Image extension type
def extension_menu():
extension_type = input("\nEnter the image file extension for your QRCode\n 1. JPEG 2. JPG 3. PNG\n 4. GIF 5. TIFF 6. BMP\n\n --> ").lower()
image_format = "JPEG"
if extension_type in ['1','jpeg','']:
extension = '.jpeg'
elif extension_type in ['2','jpg']:
extension = '.jpg'
elif extension_type in ['3','png']:
extension = '.png'
image_format = "PNG"
elif extension_type in ['4','gif']:
extension = '.gif'
image_format = "GIF"
elif extension_type in ['5','tiff']:
extension = '.tiff'
image_format = "TIFF"
elif extension_type in ['6','bmp']:
extension = '.bmp'
image_format = "BMP"
else:
print("\nInvalid extension!!! Please select from the above options\n")
exit(1)
return extension, image_format
## --------------------------------------------------------------------------
# Function manage all QR creation tasks
def generate_qrcode():
# Get input text from the user
input_text = get_text()
# QR codes have four error correction levels, or error correction rates, that determine how much data can be restored if the code is damaged or dirty:
# Level L (Low): 7% error correction rate, up to 7% damage
# Level M (Medium): 15% error correction rate, up to 15% damage
# Level Q (Quartile): 25% error correction rate, up to 25% damage
# Level H (High): 30% error correction rate, up to 30% damage
# Get the QR Error Correction Level
error_correction = input("\nSelect Error Correction level (Low-L, Medium-M, Quartile-Q, High-H): ").upper()
if error_correction not in ['L','M','Q','H']:
print("\nInvalid Input! Please select from L, M, Q, H\nQR code creation failed.\n")
exit(1)
try:
# Generate QR Image
qr_image = qr_gen(input_text, error_correction)
filename = input("\nEnter the filename for the QR code image: ")
if re.search(FORBIDDEN_CHARS, filename):
print("\nInvalid filename! QR code creation failed.\nFilename can't contain \\/:*?\"<>| symbols\n")
return
# Get the extension type
extension, image_format = extension_menu()
qr_image_path = os.path.join(QRCODES_DIRECTORY_PATH, f"{filename}{extension}")
# Handle if QR Code Image has existing filename
counter = 1
while os.path.exists(qr_image_path):
qr_image_path = f"{QRCODES_DIRECTORY_PATH}{filename}_{counter}{extension}"
counter += 1
# Save the QR Code
qr_image.save(qr_image_path, format=image_format)
return qr_image_path
except Exception as e:
print(f"\nOops! There was an error in creating QR.\n{e}\n")
exit(1)
### ===========================================================================
## Main
#
if __name__ == "__main__":
QRCODES_DIRECTORY = 'QRCodes'
FORBIDDEN_CHARS = r'[\/:*?"<>|]'
QRCODES_DIRECTORY_PATH = os.path.join(os.getcwd(), QRCODES_DIRECTORY)
os.makedirs(QRCODES_DIRECTORY_PATH, exist_ok=True)
print()
print(" QR Code Generator ".center(29, "-"))
qr_image_path = generate_qrcode()
print(f"\nQR code \"{qr_image_path[len(QRCODES_DIRECTORY_PATH):]}\" created successfully!\n")