CultriX's picture
Update app.py
9e1cd24 verified
raw
history blame
3.24 kB
import qrcode
import cv2
from PIL import Image
import gradio as gr
import tempfile
import numpy as np
# Function to generate a QR code
def generate_qr(data):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill="black", back_color="white")
# Save to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
img.save(temp_file.name, format="PNG")
temp_file.close() # Ensure file is written to disk
return temp_file.name, img # Return the file path and the image
# Function to read a QR code
def read_qr(img):
# Convert PIL image to a NumPy array
img = np.array(img)
# Convert RGB to BGR as OpenCV expects
if img.ndim == 3:
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
# Initialize OpenCV QR code detector
detector = cv2.QRCodeDetector()
data, _, _ = detector.detectAndDecode(img)
return data if data else "No QR code found."
# Function for generating QR codes with both image and download link
def generate_qr_interface(data):
qr_file, qr_image = generate_qr(data)
return qr_image, qr_file # Return the image and file for download
# Function for reading QR codes with decoded text and clipboard update
def read_qr_interface(img):
decoded_data = read_qr(img)
return decoded_data # Return the decoded text
# Clipboard copy callback
def copy_to_clipboard(decoded_text):
# Gradio does not support direct clipboard copy; simulate success message
return f"Copied: {decoded_text}" if decoded_text else "Nothing to copy!"
# Create Gradio Interface
def create_gradio_interface():
# QR Code Generator Tab
generate_interface = gr.Interface(
fn=generate_qr_interface,
inputs=gr.Textbox(placeholder="Enter text or URL here...", label="Data to Encode"),
outputs=[
gr.Image(label="Generated QR Code"), # Display the image
gr.File(label="Download QR Code"), # Provide a download link
],
title="Generate QR Code",
description="Quickly create a QR code from any text or URL.",
)
# QR Code Reader Tab
with gr.Blocks() as read_interface:
gr.Markdown("### Read QR Code")
with gr.Row():
qr_input = gr.Image(type="pil", label="Upload QR Code Image")
qr_text = gr.Textbox(label="Decoded Data", interactive=False)
copy_button = gr.Button("Copy to Clipboard")
copy_feedback = gr.Textbox(label="Clipboard Status", interactive=False)
# Define interactions
qr_input.change(read_qr_interface, inputs=qr_input, outputs=qr_text)
copy_button.click(copy_to_clipboard, inputs=qr_text, outputs=copy_feedback)
# Main interface with tabs
with gr.Blocks() as demo:
gr.Markdown("# QR Code Tool: Generate and Decode with Ease")
with gr.Tab("Generate QR Code"):
generate_interface.render()
with gr.Tab("Read QR Code"):
read_interface.render()
# Launch the interface
demo.launch(share=True)
# Run the Gradio app
create_gradio_interface()