MVPTesting / app.py
walepavan's picture
Create app.py
5dba7e8 verified
Raw
History Blame Contribute Delete
4.94 kB
import gradio as gr
# -----------------------------
# Core data and logic
# -----------------------------
# Same inventory as in the notebook
Inventory = [
[1, "Apples", 250],
[2, "Cherry", 650],
[3, "Chickoo", 50],
[4, "Grapes", 90],
[5, "Mangoes", 150],
]
# Global cart (Space will run single-process)
YourCart = [] # each item is [product_id, name, price_per_kg]
def add_item_to_cart(item_id: int):
"""Add one unit of the given product ID to the cart."""
try:
item = Inventory[item_id - 1]
except IndexError:
return "Invalid item ID. Please enter a valid Product ID."
YourCart.append(item)
return f"The item {item[1]} has been added to the cart, and your shopping cart has been updated."
def remove_item_from_cart(cart_index: int):
"""Remove item by 1-based index from the cart."""
if not YourCart:
return "Invalid cart index or cart is empty."
try:
removed_item = YourCart.pop(cart_index - 1)
return f"The item {removed_item[1]} has been removed from the cart, and your shopping cart has been updated."
except IndexError:
return "Invalid cart index or cart is empty."
def display_cart(cart):
"""Return a formatted string of the cart contents."""
if not cart:
return "Your cart is empty!!!\nWhy not buy Fruits from us ..."
lines = []
lines.append("Your Cart\n")
lines.append("Index Name Quantity Price (Total)\n")
lines.append("--------------------------------------------------")
unique_items = list({tuple(i) for i in cart})
total_cost = 0
for idx, item in enumerate(unique_items, start=1):
quantity = cart.count(list(item))
name = item[1]
price_per_kg = item[2]
price_total = price_per_kg * quantity
total_cost += price_total
lines.append(
f"{idx:<7} {name:<14} {quantity:<9} {price_total:>10.2f}"
)
lines.append("--------------------------------------------------")
lines.append(f"Total Cost: {total_cost:.2f}")
return "\n".join(lines)
def total_cost(cart):
"""Compute total cost as plain string."""
if not cart:
return "Total cost: 0.00"
s = sum(item[2] for item in cart)
return f"Total cost: {s:.2f}"
# -----------------------------
# Gradio interface wrapper
# -----------------------------
def gradio_interface(item_id, cart_index):
"""
Wrapper matching your notebook logic:
- If item_id is provided, add that product.
- If cart_index is provided, remove that entry.
- Always return: cart_display, add_message, remove_message, total_cost_message.
"""
add_msg = ""
remove_msg = ""
# Normalize None to 0 (Gradio Number can return None)
if item_id is not None and item_id > 0:
add_msg = add_item_to_cart(int(item_id))
if cart_index is not None and cart_index > 0:
remove_msg = remove_item_from_cart(int(cart_index))
cart_display = display_cart(YourCart)
cost_msg = total_cost(YourCart)
return cart_display, add_msg, remove_msg, cost_msg
# -----------------------------
# Build Gradio Blocks UI
# -----------------------------
with gr.Blocks() as demo:
gr.Markdown("# Fruit Shopping Cart System")
with gr.Row():
itemid_input = gr.Number(
label="Enter Product ID to Add to Cart",
interactive=True
)
cartindex_input = gr.Number(
label="Enter Index ID to Remove from Cart",
interactive=True
)
with gr.Row():
add_button = gr.Button("Add to Cart")
remove_button = gr.Button("Remove from Cart")
cart_display_output = gr.Textbox(
label="Your Cart",
interactive=False,
lines=12
)
add_message_output = gr.Textbox(
label="Add Item Message",
interactive=False,
lines=3
)
remove_message_output = gr.Textbox(
label="Remove Item Message",
interactive=False,
lines=3
)
total_cost_output = gr.Textbox(
label="Total Cost",
interactive=False,
lines=2
)
# Add item: pass itemid_input and a dummy 0 for cart_index
add_button.click(
fn=gradio_interface,
inputs=[itemid_input, gr.Number(visible=False, value=0)],
outputs=[
cart_display_output,
add_message_output,
remove_message_output,
total_cost_output,
],
)
# Remove item: pass a dummy 0 for item_id and cartindex_input
remove_button.click(
fn=gradio_interface,
inputs=[gr.Number(visible=False, value=0), cartindex_input],
outputs=[
cart_display_output,
add_message_output,
remove_message_output,
total_cost_output,
],
)
# This is the entrypoint Hugging Face Spaces expects
if __name__ == "__main__":
demo.launch()