Skip to content

API documentation

kennerspiel

make_transformer(list_columns: Iterable[str] | str, player_count_columns: Iterable[str] | str = ('min_players', 'max_players'), min_df: float = 0.01) -> ColumnTransformer

Game transformer.

Source code in src/spiel_des_jahres/kennerspiel/__init__.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def make_transformer(
    list_columns: Iterable[str] | str,
    player_count_columns: Iterable[str] | str = ("min_players", "max_players"),
    min_df: float = 0.01,
) -> ColumnTransformer:
    """Game transformer."""

    list_pipeline = Pipeline(
        [
            ("list_dataframe", FunctionTransformer(_list_dataframe)),
            ("combine_lists", FunctionTransformer(_combine_lists)),
            (
                "count_vectorizer",
                CountVectorizer(
                    analyzer=set,
                    min_df=min_df,
                    binary=True,
                    dtype=np.bool_,
                ),
            ),
            ("todense", FunctionTransformer(csr_matrix.toarray)),
        ],
    )

    playable_transformer = FunctionTransformer(
        _playable_with,
        kw_args={
            "counts": range(1, 11),
            "prefix": "playable_with_",
            "more_column": True,
        },
    )

    if isinstance(list_columns, str):
        list_columns = [list_columns]

    if isinstance(player_count_columns, str):
        player_count_columns = [player_count_columns]

    return ColumnTransformer(
        [
            ("list_pipeline", list_pipeline, list_columns),
            ("playable_transformer", playable_transformer, player_count_columns),
        ],
        remainder="passthrough",
        force_int_remainder_cols=False,
    )

predictions

fetch_candidates(year: int, *, main_user: str = 's_d_j', jury_member_prefix: str = 's_d_j_', kennerspiel_cutoff_score: float = 0.5, max_results: int | None = 25, base_url: str = BASE_URL, timeout: float = 60, max_exclude_games: int = 250, progress_bar: bool = False) -> tuple[list[str], pl.LazyFrame]

Fetch all candidates from the recommendation API.

Source code in src/spiel_des_jahres/predictions.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def fetch_candidates(
    year: int,
    *,
    main_user: str = "s_d_j",
    jury_member_prefix: str = "s_d_j_",
    kennerspiel_cutoff_score: float = 0.5,
    max_results: int | None = 25,
    base_url: str = BASE_URL,
    timeout: float = 60,
    max_exclude_games: int = 250,
    progress_bar: bool = False,
) -> tuple[list[str], pl.LazyFrame]:
    """Fetch all candidates from the recommendation API."""

    include, exclude, jury_members = include_exclude_jury_members(year)

    LOGGER.info("Including %d games", len(include))
    exclude = exclude.head(max_exclude_games)
    LOGGER.info("Excluding %d games", len(exclude))

    LOGGER.info("Fetching candidates for %s", main_user)
    result = fetch_candidates_for_single_user(
        user_name=main_user,
        year=year,
        bgg_ids_include=include,
        bgg_ids_exclude=exclude,
        kennerspiel_cutoff_score=kennerspiel_cutoff_score,
        max_results=max_results,
        base_url=base_url,
        timeout=timeout,
        request_params={"exclude_known": True},
        progress_bar=progress_bar,
    )

    for jury_member in jury_members:
        LOGGER.info("Fetching candidates for %s", jury_member)
        results_jury_member = fetch_candidates_for_single_user(
            user_name=f"{jury_member_prefix}{jury_member}",
            year=year,
            bgg_ids_include=include,
            bgg_ids_exclude=exclude,
            kennerspiel_cutoff_score=kennerspiel_cutoff_score,
            max_results=max_results,
            base_url=base_url,
            timeout=timeout,
            progress_bar=progress_bar,
        ).select("bgg_id", "rec_rating", "rec_rel_rank", "rec_min_max", "rec_standard")

        result = result.join(
            results_jury_member,
            on="bgg_id",
            how="left",
            suffix=f"_{jury_member}",
        )

    return jury_members, result.rename(
        {
            "rec_rating": f"rec_rating_{main_user}",
            "rec_rel_rank": f"rec_rel_rank_{main_user}",
            "rec_min_max": f"rec_min_max_{main_user}",
            "rec_standard": f"rec_standard_{main_user}",
        },
    )

recommend_games(*, base_url: str = BASE_URL, max_results: int | None = 25, timeout: float = 60, request_params: dict[str, Any] | None = None, progress_bar: bool = False) -> Generator[dict[str, Any]]

Call to a Recommend.Games instance.

Source code in src/spiel_des_jahres/predictions.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def recommend_games(
    *,
    base_url: str = BASE_URL,
    max_results: int | None = 25,
    timeout: float = 60,
    request_params: dict[str, Any] | None = None,
    progress_bar: bool = False,
) -> Generator[dict[str, Any]]:
    """Call to a Recommend.Games instance."""

    results: Iterable[dict[str, Any]] = _recommend_games(
        base_url=base_url,
        timeout=timeout,
        request_params=request_params,
    )

    results = islice(results, max_results) if max_results else results

    if progress_bar:
        from tqdm import tqdm  # noqa: PLC0415

        results = tqdm(
            results,
            desc="Fetching recommendations",
            unit=" game(s)",
            total=max_results,
        )

    yield from results

sdj_predictions(year: int, *, fetch_from_api: bool = False, main_user: str = 's_d_j', main_user_weights: Mapping[str, float] | None = None, jury_member_prefix: str = 's_d_j_', jury_member_weights: Mapping[str, float] | None = None, kennerspiel_cutoff_score: float = 0.5, games_path: Path | str = SCRAPED_DIR / 'bgg_GameItem.csv', kennerspiel_model: BaseEstimator | Path | str | None = None, recommender_model: BaseGamesRecommender[int, str] | Path | str | None = None, max_results: int | None = 25, base_url: str = BASE_URL, timeout: float = 60, max_exclude_games: int = 250, progress_bar: bool = False) -> pl.LazyFrame

Predict the Spiel des Jahres winner.

Source code in src/spiel_des_jahres/predictions.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def sdj_predictions(
    year: int,
    *,
    fetch_from_api: bool = False,
    main_user: str = "s_d_j",
    main_user_weights: Mapping[str, float] | None = None,
    jury_member_prefix: str = "s_d_j_",
    jury_member_weights: Mapping[str, float] | None = None,
    kennerspiel_cutoff_score: float = 0.5,
    games_path: Path | str = SCRAPED_DIR / "bgg_GameItem.csv",
    kennerspiel_model: BaseEstimator | Path | str | None = None,
    recommender_model: BaseGamesRecommender[int, str] | Path | str | None = None,
    max_results: int | None = 25,
    base_url: str = BASE_URL,
    timeout: float = 60,
    max_exclude_games: int = 250,
    progress_bar: bool = False,
) -> pl.LazyFrame:
    """Predict the Spiel des Jahres winner."""

    if fetch_from_api:
        jury_members, candidates = fetch_candidates(
            year=year,
            main_user=main_user,
            jury_member_prefix=jury_member_prefix,
            kennerspiel_cutoff_score=kennerspiel_cutoff_score,
            max_results=max_results,
            base_url=base_url,
            timeout=timeout,
            max_exclude_games=max_exclude_games,
            progress_bar=progress_bar,
        )

    else:
        assert kennerspiel_model is not None, "kennerspiel_model must be provided"
        assert recommender_model is not None, "recommender_model must be provided"

        jury_members, candidates = load_candidates(
            year=year,
            games_path=games_path,
            kennerspiel_model=kennerspiel_model,
            recommender_model=recommender_model,
            main_user=main_user,
            jury_member_prefix=jury_member_prefix,
            kennerspiel_cutoff_score=kennerspiel_cutoff_score,
        )

    main_user_weights = main_user_weights or {}
    jury_member_weights = jury_member_weights or {}

    main_user_weights = {
        f"{col}_{main_user}": weight for col, weight in main_user_weights.items()
    }
    jury_member_weights = {
        f"{col}_{jury_member}": weight
        for col, weight in jury_member_weights.items()
        for jury_member in jury_members
    }
    weights = main_user_weights | jury_member_weights
    total_weight = sum(weights.values())

    if total_weight == 0:
        return candidates.with_columns(
            sdj_score=pl.lit(None),
            sdj_rank=pl.lit(None),
        )

    return (
        candidates.with_columns(
            sdj_score=pl.sum_horizontal(
                pl.col(col) * weight for col, weight in weights.items()
            )
            / total_weight,
        )
        .with_columns(
            sdj_rank=pl.col("sdj_score")
            .rank(method="min", descending=True)
            .over("kennerspiel"),
        )
        .sort("kennerspiel", "sdj_rank")
    )

update_reviews

find_bgg_ids(df: pl.DataFrame, bgg_games_path: Path) -> pl.DataFrame

Try to find BGG IDs for games with missing IDs using exact and fuzzy matching.

Source code in src/spiel_des_jahres/update_reviews.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def find_bgg_ids(
    df: pl.DataFrame,
    bgg_games_path: Path,
) -> pl.DataFrame:
    """Try to find BGG IDs for games with missing IDs using exact and fuzzy matching."""
    if not bgg_games_path.exists():
        LOGGER.warning(
            "BGG games file <%s> not found. Skipping ID matching.",
            bgg_games_path,
        )
        return df

    if (missing_count := df.filter(pl.col("bgg_id").is_null()).height) == 0:
        return df

    LOGGER.info("Attempting to find BGG IDs for %d games...", missing_count)

    bgg_lf = pl.scan_csv(bgg_games_path, schema_overrides={"bgg_id": pl.Int64}).select(
        "bgg_id",
        "name",
        name_lower=pl.col("name").str.to_lowercase(),
    )

    # 1. Try exact matching (case-insensitive)
    bgg_exact = bgg_lf.with_columns(count=pl.len().over("name_lower"))

    df = (
        df.lazy()
        .with_columns(name_lower=pl.col("name").str.to_lowercase())
        .join(
            bgg_exact.filter(pl.col("count") == 1).select("bgg_id", "name_lower"),
            on="name_lower",
            how="left",
            suffix="_matched",
        )
        .join(
            bgg_exact.filter(pl.col("count") > 1)
            .select("name_lower")
            .unique()
            .with_columns(is_ambiguous=pl.lit(value=True)),
            on="name_lower",
            how="left",
        )
        .with_columns(bgg_id=pl.coalesce("bgg_id", "bgg_id_matched"))
        .collect()
    )

    for name in df.filter(
        pl.col("is_ambiguous").fill_null(value=False) & pl.col("bgg_id").is_null(),
    )["name"].unique():
        LOGGER.warning(
            "Exact match skipped for '%s' because of BGG name ambiguity.",
            name,
        )

    df = df.drop("name_lower", "bgg_id_matched", "is_ambiguous")

    # 2. Try fuzzy matching for remaining nulls
    still_missing = df.filter(pl.col("bgg_id").is_null())["name"].unique().to_list()
    if not still_missing:
        return df

    LOGGER.info("Performing fuzzy matching for %d games...", len(still_missing))

    bgg_fuzzy = bgg_lf.with_columns(count=pl.len().over("name")).collect()
    bgg_id_map = dict(
        bgg_fuzzy.filter(pl.col("count") == 1).select("name", "bgg_id").iter_rows(),
    )

    fuzzy_results = []
    for name in still_missing:
        best_match, score = process.extractOne(name, bgg_fuzzy["name"])
        if score >= FUZZY_MATCH_THRESHOLD:
            if bgg_id := bgg_id_map.get(best_match):
                LOGGER.info(
                    "Fuzzy match: '%s' -> '%s' (ID: %d, score: %d)",
                    name,
                    best_match,
                    bgg_id,
                    score,
                )
                fuzzy_results.append({"name": name, "bgg_id_fuzzy": bgg_id})
            else:
                LOGGER.warning(
                    "Fuzzy match skipped: '%s' -> '%s' (score: %d) - ambiguous in BGG.",
                    name,
                    best_match,
                    score,
                )
        else:
            LOGGER.debug(
                "No confident fuzzy match for '%s' (best: '%s', score: %d)",
                name,
                best_match,
                score,
            )

    if fuzzy_results:
        df = (
            df.join(pl.DataFrame(fuzzy_results), on="name", how="left")
            .with_columns(bgg_id=pl.coalesce("bgg_id", "bgg_id_fuzzy"))
            .drop("bgg_id_fuzzy")
        )

    return df