make_QR / app.py
Simonlob's picture
Update app.py
4abfaf2 verified
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)
# Explicitly create a PIL Image and convert to RGB mode
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:
# Validate URL/data is not empty
if not url:
raise ValueError("URL or data cannot be empty")
# Convert empty strings to None
fill_color = fill_color.strip() if fill_color else 'black'
back_color = back_color.strip() if back_color else 'white'
# Generate QR code with optional color parameters
return get_qr_image(url, fill_color, back_color)
except Exception as e:
# Error handling for Gradio
gr.Warning(f"Error generating QR code: {str(e)}")
return None
# Create Gradio interface
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."
)
# Launch the app
if __name__ == "__main__":
iface.launch()