Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (16)
- DockerfileAdded+13
- README.md+8-6
- auth.pyAdded+13
- config.pyAdded+38
- data/byg_menu.jsonAdded+53
- main.pyAdded+46
- matcher.pyAdded+44
- requirements.txtAdded+7
- routes/__init__.pyAdded
- routes/calls.pyAdded+80
- routes/menu.pyAdded+148
- routes/orders.pyAdded+160
- routes/webhooks.pyAdded+70
- sanitize.pyAdded+14
- seed.pyAdded+29
- store.pyAdded+219
12345678910111213# Bell backend — HuggingFace Spaces (Docker SDK, app_port 7860)FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 7860
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]1234523456778910101112---title: Bell Backendemoji: ⚡colorFrom: bluecolorTo: graytitle: bell-backendemoji: 🔔colorFrom: yellowcolorTo: redsdk: dockerpinned: falseapp_port: 7860---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Bell — BYG Brewski Voice Ordering API
FastAPI backend powering Bell, the voice AI ordering assistant. Tool endpoints for the Bolna agent + live order feeds for the kitchen display.12345678910111213"""Bearer-token guard for Bolna-facing tool endpoints."""
from fastapi import Header, HTTPException
import config
async def require_token(authorization: str = Header(default="")) -> None: if not config.BACKEND_API_TOKEN: return # auth disabled (local dev) token = authorization.removeprefix("Bearer ").strip() if token != config.BACKEND_API_TOKEN: raise HTTPException(status_code=401, detail="Invalid or missing API token")1234567891011121314151617181920212223242526272829303132333435363738"""Environment configuration. Every external service is optional —the backend degrades to local in-memory mode so the demo never blocks."""
import osfrom pathlib import Path
from dotenv import load_dotenv
load_dotenv()
BASE_DIR = Path(__file__).parentMENU_FILE = BASE_DIR / "data" / "byg_menu.json"
SUPABASE_URL = os.getenv("SUPABASE_URL", "")SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY", "")
BOLNA_API_KEY = os.getenv("BOLNA_API_KEY", "")BOLNA_AGENT_ID = os.getenv("BOLNA_AGENT_ID", "")BOLNA_WS_HOST = os.getenv("BOLNA_WS_HOST", "") # e.g. wss://ws.bolna.aiBOLNA_API_HOST = os.getenv("BOLNA_API_HOST", "https://api.bolna.ai")
# Bearer token Bolna tools must present when calling this backend.# Empty value disables auth (local dev).BACKEND_API_TOKEN = os.getenv("BACKEND_API_TOKEN", "")
# Origins allowed to call this API from the browser.CORS_ORIGINS = [ o.strip() for o in os.getenv("CORS_ORIGINS", "http://localhost:3000").split(",") if o.strip()]
DEFAULT_OUTLET = "Hennur"OUTLETS = ["Hennur", "Sarjapur", "Yeshwantpur"]
def supabase_configured() -> bool: return bool(SUPABASE_URL and SUPABASE_SERVICE_KEY)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "restaurant": "BYG Brewski", "outlets": ["Hennur", "Sarjapur", "Yeshwantpur"], "craft_beers": { "Hennur": [ {"name": "Belgian Wheat", "price": 349, "description": "A refreshing wheat beer with hints of coriander and citrus, delivering a zesty crisp finish perfect for easy sipping.", "abv": "5.2%", "style": "Wheat Beer", "rating": 4.5, "tags": ["recommended"]}, {"name": "Hazy IPA", "price": 399, "description": "A hazy IPA packed with tropical fruit aroma, a fuller body, and a smooth juicy flavor with minimal bitterness.", "abv": "6.5%", "style": "IPA", "rating": 4.7, "tags": ["bestseller", "recommended"]}, {"name": "Nitro Stout", "price": 399, "description": "A velvety dark ale with coffee and chocolate flavors, complemented by a cascading nitrogenated pour and caramel sweetness.", "abv": "4.8%", "style": "Stout", "rating": 4.6}, {"name": "Hefeweizen", "price": 349, "description": "A smooth wheat beer with subtle banana and clove aromas, offering a light fruity flavor profile.", "abv": "5.0%", "style": "Hefeweizen", "rating": 4.4}, {"name": "Smoked Bacon Ale", "price": 429, "description": "This beer brings bold bacon notes with campfire barbecue smokiness, balanced by sweet caramel malt for a hearty flavor.", "abv": "5.5%", "style": "Smoked Ale", "rating": 4.3, "tags": ["new"]}, {"name": "Classic Lager", "price": 329, "description": "A crisp clear lager with a soft mouthfeel, sweet malty notes, and a refreshing balance from Hallertau hops.", "abv": "4.5%", "style": "Lager", "rating": 4.4} ], "Sarjapur": [ {"name": "Hazy IPA", "price": 399, "description": "A hazy IPA packed with tropical fruit aroma, a fuller body, and a smooth juicy flavor with minimal bitterness.", "abv": "6.5%", "style": "IPA", "rating": 4.7, "tags": ["bestseller", "recommended"]}, {"name": "Belgian Wheat", "price": 349, "description": "A refreshing wheat beer with hints of coriander and citrus, delivering a zesty crisp finish.", "abv": "5.2%", "style": "Wheat Beer", "rating": 4.5, "tags": ["recommended"]}, {"name": "Nitro Stout", "price": 399, "description": "A velvety dark ale with coffee and chocolate flavors and a cascading nitrogenated pour.", "abv": "4.8%", "style": "Stout", "rating": 4.6}, {"name": "Belgian Triple", "price": 449, "description": "A Belgian-style triple that pours golden orange. Fruity aromas of sweet mango, banana, and spice with a medium-full body.", "abv": "8.5%", "style": "Belgian Triple", "rating": 4.5, "tags": ["new"]}, {"name": "Pilsner", "price": 329, "description": "A crisp clean classic lager made with Pilsner malt and Saaz hops. Light and well-carbonated.", "abv": "4.8%", "style": "Pilsner", "rating": 4.3}, {"name": "Apple Mead", "price": 429, "description": "A festive apple mead infused with cinnamon, nutmeg, and cloves for a warm spiced flavor.", "abv": "5.9%", "style": "Mead", "rating": 4.4, "tags": ["recommended"]} ], "Yeshwantpur": [ {"name": "German Lager", "price": 349, "description": "A clean crisp malty lager, medium-bodied and easy-drinking, brewed with authentic German malt and hops.", "abv": "5.0%", "style": "Lager", "rating": 4.4}, {"name": "Dark Lager", "price": 369, "description": "A smooth dark lager with gentle coffee and chocolate notes, hints of caramel, dried fruits, and a touch of liquorice.", "abv": "5.2%", "style": "Dark Lager", "rating": 4.5}, {"name": "Tropical Red Ale", "price": 399, "description": "A hazy red-brown beer with notes of banana, pineapple, and caramel sweetness, balanced by smoky malt and toasted coconut.", "abv": "5.8%", "style": "Red Ale", "rating": 4.4, "tags": ["new"]}, {"name": "Hazy IPA", "price": 399, "description": "A hazy IPA with bold passion fruit, orange, and tropical fruit flavors from Galaxy, Mosaic, and Citra hops.", "abv": "6.5%", "style": "IPA", "rating": 4.7, "tags": ["bestseller", "recommended"]}, {"name": "Belgian Wheat", "price": 349, "description": "A refreshing wheat beer with hints of coriander and citrus, delivering a zesty crisp finish.", "abv": "5.2%", "style": "Wheat Beer", "rating": 4.5, "tags": ["recommended"]}, {"name": "Hefeweizen", "price": 349, "description": "A smooth wheat beer with subtle banana and clove aromas, offering a light fruity flavor profile.", "abv": "5.0%", "style": "Hefeweizen", "rating": 4.4} ] }, "food_menu": [ {"name": "Nachos", "category": "starters", "is_veg": true, "price": 349, "description": "Crispy tortilla chips loaded with cheese, jalapeños, salsa, and sour cream.", "rating": 4.5, "spice_level": "medium", "tags": ["bestseller"]}, {"name": "Chicken Wings", "category": "starters", "is_veg": false, "price": 449, "description": "Crispy wings tossed in your choice of BBQ, buffalo, or honey garlic sauce.", "rating": 4.7, "spice_level": "hot", "tags": ["bestseller", "recommended"]}, {"name": "Paneer Tikka", "category": "starters", "is_veg": true, "price": 399, "description": "Smoky tandoor-grilled paneer with bell peppers, onions, and mint chutney.", "rating": 4.4, "spice_level": "medium", "tags": ["recommended"]}, {"name": "Bruschetta", "category": "starters", "is_veg": true, "price": 299, "description": "Toasted sourdough with fresh tomatoes, basil, garlic, and olive oil.", "rating": 4.2, "spice_level": "mild"}, {"name": "Calamari", "category": "starters", "is_veg": false, "price": 499, "description": "Lightly battered fried squid rings served with aioli and lemon.", "rating": 4.3, "spice_level": "mild"}, {"name": "Margherita Pizza", "category": "mains", "is_veg": true, "price": 549, "description": "Classic thin crust with San Marzano tomatoes, fresh mozzarella, and basil.", "rating": 4.3, "spice_level": "mild"}, {"name": "BBQ Chicken Pizza", "category": "mains", "is_veg": false, "price": 649, "description": "Smoky BBQ base with grilled chicken, caramelized onions, and mozzarella.", "rating": 4.6, "spice_level": "mild", "tags": ["bestseller"]}, {"name": "Chicken Burger", "category": "mains", "is_veg": false, "price": 449, "description": "Grilled chicken patty with lettuce, tomato, pickles, and house sauce in a brioche bun.", "rating": 4.5, "spice_level": "mild", "tags": ["recommended"]}, {"name": "Veggie Burger", "category": "mains", "is_veg": true, "price": 399, "description": "Black bean and quinoa patty with avocado, lettuce, and sriracha mayo.", "rating": 4.1, "spice_level": "mild"}, {"name": "Butter Chicken", "category": "mains", "is_veg": false, "price": 549, "description": "Tender chicken in a rich, creamy tomato-based curry. Best paired with naan.", "rating": 4.6, "spice_level": "medium", "tags": ["bestseller", "recommended"]}, {"name": "Dal Makhani", "category": "mains", "is_veg": true, "price": 449, "description": "Slow-cooked black lentils in a buttery tomato gravy. Comfort food at its finest.", "rating": 4.5, "spice_level": "mild", "tags": ["recommended"]}, {"name": "Fish and Chips", "category": "mains", "is_veg": false, "price": 599, "description": "Beer-battered fish with crispy fries, tartar sauce, and mushy peas.", "rating": 4.4, "spice_level": "mild"}, {"name": "Garlic Bread", "category": "sides", "is_veg": true, "price": 199, "description": "Toasted baguette with garlic butter and herbs. Perfect with pizza.", "rating": 4.3, "spice_level": "mild"}, {"name": "French Fries", "category": "sides", "is_veg": true, "price": 249, "description": "Golden crispy fries seasoned with sea salt. Classic and irresistible.", "rating": 4.2, "spice_level": "mild"}, {"name": "Raita", "category": "sides", "is_veg": true, "price": 149, "description": "Chilled yogurt with cucumber, cumin, and mint. Perfect with biryani.", "rating": 4.0, "spice_level": "mild"}, {"name": "Chocolate Lava Cake", "category": "desserts", "is_veg": true, "price": 349, "description": "Warm chocolate cake with a molten centre, served with vanilla ice cream.", "rating": 4.8, "spice_level": "none", "tags": ["bestseller"]}, {"name": "Tiramisu", "category": "desserts", "is_veg": true, "price": 299, "description": "Classic Italian dessert with espresso-soaked ladyfingers and mascarpone.", "rating": 4.5, "spice_level": "none"}, {"name": "Virgin Mojito", "category": "mocktails", "is_veg": true, "price": 249, "description": "Fresh lime, mint, soda, and sugar syrup. Refreshing and light.", "rating": 4.4, "spice_level": "none"}, {"name": "Blue Lagoon", "category": "mocktails", "is_veg": true, "price": 279, "description": "Blue curacao syrup, lemon, and soda. Visually stunning and refreshing.", "rating": 4.3, "spice_level": "none"}, {"name": "Watermelon Cooler", "category": "mocktails", "is_veg": true, "price": 259, "description": "Fresh watermelon juice with mint, lime, and a hint of ginger.", "rating": 4.5, "spice_level": "none", "tags": ["recommended"]}, {"name": "Water Bottle", "category": "beverages", "is_veg": true, "price": 60, "description": "500ml mineral water.", "rating": null, "spice_level": "none"} ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Bell backend — voice ordering API for BYG Brewski (Bolna tool endpoints +frontend endpoints). Runs on HuggingFace Spaces (port 7860) or locally."""
from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware
import configfrom routes import calls, menu, orders, webhooksfrom store import get_store
app = FastAPI(title="Bell — BYG Brewski Voice Ordering API", version="1.0.0")
app.add_middleware( CORSMiddleware, allow_origins=config.CORS_ORIGINS, allow_origin_regex=r"https://.*\.vercel\.app", allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
app.include_router(menu.router)app.include_router(orders.router)app.include_router(calls.router)app.include_router(webhooks.router)
@app.get("/")async def root(): return {"service": "bell-backend", "restaurant": "BYG Brewski", "docs": "/docs"}
@app.get("/api/health")async def health(): """Read-only health check — never seeds or mutates state.""" try: store_health = get_store().health() return {"status": "ok", **store_health, "bolna_configured": bool(config.BOLNA_AGENT_ID)} except Exception as exc: return {"status": "degraded", "error": str(exc)}
if __name__ == "__main__": import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344"""RapidFuzz menu matching — fast, no embeddings, no cold start.
Handles voice-transcript noise: "hazy ipa beer" → Hazy IPA,"nacho chips" → Nachos, "butter chiken" → Butter Chicken."""
from __future__ import annotations
from typing import Optional
from rapidfuzz import fuzz
MATCH_THRESHOLD = 70
# Words the LLM/customer commonly appends that aren't part of menu names._NOISE_WORDS = {"beer", "pint", "glass", "bottle", "dish", "plate", "the", "a", "an", "one"}
def _normalize(text: str) -> str: words = [w for w in text.lower().replace("-", " ").split() if w not in _NOISE_WORDS] return " ".join(words) or text.lower().strip()
def find_dish(query: str, menu: list[dict]) -> tuple[Optional[dict], float]: """Return (best_match_item, confidence 0-100) or (None, score) below threshold.""" if not query or not query.strip() or not menu: return None, 0.0
normalized_query = _normalize(query)
def score(name: str) -> float: # token_set handles word-subset matches ("lava cake" → Chocolate Lava # Cake); WRatio handles near-token noise ("nacho chips" → Nachos). return max( fuzz.token_set_ratio(normalized_query, name.lower()), fuzz.WRatio(normalized_query, name.lower()), )
best_item, best_score = max( ((item, score(item["name"])) for item in menu), key=lambda pair: pair[1] ) if best_score < MATCH_THRESHOLD: return None, float(best_score) return best_item, float(best_score)1234567fastapi>=0.111uvicorn[standard]>=0.30supabase>=2.5rapidfuzz>=3.9httpx>=0.27python-dotenv>=1.0pydantic>=2.71234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Phone-fallback calling via Bolna's outbound API + web-call config for the browser."""
from __future__ import annotations
import refrom typing import Optional
import httpxfrom fastapi import APIRouterfrom pydantic import BaseModel
import configimport sanitize
router = APIRouter(prefix="/api", tags=["calls"])
class CallBody(BaseModel): phone: str table_number: Optional[str] = None outlet_location: str = config.DEFAULT_OUTLET
def normalize_phone(phone: str) -> Optional[str]: """Return E.164 or None. Bare 10-digit numbers are assumed Indian (+91).""" digits = re.sub(r"[^\d+]", "", phone.strip()) if re.fullmatch(r"\+\d{10,15}", digits): return digits if re.fullmatch(r"\d{10}", digits): return f"+91{digits}" if re.fullmatch(r"91\d{10}", digits): return f"+{digits}" return None
@router.post("/call")async def start_phone_call(body: CallBody): phone = normalize_phone(body.phone) if not phone: return {"success": False, "message": "Please enter a valid 10-digit phone number."} if not (config.BOLNA_API_KEY and config.BOLNA_AGENT_ID): return {"success": False, "message": "Phone calling is not configured yet (missing Bolna keys)."}
payload = { "agent_id": config.BOLNA_AGENT_ID, "recipient_phone_number": phone, "user_data": { "restaurant_name": "BYG Brewski", "table_number": sanitize.clean(body.table_number) or "takeaway", "outlet_location": sanitize.clean(body.outlet_location) or config.DEFAULT_OUTLET, }, } try: async with httpx.AsyncClient(timeout=15) as client: res = await client.post( f"{config.BOLNA_API_HOST}/call", json=payload, headers={"Authorization": f"Bearer {config.BOLNA_API_KEY}"}, ) data = res.json() if res.status_code >= 400: return {"success": False, "message": data.get("message", "Bolna rejected the call request.")} return {"success": True, "execution_id": data.get("execution_id"), "message": "Bell is calling you now."} except Exception as exc: return {"success": False, "message": f"Could not start the call: {exc}"}
@router.get("/webcall-config")async def webcall_config(): """Runtime config for the browser web call. Keeps tokens out of the JS bundle; exposure at runtime is an accepted hackathon trade-off (use short-lived tokens here if/when Bolna issues them).""" if not (config.BOLNA_AGENT_ID and config.BOLNA_API_KEY and config.BOLNA_WS_HOST): return {"available": False, "message": "Web calling not configured. Use phone fallback."} return { "available": True, "agent_id": config.BOLNA_AGENT_ID, "access_token": config.BOLNA_API_KEY, "ws_host": config.BOLNA_WS_HOST, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Menu tools called by the Bolna agent (get_menu, get_dish_details).
Tool endpoints always return 200 with {success: bool, ...} — the agent'sscripted retry/fallback lines depend on never seeing a transport error."""
from fastapi import APIRouter, Depends, Query
import sanitizefrom auth import require_tokenfrom matcher import find_dishfrom store import get_store
router = APIRouter(prefix="/api/menu", tags=["menu"], dependencies=[Depends(require_token)])
MAX_ITEMS = 12
# Single source of truth mapping the agent's category vocabulary → filters.# A filter is (field, value) checked against each menu row.CATEGORY_ALIASES: dict[str, dict] = { "all": {}, # veg/non-veg mean food in the agent's vocabulary — beers excluded "veg": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]}, "vegetarian": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]}, "non-veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, "nonveg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, "non veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, "starters": {"category": "starters"}, "appetizers": {"category": "starters"}, "mains": {"category": "mains"}, "main course": {"category": "mains"}, "sides": {"category": "sides"}, "desserts": {"category": "desserts"}, "dessert": {"category": "desserts"}, "mocktails": {"category": "mocktails"}, "mocktail": {"category": "mocktails"}, "drinks": {"category": ["mocktails", "craft-beer", "beverages"]}, "beverages": {"category": ["mocktails", "craft-beer", "beverages"]}, "craft-beer": {"category": "craft-beer"}, "craft beer": {"category": "craft-beer"}, "beer": {"category": "craft-beer"}, "beers": {"category": "craft-beer"}, "food": {"category": ["starters", "mains", "sides", "desserts"]},}
def _matches(item: dict, filters: dict) -> bool: for field, expected in filters.items(): actual = item.get(field) if isinstance(expected, list): if actual not in expected: return False elif actual != expected: return False return True
def _at_outlet(item: dict, outlet: str | None) -> bool: if not outlet: return True outlets = [o.lower() for o in (item.get("outlet_location") or [])] # Unknown outlet name → don't filter (better to show menu than nothing). return outlet.lower() in outlets if outlets else True
def _compact(item: dict) -> dict: out = { "name": item["name"], "price": item["price"], "category": item["category"], "is_veg": item.get("is_veg"), "description": (item.get("description") or "")[:140], "rating": item.get("rating"), "tags": item.get("tags") or [], } if item.get("abv"): out["abv"] = item["abv"] out["style"] = item.get("style") return out
@router.get("")async def get_menu( category: str = Query(default="all"), outlet_location: str = Query(default=""),): try: menu = get_store().get_menu() key = (sanitize.clean(category) or "all").lower() filters = CATEGORY_ALIASES.get(key) if filters is None: # Unknown category from the LLM — fuzzy-fall back to everything # rather than failing the tool call. filters = {}
outlet = sanitize.clean(outlet_location) rows = [m for m in menu if _matches(m, filters) and _at_outlet(m, outlet)] rows.sort(key=lambda m: (m.get("rating") or 0), reverse=True) items = [_compact(m) for m in rows[:MAX_ITEMS]]
if not items: return { "success": True, "items": [], "message": f"No items found for category '{category}'. Try another category.", } return {"success": True, "category": key, "count": len(items), "items": items} except Exception as exc: # never 500 a tool call return {"success": False, "message": f"Menu temporarily unavailable: {exc}"}
@router.get("/dish")async def get_dish_details(dish_name: str = Query(default="")): try: name = sanitize.clean(dish_name) if not name: return {"success": False, "found": False, "message": "No dish name provided."}
menu = get_store().get_menu() item, confidence = find_dish(name, menu) if item is None: return { "success": True, "found": False, "message": f"No close match for '{dish_name}' on the menu.", } return { "success": True, "found": True, "confidence": confidence, "dish": { "name": item["name"], "price": item["price"], "currency": "INR", "category": item["category"], "is_veg": item.get("is_veg"), "description": item.get("description"), "rating": item.get("rating"), "spice_level": item.get("spice_level"), "abv": item.get("abv"), "style": item.get("style"), "allergens": item.get("allergens") or [], "tags": item.get("tags") or [], "available_at": item.get("outlet_location") or [], }, } except Exception as exc: return {"success": False, "message": f"Dish lookup failed: {exc}"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Order tools (place_order, get_order_status) + kitchen display endpoints."""
from __future__ import annotations
import refrom typing import Optional
from fastapi import APIRouter, Depends, Queryfrom pydantic import BaseModel
import configimport sanitizefrom auth import require_tokenfrom matcher import find_dishfrom store import ORDER_STATUSES, get_store
router = APIRouter(prefix="/api/orders", tags=["orders"])
# "2x Nachos", "2 x Nachos", "2 Nachos", "Nachos" (qty 1)_ITEM_RE = re.compile(r"^\s*(\d+)\s*[x×*]?\s*(.+?)\s*$", re.IGNORECASE)
def parse_items(items_str: str, menu: list[dict]) -> tuple[list[dict], int]: """Parse the agent's comma-separated item string into priced line items.
Unresolved names are kept with price=None so the kitchen still sees them. Returns (items, total) where total covers only priced items. """ items: list[dict] = [] total = 0 for segment in items_str.split(","): segment = segment.strip() if not segment: continue m = _ITEM_RE.match(segment) if m and m.group(2): quantity, name = int(m.group(1)), m.group(2) else: quantity, name = 1, segment
matched, _ = find_dish(name, menu) if matched: price = matched["price"] items.append({"name": matched["name"], "quantity": quantity, "price": price}) total += price * quantity else: items.append({"name": name, "quantity": quantity, "price": None}) return items, total
class PlaceOrderBody(BaseModel): items: str order_type: str = "dine-in" outlet_location: str = config.DEFAULT_OUTLET table_number: Optional[str] = None customer_name: Optional[str] = None customer_phone: Optional[str] = None call_id: Optional[str] = None
@router.post("", dependencies=[Depends(require_token)])async def place_order(body: PlaceOrderBody): try: store = get_store() items_str = sanitize.clean(body.items) if not items_str: return {"success": False, "message": "No items in the order."}
items, total = parse_items(items_str, store.get_menu()) if not items: return {"success": False, "message": "Could not understand the order items."}
order = store.insert_order( { "table_number": sanitize.clean(body.table_number), "outlet_location": sanitize.clean(body.outlet_location) or config.DEFAULT_OUTLET, "order_type": (sanitize.clean(body.order_type) or "dine-in").lower(), "items": items, "total_amount": total, "customer_name": sanitize.clean(body.customer_name), "customer_phone": sanitize.clean(body.customer_phone), "call_id": sanitize.clean(body.call_id), } ) unresolved = [i["name"] for i in items if i["price"] is None] message = f"Order sent to the kitchen. Total ₹{total}." if unresolved: message += f" Note: {', '.join(unresolved)} will be confirmed by staff." return {"success": True, "order_id": order["id"], "total_amount": total, "message": message} except Exception as exc: return {"success": False, "message": f"Could not place the order: {exc}"}
@router.get("/status", dependencies=[Depends(require_token)])async def get_order_status( table_number: str = Query(default=""), outlet_location: str = Query(default=config.DEFAULT_OUTLET),): try: table = sanitize.clean(table_number) outlet = sanitize.clean(outlet_location) or config.DEFAULT_OUTLET if not table: return {"success": False, "message": "No table number provided."}
order = get_store().latest_order(table, outlet) if not order: return { "success": True, "found": False, "message": f"No order found for table {table} yet.", }
friendly = { "received": "Your order has reached the kitchen and will be picked up shortly.", "preparing": "The kitchen is preparing your order right now.", "ready": "Your order is ready and on its way to your table!", "served": "Your order has been served. Enjoy!", } return { "success": True, "found": True, "status": order["status"], "items": order["items"], "total_amount": order.get("total_amount"), "message": friendly.get(order["status"], f"Order status: {order['status']}"), } except Exception as exc: return {"success": False, "message": f"Could not fetch order status: {exc}"}
# ---- Frontend-facing endpoints (kitchen display + table tracker polling) ----
@router.get("")async def list_orders(outlet_location: str = Query(default="")): store = get_store() return {"orders": store.list_orders(sanitize.clean(outlet_location))}
@router.get("/table")async def orders_for_table( table_number: str = Query(...), outlet_location: str = Query(default=config.DEFAULT_OUTLET),): store = get_store() return {"orders": store.orders_for_table(table_number, outlet_location)}
class StatusBody(BaseModel): status: str
@router.patch("/{order_id}/status")async def update_status(order_id: str, body: StatusBody): if body.status not in ORDER_STATUSES: return {"success": False, "message": f"Invalid status. Use one of {ORDER_STATUSES}."} order = get_store().update_order_status(order_id, body.status) if not order: return {"success": False, "message": "Order not found."} return {"success": True, "order": order}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Bolna post-call webhook → call_logs audit trail.
Bolna's payload shape varies by configuration, so parsing is defensive:we pick out whatever transcript/extraction/context fields are present."""
from __future__ import annotations
from fastapi import APIRouter, Request
from store import get_store
router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
def _parse_transcript(payload: dict): raw = ( payload.get("transcript") or payload.get("transcription") or (payload.get("telephony_data") or {}).get("transcript") or (payload.get("data") or {}).get("transcript") ) if raw is None: return None if isinstance(raw, list): return raw if isinstance(raw, str): # "assistant: hi\nuser: hello" style → structured turns turns = [] for line in raw.splitlines(): line = line.strip() if not line: continue role, _, text = line.partition(":") if text and role.lower() in ("assistant", "user", "agent", "customer", "bell", "human"): turns.append({"role": role.strip().lower(), "text": text.strip()}) else: turns.append({"role": "unknown", "text": line}) return turns return [{"role": "unknown", "text": str(raw)}]
@router.post("/bolna")async def bolna_webhook(request: Request): try: payload = await request.json() except Exception: return {"success": False, "message": "Invalid JSON payload."}
context = ( payload.get("context_details") or payload.get("user_data") or (payload.get("context_data") or {}) ) if isinstance(context, dict): context = context.get("recipient_data") or context
log = { "session_id": payload.get("id") or payload.get("execution_id") or payload.get("call_id") or payload.get("call_sid"), "table_number": str(context.get("table_number")) if isinstance(context, dict) and context.get("table_number") else None, "outlet_location": context.get("outlet_location") if isinstance(context, dict) else None, "channel": "phone" if payload.get("telephony_data") else "web", "transcript": _parse_transcript(payload), "extractions": payload.get("extracted_data") or payload.get("extraction") or None, } saved = get_store().upsert_call_log(log) return {"success": True, "id": saved.get("id")}1234567891011121314"""Bolna substitutes absent %(param)s values as literal strings like "None" —normalize those artifacts to real nulls before they reach storage."""
from typing import Optional
_NULL_ARTIFACTS = {"none", "null", "", "undefined", "not applicable", "n/a", "nil"}
def clean(value: Optional[str]) -> Optional[str]: if value is None: return None if value.strip().lower() in _NULL_ARTIFACTS: return None return value.strip()1234567891011121314151617181920212223242526272829"""One-off seeding script — loads data/byg_menu.json into Supabase.
Run manually after applying database/schema.sql: python seed.py
Never runs at startup; restarts must not touch production data."""
import sys
import configfrom store import load_menu_from_file
def main(): if not config.supabase_configured(): sys.exit("SUPABASE_URL / SUPABASE_SERVICE_KEY not set — nothing to seed.")
from supabase import create_client
client = create_client(config.SUPABASE_URL, config.SUPABASE_SERVICE_KEY) items = load_menu_from_file()
res = client.table("menu_items").upsert(items, on_conflict="name,category").execute() print(f"Seeded {len(res.data)} menu items into Supabase.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""Storage layer: SupabaseStore when keys are configured, MemoryStore otherwise.
MemoryStore keeps the whole stack runnable with zero external services —menu loads from data/byg_menu.json and orders live in process memory(the frontend polls instead of using realtime in that mode)."""
from __future__ import annotations
import jsonimport uuidfrom datetime import datetime, timezonefrom typing import Any, Optional
import config
ORDER_STATUSES = ["received", "preparing", "ready", "served"]
def load_menu_from_file() -> list[dict]: """Flatten byg_menu.json into menu_items rows (food shared across outlets, craft beers merged per-outlet by name).""" raw = json.loads(config.MENU_FILE.read_text()) items: list[dict] = []
for food in raw["food_menu"]: items.append( { "name": food["name"], "category": food["category"], "description": food.get("description"), "price": food["price"], "is_veg": food.get("is_veg", False), "is_available": True, "rating": food.get("rating"), "spice_level": food.get("spice_level"), "abv": None, "style": None, "outlet_location": raw["outlets"], "tags": food.get("tags", []), } )
beers: dict[str, dict] = {} for outlet, brews in raw["craft_beers"].items(): for brew in brews: entry = beers.setdefault( brew["name"], { "name": brew["name"], "category": "craft-beer", "description": brew.get("description"), "price": brew["price"], "is_veg": True, "is_available": True, "rating": brew.get("rating"), "spice_level": "none", "abv": brew.get("abv"), "style": brew.get("style"), "outlet_location": [], "tags": brew.get("tags", []), }, ) entry["outlet_location"].append(outlet)
items.extend(beers.values()) return items
def _now() -> str: return datetime.now(timezone.utc).isoformat()
class MemoryStore: mode = "memory"
def __init__(self): self.menu = load_menu_from_file() self.orders: list[dict] = [] self.call_logs: dict[str, dict] = {}
def get_menu(self) -> list[dict]: return self.menu
def insert_order(self, order: dict) -> dict: order = { **order, "id": str(uuid.uuid4()), "status": "received", "created_at": _now(), "updated_at": _now(), } self.orders.append(order) return order
def list_orders(self, outlet_location: Optional[str] = None) -> list[dict]: rows = [ o for o in self.orders if not outlet_location or o["outlet_location"].lower() == outlet_location.lower() ] return sorted(rows, key=lambda o: o["created_at"], reverse=True)
def latest_order(self, table_number: str, outlet_location: str) -> Optional[dict]: for o in self.list_orders(outlet_location): if str(o.get("table_number")) == str(table_number): return o return None
def orders_for_table(self, table_number: str, outlet_location: str) -> list[dict]: return [ o for o in self.list_orders(outlet_location) if str(o.get("table_number")) == str(table_number) ]
def update_order_status(self, order_id: str, status: str) -> Optional[dict]: for o in self.orders: if o["id"] == order_id: o["status"] = status o["updated_at"] = _now() return o return None
def upsert_call_log(self, log: dict) -> dict: key = log.get("session_id") or str(uuid.uuid4()) existing = self.call_logs.get(key, {"id": str(uuid.uuid4()), "created_at": _now()}) existing.update({k: v for k, v in log.items() if v is not None}) existing["session_id"] = key self.call_logs[key] = existing return existing
def health(self) -> dict: return {"store": "memory", "menu_items": len(self.menu), "orders": len(self.orders)}
class SupabaseStore: mode = "supabase"
def __init__(self): from supabase import create_client
self.client = create_client(config.SUPABASE_URL, config.SUPABASE_SERVICE_KEY) self._menu_cache: list[dict] = []
def get_menu(self) -> list[dict]: if not self._menu_cache: res = ( self.client.table("menu_items") .select("*") .eq("is_available", True) .execute() ) self._menu_cache = res.data or [] if not self._menu_cache: # Table not seeded yet — fall back to the bundled menu so # the agent tools keep working. self._menu_cache = load_menu_from_file() return self._menu_cache
def insert_order(self, order: dict) -> dict: res = self.client.table("orders").insert(order).execute() return res.data[0]
def list_orders(self, outlet_location: Optional[str] = None) -> list[dict]: q = self.client.table("orders").select("*").order("created_at", desc=True).limit(50) if outlet_location: q = q.ilike("outlet_location", outlet_location) return q.execute().data or []
def latest_order(self, table_number: str, outlet_location: str) -> Optional[dict]: rows = self.orders_for_table(table_number, outlet_location) return rows[0] if rows else None
def orders_for_table(self, table_number: str, outlet_location: str) -> list[dict]: res = ( self.client.table("orders") .select("*") .eq("table_number", str(table_number)) .ilike("outlet_location", outlet_location) .order("created_at", desc=True) .limit(20) .execute() ) return res.data or []
def update_order_status(self, order_id: str, status: str) -> Optional[dict]: res = ( self.client.table("orders") .update({"status": status, "updated_at": _now()}) .eq("id", order_id) .execute() ) return res.data[0] if res.data else None
def upsert_call_log(self, log: dict) -> dict: res = ( self.client.table("call_logs") .upsert(log, on_conflict="session_id") .execute() ) return res.data[0] if res.data else log
def health(self) -> dict: count = ( self.client.table("menu_items").select("id", count="exact").execute().count ) return {"store": "supabase", "menu_items": count}
_store: MemoryStore | SupabaseStore | None = None
def get_store(): global _store if _store is None: _store = SupabaseStore() if config.supabase_configured() else MemoryStore() return _storeDockerfileAdded+13
README.md+8-6
auth.pyAdded+13
config.pyAdded+38
data/byg_menu.jsonAdded+53
main.pyAdded+46
matcher.pyAdded+44
requirements.txtAdded+7
routes/__init__.pyAdded
routes/calls.pyAdded+80
routes/menu.pyAdded+148
routes/orders.pyAdded+160
routes/webhooks.pyAdded+70
sanitize.pyAdded+14
seed.pyAdded+29
store.pyAdded+219