Spaces:
Sleeping
Sleeping
Download model/feature_extractor.py from marcolouis/romio_explore_ai_api: direct link, hf CLI and curl.
- Browser
- Download file 8.36 kB
-
https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/feature_extractor.py
- Command line
-
hf download hf://spaces/marcolouis/romio_explore_ai_api/model/feature_extractor.py
-
curl -L -o feature_extractor.py https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/feature_extractor.py
8.36 kB
| """ | |
| 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()} | |