File size: 3,966 Bytes
2c7ce16
b271788
 
 
 
 
 
 
 
 
 
2c7ce16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import gradio as gr

# --- Data Structures ---
Inventory = [
    ("Apples", 250),
    ("Cherry", 650),
    ("Chickoo", 50),
    ("Oranges", 80),
    ("Mangoes", 150),
]

# Create a price lookup dictionary for convenience.
price_dict = {name: price for name, price in Inventory}

def format_cart(cart):
    """Return a formatted string of the cart contents and total bill."""
    if not cart:
        return "Your cart is empty."
    summary = ""
    total = 0
    for i, (product, quantity) in enumerate(cart):
        price = price_dict[product]
        subtotal = price * quantity
        summary += f"{i+1}. **{product}** x {quantity} @ {price} each = {subtotal}\n"
        total += subtotal
    summary += f"\n**Total Bill:** {total}"
    return summary

def generate_remove_options(cart):
    """Generate options for the removal dropdown from the cart list."""
    options = []
    for i, (product, quantity) in enumerate(cart):
        price = price_dict[product]
        subtotal = price * quantity
        options.append(f"{i}: {product} x {quantity} (Subtotal: {subtotal})")
    return options

def add_to_cart(product, quantity, cart):
    """
    Add the selected product and quantity to the cart.
    Returns the updated cart state, a message, the cart summary,
    and updated removal dropdown options.
    """
    # Ensure the cart exists.
    if cart is None:
        cart = []
    cart.append((product, int(quantity)))
    message = f"Added {int(quantity)} **{product}**(s) to your cart!"
    summary = format_cart(cart)
    remove_options = generate_remove_options(cart)
    # Use gr.Dropdown.update to update the choices for removal.
    return cart, message, summary, gr.Dropdown.update(choices=remove_options)

def remove_from_cart(selected_option, cart):
    """
    Remove the selected item from the cart.
    Returns the updated cart state, a message, the cart summary,
    and updated removal dropdown options.
    """
    if not cart:
        message = "Cart is empty."
        return cart, message, format_cart(cart), gr.Dropdown.update(choices=[])
    # Extract the index from the selected option.
    index = int(selected_option.split(":")[0])
    removed_item = cart.pop(index)
    message = f"Removed {removed_item[1]} **{removed_item[0]}**(s) from your cart."
    summary = format_cart(cart)
    remove_options = generate_remove_options(cart)
    return cart, message, summary, gr.Dropdown.update(choices=remove_options)

# --- Build the Gradio Interface ---
with gr.Blocks() as demo:
    # Initialize an empty cart in state.
    cart_state = gr.State([])

    gr.Markdown("# Gradio Shopping Cart")

    with gr.Row():
        product_input = gr.Dropdown(
            label="Select Product",
            choices=[name for name, _ in Inventory],
            value=Inventory[0][0]
        )
        quantity_input = gr.Number(
            label="Quantity",
            value=1,
            precision=0
        )
        add_button = gr.Button("Add to Cart")

    add_message = gr.Markdown("")  # To display add-to-cart messages.
    cart_display = gr.Textbox(
        label="Cart Summary",
        interactive=False,
        lines=10,
        value="Your cart is empty."
    )

    gr.Markdown("## Remove Items from Cart")
    with gr.Row():
        remove_dropdown = gr.Dropdown(
            label="Select Item to Remove",
            choices=[]  # Updated dynamically after adding items.
        )
        remove_button = gr.Button("Remove Selected Item")
    remove_message = gr.Markdown("")  # To display removal messages.

    # Set up interactions:
    add_button.click(
        fn=add_to_cart,
        inputs=[product_input, quantity_input, cart_state],
        outputs=[cart_state, add_message, cart_display, remove_dropdown]
    )
    remove_button.click(
        fn=remove_from_cart,
        inputs=[remove_dropdown, cart_state],
        outputs=[cart_state, remove_message, cart_display, remove_dropdown]
    )

demo.launch()