Download tasks/brooklinen/tests/oracle-runtime/clone/app.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 24.8 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/brooklinen/tests/oracle-runtime/clone/app.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/brooklinen/tests/oracle-runtime/clone/app.py
-
curl -L -o app.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/brooklinen/tests/oracle-runtime/clone/app.py
24.8 kB
| """Brooklinen offline clone — WebsiteBench candidate application. | |
| Serves the frozen source-derived catalogue, journeys and states entirely from | |
| local data. No runtime remote request is made; carts, accounts, orders, mail and | |
| payments are deterministic local sandbox effects. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import pathlib | |
| import secrets | |
| from typing import Any | |
| from fastapi import FastAPI, Form, Query, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| import catalog as cat | |
| import content as C | |
| import store | |
| from backend.site_backend_integration import open_site_services | |
| BASE = pathlib.Path(__file__).resolve().parent | |
| SITE_ID = "brooklinen" | |
| DISPLAY_NAME = "Brooklinen" | |
| SESSION_COOKIE = "brooklinen_session" | |
| BATCH_SIZE = 22 # source-observed first collection batch | |
| PAYMENT_SCENARIOS = [ | |
| {"id": "sandbox-approved", "label": "Simulated approval"}, | |
| {"id": "sandbox-declined", "label": "Simulated decline"}, | |
| {"id": "sandbox-retry", "label": "Simulated retry"}, | |
| ] | |
| app = FastAPI(title=DISPLAY_NAME) | |
| app.mount("/static", StaticFiles(directory=BASE / "static"), name="static") | |
| app.mount("/assets", StaticFiles(directory=BASE / "static/assets"), name="assets") | |
| templates = Jinja2Templates(directory=BASE / "frontend/templates") | |
| templates.env.globals["display_name"] = DISPLAY_NAME | |
| _backend = None | |
| _auth = None | |
| def services(): | |
| global _backend, _auth | |
| if _backend is None: | |
| _backend, _auth = open_site_services() | |
| with _backend.lifecycle.connection() as conn: | |
| store.ensure_schema(conn) | |
| return _backend, _auth | |
| def conn(): | |
| backend, _ = services() | |
| return backend.lifecycle.connection() | |
| # ---------------------------------------------------------------- session | |
| def session_token(request: Request) -> str: | |
| return request.cookies.get(SESSION_COOKIE) or "" | |
| def ensure_session(request: Request, response: Response) -> str: | |
| """Bind the browser to a session issued by the local auth store.""" | |
| _, auth = services() | |
| token = session_token(request) | |
| issued, _state = auth.ensure_session(token or None) | |
| if issued != token: | |
| response.set_cookie(SESSION_COOKIE, issued, httponly=True, samesite="lax", path="/") | |
| return issued | |
| def current_customer(token: str) -> dict | None: | |
| _, auth = services() | |
| if not token: | |
| return None | |
| try: | |
| resolved = auth.resolve_session(token) | |
| except Exception: | |
| return None | |
| if not resolved or not resolved.get("authenticated"): | |
| return None | |
| account = resolved.get("account") or {} | |
| email = account.get("email_normalized") | |
| if not email: | |
| return None | |
| import time as _time | |
| return {"email": email, "display_name": account.get("display_name"), | |
| "created_at": _time.strftime("%b %Y", _time.localtime(resolved.get("created_at", 0)))} | |
| # ---------------------------------------------------------------- cart model | |
| def cart_view(token: str) -> dict[str, Any]: | |
| idx = cat.variant_index() | |
| items, subtotal, savings = [], 0.0, 0.0 | |
| if token: | |
| with conn() as c: | |
| rows = store.cart_rows(c, token) | |
| for variant_id, quantity in rows: | |
| found = idx.get(variant_id) | |
| if not found: | |
| continue | |
| handle, v = found | |
| p = cat.catalog()["products"][handle] | |
| unit = float(v["price"]) | |
| unit_sale = round(unit * (1 - cat.SITEWIDE_DISCOUNT), 2) | |
| subtotal += unit_sale * quantity | |
| savings += (unit - unit_sale) * quantity | |
| items.append({ | |
| "variant_id": variant_id, "handle": handle, "title": p["title"], | |
| "option1": v.get("option1"), "option2": v.get("option2"), | |
| "quantity": quantity, "unit_price": unit, "unit_sale_price": unit_sale, | |
| "on_sale": True, | |
| "image": cat.img_url(v.get("image") or (p["images"][0] if p["images"] else None), cat.SWATCH), | |
| }) | |
| remaining = max(0.0, cat.FREE_SHIPPING_THRESHOLD - subtotal) | |
| return { | |
| "lines": items, | |
| "item_count": sum(i["quantity"] for i in items), | |
| "subtotal": round(subtotal, 2), | |
| "savings": round(savings, 2), | |
| "free_shipping_remaining": round(remaining, 2), | |
| "free_shipping_pct": min(100, int(subtotal / cat.FREE_SHIPPING_THRESHOLD * 100)) if subtotal else 0, | |
| "shipping_label": "Free" if remaining <= 0 and subtotal else "TBD", | |
| } | |
| def base_ctx(request: Request, **extra) -> dict[str, Any]: | |
| token = session_token(request) | |
| ctx = { | |
| "request": request, | |
| "main_nav": C.MAIN_NAV, | |
| "nav_panels": C.NAV_PANELS, | |
| "nav_free_shipping": C.NAV_FREE_SHIPPING, | |
| "footer_nav": C.FOOTER_NAV, | |
| "announcement": C.ANNOUNCEMENTS[1], | |
| "cart": cart_view(token), | |
| "customer": current_customer(token), | |
| "current_nav": request.url.path, | |
| # The source raises this offer through a third-party script a few seconds into a | |
| # first visit. Reproducing that timing would make every frame non-deterministic, so | |
| # the clone exposes it as an explicit state instead of an automatic overlay. | |
| "show_offer_modal": request.query_params.get("offer") == "1" | |
| and request.cookies.get("bk_offer") is None, | |
| "q": request.query_params.get("q"), | |
| "request_path": request.url.path, | |
| "newsletter_message": None, | |
| "show_social_proof": request.url.path != "/", | |
| } | |
| ctx.update(extra) | |
| return ctx | |
| def render(name: str, request: Request, status_code: int = 200, **extra) -> HTMLResponse: | |
| ctx = base_ctx(request, **extra) | |
| response = templates.TemplateResponse(request, name, ctx, status_code=status_code) | |
| ensure_session(request, response) | |
| return response | |
| # ---------------------------------------------------------------- health | |
| def healthz() -> dict[str, object]: | |
| return {"ok": True, "site_id": SITE_ID} | |
| # ---------------------------------------------------------------- home | |
| def home(request: Request): | |
| products = cat.catalog()["products"] | |
| def module(spec): | |
| return {"title": spec["title"], | |
| "products": [products[h] for h in spec["handles"] if h in products]} | |
| categories = [dict(c) for c in C.HOME_CATEGORIES] | |
| spotlight = [dict(s) for s in C.HOME_SPOTLIGHT] | |
| duo = dict(C.DUO_SHOP) | |
| duo["products"] = [products[h] for h in duo["handles"] if h in products] | |
| duo["image"] = (duo["products"][0]["card_image"] if duo["products"] else None) | |
| return render("home.html", request, | |
| hero=dict(C.HOME_HERO), new_hero=dict(C.NEW_HERO), | |
| collection_module=module(C.HOME_COLLECTION), | |
| new_arrivals_module=module(C.HOME_NEW_ARRIVALS), | |
| categories=categories, duo=duo, reviews=C.HOME_REVIEWS, | |
| spotlight=spotlight, press=C.PRESS, stores=C.STORES) | |
| # ---------------------------------------------------------------- landing pages | |
| def page(request: Request, slug: str): | |
| if slug in C.LANDING_PAGES: | |
| spec = C.LANDING_PAGES[slug] | |
| rows, used = [], set() | |
| for row in spec["rows"]: | |
| kind = row.get("kind", "products") | |
| if kind != "products": | |
| rows.append({**row, "kind": kind}) | |
| continue | |
| col = cat.collection(row["collection"]) | |
| if not col: | |
| continue | |
| pool = cat.products_for(col["product_handles"]) | |
| wanted = row.get("bundle_type") | |
| if wanted: | |
| pool = [p for p in pool if wanted in p["facets"].get("bundle_type", [])] | |
| # Two source rows share one bundle-type tag; keep their products distinct. | |
| fresh = [p for p in pool if p["handle"] not in used] or pool | |
| picked = fresh[: row["limit"]] | |
| used.update(p["handle"] for p in picked) | |
| rows.append({"kind": "products", "id": row.get("id"), "title": row["title"], | |
| "url": row.get("url"), "includes": row.get("includes"), | |
| "products": picked}) | |
| fabrics = [] | |
| for i, f in enumerate(spec["fabrics"]): | |
| image = f.get("image") | |
| if not image: | |
| handle = f["url"].rsplit("/", 1)[-1] | |
| col = cat.collection(handle) or cat.collection("all-towels") | |
| sample = cat.products_for(col["product_handles"][i: i + 1]) | |
| image = sample[0]["card_image"] if sample else None | |
| fabrics.append({**f, "image": image}) | |
| spotlight = [] | |
| for i, sp in enumerate(spec.get("spotlight", [])): | |
| col = cat.collection(sp["url"].rsplit("/", 1)[-1]) or cat.collection("best-sellers") | |
| sample = cat.products_for(col["product_handles"][i: i + 1]) | |
| spotlight.append({**sp, "image": sample[0]["card_image"] if sample else None}) | |
| page_ctx = {**spec, "slug": slug, "rows": rows, "fabrics": fabrics, "spotlight": spotlight} | |
| return render("landing.html", request, page=page_ctx) | |
| if slug in C.CONTENT_PAGES: | |
| title, body = C.CONTENT_PAGES[slug] | |
| return render("content.html", request, page={"title": title, "body": body}) | |
| return render("notfound.html", request, status_code=404) | |
| # ---------------------------------------------------------------- collections | |
| def collection(request: Request, handle: str, batch: int = Query(1, ge=1)): | |
| col = cat.collection(handle) | |
| if not col: | |
| return render("notfound.html", request, status_code=404) | |
| products = cat.products_for(col["product_handles"]) | |
| selected: dict[str, list[str]] = {} | |
| for key, _label in cat.FACET_GROUPS: | |
| values = request.query_params.getlist(key) | |
| if values: | |
| selected[key] = values | |
| def matches(p): | |
| return all(any(v in p["facets"].get(key, []) for v in values) | |
| for key, values in selected.items()) | |
| # Facet counts come from the products the *other* selected facets still allow, so a | |
| # group never hides its own alternatives. | |
| facets = [] | |
| for key, label in cat.FACET_GROUPS: | |
| others = {k: v for k, v in selected.items() if k != key} | |
| pool = [p for p in products | |
| if all(any(v in p["facets"].get(k, []) for v in vals) for k, vals in others.items())] | |
| counts: dict[str, int] = {} | |
| for p in pool: | |
| for value in p["facets"].get(key, []): | |
| counts[value] = counts.get(value, 0) + 1 | |
| if not counts: | |
| continue | |
| order = cat.FACET_ORDER.get(key) | |
| names = ([v for v in order if v in counts] + sorted(k for k in counts if k not in order) | |
| if order else sorted(counts)) | |
| facets.append({"name": key, "label": label, | |
| "options": [{"value": v, "count": counts[v], | |
| "checked": v in selected.get(key, [])} for v in names]}) | |
| filtered = [p for p in products if matches(p)] | |
| total = len(filtered) | |
| shown = filtered[: BATCH_SIZE * batch] | |
| query = "".join(f"&{k}={v}" for k, values in selected.items() for v in values) | |
| return render("collection.html", request, collection=col, products=shown, total=total, | |
| facets=facets, has_more=len(shown) < total, | |
| more_url=f"/collections/{handle}?batch={batch + 1}{query}", | |
| lede=C.COLLECTION_LEDE.get(handle), | |
| fabrics=C.COLLECTION_FABRICS.get(handle), | |
| active_filters=sum(len(v) for v in selected.values())) | |
| # ---------------------------------------------------------------- product | |
| def product(request: Request, handle: str, variant: int | None = None, | |
| image: int = 0, added: bool = False): | |
| data = cat.catalog()["products"] | |
| p = data.get(handle) | |
| if not p: | |
| return render("notfound.html", request, status_code=404) | |
| variants = p["variants"] | |
| selected = next((v for v in variants if v["id"] == variant), variants[0]) | |
| colors, seen = [], set() | |
| for v in variants: | |
| if v.get("option1") in seen: | |
| continue | |
| seen.add(v.get("option1")) | |
| meta = cat.swatch_table().get(v.get("option1") or "", {}) | |
| colors.append({"id": v["id"], "title": v.get("option1"), "hex": meta.get("hex"), | |
| "description": meta.get("description"), | |
| "swatch": cat.img_url(v.get("image"), cat.SWATCH)}) | |
| sizes = [] | |
| if len(p["options"]) > 1: | |
| for v in variants: | |
| if v.get("option1") == selected.get("option1") and v.get("option2"): | |
| sizes.append({"id": v["id"], "label": v["option2"]}) | |
| gallery_srcs = p["images"][:4] | |
| gallery = [{"thumb": cat.img_url(s, cat.HERO if i == 0 else cat.GALLERY)} | |
| for i, s in enumerate(gallery_srcs)] | |
| image = max(0, min(image, len(gallery_srcs) - 1)) if gallery_srcs else 0 | |
| hero = None | |
| if selected.get("image") and image == 0: | |
| hero = cat.img_url(selected["image"], cat.HERO) or cat.img_url(selected["image"], cat.GALLERY) | |
| if hero is None and gallery_srcs: | |
| hero = cat.img_url(gallery_srcs[image], cat.HERO if image == 0 else cat.GALLERY) | |
| unit = float(selected["price"]) | |
| view = { | |
| **p, | |
| "lede": _lede(p), | |
| "social_note": f"{40 + (p['id'] % 60)} people have this in their cart right now.", | |
| "details": [ | |
| {"title": "Details", "body": p["body_html"]}, | |
| {"title": "Shipping & Returns", "body": "<p>Free ground shipping within the contiguous U.S. on orders " | |
| "of $100+, before tax. 365-day happiness guarantee.</p>"}, | |
| {"title": "Care", "body": "<p>Machine wash cold, tumble dry low. Skip fabric softener.</p>"}, | |
| ], | |
| } | |
| selected_view = {**selected, "price": unit, | |
| "sale_price": round(unit * (1 - cat.SITEWIDE_DISCOUNT), 2), | |
| "color_description": cat.swatch_table() | |
| .get(selected.get("option1") or "", {}).get("description")} | |
| related = cat.products_for( | |
| [h for h in (cat.collection("all-towels") or {"product_handles": []})["product_handles"] if h != handle][:4] | |
| ) | |
| return render("product.html", request, product=view, variant=selected_view, colors=colors, | |
| sizes=sizes, gallery=gallery, hero_image=hero, image_index=image, | |
| related=related, added=added) | |
| def _lede(p: dict) -> str: | |
| import re | |
| text = re.sub(r"<[^>]+>", " ", p["body_html"]) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text[:150] + ("…" if len(text) > 150 else "") | |
| # ---------------------------------------------------------------- cart routes | |
| def cart_page(request: Request): | |
| return render("cart.html", request) | |
| def cart_js(request: Request): | |
| view = cart_view(session_token(request)) | |
| return JSONResponse({ | |
| "item_count": view["item_count"], | |
| "total_price": int(round(view["subtotal"] * 100)), | |
| "items": [{"variant_id": i["variant_id"], "title": i["title"], "quantity": i["quantity"], | |
| "line_price": int(round(i["unit_sale_price"] * i["quantity"] * 100)), | |
| "options_with_values": [{"name": "Color", "value": i["option1"]}]} | |
| for i in view["lines"]], | |
| }) | |
| def cart_add(request: Request, variant_id: int = Form(...), quantity: int = Form(1)): | |
| idx = cat.variant_index() | |
| if variant_id not in idx: | |
| return RedirectResponse("/cart", status_code=303) | |
| handle, _ = idx[variant_id] | |
| response = RedirectResponse(f"/products/{handle}?variant={variant_id}&added=true", status_code=303) | |
| token = ensure_session(request, response) | |
| with conn() as c: | |
| store.cart_add(c, token, variant_id, max(1, quantity)) | |
| return response | |
| def cart_change(request: Request, variant_id: int = Form(...), quantity: int = Form(...)): | |
| response = RedirectResponse("/cart", status_code=303) | |
| token = ensure_session(request, response) | |
| with conn() as c: | |
| store.cart_set(c, token, variant_id, quantity) | |
| return response | |
| def cart_remove(request: Request, variant_id: int = Form(...)): | |
| response = RedirectResponse("/cart", status_code=303) | |
| token = ensure_session(request, response) | |
| with conn() as c: | |
| store.cart_remove(c, token, variant_id) | |
| return response | |
| # ---------------------------------------------------------------- search | |
| def search(request: Request, q: str = ""): | |
| query = (q or "").strip().lower() | |
| results = [] | |
| if query: | |
| for p in cat.catalog()["products"].values(): | |
| haystack = f"{p['title']} {p['product_type']} {' '.join(p['tags'])}".lower() | |
| if query in haystack: | |
| results.append(p) | |
| results.sort(key=lambda p: (query not in p["title"].lower(), p["title"])) | |
| return render("search.html", request, q=q, products=results[:48], total=len(results)) | |
| # ---------------------------------------------------------------- offer modal | |
| def offer_dismiss(request: Request, choice: str = Form("close")): | |
| referer = request.headers.get("referer") or "/" | |
| response = RedirectResponse(referer, status_code=303) | |
| response.set_cookie("bk_offer", choice, max_age=60 * 60 * 24, samesite="lax", path="/") | |
| return response | |
| def newsletter(request: Request, email: str = Form(...)): | |
| response = RedirectResponse(request.headers.get("referer") or "/", status_code=303) | |
| with conn() as c: | |
| store.newsletter_add(c, email) | |
| store.outbox_add(c, email, "Welcome to the list", | |
| "Thanks for signing up for Brooklinen news and offers.") | |
| return response | |
| # ---------------------------------------------------------------- account | |
| ACCOUNT_NAV = [ | |
| {"label": "Orders", "url": "/account/orders"}, | |
| {"label": "Profile", "url": "/account/profile"}, | |
| {"label": "My Rewards", "url": "/account/rewards"}, | |
| {"label": "Wishlist", "url": "/account/wishlist"}, | |
| ] | |
| def account_root(request: Request): | |
| return RedirectResponse("/account/orders", status_code=303) | |
| def account_view(request: Request, view: str): | |
| if view in {"login", "register", "reset"}: | |
| name = "register.html" if view == "register" else "login.html" | |
| return render(name, request, stage=request.query_params.get("stage"), | |
| email=request.cookies.get("bk_pending_email")) | |
| customer = current_customer(session_token(request)) | |
| if not customer: | |
| return RedirectResponse("/account/login", status_code=303) | |
| if view not in {"orders", "profile", "rewards", "wishlist"}: | |
| return render("notfound.html", request, status_code=404) | |
| orders = [] | |
| if view == "orders": | |
| with conn() as c: | |
| orders = store.orders_for(c, customer["email"]) | |
| heading = {"orders": "Orders", "profile": "Profile", "rewards": "My Rewards", | |
| "wishlist": "Wishlist"}[view] | |
| return render("account.html", request, view=view, heading=heading, orders=orders, | |
| account_nav=ACCOUNT_NAV, rewards={"points": 0}) | |
| def account_login(request: Request, email: str = Form(...), password: str = Form(...)): | |
| _, auth = services() | |
| response = RedirectResponse("/account/orders", status_code=303) | |
| token = ensure_session(request, response) | |
| try: | |
| result = auth.sign_in(token, email=email, password=password) | |
| except Exception: | |
| return render("login.html", request, error="Incorrect email or password.", email=email) | |
| rotated = (result or {}).get("session_token") | |
| if rotated and rotated != token: | |
| with conn() as c: | |
| store.cart_merge(c, token, rotated) | |
| response.set_cookie(SESSION_COOKIE, rotated, httponly=True, samesite="lax", path="/") | |
| return response | |
| def account_logout(request: Request): | |
| _, auth = services() | |
| response = RedirectResponse("/", status_code=303) | |
| try: | |
| auth.sign_out(session_token(request)) | |
| except Exception: | |
| pass | |
| return response | |
| def account_register(request: Request, email: str = Form(...), password: str = Form(...)): | |
| _, auth = services() | |
| response = RedirectResponse("/account/register?stage=verify", status_code=303) | |
| token = ensure_session(request, response) | |
| response.set_cookie("bk_pending_email", email, max_age=1800, samesite="lax", path="/") | |
| try: | |
| auth.start_registration(token, email=email, display_name=email.split("@")[0], | |
| password=password, restart_invalid_flow=True) | |
| except Exception: # deterministic, non-enumerating message | |
| return render("register.html", request, error="We could not start that registration.", | |
| email=email) | |
| mail = auth.local_mail_for_session(token, purpose="registration") or {} | |
| code = mail.get("verification_code") | |
| body = f"Your verification code is {code}." if code else "Your verification code is in the local auth store." | |
| with conn() as c: | |
| store.outbox_add(c, email, "Verify your Brooklinen account", body) | |
| return response | |
| def account_register_verify(request: Request, code: str = Form(...)): | |
| _, auth = services() | |
| token = session_token(request) | |
| email = request.cookies.get("bk_pending_email", "") | |
| try: | |
| auth.verify_registration_code(token, code) | |
| completed = auth.complete_registration(token) | |
| except Exception: | |
| return render("register.html", request, stage="verify", email=email, | |
| error="That code did not match. Check the local outbox and try again.") | |
| response = RedirectResponse("/account/orders", status_code=303) | |
| rotated = completed.get("session_token") | |
| if rotated and rotated != token: | |
| with conn() as c: | |
| store.cart_merge(c, token, rotated) | |
| response.set_cookie(SESSION_COOKIE, rotated, httponly=True, samesite="lax", path="/") | |
| response.delete_cookie("bk_pending_email", path="/") | |
| return response | |
| def checkout(request: Request): | |
| token = session_token(request) | |
| view = cart_view(token) | |
| if not view["lines"]: | |
| return RedirectResponse("/cart", status_code=303) | |
| return render("checkout.html", request, scenarios=PAYMENT_SCENARIOS) | |
| def checkout_submit(request: Request, email: str = Form(...), scenario: str = Form("sandbox-approved")): | |
| token = session_token(request) | |
| view = cart_view(token) | |
| if not view["lines"]: | |
| return RedirectResponse("/cart", status_code=303) | |
| customer = current_customer(token) | |
| account_email = (customer or {}).get("email") or email | |
| with conn() as c: | |
| order = store.create_order( | |
| c, session_token=token, account_email=account_email, subtotal=view["subtotal"], | |
| lines=[{"variant_id": l["variant_id"], "title": l["title"], "quantity": l["quantity"], | |
| "price": l["unit_sale_price"]} for l in view["lines"]], | |
| scenario=scenario, | |
| ) | |
| if order["outcome"] == "approved": | |
| store.cart_clear(c, token) | |
| store.outbox_add(c, account_email, f"Your Brooklinen order {order['number']}", | |
| f"We received your order {order['number']} for " | |
| f"${view['subtotal']:.2f}. This is a local sandbox order.") | |
| return render("order.html", request, order=order, total=view["subtotal"], email=account_email) | |
| def outbox(request: Request): | |
| with conn() as c: | |
| messages = store.outbox_all(c) | |
| return render("outbox.html", request, messages=messages) | |
| # ---------------------------------------------------------------- fallback | |
| async def not_found(request: Request, exc): # noqa: ANN001 | |
| return render("notfound.html", request, status_code=404) | |