MVPShoppingCart / app.py
walepavan's picture
Update app.py
40be27c verified
Raw
History Blame Contribute Delete
3.17 kB
import gradio as gr
from tabulate import tabulate
# Given Data (from original notebook cell)
inventory_data = [
(1, "Apples", 250),
(2, "Cherry", 650),
(3, "Chickoo", 50),
(4, "Grapes", 90),
(5, "Mangoes", 150),
]
# Initialize the cart (from original notebook cell)
my_cart = []
# Function to add items pulling details from inventory (from original notebook cell)
def add_to_cart(product_id):
for item in inventory_data:
if item[0] == product_id:
product = {"id": item[0], "name": item[1], "price": item[2]}
my_cart.append(product)
print(f"Added {item[1]} to the cart.")
return
print(f"Product ID {product_id} not found.")
# Function to remove an item from the cart (from original notebook cell)
def remove_from_cart(product_name):
for item in my_cart:
if item['name'].lower() == product_name.lower():
my_cart.remove(item)
print(f"Removed {product_name} from the cart.")
return
print(f"{product_name} not found in the cart.")
# Function to calculate total (from original notebook cell)
def calculate_total():
total = sum(item['price'] for item in my_cart)
print(f"--- Final Bill ---")
for item in my_cart:
print(f"{item['name']}: {item['price']}")
print(f"------------------")
print(f"Total amount to pay: {total}")
return total # Return total for UI
def update_ui():
inventory_table = tabulate(inventory_data, headers=["ID", "Product Name", "Price"], tablefmt="html")
cart_display = [(item['id'], item['name'], item['price']) for item in my_cart]
if not my_cart:
cart_table = "Your cart is empty."
total_text = "Total: 0"
else:
cart_table = tabulate(cart_display, headers=["ID", "Product Name", "Price"], tablefmt="html")
total = sum(item['price'] for item in my_cart)
total_text = f"Total amount to pay: {total}"
return inventory_table, cart_table, total_text
def add_item_ui(prod_id):
try:
add_to_cart(int(prod_id))
except ValueError:
pass # Handle invalid input gracefully in UI
return update_ui()
def remove_item_ui(prod_name):
remove_from_cart(prod_name)
return update_ui()
with gr.Blocks() as demo:
gr.Markdown("# 🍎 Fruit Shopping System")
with gr.Row():
with gr.Column():
gr.Markdown("### Inventory")
inventory_html = gr.HTML()
with gr.Column():
gr.Markdown("### Your Cart")
cart_html = gr.HTML()
total_output = gr.Markdown()
with gr.Row():
prod_id_input = gr.Number(label="Product ID to Add")
add_btn = gr.Button("Add to Cart")
with gr.Row():
prod_name_input = gr.Textbox(label="Product Name to Remove")
remove_btn = gr.Button("Remove from Cart")
add_btn.click(add_item_ui, inputs=[prod_id_input], outputs=[inventory_html, cart_html, total_output])
remove_btn.click(remove_item_ui, inputs=[prod_name_input], outputs=[inventory_html, cart_html, total_output])
demo.load(update_ui, outputs=[inventory_html, cart_html, total_output])
demo.launch()