File size: 4,943 Bytes
5dba7e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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()