Introduction
In this tutorial, we'll explore how to build a content recommendation system that could potentially leverage partnerships like the upcoming YouTube Premium and Peacock bundle. This system will demonstrate how to combine multiple streaming services' content libraries to provide personalized recommendations. While the actual partnership details are about bundling services, we'll focus on the underlying technology that enables such integrations.
By the end of this tutorial, you'll have built a prototype recommendation engine that can work with multiple content providers, similar to what companies like NBCUniversal and Google might use to create bundled offerings.
Prerequisites
- Python 3.7 or higher installed
- Basic understanding of machine learning concepts
- Knowledge of REST APIs and HTTP requests
- Installed libraries: requests, pandas, scikit-learn, numpy
Step-by-Step Instructions
1. Set up the project structure
First, create a new directory for our recommendation system and initialize the project structure:
mkdir content_recommender
cd content_recommender
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install requests pandas scikit-learn numpy
This creates a clean environment for our project and installs the necessary dependencies for handling data and implementing machine learning algorithms.
2. Create mock data for content providers
Since we can't access real streaming APIs without proper credentials, we'll create mock data representing content from different providers:
import pandas as pd
import numpy as np
# Create mock data for different content providers
providers = ['YouTube', 'Peacock', 'Netflix', 'Hulu']
# Generate mock content data
np.random.seed(42)
content_data = {
'title': [f'Content_{i}' for i in range(100)],
'provider': np.random.choice(providers, 100),
'genre': np.random.choice(['Action', 'Comedy', 'Drama', 'Sci-Fi', 'Documentary'], 100),
'rating': np.random.uniform(1, 10, 100),
'duration': np.random.randint(30, 180, 100),
'year': np.random.randint(2000, 2024, 100)
}
content_df = pd.DataFrame(content_data)
content_df.to_csv('content_data.csv', index=False)
print(content_df.head())
This step creates a realistic dataset that mimics what streaming services would have, including metadata like provider, genre, rating, and duration.
3. Implement a basic recommendation algorithm
Now we'll implement a simple collaborative filtering approach that can work with our content data:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import warnings
warnings.filterwarnings('ignore')
class ContentRecommender:
def __init__(self, data):
self.data = data
self.tfidf_matrix = None
self.cosine_sim = None
def preprocess_data(self):
# Combine features for better recommendations
self.data['combined_features'] = (
self.data['genre'] + ' ' +
self.data['provider'] + ' ' +
self.data['year'].astype(str)
)
def build_similarity_matrix(self):
# Create TF-IDF matrix
tfidf = TfidfVectorizer(stop_words='english')
self.tfidf_matrix = tfidf.fit_transform(self.data['combined_features'])
# Compute cosine similarity matrix
self.cosine_sim = cosine_similarity(self.tfidf_matrix, self.tfidf_matrix)
def get_recommendations(self, title, num_recommendations=5):
# Get the index of the content that matches the title
idx = self.data[self.data['title'] == title].index[0]
# Get similarity scores for that content
sim_scores = list(enumerate(self.cosine_sim[idx]))
# Sort by similarity score
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get indices of top similar content (excluding the content itself)
sim_scores = sim_scores[1:num_recommendations+1]
# Get content titles
content_indices = [i[0] for i in sim_scores]
return self.data['title'].iloc[content_indices]
# Load and process data
content_df = pd.read_csv('content_data.csv')
recommender = ContentRecommender(content_df)
recommender.preprocess_data()
recommender.build_similarity_matrix()
This algorithm combines multiple features to create a similarity matrix, which allows us to recommend similar content based on user preferences.
4. Test the recommendation system
Let's test our recommendation system with a sample content item:
# Test recommendations
sample_content = 'Content_15'
recommendations = recommender.get_recommendations(sample_content, 5)
print(f"Recommendations for {sample_content}:")
for i, rec in enumerate(recommendations, 1):
print(f"{i}. {rec}")
This demonstrates how our system would work in practice, showing how content from different providers could be recommended based on user preferences.
5. Implement provider-specific filtering
Since the partnership involves bundling services, we'll add functionality to filter recommendations by provider:
def get_provider_recommendations(self, title, provider=None, num_recommendations=5):
# Get base recommendations
base_recs = self.get_recommendations(title, num_recommendations * 2)
# If provider specified, filter results
if provider:
filtered_recs = self.data[self.data['title'].isin(base_recs) &
(self.data['provider'] == provider)]['title']
return filtered_recs.head(num_recommendations)
return base_recs.head(num_recommendations)
# Add this method to the ContentRecommender class
# Then test with specific provider
provider_recommendations = recommender.get_provider_recommendations('Content_15', 'Peacock', 3)
print(f"Peacock recommendations for Content_15:")
for i, rec in enumerate(provider_recommendations, 1):
print(f"{i}. {rec}")
This enhancement allows our system to specifically recommend content from a particular provider, which is crucial for bundling services like YouTube Premium and Peacock.
6. Create a simple API endpoint for recommendations
Finally, we'll create a basic API endpoint that could be used in a production system:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/recommend', methods=['GET'])
def recommend_content():
title = request.args.get('title')
provider = request.args.get('provider')
num = int(request.args.get('num', 5))
if not title:
return jsonify({'error': 'Title parameter is required'}), 400
try:
if provider:
recommendations = recommender.get_provider_recommendations(title, provider, num)
else:
recommendations = recommender.get_recommendations(title, num)
return jsonify({
'title': title,
'provider': provider,
'recommendations': recommendations.tolist()
})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
This API endpoint allows external systems to query recommendations, simulating how a real streaming service partnership would work.
Summary
In this tutorial, we've built a prototype content recommendation system that demonstrates the technology behind bundling streaming services like YouTube Premium and Peacock. We've implemented:
- A data preprocessing pipeline to handle content metadata
- A collaborative filtering algorithm using TF-IDF and cosine similarity
- Provider-specific recommendation filtering
- A simple API endpoint for querying recommendations
This system could be extended with real streaming APIs, user behavior data, and more sophisticated recommendation algorithms. The approach we've demonstrated is similar to what major streaming companies use to create bundled offerings and enhance user experience across multiple platforms.



