Skip to content

Commit

Permalink
Update generate_qr.py
Browse files Browse the repository at this point in the history
Error Handling: I added checks to ensure the input file exists before processing. If the file is missing, the script raises a FileNotFoundError with a clear message.
Modularization: I split the code into functions to improve readability and maintainability.
Improved Feedback: I updated the script to provide clearer messages about the process and errors, making it easier to understand and debug.
  • Loading branch information
Amansingh0807 authored Jan 2, 2025
1 parent 66525dd commit 871316c
Showing 1 changed file with 49 additions and 15 deletions.
64 changes: 49 additions & 15 deletions generate_qr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,57 @@
import base64
import qrcode
import urllib.parse
import os

# Change this if you want to use decoding file hosted elsewhere
WEB_URL_PREFIX = "https://amanraox.github.io/share-bits-wirelessly/dl.html"

if len(sys.argv) > 1:
in_filename = sys.argv[1]
out_filename = in_filename if len(sys.argv) == 2 else sys.argv[2]
else:
print("Usage: python generate_qr.py inputfile [optional output filename]")
exit(-1)
def validate_file(input_filename):
"""Check if the input file exists and is a valid file."""
if not os.path.isfile(input_filename):
raise FileNotFoundError(f"The file {input_filename} does not exist.")

def encode_file(input_filename):
"""Encode the file to base64."""
with open(input_filename, "rb") as f:
file_data = f.read()
return base64.b64encode(file_data).decode('ascii')

with open(in_filename, "rb") as f:
file_data = f.read()

b64_file_data = base64.b64encode(file_data).decode('ascii')
url_file_data = urllib.parse.quote_plus(b64_file_data)
full_url = f"{WEB_URL_PREFIX}?f={out_filename}#{url_file_data}"
print("encoded url:", full_url)
qr_img = qrcode.make(full_url)
qr_img.save(f"{out_filename}_qr.png")
def generate_qr_code(url, output_filename):
"""Generate QR code and save it."""
qr_img = qrcode.make(url)
qr_img.save(f"{output_filename}_qr.png")
print(f"QR code saved as {output_filename}_qr.png")

def main():
if len(sys.argv) > 1:
input_filename = sys.argv[1]
output_filename = input_filename if len(sys.argv) == 2 else sys.argv[2]
else:
print("Usage: python generate_qr.py inputfile [optional output filename]")
exit(-1)

try:
# Validate input file existence
validate_file(input_filename)

# Encode file content to base64
b64_file_data = encode_file(input_filename)

# URL encode the base64 file data
url_file_data = urllib.parse.quote_plus(b64_file_data)

# Generate the full URL
full_url = f"{WEB_URL_PREFIX}?f={output_filename}#{url_file_data}"
print("Encoded URL:", full_url)

# Generate QR code and save it
generate_qr_code(full_url, output_filename)

except FileNotFoundError as e:
print(e)
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
main()

0 comments on commit 871316c

Please sign in to comment.