import qrcode
import io
import base64
from pyscript import document
from pyscript import window
# Turn on the button once Python is fully loaded
document.getElementById("loading").style.display = "none"
btn = document.getElementById("generateBtn")
btn.disabled = False
btn.classList.remove("opacity-50", "cursor-not-allowed")
def generate_qr(event):
url = document.getElementById("urlInput").value.strip()
error_panel = document.getElementById("errorPanel")
error_msg = document.getElementById("errorMessage")
output_section = document.getElementById("outputSection")
img_element = document.getElementById("qrImage")
download_btn = document.getElementById("downloadBtn")
# Reset visuals
error_panel.classList.add("hidden")
output_section.classList.add("hidden")
# Simple checks
if not url:
error_msg.innerText = "The URL field cannot be empty."
error_panel.classList.remove("hidden")
return
if not (url.startswith("http://") or url.startswith("https://")):
error_msg.innerText = "The URL must start with http:// or https://"
error_panel.classList.remove("hidden")
return
try:
# Create the QR code layout
qr = qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(url)
qr.make(fit=True)
# Draw the image
img = qr.make_image(fill_color="black", back_color="white")
# Convert the image to raw memory data so the website can read it
buf = io.BytesIO()
img.save(buf, format="PNG")
image_data = buf.getvalue()
# Translate raw memory into a web link format (base64)
encoded_string = base64.b64encode(image_data).decode('utf-8')
image_source = f"data:image/png;base64,{encoded_string}"
# Generate a safe, unique filename based on the URL
safe_name = "".join(c if c.isalnum() else "_" for c in url.split("://")[-1])
safe_filename = f"{safe_name[:50]}_qr.png"
# Push the image to the screen
img_element.src = image_source
download_btn.href = image_source
download_btn.download = safe_filename
output_section.classList.remove("hidden")
except Exception as e:
error_msg.innerText = "Something broke while drawing the QR code."
error_panel.classList.remove("hidden")
print(f"Error details: {e}")