API reference¶
Generated from the source docstrings. Start with sr.run; the recommender contract is
get_recommendations(user_id, k, session_items=None, selections=None, **params) -> list[item_id].
Application¶
streamlit_recommenders.run(get_recommendations, items, interactions=None, layout='rows', params=None, config=None, title='Recommender Demo', subtitle=None, item_columns=None, intro=None, body=None, session_user=True, swipes_per_refresh=5)
¶
Orchestrate the full Streamlit demo app.
Renders the sidebar (user picker, parameters), the user profile strips, and the recommendation layout(s), computing recommendations on demand and caching displayed results in session state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
get_recommendations
|
GetRecommendationsInput
|
A recommender callable/object, or a mapping of label to recommender for side-by-side comparison mode. |
required |
items
|
DataFrame
|
Item catalog DataFrame. |
required |
interactions
|
DataFrame | None
|
Optional user-item interactions used for user history and the user selector. |
None
|
layout
|
str
|
Layout style ("rows", "grid", or "cards"); overridable via YAML. |
'rows'
|
params
|
dict[str, Any] | None
|
Parameter definitions for the sidebar controls. |
None
|
config
|
str | None
|
Optional path to a YAML config file whose values override the corresponding keyword arguments. |
None
|
title
|
str
|
Page and browser tab title. |
'Recommender Demo'
|
subtitle
|
str | None
|
Optional caption shown under the title. |
None
|
item_columns
|
dict[str, str] | None
|
Mapping of logical item fields to catalog column names. |
None
|
intro
|
Callable[[], None] | None
|
Optional callback rendered in a bordered container above the app. |
None
|
body
|
Callable[[], None] | None
|
Optional callback rendered in a bordered container below the app. |
None
|
session_user
|
bool
|
Whether to offer the interactive "Try yourself" session user in the user picker. |
True
|
swipes_per_refresh
|
int
|
Number of swipes before new cards are requested in the "cards" layout. |
5
|
Data loading¶
streamlit_recommenders.load_items(path, id_col='item_id')
¶
Load the item catalog from path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the item data file. |
required |
id_col
|
str
|
Name of the item identifier column. |
'item_id'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The item catalog as a DataFrame. |
streamlit_recommenders.load_interactions(path, user_col='user_id', item_col='item_id')
¶
Load user-item interactions from path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the interactions data file. |
required |
user_col
|
str
|
Name of the user identifier column. |
'user_id'
|
item_col
|
str
|
Name of the item identifier column. |
'item_id'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The interactions as a DataFrame. |
streamlit_recommenders.load_dataset(root, *, resolve_images=True)
¶
Load a prepared dataset folder, cached across Streamlit reruns.
Cached wrapper over
:func:streamlit_recommenders.data.load_dataset so a demo reloads
(items, interactions, test) once per session instead of on every rerun.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str
|
Prepared dataset folder, e.g. |
required |
resolve_images
|
bool
|
Resolve item poster paths to local files when True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple of |
DataFrame | None
|
their CSVs are absent. |
streamlit_recommenders.load_dataset_from_paths(*, items, interactions=None, users=None, train=None, test=None, columns=None)
¶
Load and validate a Dataset from individual CSV paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
str
|
Path to the items CSV. |
required |
interactions
|
str | None
|
Optional path to the full interactions CSV. |
None
|
users
|
str | None
|
Optional path to the users CSV. |
None
|
train
|
str | None
|
Optional path to the training interactions CSV. |
None
|
test
|
str | None
|
Optional path to the test interactions CSV. |
None
|
columns
|
ColumnMap | None
|
Column mapping to apply; defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Dataset
|
A validated Dataset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If validation fails. |
Session readers (for body())¶
streamlit_recommenders.current_user()
¶
Return the id of the currently selected user.
streamlit_recommenders.selected_items()
¶
Return the item ids the user selected during this session.
streamlit_recommenders.disliked_items()
¶
Return the item ids the user disliked during this session.
streamlit_recommenders.displayed_items(section=None)
¶
Item ids currently shown in the recommender window.
Returns the list for one section label, or a {label: ids} dict for
all sections when section is None. This is the single source of
truth for what the UI displays, so diagnostics in body() (overlap
heatmaps, score tables) stay consistent with the rows on screen, including
the cold-start sample shown for the "Try yourself" session user.
streamlit_recommenders.selections(section=None)
¶
Return recorded like/dislike selections for a section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
section
|
str | None
|
Section label to fetch selections for, or |
None
|
Returns:
| Type | Description |
|---|---|
|
The selection metadata for the requested section(s). |
streamlit_recommenders.param_value(name, default=None)
¶
Return the current sidebar value for parameter name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Parameter name as defined in the sidebar controls. |
required |
default
|
Value to return if the parameter is not set. |
None
|
Returns:
| Type | Description |
|---|---|
|
The parameter's current value from session state, or |
Recommender contract¶
streamlit_recommenders.recommenders.base.BaseRecommender
¶
Shared contract for score-based recommenders.
Subclasses provide scores() returning one value per self.item_ids;
the base ranks unseen items via the common seen-filtering + top-k logic.
Attributes:
| Name | Type | Description |
|---|---|---|
interactions |
DataFrame | None
|
Optional interactions DataFrame used to determine which items a user has already seen. |
item_ids |
list
|
Ordered item ids aligned with the score vector. |
scores(user_id, session_items=None, **params)
¶
Return one score per item in self.item_ids for user_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | int
|
Id of the user to score items for. |
required |
session_items
|
list | None
|
Items selected during the current session. |
None
|
**params
|
Model-specific scoring parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A score array aligned with |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always; subclasses must implement scoring. |
get_recommendations(user_id, k, session_items=None, selections=None, **params)
¶
Return the top-k recommended item ids, excluding seen items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | int
|
Id of the user to recommend for. |
required |
k
|
int
|
Number of item ids to return. |
required |
session_items
|
list | None
|
Items selected during the current session. |
None
|
selections
|
list[dict] | None
|
UI feedback metadata; ignored here, subclasses that want it should override this method. |
None
|
**params
|
Model-specific scoring parameters passed to |
{}
|
Returns:
| Type | Description |
|---|---|
list
|
Up to |
streamlit_recommenders.recommenders.artifact.ArtifactRecommender(artifact_path, interactions)
¶
Bases: BaseRecommender
Expose exported NumPy artifacts (item_ids, weights, popularity).
Loads a .npz artifact and serves recommendations either from an
item-item weight matrix (item-based CF or sequential CF) or from a
popularity fallback when the user/session profile is empty.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Artifact file stem, used as a display name. |
|
model_type |
Artifact model type, e.g. |
|
item_ids |
Ordered item ids aligned with weights and popularity. |
|
item_index |
Mapping from item id to its row index. |
|
weights |
Item-item weight matrix. |
|
popularity |
Global popularity scores used as a fallback. |
|
interactions |
Interactions DataFrame supplying user history. |
|
user_history |
Mapping from user id to their ordered item history. |
Load the artifact and build per-user interaction history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artifact_path
|
str | Path
|
Path to the exported |
required |
interactions
|
DataFrame
|
Interactions DataFrame used for user history. |
required |
scores(user_id, session_items=None, history_window=None, **params)
¶
Score every item for user_id using the loaded artifact.
For sequential models, scores come from the weight row of the most recent (anchor) item; otherwise from a user profile vector multiplied by the weight matrix. Falls back to popularity when no signal exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | int
|
Id of the user to score items for. |
required |
session_items
|
list | None
|
Items selected during the current session. |
None
|
history_window
|
int | str | None
|
Number of most recent history items to keep, or
|
None
|
**params
|
Additional parameters (ignored). |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A score array aligned with |
score_frame(user_id, session_items=None, items=None, **params)
¶
Return a score-per-item DataFrame sorted by descending score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | int
|
Id of the user to score items for. |
required |
session_items
|
list | None
|
Items selected during the current session. |
None
|
items
|
DataFrame | None
|
Optional catalog used to attach item titles. |
None
|
**params
|
Additional scoring parameters forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with |
DataFrame
|
when |
streamlit_recommenders.load_artifacts(paths, interactions)
¶
Load exported .npz artifacts into recommenders, cached across reruns.
Cached wrapper over
:func:streamlit_recommenders.recommenders.load_artifacts: pass a mapping
of display label to artifact path and get one loaded recommender per label,
loaded once per session rather than rebuilt on every rerun.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
dict[str, str]
|
Mapping of display label to the artifact's |
required |
interactions
|
DataFrame
|
Interactions DataFrame supplying per-user history. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ArtifactRecommender]
|
A dict mapping each label to its loaded |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any artifact path does not exist. |
streamlit_recommenders.models.protocol.RecommenderProtocol
¶
Bases: Protocol
Contract a recommender object implements to plug into the demo.
Any object exposing a matching get_recommendations method is accepted;
runtime_checkable allows isinstance checks against this protocol.
get_recommendations(user_id, k, session_items=None, selections=None, **params)
¶
Return the top-k recommended item ids for a user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | int
|
Id of the user to recommend for. |
required |
k
|
int
|
Number of item ids to return. |
required |
session_items
|
list[str | int] | None
|
Items selected during the current session. |
None
|
selections
|
list[dict] | None
|
Optional UI feedback metadata (e.g. likes/dislikes). |
None
|
**params
|
Any
|
Model-specific parameters supplied by the sidebar. |
{}
|
Returns:
| Type | Description |
|---|---|
list[str | int]
|
Up to |
Metrics¶
streamlit_recommenders.evaluate(recommendations, test_interactions, *, k, item_col='item_id', user_col='user_id', all_item_ids=None)
¶
Evaluate one or more recommenders against held-out interactions.
Ground truth is grouped from test_interactions by user; hit rate,
recall, NDCG and MRR are averaged over users, plus optional coverage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recommendations
|
Mapping
|
Either |
required |
test_interactions
|
DataFrame
|
Held-out interactions holding ground-truth items. |
required |
k
|
int
|
Cutoff rank for all metrics. |
required |
item_col
|
str
|
Item id column in |
'item_id'
|
user_col
|
str
|
User id column in |
'user_id'
|
all_item_ids
|
Sequence | None
|
Full catalog; when given, a coverage row is added per model. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Long-form DataFrame with columns |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Visualization¶
streamlit_recommenders.dataset_info(items, interactions, *, users=None, title='Dataset info', item_id_col='item_id', user_id_col='user_id', genre_cols=('genres', 'genre'), exclude_item_cols=('image_url', 'poster_path', 'description'), expanded=False, key_prefix='streamlit_recommenders.dataset_info')
¶
Render a compact, reusable dataset inspection block.
Headline metrics and a raw-count table summarise the dataset; a tabbed switcher (consistent with the results-inspection plots) then flips between the available distributions, defaulting to item genres when present.