""" Enhanced Diversification for Recommender System Adds variety to recommendations so users don’t get stuck in a "filter bubble". """ import numpy as np import json from typing import List, Dict, Any, Set, Optional import random from enum import Enum import os class DiversificationStrategy: """ Controls how recommendations mix: - Exploitation (top-score items) - Exploration (diverse items) This prevents the model from only showing similar items. """ def __init__( self, exploration_rate: float = 0.2, # Probability of adding a diverse item strategic_positions: List[int] = None, # Positions where diversity is forced exploration_frequency: int = 5, # Insert diversity every N items min_interest_coverage: int = 3 # Ensure we show at least N interests ): self.exploration_rate = exploration_rate self.exploration_frequency = exploration_frequency self.strategic_positions = strategic_positions or [] self.min_interest_coverage = min_interest_coverage # ---------------------------------------------------------- # Generate positions where exploration should occur def _generate_strategic_positions(self, limit: int) -> List[int]: """Builds a list of indices (0-based) where diverse items must appear.""" if self.strategic_positions is not None: positions = list(self.strategic_positions) # If the recommendation list is longer, continue the pattern max_static = max(positions) if positions else 0 if limit > max_static: last_pos = positions[-1] if positions else -1 current = last_pos + self.exploration_frequency while current < limit: positions.append(current) current += self.exploration_frequency return [p for p in positions if p < limit] # Auto-generate if none given positions = [] current = self.exploration_frequency - 1 while current < limit: positions.append(current) current += self.exploration_frequency return positions # ---------------------------------------------------------- # Main diversification logic def diversify_recommendations( self, sorted_indices: np.ndarray, # Indices sorted by score plan_objects: List[Dict], # Raw plan data plan_ids: List[str], # IDs matching sorted_indices scores: List[float], # Model scores limit: int, # Max items to output user_interest_history: Set[str] = None ) -> List[Dict[str, Any]]: """ Produces a final list of recommendations that mix: - High-relevance items - Items from different interest categories """ if len(sorted_indices) == 0: return [] # Build strategic positions if missing if not self.strategic_positions: self.strategic_positions = self._generate_strategic_positions(limit) # Analyze which interests dominate the top results interest_groups = self._group_by_interests(sorted_indices, plan_objects) dominant_interest = self._find_dominant_interest(sorted_indices[:20], plan_objects) shown_interests = set() user_interest_history = user_interest_history or set() recommendations = [] used_indices = set() # Split into two groups: "normal" items and "diverse" items exploitation_buffer = [] exploration_candidates = [] for idx in sorted_indices: interests = self._get_plan_interests(plan_objects[idx]) # If the item doesn't share the dominant interest → it's diverse if dominant_interest and dominant_interest not in interests: exploration_candidates.append(idx) else: exploitation_buffer.append(idx) # Build final recommendation list for position in range(limit): if position >= len(sorted_indices): break # Decide if this slot should contain a diverse item should_explore = self._should_explore_at_position( position, shown_interests, user_interest_history ) chosen_idx = None # Exploration branch: choose diverse item if should_explore and exploration_candidates: chosen_idx = self._pick_exploration_item( exploration_candidates, shown_interests, plan_objects ) if chosen_idx is not None and chosen_idx not in used_indices: exploration_candidates.remove(chosen_idx) used_indices.add(chosen_idx) else: chosen_idx = None # Exploitation branch: fallback to top-ranked remaining items if chosen_idx is None: while exploitation_buffer: candidate = exploitation_buffer.pop(0) if candidate not in used_indices: chosen_idx = candidate used_indices.add(candidate) break # Last fallback: pick any remaining diverse item if chosen_idx is None: while exploration_candidates: candidate = exploration_candidates.pop(0) if candidate not in used_indices: chosen_idx = candidate used_indices.add(candidate) break if chosen_idx is None: break plan = plan_objects[chosen_idx] interests = self._get_plan_interests(plan) recommendations.append({ "item_id": plan_ids[chosen_idx], "score": float(scores[chosen_idx]), "is_exploration": should_explore, "interests": interests }) shown_interests.update(interests) return recommendations # ---------------------------------------------------------- # Pick the best exploration item def _pick_exploration_item( self, exploration_candidates: List[int], shown_interests: Set[str], plan_objects: List[Dict] ) -> Optional[int]: """ Selects a diverse item: - Prefer items with new interest categories - Fallback to any exploration candidate """ if not exploration_candidates: return None unseen_interest_items = [] seen_interest_items = [] # Limit to first 50 for speed for idx in exploration_candidates[:50]: interests = self._get_plan_interests(plan_objects[idx]) has_new_interest = any(i not in shown_interests for i in interests) if has_new_interest: unseen_interest_items.append(idx) else: seen_interest_items.append(idx) # Prefer new-interest items if unseen_interest_items: return unseen_interest_items[0] if seen_interest_items: return seen_interest_items[0] return exploration_candidates[0] # ---------------------------------------------------------- # Logic that decides when to explore def _should_explore_at_position( self, position: int, shown_interests: Set[str], user_interest_history: Set[str] ) -> bool: """ Decides whether this position should contain a diverse item. Rules: - Early items must be high-quality (no exploration) - Some positions are always exploration - If variety is low, increase exploration - Random chance also involved """ if position < 2: return False if self.strategic_positions and position in self.strategic_positions: return True if len(shown_interests) < self.min_interest_coverage: if position % 3 == 0: return True return random.random() < self.exploration_rate # ---------------------------------------------------------- # Group items by their interest category def _group_by_interests(self, indices, plan_objects) -> Dict[str, List[int]]: """Builds a mapping: interest → list of item indices.""" groups = {} for idx in indices: for interest in self._get_plan_interests(plan_objects[idx]): groups.setdefault(interest, []).append(idx) return groups # ---------------------------------------------------------- # Detect dominant interest among top items def _find_dominant_interest(self, top_indices, plan_objects) -> str: """ Finds the interest category that appears most frequently in the top N items. This helps determine what counts as "diverse". """ interest_counts = {} for idx in top_indices: for interest in self._get_plan_interests(plan_objects[idx]): interest_counts[interest] = interest_counts.get(interest, 0) + 1 if not interest_counts: return None return max(interest_counts, key=interest_counts.get) # ---------------------------------------------------------- # Parse a plan's interest list safely def _get_plan_interests(self, plan: Dict) -> List[str]: """Returns a clean list of interest IDs, even if stored as a JSON string.""" raw = plan.get("interestIds", []) if isinstance(raw, str): try: raw = json.loads(raw) except Exception: raw = [] if not isinstance(raw, list): raw = [] return [str(i) for i in raw] # ===================================================================== # PRESET DIVERSITY LEVELS (simple configs) # ===================================================================== class DiversityLevel(Enum): """Simple preset modes for diversity.""" FOCUSED = "focused" BALANCED = "balanced" DISCOVERY = "discovery" AGGRESSIVE = "aggressive" @classmethod def get_config(cls, level): """Return ready-to-use settings for each mode.""" configs = { cls.FOCUSED: {"exploration_rate": 0.1, "exploration_frequency": 10, "strategic_positions": None, "min_interest_coverage": 2, "description": "Show mostly focused recommendations"}, cls.BALANCED: {"exploration_rate": 0.2, "exploration_frequency": 5, "strategic_positions": None, "min_interest_coverage": 3, "description": "Balanced mix of relevance and variety"}, cls.DISCOVERY: {"exploration_rate": 0.35,"exploration_frequency": 3, "strategic_positions": None, "min_interest_coverage": 4, "description": "Help user explore new interests"}, cls.AGGRESSIVE:{"exploration_rate": 0.5, "exploration_frequency": 2, "strategic_positions": None, "min_interest_coverage": 5, "description": "Highly diverse results"}, } return configs[level] # ===================================================================== # CONFIGURATION MANAGER (global + per-user settings) # ===================================================================== class DiversityConfigManager: """ Loads and manages global diversity configuration. """ def __init__(self, config_path: str = "config/diversity_config.json"): self.config_path = config_path self.global_config = self._load_config() def _load_config(self): """Load configuration file or fallback to defaults.""" if os.path.exists(self.config_path): try: with open(self.config_path, "r") as f: return json.load(f) except Exception: pass # if file is corrupted → fallback to defaults # Default mode → DISCOVERY base = DiversityLevel.get_config(DiversityLevel.DISCOVERY) return { "exploration_rate": base["exploration_rate"], "exploration_frequency": base["exploration_frequency"], "strategic_positions": base["strategic_positions"], "min_interest_coverage": base["min_interest_coverage"], } def get_config(self): """Return global diversity configuration.""" return self.global_config # ===================================================================== # USED BY THE RECOMMENDER CLASS # ===================================================================== class DiversityController: """ Helper used inside the main recommender. Fetches correct diversification settings and adjusts based on context. """ def __init__(self, config_manager: DiversityConfigManager): self.config_manager = config_manager def get_diversification_params(self): return self.config_manager.global_config def apply_context_adjustment(self, params: Dict[str, Any], context: Dict[str, Any]): """ Adjust parameters depending on: - New users - Discovery mode - Search queries - Time of day """ adjusted = params.copy() if context.get("is_new_user"): adjusted["exploration_rate"] = min(0.4, adjusted["exploration_rate"] * 1.5) if context.get("mode") == "discovery": adjusted["exploration_rate"] = 0.5 adjusted["min_interest_coverage"] = 5 if context.get("search_query"): adjusted["exploration_rate"] *= 0.5 if (hour := context.get("hour")) and 20 <= hour <= 23: adjusted["exploration_rate"] = min(0.4, adjusted["exploration_rate"] * 1.2) return adjusted