AgPerry's picture
Add files using upload-large-folder tool
fb2916f verified
Raw History Blame Contribute Delete
13.3 kB
"""Local route families derived from the Playwright evidence.
``data/families.json`` is written by ``tools/build_local_data.py`` from the
captured page instances. This module turns it into the view models the family
templates render, and it owns two rules that keep the clone honest:
* every list this module hands a template is either a real local route or an
explicit boundary row — never a ``#`` link and never a remote origin;
* every source-side figure (question counts, chapter counts, contest dates) is
labelled as a *source* figure, because the local seeded body below it is a
deterministic sample of this clone's own 1,000-problem catalogue.
Company↔problem and tag↔problem mappings were not capturable: LeetCode renders
company tags behind Premium, and the tag list pages render their rows from an
authenticated API. Each collection page therefore seeds a deterministic local
sample from this clone's catalogue and says so on the page.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Iterable
from . import content
DATA_DIR = Path(__file__).resolve().parent / "data"
FAMILIES: dict[str, Any] = json.loads(
(DATA_DIR / "families.json").read_text(encoding="utf-8")
)
COMPANY_ROWS: tuple[dict[str, Any], ...] = tuple(FAMILIES["company"]["rows"])
COMPANY_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in COMPANY_ROWS}
COMPANY_POPULATION: int = int(FAMILIES["company"]["population"])
COMPANY_SAMPLE: int = int(FAMILIES["company"]["sample"])
TAG_ROWS: tuple[dict[str, Any], ...] = tuple(FAMILIES["tag"]["rows"])
TAG_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in TAG_ROWS}
EXPLORE_SECTIONS: tuple[dict[str, Any], ...] = tuple(FAMILIES["explore"]["sections"])
EXPLORE_SECTION_BY_PATH: dict[str, dict[str, Any]] = {
row["path"]: row for row in EXPLORE_SECTIONS
}
EXPLORE_CARDS: tuple[dict[str, Any], ...] = tuple(FAMILIES["explore"]["cards"])
EXPLORE_CARD_BY_PATH: dict[str, dict[str, Any]] = {
row["path"]: row for row in EXPLORE_CARDS
}
STUDYPLANS: tuple[dict[str, Any], ...] = tuple(FAMILIES["studyplan"]["plans"])
STUDYPLAN_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in STUDYPLANS}
STUDYPLAN_DETAIL: dict[str, dict[str, Any]] = {
row["slug"]: row for row in FAMILIES["studyplan"]["details"]
}
CONTEST: dict[str, Any] = FAMILIES["contest"]
CONTEST_BY_SLUG: dict[str, dict[str, Any]] = {
row["slug"]: row for row in (*CONTEST["upcoming"], *CONTEST["past"])
}
DISCUSS: dict[str, Any] = FAMILIES["discuss"]
DISCUSS_BY_ID: dict[str, dict[str, Any]] = {row["id"]: row for row in DISCUSS["posts"]}
PROFILES: tuple[dict[str, Any], ...] = tuple(FAMILIES["profile"])
PROFILE_BY_HANDLE: dict[str, dict[str, Any]] = {
row["handle"]: row for row in PROFILES
}
PREMIUM: dict[str, Any] = FAMILIES["premium"]
STORE: dict[str, Any] = FAMILIES["store"]
INTERVIEW: dict[str, Any] = FAMILIES["interview"]
ASSESSMENT: dict[str, Any] = FAMILIES["assessment"]
BUSINESS: dict[str, Any] = FAMILIES["business"]
SUPPORT: dict[str, Any] = FAMILIES["support"]
LEGAL: dict[str, Any] = FAMILIES["legal"]
STATIC_PAGES: dict[str, dict[str, Any]] = {
row["path"]: row for row in FAMILIES["static_pages"]
}
PROBLEMSET_CATEGORIES: tuple[dict[str, Any], ...] = tuple(
FAMILIES["problemset_categories"]
)
#: Shown wherever a page seeds local rows in place of a source collection the
#: anonymous capture could not enumerate.
SEEDED_NOTE = (
"The membership list below is a deterministic local sample of this clone's "
"own 1,000-problem catalogue. The source renders this collection from an "
"authenticated or Premium-gated API, so no membership was captured and none "
"is invented here."
)
PREMIUM_BOUNDARY = (
"This clone implements no payment. LeetCode Premium is presented from the "
"captured marketing copy only; every subscribe control answers locally and "
"no card, price or account is ever charged."
)
# ---------------------------------------------------------------------------
# deterministic local sampling
# ---------------------------------------------------------------------------
def _rotate(seed: str) -> int:
"""A stable non-cryptographic offset derived from a slug.
``hash()`` is salted per process, so a hand-rolled sum keeps the seeded
sample identical across restarts, which the site tests depend on.
"""
total = 0
for position, character in enumerate(seed):
total = (total * 131 + ord(character) + position) % 1_000_003
return total
def sample_questions(seed: str, size: int) -> list[content.Question]:
"""A stable, evenly spread slice of the catalogue for one collection."""
catalogue = content.LISTING_ORDER
if not catalogue or size <= 0:
return []
size = min(size, len(catalogue))
offset = _rotate(seed) % len(catalogue)
stride = max(1, len(catalogue) // size)
picked: list[content.Question] = []
seen: set[str] = set()
index = offset
while len(picked) < size:
item = catalogue[index % len(catalogue)]
if item.slug not in seen:
seen.add(item.slug)
picked.append(item)
index += stride
if len(seen) >= len(catalogue):
break
picked.sort(key=lambda item: item.number)
return picked
def question_rows(items: Iterable[content.Question]) -> list[dict[str, Any]]:
return [
{
"slug": item.slug,
"number": item.number,
"title": item.title,
"difficulty": item.difficulty,
"difficulty_label": content.difficulty_label(item.difficulty),
"acceptance": item.acceptance,
"href": f"/problems/{item.slug}/description/",
"premium_locked": item.premium_locked,
}
for item in items
]
# ---------------------------------------------------------------------------
# collections (company + tag/problem-list)
# ---------------------------------------------------------------------------
def company(slug: str) -> dict[str, Any] | None:
row = COMPANY_BY_SLUG.get(slug)
if row is None:
return None
size = min(25, max(5, int(row.get("source_question_count") or 0) or 5))
return {
"kind": "company",
"slug": slug,
"name": row.get("name") or slug,
"source_question_count": row.get("source_question_count"),
"source_saved_count": row.get("source_saved_count"),
"source_updated_label": row.get("source_updated_label"),
"rows": question_rows(sample_questions(f"company:{slug}", size)),
"seeded_note": SEEDED_NOTE,
"discuss_href": "/discuss/",
"premium_href": "/subscribe/",
}
def tag(slug: str) -> dict[str, Any] | None:
row = TAG_BY_SLUG.get(slug)
if row is None:
return None
label = row.get("label") or slug
local = [item for item in content.LISTING_ORDER if label in item.topics]
return {
"kind": "tag",
"slug": slug,
"name": label,
"source_question_count": row.get("source_question_count"),
"source_saved_count": row.get("source_saved_count"),
"source_updated_label": row.get("source_updated_label"),
"list_available": bool(row.get("list_available", True)),
"label_source": row.get("label_source", "tag-page"),
"rows": question_rows(local),
"filter_href": f"/problemset/?topic={label.replace(' ', '+')}",
"seeded_note": (
"The rows below are this clone's own 1,000-problem catalogue "
"filtered by the captured per-problem topic chips. The source "
"figure beside the heading counts the full 4,029-problem bank."
),
"discuss_href": "/discuss/",
"premium_href": "/subscribe/",
}
# ---------------------------------------------------------------------------
# study plans
# ---------------------------------------------------------------------------
def studyplan(slug: str) -> dict[str, Any] | None:
row = STUDYPLAN_BY_SLUG.get(slug)
if row is None:
return None
detail = STUDYPLAN_DETAIL.get(slug)
groups: list[dict[str, Any]] = []
if detail is not None:
for group in detail["groups"]:
problems = []
for entry in group["problems"]:
local = content.question(entry["slug"])
problems.append(
{
"slug": entry["slug"],
"title": entry.get("title") or entry["slug"],
"difficulty": entry.get("difficulty") or "",
"href": (
f"/problems/{entry['slug']}/description/"
if local is not None
else None
),
}
)
groups.append({"name": group["name"], "problems": problems})
return {
"slug": slug,
"label": row.get("label") or slug,
"premium": bool(row.get("premium")),
"detail": detail is not None,
"title": (detail or {}).get("title") or row.get("label") or slug,
"groups": groups,
"problem_total": sum(len(group["problems"]) for group in groups),
"local_total": sum(
1
for group in groups
for problem in group["problems"]
if problem["href"] is not None
),
}
# ---------------------------------------------------------------------------
# explore
# ---------------------------------------------------------------------------
def explore_section(path: str) -> dict[str, Any] | None:
row = EXPLORE_SECTION_BY_PATH.get(path)
if row is None:
return None
cards = []
for card in row["cards"]:
target = card.get("path")
cards.append(
{
**card,
"href": target if target in EXPLORE_CARD_BY_PATH else None,
"locked": card.get("state") == "Locked" or card.get("premium"),
}
)
return {"path": path, "title": row["title"], "cards": cards}
def explore_card(path: str) -> dict[str, Any] | None:
row = EXPLORE_CARD_BY_PATH.get(path)
if row is None:
return None
card = row.get("card") or {}
seed = path.strip("/").rsplit("/", 1)[-1]
return {
"path": path,
"caption": card.get("caption") or "Explore card",
"chapters": card.get("chapters"),
"items": card.get("items"),
"locked": card.get("state") == "Locked" or card.get("premium"),
"rows": question_rows(sample_questions(f"explore:{seed}", 8)),
"captured_text": row.get("captured_text", ""),
}
# ---------------------------------------------------------------------------
# contest
# ---------------------------------------------------------------------------
def contest(slug: str) -> dict[str, Any] | None:
row = CONTEST_BY_SLUG.get(slug)
if row is None:
return None
upcoming = any(entry["slug"] == slug for entry in CONTEST["upcoming"])
return {
"slug": slug,
"name": row.get("name") or slug,
"starts": row.get("starts") or "",
"upcoming": upcoming,
"rows": question_rows(sample_questions(f"contest:{slug}", 4)),
}
# ---------------------------------------------------------------------------
# discuss
# ---------------------------------------------------------------------------
def discuss_post(identifier: str) -> dict[str, Any] | None:
row = DISCUSS_BY_ID.get(identifier)
if row is None:
return None
featured = DISCUSS.get("featured_post") or {}
body = featured.get("captured_text", "") if featured.get("path") == row["path"] else ""
return {
"id": identifier,
"path": row["path"],
"title": row.get("label") or featured.get("title") or "Discuss post",
"captured_body": body,
"has_body": bool(body),
}
# ---------------------------------------------------------------------------
# public profiles
# ---------------------------------------------------------------------------
def profile(handle: str) -> dict[str, Any]:
row = PROFILE_BY_HANDLE.get(handle)
return {
"handle": handle,
"captured": row is not None,
"title": (row or {}).get("title") or handle,
"captured_text": (row or {}).get("captured_text", ""),
}
__all__ = [
"ASSESSMENT",
"BUSINESS",
"COMPANY_BY_SLUG",
"COMPANY_POPULATION",
"COMPANY_ROWS",
"COMPANY_SAMPLE",
"CONTEST",
"CONTEST_BY_SLUG",
"DISCUSS",
"DISCUSS_BY_ID",
"EXPLORE_CARDS",
"EXPLORE_CARD_BY_PATH",
"EXPLORE_SECTIONS",
"EXPLORE_SECTION_BY_PATH",
"INTERVIEW",
"LEGAL",
"PREMIUM",
"PREMIUM_BOUNDARY",
"PROBLEMSET_CATEGORIES",
"PROFILES",
"SEEDED_NOTE",
"STATIC_PAGES",
"STORE",
"STUDYPLANS",
"STUDYPLAN_BY_SLUG",
"STUDYPLAN_DETAIL",
"SUPPORT",
"TAG_BY_SLUG",
"TAG_ROWS",
"company",
"contest",
"discuss_post",
"explore_card",
"explore_section",
"profile",
"question_rows",
"sample_questions",
"studyplan",
"tag",
]