|
| 1 | +import logging |
| 2 | +from typing import Dict, List, Any, Tuple |
| 3 | +from sentence_transformers import CrossEncoder |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +class CrossEncoderManager: |
| 10 | + """Manages cross-encoder for computing semantic relevance scores between articles.""" |
| 11 | + |
| 12 | + def __init__(self, model_name: str = "cross-encoder/ms-marco-MiniLM-L-6-v2"): |
| 13 | + """ |
| 14 | + Initialize the cross encoder. |
| 15 | + |
| 16 | + Args: |
| 17 | + model_name: HuggingFace model identifier for cross-encoder |
| 18 | + Default: ms-marco-MiniLM-L-6-v2 (efficient and accurate for relevance) |
| 19 | + """ |
| 20 | + self.model_name = model_name |
| 21 | + try: |
| 22 | + self.model = CrossEncoder(model_name) |
| 23 | + logger.info(f"Cross-encoder loaded: {model_name}") |
| 24 | + except Exception as e: |
| 25 | + logger.error(f"Failed to load cross-encoder: {e}") |
| 26 | + self.model = None |
| 27 | + |
| 28 | + def compute_relevance_score( |
| 29 | + self, |
| 30 | + query_article: Dict[str, Any], |
| 31 | + candidate_article: Dict[str, Any] |
| 32 | + ) -> float: |
| 33 | + """ |
| 34 | + Compute semantic relevance score between two articles. |
| 35 | + |
| 36 | + Args: |
| 37 | + query_article: Source article dict with title, description, full_content |
| 38 | + candidate_article: Target article dict for comparison |
| 39 | + |
| 40 | + Returns: |
| 41 | + Relevance score between 0 and 1 |
| 42 | + """ |
| 43 | + if self.model is None: |
| 44 | + logger.warning("Cross-encoder model not loaded, returning 0.5") |
| 45 | + return 0.5 |
| 46 | + |
| 47 | + try: |
| 48 | + query_text = self._build_article_text(query_article) |
| 49 | + candidate_text = self._build_article_text(candidate_article) |
| 50 | + scores = self.model.predict([ |
| 51 | + [query_text, candidate_text] |
| 52 | + ]) |
| 53 | + relevance_score = self._sigmoid(scores[0]) |
| 54 | + |
| 55 | + return float(relevance_score) |
| 56 | + |
| 57 | + except Exception as e: |
| 58 | + logger.error(f"Error computing relevance score: {e}") |
| 59 | + return 0.5 |
| 60 | + |
| 61 | + def compute_batch_relevance_scores( |
| 62 | + self, |
| 63 | + query_article: Dict[str, Any], |
| 64 | + candidate_articles: List[Dict[str, Any]] |
| 65 | + ) -> List[float]: |
| 66 | + """ |
| 67 | + Compute relevance scores between one query article and multiple candidates. |
| 68 | + |
| 69 | + Args: |
| 70 | + query_article: Source article |
| 71 | + candidate_articles: List of candidate articles |
| 72 | + |
| 73 | + Returns: |
| 74 | + List of relevance scores |
| 75 | + """ |
| 76 | + if self.model is None or not candidate_articles: |
| 77 | + return [0.5] * len(candidate_articles) |
| 78 | + |
| 79 | + try: |
| 80 | + query_text = self._build_article_text(query_article) |
| 81 | + |
| 82 | + pairs = [ |
| 83 | + [query_text, self._build_article_text(candidate)] |
| 84 | + for candidate in candidate_articles |
| 85 | + ] |
| 86 | + scores = self.model.predict(pairs) |
| 87 | + normalized_scores = [float(self._sigmoid(score)) for score in scores] |
| 88 | + |
| 89 | + return normalized_scores |
| 90 | + |
| 91 | + except Exception as e: |
| 92 | + logger.error(f"Error computing batch relevance scores: {e}") |
| 93 | + return [0.5] * len(candidate_articles) |
| 94 | + |
| 95 | + def _build_article_text(self, article: Dict[str, Any]) -> str: |
| 96 | + """ |
| 97 | + Build a text representation of an article for cross-encoder. |
| 98 | + |
| 99 | + Args: |
| 100 | + article: Article dictionary |
| 101 | + |
| 102 | + Returns: |
| 103 | + Combined text of title and description |
| 104 | + """ |
| 105 | + title = article.get("title", "").strip() |
| 106 | + description = article.get("description", "").strip() |
| 107 | + |
| 108 | + if title and description: |
| 109 | + return f"{title} {description}" |
| 110 | + elif title: |
| 111 | + return title |
| 112 | + elif description: |
| 113 | + return description |
| 114 | + else: |
| 115 | + return "" |
| 116 | + |
| 117 | + @staticmethod |
| 118 | + def _sigmoid(x: float) -> float: |
| 119 | + """Apply sigmoid function to normalize cross-encoder output.""" |
| 120 | + import math |
| 121 | + try: |
| 122 | + return 1.0 / (1.0 + math.exp(-x)) |
| 123 | + except OverflowError: |
| 124 | + return 0.0 if x < 0 else 1.0 |
0 commit comments