diff --git a/service/Dockerfile b/service/Dockerfile index e32d005c..8072f6b4 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "websockets==12.0" \ "partial-json-parser==0.2.1.1.post7" \ "sqlmodel~=0.0.33" \ - "argon2-cffi~=25.1.0" + "argon2-cffi~=25.1.0" \ + "pandas~=2.3.3" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index 118c8fe1..6e6b8cb5 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -21,6 +21,7 @@ dependencies = [ "torch", "sqlmodel~=0.0.33", "argon2-cffi~=25.1.0", + "pandas~=2.3.3", ] [[tool.uv.index]] diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 998feec3..9cd2ff90 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -5,6 +5,8 @@ import logging from time import time from typing import Any, List, Optional +import pandas as pd + from inse.integrations import elasticsearch from inse.model import ESCluster from inse.persons.logic import _classify_career_stage @@ -179,23 +181,51 @@ def _citations_from_bucket(author_bucket: dict) -> int: return int(citations_value) -def _weighted_score(works_count: int, citations_count: int, weights: RankingWeights) -> float: - """Computes the weighted score for an author in the backend.""" - return works_count * weights.works + citations_count * weights.citation - - -def _bucket_to_ranked_author(author_bucket: dict, weights: RankingWeights) -> RankedAuthor: - works_count = author_bucket.get("doc_count", 0) - citations_count = _citations_from_bucket(author_bucket) +def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor: + """Converts an author bucket from the ES aggregation into a RankedAuthor.""" return RankedAuthor( author_id=author_bucket.get("key", ""), display_name=_display_name_from_bucket(author_bucket), - works_count=works_count, - citations_count=citations_count, - score=_weighted_score(works_count, citations_count, weights), + works_count=author_bucket.get("doc_count", 0), + citations_count=_citations_from_bucket(author_bucket), ) +def _min_max_normalize(values: pd.Series) -> pd.Series: + """Scales a numeric column to the range [0, 1] via min-max normalization.""" + minimum = values.min() + maximum = values.max() + # if all values are the same, return a series of 1.0 to avoid division by zero. + if maximum == minimum: + return pd.Series([1.0] * len(values)) + + return (values - minimum) / (maximum - minimum) + + +def _apply_scores(authors: List[RankedAuthor], weights: RankingWeights) -> None: + """Normalizes works and citations to [0, 1] and sets each author's weighted score.""" + if not authors: + return + + works_counts = [] + citations_counts = [] + for author in authors: + works_counts.append(author.works_count) + citations_counts.append(author.citations_count) + + frame = pd.DataFrame({ + "works": works_counts, + "citations": citations_counts, + }) + + works_normalized = _min_max_normalize(frame["works"]) + citations_normalized = _min_max_normalize(frame["citations"]) + scores = works_normalized * weights.works + citations_normalized * weights.citation + + for index, author in enumerate(authors): + author.score = float(scores.iloc[index]) + + def _author_score(author: RankedAuthor) -> float: """Sort key: the weighted score of an author.""" return author.score @@ -314,12 +344,15 @@ async def rank_authors_by_keywords( .get("by_author", {}) .get("buckets", []) ) + logger.error(author_buckets) - # Build the raw authors and compute the weighted score in the backend. + # Build the raw authors, then compute the normalized weighted score. backend_processing_start_time = time() ranked_authors = [] for author_bucket in author_buckets: - ranked_authors.append(_bucket_to_ranked_author(author_bucket, weights)) + ranked_authors.append(_bucket_to_ranked_author(author_bucket)) + + _apply_scores(ranked_authors, weights) # Sort by the weighted score, highest first. ranked_authors.sort(key=_author_score, reverse=True) diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index ec8402ec..c36c46dc 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -115,7 +115,10 @@ class RankedAuthor(BaseModel): citations_count: int = Field( description="Total citations across this author's matching works.", ) - score: float = Field(description="Weighted total score used for ranking.") + score: float = Field( + default=0.0, + description="Normalized weighted score used for ranking.", + ) career_stage: CareerStage = Field( default=CareerStage.UNKNOWN, description="Career stage derived from the author's active publication years.",