Team Ai
Apppublic

Ai-developer10/E-Commerce-system

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
0likes
app.py172 linesDownload Raw Back to root
1import streamlit as st2import requests3from PIL import Image4 5# Function to fetch product data from the API6def fetch_products():7    url = "https://fakestoreapi.com/products"8    response = requests.get(url)9    if response.status_code == 200:10        return response.json()11    else:12        return []13 14# Function to display a product with its image15def display_product(product):16    # Display product image, title, price, and description with colors17    st.image(product['image'], caption=product['title'], use_container_width=True)18    st.markdown(f"<h3 style='color: #2e6c9b;'>{product['title']}</h3>", unsafe_allow_html=True)19    st.markdown(f"<p style='color: #f57c00;'>Price: ${product['price']}</p>", unsafe_allow_html=True)20    st.write(f"{product['description']}")21 22# Function to generate a receipt23def generate_receipt(cart, total_price, delivery_address):24    store_name = "The Affordeblers"25   26    # Receipt Layout: Clear background and boxed area with color27    st.markdown(28        f"""29        <div style="padding: 20px; background-color: #f4f4f4; border-radius: 10px; border: 1px solid #ddd;">30            <h3 style="color: #2e6c9b; text-align: center;">Receipt from {store_name}</h3>31            <hr style="border: 1px solid #ccc;">32            {"".join([f"<p>{item['product']['title']} (x{item['quantity']}) - ${item['product']['price'] * item['quantity']}</p>" for item in cart.values()])}33            <hr style="border: 1px solid #ccc;">34            <h4 style="color: #f57c00; text-align: center;">Total Amount: ${total_price}</h4>35            <p style="color: #3a4750;">Delivery Address: {delivery_address}</p>36            <p style="text-align: center;">Thank you for shopping with us!</p>37        </div>38        """, unsafe_allow_html=True)39 40# Main function for the Streamlit app41def main():42    # Adding the optimized animation CSS to the page43    st.markdown("""44        <style>45            /* Main heading animation */46            @keyframes fadeInHeading {47                0% { opacity: 0; transform: translateY(-20px); }48                100% { opacity: 1; transform: translateY(0); }49            }50 51            /* Description animation */52            @keyframes fadeInDescription {53                0% { opacity: 0; transform: translateX(-20px); }54                100% { opacity: 1; transform: translateX(0); }55            }56 57            /* Applying the animation to the main heading */58            h1 {59                animation: fadeInHeading 1s ease-out forwards;60            }61 62            /* Applying the animation to the description text */63            p.description {64                animation: fadeInDescription 1s ease-out 1s forwards;65            }66        </style>67    """, unsafe_allow_html=True)68 69    # Title of the app with animation70    st.markdown("<h1 style='color: #2e6c9b;'>The Affordeblers E-System </h1>", unsafe_allow_html=True)71    72    # Add the first description line (it will animate after the heading)73    st.markdown("<p class='description' style='color: #3a4750;'>Welcome to The Affordeblers E-System!</p>", unsafe_allow_html=True)74 75    # Add another description line after the first one (this will be animated)76    st.markdown("<p class='description' style='color: #3a4750;'>Browse through our extensive product range, find the best deals, and add your favorite items to the cart for a seamless shopping experience.</p>", unsafe_allow_html=True)77 78    # Fetch products from the API79    products = fetch_products()80 81    if not products:82        st.error("Failed to load products.")83        return84 85    # Initialize session state to store cart information86    if 'cart' not in st.session_state:87        st.session_state.cart = {}88   89    if 'total_price' not in st.session_state:90        st.session_state.total_price = 091 92    # Create two columns: 8 for products and 4 for receipt93    col1, col2 = st.columns([8, 4])  # 8 parts for products, 4 parts for cart/receipt94 95    # Left column for displaying products (taking 8 parts of the space)96    with col1:97        st.header("Products To Serve.")98        # Display products in a grid-like layout with cards99        for idx, product in enumerate(products):100            col1_1, col1_2, col1_3 = st.columns([7, 2, 3])  # 7 for image/text, 2 for quantity input and button, 3 for button size101 102            with col1_1:103                display_product(product)104 105            with col1_2:106                quantity = st.number_input(f"Qty for {product['title']}", min_value=0, max_value=10, key=product['id'])107           108            with col1_3:109                if quantity > 0:110                    if st.button(f"Add to Cart", key=f"add_{product['id']}", help="Click to add to your cart"):111                        if product['id'] in st.session_state.cart:112                            st.session_state.cart[product['id']]['quantity'] += quantity113                        else:114                            st.session_state.cart[product['id']] = {'product': product, 'quantity': quantity}115                        st.session_state.total_price += product['price'] * quantity116                        st.markdown(f"<span style='color: #388e3c;'>Added {quantity} {product['title']}(s) to cart.</span>", unsafe_allow_html=True)117 118    # Right column for displaying cart and receipt (taking 4 parts of the space)119    with col2:120        st.header("Your Cart:")121        if st.session_state.cart:122            # Cart Details (Styled)123            for item in st.session_state.cart.values():124                product = item['product']125                quantity = item['quantity']126                st.markdown(f"<p><strong>{product['title']} (x{quantity})</strong> - <span style='color: #f57c00;'>${product['price'] * quantity}</span></p>", unsafe_allow_html=True)127           128            st.markdown(f"<h3 style='color: #f57c00;'>Total Price: ${st.session_state.total_price}</h3>", unsafe_allow_html=True)129 130            # Place Order Button (First time click to request address)131            if 'delivery_address' not in st.session_state or not st.session_state.delivery_address:132                if st.button("Place Order", key="place_order", help="Place your order and provide delivery address"):133                    # Display the input form for delivery address134                    st.session_state.delivery_address = st.text_area("Enter your delivery address", height=100)135                    st.session_state.order_placed = False136                    st.markdown("<span style='color: #388e3c;'>Please enter your delivery address to proceed with the order.</span>", unsafe_allow_html=True)137            else:138                # After delivery address is entered, show the "Confirm Order" button139                if st.session_state.delivery_address:140                    if st.button("Confirm Order", key="confirm_order", help="Confirm your order and generate receipt"):141                        # Generate receipt142                        generate_receipt(st.session_state.cart, st.session_state.total_price, st.session_state.delivery_address)143                        # Clear the cart and reset the total price after order144                        st.session_state.cart.clear()145                        st.session_state.total_price = 0146        else:147            st.info("Your cart is empty.")148 149    # Contact Us Button in the upper-left corner150    st.sidebar.header("Contact Us")151    contact_option = st.sidebar.radio(152        "Choose a platform", 153        ["Select a Platform", "Contact on WhatsApp", "Contact on Instagram", "Contact on Facebook"]154    )155 156    # URLs for contact platforms (replace with actual URLs)157    whatsapp_url = "https://wa.me/+923173274351"  # Replace with your WhatsApp link158    instagram_url = "https://www.instagram.com/invites/contact/?igsh=1eti3vl7uovmc&utm_content=h2bnhxt"  # Replace with your Instagram link159    facebook_url = "https://www.facebook.com/share/12GAMfcBLqq/?mibextid=wwXIfr"  # Replace with your Facebook link160 161    # Handle redirection based on selection162    if contact_option == "Contact on WhatsApp":163        st.sidebar.markdown(f"<a href='{whatsapp_url}' target='_blank'>Click here to contact us on WhatsApp</a>", unsafe_allow_html=True)164    elif contact_option == "Contact on Instagram":165        st.sidebar.markdown(f"<a href='{instagram_url}' target='_blank'>Click here to contact us on Instagram</a>", unsafe_allow_html=True)166    elif contact_option == "Contact on Facebook":167        st.sidebar.markdown(f"<a href='{facebook_url}' target='_blank'>Click here to contact us on Facebook</a>", unsafe_allow_html=True)168 169# Run the app170if __name__ == "__main__":171    main()172