File size: 8,355 Bytes
9166aef
9031b79
 
9166aef
 
 
 
 
 
 
 
 
 
9031b79
 
9166aef
720e732
9166aef
9031b79
 
 
9166aef
 
720e732
9031b79
9166aef
 
720e732
9031b79
 
 
 
720e732
 
 
9166aef
9031b79
 
 
 
 
9166aef
9031b79
 
9166aef
9031b79
 
 
720e732
9031b79
9166aef
 
9031b79
720e732
9031b79
 
 
 
 
720e732
9031b79
 
 
 
720e732
9031b79
 
 
 
720e732
9166aef
720e732
 
9166aef
720e732
9031b79
 
 
 
9166aef
720e732
9166aef
 
9031b79
 
 
720e732
9031b79
9166aef
9031b79
 
 
 
 
 
720e732
9031b79
720e732
 
9031b79
 
720e732
 
 
9166aef
720e732
9031b79
 
 
dd7220f
9031b79
dd7220f
 
9031b79
720e732
9166aef
9031b79
9166aef
720e732
9031b79
 
 
 
720e732
9031b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720e732
 
9031b79
 
720e732
 
9166aef
720e732
9031b79
 
9166aef
9031b79
720e732
9166aef
 
720e732
 
 
9031b79
 
720e732
 
 
9031b79
720e732
 
 
 
 
 
9166aef
720e732
9031b79
 
 
 
9166aef
 
 
 
720e732
9166aef
 
9031b79
 
 
 
 
 
9166aef
9031b79
 
720e732
9166aef
9031b79
720e732
9031b79
 
720e732
9031b79
720e732
 
9031b79
720e732
 
9031b79
 
 
 
720e732
 
9031b79
720e732
 
 
 
9031b79
 
 
720e732
9031b79
 
 
 
720e732
9031b79
720e732
9031b79
 
 
720e732
9166aef
9031b79
 
720e732
 
 
 
9166aef
720e732
9031b79
720e732
9166aef
9031b79
720e732
9031b79
720e732
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
"""
Feature extraction utilities for ML models.
Converts raw Supabase plan/user/place data into normalized tensors.
"""

import json
import torch
import numpy as np
from typing import List, Dict, Any, Tuple


class FeatureExtractor:
    """
    Extracts numerical and sequence features from plans and user interactions.
    Handles JSON parsing, vocabulary mapping, padding, and safe fallbacks.
    """

    def __init__(self):
        # Dictionaries mapping raw IDs → index values used by the model
        self.interest_to_idx = {}
        self.category_to_idx = {}
        self.user_to_idx = {}
        self.plan_to_idx = {}

        # Reverse lookup dictionaries (index → original ID)
        self.idx_to_interest = {}
        self.idx_to_category = {}

    # ============================================================
    # Vocabulary construction
    # ============================================================

    def build_vocabularies(
        self, plans: List[Dict], places: List[Dict], interests: List[Dict]
    ):
        """
        Build ID → index vocabularies for:
        - interests
        - place categories

        Must be called before training.
        """

        # Map interest IDs
        for idx, interest in enumerate(interests):
            iid = str(interest["id"])
            self.interest_to_idx[iid] = idx
            self.idx_to_interest[idx] = iid

        # Collect unique place categories
        unique_categories = set()
        for place in places:
            cats = place.get("categories", "[]")

            # Safe JSON handling
            try:
                cats = json.loads(cats) if isinstance(cats, str) else cats
            except Exception:
                cats = []

            for c in cats:
                name = c.get("name", "")
                if name:
                    unique_categories.add(name)

        # Map category names
        for idx, cat in enumerate(sorted(unique_categories)):
            self.category_to_idx[cat] = idx
            self.idx_to_category[idx] = cat

        return {
            "n_interests": len(self.interest_to_idx),
            "n_categories": len(self.category_to_idx),
        }

    # ============================================================
    # Plan feature extraction
    # ============================================================

    def extract_plan_features(
        self, plan: Dict[str, Any], places_data: List[Dict[str, Any]] = None
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        """
        Extracts:
        - interest ID indices (fixed-length padded tensor)
        - normalized numerical features

        Always safe: falls back to defaults if data is missing or corrupted.
        """

        # --------------------------------------------
        # Interest IDs
        # --------------------------------------------
        raw = plan.get("interestIds", [])
        if isinstance(raw, str):
            try:
                interest_ids = json.loads(raw)
            except Exception:
                interest_ids = []
        elif isinstance(raw, list):
            interest_ids = raw
        else:
            interest_ids = []

        interest_indices = []
        for iid in interest_ids:
            iid = str(iid)
            if iid in self.interest_to_idx:
                interest_indices.append(self.interest_to_idx[iid])
            else:
                interest_indices.append(0)  # unknown/default

        if not interest_indices:
            interest_indices = [0]

        max_interests = 5
        interest_indices = (interest_indices + [0] * max_interests)[:max_interests]
        interest_tensor = torch.tensor(interest_indices, dtype=torch.long)

        # --------------------------------------------
        # Numerical fields (safe parsing)
        # --------------------------------------------
        def safe_float(value, default):
            try:
                return float(value)
            except Exception:
                return default

        rating = safe_float(plan.get("rating", 3.0), 3.0)
        min_price = safe_float(plan.get("minPrice", 0), 0.0)
        max_price = safe_float(plan.get("maxPrice", 100), 100.0)
        min_dist = safe_float(plan.get("minDist", 0), 0.0)
        max_dist = safe_float(plan.get("maxDist", 10), 10.0)

        # Places count
        raw_places = plan.get("placeIds", [])
        if isinstance(raw_places, str):
            try:
                place_ids = json.loads(raw_places)
            except Exception:
                place_ids = []
        elif isinstance(raw_places, list):
            place_ids = raw_places
        else:
            place_ids = []
        n_places = len(place_ids)

        # Derived features
        avg_place_rating = 3.5
        if places_data:
            avg_place_rating = np.mean([3.5 for _ in places_data]) if places_data else 3.5

        price_range = max_price - min_price
        dist_range = max_dist - min_dist

        numerical_features = torch.tensor(
            [
                rating / 5.0,
                min_price / 1000.0,
                max_price / 1000.0,
                min_dist / 10.0,
                max_dist / 10.0,
                n_places / 10.0,
                avg_place_rating / 5.0,
                price_range / 1000.0,
            ],
            dtype=torch.float32,
        )

        return interest_tensor, numerical_features

    # ============================================================
    # User interaction sequence encoding
    # ============================================================

    def extract_user_interaction_sequence(
        self,
        interactions: List[Dict[str, Any]],
        plan_embeddings: Dict[str, torch.Tensor],
        max_sequence_length: int = 20,
    ) -> torch.Tensor:
        """
        Converts a user's historical interactions into a fixed-length sequence tensor.
        Each step contains:
        - plan embedding (size 64)
        - rating/bookmark/duration features

        Always pads or truncates to max_sequence_length.
        """

        sequence_list = []

        for interaction in interactions[-max_sequence_length:]:
            pid = str(interaction["plan_id"])

            # Use plan embedding if available, else zeros
            plan_emb = plan_embeddings.get(pid, torch.zeros(64))

            # Safe rating parsing
            raw_rating = interaction.get("rating", 0)
            try:
                rating = float(raw_rating or 0) / 5.0
            except Exception:
                rating = 0.0

            is_bookmarked = 1.0 if interaction.get("interaction_type") == "bookmark" else 0.0

            # Safe duration parsing
            raw_duration = interaction.get("duration_seconds", 0)
            try:
                duration = float(raw_duration or 0) / 300.0
            except Exception:
                duration = 0.0
            duration = min(duration, 1.0)

            extra = torch.tensor([rating, is_bookmarked, duration])
            full = torch.cat([plan_emb, extra])
            sequence_list.append(full)

        # Pad with zeros if needed
        feature_size = 64 + 3
        while len(sequence_list) < max_sequence_length:
            sequence_list.append(torch.zeros(feature_size))

        return torch.stack(sequence_list[:max_sequence_length])

    # ============================================================
    # Vocabulary saving/loading
    # ============================================================

    def save_vocabularies(self, path: str):
        """Save vocabularies to disk."""
        data = {
            "interest_to_idx": self.interest_to_idx,
            "category_to_idx": self.category_to_idx,
            "idx_to_interest": self.idx_to_interest,
            "idx_to_category": self.idx_to_category,
        }
        with open(path, "w") as f:
            json.dump(data, f)

    def load_vocabularies(self, path: str):
        """Load vocabularies from disk."""
        with open(path, "r") as f:
            data = json.load(f)

        self.interest_to_idx = data["interest_to_idx"]
        self.category_to_idx = data["category_to_idx"]
        self.idx_to_interest = {int(k): v for k, v in data["idx_to_interest"].items()}
        self.idx_to_category = {int(k): v for k, v in data["idx_to_category"].items()}