Skip to content

weighted sampling#679

Open
shuaibmunshi wants to merge 15 commits into
helgeerbe:mainfrom
shuaibmunshi:main
Open

weighted sampling#679
shuaibmunshi wants to merge 15 commits into
helgeerbe:mainfrom
shuaibmunshi:main

Conversation

@shuaibmunshi

@shuaibmunshi shuaibmunshi commented Jun 9, 2026

Copy link
Copy Markdown

Adds an optional weighted sampling feature to see more recent photos more frequently.

Summary by Sourcery

Introduce optional age-weighted photo sampling to bias slideshows toward more recent images while supporting portrait pairing and configurable limits.

New Features:

  • Add configurable age-weighted sampling mode that biases photo selection toward newer images using a recency half-life setting.
  • Allow limiting the size of the weighted sample to force more frequent reshuffles on large photo libraries.
  • Extend supported image file types to include TIFF and BMP formats.

Enhancements:

  • Expose portrait pairing preference from the image cache and ensure weighted sampling respects portrait pair grouping in the slideshow ordering.

Tests:

  • Add unit tests covering weighted sampling behavior, sample limiting, portrait pairing interactions, and configuration warnings.
  • Add a standalone script for exercising and inspecting weighted sampling behavior against a temporary SQLite database.

@sourcery-ai

sourcery-ai Bot commented Jun 9, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implements an optional age-weighted sampling path for slideshow photo selection, including a new DB query, weighted reservoir sampling with recency bias, portrait-pair handling, config wiring, and tests, plus minor image format support expansion.

Sequence diagram for age-weighted photo sampling in __get_files

sequenceDiagram
    participant Model
    participant ImageCache

    Model->>Model: __get_files()
    Model->>Model: get_model_config()
    alt [age_weighted_sampling enabled] and [__use_weighted_sampling]
        Model->>Model: __use_weighted_sampling()
        Model->>Model: __get_weighted_sample(where_clause)
        Model->>ImageCache: query_file_ids_with_timestamps(where_clause)
        ImageCache-->>Model: [(file_id,last_modified,is_portrait)]
        Model->>Model: __join_portrait_pairs(keyed) [when ImageCache.portrait_pairs]
        Model-->>Model: __file_list (weighted order)
    else default ordering
        Model->>ImageCache: query_cache(where_clause,sort_clause)
        ImageCache-->>Model: __file_list (sorted/shuffled)
    end
Loading

File-Level Changes

Change Details Files
Introduce an age-weighted sampling mode that replaces the existing shuffle/sort path when enabled, including configuration, warnings, sampling logic, and portrait pairing.
  • Add model config flags age_weighted_sampling, recency_half_life_days, and sample_limit with defaults and expose them in the example configuration file
  • Branch __get_files to either use the existing shuffle/sort logic or a new weighted sampling path based on configuration and an internal gate
  • Add __use_weighted_sampling to gate weighted sampling, emit one-time warnings when it overrides shuffle or recent_n, and record enablement
  • Implement __get_weighted_sample to query file ids and timestamps, compute exponential age-based weights, perform Efraimidis–Spirakis weighted sampling, apply optional sample_limit truncation, and adapt output for portrait_pairs or singletons
  • Add __join_portrait_pairs helper to reconstruct landscape entries and portrait pairs into tuples consistent with the non-weighted query_cache behavior
src/picframe/model.py
src/picframe/config/configuration_example.yaml
Extend ImageCache to support weighted sampling queries and expose portrait pairing configuration.
  • Add support for .tif, .tiff, and .bmp extensions to the list of recognized image types
  • Introduce query_file_ids_with_timestamps to return (file_id, last_modified, is_portrait) rows from all_data with a where_clause, for use by the model’s weighted sampling
  • Expose portrait_pairs as a read-only property to allow the model to decide whether to join portrait pairs
src/picframe/image_cache.py
Add automated tests for the weighted sampling behavior and portrait pairing logic, plus a standalone script to experiment with and validate the weighting and sample_limit behavior.
  • Add test helper functions to construct a Model instance with mocked internals and to stub cache rows for weighted sampling tests
  • Verify core behaviors of __get_weighted_sample including empty input, preservation of all ids, sample_limit semantics, recency bias, robustness to equal and very old timestamps, and portrait_pairs on/off behavior
  • Verify that __use_weighted_sampling logs warnings when it overrides shuffle or recent_n and no longer disables weighted sampling when portrait_pairs is enabled
  • Add an executable test_weighted_sampling.py script that builds a temporary SQLite database, computes exponential-decay weights over a synthetic time range, prints weight and probability distributions, and simulates sample_limit behavior for manual inspection
test/test_weighted_sampling.py
test_weighted_sampling.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 security issue, and left some high level feedback:

Security issues:

  • Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option. (link)

General comments:

  • In __use_weighted_sampling, the guard flag uses getattr(self, "_Model__weighted_warned", False) but sets self.__weighted_warned, so the warning-suppression flag is never respected and warnings will be logged on every call; align the attribute name so the guard works as intended.
  • The portrait pairing in __join_portrait_pairs repeatedly pop(0) from pair_queue, which is O(n) per pop on a list and can become expensive on large libraries; consider using collections.deque or indexing to avoid quadratic behavior.
  • The standalone test_weighted_sampling.py script at the repo root reimplements a different weighting scheme and bypasses the package’s import path, which may be confusing and drift from the real logic; consider either integrating its checks into the main test suite or removing it to avoid duplicate, inconsistent code paths.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `__use_weighted_sampling`, the guard flag uses `getattr(self, "_Model__weighted_warned", False)` but sets `self.__weighted_warned`, so the warning-suppression flag is never respected and warnings will be logged on every call; align the attribute name so the guard works as intended.
- The portrait pairing in `__join_portrait_pairs` repeatedly `pop(0)` from `pair_queue`, which is O(n) per pop on a list and can become expensive on large libraries; consider using `collections.deque` or indexing to avoid quadratic behavior.
- The standalone `test_weighted_sampling.py` script at the repo root reimplements a different weighting scheme and bypasses the package’s import path, which may be confusing and drift from the real logic; consider either integrating its checks into the main test suite or removing it to avoid duplicate, inconsistent code paths.

## Individual Comments

### Comment 1
<location path="src/picframe/image_cache.py" line_range="160" />
<code_context>
            return cursor.execute(sql).fetchall()
</code_context>
<issue_to_address>
**security (python.sqlalchemy.security.sqlalchemy-execute-raw-query):** Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/picframe/image_cache.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant