Learn how to build a powerful recommendations engine with Lovable. Follow our step-by-step guide to boost personalization and user engagement.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Prerequisites
Setting Up Your Lovable Project
Adding Dependencies
main.py
) to install required packages (for example, numpy and pandas):
import pip
pip.main(['install', 'numpy']) # Install numpy for numerical operations
pip.main(['install', 'pandas']) # Install pandas to manage data structures
Creating the Recommendation Engine Module
recommendations.py
. This file will encapsulate the recommendation engine logic.recommendations.py
, insert the following code snippet which defines a simple recommendation function:
def get_recommendations(user_profile, items):
recommended = []
# Loop through each item and check if the item's category is in the user's interests
for item in items:
if item.get('category') in user\_profile.get('interests', []):
recommended.append(item)
return recommended
Integrating the Recommendation Engine in Your Main Code
main.py
) where you want to use the recommendation engine.recommendations.py
and add the example testing code. Insert the following snippet in your main file at the desired location:
from recommendations import get\_recommendations
Example user profile with interests
user_profile = {
'id': 1,
'name': 'Alice',
'interests': ['technology', 'books']
}
Example list of items with categories
items = [
{'id': 101, 'name': 'Smartphone', 'category': 'technology'},
{'id': 102, 'name': 'Novel', 'category': 'books'},
{'id': 103, 'name': 'Cooking Set', 'category': 'home'},
]
Obtain recommendations based on user interests
recommended_items = get_recommendations(user_profile, items)
print("Recommended Items:", recommended_items)
Testing Your Recommendation Engine
Deploying Your Recommendations Engine
recommendations.py
and main.py
, then run again.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// Calculate similarity between two users based on their preferences
function calculateSimilarity(userA, userB) {
let similarity = 0;
const keys = Object.keys(userA.preferences);
keys.forEach(key => {
if (userB.preferences[key] !== undefined) {
similarity += 1 / (1 + Math.abs(userA.preferences[key] - userB.preferences[key]));
}
});
return similarity;
}
// Generate recommendations for a given user based on what similar users loved
function getRecommendations(userId, users, items) {
const currentUser = users.find(user => user.id === userId);
if (!currentUser) return [];
// Score items based on similar users' preferences and loves
const itemScores = {};
users.forEach(otherUser => {
if (otherUser.id !== userId) {
const similarity = calculateSimilarity(currentUser, otherUser);
otherUser.lovedItems.forEach(itemId => {
// Only consider items not already loved by current user
if (!currentUser.lovedItems.includes(itemId)) {
itemScores[itemId] = (itemScores[itemId] || 0) + similarity;
}
});
}
});
// Sort items based on their score and return top 5 recommendations
return Object.entries(itemScores)
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([itemId]) => items.find(item => item.id === parseInt(itemId)));
}
// Example in-memory data structure for users and items
const users = [
{ id: 1, preferences: { romance: 8, action: 2 }, lovedItems: [101, 102] },
{ id: 2, preferences: { romance: 7, action: 3 }, lovedItems: [102, 103] },
{ id: 3, preferences: { romance: 5, action: 9 }, lovedItems: [104, 105] }
];
const items = [
{ id: 101, name: 'Love in Paris' },
{ id: 102, name: 'Romantic Getaway' },
{ id: 103, name: 'Charming Nights' },
{ id: 104, name: 'Action Blast' },
{ id: 105, name: 'Explosive Tales' },
{ id: 106, name: 'Unexpected Journey' }
];
// API endpoint to get recommended items for a user
app.get('/api/recommendations/:userId', (req, res) => {
const userId = parseInt(req.params.userId, 10);
const recommendations = getRecommendations(userId, users, items);
res.json({ userId, recommendations });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
const users = [
{ id: 1, preferences: { adventure: 9, drama: 4 }, likedItems: [201, 202] },
{ id: 2, preferences: { adventure: 7, drama: 6 }, likedItems: [202, 203] },
];
const items = [
{ id: 201, name: 'Jungle Quest' },
{ id: 202, name: 'City Lights' },
{ id: 203, name: 'Sailing Dreams' },
{ id: 204, name: 'Mystery Tales' },
];
// Basic recommendation logic: return items not already liked by the user.
function basicRecommendations(userId) {
const user = users.find(u => u.id === userId);
if (!user) return [];
return items.filter(item => !user.likedItems.includes(item.id));
}
// Function to fetch external sentiment score for an item to adjust its ranking
async function fetchExternalSentiment(itemId) {
try {
const response = await axios.get(`https://api.external-service.com/sentiment/${itemId}`);
return response.data.score; // Assume API returns { score: number }
} catch (error) {
return 0;
}
}
// API endpoint: enhanced recommendations merging internal logic with external sentiment scoring
app.get('/api/enhanced-recommendations/:userId', async (req, res) => {
const userId = parseInt(req.params.userId, 10);
const recs = basicRecommendations(userId);
const enhancedRecommendations = await Promise.all(
recs.map(async (item) => {
const sentimentScore = await fetchExternalSentiment(item.id);
return { ...item, sentimentScore };
})
);
// Sort by external sentiment score descending
enhancedRecommendations.sort((a, b) => b.sentimentScore - a.sentimentScore);
res.json({ userId, recommendations: enhancedRecommendations });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
const express = require('express');
const app = express();
app.use(express.json());
// In-memory dataset simulating users and items
const users = [
{ id: 1, tastes: { comedy: 5, drama: 3, horror: 1 }, lovedItems: [1, 2] },
{ id: 2, tastes: { comedy: 4, drama: 4, horror: 2 }, lovedItems: [3, 2] },
{ id: 3, tastes: { comedy: 1, drama: 5, horror: 4 }, lovedItems: [4, 5] }
];
const items = [
{ id: 1, title: 'Laugh Out Loud', genres: ['comedy'] },
{ id: 2, title: 'Deep Emotions', genres: ['drama'] },
{ id: 3, title: 'Stand-Up Special', genres: ['comedy'] },
{ id: 4, title: 'Night Terrors', genres: ['horror'] },
{ id: 5, title: 'Epic Tragedy', genres: ['drama'] },
{ id: 6, title: 'Odd Blend', genres: ['comedy', 'horror'] }
];
// Compute cosine similarity between two users' taste profiles
function computeCosineSimilarity(tasteA, tasteB) {
const keys = Object.keys(tasteA);
let dot = 0, normA = 0, normB = 0;
keys.forEach(key => {
const a = tasteA[key] || 0;
const b = tasteB[key] || 0;
dot += a \* b;
normA += a \* a;
normB += b \* b;
});
return normA && normB ? dot / (Math.sqrt(normA) \* Math.sqrt(normB)) : 0;
}
// POST endpoint for personalized recommendations using Lovable techniques
app.post('/api/lovable-recommendation', (req, res) => {
const { userId } = req.body;
const currentUser = users.find(u => u.id === userId);
if (!currentUser) return res.status(404).json({ error: 'User not found' });
// Find similarity scores with other users
const similarityScores = users
.filter(u => u.id !== userId)
.map(u => ({ id: u.id, score: computeCosineSimilarity(currentUser.tastes, u.tastes) }))
.sort((a, b) => b.score - a.score);
// Choose the most similar user as a basis for recommendations
const similarUser = users.find(u => u.id === similarityScores[0].id);
// Recommend items: those loved by the similar user that the current user hasn't loved,
// and sharing at least one genre with any item the similar user loved.
const recommendations = items.filter(item => {
if (currentUser.lovedItems.includes(item.id)) return false;
const matches = similarUser.lovedItems.some(lovedId => {
const lovedItem = items.find(i => i.id === lovedId);
return lovedItem && lovedItem.genres.some(genre => item.genres.includes(genre));
});
return matches;
}).map(item => {
// Enhance recommendation with a score based on user's tastes matching the movie's genres
const enhancedScore = item.genres.reduce((sum, genre) => sum + (currentUser.tastes[genre] || 0), 0);
return { ...item, enhancedScore };
});
// Return recommendations sorted by the enhanced score in descending order
recommendations.sort((a, b) => b.enhancedScore - a.enhancedScore);
res.json({ userId, recommendations });
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Recommendation engine running on port ${PORT}`);
});
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Understanding Recommendation Engines and AI Code Generators
Setting Up Your Development Environment
Collecting and Preparing Data
Creating Your First Recommendation Model
import pandas as pd
from sklearn.metrics.pairwise import cosine\_similarity
# Sample data: Rows represent users and columns represent items (1 means interest, 0 means no interest)
data = {
'item\_A': [1, 0, 1],
'item\_B': [0, 1, 1],
'item\_C': [1, 1, 0]
}
user_item_matrix = pd.DataFrame(data, index=['User1', 'User2', 'User3'])
# Calculate cosine similarity between users
similarity_matrix = cosine_similarity(user_item_matrix)
similarity_df = pd.DataFrame(similarity_matrix, index=user_item_matrix.index, columns=user_item_matrix.index)
print(similarity\_df)
Integrating AI Code Generators
Evaluating and Improving Your Model
Integrating the Recommendation Engine into Your Application
Best Practices for Building a Scalable Engine
Maintenance and Monitoring
Conclusion
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.