Spaces:
Running
Running
import qrcode | |
from PIL import Image | |
import gradio as gr | |
import io | |
import base64 | |
# Function to generate a QR code and return base64 string | |
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") | |
return f"data:image/png;base64,{img_base64}" # Return the base64 string | |
# Gradio Interface | |
def create_gradio_interface(): | |
with gr.Blocks() as demo: | |
gr.Markdown("## QR Code Generator and Viewer") | |
# Input to generate QR code | |
with gr.Tab("Generate QR Code"): | |
with gr.Row(): | |
data_input = gr.Textbox(placeholder="Enter text or URL to encode", label="Input Data") | |
generate_button = gr.Button("Generate QR Code") | |
qr_code_html = gr.HTML(label="Generated QR Code (Base64 Embedded)") | |
def generate_qr_interface(data): | |
if not data.strip(): | |
raise ValueError("Input text cannot be empty!") | |
img_base64 = generate_qr(data) | |
# Wrap the base64 string in an <img> tag for display | |
html_content = f'<img src="{img_base64}" alt="QR Code" style="max-width:300px;">' | |
return html_content | |
generate_button.click( | |
generate_qr_interface, | |
inputs=data_input, | |
outputs=qr_code_html, | |
) | |
demo.launch(share=True) | |
# Run the Gradio interface | |
create_gradio_interface() | |