import qrcode from PIL import Image import base64 import gradio as gr # Function to encode text or file content in base64 and generate a QR code def generate_qr(data: str, error_correction: int = qrcode.constants.ERROR_CORRECT_L, box_size: int = 10, border: int = 4, fill_color: str = "black", back_color: str = "white", logo_path: str = None): encoded_data = base64.b64encode(data.encode('utf-8')).decode('utf-8') final_url = f"https://flowly-ai.vercel.app/tools/qr/qr-code/read/{encoded_data}" qr = qrcode.QRCode( version=1, error_correction=error_correction, box_size=box_size, border=border, ) qr.add_data(final_url) qr.make(fit=True) img_qr = qr.make_image(fill_color=fill_color, back_color=back_color) if logo_path: try: logo = Image.open(logo_path).convert("RGBA") qr_width, qr_height = img_qr.size logo = logo.resize((qr_width // 5, qr_height // 5)) logo_position = ((qr_width - logo.size[0]) // 2, (qr_height - logo.size[1]) // 2) img_qr.paste(logo, logo_position, logo) except Exception as e: print(f"Error loading logo: {e}") output_path = "qr_code.png" img_qr.save(output_path) return output_path # Function to handle text or file input def qr_code_interface(input_type, text, file, error_correction, box_size, border, fill_color, back_color, logo): logo_path = logo.name if logo else None if input_type == "Text" and text: return generate_qr(text, error_correction, box_size, border, fill_color, back_color, logo_path) elif input_type == "File" and file: with open(file.name, 'r') as f: file_data = f.read() return generate_qr(file_data, error_correction, box_size, border, fill_color, back_color, logo_path) else: return None # Gradio Interface interface = gr.Interface( fn=qr_code_interface, inputs=[ gr.Radio(["Text", "File"], label="Input Type", value="Text"), gr.Textbox(label="Enter Text", visible=True), gr.File(label="Upload Text File", type="file", visible=False), gr.Slider(0, 3, 1, label="Error Correction", value=0), gr.Slider(1, 20, 1, label="Box Size", value=10), gr.Slider(1, 10, 1, label="Border Size", value=4), gr.ColorPicker(label="QR Fill Color", value="#000000"), gr.ColorPicker(label="QR Background Color", value="#FFFFFF"), gr.File(label="Upload Logo (Optional)") ], outputs=gr.Image(type="filepath", label="Generated QR Code"), description="Generate a QR Code from either text or file with custom styles, colors, and an optional logo." ) # Launch the app interface.launch(share=True)