File size: 13,964 Bytes
be1c9c3
 
9031b79
be1c9c3
 
 
 
 
 
 
 
 
 
 
 
9031b79
 
 
be1c9c3
9031b79
be1c9c3
9031b79
be1c9c3
9031b79
 
 
 
 
be1c9c3
 
 
 
 
9031b79
 
 
be1c9c3
9031b79
be1c9c3
 
9031b79
 
be1c9c3
 
 
 
 
 
 
9031b79
be1c9c3
9031b79
 
be1c9c3
9031b79
be1c9c3
 
 
 
9031b79
 
 
be1c9c3
 
9031b79
 
 
 
 
be1c9c3
 
 
9031b79
 
 
be1c9c3
9031b79
be1c9c3
 
9031b79
 
be1c9c3
 
 
9031b79
be1c9c3
9031b79
 
be1c9c3
 
9031b79
be1c9c3
9031b79
 
 
67a1b5e
 
9031b79
67a1b5e
9031b79
 
 
67a1b5e
 
 
 
9031b79
 
be1c9c3
 
 
9031b79
 
be1c9c3
 
 
9031b79
be1c9c3
9031b79
 
be1c9c3
 
9031b79
be1c9c3
67a1b5e
be1c9c3
9031b79
67a1b5e
9031b79
 
 
67a1b5e
 
 
 
 
9031b79
67a1b5e
9031b79
 
67a1b5e
 
 
 
 
9031b79
67a1b5e
9031b79
be1c9c3
 
9031b79
be1c9c3
9031b79
 
be1c9c3
 
 
 
9031b79
be1c9c3
9031b79
 
 
be1c9c3
67a1b5e
9031b79
 
67a1b5e
 
 
 
 
9031b79
 
 
 
 
 
67a1b5e
 
9031b79
67a1b5e
 
9031b79
 
 
 
67a1b5e
9031b79
67a1b5e
 
 
 
9031b79
 
67a1b5e
 
9031b79
67a1b5e
9031b79
 
 
 
 
be1c9c3
9031b79
 
be1c9c3
 
 
9031b79
 
 
 
 
 
 
 
 
be1c9c3
 
9031b79
be1c9c3
 
9031b79
be1c9c3
 
 
9031b79
 
 
 
 
 
 
be1c9c3
 
9031b79
 
be1c9c3
9031b79
 
 
 
 
 
 
 
be1c9c3
 
9031b79
be1c9c3
9031b79
be1c9c3
 
9031b79
be1c9c3
9031b79
 
 
be1c9c3
9031b79
 
 
 
be1c9c3
9031b79
be1c9c3
9031b79
 
 
 
be1c9c3
9031b79
be1c9c3
9031b79
 
 
be1c9c3
 
9031b79
 
 
 
 
 
 
be1c9c3
9031b79
 
be1c9c3
9031b79
 
 
 
be1c9c3
 
 
 
9031b79
 
 
be1c9c3
 
 
57fc5f7
be1c9c3
9031b79
be1c9c3
 
 
9031b79
 
 
be1c9c3
 
9031b79
be1c9c3
9031b79
57fc5f7
be1c9c3
9031b79
 
be1c9c3
 
 
 
 
 
9031b79
57fc5f7
 
 
9031b79
 
 
 
 
be1c9c3
 
 
9031b79
 
be1c9c3
9031b79
be1c9c3
 
9031b79
57fc5f7
 
9031b79
 
be1c9c3
9031b79
 
 
 
 
be1c9c3
 
9031b79
be1c9c3
 
9031b79
be1c9c3
 
 
 
9031b79
 
be1c9c3
9031b79
 
be1c9c3
9031b79
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"""
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