Download tasks/eatthismuch/environment/reference/clone/backend/g_api.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/eatthismuch/environment/reference/clone/backend/g_api.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/eatthismuch/environment/reference/clone/backend/g_api.py
-
curl -L -o g_api.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/eatthismuch/environment/reference/clone/backend/g_api.py
10.7 kB
| """``/g/*`` —— /app 那个 SPA 真正吃的那一层接口。 | |
| 为什么单独一层:``/api/v1/*`` 是 Django-Tastypie 的资源层(对象按 id 取), | |
| ``/g/*`` 是站点自己写的动作层(搜索、生成、清单)。bundle 里两层都用, | |
| 少哪一层规划器都跑不起来——``/food/browse`` 就是死在缺 ``/g/food-search/`` | |
| 上:那次 fetch 永远不 settle,页面到不了 networkidle,而验收用的正是 | |
| ``page.goto(wait_until="networkidle")``。 | |
| 形状全部实测,来源三处,都留了证物: | |
| 1. **匿名 GET**(recon/g-api/probe.json)——``/g/check-status/`` 答裸对象 | |
| ``{"status":"ok"}``;``/g/food-search/`` 答统一信封;账号面的端点答 | |
| **401 且响应体是一个裸 JSON 字符串** ``"not logged in"``,不是空体、 | |
| 也不是带 errors 的信封。 | |
| 2. **带会话 GET**(recon/g-api/auth/probe.json)——``/g/meal-categories/`` | |
| 82 条全局分类(核过,不含账号标识)、``/g/exclusions-stats/`` 的 ``data`` | |
| 是个裸数字 100、``/g/customfoods/`` 等一律 ``data: []``。 | |
| 3. **bundle 自己的调用点**(source-assets/…/nodes/52.D_p2WSUh.js、chunks/Cer-cfCG.js) | |
| ——参数名是 ``exclude_user_foods / filters / limit / order_by / page / q``, | |
| ``order_by`` 要写成 ``serving_<营养素>``;返回值它只读 | |
| ``data.object_resource_uris`` 再逐个去取 ``/api/v1/food/<id>/``。 | |
| ``/g/generate/day/`` 它读的是 ``data.results[0].meals[].foods[].food``。 | |
| 未路由的 ``/g/…`` 源站答的是 **404 + text/plain** ``404 page not found`` | |
| (实测 ``/g/generate/day/`` 的 GET)。克隆照抄——不能让它掉进 catch_all 拿一份 | |
| 235KB 的 HTML 404,那玩意儿在 fetch 里既慢又会把 JSON 解析打挂。 | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from typing import Any | |
| from . import app_api | |
| from . import content_store as store | |
| # 未登录时的响应体:裸 JSON 字符串,不是信封。实测值。 | |
| NOT_LOGGED_IN = "not logged in" | |
| # bundle 把 order_by 写成 serving_<营养素>;索引里的分面 id 是不带前缀的 | |
| _SERVING = "serving_" | |
| # filters 取值 → 克隆索引里的 kind。源站分四类,克隆抓到的 2129 份里 | |
| # 2128 份是 recipe,所以别的类目在离线档里必然是空的(写进台账)。 | |
| FILTER_KINDS = { | |
| "recipes": "recipe", | |
| "basic_foods": "food", | |
| "branded_foods": "branded", | |
| "restaurant_foods": "restaurant", | |
| } | |
| def envelope(data: Any, *, meta: dict | None = None, success: bool = True, | |
| errors: Any = None) -> dict: | |
| """``/g/*`` 的信封和 ``/api/v1/*`` 同形,但 ``errors`` 实测是 ``{}`` 不是 null。""" | |
| return { | |
| "data": data, | |
| "warnings": {}, | |
| "meta": meta if meta is not None else {}, | |
| "success": success, | |
| "errors": errors if errors is not None else {}, | |
| } | |
| def food_object(food_id: str, *, meal_id: int = 0, user_id: int = 0, | |
| amount: float = 1, scaled_amount: float = 1.0) -> dict: | |
| """一条「餐里的食物」。字段名来自 ``/g/search-with-suggestions/`` 的实测行。""" | |
| return { | |
| "user_id": user_id, | |
| "meal_id": meal_id, | |
| "food_id": int(food_id), | |
| "amount": amount, | |
| "units": 1, | |
| "locked": False, | |
| "is_leftovers": False, | |
| "has_leftovers": False, | |
| "user_chosen": False, | |
| "eaten": False, | |
| "removed_from_pantry": False, | |
| "scaled_amount": scaled_amount, | |
| "date_added": None, | |
| "makes_leftovers_for": [], | |
| "leftovers_from": None, | |
| "uses_leftovers_from": None, | |
| "food": f"/api/v1/food/{food_id}/", | |
| "missing_resource_uris": [], | |
| "total_ingredients": 1, | |
| } | |
| # ---------------------------------------------------------------- 搜索 | |
| def _order_ids(order_by: str | None) -> tuple[list[str], str]: | |
| """把 bundle 的 ``order_by`` 翻回索引里的分面 id,并取出该分面的顺序。""" | |
| if not order_by: | |
| return store.browse_order("default"), "default" | |
| raw = order_by.strip() | |
| sign = "" | |
| if raw.startswith("-"): | |
| sign, raw = "-", raw[1:] | |
| if raw.startswith(_SERVING): | |
| raw = raw[len(_SERVING):] | |
| facet = f"{sign}{raw}" | |
| ids = store.browse_order(facet) | |
| if ids: | |
| return ids, facet | |
| return store.browse_order("default"), "default" | |
| def _matches(summary: dict, needle: str, kinds: set[str]) -> bool: | |
| if kinds and summary.get("kind") not in kinds: | |
| return False | |
| if not needle: | |
| return True | |
| name = (summary.get("name") or "").lower() | |
| return needle in name | |
| def food_search(params) -> dict: | |
| """``GET /g/food-search/``。 | |
| ``q`` 是真的会过滤的(实测:``q=banana`` 与 ``q=chicken soup`` 返回两组 | |
| 完全不同的 id)。早先用 ``search=`` 试过一轮没反应——那是参数名不对, | |
| 不是端点不认;bundle 里写的就是 ``q``。 | |
| """ | |
| try: | |
| limit = int(params.get("limit") or 20) | |
| except ValueError: | |
| limit = 20 | |
| limit = max(1, min(limit, 50)) | |
| try: | |
| page = int(params.get("page") or 1) | |
| except ValueError: | |
| page = 1 | |
| page = max(1, page) | |
| needle = (params.get("q") or "").strip().lower() | |
| kinds: set[str] = set() | |
| raw_filters = params.get("filters") | |
| if raw_filters: | |
| try: | |
| wanted = json.loads(raw_filters) | |
| except (ValueError, TypeError): | |
| wanted = [] | |
| if isinstance(wanted, str): | |
| wanted = [wanted] | |
| for item in wanted or []: | |
| kind = FILTER_KINDS.get(str(item)) | |
| if kind: | |
| kinds.add(kind) | |
| ids, _facet = _order_ids(params.get("order_by")) | |
| foods = store.index()["foods"] | |
| if needle or kinds: | |
| # 过滤时要在**全量**上过,不能只在分面那前两页上过, | |
| # 否则一搜就只剩两三条。分面顺序在前,其余按默认序补。 | |
| seen = set(ids) | |
| pool = ids + [f for f in store.browse_order("default") if f not in seen] | |
| rows = [f for f in pool if f in foods and _matches(foods[f], needle, kinds)] | |
| else: | |
| rows = [f for f in ids if f in foods] | |
| total = len(rows) | |
| offset = (page - 1) * limit | |
| window = rows[offset:offset + limit] | |
| return envelope( | |
| { | |
| "objects": [], | |
| "object_resource_uris": [f"/api/v1/food/{f}/" for f in window], | |
| "pantry_info_map": None, | |
| }, | |
| meta={ | |
| "limit": limit, | |
| "offset": offset, | |
| "total_count": total, | |
| "total_pages": max(1, math.ceil(total / limit)) if total else 0, | |
| }, | |
| ) | |
| def search_with_suggestions(params) -> dict: | |
| """``GET /g/search-with-suggestions/``。实测:``data.objects`` 是一个分组数组, | |
| 每组 ``{title, total_count, results:[食物对象]}``。""" | |
| body = food_search(params) | |
| uris = body["data"]["object_resource_uris"] | |
| meta = body["meta"] | |
| results = [food_object(u.strip("/").rsplit("/", 1)[-1]) for u in uris] | |
| return envelope( | |
| { | |
| "objects": [ | |
| { | |
| "title": "results", | |
| "total_count": meta["total_count"], | |
| "results": results, | |
| } | |
| ] | |
| }, | |
| meta={"limit": meta["limit"], "offset": meta["offset"], | |
| "total_count": 1 if results else 0, "total_pages": 1 if results else 0}, | |
| ) | |
| # ---------------------------------------------------------------- 账号面 | |
| def meal_categories() -> Any: | |
| """82 条全局分类,取自实测响应体(recon/g-api/auth/meal-categories.body)。 | |
| 核过:不含账号邮箱、user_id、mealtype id,任何 7 位以上数字都没有。""" | |
| path = store.CONTENT / "g" / "meal-categories.json" | |
| if not path.exists(): | |
| return [] | |
| body = json.loads(path.read_text(encoding="utf-8")) | |
| return body.get("data", body) if isinstance(body, dict) else body | |
| def owned_groceries_suggestions() -> list[str]: | |
| ids = store.browse_order("default")[:10] | |
| return [f"/api/v1/food/{f}/" for f in ids] | |
| def leftovers_preview(state: dict) -> list[dict]: | |
| """七天 × 每天四餐的剩菜预览。餐型 id 用 demo 账号那套合成 id。""" | |
| names = ("Monday", "Tuesday", "Wednesday", "Thursday", | |
| "Friday", "Saturday", "Sunday") | |
| rows = [] | |
| for index, name in enumerate(names): | |
| meals = [] | |
| for meal_id in app_api.mealtype_ids(): | |
| meals.append({ | |
| "meal_type": app_api.uri("mealtype", meal_id), | |
| "meal_type_id": meal_id, | |
| "is_parent_leftovers": False, | |
| "is_child_leftovers": False, | |
| "leftovers_chain": None, | |
| "leftovers_chain_instance_index": None, | |
| "leftovers_chain_instance_uuid": None, | |
| "is_end_of_leftovers_chain_instance": False, | |
| }) | |
| rows.append({"weekday_int": index, "weekday": name, "meals": meals}) | |
| return rows | |
| # ---------------------------------------------------------------- 生成 | |
| def _plan_ids(seed: int, count: int) -> list[str]: | |
| """从离线档里挑食物。确定性:同一个 seed 永远挑出同一组, | |
| 这样截图和测试都可复现。""" | |
| pool = [f for f in store.browse_order("default") if f in store.index()["foods"]] | |
| if not pool: | |
| return [] | |
| step = max(1, len(pool) // max(count, 1)) | |
| return [pool[(seed * 7 + i * step) % len(pool)] for i in range(count)] | |
| def generate_day(state: dict, date: str, day_index: int) -> dict: | |
| """``POST /g/generate/day/``。 | |
| bundle 只读 ``data.results[0].meals[].foods[].food``(chunks/Cer-cfCG.js)—— | |
| 所以返回的是**一份 diet 对象**,和 ``/api/v1/calendar/`` 里那个 ``diet`` | |
| 同形,区别只在 ``foods`` 这次不是空的。 | |
| 值得说清楚:``foods`` 的元素形状不是编的,是 | |
| ``/g/search-with-suggestions/`` 实测行的 19 个字段原样。源站上跑一次真实 | |
| 生成去看它自己的填充结果,那一步被沙箱拦下了,所以这里填的是**离线档里 | |
| 的食物 × 实测的字段形状**——形状可信,选品是克隆自己的。写进台账。 | |
| """ | |
| diet = app_api._diet(day_index, state) | |
| for position, meal in enumerate(diet.get("meals", [])): | |
| picks = _plan_ids(day_index * 4 + position, 2) | |
| meal["foods"] = [ | |
| food_object(fid, meal_id=meal["id"], user_id=app_api.DEMO_USER_ID, | |
| scaled_amount=1.0) | |
| for fid in picks | |
| ] | |
| diet["date"] = date | |
| return diet | |