import sqlite3 from sqlite3.dbapi2 import Connection import gradio as gr from PIL import Image, ImageDraw, ImageFont # Function to fill the template, save to SQLite, and convert to image def write_text_to_image( name: str, distance: float, conn: Connection, static_dir: str = "static", name_x: int = 410, name_y: int = 410, distance_x: int = 435, distance_y: int = 450, ): # Save the input data to the SQLite database cursor = conn.cursor() cursor.execute( "INSERT INTO user_inputs (name, distance) VALUES (?, ?)", (name, distance), ) conn.commit() # Open the background image background_image_path = f"{static_dir}/phocao_run_2024.jpg" image = Image.open(background_image_path) draw = ImageDraw.Draw(image) # Set the font (adjust the font size and style) font = ImageFont.truetype("font/RobotoSlab-Medium.ttf", 25) # Define text colors text_color = (0, 255, 0) # Green # Write the name on the image at the specified coordinates draw.text((name_x, name_y), name, font=font, fill=text_color) # Write the distance on the image at the specified coordinates draw.text((distance_x, distance_y), f"{distance} km", font=font, fill=text_color) return image # Serve the app if __name__ == "__main__": # Connect to SQLite database conn = sqlite3.connect("user_input.db", check_same_thread=False) cursor = conn.cursor() # Create a table if it doesn't already exist cursor.execute( """ CREATE TABLE IF NOT EXISTS user_inputs ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, distance FLOAT ) """ ) conn.commit() # Gradio Blocks interface with gr.Blocks(title="PhoCao Run 2024 - Chứng Nhận Hoàn Thành", css="footer {visibility: hidden}") as demo: gr.Markdown("## PhoCao Run 2024 - Chứng Nhận Hoàn Thành") name_input = gr.Textbox(label="Tên/Nickname") distance_input = gr.Number(label="Số km") submit_button = gr.Button("Chạm Đích") output_image = gr.Image(label="Kết quả") # Event handler for the button click def on_submit(name, distance): image_path = write_text_to_image(name, distance, conn, static_dir="static") submit_button = gr.Button(visible=False) return submit_button, image_path submit_button.click( on_submit, inputs=[name_input, distance_input], outputs=[submit_button, output_image], scroll_to_output=True, api_name=None, max_batch_size=1, show_api=False, ) # Mount Gradio app to FastAPI app demo.show_api = False demo.launch()