import gradio as gr import requests import qrcode import io from PIL import Image, ImageDraw 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 transparency def generate_qr_image(url): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(url) qr.make(fit=True) qr_img = qr.make_image(fill_color="black", back_color="white") qr_img_rgba = qr_img.convert("RGBA") # Add transparency to the QR code qr_data = qr_img_rgba.getdata() new_qr_data = [] for item in qr_data: if item[0] == 0 and item[1] == 0 and item[2] == 0: new_qr_data.append((0, 0, 0, 0)) else: new_qr_data.append(item) qr_img_rgba.putdata(new_qr_data) return qr_img_rgba # Function to query the image from the Hugging Face API def query_image(text): API_URL = "https://api-inference.huggingface.co/models/stablediffusionapi/realistic-vision-v51" 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 with transparency qr_image = generate_qr_image(url) # Resize the QR code to fit into the generated image qr_width, qr_height = qr_image.size api_image_width, api_image_height = api_image.size qr_image = qr_image.resize((int(qr_width * 0.5), int(qr_height * 0.5))) # Blend the two images together final_image = api_image.copy() final_image.paste(qr_image, (api_image_width - qr_image.width, api_image_height - qr_image.height), qr_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()