From e99e534259ba320886c33bcf71e2061dfbe9818a Mon Sep 17 00:00:00 2001 From: aruship4 Date: Wed, 25 Nov 2026 00:00:57 +0000 Subject: [PATCH] fix: Show the reviewed Pinkfong video under Music and Narrative (plans 007, 013) --- .../src/hyperstim_api/collector/collector.py | 6 +++- backend/src/hyperstim_api/dataset.py | 30 ++++++++++++++++--- backend/src/hyperstim_api/main.py | 2 ++ backend/tests/test_api.py | 1 + backend/tests/test_collected.py | 22 ++++++++++++++ backend/tests/test_collector.py | 14 +++++++++ frontend/e2e/rankings.spec.ts | 19 ++++++++++++ frontend/src/lib/api.ts | 1 + plans/007-rankings.md | 4 ++- plans/013-growing-dataset.md | 7 +++++ 10 files changed, 100 insertions(+), 6 deletions(-) diff --git a/backend/src/hyperstim_api/collector/collector.py b/backend/src/hyperstim_api/collector/collector.py index f75907d..2c11851 100644 --- a/backend/src/hyperstim_api/collector/collector.py +++ b/backend/src/hyperstim_api/collector/collector.py @@ -39,7 +39,7 @@ from hyperstim_api.collector.seed import tier from hyperstim_api.collector.store import IN_STATES, KEPT, Store, Upload from hyperstim_api.collector.youtube import ApiError, DataApi, OutOfUnits, quota_day -from hyperstim_api.dataset import LEFT_OUT_FILE, Dataset +from hyperstim_api.dataset import LEFT_OUT_FILE, REVIEWED_CATEGORIES, Dataset from hyperstim_api.thumbnails import OFFLINE_HINTS log = logging.getLogger(__name__) @@ -1186,6 +1186,7 @@ def export(self) -> None: "video_id", "title", "channel_id", "channel_title", "category", "published_at", "duration_s", *scoring.FEATURES, "added_at", "r", "cutoff", "pick", "rule_version", "measured_by", "ytdlp_version", "ffmpeg_version", "pipeline_commit", "cache_version", + "categories", ) # fmt: skip @@ -1213,6 +1214,9 @@ def export( "channel_id": row["channel_id"], "channel_title": row["channel_title"], "category": row["category"] or "", + "categories": ",".join( + CATEGORY_NAMES[key] for key in REVIEWED_CATEGORIES.get(row["video_id"], ()) + ), "published_at": row["published_at"][:10], "duration_s": row["duration_s"] if row["duration_s"] is not None else "", "added_at": row["added_at"], diff --git a/backend/src/hyperstim_api/dataset.py b/backend/src/hyperstim_api/dataset.py index 8336195..4ad271a 100644 --- a/backend/src/hyperstim_api/dataset.py +++ b/backend/src/hyperstim_api/dataset.py @@ -30,6 +30,11 @@ "gaming": "gaming", } +# Reviewed memberships keyed by video ID, shared by dataset loading and collector export. +REVIEWED_CATEGORIES: dict[str, tuple[str, ...]] = { + "--7WJyWZf8A": ("music", "narrative"), +} + # Per-minute counts (plan 004). A count of 0 is the least stimulating value there is, so it shows as # percentile 0: in the pool thousands of videos tie at 0, and "at or below" puts them in the # middle (e.g. 60). Shown values only; the score uses the pool percentiles (scoring.py). @@ -74,6 +79,13 @@ class Video: published_at: str | None # ISO date; None for a video analyzed live added_at: str | None = None # UTC, ISO 8601, when the collector added it; None: reference set removed_at: str | None = None # when the collector took it out (offline); None: in + categories: tuple[str, ...] | None = None + + @property + def memberships(self) -> tuple[str, ...]: + if self.categories is not None: + return self.categories + return (self.category,) if self.category else () def visible(self, as_of: str | None) -> bool: """In the dataset now (`as_of` None), or at the time `as_of` (UTC, ISO 8601).""" @@ -154,7 +166,7 @@ def ranked_videos( order, None if default - else lambda v: v.visible(as_of) and (category is None or v.category == category), + else lambda v: v.visible(as_of) and (category is None or category in v.memberships), query, offset, limit, @@ -277,7 +289,7 @@ def _channel(members: list[Video]) -> Channel: score=sum(v.score for v in members) / len(members), features=tuple(features), videos=tuple(sorted(members, key=lambda v: (v.published_at or "", v.id))), - categories=frozenset(v.category for v in members if v.category is not None), + categories=frozenset(category for v in members for category in v.memberships), added_at=None if any(v.added_at is None for v in members) else min(v.added_at for v in members if v.added_at is not None), @@ -305,6 +317,14 @@ def _category(path: Path, raw: str) -> str: return key +def _memberships(path: Path, row: dict[str, str]) -> tuple[str, ...] | None: + reviewed = REVIEWED_CATEGORIES.get(row["video_id"].strip()) + if reviewed is not None: + return reviewed + raw = row.get("categories") or "" + return tuple(dict.fromkeys(_category(path, value) for value in raw.split(","))) if raw else None + + def meta_path(dataset_path: Path) -> Path: return dataset_path.with_suffix(".meta.json") @@ -385,7 +405,7 @@ def load_dataset(path: Path, collected_dir: Path | None = None) -> Dataset: composite_pool, ) assert video is not None # every kept row has a feature value - videos.append(video) + videos.append(replace(video, categories=_memberships(path, row))) reference_count = len(videos) if collected_dir is not None: videos = _with_collected(videos, collected_dir, pools, composite_pool, names) @@ -501,7 +521,9 @@ def _with_collected( composite_pool, ) if video is not None: - by_id[video_id] = replace(video, added_at=row["added_at"]) + by_id[video_id] = replace( + video, added_at=row["added_at"], categories=_memberships(path, row) + ) for video_id, removed_at in removed.items(): if video_id in by_id: by_id[video_id] = replace(by_id[video_id], removed_at=removed_at) diff --git a/backend/src/hyperstim_api/main.py b/backend/src/hyperstim_api/main.py index 1ca7d84..3115a60 100644 --- a/backend/src/hyperstim_api/main.py +++ b/backend/src/hyperstim_api/main.py @@ -104,6 +104,7 @@ class FeatureValue(ApiModel): class RankedVideo(VideoSummary): category: str + categories: list[str] rank: int | None # within its category, 1 = first in the list's order; None = no value features: list[FeatureValue] @@ -200,6 +201,7 @@ def ranked_video(r: Ranked[Video]) -> RankedVideo: channel_id=v.channel_id, channel=v.channel, category=v.category or "", + categories=list(v.memberships), rank=r.rank, score=round(v.score, 1), features=feature_values(v.features), diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index a93ce27..a229698 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -59,6 +59,7 @@ def test_videos_most_stimulating_first(client: TestClient) -> None: "channelId": "chan-c", "channel": "Channel chan-c", "category": "music", + "categories": ["music"], "rank": 1, "score": 100.0, } diff --git a/backend/tests/test_collected.py b/backend/tests/test_collected.py index 60cd055..95bfbf1 100644 --- a/backend/tests/test_collected.py +++ b/backend/tests/test_collected.py @@ -95,6 +95,28 @@ def test_counts_categories_and_removals(dataset_path: Path, collected: Path) -> assert grown.channel_count_at(T2) == 4 +def test_reviewed_video_is_in_both_rankings( + tmp_path: Path, make_client: Callable[..., TestClient] +) -> None: + video_id = "--7WJyWZf8A" + path = write_dataset( + tmp_path / "videos.tsv", + [video_row(video_id, "reviewed", 5.0), video_row("legacy", "legacy", 3.0)], + ) + with make_client(path) as client: + for category in ("", "music", "narrative"): + params = {"category": category} + videos = client.get("/api/videos", params=params).json()["items"] + reviewed = [video for video in videos if video["id"] == video_id] + assert len(reviewed) == 1 + assert reviewed[0]["category"] == "music" + assert reviewed[0]["categories"] == ["music", "narrative"] + legacy = [video["categories"] for video in videos if video["id"] == "legacy"] + assert legacy == ([] if category == "narrative" else [["music"]]) + channels = client.get("/api/channels", params=params) + assert [row["id"] for row in channels.json()["items"]].count("reviewed") == 1 + + def test_unknown_category_in_the_collected_files_is_an_error( dataset_path: Path, tmp_path: Path ) -> None: diff --git a/backend/tests/test_collector.py b/backend/tests/test_collector.py index 947593d..f6aad6a 100644 --- a/backend/tests/test_collector.py +++ b/backend/tests/test_collector.py @@ -1932,6 +1932,20 @@ def test_export_is_read_by_the_api( assert "CHANGELOG.tsv" not in [p.name for p in collected_files(folder)] +def test_export_keeps_reviewed_memberships_for_existing_rows(tmp_path: Path) -> None: + store = make_store(tmp_path) + video_id = "--7WJyWZf8A" + added(store, CHANNEL, video_id, NOW) + store.db.execute("UPDATE collected SET category = 'music' WHERE video_id = ?", (video_id,)) + folder = tmp_path / "collected" + for _ in range(2): + export(store, folder, NOW + 60) + with (folder / "2026.tsv").open(newline="", encoding="utf-8") as fh: + row = next(csv.DictReader(fh, delimiter="\t")) + assert row["category"] == "music" + assert row["categories"] == "music,narrative" + + def test_videos_picked_under_rule_v1_keep_their_provenance(tmp_path: Path) -> None: store = make_store(tmp_path) for video_id, pick in (("old00000001", "floor"), ("old00000002", "sample")): diff --git a/frontend/e2e/rankings.spec.ts b/frontend/e2e/rankings.spec.ts index b3ec527..7956640 100644 --- a/frontend/e2e/rankings.spec.ts +++ b/frontend/e2e/rankings.spec.ts @@ -55,6 +55,25 @@ test.describe("rankings", () => { await expect(results(page).getByRole("link", { name: video.title, exact: true })).toBeVisible(); }); + test("the reviewed Pinkfong video appears once in All, Music, and Narrative", async ({ page }) => { + const query = new URLSearchParams({ q: "--7WJyWZf8A" }); + await page.goto(`/rankings/?${query}`); + const video = results(page).getByRole("link", { name: /Police Car vs\. Thief.*S2 EP01.*Pinkfong/ }); + await expect(video).toHaveCount(1); + const chips = page.getByRole("group", { name: "Category" }).filter({ visible: true }); + for (const name of ["Music", "Narrative"]) { + if (await chips.isVisible()) { + await chips.getByRole("button", { name, exact: true }).click(); + } else { + await page.getByRole("combobox", { name: "Category" }).selectOption({ label: name }); + } + await expect(page).toHaveURL(new RegExp(`category%3A${name.toLowerCase()}`)); + await page.reload(); + await expect(page.getByText(new RegExp(`^Showing .* ${name.toLowerCase()} video for this link$`))).toBeVisible(); + await expect(video).toHaveCount(1); + } + }); + test("a click anywhere in a table row opens its video", async ({ page, request }) => { test.skip(isPhone(), "phones get a list of cards"); const [video] = await topVideos(request); diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 65d58ab..3795734 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -79,6 +79,7 @@ export type ChannelDetail = { export type RankedVideo = VideoSummary & { /** Category key (see `CATEGORIES`). */ category: string; + categories?: string[]; /** Place by the ranking's criterion within its category, 1 = first in the order asked for (the * most stimulating, or with `asc` the least stimulating); null = no value. */ rank: number | null; diff --git a/plans/007-rankings.md b/plans/007-rankings.md index d1ee7c1..45c0763 100644 --- a/plans/007-rankings.md +++ b/plans/007-rankings.md @@ -162,9 +162,11 @@ DOM order: H1 + intro → rankings card (search + view switch, category chips, r ## API contract (frontend `api.ts` ↔ backend) +- **Category classification update** (2026-11-24, plan 013) _(human decision)_. The backend filters video and channel rankings by category memberships. A video qualifies for each applicable filter and appears once in All. A channel qualifies once if any of its videos belongs to the selected category. Keep existing filter URLs and accept legacy single-category data during rollout. Verify on the built site against the real backend that the reviewed Pinkfong example appears under Narrative and Music and once in All. + ``` GET /api/videos?sort=score|&order=desc|asc&category=&q=&offset=0&limit=25 - → { items: [{ id, title, channelId, channel, category, // category: key, e.g. "play" + → { items: [{ id, title, channelId, channel, category, categories, // category keys, e.g. "play" rank: number | null, // by `sort` within `category`, 1 = first in `order`; null = no value score: number, // 0–100, 1 decimal features: [{ key, value, percentile }] }], // the 12, as in GET /api/videos/{id} diff --git a/plans/013-growing-dataset.md b/plans/013-growing-dataset.md index 4d90186..fe4a9c3 100644 --- a/plans/013-growing-dataset.md +++ b/plans/013-growing-dataset.md @@ -533,6 +533,13 @@ By hand (the team), in order: - Tests (pytest): a catching-up channel with only put-off uploads doesn't stop a first video (fails without the change); with a ready upload it still goes first; a "removed by the uploader" failure missing from the fake API becomes `ineligible` / `gone` and isn't retried (fails without the change); the same error with the video still listed, or with the API failing, gets the 1-day retry; an "exit 0 but wrote 262 B" failure gets the retry and no API call; a gone video doesn't add to the failures in a row; the start-up pass settles a waiting gone upload and leaves a waiting empty-file one, and a gone-error one listed again, alone; `status` counts a settled one for 30 days. - Stop for review; deployed with the next release. +## Reviewed category memberships (2026-11-24) + +- Show the reviewed Pinkfong upload (`--7WJyWZf8A`) under Music and Narrative because it opens with a story and ends with a featured song. Show it once in All _(human decision)_. +- Keep the primary category for older clients. On dataset load and collector export, apply the reviewed memberships by video ID. Legacy rows use the primary category when no list or override exists. +- Filter video and channel rankings by membership (plan 007). Verify both filters and All on the built site against the real backend, and check that repeated collector exports retain the correction. +- Broader classifier selection remains open pending evaluation on held-out channels. + ## Review decisions Decisions made while building (2026-10-26), each in its spot above where it fits there: