Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion backend/src/hyperstim_api/collector/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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"],
Expand Down
30 changes: 26 additions & 4 deletions backend/src/hyperstim_api/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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)."""
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions backend/src/hyperstim_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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),
Expand Down
1 change: 1 addition & 0 deletions backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
22 changes: 22 additions & 0 deletions backend/tests/test_collected.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 14 additions & 0 deletions backend/tests/test_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")):
Expand Down
19 changes: 19 additions & 0 deletions frontend/e2e/rankings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion plans/007-rankings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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|<feature key>&order=desc|asc&category=<key>&q=<text>&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}
Expand Down
7 changes: 7 additions & 0 deletions plans/013-growing-dataset.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading