oximedia-recommend 0.1.2

Content recommendation engine for media libraries
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Content recommendation and discovery engine for `OxiMedia`.
//!
//! `oximedia-recommend` provides comprehensive recommendation capabilities for media platforms,
//! including content-based filtering, collaborative filtering, hybrid approaches, and
//! advanced personalization features.
//!
//! # Features
//!
//! - **Content-based Filtering**: Recommend similar content based on features
//! - **Collaborative Filtering**: User behavior-based recommendations
//! - **Hybrid Approach**: Combine multiple recommendation methods
//! - **Similarity Metrics**: Calculate content similarity using various metrics
//! - **User Profiles**: Build and manage user preference profiles
//! - **View History**: Track and analyze viewing patterns
//! - **Rating System**: Handle explicit and implicit ratings
//! - **Trending Detection**: Identify trending content in real-time
//! - **Personalization**: Context-aware personalized recommendations
//! - **Diversity**: Ensure recommendation diversity and avoid filter bubbles
//! - **Freshness**: Balance popular and new content
//!
//! # Modules
//!
//! - [`content`]: Content-based filtering and similarity
//! - [`collaborative`]: Collaborative filtering algorithms
//! - [`hybrid`]: Hybrid recommendation approaches
//! - [`profile`]: User profile management
//! - [`history`]: View history tracking and analysis
//! - [`rating`]: Rating system (explicit and implicit)
//! - [`trending`]: Trending content detection
//! - [`personalize`]: Personalization engine
//! - [`diversity`]: Diversity enforcement
//! - [`freshness`]: Fresh content promotion
//! - [`rank`]: Ranking and scoring
//! - [`explain`]: Recommendation explanations
//!
//! # Example
//!
//! ```
//! use oximedia_recommend::{RecommendationEngine, RecommendationRequest};
//! use uuid::Uuid;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a recommendation engine
//! let engine = RecommendationEngine::new();
//!
//! // Get recommendations for a user
//! let user_id = Uuid::new_v4();
//! let request = RecommendationRequest {
//!     user_id,
//!     limit: 10,
//!     ..Default::default()
//! };
//!
//! // let recommendations = engine.recommend(&request)?;
//! # Ok(())
//! # }
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::similar_names)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::missing_errors_doc)]
#![allow(dead_code)]

pub mod ab_test;
pub mod als;
pub mod bandits;
pub mod calibration;
pub mod cold_start;
pub mod collab_filter;
pub mod collaborative;
pub mod content;
pub mod content_based;
pub mod context_signal;
pub mod decay_model;
pub mod dense_linalg;
pub mod diversity;
pub mod error;
pub mod explain;
pub mod exploration_policy;
pub mod feature_store;
pub mod feedback_signal;
pub mod freshness;
pub mod history;
pub mod hybrid;
pub mod impression_tracker;
pub mod item_similarity;
pub mod lsh;
pub mod personalize;
pub mod popularity_bias;
pub mod profile;
pub mod rank;
pub mod ranking;
pub mod rating;
pub mod recommendation_score;
pub mod score_cache;
pub mod sequence_model;
pub mod session;
pub mod svd_pp;
pub mod trending;
pub mod user_profile;

// Re-export commonly used items
pub use error::{RecommendError, RecommendResult};

use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Main recommendation engine coordinating all recommendation capabilities
pub struct RecommendationEngine {
    /// Content-based recommender
    content_recommender: content::similarity::ContentRecommender,
    /// Collaborative filtering engine
    collaborative_engine: collaborative::matrix::CollaborativeEngine,
    /// Hybrid combiner
    hybrid_combiner: hybrid::combine::HybridCombiner,
    /// User profile manager
    profile_manager: profile::user::UserProfileManager,
    /// View history tracker
    history_tracker: history::track::HistoryTracker,
    /// Rating manager
    rating_manager: rating::explicit::RatingManager,
    /// Trending detector
    trending_detector: trending::detect::TrendingDetector,
    /// Personalization engine
    personalization_engine: personalize::engine::PersonalizationEngine,
    /// Diversity enforcer
    diversity_enforcer: diversity::ensure::DiversityEnforcer,
    /// Freshness balancer
    freshness_balancer: freshness::balance::FreshnessBalancer,
}

/// Recommendation request configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecommendationRequest {
    /// User ID to get recommendations for
    pub user_id: Uuid,
    /// Number of recommendations to return
    pub limit: usize,
    /// Content ID to base recommendations on (optional)
    pub content_id: Option<Uuid>,
    /// Recommendation strategy to use
    pub strategy: RecommendationStrategy,
    /// Context information
    pub context: RecommendationContext,
    /// Diversity settings
    pub diversity: DiversitySettings,
    /// Include explanations
    pub include_explanations: bool,
}

/// Recommendation strategy
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum RecommendationStrategy {
    /// Content-based filtering only
    ContentBased,
    /// Collaborative filtering only
    Collaborative,
    /// Hybrid approach (combines multiple methods)
    Hybrid,
    /// Personalized recommendations
    Personalized,
    /// Trending content
    Trending,
}

/// Context information for recommendations
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RecommendationContext {
    /// Current time (unix timestamp)
    pub timestamp: Option<i64>,
    /// Device type
    pub device: Option<String>,
    /// Location
    pub location: Option<String>,
    /// Session ID
    pub session_id: Option<Uuid>,
    /// Time of day
    pub time_of_day: Option<TimeOfDay>,
    /// Day of week
    pub day_of_week: Option<u8>,
}

/// Time of day categories
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum TimeOfDay {
    /// Morning (6am-12pm)
    Morning,
    /// Afternoon (12pm-6pm)
    Afternoon,
    /// Evening (6pm-10pm)
    Evening,
    /// Night (10pm-6am)
    Night,
}

/// Diversity settings for recommendations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiversitySettings {
    /// Enable diversity enforcement
    pub enabled: bool,
    /// Minimum category diversity (0.0-1.0)
    pub category_diversity: f32,
    /// Include novel/surprising items
    pub include_serendipity: bool,
    /// Serendipity weight (0.0-1.0)
    pub serendipity_weight: f32,
}

/// Recommendation result item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Recommendation {
    /// Content ID
    pub content_id: Uuid,
    /// Recommendation score (0.0-1.0)
    pub score: f32,
    /// Rank in recommendation list
    pub rank: usize,
    /// Reasons for recommendation
    pub reasons: Vec<RecommendationReason>,
    /// Content metadata
    pub metadata: ContentMetadata,
    /// Explanation (if requested)
    pub explanation: Option<String>,
}

/// Reason for recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RecommendationReason {
    /// Similar to content the user liked
    SimilarToLiked {
        /// ID of the similar content that the user liked
        content_id: Uuid,
        /// Similarity score (0-1)
        similarity: f32,
    },
    /// Users similar to you also liked this
    CollaborativeFiltering {
        /// Confidence score (0-1)
        confidence: f32,
    },
    /// Trending in your area/globally
    Trending {
        /// Trending score indicating popularity momentum
        trending_score: f32,
    },
    /// Matches your interests
    MatchesProfile {
        /// Categories that matched the user profile
        categories: Vec<String>,
    },
    /// New/fresh content
    FreshContent {
        /// Number of days since publication
        published_days_ago: u32,
    },
    /// Popular content
    Popular {
        /// Total view count
        view_count: u64,
    },
    /// Completes a series/collection
    ContinueWatching {
        /// Watch progress (0-1)
        progress: f32,
    },
}

/// Content metadata for recommendations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentMetadata {
    /// Content title
    pub title: String,
    /// Content description
    pub description: Option<String>,
    /// Categories/genres
    pub categories: Vec<String>,
    /// Duration (milliseconds)
    pub duration_ms: Option<i64>,
    /// Thumbnail URL
    pub thumbnail_url: Option<String>,
    /// Created timestamp
    pub created_at: i64,
    /// Average rating
    pub avg_rating: Option<f32>,
    /// View count
    pub view_count: u64,
}

/// Recommendation results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecommendationResults {
    /// User ID
    pub user_id: Uuid,
    /// Recommended items
    pub recommendations: Vec<Recommendation>,
    /// Total candidates evaluated
    pub total_candidates: usize,
    /// Processing time (milliseconds)
    pub processing_time_ms: u64,
    /// Strategy used
    pub strategy: RecommendationStrategy,
}

impl RecommendationEngine {
    /// Create a new recommendation engine
    #[must_use]
    pub fn new() -> Self {
        Self {
            content_recommender: content::similarity::ContentRecommender::new(),
            collaborative_engine: collaborative::matrix::CollaborativeEngine::new(),
            hybrid_combiner: hybrid::combine::HybridCombiner::new(),
            profile_manager: profile::user::UserProfileManager::new(),
            history_tracker: history::track::HistoryTracker::new(),
            rating_manager: rating::explicit::RatingManager::new(),
            trending_detector: trending::detect::TrendingDetector::new(),
            personalization_engine: personalize::engine::PersonalizationEngine::new(),
            diversity_enforcer: diversity::ensure::DiversityEnforcer::new(),
            freshness_balancer: freshness::balance::FreshnessBalancer::new(0.3, 30),
        }
    }

    /// Get recommendations for a user
    ///
    /// For the `Hybrid` strategy, all sub-strategies are evaluated in parallel
    /// via rayon.  The resulting candidate lists are merged and deduplicated by
    /// content ID, taking the maximum score for any item that appeared in
    /// multiple strategy outputs.
    ///
    /// # Errors
    ///
    /// Returns an error if recommendation generation fails
    pub fn recommend(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<RecommendationResults> {
        use std::collections::HashMap;

        let start = std::time::Instant::now();

        // Get candidates based on strategy.
        // For Hybrid, all strategies are evaluated in parallel with rayon.
        let candidates = match request.strategy {
            RecommendationStrategy::ContentBased => {
                self.get_content_based_recommendations(request)?
            }
            RecommendationStrategy::Collaborative => {
                self.get_collaborative_recommendations(request)?
            }
            RecommendationStrategy::Hybrid => self.get_hybrid_parallel(request)?,
            RecommendationStrategy::Personalized => {
                self.get_personalized_recommendations(request)?
            }
            RecommendationStrategy::Trending => self.get_trending_recommendations(request)?,
        };

        // Deduplicate merged candidates: keep highest score per content_id
        let candidates = {
            let mut best: HashMap<uuid::Uuid, Recommendation> = HashMap::new();
            for rec in candidates {
                let entry = best.entry(rec.content_id);
                entry
                    .and_modify(|existing| {
                        if rec.score > existing.score {
                            *existing = rec.clone();
                        }
                    })
                    .or_insert(rec);
            }
            let mut deduped: Vec<Recommendation> = best.into_values().collect();
            deduped.sort_by(|a, b| {
                b.score
                    .partial_cmp(&a.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            deduped
        };

        // Apply diversity if enabled
        let diverse_candidates = if request.diversity.enabled {
            self.diversity_enforcer
                .enforce_diversity(candidates, &request.diversity)?
        } else {
            candidates
        };

        // Apply freshness balancing
        let balanced_candidates = self.freshness_balancer.balance(diverse_candidates)?;

        // Rank and score
        let mut ranked = self.rank_recommendations(balanced_candidates)?;

        // Limit results
        ranked.truncate(request.limit);

        // Add explanations if requested
        if request.include_explanations {
            self.add_explanations(&mut ranked)?;
        }

        let processing_time_ms = start.elapsed().as_millis() as u64;

        let total_candidates = ranked.len();
        Ok(RecommendationResults {
            user_id: request.user_id,
            recommendations: ranked,
            total_candidates,
            processing_time_ms,
            strategy: request.strategy,
        })
    }

    /// Get content-based recommendations
    fn get_content_based_recommendations(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        self.content_recommender.recommend(request)
    }

    /// Get collaborative filtering recommendations
    fn get_collaborative_recommendations(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        self.collaborative_engine.recommend(request)
    }

    /// Get hybrid recommendations (single-threaded, delegates to HybridCombiner)
    fn get_hybrid_recommendations(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        self.hybrid_combiner.recommend(request)
    }

    /// Evaluate all non-Hybrid strategies in parallel via rayon and merge results.
    ///
    /// Each strategy is run concurrently; any strategy that fails is silently
    /// dropped so that a single sub-strategy error never blocks results from
    /// the others.
    fn get_hybrid_parallel(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        use rayon::prelude::*;

        // List of strategy labels to evaluate in parallel.
        // We exclude Hybrid itself to avoid recursion.
        let strategies: &[RecommendationStrategy] = &[
            RecommendationStrategy::ContentBased,
            RecommendationStrategy::Collaborative,
            RecommendationStrategy::Personalized,
            RecommendationStrategy::Trending,
        ];

        // Evaluate strategies in parallel; collect successful results.
        let parallel_results: Vec<Vec<Recommendation>> = strategies
            .par_iter()
            .filter_map(|strategy| {
                let result = match strategy {
                    RecommendationStrategy::ContentBased => {
                        self.get_content_based_recommendations(request)
                    }
                    RecommendationStrategy::Collaborative => {
                        self.get_collaborative_recommendations(request)
                    }
                    RecommendationStrategy::Personalized => {
                        self.get_personalized_recommendations(request)
                    }
                    RecommendationStrategy::Trending => self.get_trending_recommendations(request),
                    RecommendationStrategy::Hybrid => return None,
                };
                result.ok()
            })
            .collect();

        // Also get the HybridCombiner result (which has its own weighting logic)
        let combiner_result = self.hybrid_combiner.recommend(request).unwrap_or_default();

        // Merge all candidate lists
        let mut merged: Vec<Recommendation> = parallel_results.into_iter().flatten().collect();
        merged.extend(combiner_result);
        Ok(merged)
    }

    /// Get personalized recommendations
    fn get_personalized_recommendations(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        self.personalization_engine.recommend(request)
    }

    /// Get trending recommendations
    fn get_trending_recommendations(
        &self,
        request: &RecommendationRequest,
    ) -> RecommendResult<Vec<Recommendation>> {
        self.trending_detector.get_trending(request.limit)
    }

    /// Rank recommendations
    fn rank_recommendations(
        &self,
        candidates: Vec<Recommendation>,
    ) -> RecommendResult<Vec<Recommendation>> {
        rank::score::rank_recommendations(candidates)
    }

    /// Add explanations to recommendations
    fn add_explanations(&self, recommendations: &mut [Recommendation]) -> RecommendResult<()> {
        for rec in recommendations {
            let explanation = explain::generate::generate_explanation(rec)?;
            rec.explanation = Some(explanation);
        }
        Ok(())
    }

    /// Record a user view event
    ///
    /// # Errors
    ///
    /// Returns an error if recording fails
    pub fn record_view(
        &mut self,
        user_id: Uuid,
        content_id: Uuid,
        watch_time_ms: i64,
        completed: bool,
    ) -> RecommendResult<()> {
        // Record in history
        self.history_tracker
            .record_view(user_id, content_id, watch_time_ms, completed)?;

        // Update user profile
        self.profile_manager
            .update_from_view(user_id, content_id, watch_time_ms, completed)?;

        // Update implicit rating
        self.rating_manager.update_implicit_rating(
            user_id,
            content_id,
            watch_time_ms,
            completed,
        )?;

        Ok(())
    }

    /// Record an explicit rating
    ///
    /// # Errors
    ///
    /// Returns an error if recording fails
    pub fn record_rating(
        &mut self,
        user_id: Uuid,
        content_id: Uuid,
        rating: f32,
    ) -> RecommendResult<()> {
        self.rating_manager
            .record_rating(user_id, content_id, rating)?;
        self.profile_manager
            .update_from_rating(user_id, content_id, rating)?;
        Ok(())
    }

    /// Update trending scores
    ///
    /// # Errors
    ///
    /// Returns an error if update fails
    pub fn update_trending(&mut self) -> RecommendResult<()> {
        self.trending_detector.update_scores()
    }

    /// Get user profile
    ///
    /// # Errors
    ///
    /// Returns an error if retrieval fails
    pub fn get_user_profile(&self, user_id: Uuid) -> RecommendResult<profile::user::UserProfile> {
        self.profile_manager.get_profile(user_id)
    }

    /// Get similar users
    ///
    /// # Errors
    ///
    /// Returns an error if retrieval fails
    pub fn get_similar_users(&self, user_id: Uuid, limit: usize) -> RecommendResult<Vec<Uuid>> {
        self.profile_manager.get_similar_users(user_id, limit)
    }
}

impl Default for RecommendationEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for RecommendationRequest {
    fn default() -> Self {
        Self {
            user_id: Uuid::new_v4(),
            limit: 10,
            content_id: None,
            strategy: RecommendationStrategy::Hybrid,
            context: RecommendationContext::default(),
            diversity: DiversitySettings::default(),
            include_explanations: false,
        }
    }
}

impl Default for DiversitySettings {
    fn default() -> Self {
        Self {
            enabled: true,
            category_diversity: 0.3,
            include_serendipity: true,
            serendipity_weight: 0.1,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_recommendation_engine_creation() {
        let engine = RecommendationEngine::new();
        assert!(std::mem::size_of_val(&engine) > 0);
    }

    #[test]
    fn test_recommendation_request_default() {
        let request = RecommendationRequest::default();
        assert_eq!(request.limit, 10);
        assert!(matches!(request.strategy, RecommendationStrategy::Hybrid));
    }

    #[test]
    fn test_diversity_settings_default() {
        let settings = DiversitySettings::default();
        assert!(settings.enabled);
        assert!((settings.category_diversity - 0.3).abs() < f32::EPSILON);
    }

    #[test]
    fn test_recommendation_strategy_variants() {
        let strategies = [
            RecommendationStrategy::ContentBased,
            RecommendationStrategy::Collaborative,
            RecommendationStrategy::Hybrid,
            RecommendationStrategy::Personalized,
            RecommendationStrategy::Trending,
        ];
        assert_eq!(strategies.len(), 5);
    }

    #[test]
    fn test_recommend_hybrid_parallel_succeeds() {
        let engine = RecommendationEngine::new();
        let request = RecommendationRequest {
            strategy: RecommendationStrategy::Hybrid,
            limit: 10,
            ..Default::default()
        };
        // Hybrid should run in parallel without panicking and return Ok
        let result = engine.recommend(&request);
        assert!(result.is_ok());
        assert!(matches!(
            result.expect("hybrid recommend should succeed").strategy,
            RecommendationStrategy::Hybrid
        ));
    }

    #[test]
    fn test_recommend_all_strategies_run() {
        let engine = RecommendationEngine::new();
        for strategy in [
            RecommendationStrategy::ContentBased,
            RecommendationStrategy::Collaborative,
            RecommendationStrategy::Hybrid,
            RecommendationStrategy::Personalized,
            RecommendationStrategy::Trending,
        ] {
            let request = RecommendationRequest {
                strategy,
                limit: 5,
                ..Default::default()
            };
            let result = engine.recommend(&request);
            assert!(result.is_ok(), "strategy {strategy:?} failed");
        }
    }
}