"""Polished, functional and entirely local Amazon Home Services WebsiteBench clone.""" from __future__ import annotations import html import json import os from pathlib import Path from typing import Any from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from ahs_app import db from ahs_app.api import Ctx, router from ahs_app.services import SERVICES SITE_ID = "amazon-home-services" ROOT = Path(__file__).resolve().parent app = FastAPI(title="Amazon Home Services local home services", docs_url=None, redoc_url=None, openapi_url=None) app.include_router(router) app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static") def esc(value: Any) -> str: return html.escape(str(value or ""), quote=True) def money(cents: int) -> str: return f"${cents / 100:,.0f}" def current(request: Request) -> Ctx: return Ctx(request) def layout( request: Request, title: str, body: str, *, active: str = "", retail_department: str = "Home & Business Services", ) -> HTMLResponse: c = current(request) signed_in = bool(c.account_id and c.profile) label = c.profile["display_name"] if signed_in else "Log in" account = "/account" if signed_in else "/login" if active in {"home", "help"}: header = f"""
amazonDeliver to local areaUpdate location
ENReturns& Orders0Cart
Delivering to local area - Update location
""" header = header.replace( 'RegistryMusic', 'SellFashionRegistryMusicAmazon HomeToys & GamesAutomotiveBabyHome ImprovementSports & OutdoorsSmart HomeShop By InterestPharmacyEveryday', ) footer = """""" sandbox = "" body_class = f' class="retail-home{" retail-help" if active == "help" else ""}"' else: header = f"""
Saved
""" footer = """""" sandbox = '
WebsiteBench local home-services sandbox — no real provider is contacted and no real payment is made.
' body_class = "" return HTMLResponse(f""" {esc(title)} | Amazon Home Services {sandbox}{header}
{body}
{footer}
""") def provider_card(provider: dict[str, Any]) -> str: services = json.loads(provider["services_json"]) service_label = services[0].replace("-", " ").title() badges = "".join(["✓ Screened" if provider["verified"] else "", "Licensed" if provider["licensed"] else "", "Insured" if provider["insured"] else ""]) return f"""
{''.join(x[0] for x in provider['name'].split()[:2])}

{esc(service_label)}

{esc(provider['name'])}

★ {provider['rating']:.1f} · {provider['review_count']} reviews · {provider['years_in_business']} years

{badges}

{esc(provider['bio'])}

Local arrival options availableView service
""" @app.get("/healthz") def healthz() -> JSONResponse: with SERVICES.auth.connect() as connection: connection.execute("SELECT 1").fetchone() build = os.environ.get("DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "")) return JSONResponse({"ok": True, "site_id": SITE_ID, "version": "amazon-home-services-offline-v1"}, headers={"X-WebsiteBench-Container-Build-ID": build}) @app.get("/") def home(request: Request) -> HTMLResponse: body = """
""" body = body.replace( '
', '

Amazon Home & Business Services

', 1, ) # The source keeps its desktop content canvas when the browser narrows; the # narrow acceptance view is a clipped 1000px page rather than a mobile skin. for mobile_source in ( '', '', '', '', '', ): body = body.replace(mobile_source, "") return layout(request, "Amazon Home Services", body, active="home") @app.get("/search") def search(request: Request) -> HTMLResponse: q = request.query_params query = q.get("q", "").strip().lower() service = q.get("service", "") if service == "grill-assembly" and q.get("view") != "providers": rail = """Home ServicesFitness EquipmentFurnitureGrillsTelevisionsGrills with FREE assemblyCharcoal grillsElectric grillsGas grillsCombo grills & Outdoor smokersShop all eligible grillsShop by brandsBlackstoneMasterbuiltOklahoma Joe'sPit BossTraegerWeberZ GrillsResourcesHelp and Customer ServiceDepartmentGrills and smokers with professional assemblyAppliancesGrocery & Gourmet FoodHome & KitchenIndustrial & ScientificPatio, Lawn & GardenAmazon PrimeEligible for Free Shipping

Get FREE Shipping on eligible orders shipped by Amazon

Customer Reviews★★★★☆ & Up""" categories = ( ("charcoal", "Charcoal grills"), ("electric", "Electric grills"), ("gas", "Gas grills"), ("combo", "Combo grills &
Outdoor smokers"), ("all", "All grills"), ) category_links = "".join( f'{label}' for key, label in categories ) brands = ("blackstone", "masterbuilt", "pitboss", "traeger", "weber", "zgrills") brand_links = "".join( f'{brand.title()}' for brand in brands ) body = f"""
Savor every moment. Leave the assembly to us.
Add an assembly service to your eligible order and we’ll take care of what’s needed to get you started.Customers are responsible for turning off and disconnecting the fuel source before the service appointment.
How it works
Add an eligible item to your cart and proceed to checkoutSelect a date and time for delivery and serviceVerify the information and place your order

Grill Assembly and local service options

Compare local grill service providers
""" return layout(request, "Grills and smokers with FREE delivery and assembly", body, active="help", retail_department="Grills and smokers with professional assembly") if service == "furniture-assembly" and q.get("view") != "providers": store_nav = """""" rail = """Home ServicesFitness EquipmentFurnitureGrillsTelevisionsResourcesHelp and Customer ServiceDepartmentHome & KitchenFurniture with Deluxe delivery and unpackingBedroom setsBox springs and foundationsMattresses and mattress framesLiving room setsTable, sofas, and chairsBenchesAmazon PrimeEligible for Free Shipping

Get FREE Shipping on eligible orders shipped by Amazon

Brands""" categories = ( ("bedroom", "Bedroom sets"), ("foundations", "Box springs
and foundations"), ("mattresses", "Mattresses and
mattress frames"), ("living", "Living room sets"), ("tables", "Table, sofas,
and chairs"), ("benches", "Benches"), ) bubbles = "".join( f'{label}' for key, label in categories ) body = f"""{store_nav}
All the excitement, none of the clutter. Leave the unpacking to us.
Add an unpacking service to your eligible order and we’ll take care of the box and packaging cleanup.
How it works
Add an eligible item to your cart and proceed to checkoutSelect a delivery and service appointmentVerify the information and place your order

Furniture Assembly and local service options

Compare local furniture service providers
""" return layout(request, "Furniture with Deluxe delivery and unpacking", body, active="help", retail_department="Furniture with Deluxe delivery and unpacking") if service == "fitness-equipment": categories = ( ("treadmills", "Treadmills"), ("bikes", "Exercise Bikes"), ("ellipticals", "Ellipticals"), ("rowers", "Rowers"), ("benches", "Benches"), ("machines", "Machines and Towers"), ) category_links = "".join( f'' f'{label}' for slug, label in categories ) rail_links = "".join( f'{label}' for slug, label in categories ) rail = f"""Home ServicesFitness EquipmentFurnitureGrillsTelevisionsEligible for Professional Assembly{rail_links}ResourcesHelp and Customer ServiceDepartmentFitness equipment with professional assembly""" selected = next((item for item in categories if item[0] == q.get("category")), None) if selected: category_slug, category_label = selected body = f"""
‹ All Fitness Equipment
{esc(category_label)}

Eligible for professional assembly

{esc(category_label)}

Explore eligible {esc(category_label).lower()} and return to the complete equipment guide at any time.

Browse all fitness equipment
""" return layout( request, f"{category_label} with professional assembly", body, active="home", retail_department="Fitness equipment with professional assembly", ) body = f"""
Fitness equipment with professional assembly
1. Add an eligible item to your cart and proceed to checkout2. Select a date and time for delivery and service3. Verify the information and place your order
""" return layout( request, "Fitness equipment with professional assembly", body, active="home", retail_department="Fitness equipment with professional assembly", ) zip_code = q.get("zip", "") verified = q.get("verified") == "1" rating = float(q.get("rating", "0") or 0) price = int(q.get("price", "0") or 0) sort = q.get("sort", "recommended") with SERVICES.auth.connect() as connection: services = db.rows(connection.execute("SELECT * FROM an_services ORDER BY name").fetchall()) providers = db.rows(connection.execute("SELECT * FROM an_providers").fetchall()) if query and not service: match = next((item for item in services if query in item["name"].lower() or query in item["summary"].lower()), None) service = match["slug"] if match else "" for item in providers: item["services"] = json.loads(item["services_json"]) item["distance"] = db.distance(zip_code, item["zip"]) if zip_code else 0 if service: providers = [item for item in providers if service in item["services"]] if zip_code: providers = [item for item in providers if item["distance"] <= item["radius_miles"]] if verified: providers = [item for item in providers if item["verified"]] if rating: providers = [item for item in providers if item["rating"] >= rating] if price: providers = [item for item in providers if item["price_level"] <= price] keys = {"rating": lambda x: -x["rating"], "reviews": lambda x: -x["review_count"], "distance": lambda x: x["distance"], "price": lambda x: x["price_level"]} providers.sort(key=keys.get(sort, lambda x: (-x["verified"], -x["rating"], x["response_minutes"]))) options = "".join(f"" for item in services) cards = "".join(provider_card(item) for item in providers) empty = "" if providers else "

No pros match those filters

Try a nearby ZIP, lower rating threshold or clear filters. Your project details are unchanged.

Expand search
" body = f"""

Amazon Home Services local demo

Find an in-home service

{len(providers)} service options found {('near '+esc(zip_code)) if zip_code else ''}

{empty}
{cards}
""" return layout(request, "Find a pro", body, active="services") @app.get("/services/{slug}") def service_detail(slug: str, request: Request) -> HTMLResponse: if slug == "tv-wall-mounting": electronics = """""" rail = """Home ServicesFitness EquipmentFurnitureGrillsTelevisionsService-Eligible TVs by TypeSmart TVsLED TVsOLED TVs8K TVs4K TVsShop AllService-Eligible TVs by Size55 to 65 inches65 to 75 inches75 to 85 inches85 inches and largerShop AllResourcesHelp and Customer ServiceDepartmentElectronicsTelevisions with Delivery and unpackingTelevision & VideoTelevisionsLED & LCD TVsOLED TVsQLED TVsTV PriceUnder $500""" categories = ( ("smart", "Smart TVs"), ("led", "LED TVs"), ("oled", "OLED TVs"), ("4k", "4K TVs"), ("8k", "8K TVs"), ("all", "All TVs"), ) bubbles = "".join( f'{label}' for key, label in categories ) body = f"""{electronics}
Happiness delivered. Packaging, removed. Leave the unpacking to us.
Add an unpacking service to your eligible order and we’ll take care of the box and packaging cleanup.
How it works
Add an eligible item to your cart and proceed to checkoutOn the Checkout page, select a date and time for delivery and service appointmentVerify the information and place your order
Unhappy with your purchase? Return it at any point during your service appointment.

TV Wall Mounting and local service options

Compare local TV service providers
""" return layout(request, "Televisions with Delivery and unpacking", body, active="help", retail_department="Televisions with Delivery and unpacking") with SERVICES.auth.connect() as connection: service = db.row(connection.execute("SELECT * FROM an_services WHERE slug=?", (slug,)).fetchone()) providers = db.rows(connection.execute("SELECT * FROM an_providers").fetchall()) if not service: return layout(request, "Service not found", "

Service not found

Browse services
") providers = [item for item in providers if slug in json.loads(item["services_json"])][:3] body = f"""

{esc(service['category'])}

{esc(service['name'])}

{esc(service['description'])}

Typical local demo range{money(service['price_low'])}–{money(service['price_high'])}{esc(service['unit'])}
Compare {esc(service['name'])} pros
⌂{esc(service['name'])}

What to expect

  1. Tell us about the workAnswer project-specific questions.
  2. Compare local quotesReview price, timing and provider details.
  3. Book in the sandboxNo real provider or payment is involved.

Cost estimator

Save a project range

Featured {esc(service['name'])} pros

{''.join(provider_card(item) for item in providers)}
""" return layout(request, service["name"], body, active="services") @app.get("/pros/{slug}") def provider_detail(slug: str, request: Request) -> HTMLResponse: with SERVICES.auth.connect() as connection: provider = db.row(connection.execute("SELECT * FROM an_providers WHERE slug=?", (slug,)).fetchone()) if not provider: return layout(request, "Provider not found", "

Provider not found

Find another pro
") portfolio = db.rows(connection.execute("SELECT * FROM an_portfolio WHERE provider_id=?", (provider["provider_id"],)).fetchall()) reviews = db.rows(connection.execute("SELECT * FROM an_public_reviews WHERE provider_id=? AND public=1 ORDER BY created_at DESC", (provider["provider_id"],)).fetchall()) services = json.loads(provider["services_json"]) availability = json.loads(provider["availability_json"]) gallery = "".join(f"
Project photo

{esc(item['title'])}

{esc(item['caption'])}

" for item in portfolio) review_html = "".join(f"

{'★'*item['rating']}{'☆'*(5-item['rating'])}

{esc(item['body'])}

{esc(item['author'])} · {esc(item['service_type'])}
" for item in reviews) slots = "".join(f"" for slot in availability) or "" service_opts = "".join(f"" for s in services) body = f"""
{''.join(x[0] for x in provider['name'].split()[:2])}

Screened local demo profile

{esc(provider['name'])}

★ {provider['rating']:.1f} · {provider['review_count']} reviews · {provider['years_in_business']} years in business

✓ Identity screened{'Licensed' if provider['licensed'] else ''}Insured

{esc(provider['bio'])}

{esc(provider['city'])}, {esc(provider['state'])} · {provider['radius_miles']}-mile service area · responds in about {provider['response_minutes']} min

Services & pricing

{''.join(f'{esc(s.replace("-"," ").title())}' for s in services)}

Price level: {'$'*provider['price_level']} · final scope and synthetic quote are shown before any local booking.

Project portfolio

Synthetic examples
{gallery}

Homeowner reviews

Public local-demo reviews only
{review_html or '

No public reviews yet.

'}

Availability

Choose a preferred time

Selection is carried into a local request and can be changed later.

Nothing is sent to {esc(provider['name'])}; this is a synthetic workflow.

""" return layout(request, provider["name"], body, active="services") def auth_page(request: Request, mode: str) -> HTMLResponse: configs = { "register": ("Create your account", "Save providers and manage local projects.", "", "Create account", "Already a member? Log in"), "login": ("Welcome back", "Continue your synthetic home project.", "", "Log in", "Forgot password? · Create account"), "verify": ("Verify locally", "Use the code displayed in the local outbox below.", "
Loading local code…
", "Verify account", "No email is sent outside this site."), "forgot": ("Reset your password", "A reset code will be written to this session's local outbox.", "", "Create local reset code", "Return to login"), "reset": ("Choose a new password", "Enter the code from the local outbox.", "
Loading local code…
", "Update password", "No external delivery is used."), } heading, intro, fields, button, foot = configs[mode] body = f"

Local account

{heading}

{intro}

  • Generated WebsiteBench account store
  • Local verification and recovery
  • No real email or provider contact
{fields}

{foot}

" return layout(request, heading, body) @app.get("/register") def register_page(request: Request): return auth_page(request, "register") @app.get("/login") def login_page(request: Request): return auth_page(request, "login") @app.get("/verify") def verify_page(request: Request): return auth_page(request, "verify") @app.get("/forgot-password") def forgot_page(request: Request): return auth_page(request, "forgot") @app.get("/reset-password") def reset_page(request: Request): return auth_page(request, "reset") @app.get("/account") def account(request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse("/login?next=/account", 303) body = """""" return layout(request, "My projects", body, active="projects") @app.get("/saved") def saved(request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse("/login?next=/saved", 303) return layout(request, "Saved services", "
Loading saved services…
") @app.get("/settings") def settings_page(request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse("/login?next=/settings", 303) body = """

Privacy & consent

Notifications

Security & sessions

Loading local sessions…

No external Amazon session is visible or affected.

""" return layout(request, "Privacy and account settings", body) @app.get("/projects/{project_id}") def project_page(project_id: str, request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse(f"/login?next=/projects/{project_id}", 303) body = f"""
← All appointments

Local in-home service

Choose a package, date and technician

Every action is contained in this synthetic WebsiteBench sandbox.

    Loading appointment…
    """ return layout(request, "Manage service appointment", body, active="projects") @app.get("/provider/dashboard") def provider_dashboard(request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse("/login?next=/provider/dashboard", 303) body = "
    Loading local assignments…
    " return layout(request, "Provider lead management", body, active="projects") @app.get("/help") def help_page(request: Request) -> HTMLResponse: query = request.query_params.get("q", "").strip() topics = ( "All Help Topics", "Shipping and Delivery", "Returns and Refunds", "Payment, Pricing and Promotions", "Security and Privacy", "Ordering", "Managing Your Account", "Gifts, Gift Cards and Registries", "Site Features", "Amazon Global Store", "Amazon Business Help", "Digital Services and Device Support", "Author Publisher & Vendor Guides", "Large Items and Heavy-Bulky Services", "Amazon Health Help Center", "Amazon Fresh and Groceries on Amazon", "Shipping and Delivery with Amazon Logistics", "Amazon Now", "Amazon Physical Stores", ) sections = ( ("about-large-and-bulky-items", "About Large and Bulky Items", ( "Buying Large and Bulky Items", "Shipping Restrictions for Large Items", "Prepare for Your Service Appointment or Large Item Delivery")), ("large-items-delivery", "Large Items Delivery", ( "Special Delivery Options for Large and Bulky Items", "Change Your Scheduled Delivery Date and Time", "Buy Online, Pick Up in Store", "Ship Your Large Item to a Local Store for Assembly or Installation", "More about Large Items Delivery")), ("home-services", "Home Services & Service Provider Licensing", ( "Installation, Assembly, and Haul-Away Services", "Reschedule Your Service Appointment", "More about Home Services & Service Provider Licensing")), ("large-appliances", "Large Appliances", ( "Buying Large Appliances on Amazon.com", "Cooking Ranges (Electric)", "Cooking Ranges (Gas)", "Dishwashers", "Dryers (Electric)", "Dryers (Gas)")), ) narrow_topic_lines = { "Shipping and Delivery": ("Shipping and", "Delivery"), "Returns and Refunds": ("Returns and", "Refunds"), "Payment, Pricing and Promotions": ("Payment,", "Pricing and", "Promotions"), "Security and Privacy": ("Security and", "Privacy"), "Managing Your Account": ("Managing", "Your", "Account"), "Gifts, Gift Cards and Registries": ("Gifts, Gift", "Cards and", "Registries"), "Amazon Global Store": ("Amazon", "Global", "Store"), "Amazon Business Help": ("Amazon", "Business", "Help"), "Digital Services and Device Support": ("Digital", "Services", "and Device", "Support"), "Author Publisher & Vendor Guides": ("Author", "Publisher &", "Vendor", "Guides"), } def topic_label(text: str) -> str: lines = narrow_topic_lines.get(text) return "".join(f'{esc(line)}' for line in lines) if lines else esc(text) rail = "".join( f'{topic_label(text)}' if text == "Large Items and Heavy-Bulky Services" else f'{topic_label(text)}' for text in topics ) def help_link(slug: str, link: str) -> str: marker = '' if link.startswith("More about") else "" return f'{marker}{esc(link)}' rows = "".join( f'

    {esc(label)}

    ' + "".join(help_link(slug, link) for link in links) + "
    " for slug, label, links in sections ) result = f'

    Showing local help results for {esc(query)}.

    ' if query else "" body = f'''

    Help & Customer Service

    Find more solutions

    {result}

    Large Items and Heavy-Bulky Services

    {rows}

    Quick solutions

    Your OrdersYour AccountReturns & Refunds
    ''' return layout(request, "Help & Customer Service", body, active="help", retail_department="All") @app.get("/waitlist") def waitlist_page(request: Request) -> HTMLResponse: c = current(request) if not c.account_id: return RedirectResponse("/login?next=/waitlist", 303) body = """

    No availability?

    Join a local waitlist

    Save a preferred in-home date. This creates no external notification or booking.

    """ return layout(request, "Local service waitlist", body) @app.get("/safety") def safety(request: Request) -> HTMLResponse: licenses = ( "Alaska – 167125", "Arizona – ROC362888", "California – 50855", "Delaware – 2020704499", "Florida – CGC1532924", "Georgia – 4355909", "Idaho – RCE-55448", "Illinois – CNTR-01740, TGC142146", "Kansas – 2021-3239", "Louisiana – RL888077", "Maryland – 145798", "Massachusetts – 198367", "Michigan – 242500536", "Nebraska – B01375", "Nevada – 93943", "New Jersey – 13VH11117900", "New Mexico – 424933", "New York – 2131357-DCWP, H-21307", "North Carolina – L87237, L84434", "Oregon – 231048", "Rhode Island – GC-44270", "South Carolina – 50887, CCM1220", "Texas – 740390", "Utah – 12177505-5501", "Virginia – 2705179423", "Washington – AMAZOSL808DQ", "West Virginia – WV060649", "Wyoming – BUCT-31210, BUCT-31188, CL-25-112", ) items = "".join(f"
  1. {esc(item)}
  2. " for item in licenses) rail = """Home ServicesFitness EquipmentFurnitureGrillsTelevisionsResourcesHelp and Customer ServiceLicenses""" body = f"""
    Maximize the results. Minimize the effort. Let us do the work. Amazon Home Services.

    Licenses:

      {items}
    Want to learn more about our service providers?Go to Service providers licensing
    """ return layout(request, "Licenses", body, active="home", retail_department="Licensed services") @app.exception_handler(404) async def not_found(request: Request, _exc): return layout(request, "Page not found", "

    We couldn't find that page

    Browse local services or return to your projects.

    Go home
    ")