CultriX's picture
Update app.py
327c8c5 verified
raw
history blame
2.87 kB
import qrcode
import cv2
from PIL import Image
import gradio as gr
import tempfile
import numpy as np
import os
# 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 QR code image to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
img.save(temp_file.name, format="PNG")
temp_file.close() # Ensure the file is saved
return temp_file.name # Return the file path
# 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."
# Gradio Interface
def create_gradio_interface():
with gr.Blocks() as demo:
gr.Markdown("## QR Code Tool: Generate and Decode with Ease")
# Tab for generating QR codes
with gr.Tab("Generate QR Code"):
with gr.Row():
data_input = gr.Textbox(placeholder="Enter text or URL here...", label="Data to Encode")
generate_button = gr.Button("Generate QR Code")
with gr.Row():
qr_image = gr.Image(label="Generated QR Code")
qr_file = gr.File(label="Download QR Code")
def generate_qr_interface(data):
if not data.strip():
raise ValueError("Input text cannot be empty!")
qr_file_path = generate_qr(data)
qr_image_pil = Image.open(qr_file_path)
return qr_image_pil, qr_file_path
generate_button.click(
generate_qr_interface,
inputs=data_input,
outputs=[qr_image, qr_file],
)
# Tab for reading QR codes
with gr.Tab("Read QR Code"):
with gr.Row():
image_input = gr.Image(type="pil", label="Upload QR Code Image")
decode_button = gr.Button("Decode QR Code")
decoded_data = gr.Textbox(label="Decoded Data")
def read_qr_interface(img):
if img is None:
raise ValueError("Please upload a valid QR code image!")
return read_qr(img)
decode_button.click(
read_qr_interface,
inputs=image_input,
outputs=decoded_data,
)
demo.launch(share=True)
# Run the Gradio interface
create_gradio_interface()