Spaces:
Sleeping
Sleeping
Download app.py from abdullah9873/e-comm-flask: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/spaces/abdullah9873/e-comm-flask/resolve/main/app.py
- Command line
-
hf download hf://spaces/abdullah9873/e-comm-flask/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abdullah9873/e-comm-flask/resolve/main/app.py
14.9 kB
| from flask import Flask, render_template, request, jsonify | |
| from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel, AsyncOpenAI, RunConfig | |
| from dotenv import load_dotenv | |
| from rich import print | |
| import os | |
| import json | |
| from typing import Dict, Any | |
| from twilio.rest import Client | |
| from datetime import datetime | |
| import random | |
| load_dotenv() | |
| # Load products | |
| with open("products.json", "r") as file: | |
| data = json.load(file) | |
| products = data["products"] | |
| # Gemini API | |
| client = AsyncOpenAI( | |
| api_key=os.getenv("GEMINI_API_KEY"), | |
| base_url="https://generativelanguage.googleapis.com/v1beta/openai/", | |
| ) | |
| model = OpenAIChatCompletionsModel( | |
| model="gemini-3.1-flash-lite-preview", | |
| openai_client=client | |
| ) | |
| config = RunConfig( | |
| model=model, | |
| tracing_disabled=True | |
| ) | |
| # ========================= TOOLS ========================= # | |
| def search_products(query: str): | |
| """Search for products by name, category, or show all products. Return a human-readable response.""" | |
| results = [] | |
| q = query.lower().strip() | |
| # β Show all products if user asks for "all products", "tamam cheezen", etc. | |
| show_all_keywords = [ | |
| "all products", "tamam products", "sab products", "tamam cheezen", "tamam saman", | |
| "sab cheezen", "all items", "sab kuch", "tamam items", "show all" | |
| ] | |
| if q in show_all_keywords: | |
| results = products # show all | |
| else: | |
| q = q.rstrip('s') # handle plurals like lamps β lamp | |
| for product in products: | |
| if q in product["name"].lower() or q in product["category"].lower(): | |
| results.append(product) | |
| if not results: | |
| return "Hamare paas aapki talash ke mutabiq koi product nahi mila." | |
| response = f"Humain aapki talash ke mutabiq {len(results)} product{'s' if len(results) > 1 else ''} milay hain:\n\n" | |
| for p in results: | |
| response += f"πΉ **{p['name']}** ({p['category'].title()})\n" | |
| response += f"π° Price: βΉ{p['price']}\n" | |
| response += f"β Rating: {p['rating']}/5\n" | |
| response += f"π Description: {p['description']}\n" | |
| if "dimensions" in p: | |
| response += f"π Dimensions: {p['dimensions']}\n" | |
| elif "care_level" in p: | |
| response += f"π± Care Level: {p['care_level']}\n" | |
| response += f"β¨ Features: {', '.join(p['features'])}\n\n" | |
| return response | |
| def filter_by_price(max_price: float, category: str = ""): | |
| """ | |
| Filter products by maximum price and optional category. | |
| Use empty string ('') for category to ignore it. | |
| """ | |
| results = [] | |
| for product in products: | |
| product_cat = product["category"].lower() | |
| user_cat = category.lower().rstrip('s') # handle "sofa" vs "sofas" | |
| if category and user_cat not in product_cat: | |
| continue | |
| if product["price"] <= max_price: | |
| results.append(product) | |
| if not results: | |
| return [{"message": "No products found under this price."}] | |
| return results | |
| def suggest_market_for_product(product_name: str): | |
| """ | |
| Provides complete market suggestions with REAL WORKING images and all details | |
| when products are unavailable. | |
| """ | |
| # Check product availability | |
| available = any(p["name"].lower() == product_name.lower() for p in products) | |
| if available: | |
| return { | |
| "product": product_name, | |
| "available": True, | |
| "message": f"β <b>{product_name}</b> hamari website par available hai!" | |
| } | |
| # Market database with GUARANTEED WORKING image URLs | |
| markets = [ | |
| { | |
| "name": "Decor World Karachi", | |
| "address": "Sea View Plaza, Block 9, Clifton", | |
| "maps": "https://maps.app.goo.gl/1tQb4J7XvJzXqY3W7", | |
| "image": "https://storage.googleapis.com/proudcity/mebanenc/uploads/2021/03/placeholder-image.png", # Placeholder image URL that always works | |
| "contact": "021-35876543", | |
| "hours": "10AM-10PM (Daily)", | |
| "specialty": "Mirrors, Wall Art, Home Decor" | |
| }, | |
| { | |
| "name": "Furniture Mall", | |
| "address": "Plot FL-1, Block 5, Main Clifton Road", | |
| "maps": "https://maps.app.goo.gl/7JkLz9XmY1wWqW9V8", | |
| "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/832px-No-Image-Placeholder.svg.png", # Wikimedia placeholder | |
| "contact": "021-35361234", | |
| "hours": "11AM-9PM (Closed Fridays)", | |
| "specialty": "Modern Furniture" | |
| } | |
| ] | |
| # Build RICH RESPONSE with images | |
| response = f""" | |
| <div style="margin-bottom:15px;font-size:15px;"> | |
| β <b>{product_name}</b> hamare pas available nahi, lekin aap ye markets check kar sakte hain: | |
| </div> | |
| """ | |
| for market in markets: | |
| response += f""" | |
| <div style=" | |
| border:1px solid #ddd; | |
| border-radius:10px; | |
| padding:15px; | |
| margin-bottom:15px; | |
| background:white; | |
| display:flex; | |
| gap:15px; | |
| "> | |
| <img src="{market['image']}" | |
| style="width:120px;height:120px;object-fit:cover;border-radius:8px;"> | |
| <div> | |
| <h3 style="margin:0 0 8px 0;">{market['name']}</h3> | |
| <p style="margin:5px 0;"><b>π</b> {market['address']}</p> | |
| <p style="margin:5px 0;"><b>π</b> {market['hours']}</p> | |
| <p style="margin:5px 0;"><b>π</b> {market['contact']}</p> | |
| <p style="margin:5px 0;"><b>Specialty:</b> {market['specialty']}</p> | |
| <a href="{market['maps']}" target="_blank" | |
| style="display:inline-block;padding:8px 15px; | |
| background:#4CAF50;color:white; | |
| text-decoration:none;border-radius:5px; | |
| margin-top:8px;"> | |
| πΊοΈ View on Map | |
| </a> | |
| </div> | |
| </div> | |
| """ | |
| response += """ | |
| <div style="margin-top:10px;padding:10px;background:#f8f9fa;border-radius:5px;"> | |
| π‘ <b>Tip:</b> Janay se pehlay phone kar ke confirm karein | |
| </div> | |
| """ | |
| return { | |
| "product": product_name, | |
| "available": False, | |
| "message": response, | |
| "ui_type": "rich_market_suggestion" | |
| } | |
| def page_links(query: str): | |
| """Return clickable page links with complete URLs for products and other pages.""" | |
| query = query.lower().strip() | |
| # Base URL - Using empty string for relative paths | |
| base_url = "" | |
| # Complete product list with all details | |
| products = [ | |
| { | |
| "id": 1, | |
| "name": "Classic 3-Seater Sofa", | |
| "category": "sofa", | |
| "price": 45000, | |
| "image": "/static/images/sofa1.webp" | |
| }, | |
| { | |
| "id": 2, | |
| "name": "Luxury Recliner Sofa", | |
| "category": "sofa", | |
| "price": 65000, | |
| "image": "/static/images/sofa2.webp" | |
| }, | |
| { | |
| "id": 3, | |
| "name": "Modern Loveseat Sofa", | |
| "category": "sofa", | |
| "price": 38000, | |
| "image": "/static/images/sofa3.webp" | |
| }, | |
| { | |
| "id": 4, | |
| "name": "Aurora Night Lamp", | |
| "category": "lamp", | |
| "price": 5500, | |
| "image": "/static/images/lamp1.webp" | |
| }, | |
| { | |
| "id": 5, | |
| "name": "Vintage Desk Lamp", | |
| "category": "lamp", | |
| "price": 4500, | |
| "image": "/static/images/lamp2.webp" | |
| }, | |
| { | |
| "id": 6, | |
| "name": "Crystal Touch Lamp", | |
| "category": "lamp", | |
| "price": 7500, | |
| "image": "/static/images/lamp3.webp" | |
| }, | |
| { | |
| "id": 7, | |
| "name": "Peace Lily", | |
| "category": "plant", | |
| "price": 2500, | |
| "image": "/static/images/plant1.webp" | |
| }, | |
| { | |
| "id": 8, | |
| "name": "Snake Plant", | |
| "category": "plant", | |
| "price": 2000, | |
| "image": "/static/images/plant2.webp" | |
| }, | |
| { | |
| "id": 9, | |
| "name": "Aloe Vera", | |
| "category": "plant", | |
| "price": 1500, | |
| "image": "/static/images/plant3.png" | |
| }, | |
| { | |
| "id": 10, | |
| "name": "Modern Glass Coffee Table", | |
| "category": "table", | |
| "price": 22000, | |
| "image": "/static/images/table1.webp" | |
| }, | |
| { | |
| "id": 11, | |
| "name": "Rustic Wood Dining Table", | |
| "category": "table", | |
| "price": 35000, | |
| "image": "/static/images/table2.png" | |
| }, | |
| { | |
| "id": 12, | |
| "name": "Compact Study Table", | |
| "category": "table", | |
| "price": 18000, | |
| "image": "/static/images/table3.webp" | |
| } | |
| ] | |
| # 1. First check for product-specific queries | |
| for product in products: | |
| if product['name'].lower() in query: | |
| return { | |
| "page": "Product Detail", | |
| "message": f"Here is the detail for {product['name']}:", | |
| "link": { | |
| "text": "π View Product Details", | |
| "url": f"{base_url}/product-detail/{product['id']}" | |
| }, | |
| "product_id": product["id"], | |
| "image": product["image"], | |
| "price": product["price"] | |
| } | |
| # 2. Check for category pages | |
| categories = { | |
| "sofa": { | |
| "url": f"{base_url}/products?category=sofa", | |
| "text": "ποΈ Browse All Sofas" | |
| }, | |
| "lamp": { | |
| "url": f"{base_url}/products?category=lamp", | |
| "text": "π‘ Browse All Lamps" | |
| }, | |
| "plant": { | |
| "url": f"{base_url}/products?category=plant", | |
| "text": "πΏ Browse All Plants" | |
| }, | |
| "table": { | |
| "url": f"{base_url}/products?category=table", | |
| "text": "πͺ Browse All Tables" | |
| } | |
| } | |
| for category, details in categories.items(): | |
| if category in query: | |
| return { | |
| "page": f"{category.title()} Collection", | |
| "message": f"Browse our {category} collection:", | |
| "link": details | |
| } | |
| if "contact" in query or "help" in query or "support" in query: | |
| return { | |
| "page": "Contact Us", | |
| "link": { | |
| "text": "π Contact Support", | |
| "url": f"{base_url}/contact" | |
| } | |
| } | |
| elif "new" in query or "new products" in query: | |
| return { | |
| "page": "New Arrivals", | |
| "link": { | |
| "text": "π View New Arrivals", | |
| "url": f"{base_url}/new" | |
| } | |
| } | |
| elif "shop" in query or "products" in query or "collection" in query: | |
| return { | |
| "page": "Shop Now", | |
| "link": { | |
| "text": "ποΈ Browse All Products", | |
| "url": f"{base_url}/products" | |
| } | |
| } | |
| elif "cart" in query or "basket" in query or "order" in query: | |
| return { | |
| "page": "Your Cart", | |
| "link": { | |
| "text": "π View Your Cart", | |
| "url": f"{base_url}/cart" | |
| } | |
| } | |
| # Default response if no match found | |
| return { | |
| "message": "I couldn't find that page. Here are some options:", | |
| "suggestions": [ | |
| "Browse sofas", | |
| "See new arrivals", | |
| "Contact support", | |
| "View my cart" | |
| ] | |
| } | |
| # ==================== UPDATED AGENT ==================== # | |
| shopper_agent = Agent( | |
| name="Enhanced Shopping Assistant", | |
| instructions=""" | |
| You are a smart shopping assistant for a furniture website in Karachi. | |
| RULES: | |
| 1. If a user mentions a product, always use `search_products` to check availability. | |
| 2. If product is found, tell the user it is available and ask for their phone number once. | |
| 3. If the user provides a phone number (in format 923XXXXXXXXX), use `handle_order` immediately. | |
| 4. If product is NOT found, use `suggest_market_for_product` to suggest nearby Karachi markets. | |
| 5. Do NOT switch to any other product unless the user explicitly mentions it. | |
| 6. Do NOT confuse a phone number with a product name. | |
| 7. Do NOT continue the chat after order confirmation is sent. | |
| EXAMPLES: | |
| User: βMujhe mirror chahiyeβ | |
| Assistant: search_products("mirror") β not found β suggest_market_for_product("mirror") | |
| User: βMujhe snake plant chahiyeβ | |
| Assistant: search_products("snake plant") β found β ask for phone number β user gives β handle_order() | |
| """, | |
| tools=[ | |
| search_products, | |
| filter_by_price, | |
| suggest_market_for_product, | |
| page_links, | |
| ] | |
| ) | |
| # ==================== FLASK APP ==================== # | |
| app = Flask(__name__) | |
| def home(): | |
| return render_template("index.html") | |
| def products_page(): | |
| return render_template("products.html") | |
| def cart(): | |
| return render_template("cart.html") | |
| def checkout(): | |
| return render_template("checkout.html") | |
| def contact(): | |
| return render_template('contact.html') | |
| def new_arrivals(): | |
| return render_template("new.html") | |
| def product_detail(product_id): | |
| # Find the product | |
| product = next((p for p in products if p['id'] == product_id), None) | |
| if not product: | |
| return "Product not found", 404 | |
| # Debug print to console | |
| print(f"\nDisplaying product ID {product_id}:") | |
| print(f"Name: {product['name']}") | |
| print(f"Image Path: {product['image']}\n") | |
| return render_template('product-detail.html', product=product) | |
| def chat(): | |
| user_message = request.json.get('message') | |
| response = Runner.run_sync( | |
| starting_agent=shopper_agent, | |
| input=user_message, | |
| run_config=config | |
| ) | |
| return jsonify({"reply": response.final_output}) | |
| if __name__ == '__main__': | |
| app.run(host="0.0.0.0", port=7860, debug=False) | |