PRO-QR-Codes / app.py
Adityadn's picture
Update app.py
bcb8d08 verified
raw
history blame
2.83 kB
import qrcode
from PIL import Image
import base64
import gradio as gr
# Function to process text and generate QR code
def txt2qrcode(text: str):
# Encode the text as URL-safe base64
encoded_text = base64.b64encode(text.encode('utf-8')).decode('utf-8') # URL encoding the input text
# Construct the final URL to embed into the QR code
final_url = f"https://flowly-ai.vercel.app/tools/qr/pro-qr-codes/read/{encoded_text}"
# Create the QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(final_url)
qr.make(fit=True)
# Create an image for the QR code
img_qr = qr.make_image(fill='black', back_color='white')
# Optionally, add a logo to the center of the QR code
logo = Image.open("logo.png") # Replace with your logo path
logo = logo.convert("RGBA")
qr_width, qr_height = img_qr.size
logo_width, logo_height = logo.size
# Resize logo to fit in the QR code
logo = logo.resize((qr_width // 5, qr_height // 5)) # Resize to be 20% of the QR code size
# Calculate position to place logo at the center
logo_position = ((qr_width - logo_width) // 2, (qr_height - logo_height) // 2)
# Paste the logo onto the QR code image
img_qr.paste(logo, logo_position, logo)
# Save the QR code image
output_path = "qr_code_with_logo.png"
img_qr.save(output_path)
return output_path
# Function to process a file (e.g., text file) and generate QR code
def file2qrcode(file: str):
# Read the content of the file
with open(file, 'r') as f:
text = f.read()
# Generate QR code with the file's text content
return txt2qrcode(text)
# Gradio Interface for the QR code generation
def qr_code_interface(text: str):
result = txt2qrcode(text)
return result
def qr_code_file_interface(file: str):
result = file2qrcode(file)
return result
# Create a Gradio interface
interface = gr.Interface(
fn=qr_code_interface,
inputs=gr.Textbox(label="Enter Text to Encode", placeholder="Enter your text here..."),
outputs=gr.Image(type="filepath", label="Generated QR Code"),
description="Generate a QR Code from your text. The input text will be URL encoded and embedded into a QR code pointing to a specific URL.",
css="footer {visibility: hidden}"
)
# Create a second Gradio interface for file input
file_interface = gr.Interface(
fn=qr_code_file_interface,
inputs=gr.File(label="Upload Text File"),
outputs=gr.Image(type="filepath", label="Generated QR Code from File"),
description="Upload a text file, and generate a QR code based on the file's content."
)
# Launch the Gradio apps
interface.launch(share=True)
file_interface.launch(share=True)