|
import gradio as gr |
|
import qrcode |
|
import qrcode.constants |
|
from PIL import Image |
|
|
|
def get_qr_image(data: str, fill_color: str = None, back_color: str = None): |
|
""" |
|
Generate a QR code image from the given data and optional color parameters. |
|
|
|
Args: |
|
data (str): The data to encode in the QR code |
|
fill_color (str, optional): Color of the QR code modules (default: black) |
|
back_color (str, optional): Background color of the QR code (default: white) |
|
|
|
Returns: |
|
PIL.Image: Generated QR code image |
|
""" |
|
qr = qrcode.QRCode( |
|
version=1, |
|
error_correction=qrcode.constants.ERROR_CORRECT_H, |
|
box_size=10, |
|
border=4, |
|
) |
|
|
|
qr.add_data(data) |
|
qr.make(fit=True) |
|
|
|
|
|
img = qr.make_image(fill_color=fill_color, back_color=back_color) |
|
img = img.convert('RGB') |
|
|
|
return img |
|
|
|
def generate_qr(url, fill_color=None, back_color=None): |
|
""" |
|
Wrapper function for Gradio interface to generate QR code. |
|
Handles potential errors and provides default behavior. |
|
|
|
Args: |
|
url (str): URL or data to encode |
|
fill_color (str, optional): Color of QR code modules |
|
back_color (str, optional): Background color of QR code |
|
|
|
Returns: |
|
PIL.Image: Generated QR code image |
|
""" |
|
try: |
|
|
|
if not url: |
|
raise ValueError("URL or data cannot be empty") |
|
|
|
|
|
fill_color = fill_color.strip() if fill_color else 'black' |
|
back_color = back_color.strip() if back_color else 'white' |
|
|
|
|
|
return get_qr_image(url, fill_color, back_color) |
|
|
|
except Exception as e: |
|
|
|
gr.Warning(f"Error generating QR code: {str(e)}") |
|
return None |
|
|
|
|
|
iface = gr.Interface( |
|
fn=generate_qr, |
|
inputs=[ |
|
gr.Textbox(label="URL or Data"), |
|
gr.Textbox(label="Fill Color (optional)", placeholder="e.g., 'blue', '#FF0000'"), |
|
gr.Textbox(label="Background Color (optional)", placeholder="e.g., 'white', '#FFFFFF'") |
|
], |
|
outputs=gr.Image(label="QR Code"), |
|
title="QR Code Generator", |
|
description="Generate a QR code from a URL or text with optional color customization." |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch() |