Spaces:
Running
on
Zero
Running
on
Zero
import gradio as gr | |
import duckdb | |
# Initialize DuckDB connection | |
conn = duckdb.connect(database=':memory:') | |
# Create a table for products | |
conn.execute('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)') | |
# Load sample data from a CSV file | |
conn.execute('INSERT INTO products (name, price) VALUES ("Product 1", 10.99), ("Product 2", 9.99), ("Product 3", 12.99)') | |
# Define a function to read all products | |
def read_products(): | |
cursor = conn.execute('SELECT * FROM products') | |
return cursor.fetchall() | |
# Define a function to create a new product | |
def create_product(name, price): | |
conn.execute('INSERT INTO products (name, price) VALUES (?, ?)', (name, price)) | |
conn.commit() | |
# Define a function to update a product | |
def update_product(id, name, price): | |
conn.execute('UPDATE products SET name = ?, price = ? WHERE id = ?', (name, price, id)) | |
conn.commit() | |
# Define a function to delete a product | |
def delete_product(id): | |
conn.execute('DELETE FROM products WHERE id = ?', (id,)) | |
conn.commit() | |
# Create a Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("CRUD Interface for Products") | |
# Create a text input for product name | |
name_input = gr.Textbox(label="Product Name") | |
# Create a number input for product price | |
price_input = gr.Number(label="Product Price") | |
# Create a button to create a new product | |
create_button = gr.Button("Create Product") | |
# Create a button to update a product | |
update_button = gr.Button("Update Product") | |
# Create a button to delete a product | |
delete_button = gr.Button("Delete Product") | |
# Create a data frame to display products | |
products_df = gr.DataFrame(label="Products") | |
# Define the create product function | |
def create_product_callback(name, price): | |
create_product(name, price) | |
return read_products() | |
# Define the update product function | |
def update_product_callback(id, name, price): | |
update_product(id, name, price) | |
return read_products() | |
# Define the delete product function | |
def delete_product_callback(id): | |
delete_product(id) | |
return read_products() | |
# Create a Gradio interface | |
create_button.click(fn=create_product_callback, inputs=[name_input, price_input], outputs=products_df) | |
update_button.click(fn=update_product_callback, inputs=[gr.Textbox(label="Product ID"), name_input, price_input], outputs=products_df) | |
delete_button.click(fn=delete_product_callback, inputs=[gr.Textbox(label="Product ID")], outputs=products_df) | |
# Display the products data frame | |
products_df.render() | |
# Launch the Gradio interface | |
demo.launch() |