import qrcode from PIL import Image import gradio as gr import io import base64 import numpy as np import cv2 import tempfile # Function to generate a QR code and return Base64 and PNG file 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") # Encode the image as a base64 string buffered = io.BytesIO() img.save(buffered, format="PNG") img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8") # Save the image temporarily as a PNG file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png") img.save(temp_file.name, format="PNG") temp_file.close() return f"data:image/png;base64,{img_base64}", temp_file.name, img_base64 # Function to decode a QR code from an uploaded image def decode_qr(img): if img is None: return "No image uploaded." # Convert PIL image to a NumPy array img_array = np.array(img) # Convert RGB to BGR as OpenCV expects if img_array.ndim == 3: img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) # Initialize OpenCV QR code detector detector = cv2.QRCodeDetector() data, _, _ = detector.detectAndDecode(img_array) return data if data else "No QR code found." # Gradio Interface def create_gradio_interface(): with gr.Blocks() as demo: gr.Markdown("## QR Code Generator and Decoder") # Add the logo at the bottom center demo.append(gr.HTML("""