mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
feat(backend): add a library-aware recommendations engine
Recommendations came straight from IGDB's `similar_games`, which mostly names titles the server does not hold and is absent entirely for anything IGDB never matched. `rom_similarity` holds a precomputed item-item graph blending four signals: IDF-weighted metadata overlap, the IGDB prior resolved against the library, collection co-membership and co-play. Scores are library-relative, so a shelf full of arcade games learns on its own that "Action" says nothing while "Metroidvania" says a great deal, with no tuning. Each edge stores the facets that produced it, so the UI can explain a recommendation rather than showing an unattributed row of covers. Candidate generation runs off an inverted index with a document-frequency cap, avoiding the all-pairs comparison. The graph is rebuilt wholesale by a scheduled task because the IDF weighting shifts as the library grows, and writes commit in batches so a task that dies leaves stale edges rather than an empty table. The personalised feed is ranked on demand from those edges plus live play history, since a nightly feed would ignore the game played an hour ago. Ratings below the scale midpoint act as negative seeds, results are diversified per franchise and platform, and owned-but-unplayed games are boosted. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,6 +12,7 @@ from models.collection import VirtualCollection
|
||||
from models.firmware import Firmware # noqa
|
||||
from models.music import MusicFavoriteTrack, MusicPlaylist, MusicPlaylistTrack # noqa
|
||||
from models.platform import Platform # noqa
|
||||
from models.recommendation import RomSimilarity # noqa
|
||||
from models.rom import Rom, RomFacets, RomMetadata, SiblingRom # noqa
|
||||
from models.user import User # noqa
|
||||
|
||||
|
||||
69
backend/alembic/versions/0108_rom_similarity.py
Normal file
69
backend/alembic/versions/0108_rom_similarity.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Precomputed item-item similarity edges for the recommendations engine
|
||||
|
||||
Recommendations previously came straight from IGDB's ``similar_games``, which
|
||||
knows nothing about which of those games are actually in the library and is
|
||||
absent entirely for anything IGDB never matched. ``rom_similarity`` holds a
|
||||
library-relative similarity graph built from the normalised metadata, the IGDB
|
||||
prior, collection co-membership and co-play, so both the "Similar games"
|
||||
section and the personalised feed read a single indexed table.
|
||||
|
||||
The table is rewritten wholesale by the recommendations task rather than
|
||||
maintained incrementally, because the IDF weighting that makes the scores
|
||||
library-relative shifts as the library grows. Rows are bounded at roughly
|
||||
``rom_count * MAX_NEIGHBOURS``.
|
||||
|
||||
Revision ID: 0108_rom_similarity
|
||||
Revises: 0107_roms_dedup_cover_index
|
||||
Create Date: 2026-08-07 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op # type: ignore[attr-defined]
|
||||
|
||||
from utils.database import CustomJSON
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0108_rom_similarity"
|
||||
down_revision = "0107_roms_dedup_cover_index"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"rom_similarity",
|
||||
sa.Column("rom_id", sa.Integer(), nullable=False),
|
||||
sa.Column("related_rom_id", sa.Integer(), nullable=False),
|
||||
sa.Column("score", sa.Float(), nullable=False),
|
||||
sa.Column("reasons", CustomJSON(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
server_default=sa.func.now(),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.TIMESTAMP(timezone=True),
|
||||
server_default=sa.func.now(),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["related_rom_id"], ["roms.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("rom_id", "related_rom_id"),
|
||||
# Reads are always "top N neighbours of this ROM", so the score rides
|
||||
# along in the index to keep the ordering off a filesort.
|
||||
sa.Index("idx_rom_similarity_rom_score", "rom_id", "score"),
|
||||
# Backs the cascade: without it Postgres seq-scans this table on every
|
||||
# ROM delete. Declared inline rather than via a following create_index
|
||||
# so InnoDB adopts it for the foreign key instead of silently adding a
|
||||
# second index on the same column.
|
||||
sa.Index("idx_rom_similarity_related_rom_id", "related_rom_id"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Dropping the table takes its indexes and constraints with it. Dropping
|
||||
# the indexes first fails on MariaDB, which needs them for the foreign keys.
|
||||
op.drop_table("rom_similarity")
|
||||
@@ -259,6 +259,15 @@ SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON: Final[str] = _get_env(
|
||||
"SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON",
|
||||
"0 4 * * *", # At 4:00 AM every day
|
||||
)
|
||||
# On by default: the similarity index is what both the "Similar games" section
|
||||
# and the personalised feed read, so leaving it off silently empties them.
|
||||
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS: Final[bool] = safe_str_to_bool(
|
||||
_get_env("ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS", "true")
|
||||
)
|
||||
SCHEDULED_BUILD_RECOMMENDATIONS_CRON: Final[str] = _get_env(
|
||||
"SCHEDULED_BUILD_RECOMMENDATIONS_CRON",
|
||||
"30 5 * * *", # At 5:30 AM every day, after the nightly scan and metadata tasks
|
||||
)
|
||||
|
||||
# SYNC
|
||||
SYNC_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/sync"
|
||||
|
||||
57
backend/endpoints/recommendations.py
Normal file
57
backend/endpoints/recommendations.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Query, Request
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses.recommendation import RecommendedRomSchema
|
||||
from endpoints.responses.rom import SimpleRomSchema
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.recommendation import FeedBuilder, get_cached_feed, set_cached_feed
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/recommendations",
|
||||
tags=["recommendations"],
|
||||
)
|
||||
|
||||
DEFAULT_FEED_LIMIT = 20
|
||||
MAX_FEED_LIMIT = 50
|
||||
|
||||
|
||||
@protected_route(router.get, "", [Scope.ROMS_READ])
|
||||
def get_recommendations(
|
||||
request: Request,
|
||||
limit: Annotated[
|
||||
int,
|
||||
Query(ge=1, le=MAX_FEED_LIMIT, description="Maximum recommendations to return"),
|
||||
] = DEFAULT_FEED_LIMIT,
|
||||
refresh: Annotated[
|
||||
bool, Query(description="Bypass the cached feed and rank again")
|
||||
] = False,
|
||||
) -> list[RecommendedRomSchema]:
|
||||
"""Personalised game recommendations for the current user.
|
||||
|
||||
Ranked on demand from the precomputed similarity graph plus the user's
|
||||
live play history, so a game played minutes ago already steers the feed.
|
||||
"""
|
||||
user_id = request.user.id
|
||||
|
||||
feed = None if refresh else get_cached_feed(user_id, limit)
|
||||
if feed is None:
|
||||
feed = FeedBuilder(user_id).build(limit=limit)
|
||||
set_cached_feed(user_id, limit, feed)
|
||||
|
||||
perms = get_permissions(request)
|
||||
|
||||
return [
|
||||
RecommendedRomSchema(
|
||||
rom=SimpleRomSchema.from_orm_with_request(item.rom, request),
|
||||
score=item.score,
|
||||
reasons=item.reasons, # type: ignore[arg-type]
|
||||
seed_rom_id=item.seed_rom_id,
|
||||
seed_rom_name=item.seed_rom_name,
|
||||
)
|
||||
for item in feed
|
||||
if perms.can_see_rom(item.rom.id, item.rom.platform_id)
|
||||
]
|
||||
31
backend/endpoints/responses/recommendation.py
Normal file
31
backend/endpoints/responses/recommendation.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from endpoints.responses.rom import SimpleRomSchema
|
||||
|
||||
|
||||
class SimilarityReasonSchema(BaseModel):
|
||||
"""Why two games were linked, e.g. {"facet": "franchise", "value": "Metroid"}.
|
||||
|
||||
`facet` is one of the metadata facets the engine scores on (genre,
|
||||
franchise, collection, company, game_mode, decade), or "igdb" when the
|
||||
link came from IGDB's own related-games list, or "top_rated" for the
|
||||
cold-start feed. The frontend maps it to a translated label.
|
||||
"""
|
||||
|
||||
facet: str
|
||||
value: str
|
||||
|
||||
|
||||
class SimilarRomSchema(BaseModel):
|
||||
rom: SimpleRomSchema
|
||||
score: float
|
||||
reasons: list[SimilarityReasonSchema]
|
||||
|
||||
|
||||
class RecommendedRomSchema(SimilarRomSchema):
|
||||
# The played game that pulled this recommendation in, for "Because you
|
||||
# played X". Absent on cold-start results, which have no seed.
|
||||
seed_rom_id: int | None = None
|
||||
seed_rom_name: str | None = None
|
||||
@@ -39,6 +39,7 @@ from config import (
|
||||
)
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.responses import BulkOperationResponse
|
||||
from endpoints.responses.recommendation import SimilarRomSchema
|
||||
from endpoints.responses.rom import (
|
||||
DetailedRomSchema,
|
||||
RomFiltersDict,
|
||||
@@ -53,7 +54,12 @@ from handler.auth.dependencies import (
|
||||
assert_rom_visible,
|
||||
get_permissions,
|
||||
)
|
||||
from handler.database import db_collection_handler, db_rom_handler, db_save_handler
|
||||
from handler.database import (
|
||||
db_collection_handler,
|
||||
db_recommendation_handler,
|
||||
db_rom_handler,
|
||||
db_save_handler,
|
||||
)
|
||||
from handler.database.base_handler import sync_session
|
||||
from handler.filesystem import fs_resource_handler, fs_rom_handler
|
||||
from handler.filesystem.assets_handler import validate_image_upload
|
||||
@@ -68,6 +74,7 @@ from handler.metadata import (
|
||||
)
|
||||
from handler.metadata.launchbox_handler.media import populate_rom_specific_paths
|
||||
from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_types
|
||||
from handler.recommendation import invalidate_cached_feed
|
||||
from handler.rom_conversion import promote_single_file_to_folder
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
@@ -116,6 +123,11 @@ router.include_router(patch_router)
|
||||
# RomUser fields the statuses filter branches on.
|
||||
STATUS_MEMBERSHIP_FIELDS = frozenset({"status", "now_playing", "backlogged", "hidden"})
|
||||
|
||||
# RomUser fields that feed the recommendation ranking.
|
||||
RECOMMENDATION_SEED_FIELDS = frozenset(
|
||||
{"rating", "status", "last_played", "now_playing", "hidden"}
|
||||
)
|
||||
|
||||
|
||||
def safe_int_or_none(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
@@ -1263,6 +1275,59 @@ def get_rom_simple(
|
||||
return SimpleRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/{id}/similar",
|
||||
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
def get_similar_roms(
|
||||
request: Request,
|
||||
id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
|
||||
limit: Annotated[
|
||||
int, Query(ge=1, le=50, description="Maximum similar roms to return")
|
||||
] = 12,
|
||||
) -> list[SimilarRomSchema]:
|
||||
"""Games in this library that resemble the given one.
|
||||
|
||||
Reads the precomputed similarity graph, which blends library-relative
|
||||
metadata overlap with IGDB's related games, collection co-membership and
|
||||
co-play. Unlike the raw IGDB list, every result is a game the server
|
||||
actually holds.
|
||||
"""
|
||||
|
||||
rom = db_rom_handler.get_rom_simple(id)
|
||||
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
assert_rom_visible(request, rom)
|
||||
|
||||
perms = get_permissions(request)
|
||||
# Over-fetch so permission filtering cannot leave a short row.
|
||||
edges = db_recommendation_handler.get_similar_rom_edges(id, limit=limit * 2)
|
||||
scores = {edge.rom_id: edge for edge in edges}
|
||||
|
||||
similar_roms = {
|
||||
similar.id: similar
|
||||
for similar in db_rom_handler.get_roms_simple_by_ids(list(scores))
|
||||
if not similar.missing_from_fs
|
||||
and perms.can_see_rom(similar.id, similar.platform_id)
|
||||
}
|
||||
|
||||
return [
|
||||
SimilarRomSchema(
|
||||
rom=SimpleRomSchema.from_orm_with_request(
|
||||
similar_roms[edge.rom_id], request
|
||||
),
|
||||
score=edge.score,
|
||||
reasons=edge.reasons, # type: ignore[arg-type]
|
||||
)
|
||||
for edge in edges
|
||||
if edge.rom_id in similar_roms
|
||||
][:limit]
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/{id}",
|
||||
@@ -2202,4 +2267,10 @@ async def update_rom_user(
|
||||
if STATUS_MEMBERSHIP_FIELDS & cleaned_data.keys():
|
||||
refresh_affected_smart_collections([id], membership_only=True)
|
||||
|
||||
# These are the fields the recommendation feed scores on, so a rating or a
|
||||
# finished playthrough should reshape it now rather than when its cache
|
||||
# happens to expire.
|
||||
if RECOMMENDATION_SEED_FIELDS & cleaned_data.keys():
|
||||
invalidate_cached_feed(request.user.id)
|
||||
|
||||
return RomUserSchema.model_validate(rom_user)
|
||||
|
||||
@@ -38,6 +38,7 @@ from tasks.manual.recompute_save_content_hashes import (
|
||||
recompute_save_content_hashes_task,
|
||||
)
|
||||
from tasks.manual.sync_folder_scan import sync_folder_scan_task
|
||||
from tasks.scheduled.build_recommendations import build_recommendations_task
|
||||
from tasks.scheduled.cleanup_orphaned_resources import cleanup_orphaned_resources_task
|
||||
from tasks.scheduled.cleanup_zip_cache import cleanup_zip_cache_task
|
||||
from tasks.scheduled.convert_images_to_webp import convert_images_to_webp_task
|
||||
@@ -88,6 +89,13 @@ scheduled_tasks: list[ScheduledTask] = [
|
||||
"task": update_switch_titledb_task,
|
||||
}
|
||||
),
|
||||
ScheduledTask(
|
||||
{
|
||||
"name": "build_recommendations",
|
||||
"type": TaskType.UPDATE,
|
||||
"task": build_recommendations_task,
|
||||
}
|
||||
),
|
||||
ScheduledTask(
|
||||
{
|
||||
"name": "convert_images_to_webp",
|
||||
|
||||
@@ -7,6 +7,7 @@ from .music_playlists_handler import DBMusicPlaylistsHandler
|
||||
from .permissions_handler import DBPermissionsHandler
|
||||
from .platforms_handler import DBPlatformsHandler
|
||||
from .play_sessions_handler import DBPlaySessionsHandler
|
||||
from .recommendations_handler import DBRecommendationsHandler
|
||||
from .roms_handler import DBRomsHandler
|
||||
from .saves_handler import DBSavesHandler
|
||||
from .screenshots_handler import DBScreenshotsHandler
|
||||
@@ -24,6 +25,7 @@ db_music_playlist_handler = DBMusicPlaylistsHandler()
|
||||
db_permission_handler = DBPermissionsHandler()
|
||||
db_platform_handler = DBPlatformsHandler()
|
||||
db_play_session_handler = DBPlaySessionsHandler()
|
||||
db_recommendation_handler = DBRecommendationsHandler()
|
||||
db_rom_handler = DBRomsHandler()
|
||||
db_save_handler = DBSavesHandler()
|
||||
db_screenshot_handler = DBScreenshotsHandler()
|
||||
|
||||
394
backend/handler/database/recommendations_handler.py
Normal file
394
backend/handler/database/recommendations_handler.py
Normal file
@@ -0,0 +1,394 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Sequence
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
from sqlalchemy import delete, func, insert, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.collection import CollectionRom
|
||||
from models.play_session import PlaySession
|
||||
from models.recommendation import RomSimilarity
|
||||
from models.rom import Rom, RomFacets, RomMetadata, RomUser
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
# Streaming chunk for the wide `roms` scan that reads the IGDB metadata blobs.
|
||||
IGDB_SCAN_CHUNK_SIZE = 500
|
||||
|
||||
# Rows per INSERT when rewriting the similarity table.
|
||||
EDGE_INSERT_CHUNK_SIZE = 1_000
|
||||
|
||||
# Co-occurrence sets larger than this say more about the collector than the
|
||||
# games: a 900-ROM "Everything" collection would otherwise emit 400k pairs and
|
||||
# relate its entire contents to itself.
|
||||
MAX_CO_OCCURRENCE_SET_SIZE = 250
|
||||
|
||||
|
||||
class RomFeatureRow(NamedTuple):
|
||||
"""The narrow slice of metadata the similarity build reads per ROM."""
|
||||
|
||||
rom_id: int
|
||||
platform_id: int
|
||||
genres: list[str] | None
|
||||
franchises: list[str] | None
|
||||
collections: list[str] | None
|
||||
companies: list[str] | None
|
||||
game_modes: list[str] | None
|
||||
first_release_date: int | None
|
||||
average_rating: float | None
|
||||
|
||||
|
||||
class UserAffinityRow(NamedTuple):
|
||||
"""One ROM the user has engaged with, and how strongly."""
|
||||
|
||||
rom_id: int
|
||||
rating: int | None
|
||||
difficulty: int | None
|
||||
completion: int | None
|
||||
status: str | None
|
||||
last_played: Any | None
|
||||
now_playing: bool
|
||||
backlogged: bool
|
||||
hidden: bool
|
||||
playtime_ms: int
|
||||
|
||||
|
||||
class SimilarRomEdge(NamedTuple):
|
||||
rom_id: int
|
||||
score: float
|
||||
reasons: list[dict[str, Any]]
|
||||
|
||||
|
||||
class DBRecommendationsHandler(DBBaseHandler):
|
||||
# --- Similarity build inputs -------------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_feature_rows(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> list[RomFeatureRow]:
|
||||
"""Every ROM's facet values, for building the library-wide IDF.
|
||||
|
||||
Reads `roms_facets` rather than `roms` on purpose: the facet values are
|
||||
mirrored there precisely so aggregations never touch the wide rows with
|
||||
their provider-metadata blobs.
|
||||
"""
|
||||
stmt = (
|
||||
select(
|
||||
RomFacets.rom_id,
|
||||
RomFacets.platform_id,
|
||||
RomFacets.genres,
|
||||
RomFacets.franchises,
|
||||
RomFacets.collections,
|
||||
RomFacets.companies,
|
||||
RomFacets.game_modes,
|
||||
RomMetadata.first_release_date,
|
||||
RomMetadata.average_rating,
|
||||
)
|
||||
.join(Rom, Rom.id == RomFacets.rom_id)
|
||||
.outerjoin(RomMetadata, RomMetadata.rom_id == RomFacets.rom_id)
|
||||
.where(Rom.missing_from_fs.is_(False))
|
||||
)
|
||||
|
||||
return [RomFeatureRow(*row) for row in session.execute(stmt).all()]
|
||||
|
||||
@begin_session
|
||||
def get_rom_igdb_ids(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> dict[int, int]:
|
||||
"""ROM id -> IGDB id.
|
||||
|
||||
Keyed by ROM id, not IGDB id: the relationship is many-to-one (region
|
||||
and revision variants of one game share an IGDB id), and keying the
|
||||
other way would silently drop every duplicate but one -- which is
|
||||
exactly the set the duplicate suppression needs to see.
|
||||
"""
|
||||
stmt = select(RomFacets.rom_id, RomFacets.igdb_id).where(
|
||||
RomFacets.igdb_id.is_not(None)
|
||||
)
|
||||
return {rom_id: igdb_id for rom_id, igdb_id in session.execute(stmt).all()}
|
||||
|
||||
@begin_session
|
||||
def iter_igdb_related(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> Iterator[tuple[int, list[int]]]:
|
||||
"""Stream each ROM's IGDB related-game ids out of its metadata blob.
|
||||
|
||||
Yields in chunks because this is the one query that has to read the
|
||||
wide `roms` row; everything else in the build works off narrow tables.
|
||||
"""
|
||||
stmt = (
|
||||
select(Rom.id, Rom.igdb_metadata)
|
||||
.where(Rom.igdb_id.is_not(None), Rom.missing_from_fs.is_(False))
|
||||
.execution_options(yield_per=IGDB_SCAN_CHUNK_SIZE)
|
||||
)
|
||||
|
||||
for rom_id, metadata in session.execute(stmt):
|
||||
if not metadata:
|
||||
continue
|
||||
|
||||
related_ids: list[int] = []
|
||||
for bucket in (
|
||||
"similar_games",
|
||||
"remakes",
|
||||
"remasters",
|
||||
"expanded_games",
|
||||
"ports",
|
||||
"expansions",
|
||||
"dlcs",
|
||||
):
|
||||
for entry in metadata.get(bucket) or ():
|
||||
entry_id = entry.get("id") if isinstance(entry, dict) else None
|
||||
if isinstance(entry_id, int):
|
||||
related_ids.append(entry_id)
|
||||
|
||||
if related_ids:
|
||||
yield rom_id, related_ids
|
||||
|
||||
@begin_session
|
||||
def get_collection_membership_sets(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> list[list[int]]:
|
||||
"""ROM ids grouped by user collection, for co-membership scoring."""
|
||||
stmt = select(CollectionRom.collection_id, CollectionRom.rom_id).order_by(
|
||||
CollectionRom.collection_id
|
||||
)
|
||||
return self._group_second_by_first(session.execute(stmt).all())
|
||||
|
||||
@begin_session
|
||||
def get_played_sets(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> list[list[int]]:
|
||||
"""ROM ids grouped by user, restricted to games they actually played.
|
||||
|
||||
This is the item-based collaborative signal. On a single-user server it
|
||||
degrades gracefully into "things I play together" rather than vanishing.
|
||||
"""
|
||||
stmt = (
|
||||
select(RomUser.user_id, RomUser.rom_id)
|
||||
.where(RomUser.last_played.is_not(None))
|
||||
.order_by(RomUser.user_id)
|
||||
)
|
||||
return self._group_second_by_first(session.execute(stmt).all())
|
||||
|
||||
@staticmethod
|
||||
def _group_second_by_first(rows: Sequence[Any]) -> list[list[int]]:
|
||||
"""Bucket (key, rom_id) rows into per-key id lists, dropping the noisy ones.
|
||||
|
||||
Singletons carry no pair information and oversized sets carry mostly
|
||||
noise, so neither is worth handing to the pair counter.
|
||||
"""
|
||||
grouped: dict[int, list[int]] = {}
|
||||
for key, rom_id in rows:
|
||||
grouped.setdefault(key, []).append(rom_id)
|
||||
|
||||
return [
|
||||
ids
|
||||
for ids in grouped.values()
|
||||
if 1 < len(ids) <= MAX_CO_OCCURRENCE_SET_SIZE
|
||||
]
|
||||
|
||||
# --- Similarity build output -------------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def replace_similarity_edges(
|
||||
self,
|
||||
rom_ids: Sequence[int],
|
||||
edges: Sequence[dict[str, Any]],
|
||||
session: Session = None, # type: ignore
|
||||
) -> int:
|
||||
"""Swap in a batch of ROMs' edges.
|
||||
|
||||
Scoped to `rom_ids` rather than truncating the table so the build can
|
||||
commit incrementally: a task that dies halfway leaves stale edges for
|
||||
the ROMs it never reached, not an empty recommendations table.
|
||||
"""
|
||||
if not rom_ids:
|
||||
return 0
|
||||
|
||||
session.execute(delete(RomSimilarity).where(RomSimilarity.rom_id.in_(rom_ids)))
|
||||
|
||||
written = 0
|
||||
for start in range(0, len(edges), EDGE_INSERT_CHUNK_SIZE):
|
||||
chunk = edges[start : start + EDGE_INSERT_CHUNK_SIZE]
|
||||
if chunk:
|
||||
session.execute(insert(RomSimilarity), chunk)
|
||||
written += len(chunk)
|
||||
|
||||
return written
|
||||
|
||||
@begin_session
|
||||
def delete_all_similarity_edges(
|
||||
self, session: Session = None # type: ignore
|
||||
) -> None:
|
||||
session.execute(delete(RomSimilarity))
|
||||
|
||||
@begin_session
|
||||
def count_similarity_edges(self, session: Session = None) -> int: # type: ignore
|
||||
return session.scalar(select(func.count()).select_from(RomSimilarity)) or 0
|
||||
|
||||
# --- Reads -------------------------------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_similar_rom_edges(
|
||||
self,
|
||||
rom_id: int,
|
||||
limit: int = 20,
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[SimilarRomEdge]:
|
||||
"""Top precomputed neighbours of one ROM, best first.
|
||||
|
||||
Returns ids rather than ROMs so every caller hydrates through the same
|
||||
`SimpleRomSchema` load path instead of each growing its own.
|
||||
"""
|
||||
stmt = (
|
||||
select(
|
||||
RomSimilarity.related_rom_id,
|
||||
RomSimilarity.score,
|
||||
RomSimilarity.reasons,
|
||||
)
|
||||
.where(RomSimilarity.rom_id == rom_id)
|
||||
.order_by(RomSimilarity.score.desc(), RomSimilarity.related_rom_id.asc())
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return [
|
||||
SimilarRomEdge(rom_id=related_id, score=score, reasons=reasons or [])
|
||||
for related_id, score, reasons in session.execute(stmt).all()
|
||||
]
|
||||
|
||||
@begin_session
|
||||
def get_neighbours_for_roms(
|
||||
self,
|
||||
rom_ids: Sequence[int],
|
||||
limit_per_rom: int = 20,
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[tuple[int, int, float, list[dict[str, Any]]]]:
|
||||
"""Edges fanning out from a set of seed ROMs, for the personalised feed.
|
||||
|
||||
Returns raw (seed_rom_id, related_rom_id, score, reasons) tuples; the
|
||||
ranking handler hydrates only the ROMs that survive its cut.
|
||||
"""
|
||||
if not rom_ids:
|
||||
return []
|
||||
|
||||
stmt = (
|
||||
select(
|
||||
RomSimilarity.rom_id,
|
||||
RomSimilarity.related_rom_id,
|
||||
RomSimilarity.score,
|
||||
RomSimilarity.reasons,
|
||||
)
|
||||
.where(RomSimilarity.rom_id.in_(rom_ids))
|
||||
.order_by(RomSimilarity.rom_id, RomSimilarity.score.desc())
|
||||
)
|
||||
|
||||
# Trim per seed in Python: a per-group LIMIT needs a window function,
|
||||
# and the row counts here are already bounded by the build's top-N cut.
|
||||
per_seed: dict[int, int] = {}
|
||||
results: list[tuple[int, int, float, list[dict[str, Any]]]] = []
|
||||
for seed_id, related_id, score, reasons in session.execute(stmt):
|
||||
taken = per_seed.get(seed_id, 0)
|
||||
if taken >= limit_per_rom:
|
||||
continue
|
||||
per_seed[seed_id] = taken + 1
|
||||
results.append((seed_id, related_id, score, reasons or []))
|
||||
|
||||
return results
|
||||
|
||||
@begin_session
|
||||
def get_user_affinity(
|
||||
self,
|
||||
user_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[UserAffinityRow]:
|
||||
"""Everything the user has done with each ROM, plus total playtime.
|
||||
|
||||
Playtime comes from `play_sessions` (the accurate signal) while the
|
||||
rest comes from `rom_user`; a ROM can appear with either or both.
|
||||
"""
|
||||
playtime_subq = (
|
||||
select(
|
||||
PlaySession.rom_id.label("rom_id"),
|
||||
func.coalesce(func.sum(PlaySession.duration_ms), 0).label(
|
||||
"playtime_ms"
|
||||
),
|
||||
)
|
||||
.where(PlaySession.user_id == user_id, PlaySession.rom_id.is_not(None))
|
||||
.group_by(PlaySession.rom_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
stmt = (
|
||||
select(
|
||||
RomUser.rom_id,
|
||||
RomUser.rating,
|
||||
RomUser.difficulty,
|
||||
RomUser.completion,
|
||||
RomUser.status,
|
||||
RomUser.last_played,
|
||||
RomUser.now_playing,
|
||||
RomUser.backlogged,
|
||||
RomUser.hidden,
|
||||
func.coalesce(playtime_subq.c.playtime_ms, 0),
|
||||
)
|
||||
.outerjoin(playtime_subq, playtime_subq.c.rom_id == RomUser.rom_id)
|
||||
.where(RomUser.user_id == user_id)
|
||||
)
|
||||
|
||||
return [
|
||||
UserAffinityRow(
|
||||
rom_id=row[0],
|
||||
rating=row[1],
|
||||
difficulty=row[2],
|
||||
completion=row[3],
|
||||
status=row[4].value if hasattr(row[4], "value") else row[4],
|
||||
last_played=row[5],
|
||||
now_playing=bool(row[6]),
|
||||
backlogged=bool(row[7]),
|
||||
hidden=bool(row[8]),
|
||||
playtime_ms=int(row[9] or 0),
|
||||
)
|
||||
for row in session.execute(stmt).all()
|
||||
]
|
||||
|
||||
@begin_session
|
||||
def get_rom_names(
|
||||
self,
|
||||
rom_ids: Sequence[int],
|
||||
session: Session = None, # type: ignore
|
||||
) -> dict[int, str]:
|
||||
"""Display names only, for the "Because you played X" attribution."""
|
||||
if not rom_ids:
|
||||
return {}
|
||||
|
||||
stmt = select(Rom.id, Rom.name, Rom.fs_name).where(Rom.id.in_(rom_ids))
|
||||
return {
|
||||
rom_id: name or fs_name
|
||||
for rom_id, name, fs_name in session.execute(stmt).all()
|
||||
}
|
||||
|
||||
@begin_session
|
||||
def get_fallback_rom_ids(
|
||||
self,
|
||||
limit: int,
|
||||
exclude_rom_ids: Sequence[int] = (),
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[int]:
|
||||
"""Cold-start feed: the best-reviewed games in the library."""
|
||||
stmt = (
|
||||
select(Rom.id)
|
||||
.join(RomMetadata, RomMetadata.rom_id == Rom.id)
|
||||
.where(
|
||||
Rom.missing_from_fs.is_(False),
|
||||
RomMetadata.average_rating.is_not(None),
|
||||
)
|
||||
.order_by(RomMetadata.average_rating.desc(), Rom.name_sort_key.asc())
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
if exclude_rom_ids:
|
||||
stmt = stmt.where(Rom.id.not_in(exclude_rom_ids))
|
||||
|
||||
return list(session.execute(stmt).scalars().all())
|
||||
@@ -471,6 +471,20 @@ class DBRomsHandler(DBBaseHandler):
|
||||
return []
|
||||
return session.scalars(query.filter(Rom.id.in_(ids))).all()
|
||||
|
||||
@begin_session
|
||||
@with_simple_details
|
||||
def get_roms_simple_by_ids(
|
||||
self,
|
||||
ids: Sequence[int],
|
||||
*,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Rom]:
|
||||
"""Get multiple ROMs by ID with only the loads `SimpleRomSchema` needs."""
|
||||
if not ids:
|
||||
return []
|
||||
return session.scalars(query.filter(Rom.id.in_(ids))).all()
|
||||
|
||||
def get_files_for_roms(
|
||||
self,
|
||||
rom_ids: list[int],
|
||||
|
||||
18
backend/handler/recommendation/__init__.py
Normal file
18
backend/handler/recommendation/__init__.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from .builder import BuildStats, SimilarityBuilder
|
||||
from .feed import (
|
||||
FeedBuilder,
|
||||
RecommendedRom,
|
||||
get_cached_feed,
|
||||
invalidate_cached_feed,
|
||||
set_cached_feed,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BuildStats",
|
||||
"FeedBuilder",
|
||||
"RecommendedRom",
|
||||
"SimilarityBuilder",
|
||||
"get_cached_feed",
|
||||
"invalidate_cached_feed",
|
||||
"set_cached_feed",
|
||||
]
|
||||
357
backend/handler/recommendation/builder.py
Normal file
357
backend/handler/recommendation/builder.py
Normal file
@@ -0,0 +1,357 @@
|
||||
"""Builds the precomputed item-item similarity graph.
|
||||
|
||||
Run from the scheduled recommendations task. The whole graph is derived from
|
||||
one consistent snapshot of the library, because the IDF weighting that makes
|
||||
scores library-relative changes as the shelf grows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from itertools import combinations
|
||||
from typing import Any, Final
|
||||
|
||||
from handler.database import db_recommendation_handler
|
||||
from handler.database.recommendations_handler import RomFeatureRow
|
||||
from logger.logger import log
|
||||
|
||||
from .scoring import (
|
||||
RomFeatures,
|
||||
blend,
|
||||
build_inverted_index,
|
||||
build_vector,
|
||||
candidate_ids,
|
||||
compute_idf,
|
||||
content_similarity,
|
||||
extract_tokens,
|
||||
has_taste_signal,
|
||||
normalise_co_occurrence,
|
||||
shared_reasons,
|
||||
)
|
||||
|
||||
# Neighbours kept per ROM. Enough to fill a "Similar games" shelf several times
|
||||
# over and to give the personalised feed room to diversify, without letting the
|
||||
# table grow to rom_count * library_size.
|
||||
MAX_NEIGHBOURS: Final = 24
|
||||
|
||||
# Below this a "recommendation" is just two games that share the word Action.
|
||||
MIN_EDGE_SCORE: Final = 0.05
|
||||
|
||||
# ROMs per write batch. Bounds peak memory and lets the task commit as it goes.
|
||||
BUILD_BATCH_SIZE: Final = 500
|
||||
|
||||
# Hard ceiling on candidates scored per ROM. Reached only by games whose every
|
||||
# facet is rare, where the tail is noise anyway.
|
||||
MAX_CANDIDATES_PER_ROM: Final = 1_500
|
||||
|
||||
|
||||
@dataclass
|
||||
class BuildStats:
|
||||
roms_indexed: int = 0
|
||||
edges_written: int = 0
|
||||
roms_without_metadata: int = 0
|
||||
total: int = 0
|
||||
|
||||
def to_dict(self) -> dict[str, int]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PairSignals:
|
||||
"""Sparse, symmetric side-signals keyed by an ordered ROM id pair."""
|
||||
|
||||
igdb: dict[tuple[int, int], float] = field(default_factory=dict)
|
||||
co_play: dict[tuple[int, int], float] = field(default_factory=dict)
|
||||
co_collection: dict[tuple[int, int], float] = field(default_factory=dict)
|
||||
play_totals: dict[int, int] = field(default_factory=dict)
|
||||
collection_totals: dict[int, int] = field(default_factory=dict)
|
||||
|
||||
# ROM id -> every ROM linked to it by a non-content signal. Built once
|
||||
# after collection: deriving it per ROM would rescan all three pair maps
|
||||
# for every ROM in the library.
|
||||
adjacency: defaultdict[int, set[int]] = field(
|
||||
default_factory=lambda: defaultdict(set)
|
||||
)
|
||||
|
||||
def index_adjacency(self) -> None:
|
||||
for source in (self.igdb, self.co_play, self.co_collection):
|
||||
for left, right in source:
|
||||
self.adjacency[left].add(right)
|
||||
self.adjacency[right].add(left)
|
||||
|
||||
def partners_of(self, rom_id: int) -> set[int]:
|
||||
return self.adjacency.get(rom_id, set())
|
||||
|
||||
|
||||
def _pair_key(left: int, right: int) -> tuple[int, int]:
|
||||
return (left, right) if left < right else (right, left)
|
||||
|
||||
|
||||
class SimilarityBuilder:
|
||||
"""Assembles the similarity graph and writes it to `rom_similarity`."""
|
||||
|
||||
def __init__(self, progress: Callable[[BuildStats], None] | None = None) -> None:
|
||||
self._progress = progress
|
||||
self.stats = BuildStats()
|
||||
|
||||
def build(self) -> BuildStats:
|
||||
feature_rows = db_recommendation_handler.get_feature_rows()
|
||||
if not feature_rows:
|
||||
log.info("No ROMs to index for recommendations")
|
||||
return self.stats
|
||||
|
||||
features = self._build_features(feature_rows)
|
||||
self.stats.total = len(features)
|
||||
self._report()
|
||||
|
||||
total_documents = len(features)
|
||||
idf = compute_idf(
|
||||
(feature.tokens for feature in features.values()), total_documents
|
||||
)
|
||||
vectors = {
|
||||
rom_id: build_vector(feature.tokens, idf)
|
||||
for rom_id, feature in features.items()
|
||||
}
|
||||
postings = build_inverted_index(features)
|
||||
|
||||
igdb_ids = {
|
||||
rom_id: igdb_id
|
||||
for rom_id, igdb_id in db_recommendation_handler.get_rom_igdb_ids().items()
|
||||
if rom_id in features
|
||||
}
|
||||
# Resolving an IGDB id back to a ROM is one-to-many; any owned copy of
|
||||
# the game is an equally good target for the edge.
|
||||
igdb_to_rom = {igdb_id: rom_id for rom_id, igdb_id in igdb_ids.items()}
|
||||
signals = self._collect_pair_signals(features, igdb_ids, igdb_to_rom)
|
||||
|
||||
log.info(f"Scoring similarity for {total_documents} ROMs")
|
||||
self._score_and_write(features, vectors, postings, signals, igdb_ids)
|
||||
|
||||
log.info(
|
||||
f"Recommendations index built: {self.stats.roms_indexed} ROMs, "
|
||||
f"{self.stats.edges_written} edges"
|
||||
)
|
||||
return self.stats
|
||||
|
||||
# --- Inputs ------------------------------------------------------------------
|
||||
|
||||
def _build_features(self, rows: Sequence[RomFeatureRow]) -> dict[int, RomFeatures]:
|
||||
features: dict[int, RomFeatures] = {}
|
||||
|
||||
for row in rows:
|
||||
tokens = extract_tokens(
|
||||
platform_id=row.platform_id,
|
||||
genres=row.genres,
|
||||
franchises=row.franchises,
|
||||
collections=row.collections,
|
||||
companies=row.companies,
|
||||
game_modes=row.game_modes,
|
||||
first_release_date=row.first_release_date,
|
||||
)
|
||||
|
||||
# Platform and decade alone describe a shelf, not a game: two
|
||||
# unmatched files from the same folder would otherwise normalise to
|
||||
# identical vectors and score a perfect match against each other.
|
||||
if not has_taste_signal(tokens):
|
||||
self.stats.roms_without_metadata += 1
|
||||
continue
|
||||
|
||||
features[row.rom_id] = RomFeatures(
|
||||
rom_id=row.rom_id,
|
||||
platform_id=row.platform_id,
|
||||
tokens=tokens,
|
||||
average_rating=row.average_rating,
|
||||
)
|
||||
|
||||
return features
|
||||
|
||||
def _collect_pair_signals(
|
||||
self,
|
||||
features: dict[int, RomFeatures],
|
||||
igdb_ids: dict[int, int],
|
||||
igdb_to_rom: dict[int, int],
|
||||
) -> _PairSignals:
|
||||
signals = _PairSignals()
|
||||
|
||||
for rom_id, related_igdb_ids in db_recommendation_handler.iter_igdb_related():
|
||||
if rom_id not in features:
|
||||
continue
|
||||
for related_igdb_id in related_igdb_ids:
|
||||
related_rom_id = igdb_to_rom.get(related_igdb_id)
|
||||
# IGDB's list is mostly games the user does not own; only the
|
||||
# ones actually on the shelf are worth an edge.
|
||||
if related_rom_id is None or related_rom_id == rom_id:
|
||||
continue
|
||||
if self._is_duplicate(rom_id, related_rom_id, igdb_ids):
|
||||
continue
|
||||
signals.igdb[_pair_key(rom_id, related_rom_id)] = 1.0
|
||||
|
||||
self._count_co_occurrence(
|
||||
db_recommendation_handler.get_played_sets(),
|
||||
features,
|
||||
igdb_ids,
|
||||
signals.co_play,
|
||||
signals.play_totals,
|
||||
)
|
||||
self._count_co_occurrence(
|
||||
db_recommendation_handler.get_collection_membership_sets(),
|
||||
features,
|
||||
igdb_ids,
|
||||
signals.co_collection,
|
||||
signals.collection_totals,
|
||||
)
|
||||
|
||||
signals.index_adjacency()
|
||||
|
||||
log.debug(
|
||||
f"Pair signals: igdb={len(signals.igdb)}, "
|
||||
f"co_play={len(signals.co_play)}, "
|
||||
f"co_collection={len(signals.co_collection)}"
|
||||
)
|
||||
return signals
|
||||
|
||||
def _count_co_occurrence(
|
||||
self,
|
||||
id_sets: Iterable[Sequence[int]],
|
||||
features: dict[int, RomFeatures],
|
||||
igdb_ids: dict[int, int],
|
||||
pair_counts: dict[tuple[int, int], float],
|
||||
totals: dict[int, int],
|
||||
) -> None:
|
||||
raw: defaultdict[tuple[int, int], int] = defaultdict(int)
|
||||
|
||||
for id_set in id_sets:
|
||||
known = sorted({rom_id for rom_id in id_set if rom_id in features})
|
||||
if len(known) < 2:
|
||||
continue
|
||||
|
||||
for rom_id in known:
|
||||
totals[rom_id] = totals.get(rom_id, 0) + 1
|
||||
|
||||
for left, right in combinations(known, 2):
|
||||
if self._is_duplicate(left, right, igdb_ids):
|
||||
continue
|
||||
raw[(left, right)] += 1
|
||||
|
||||
for (left, right), count in raw.items():
|
||||
pair_counts[(left, right)] = normalise_co_occurrence(
|
||||
count, totals.get(left, 0), totals.get(right, 0)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_duplicate(left: int, right: int, igdb_ids: dict[int, int]) -> bool:
|
||||
"""Two files of the same game (regions, revisions) are not a recommendation."""
|
||||
left_igdb = igdb_ids.get(left)
|
||||
return left_igdb is not None and left_igdb == igdb_ids.get(right)
|
||||
|
||||
# --- Scoring -----------------------------------------------------------------
|
||||
|
||||
def _score_and_write(
|
||||
self,
|
||||
features: dict[int, RomFeatures],
|
||||
vectors: dict[int, dict[str, float]],
|
||||
postings: dict[str, list[int]],
|
||||
signals: _PairSignals,
|
||||
igdb_ids: dict[int, int],
|
||||
) -> None:
|
||||
total_documents = len(features)
|
||||
batch_rom_ids: list[int] = []
|
||||
batch_edges: list[dict[str, Any]] = []
|
||||
|
||||
for rom_id, feature in features.items():
|
||||
edges = self._score_one(
|
||||
feature, features, vectors, postings, signals, igdb_ids, total_documents
|
||||
)
|
||||
|
||||
batch_rom_ids.append(rom_id)
|
||||
batch_edges.extend(edges)
|
||||
self.stats.roms_indexed += 1
|
||||
|
||||
if len(batch_rom_ids) >= BUILD_BATCH_SIZE:
|
||||
self._flush(batch_rom_ids, batch_edges)
|
||||
batch_rom_ids, batch_edges = [], []
|
||||
|
||||
self._flush(batch_rom_ids, batch_edges)
|
||||
|
||||
def _score_one(
|
||||
self,
|
||||
feature: RomFeatures,
|
||||
features: dict[int, RomFeatures],
|
||||
vectors: dict[int, dict[str, float]],
|
||||
postings: dict[str, list[int]],
|
||||
signals: _PairSignals,
|
||||
igdb_ids: dict[int, int],
|
||||
total_documents: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
rom_id = feature.rom_id
|
||||
source_vector = vectors.get(rom_id, {})
|
||||
|
||||
candidates = candidate_ids(feature, postings, total_documents)
|
||||
# A game IGDB relates to, or that users play alongside this one, is
|
||||
# worth scoring even when they share no metadata facet at all.
|
||||
candidates |= signals.partners_of(rom_id)
|
||||
candidates.discard(rom_id)
|
||||
|
||||
if len(candidates) > MAX_CANDIDATES_PER_ROM:
|
||||
candidates = set(
|
||||
sorted(
|
||||
candidates,
|
||||
key=lambda cid: content_similarity(
|
||||
source_vector, vectors.get(cid, {})
|
||||
),
|
||||
reverse=True,
|
||||
)[:MAX_CANDIDATES_PER_ROM]
|
||||
)
|
||||
|
||||
scored: list[tuple[float, int, list[dict[str, str]]]] = []
|
||||
for candidate_id in candidates:
|
||||
if self._is_duplicate(rom_id, candidate_id, igdb_ids):
|
||||
continue
|
||||
|
||||
candidate_vector = vectors.get(candidate_id, {})
|
||||
content = content_similarity(source_vector, candidate_vector)
|
||||
key = _pair_key(rom_id, candidate_id)
|
||||
|
||||
score = blend(
|
||||
content=content,
|
||||
igdb_prior=signals.igdb.get(key, 0.0),
|
||||
co_play=signals.co_play.get(key, 0.0),
|
||||
co_collection=signals.co_collection.get(key, 0.0),
|
||||
average_rating=features[candidate_id].average_rating,
|
||||
)
|
||||
|
||||
if score < MIN_EDGE_SCORE:
|
||||
continue
|
||||
|
||||
reasons = shared_reasons(source_vector, candidate_vector)
|
||||
if key in signals.igdb:
|
||||
reasons.append({"facet": "igdb", "value": "similar"})
|
||||
|
||||
scored.append((score, candidate_id, reasons))
|
||||
|
||||
scored.sort(key=lambda item: (-item[0], item[1]))
|
||||
|
||||
return [
|
||||
{
|
||||
"rom_id": rom_id,
|
||||
"related_rom_id": candidate_id,
|
||||
"score": round(score, 6),
|
||||
"reasons": reasons,
|
||||
}
|
||||
for score, candidate_id, reasons in scored[:MAX_NEIGHBOURS]
|
||||
]
|
||||
|
||||
def _flush(self, rom_ids: list[int], edges: list[dict[str, Any]]) -> None:
|
||||
if not rom_ids:
|
||||
return
|
||||
|
||||
self.stats.edges_written += db_recommendation_handler.replace_similarity_edges(
|
||||
rom_ids, edges
|
||||
)
|
||||
self._report()
|
||||
|
||||
def _report(self) -> None:
|
||||
if self._progress:
|
||||
self._progress(self.stats)
|
||||
377
backend/handler/recommendation/feed.py
Normal file
377
backend/handler/recommendation/feed.py
Normal file
@@ -0,0 +1,377 @@
|
||||
"""Builds a user's personalised recommendation feed.
|
||||
|
||||
Computed on demand from the precomputed similarity edges plus live activity,
|
||||
rather than precomputed per user: a feed built nightly would ignore the game
|
||||
someone played an hour ago, which is exactly the signal that matters most.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Final
|
||||
|
||||
from handler.database import db_recommendation_handler, db_rom_handler
|
||||
from handler.database.recommendations_handler import UserAffinityRow
|
||||
from handler.redis_handler import sync_cache
|
||||
from logger.logger import log
|
||||
from models.rom import Rom, RomUserStatus
|
||||
|
||||
# The user rating scale is 1-10; 5.5 is the indifference point, so anything
|
||||
# below it pushes similar games *away* rather than merely not pulling them in.
|
||||
NEUTRAL_RATING: Final = 5.5
|
||||
MAX_RATING: Final = 10.0
|
||||
|
||||
# Playtime saturates: the difference between 1h and 10h says a lot, the
|
||||
# difference between 100h and 200h says almost nothing.
|
||||
PLAYTIME_SATURATION_HOURS: Final = 20.0
|
||||
|
||||
# Taste drifts. A game played last week should steer the feed more than one
|
||||
# finished two years ago, without the old one falling off entirely.
|
||||
RECENCY_HALFLIFE_DAYS: Final = 60.0
|
||||
MIN_RECENCY_FACTOR: Final = 0.15
|
||||
|
||||
STATUS_AFFINITY: Final[dict[str, float]] = {
|
||||
RomUserStatus.COMPLETED_100.value: 1.0,
|
||||
RomUserStatus.FINISHED.value: 0.8,
|
||||
RomUserStatus.RETIRED.value: 0.4,
|
||||
RomUserStatus.INCOMPLETE.value: 0.3,
|
||||
}
|
||||
|
||||
# Games the user has already played still belong in the feed (a sequel to
|
||||
# something you finished is a fine suggestion), but an unplayed game you own
|
||||
# is the outcome this feature exists to produce.
|
||||
PLAYED_NOVELTY_FACTOR: Final = 0.3
|
||||
|
||||
# Disliked games steer, but less forcefully than loved ones.
|
||||
NEGATIVE_SEED_DAMPING: Final = 0.5
|
||||
|
||||
# Ceilings applied during diversification, so one series cannot own the row.
|
||||
MAX_PER_FRANCHISE: Final = 2
|
||||
MAX_PER_PLATFORM: Final = 4
|
||||
|
||||
# Seeds are read in descending affinity; beyond this the contribution is noise.
|
||||
MAX_SEEDS: Final = 60
|
||||
|
||||
# How many candidates to hydrate before diversifying down to the final count.
|
||||
OVERFETCH_FACTOR: Final = 5
|
||||
|
||||
FEED_CACHE_TTL_SECONDS: Final = 900
|
||||
FEED_CACHE_PREFIX: Final = "recommendations:feed"
|
||||
|
||||
|
||||
@dataclass
|
||||
class RecommendedRom:
|
||||
rom: Rom
|
||||
score: float
|
||||
reasons: list[dict[str, str]] = field(default_factory=list)
|
||||
seed_rom_id: int | None = None
|
||||
seed_rom_name: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Candidate:
|
||||
rom_id: int
|
||||
score: float = 0.0
|
||||
best_seed_id: int | None = None
|
||||
best_seed_contribution: float = 0.0
|
||||
reasons: list[dict[str, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def seed_affinity(row: UserAffinityRow, *, now: datetime | None = None) -> float:
|
||||
"""How strongly one played game should steer the feed, in roughly [-1, 1].
|
||||
|
||||
Negative for games the user rated below the midpoint, which is what lets
|
||||
the feed learn "not this kind of thing".
|
||||
"""
|
||||
signals: list[float] = []
|
||||
|
||||
if row.playtime_ms > 0:
|
||||
hours = row.playtime_ms / 3_600_000
|
||||
signals.append(
|
||||
min(1.0, math.log1p(hours) / math.log1p(PLAYTIME_SATURATION_HOURS))
|
||||
)
|
||||
|
||||
if row.rating:
|
||||
# Maps 10 -> +1.0 and 1 -> -1.0, crossing zero at the scale midpoint.
|
||||
signals.append(
|
||||
max(
|
||||
-1.0,
|
||||
min(1.0, (row.rating - NEUTRAL_RATING) / (MAX_RATING - NEUTRAL_RATING)),
|
||||
)
|
||||
)
|
||||
|
||||
if row.status and row.status in STATUS_AFFINITY:
|
||||
signals.append(STATUS_AFFINITY[row.status])
|
||||
|
||||
if row.now_playing:
|
||||
signals.append(1.0)
|
||||
|
||||
if not signals:
|
||||
# Played at some point, but nothing else is known about it.
|
||||
return (
|
||||
0.2 * _recency_factor(row.last_played, now=now) if row.last_played else 0.0
|
||||
)
|
||||
|
||||
affinity = sum(signals) / len(signals)
|
||||
if affinity < 0:
|
||||
affinity *= NEGATIVE_SEED_DAMPING
|
||||
|
||||
return affinity * _recency_factor(row.last_played, now=now)
|
||||
|
||||
|
||||
def _recency_factor(
|
||||
last_played: datetime | None, *, now: datetime | None = None
|
||||
) -> float:
|
||||
"""Exponential decay on time since last played, floored so old loves persist."""
|
||||
if last_played is None:
|
||||
return MIN_RECENCY_FACTOR
|
||||
|
||||
reference = now or datetime.now(timezone.utc)
|
||||
if last_played.tzinfo is None:
|
||||
last_played = last_played.replace(tzinfo=timezone.utc)
|
||||
|
||||
days = max(0.0, (reference - last_played).total_seconds() / 86_400)
|
||||
decayed = math.pow(0.5, days / RECENCY_HALFLIFE_DAYS)
|
||||
return max(MIN_RECENCY_FACTOR, decayed)
|
||||
|
||||
|
||||
class FeedBuilder:
|
||||
"""Ranks candidates for one user from the precomputed similarity graph."""
|
||||
|
||||
def __init__(self, user_id: int) -> None:
|
||||
self.user_id = user_id
|
||||
|
||||
def build(self, limit: int = 20) -> list[RecommendedRom]:
|
||||
affinity_rows = db_recommendation_handler.get_user_affinity(self.user_id)
|
||||
|
||||
seeds, excluded = self._partition(affinity_rows)
|
||||
if not seeds:
|
||||
return self._cold_start(limit, excluded)
|
||||
|
||||
candidates = self._accumulate(seeds, excluded)
|
||||
if not candidates:
|
||||
return self._cold_start(limit, excluded)
|
||||
|
||||
played_rom_ids = {
|
||||
row.rom_id for row in affinity_rows if row.last_played is not None
|
||||
}
|
||||
return self._rank(candidates, played_rom_ids, seeds, limit)
|
||||
|
||||
# --- Stages ------------------------------------------------------------------
|
||||
|
||||
def _partition(
|
||||
self, rows: Sequence[UserAffinityRow]
|
||||
) -> tuple[dict[int, float], set[int]]:
|
||||
"""Split the user's library interactions into seeds and hard exclusions."""
|
||||
seeds: dict[int, float] = {}
|
||||
excluded: set[int] = set()
|
||||
|
||||
for row in rows:
|
||||
if row.hidden or row.status == RomUserStatus.NEVER_PLAYING.value:
|
||||
excluded.add(row.rom_id)
|
||||
# Never-played-on-purpose is a filtering decision, not a taste
|
||||
# signal, so it contributes nothing to the seed set.
|
||||
if row.status == RomUserStatus.NEVER_PLAYING.value:
|
||||
continue
|
||||
|
||||
affinity = seed_affinity(row)
|
||||
if abs(affinity) > 0.01:
|
||||
seeds[row.rom_id] = affinity
|
||||
|
||||
# The seeds themselves are never their own recommendations.
|
||||
excluded.update(seeds)
|
||||
|
||||
if len(seeds) > MAX_SEEDS:
|
||||
strongest = sorted(seeds.items(), key=lambda kv: -abs(kv[1]))[:MAX_SEEDS]
|
||||
seeds = dict(strongest)
|
||||
|
||||
return seeds, excluded
|
||||
|
||||
def _accumulate(
|
||||
self, seeds: dict[int, float], excluded: set[int]
|
||||
) -> dict[int, _Candidate]:
|
||||
"""Fan out from every seed, summing weighted edge scores per candidate."""
|
||||
edges = db_recommendation_handler.get_neighbours_for_roms(list(seeds))
|
||||
candidates: dict[int, _Candidate] = {}
|
||||
|
||||
for seed_id, related_id, edge_score, reasons in edges:
|
||||
if related_id in excluded:
|
||||
continue
|
||||
|
||||
contribution = edge_score * seeds[seed_id]
|
||||
candidate = candidates.get(related_id)
|
||||
if candidate is None:
|
||||
candidate = _Candidate(rom_id=related_id)
|
||||
candidates[related_id] = candidate
|
||||
|
||||
candidate.score += contribution
|
||||
# Attribute the recommendation to whichever seed pulled hardest, so
|
||||
# "Because you played X" names the game that actually caused it.
|
||||
if contribution > candidate.best_seed_contribution:
|
||||
candidate.best_seed_contribution = contribution
|
||||
candidate.best_seed_id = seed_id
|
||||
candidate.reasons = list(reasons)
|
||||
|
||||
return {
|
||||
rom_id: candidate
|
||||
for rom_id, candidate in candidates.items()
|
||||
if candidate.score > 0
|
||||
}
|
||||
|
||||
def _rank(
|
||||
self,
|
||||
candidates: dict[int, _Candidate],
|
||||
played_rom_ids: set[int],
|
||||
seeds: dict[int, float],
|
||||
limit: int,
|
||||
) -> list[RecommendedRom]:
|
||||
for candidate in candidates.values():
|
||||
if candidate.rom_id in played_rom_ids:
|
||||
candidate.score *= PLAYED_NOVELTY_FACTOR
|
||||
|
||||
ordered = sorted(candidates.values(), key=lambda c: (-c.score, c.rom_id))[
|
||||
: limit * OVERFETCH_FACTOR
|
||||
]
|
||||
|
||||
roms = _hydrate([candidate.rom_id for candidate in ordered])
|
||||
seed_names = db_recommendation_handler.get_rom_names(
|
||||
[
|
||||
candidate.best_seed_id
|
||||
for candidate in ordered
|
||||
if candidate.best_seed_id is not None
|
||||
]
|
||||
)
|
||||
|
||||
selected: list[RecommendedRom] = []
|
||||
franchise_counts: dict[str, int] = {}
|
||||
platform_counts: dict[int, int] = {}
|
||||
|
||||
for candidate in ordered:
|
||||
rom = roms.get(candidate.rom_id)
|
||||
if rom is None:
|
||||
continue
|
||||
|
||||
franchise = self._primary_franchise(rom)
|
||||
if franchise and franchise_counts.get(franchise, 0) >= MAX_PER_FRANCHISE:
|
||||
continue
|
||||
if platform_counts.get(rom.platform_id, 0) >= MAX_PER_PLATFORM:
|
||||
continue
|
||||
|
||||
if franchise:
|
||||
franchise_counts[franchise] = franchise_counts.get(franchise, 0) + 1
|
||||
platform_counts[rom.platform_id] = (
|
||||
platform_counts.get(rom.platform_id, 0) + 1
|
||||
)
|
||||
|
||||
selected.append(
|
||||
RecommendedRom(
|
||||
rom=rom,
|
||||
score=round(candidate.score, 6),
|
||||
reasons=candidate.reasons,
|
||||
seed_rom_id=candidate.best_seed_id,
|
||||
seed_rom_name=seed_names.get(candidate.best_seed_id or -1),
|
||||
)
|
||||
)
|
||||
|
||||
if len(selected) >= limit:
|
||||
break
|
||||
|
||||
return selected
|
||||
|
||||
def _cold_start(self, limit: int, excluded: set[int]) -> list[RecommendedRom]:
|
||||
"""No usable activity yet, so fall back to the library's best-reviewed."""
|
||||
log.debug(f"No recommendation seeds for user {self.user_id}, using fallback")
|
||||
|
||||
rom_ids = db_recommendation_handler.get_fallback_rom_ids(
|
||||
limit, exclude_rom_ids=list(excluded)
|
||||
)
|
||||
roms = _hydrate(rom_ids)
|
||||
|
||||
return [
|
||||
RecommendedRom(
|
||||
rom=roms[rom_id],
|
||||
score=0.0,
|
||||
reasons=[{"facet": "top_rated", "value": ""}],
|
||||
)
|
||||
for rom_id in rom_ids
|
||||
if rom_id in roms
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _primary_franchise(rom: Rom) -> str | None:
|
||||
metadatum = rom.metadatum
|
||||
if metadatum is None:
|
||||
return None
|
||||
for values in (metadatum.collections, metadatum.franchises):
|
||||
if values:
|
||||
return str(values[0])
|
||||
return None
|
||||
|
||||
|
||||
def _hydrate(rom_ids: Sequence[int]) -> dict[int, Rom]:
|
||||
"""Load ROMs through the shared `SimpleRomSchema` load path.
|
||||
|
||||
Missing-from-disk ROMs are dropped here rather than filtered in SQL, so
|
||||
the edge queries never have to join the wide `roms` table.
|
||||
"""
|
||||
return {
|
||||
rom.id: rom
|
||||
for rom in db_rom_handler.get_roms_simple_by_ids(list(rom_ids))
|
||||
if not rom.missing_from_fs
|
||||
}
|
||||
|
||||
|
||||
def get_cached_feed(user_id: int, limit: int) -> list[RecommendedRom] | None:
|
||||
"""Read a cached feed, re-hydrating the ROMs so visibility stays live."""
|
||||
raw = sync_cache.get(_cache_key(user_id, limit))
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
try:
|
||||
entries: list[dict[str, Any]] = json.loads(raw)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
roms = _hydrate([entry["rom_id"] for entry in entries])
|
||||
|
||||
return [
|
||||
RecommendedRom(
|
||||
rom=roms[entry["rom_id"]],
|
||||
score=entry["score"],
|
||||
reasons=entry.get("reasons") or [],
|
||||
seed_rom_id=entry.get("seed_rom_id"),
|
||||
seed_rom_name=entry.get("seed_rom_name"),
|
||||
)
|
||||
for entry in entries
|
||||
if entry["rom_id"] in roms
|
||||
]
|
||||
|
||||
|
||||
def set_cached_feed(user_id: int, limit: int, feed: Sequence[RecommendedRom]) -> None:
|
||||
"""Cache only the ranking, never the ROM rows themselves."""
|
||||
payload = json.dumps(
|
||||
[
|
||||
{
|
||||
"rom_id": item.rom.id,
|
||||
"score": item.score,
|
||||
"reasons": item.reasons,
|
||||
"seed_rom_id": item.seed_rom_id,
|
||||
"seed_rom_name": item.seed_rom_name,
|
||||
}
|
||||
for item in feed
|
||||
]
|
||||
)
|
||||
sync_cache.set(_cache_key(user_id, limit), payload, ex=FEED_CACHE_TTL_SECONDS)
|
||||
|
||||
|
||||
def invalidate_cached_feed(user_id: int) -> None:
|
||||
for key in sync_cache.scan_iter(f"{FEED_CACHE_PREFIX}:{user_id}:*"):
|
||||
sync_cache.delete(key)
|
||||
|
||||
|
||||
def _cache_key(user_id: int, limit: int) -> str:
|
||||
return f"{FEED_CACHE_PREFIX}:{user_id}:{limit}"
|
||||
326
backend/handler/recommendation/scoring.py
Normal file
326
backend/handler/recommendation/scoring.py
Normal file
@@ -0,0 +1,326 @@
|
||||
"""Pure scoring primitives for the recommendation engine.
|
||||
|
||||
Deliberately free of ORM and I/O so the ranking maths can be exercised
|
||||
directly in tests. Everything here operates on plain dataclasses and dicts.
|
||||
|
||||
The engine is library-relative: a facet is only as informative as it is rare
|
||||
*in this library*. A shelf of 4000 arcade games learns that "Action" says
|
||||
nothing and that "Metroidvania" says a great deal, without anyone tuning it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Final
|
||||
|
||||
# Relative pull of each facet before IDF weighting. A shared series or
|
||||
# franchise is far stronger evidence of "you will like this too" than a shared
|
||||
# genre, and platform/decade are context rather than taste.
|
||||
FACET_WEIGHTS: Final[Mapping[str, float]] = {
|
||||
"collection": 3.0,
|
||||
"franchise": 2.5,
|
||||
"genre": 1.0,
|
||||
# Below genre on purpose. A publisher spans wildly different games -- the
|
||||
# same Nintendo label covers Metroid, Tetris and Mario Kart -- so a shared
|
||||
# company is weaker evidence than a shared genre, not stronger.
|
||||
"company": 0.7,
|
||||
# Nearly every game is "Single player", so this mostly rides along; IDF
|
||||
# already flattens it and the low weight keeps it from breaking ties.
|
||||
"game_mode": 0.4,
|
||||
"platform": 0.4,
|
||||
"decade": 0.3,
|
||||
}
|
||||
|
||||
# Facets present on more than this share of the library describe the library,
|
||||
# not the game. They still contribute to the score (with a tiny IDF) but are
|
||||
# skipped when generating candidates, so "Action" never expands into a
|
||||
# postings list covering most of the shelf.
|
||||
MAX_CANDIDATE_DF_RATIO: Final = 0.20
|
||||
MAX_CANDIDATE_POSTINGS: Final = 2_000
|
||||
# ...but the ratio only makes sense once there is a library to take a ratio of.
|
||||
# Below this, expanding every token is cheap, and skipping them would leave a
|
||||
# small shelf with no candidates at all.
|
||||
MIN_CANDIDATE_DF: Final = 50
|
||||
|
||||
# Blend of the four independent signals. These sum to 1.0 so a raw score is
|
||||
# readable as "fraction of maximum possible relatedness".
|
||||
CONTENT_WEIGHT: Final = 0.55
|
||||
IGDB_PRIOR_WEIGHT: Final = 0.20
|
||||
CO_PLAY_WEIGHT: Final = 0.15
|
||||
CO_COLLECTION_WEIGHT: Final = 0.10
|
||||
|
||||
# Similar *and* worth playing: a small nudge from critic rating, capped low
|
||||
# enough that it reorders ties without overriding genuine relatedness.
|
||||
MAX_QUALITY_BONUS: Final = 0.05
|
||||
|
||||
# Release proximity matters, but only softly: a decade token already carries
|
||||
# most of the era signal.
|
||||
SAME_DECADE_TOKEN: Final = "decade"
|
||||
|
||||
|
||||
# Facets that describe the game itself rather than where it sits on the shelf.
|
||||
# A ROM carrying none of these has nothing to be similar *about*: platform and
|
||||
# decade alone would make every unmatched file in a folder a perfect match for
|
||||
# every other, since both vectors normalise to the same thing.
|
||||
TASTE_FACETS: Final[frozenset[str]] = frozenset(
|
||||
{"genre", "franchise", "collection", "company", "game_mode"}
|
||||
)
|
||||
|
||||
|
||||
def has_taste_signal(tokens: Sequence[str]) -> bool:
|
||||
"""Whether a ROM carries any facet worth computing similarity from."""
|
||||
return any(token_facet(token) in TASTE_FACETS for token in tokens)
|
||||
|
||||
|
||||
def make_token(facet: str, value: str) -> str:
|
||||
"""Namespace a facet value so genre:Action never collides with tag:Action."""
|
||||
return f"{facet}:{value}"
|
||||
|
||||
|
||||
def token_facet(token: str) -> str:
|
||||
return token.split(":", 1)[0]
|
||||
|
||||
|
||||
def token_value(token: str) -> str:
|
||||
return token.split(":", 1)[1] if ":" in token else token
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RomFeatures:
|
||||
"""Everything the scorer needs about one ROM."""
|
||||
|
||||
rom_id: int
|
||||
platform_id: int
|
||||
tokens: tuple[str, ...] = ()
|
||||
average_rating: float | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ScoredNeighbour:
|
||||
"""One edge of the item-item graph, with its explanation."""
|
||||
|
||||
rom_id: int
|
||||
score: float
|
||||
reasons: list[dict[str, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def extract_tokens(
|
||||
*,
|
||||
platform_id: int,
|
||||
genres: Sequence[str] | None = None,
|
||||
franchises: Sequence[str] | None = None,
|
||||
collections: Sequence[str] | None = None,
|
||||
companies: Sequence[str] | None = None,
|
||||
game_modes: Sequence[str] | None = None,
|
||||
first_release_date: int | None = None,
|
||||
) -> tuple[str, ...]:
|
||||
"""Flatten a ROM's metadata into namespaced, deduplicated feature tokens."""
|
||||
tokens: list[str] = []
|
||||
|
||||
for facet, values in (
|
||||
("genre", genres),
|
||||
("franchise", franchises),
|
||||
("collection", collections),
|
||||
("company", companies),
|
||||
("game_mode", game_modes),
|
||||
):
|
||||
for value in values or ():
|
||||
cleaned = (value or "").strip()
|
||||
if cleaned:
|
||||
tokens.append(make_token(facet, cleaned))
|
||||
|
||||
tokens.append(make_token("platform", str(platform_id)))
|
||||
|
||||
year = release_year_from_epoch(first_release_date)
|
||||
if year is not None:
|
||||
tokens.append(make_token(SAME_DECADE_TOKEN, str(year // 10 * 10)))
|
||||
|
||||
# dict.fromkeys keeps first-seen order, which keeps reasons deterministic.
|
||||
return tuple(dict.fromkeys(tokens))
|
||||
|
||||
|
||||
def release_year_from_epoch(first_release_date: int | None) -> int | None:
|
||||
"""Metadata stores release dates as a UTC epoch in seconds."""
|
||||
if not first_release_date:
|
||||
return None
|
||||
try:
|
||||
# Guard against the occasional millisecond value from a bad provider row.
|
||||
seconds = (
|
||||
first_release_date // 1000
|
||||
if abs(first_release_date) > 10_000_000_000
|
||||
else first_release_date
|
||||
)
|
||||
return 1970 + int(seconds // 31_556_952)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def compute_idf(
|
||||
documents: Iterable[Sequence[str]], total_documents: int
|
||||
) -> dict[str, float]:
|
||||
"""Inverse document frequency over the library's token vocabulary.
|
||||
|
||||
Uses the BM25 form, ``ln(1 + (N - df + 0.5) / (df + 0.5))``. The simpler
|
||||
``ln(1 + N / (1 + df))`` was tried first and discriminates far too weakly:
|
||||
a token on every ROM still scored ~0.69 against ~1.9 for a rare one, so
|
||||
"Single player" (present on nearly every game) kept enough weight to pull
|
||||
unrelated titles above genuine genre matches. BM25 drives the universal
|
||||
token to ~0.02 while leaving the rare one untouched, and stays positive on
|
||||
tiny libraries where a plain ``ln(N / df)`` collapses every token to zero.
|
||||
"""
|
||||
if total_documents <= 0:
|
||||
return {}
|
||||
|
||||
document_frequency: Counter[str] = Counter()
|
||||
for tokens in documents:
|
||||
document_frequency.update(set(tokens))
|
||||
|
||||
return {
|
||||
token: math.log(1 + (total_documents - df + 0.5) / (df + 0.5))
|
||||
for token, df in document_frequency.items()
|
||||
}
|
||||
|
||||
|
||||
def build_vector(tokens: Sequence[str], idf: Mapping[str, float]) -> dict[str, float]:
|
||||
"""L2-normalised sparse vector, so cosine is a plain dot product.
|
||||
|
||||
Normalising also stops metadata-rich ROMs from dominating every candidate
|
||||
list purely by carrying more tokens than everything else.
|
||||
"""
|
||||
raw = {
|
||||
token: FACET_WEIGHTS.get(token_facet(token), 1.0) * idf.get(token, 0.0)
|
||||
for token in tokens
|
||||
}
|
||||
raw = {token: weight for token, weight in raw.items() if weight > 0}
|
||||
|
||||
norm = math.sqrt(sum(weight * weight for weight in raw.values()))
|
||||
if norm == 0:
|
||||
return {}
|
||||
|
||||
return {token: weight / norm for token, weight in raw.items()}
|
||||
|
||||
|
||||
def content_similarity(left: Mapping[str, float], right: Mapping[str, float]) -> float:
|
||||
"""Cosine similarity of two normalised vectors."""
|
||||
# Iterate the smaller side; token overlap is sparse.
|
||||
if len(left) > len(right):
|
||||
left, right = right, left
|
||||
return sum(
|
||||
weight * right[token] for token, weight in left.items() if token in right
|
||||
)
|
||||
|
||||
|
||||
def shared_reasons(
|
||||
left: Mapping[str, float],
|
||||
right: Mapping[str, float],
|
||||
*,
|
||||
limit: int = 3,
|
||||
) -> list[dict[str, str]]:
|
||||
"""The facets that actually drove the score, strongest first.
|
||||
|
||||
These are what the UI renders as "Same series as Super Metroid" rather
|
||||
than an unexplained list of covers.
|
||||
"""
|
||||
contributions = [
|
||||
(weight * right[token], token)
|
||||
for token, weight in left.items()
|
||||
if token in right
|
||||
]
|
||||
contributions.sort(key=lambda pair: (-pair[0], pair[1]))
|
||||
|
||||
reasons: list[dict[str, str]] = []
|
||||
seen_facets: set[str] = set()
|
||||
for _, token in contributions:
|
||||
facet = token_facet(token)
|
||||
# One reason per facet: three shared genres reads worse than a genre,
|
||||
# a company and a decade.
|
||||
if facet in seen_facets or facet == "platform":
|
||||
continue
|
||||
seen_facets.add(facet)
|
||||
reasons.append({"facet": facet, "value": token_value(token)})
|
||||
if len(reasons) >= limit:
|
||||
break
|
||||
|
||||
return reasons
|
||||
|
||||
|
||||
def quality_bonus(average_rating: float | None) -> float:
|
||||
"""Map a 0-100 critic rating onto a small additive bonus."""
|
||||
if not average_rating:
|
||||
return 0.0
|
||||
normalised = max(0.0, min(1.0, average_rating / 100.0))
|
||||
return MAX_QUALITY_BONUS * normalised
|
||||
|
||||
|
||||
def blend(
|
||||
*,
|
||||
content: float,
|
||||
igdb_prior: float = 0.0,
|
||||
co_play: float = 0.0,
|
||||
co_collection: float = 0.0,
|
||||
average_rating: float | None = None,
|
||||
) -> float:
|
||||
"""Combine the independent signals into a single 0-1-ish score."""
|
||||
return (
|
||||
CONTENT_WEIGHT * content
|
||||
+ IGDB_PRIOR_WEIGHT * _clamp(igdb_prior)
|
||||
+ CO_PLAY_WEIGHT * _clamp(co_play)
|
||||
+ CO_COLLECTION_WEIGHT * _clamp(co_collection)
|
||||
+ quality_bonus(average_rating)
|
||||
)
|
||||
|
||||
|
||||
def _clamp(value: float) -> float:
|
||||
return max(0.0, min(1.0, value))
|
||||
|
||||
|
||||
def build_inverted_index(
|
||||
features: Mapping[int, RomFeatures],
|
||||
) -> dict[str, list[int]]:
|
||||
"""Token -> ROM ids, used to avoid the O(n^2) all-pairs comparison.
|
||||
|
||||
Only ROMs sharing at least one *discriminative* token are ever scored
|
||||
against each other, which is what keeps a 50k-ROM library tractable.
|
||||
"""
|
||||
postings: dict[str, list[int]] = defaultdict(list)
|
||||
for rom_id, feature in features.items():
|
||||
for token in feature.tokens:
|
||||
postings[token].append(rom_id)
|
||||
return dict(postings)
|
||||
|
||||
|
||||
def candidate_ids(
|
||||
feature: RomFeatures,
|
||||
postings: Mapping[str, Sequence[int]],
|
||||
total_documents: int,
|
||||
) -> set[int]:
|
||||
"""Candidate neighbours for one ROM, drawn from its rarest facets."""
|
||||
df_cap = max(MIN_CANDIDATE_DF, int(total_documents * MAX_CANDIDATE_DF_RATIO))
|
||||
candidates: set[int] = set()
|
||||
|
||||
for token in feature.tokens:
|
||||
bucket = postings.get(token)
|
||||
if not bucket:
|
||||
continue
|
||||
if len(bucket) > df_cap or len(bucket) > MAX_CANDIDATE_POSTINGS:
|
||||
continue
|
||||
candidates.update(bucket)
|
||||
|
||||
candidates.discard(feature.rom_id)
|
||||
return candidates
|
||||
|
||||
|
||||
def normalise_co_occurrence(
|
||||
pair_count: float, left_total: int, right_total: int
|
||||
) -> float:
|
||||
"""Cosine-style normalisation of a raw co-occurrence count.
|
||||
|
||||
Without this, whatever ROM sits in the most collections (or has the most
|
||||
play sessions) would look related to everything.
|
||||
"""
|
||||
if pair_count <= 0 or left_total <= 0 or right_total <= 0:
|
||||
return 0.0
|
||||
return min(1.0, pair_count / math.sqrt(left_total * right_total))
|
||||
@@ -48,6 +48,7 @@ from endpoints.netplay import router as netplay_router
|
||||
from endpoints.permissions import router as permissions_router
|
||||
from endpoints.platform import router as platform_router
|
||||
from endpoints.play_sessions import router as play_sessions_router
|
||||
from endpoints.recommendations import router as recommendations_router
|
||||
from endpoints.roms import router as rom_router
|
||||
from endpoints.saves import router as saves_router
|
||||
from endpoints.screenshots import router as screenshots_router
|
||||
@@ -177,6 +178,7 @@ app.include_router(device_auth_router, prefix="/api")
|
||||
app.include_router(play_sessions_router, prefix="/api")
|
||||
app.include_router(platform_router, prefix="/api")
|
||||
app.include_router(rom_router, prefix="/api")
|
||||
app.include_router(recommendations_router, prefix="/api")
|
||||
app.include_router(music_router, prefix="/api")
|
||||
app.include_router(music_playlists_router, prefix="/api")
|
||||
app.include_router(search_router, prefix="/api")
|
||||
|
||||
63
backend/models/recommendation.py
Normal file
63
backend/models/recommendation.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from sqlalchemy import Float, ForeignKey, Index
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import BaseModel
|
||||
from utils.database import CustomJSON
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom
|
||||
|
||||
|
||||
class RomSimilarity(BaseModel):
|
||||
"""A precomputed edge of the item-item similarity graph.
|
||||
|
||||
Written wholesale by the recommendations task, never incrementally, so the
|
||||
rows are always consistent with a single IDF snapshot of the library. Only
|
||||
the top neighbours of each ROM are kept, which bounds the table at
|
||||
roughly ``rom_count * MAX_NEIGHBOURS`` rows.
|
||||
|
||||
Edges are stored in both directions. The scoring itself is symmetric, but
|
||||
the per-ROM top-N cut is not (a niche game's best neighbour may not
|
||||
reciprocate), and duplicating avoids an OR across two indexed columns on
|
||||
every read.
|
||||
"""
|
||||
|
||||
__tablename__ = "rom_similarity"
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_rom_similarity_rom_score", "rom_id", "score"),
|
||||
Index("idx_rom_similarity_related_rom_id", "related_rom_id"),
|
||||
)
|
||||
|
||||
rom_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
related_rom_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
score: Mapped[float] = mapped_column(Float(), nullable=False)
|
||||
|
||||
# The facets that drove the score, e.g. [{"facet": "franchise",
|
||||
# "value": "Metroid"}], so the UI can say why without recomputing.
|
||||
reasons: Mapped[list[dict[str, Any]] | None] = mapped_column(
|
||||
CustomJSON(), default=[]
|
||||
)
|
||||
|
||||
# No ORM-level delete cascade: ROMs are removed with a bulk `delete()`
|
||||
# (see `db_rom_handler.delete_rom`), which never runs one. The foreign
|
||||
# keys' ON DELETE CASCADE is what actually clears both directions.
|
||||
rom: Mapped[Rom] = relationship(
|
||||
"Rom",
|
||||
foreign_keys=[rom_id],
|
||||
back_populates="similar_roms",
|
||||
lazy="raise",
|
||||
passive_deletes=True,
|
||||
)
|
||||
related_rom: Mapped[Rom] = relationship(
|
||||
"Rom", foreign_keys=[related_rom_id], lazy="raise", passive_deletes=True
|
||||
)
|
||||
@@ -87,6 +87,7 @@ if TYPE_CHECKING:
|
||||
from models.assets import Save, Screenshot, State
|
||||
from models.collection import Collection
|
||||
from models.platform import Platform
|
||||
from models.recommendation import RomSimilarity
|
||||
from models.user import User
|
||||
|
||||
|
||||
@@ -494,6 +495,13 @@ class Rom(BaseModel):
|
||||
lazy="raise",
|
||||
back_populates="roms",
|
||||
)
|
||||
similar_roms: Mapped[list[RomSimilarity]] = relationship(
|
||||
"RomSimilarity",
|
||||
foreign_keys="RomSimilarity.rom_id",
|
||||
lazy="raise",
|
||||
back_populates="rom",
|
||||
passive_deletes=True,
|
||||
)
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@@ -7,6 +7,7 @@ from opentelemetry import trace
|
||||
from rq.job import Job
|
||||
|
||||
from config import (
|
||||
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS,
|
||||
ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP,
|
||||
ENABLE_SCHEDULED_RESCAN,
|
||||
ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
|
||||
@@ -32,6 +33,7 @@ from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY
|
||||
from tasks.manual.recompute_save_content_hashes import (
|
||||
recompute_save_content_hashes_task,
|
||||
)
|
||||
from tasks.scheduled.build_recommendations import build_recommendations_task
|
||||
from tasks.scheduled.cleanup_netplay import cleanup_netplay_task
|
||||
from tasks.scheduled.cleanup_orphaned_resources import cleanup_orphaned_resources_task
|
||||
from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task
|
||||
@@ -158,6 +160,9 @@ async def main() -> None:
|
||||
if ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP:
|
||||
log.info("Starting scheduled convert images to webp")
|
||||
convert_images_to_webp_task.init()
|
||||
if ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS:
|
||||
log.info("Starting scheduled recommendations index build")
|
||||
build_recommendations_task.init()
|
||||
_enqueue_convert_images_to_webp()
|
||||
if ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC:
|
||||
log.info("Starting scheduled RetroAchievements progress sync")
|
||||
|
||||
57
backend/tasks/scheduled/build_recommendations.py
Normal file
57
backend/tasks/scheduled/build_recommendations.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Rebuilds the item-item similarity graph that backs recommendations."""
|
||||
|
||||
from config import (
|
||||
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS,
|
||||
SCHEDULED_BUILD_RECOMMENDATIONS_CRON,
|
||||
)
|
||||
from handler.recommendation import BuildStats, SimilarityBuilder
|
||||
from logger.logger import log
|
||||
from tasks.tasks import PeriodicTask, TaskType
|
||||
from utils.context import initialize_context
|
||||
|
||||
from . import UpdateStats
|
||||
|
||||
|
||||
class BuildRecommendationsTask(PeriodicTask):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
title="Build recommendations index",
|
||||
description=(
|
||||
"Rebuilds the similar-games index from library metadata, "
|
||||
"play history and collections"
|
||||
),
|
||||
task_type=TaskType.UPDATE,
|
||||
enabled=ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS,
|
||||
manual_run=True,
|
||||
cron_string=SCHEDULED_BUILD_RECOMMENDATIONS_CRON,
|
||||
func="tasks.scheduled.build_recommendations.build_recommendations_task.run",
|
||||
)
|
||||
|
||||
@initialize_context()
|
||||
async def run(self, force: bool = False) -> dict[str, int]:
|
||||
if not self.enabled and not force:
|
||||
log.info(f"Scheduled {self.description} not enabled, unscheduling...")
|
||||
self.unschedule()
|
||||
return UpdateStats().to_dict()
|
||||
|
||||
log.info("Building recommendations index...")
|
||||
|
||||
update_stats = UpdateStats()
|
||||
|
||||
def report(stats: BuildStats) -> None:
|
||||
update_stats.update(processed=stats.roms_indexed, total=stats.total)
|
||||
|
||||
try:
|
||||
build_stats = SimilarityBuilder(progress=report).build()
|
||||
except Exception:
|
||||
log.error("Failed to build recommendations index", exc_info=True)
|
||||
raise
|
||||
|
||||
log.info(
|
||||
f"Recommendations index rebuilt: {build_stats.edges_written} edges "
|
||||
f"across {build_stats.roms_indexed} ROMs"
|
||||
)
|
||||
return update_stats.to_dict()
|
||||
|
||||
|
||||
build_recommendations_task = BuildRecommendationsTask()
|
||||
275
backend/tests/endpoints/test_recommendations.py
Normal file
275
backend/tests/endpoints/test_recommendations.py
Normal file
@@ -0,0 +1,275 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
from tests.handler.recommendation.test_builder import make_rom
|
||||
|
||||
from handler.database import db_rom_handler
|
||||
from handler.recommendation import SimilarityBuilder, invalidate_cached_feed
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
|
||||
|
||||
def build_library(platform: Platform) -> dict[str, Rom]:
|
||||
library = {
|
||||
"metroid": make_rom(
|
||||
platform,
|
||||
"Super Metroid",
|
||||
igdb_id=5001,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Metroid"],
|
||||
companies=["Nintendo"],
|
||||
),
|
||||
"metroid_2": make_rom(
|
||||
platform,
|
||||
"Metroid Fusion",
|
||||
igdb_id=5002,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Metroid"],
|
||||
companies=["Nintendo"],
|
||||
),
|
||||
"castlevania": make_rom(
|
||||
platform,
|
||||
"Castlevania SOTN",
|
||||
igdb_id=5003,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Castlevania"],
|
||||
companies=["Konami"],
|
||||
),
|
||||
}
|
||||
SimilarityBuilder().build()
|
||||
return library
|
||||
|
||||
|
||||
def test_similar_roms_returns_library_games(
|
||||
client: TestClient, access_token: str, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
response = client.get(
|
||||
f"/api/roms/{library['metroid'].id}/similar",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
assert body
|
||||
returned_ids = [entry["rom"]["id"] for entry in body]
|
||||
assert library["metroid_2"].id in returned_ids
|
||||
# The source game is never among its own recommendations.
|
||||
assert library["metroid"].id not in returned_ids
|
||||
|
||||
|
||||
def test_similar_roms_are_ordered_by_score(
|
||||
client: TestClient, access_token: str, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
body = client.get(
|
||||
f"/api/roms/{library['metroid'].id}/similar",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
).json()
|
||||
|
||||
scores = [entry["score"] for entry in body]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
|
||||
|
||||
def test_similar_roms_include_reasons(
|
||||
client: TestClient, access_token: str, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
body = client.get(
|
||||
f"/api/roms/{library['metroid'].id}/similar",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
).json()
|
||||
|
||||
match = next(
|
||||
entry for entry in body if entry["rom"]["id"] == library["metroid_2"].id
|
||||
)
|
||||
assert {"facet": "franchise", "value": "Metroid"} in match["reasons"]
|
||||
|
||||
|
||||
def test_similar_roms_respects_the_limit(
|
||||
client: TestClient, access_token: str, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
body = client.get(
|
||||
f"/api/roms/{library['metroid'].id}/similar?limit=1",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
).json()
|
||||
|
||||
assert len(body) == 1
|
||||
|
||||
|
||||
def test_similar_roms_rejects_an_out_of_range_limit(
|
||||
client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/similar?limit=999",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
|
||||
|
||||
|
||||
def test_similar_roms_404s_for_an_unknown_rom(client: TestClient, access_token: str):
|
||||
response = client.get(
|
||||
"/api/roms/99999999/similar",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_similar_roms_requires_auth(client: TestClient, rom: Rom):
|
||||
assert client.get(f"/api/roms/{rom.id}/similar").status_code in (
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
|
||||
|
||||
def test_similar_roms_is_empty_before_the_index_is_built(
|
||||
client: TestClient, access_token: str, rom: Rom
|
||||
):
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/similar",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.json() == []
|
||||
|
||||
|
||||
def test_recommendations_are_seeded_by_play_history(
|
||||
client: TestClient, access_token: str, admin_user: User, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
rom_user = db_rom_handler.get_rom_user(library["metroid"].id, admin_user.id)
|
||||
if rom_user is None:
|
||||
rom_user = db_rom_handler.add_rom_user(library["metroid"].id, admin_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id,
|
||||
{"rating": 10, "last_played": datetime.now(timezone.utc)},
|
||||
)
|
||||
invalidate_cached_feed(admin_user.id)
|
||||
|
||||
response = client.get(
|
||||
"/api/recommendations",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
returned_ids = [entry["rom"]["id"] for entry in body]
|
||||
|
||||
# Loving Super Metroid should surface Metroid Fusion, and never re-suggest
|
||||
# the seed itself.
|
||||
assert library["metroid_2"].id in returned_ids
|
||||
assert library["metroid"].id not in returned_ids
|
||||
|
||||
|
||||
def test_recommendations_attribute_the_seed_game(
|
||||
client: TestClient, access_token: str, admin_user: User, platform: Platform
|
||||
):
|
||||
library = build_library(platform)
|
||||
|
||||
rom_user = db_rom_handler.get_rom_user(library["metroid"].id, admin_user.id)
|
||||
if rom_user is None:
|
||||
rom_user = db_rom_handler.add_rom_user(library["metroid"].id, admin_user.id)
|
||||
db_rom_handler.update_rom_user(
|
||||
rom_user.id,
|
||||
{"rating": 10, "last_played": datetime.now(timezone.utc)},
|
||||
)
|
||||
invalidate_cached_feed(admin_user.id)
|
||||
|
||||
body = client.get(
|
||||
"/api/recommendations",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
).json()
|
||||
|
||||
match = next(
|
||||
entry for entry in body if entry["rom"]["id"] == library["metroid_2"].id
|
||||
)
|
||||
assert match["seed_rom_id"] == library["metroid"].id
|
||||
assert match["seed_rom_name"] == "Super Metroid"
|
||||
|
||||
|
||||
def test_rating_a_game_reshapes_the_feed_without_an_explicit_refresh(
|
||||
client: TestClient, access_token: str, admin_user: User, platform: Platform
|
||||
):
|
||||
"""Updating rom_user must drop the cached feed, not wait out its TTL."""
|
||||
library = build_library(platform)
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
invalidate_cached_feed(admin_user.id)
|
||||
|
||||
# Prime the cache while there is no history at all.
|
||||
before = client.get("/api/recommendations", headers=headers).json()
|
||||
assert library["metroid_2"].id not in [entry["rom"]["id"] for entry in before]
|
||||
|
||||
response = client.put(
|
||||
f"/api/roms/{library['metroid'].id}/props?update_last_played=true",
|
||||
headers=headers,
|
||||
json={"rating": 10},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
after = client.get("/api/recommendations", headers=headers).json()
|
||||
assert library["metroid_2"].id in [entry["rom"]["id"] for entry in after]
|
||||
|
||||
|
||||
def test_recommendations_fall_back_when_there_is_no_history(
|
||||
client: TestClient, access_token: str, admin_user: User, platform: Platform
|
||||
):
|
||||
make_rom(
|
||||
platform,
|
||||
"Acclaimed Game",
|
||||
igdb_id=6001,
|
||||
genres=["RPG"],
|
||||
average_rating=95.0,
|
||||
)
|
||||
SimilarityBuilder().build()
|
||||
invalidate_cached_feed(admin_user.id)
|
||||
|
||||
response = client.get(
|
||||
"/api/recommendations",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
assert body
|
||||
assert all(
|
||||
entry["reasons"] == [{"facet": "top_rated", "value": ""}] for entry in body
|
||||
)
|
||||
|
||||
|
||||
def test_recommendations_respect_the_limit(
|
||||
client: TestClient, access_token: str, admin_user: User, platform: Platform
|
||||
):
|
||||
build_library(platform)
|
||||
invalidate_cached_feed(admin_user.id)
|
||||
|
||||
body = client.get(
|
||||
"/api/recommendations?limit=1",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
).json()
|
||||
|
||||
assert len(body) <= 1
|
||||
|
||||
|
||||
def test_recommendations_reject_an_out_of_range_limit(
|
||||
client: TestClient, access_token: str
|
||||
):
|
||||
response = client.get(
|
||||
"/api/recommendations?limit=500",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
|
||||
|
||||
|
||||
def test_recommendations_require_auth(client: TestClient):
|
||||
assert client.get("/api/recommendations").status_code in (
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
0
backend/tests/handler/recommendation/__init__.py
Normal file
0
backend/tests/handler/recommendation/__init__.py
Normal file
280
backend/tests/handler/recommendation/test_builder.py
Normal file
280
backend/tests/handler/recommendation/test_builder.py
Normal file
@@ -0,0 +1,280 @@
|
||||
"""End-to-end checks for the similarity index build.
|
||||
|
||||
Metadata is seeded by writing `roms.igdb_metadata`, because `roms_metadata` is
|
||||
a view over generated columns and `roms_facets` is trigger-maintained from the
|
||||
same source: writing the blob is what drives both.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.database import db_recommendation_handler, db_rom_handler
|
||||
from handler.recommendation import SimilarityBuilder
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
|
||||
|
||||
def make_rom(
|
||||
platform: Platform,
|
||||
name: str,
|
||||
*,
|
||||
igdb_id: int | None = None,
|
||||
genres: list[str] | None = None,
|
||||
franchises: list[str] | None = None,
|
||||
collections: list[str] | None = None,
|
||||
companies: list[str] | None = None,
|
||||
similar_igdb_ids: list[int] | None = None,
|
||||
average_rating: float | None = None,
|
||||
) -> Rom:
|
||||
metadata: dict = {
|
||||
"genres": genres or [],
|
||||
"franchises": franchises or [],
|
||||
"collections": collections or [],
|
||||
"companies": companies or [],
|
||||
"game_modes": [],
|
||||
}
|
||||
if average_rating is not None:
|
||||
# IGDB's total_rating is carried as a string; the generated column casts it.
|
||||
metadata["total_rating"] = str(average_rating)
|
||||
if similar_igdb_ids:
|
||||
metadata["similar_games"] = [
|
||||
{"id": similar_id, "name": f"game-{similar_id}", "type": "similar"}
|
||||
for similar_id in similar_igdb_ids
|
||||
]
|
||||
|
||||
# Set on insert rather than updated afterwards: the generated columns (and
|
||||
# the roms_facets triggers) derive from this blob, so one write is enough.
|
||||
return db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
name=name,
|
||||
slug=name.lower().replace(" ", "-"),
|
||||
fs_name=f"{name}.zip",
|
||||
fs_name_no_tags=name,
|
||||
fs_name_no_ext=name,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
igdb_id=igdb_id,
|
||||
igdb_metadata=metadata,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library(platform: Platform) -> dict[str, Rom]:
|
||||
"""A small library with one tight cluster and one unrelated outlier.
|
||||
|
||||
Deliberately padded with unrelated games. IDF is relative to the library,
|
||||
so on a four-game shelf where three are platformers "Platform" carries
|
||||
almost no weight and a genre-only match drops under MIN_EDGE_SCORE -- a
|
||||
degenerate case that says nothing about ranking on a real library.
|
||||
"""
|
||||
for index, (genre, franchise, company) in enumerate(
|
||||
[
|
||||
("Racing", "Outrun", "Sega"),
|
||||
("Shooter", "Gradius", "Konami"),
|
||||
("Sport", "Tennis", "Namco"),
|
||||
("Fighting", "Street Fighter", "Capcom"),
|
||||
("Simulation", "Sim", "Maxis"),
|
||||
]
|
||||
):
|
||||
make_rom(
|
||||
platform,
|
||||
f"Filler {index}",
|
||||
igdb_id=9000 + index,
|
||||
genres=[genre],
|
||||
franchises=[franchise],
|
||||
companies=[company],
|
||||
)
|
||||
|
||||
return {
|
||||
"metroid": make_rom(
|
||||
platform,
|
||||
"Super Metroid",
|
||||
igdb_id=1001,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Metroid"],
|
||||
companies=["Nintendo"],
|
||||
),
|
||||
"metroid_2": make_rom(
|
||||
platform,
|
||||
"Metroid Fusion",
|
||||
igdb_id=1002,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Metroid"],
|
||||
companies=["Nintendo"],
|
||||
),
|
||||
"castlevania": make_rom(
|
||||
platform,
|
||||
"Castlevania SOTN",
|
||||
igdb_id=1003,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Castlevania"],
|
||||
companies=["Konami"],
|
||||
),
|
||||
"puzzle": make_rom(
|
||||
platform,
|
||||
"Tetris",
|
||||
igdb_id=1004,
|
||||
genres=["Puzzle"],
|
||||
companies=["Nintendo"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def test_build_creates_edges_for_related_games(library: dict[str, Rom]):
|
||||
# Counts are >= rather than ==: the builder indexes the whole library, so
|
||||
# ROMs left behind by other tests in this worker's database count too.
|
||||
stats = SimilarityBuilder().build()
|
||||
|
||||
assert stats.roms_indexed >= len(library)
|
||||
assert stats.edges_written > 0
|
||||
|
||||
edges = db_recommendation_handler.get_similar_rom_edges(library["metroid"].id)
|
||||
assert [edge.rom_id for edge in edges]
|
||||
|
||||
|
||||
def test_same_franchise_outranks_same_genre(library: dict[str, Rom]):
|
||||
SimilarityBuilder().build()
|
||||
|
||||
edges = db_recommendation_handler.get_similar_rom_edges(library["metroid"].id)
|
||||
ranked = [edge.rom_id for edge in edges]
|
||||
|
||||
# Metroid Fusion shares the franchise; Castlevania only shares genres.
|
||||
assert ranked.index(library["metroid_2"].id) < ranked.index(
|
||||
library["castlevania"].id
|
||||
)
|
||||
|
||||
|
||||
def test_unrelated_game_scores_below_a_franchise_match(library: dict[str, Rom]):
|
||||
SimilarityBuilder().build()
|
||||
|
||||
by_rom = {
|
||||
edge.rom_id: edge.score
|
||||
for edge in db_recommendation_handler.get_similar_rom_edges(
|
||||
library["metroid"].id
|
||||
)
|
||||
}
|
||||
|
||||
assert by_rom[library["metroid_2"].id] > by_rom.get(library["puzzle"].id, 0.0)
|
||||
|
||||
|
||||
def test_edges_carry_a_human_readable_reason(library: dict[str, Rom]):
|
||||
SimilarityBuilder().build()
|
||||
|
||||
edges = db_recommendation_handler.get_similar_rom_edges(library["metroid"].id)
|
||||
match = next(edge for edge in edges if edge.rom_id == library["metroid_2"].id)
|
||||
|
||||
assert {"facet": "franchise", "value": "Metroid"} in match.reasons
|
||||
|
||||
|
||||
def test_a_rom_is_never_similar_to_itself(library: dict[str, Rom]):
|
||||
SimilarityBuilder().build()
|
||||
|
||||
for rom in library.values():
|
||||
neighbours = db_recommendation_handler.get_similar_rom_edges(rom.id)
|
||||
assert rom.id not in {edge.rom_id for edge in neighbours}
|
||||
|
||||
|
||||
def test_region_duplicates_are_not_recommendations(platform: Platform):
|
||||
"""Two files of the same game must never recommend each other."""
|
||||
usa = make_rom(
|
||||
platform,
|
||||
"Chrono Trigger (USA)",
|
||||
igdb_id=2001,
|
||||
genres=["RPG"],
|
||||
franchises=["Chrono"],
|
||||
)
|
||||
europe = make_rom(
|
||||
platform,
|
||||
"Chrono Trigger (Europe)",
|
||||
igdb_id=2001,
|
||||
genres=["RPG"],
|
||||
franchises=["Chrono"],
|
||||
)
|
||||
|
||||
SimilarityBuilder().build()
|
||||
|
||||
neighbours = db_recommendation_handler.get_similar_rom_edges(usa.id)
|
||||
assert europe.id not in {edge.rom_id for edge in neighbours}
|
||||
|
||||
|
||||
def test_igdb_similar_games_link_owned_roms(platform: Platform):
|
||||
"""IGDB's prior should create an edge even without shared metadata."""
|
||||
source = make_rom(
|
||||
platform,
|
||||
"Source Game",
|
||||
igdb_id=3001,
|
||||
genres=["Shooter"],
|
||||
similar_igdb_ids=[3002],
|
||||
)
|
||||
target = make_rom(platform, "Target Game", igdb_id=3002, genres=["Racing"])
|
||||
make_rom(platform, "Unrelated Game", igdb_id=3003, genres=["Racing"])
|
||||
|
||||
SimilarityBuilder().build()
|
||||
|
||||
neighbours = db_recommendation_handler.get_similar_rom_edges(source.id)
|
||||
assert target.id in {edge.rom_id for edge in neighbours}
|
||||
|
||||
|
||||
def test_rebuild_replaces_edges_rather_than_duplicating(library: dict[str, Rom]):
|
||||
first = SimilarityBuilder().build()
|
||||
second = SimilarityBuilder().build()
|
||||
|
||||
assert first.edges_written == second.edges_written
|
||||
assert db_recommendation_handler.count_similarity_edges() == second.edges_written
|
||||
|
||||
|
||||
def test_unidentified_roms_are_not_related_to_each_other(platform: Platform):
|
||||
"""Sharing only a platform is not similarity.
|
||||
|
||||
Two files that never matched a provider carry nothing but platform (and
|
||||
maybe decade), which normalise to identical vectors -- they would score a
|
||||
perfect match against each other if they were indexed at all.
|
||||
"""
|
||||
first = make_rom(platform, "Unknown Game A")
|
||||
second = make_rom(platform, "Unknown Game B")
|
||||
|
||||
stats = SimilarityBuilder().build()
|
||||
|
||||
assert stats.roms_without_metadata >= 2
|
||||
assert db_recommendation_handler.get_similar_rom_edges(first.id) == []
|
||||
assert db_recommendation_handler.get_similar_rom_edges(second.id) == []
|
||||
|
||||
|
||||
def test_an_identified_rom_is_not_related_to_an_unidentified_one(platform: Platform):
|
||||
identified = make_rom(
|
||||
platform, "Known Game", igdb_id=4001, genres=["RPG"], franchises=["Saga"]
|
||||
)
|
||||
unidentified = make_rom(platform, "Mystery File")
|
||||
|
||||
SimilarityBuilder().build()
|
||||
|
||||
neighbours = db_recommendation_handler.get_similar_rom_edges(identified.id)
|
||||
assert unidentified.id not in {edge.rom_id for edge in neighbours}
|
||||
|
||||
|
||||
def test_deleting_a_rom_clears_its_edges_in_both_directions(library: dict[str, Rom]):
|
||||
"""Edges are cleaned up by the foreign keys, not by an ORM cascade.
|
||||
|
||||
ROMs are removed with a bulk delete, which never triggers an ORM-level
|
||||
cascade, so inbound edges would be left dangling without ON DELETE CASCADE
|
||||
on both columns.
|
||||
"""
|
||||
SimilarityBuilder().build()
|
||||
deleted_id = library["metroid"].id
|
||||
|
||||
assert db_recommendation_handler.get_similar_rom_edges(deleted_id)
|
||||
|
||||
db_rom_handler.delete_rom(deleted_id)
|
||||
|
||||
assert db_recommendation_handler.get_similar_rom_edges(deleted_id) == []
|
||||
# The surviving ROM must not still point at the deleted one.
|
||||
survivors = db_recommendation_handler.get_similar_rom_edges(library["metroid_2"].id)
|
||||
assert deleted_id not in {edge.rom_id for edge in survivors}
|
||||
|
||||
|
||||
def test_build_on_an_empty_library_is_a_no_op():
|
||||
stats = SimilarityBuilder().build()
|
||||
|
||||
assert stats.roms_indexed == 0
|
||||
assert stats.edges_written == 0
|
||||
127
backend/tests/handler/recommendation/test_feed.py
Normal file
127
backend/tests/handler/recommendation/test_feed.py
Normal file
@@ -0,0 +1,127 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.database.recommendations_handler import UserAffinityRow
|
||||
from handler.recommendation.feed import (
|
||||
MIN_RECENCY_FACTOR,
|
||||
RECENCY_HALFLIFE_DAYS,
|
||||
seed_affinity,
|
||||
)
|
||||
from models.rom import RomUserStatus
|
||||
|
||||
NOW = datetime(2026, 8, 7, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def affinity_row(**overrides) -> UserAffinityRow:
|
||||
defaults = {
|
||||
"rom_id": 1,
|
||||
"rating": None,
|
||||
"difficulty": None,
|
||||
"completion": None,
|
||||
"status": None,
|
||||
"last_played": NOW,
|
||||
"now_playing": False,
|
||||
"backlogged": False,
|
||||
"hidden": False,
|
||||
"playtime_ms": 0,
|
||||
}
|
||||
return UserAffinityRow(**{**defaults, **overrides})
|
||||
|
||||
|
||||
def test_high_rating_produces_a_positive_seed():
|
||||
assert seed_affinity(affinity_row(rating=10), now=NOW) > 0
|
||||
|
||||
|
||||
def test_low_rating_produces_a_negative_seed():
|
||||
# The point of a negative seed: steer the feed away from this kind of game.
|
||||
assert seed_affinity(affinity_row(rating=1), now=NOW) < 0
|
||||
|
||||
|
||||
def test_midpoint_rating_is_roughly_neutral():
|
||||
assert seed_affinity(affinity_row(rating=5), now=NOW) == pytest.approx(0, abs=0.15)
|
||||
|
||||
|
||||
def test_negative_seeds_are_damped_relative_to_positive_ones():
|
||||
liked = seed_affinity(affinity_row(rating=10), now=NOW)
|
||||
disliked = seed_affinity(affinity_row(rating=1), now=NOW)
|
||||
|
||||
assert abs(disliked) < abs(liked)
|
||||
|
||||
|
||||
def test_playtime_increases_affinity_with_diminishing_returns():
|
||||
hour = 3_600_000
|
||||
short = seed_affinity(affinity_row(playtime_ms=hour), now=NOW)
|
||||
medium = seed_affinity(affinity_row(playtime_ms=10 * hour), now=NOW)
|
||||
marathon = seed_affinity(affinity_row(playtime_ms=200 * hour), now=NOW)
|
||||
|
||||
assert short < medium <= marathon
|
||||
# Saturation: 20h to 200h must matter far less than 1h to 10h.
|
||||
assert (marathon - medium) < (medium - short)
|
||||
|
||||
|
||||
def test_completion_status_outweighs_merely_starting_a_game():
|
||||
completed = seed_affinity(
|
||||
affinity_row(status=RomUserStatus.COMPLETED_100.value), now=NOW
|
||||
)
|
||||
incomplete = seed_affinity(
|
||||
affinity_row(status=RomUserStatus.INCOMPLETE.value), now=NOW
|
||||
)
|
||||
|
||||
assert completed > incomplete > 0
|
||||
|
||||
|
||||
def test_now_playing_is_a_strong_signal():
|
||||
assert seed_affinity(affinity_row(now_playing=True), now=NOW) > seed_affinity(
|
||||
affinity_row(status=RomUserStatus.INCOMPLETE.value), now=NOW
|
||||
)
|
||||
|
||||
|
||||
def test_recent_play_outweighs_an_old_one_of_equal_rating():
|
||||
recent = seed_affinity(affinity_row(rating=10, last_played=NOW), now=NOW)
|
||||
old = seed_affinity(
|
||||
affinity_row(rating=10, last_played=NOW - timedelta(days=365)), now=NOW
|
||||
)
|
||||
|
||||
assert recent > old > 0
|
||||
|
||||
|
||||
def test_recency_decay_halves_at_the_configured_halflife():
|
||||
fresh = seed_affinity(affinity_row(rating=10, last_played=NOW), now=NOW)
|
||||
halflife = seed_affinity(
|
||||
affinity_row(
|
||||
rating=10, last_played=NOW - timedelta(days=RECENCY_HALFLIFE_DAYS)
|
||||
),
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
assert halflife == pytest.approx(fresh * 0.5, rel=0.01)
|
||||
|
||||
|
||||
def test_old_favourites_never_decay_to_nothing():
|
||||
ancient = seed_affinity(
|
||||
affinity_row(rating=10, last_played=NOW - timedelta(days=3650)), now=NOW
|
||||
)
|
||||
|
||||
assert ancient == pytest.approx(MIN_RECENCY_FACTOR, rel=0.01)
|
||||
|
||||
|
||||
def test_naive_timestamps_are_treated_as_utc():
|
||||
# MariaDB hands back naive datetimes; a crash here would break the feed.
|
||||
naive = seed_affinity(
|
||||
affinity_row(rating=10, last_played=NOW.replace(tzinfo=None)), now=NOW
|
||||
)
|
||||
aware = seed_affinity(affinity_row(rating=10, last_played=NOW), now=NOW)
|
||||
|
||||
assert naive == pytest.approx(aware)
|
||||
|
||||
|
||||
def test_a_row_with_no_signals_at_all_contributes_nothing():
|
||||
assert seed_affinity(affinity_row(last_played=None), now=NOW) == 0.0
|
||||
|
||||
|
||||
def test_a_played_but_unrated_game_still_seeds_weakly():
|
||||
weak = seed_affinity(affinity_row(last_played=NOW), now=NOW)
|
||||
rated = seed_affinity(affinity_row(rating=9, last_played=NOW), now=NOW)
|
||||
|
||||
assert 0 < weak < rated
|
||||
303
backend/tests/handler/recommendation/test_scoring.py
Normal file
303
backend/tests/handler/recommendation/test_scoring.py
Normal file
@@ -0,0 +1,303 @@
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.recommendation.scoring import (
|
||||
MAX_QUALITY_BONUS,
|
||||
RomFeatures,
|
||||
blend,
|
||||
build_inverted_index,
|
||||
build_vector,
|
||||
candidate_ids,
|
||||
compute_idf,
|
||||
content_similarity,
|
||||
extract_tokens,
|
||||
has_taste_signal,
|
||||
make_token,
|
||||
normalise_co_occurrence,
|
||||
quality_bonus,
|
||||
release_year_from_epoch,
|
||||
shared_reasons,
|
||||
)
|
||||
|
||||
# 1991-08-13, the sort of epoch value roms_metadata carries.
|
||||
SUPER_NES_ERA_EPOCH = 682_041_600
|
||||
|
||||
|
||||
def test_extract_tokens_namespaces_every_facet():
|
||||
tokens = extract_tokens(
|
||||
platform_id=7,
|
||||
genres=["Platform", "Adventure"],
|
||||
franchises=["Metroid"],
|
||||
collections=["Super Metroid"],
|
||||
companies=["Nintendo"],
|
||||
game_modes=["Single player"],
|
||||
first_release_date=SUPER_NES_ERA_EPOCH,
|
||||
)
|
||||
|
||||
assert make_token("genre", "Platform") in tokens
|
||||
assert make_token("franchise", "Metroid") in tokens
|
||||
assert make_token("collection", "Super Metroid") in tokens
|
||||
assert make_token("company", "Nintendo") in tokens
|
||||
assert make_token("game_mode", "Single player") in tokens
|
||||
assert make_token("platform", "7") in tokens
|
||||
assert make_token("decade", "1990") in tokens
|
||||
|
||||
|
||||
def test_extract_tokens_skips_blanks_and_deduplicates():
|
||||
tokens = extract_tokens(
|
||||
platform_id=1,
|
||||
genres=["Action", " ", "", "Action"],
|
||||
franchises=None,
|
||||
)
|
||||
|
||||
assert tokens.count(make_token("genre", "Action")) == 1
|
||||
assert not any(token.endswith(":") for token in tokens)
|
||||
|
||||
|
||||
def test_release_year_handles_seconds_and_millisecond_epochs():
|
||||
assert release_year_from_epoch(SUPER_NES_ERA_EPOCH) == 1991
|
||||
# Some provider rows arrive in milliseconds; both must land in the same decade.
|
||||
assert release_year_from_epoch(SUPER_NES_ERA_EPOCH * 1000) == 1991
|
||||
assert release_year_from_epoch(None) is None
|
||||
assert release_year_from_epoch(0) is None
|
||||
|
||||
|
||||
def test_idf_penalises_ubiquitous_tokens():
|
||||
documents = [
|
||||
("genre:Action", "franchise:Metroid"),
|
||||
("genre:Action",),
|
||||
("genre:Action",),
|
||||
("genre:Action",),
|
||||
]
|
||||
|
||||
idf = compute_idf(documents, total_documents=4)
|
||||
|
||||
# "Action" is on every game here and says nothing; the franchise is rare.
|
||||
assert idf["genre:Action"] < idf["franchise:Metroid"]
|
||||
|
||||
|
||||
def test_a_token_on_every_game_is_worth_almost_nothing():
|
||||
"""The property the original smoothed IDF failed.
|
||||
|
||||
"Single player" sits on nearly every game in a real library. If it keeps
|
||||
meaningful weight it drags unrelated titles up the rankings on nothing but
|
||||
a shared game mode.
|
||||
"""
|
||||
documents = [("game_mode:Single player", f"franchise:F{i}") for i in range(50)]
|
||||
|
||||
idf = compute_idf(documents, total_documents=50)
|
||||
|
||||
assert idf["game_mode:Single player"] < 0.05
|
||||
# ...while a genuinely rare token stays strong.
|
||||
assert idf["franchise:F0"] > 3.0
|
||||
|
||||
|
||||
def test_ubiquitous_facets_cannot_outrank_a_shared_genre():
|
||||
"""Regression: Tetris used to outrank Super Mario World for Super Metroid.
|
||||
|
||||
Both shared "Nintendo" and "Single player" with the source game, but only
|
||||
the platformer shared its genre -- which must dominate.
|
||||
"""
|
||||
library = [
|
||||
("genre:Platform", "company:Nintendo", "game_mode:Single player"),
|
||||
("genre:Platform", "company:Nintendo", "game_mode:Single player"),
|
||||
("genre:Puzzle", "company:Nintendo", "game_mode:Single player"),
|
||||
("genre:RPG", "company:Square", "game_mode:Single player"),
|
||||
("genre:Racing", "company:Sega", "game_mode:Single player"),
|
||||
("genre:RPG", "company:Square", "game_mode:Single player"),
|
||||
]
|
||||
idf = compute_idf(library, total_documents=len(library))
|
||||
|
||||
source = build_vector(library[0], idf)
|
||||
same_genre = build_vector(library[1], idf)
|
||||
same_company_only = build_vector(library[2], idf)
|
||||
|
||||
assert content_similarity(source, same_genre) > content_similarity(
|
||||
source, same_company_only
|
||||
)
|
||||
|
||||
|
||||
def test_build_vector_is_unit_length():
|
||||
idf = {"genre:Action": 1.2, "franchise:Metroid": 2.4}
|
||||
vector = build_vector(("genre:Action", "franchise:Metroid"), idf)
|
||||
|
||||
magnitude = math.sqrt(sum(weight**2 for weight in vector.values()))
|
||||
assert magnitude == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_build_vector_drops_zero_weight_tokens():
|
||||
vector = build_vector(("genre:Action", "genre:Unknown"), {"genre:Action": 1.0})
|
||||
|
||||
assert "genre:Unknown" not in vector
|
||||
|
||||
|
||||
def test_build_vector_of_unknown_tokens_is_empty():
|
||||
assert build_vector(("genre:Action",), {}) == {}
|
||||
|
||||
|
||||
def test_content_similarity_ranks_shared_franchise_above_shared_genre():
|
||||
idf = compute_idf(
|
||||
[
|
||||
("genre:Action", "franchise:Metroid"),
|
||||
("genre:Action", "franchise:Metroid"),
|
||||
("genre:Action", "franchise:Mario"),
|
||||
("genre:Action", "franchise:Zelda"),
|
||||
],
|
||||
total_documents=4,
|
||||
)
|
||||
|
||||
source = build_vector(("genre:Action", "franchise:Metroid"), idf)
|
||||
same_franchise = build_vector(("genre:Action", "franchise:Metroid"), idf)
|
||||
same_genre_only = build_vector(("genre:Action", "franchise:Zelda"), idf)
|
||||
|
||||
assert content_similarity(source, same_franchise) > content_similarity(
|
||||
source, same_genre_only
|
||||
)
|
||||
|
||||
|
||||
def test_content_similarity_is_symmetric_and_bounded():
|
||||
idf = {"genre:Action": 1.0, "franchise:Metroid": 2.0}
|
||||
left = build_vector(("genre:Action", "franchise:Metroid"), idf)
|
||||
right = build_vector(("genre:Action",), idf)
|
||||
|
||||
assert content_similarity(left, right) == pytest.approx(
|
||||
content_similarity(right, left)
|
||||
)
|
||||
assert 0.0 <= content_similarity(left, right) <= 1.0
|
||||
assert content_similarity(left, left) == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_content_similarity_of_disjoint_vectors_is_zero():
|
||||
idf = {"genre:Action": 1.0, "genre:Puzzle": 1.0}
|
||||
assert (
|
||||
content_similarity(
|
||||
build_vector(("genre:Action",), idf), build_vector(("genre:Puzzle",), idf)
|
||||
)
|
||||
== 0.0
|
||||
)
|
||||
|
||||
|
||||
def test_shared_reasons_reports_strongest_facet_first():
|
||||
idf = compute_idf(
|
||||
[
|
||||
("genre:Action", "franchise:Metroid", "company:Nintendo"),
|
||||
("genre:Action", "franchise:Mario", "company:Nintendo"),
|
||||
("genre:Action", "franchise:Zelda", "company:Sega"),
|
||||
("genre:Action", "franchise:Sonic", "company:Sega"),
|
||||
],
|
||||
total_documents=4,
|
||||
)
|
||||
tokens = ("genre:Action", "franchise:Metroid", "company:Nintendo")
|
||||
vector = build_vector(tokens, idf)
|
||||
|
||||
reasons = shared_reasons(vector, vector)
|
||||
|
||||
assert reasons[0] == {"facet": "franchise", "value": "Metroid"}
|
||||
# One reason per facet, so the list reads as distinct explanations.
|
||||
assert len({reason["facet"] for reason in reasons}) == len(reasons)
|
||||
|
||||
|
||||
def test_shared_reasons_never_explains_a_match_by_platform():
|
||||
idf = {"platform:7": 5.0, "genre:Action": 1.0}
|
||||
vector = build_vector(("platform:7", "genre:Action"), idf)
|
||||
|
||||
assert all(
|
||||
reason["facet"] != "platform" for reason in shared_reasons(vector, vector)
|
||||
)
|
||||
|
||||
|
||||
def test_quality_bonus_is_bounded_and_monotonic():
|
||||
assert quality_bonus(None) == 0.0
|
||||
assert quality_bonus(0) == 0.0
|
||||
assert quality_bonus(100) == pytest.approx(MAX_QUALITY_BONUS)
|
||||
assert quality_bonus(50) < quality_bonus(90)
|
||||
# Providers occasionally emit out-of-range scores.
|
||||
assert quality_bonus(140) == pytest.approx(MAX_QUALITY_BONUS)
|
||||
|
||||
|
||||
def test_blend_rewards_every_signal_independently():
|
||||
baseline = blend(content=0.5)
|
||||
|
||||
assert blend(content=0.5, igdb_prior=1.0) > baseline
|
||||
assert blend(content=0.5, co_play=1.0) > baseline
|
||||
assert blend(content=0.5, co_collection=1.0) > baseline
|
||||
assert blend(content=0.5, average_rating=95) > baseline
|
||||
|
||||
|
||||
def test_blend_weights_igdb_above_collection_co_membership():
|
||||
assert blend(content=0.0, igdb_prior=1.0) > blend(content=0.0, co_collection=1.0)
|
||||
|
||||
|
||||
def test_blend_clamps_out_of_range_signals():
|
||||
# A malformed signal must not let a score run away past the maximum.
|
||||
assert blend(content=1.0, igdb_prior=50.0, average_rating=100) <= 1.0 + 1e-9
|
||||
|
||||
|
||||
def test_candidate_ids_skips_tokens_that_cover_the_library():
|
||||
features = {
|
||||
rom_id: RomFeatures(
|
||||
rom_id=rom_id,
|
||||
platform_id=1,
|
||||
tokens=("genre:Action",) + (("franchise:Metroid",) if rom_id < 3 else ()),
|
||||
)
|
||||
for rom_id in range(1, 301)
|
||||
}
|
||||
postings = build_inverted_index(features)
|
||||
|
||||
candidates = candidate_ids(features[1], postings, total_documents=len(features))
|
||||
|
||||
# "genre:Action" is on all 300 ROMs, well past the df cap, so only the ROM
|
||||
# sharing the rare franchise is considered.
|
||||
assert candidates == {2}
|
||||
|
||||
|
||||
def test_candidate_ids_expands_every_token_on_a_small_library():
|
||||
# The df ratio must not starve a small shelf of candidates entirely.
|
||||
features = {
|
||||
rom_id: RomFeatures(rom_id=rom_id, platform_id=1, tokens=("genre:Action",))
|
||||
for rom_id in range(1, 5)
|
||||
}
|
||||
postings = build_inverted_index(features)
|
||||
|
||||
assert candidate_ids(features[1], postings, total_documents=4) == {2, 3, 4}
|
||||
|
||||
|
||||
def test_candidate_ids_excludes_the_source_rom():
|
||||
features = {
|
||||
1: RomFeatures(rom_id=1, platform_id=1, tokens=("franchise:Metroid",)),
|
||||
2: RomFeatures(rom_id=2, platform_id=1, tokens=("franchise:Metroid",)),
|
||||
}
|
||||
postings = build_inverted_index(features)
|
||||
|
||||
assert 1 not in candidate_ids(features[1], postings, total_documents=2)
|
||||
|
||||
|
||||
def test_has_taste_signal_rejects_context_only_tokens():
|
||||
# Platform and decade describe the shelf, not the game.
|
||||
assert not has_taste_signal(("platform:7", "decade:1990"))
|
||||
assert not has_taste_signal(())
|
||||
assert has_taste_signal(("platform:7", "genre:RPG"))
|
||||
assert has_taste_signal(("franchise:Metroid",))
|
||||
|
||||
|
||||
def test_context_only_vectors_would_otherwise_match_perfectly():
|
||||
"""Documents the reason context-only ROMs are excluded from the index."""
|
||||
idf = {"platform:7": 2.0, "decade:1990": 1.5}
|
||||
tokens = ("platform:7", "decade:1990")
|
||||
|
||||
left = build_vector(tokens, idf)
|
||||
right = build_vector(tokens, idf)
|
||||
|
||||
assert content_similarity(left, right) == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_normalise_co_occurrence_damps_ubiquitous_items():
|
||||
# Two games seen together twice, where one appears in everything.
|
||||
focused = normalise_co_occurrence(2, left_total=2, right_total=2)
|
||||
ubiquitous = normalise_co_occurrence(2, left_total=2, right_total=500)
|
||||
|
||||
assert focused > ubiquitous
|
||||
assert focused <= 1.0
|
||||
assert normalise_co_occurrence(0, 5, 5) == 0.0
|
||||
assert normalise_co_occurrence(3, 0, 5) == 0.0
|
||||
Reference in New Issue
Block a user