Kvikontent's picture
Update app.py
475db54 verified
raw
history blame
2.35 kB
import gradio as gr
import requests
import qrcode
import io
from PIL import Image
import os
# Get the Hugging Face API token from the environment variable
hf_token = os.environ.get("hf_token")
# Function to generate a QR code with transparent fill color
def generate_qr_image(url, image_size):
# Determine box size based on the larger dimension of the image
max_dim = max(image_size[0], image_size[1])
box_size = max_dim // 25
border = 1
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=box_size,
border=border,
)
qr.add_data(url)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color=None).convert("RGBA")
qr_img = qr_img.resize(image_size)
return qr_img
# Function to query the image from the Hugging Face API
def query_image(text):
API_URL = "https://api-inference.huggingface.co/models/goofyai/3d_render_style_xl"
headers = {"Authorization": f"Bearer {hf_token}"}
response = requests.post(API_URL, headers=headers, json={"inputs": text})
return response.content
# Gradio app function
def generate_image(url, text):
# Generate image from Hugging Face API
image_bytes = query_image(text)
api_image = Image.open(io.BytesIO(image_bytes))
# Generate QR code image
qr_image = generate_qr_image(url, api_image.size)
# Create a blank image with transparency
final_image = Image.new('RGBA', api_image.size, (255, 255, 255, 0))
# Position the QR code in the image
qr_position = ((final_image.width - qr_image.width) // 2, (final_image.height - qr_image.height) // 2)
final_image.paste(qr_image, qr_position, qr_image)
# Composite the API image and the final image with the QR code
final_image = Image.alpha_composite(api_image.convert("RGBA"), final_image)
return final_image
# Inputs and outputs for Gradio interface
inputs = [
gr.Textbox(lines=1, label="URL"),
gr.Textbox(lines=2, label="Prompt for Image"),
]
output = gr.Image(type="pil", label="Generated Image")
# Gradio app interface
gr.Interface(fn=generate_image, inputs=inputs, outputs=output, title="QR Code Image Generator", description="Generate an image with a QR code linked to the input URL and an image from the Hugging Face API", theme="soft").launch()