Building a Recommendation System in Spring Boot
Recommendation systems are widely used in platforms like Netflix, Amazon, and Spotify to suggest relevant content to users. In this post, we will learn how to build a simple **content-based recommendation system** using **Spring Boot** and **Hugging Face API**.
๐ก What is a Content-Based Recommendation System?
Content-based filtering recommends items based on their features and the preferences of users. For example, it might recommend movies similar to a user's watched movie based on genre, director, or actors.
- **User preferences**: What the user likes (e.g., genres, artists, topics, etc.)
- **Item features**: Information about items (e.g., movie plots, product descriptions, etc.)
๐ฆ Step 1: Setup Spring Boot Project
Let’s start by adding necessary dependencies in our pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
๐จ Step 2: Building the Recommendation Controller
We will create a Spring Boot controller that handles incoming requests for recommendations. We’ll use text similarity (cosine similarity or embeddings) to recommend similar content to the user.
package com.example.recommendation;
import org.springframework.web.bind.annotation.*;
import java.net.http.*;
import java.net.URI;
import java.util.*;
@RestController
@RequestMapping("/api/recommendations")
public class RecommendationController {
private static final String HF_TOKEN = "your-huggingface-api-token";
private static final String MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"; // Model to generate embeddings
@PostMapping
public List<String> getRecommendations(@RequestBody String userPreferences) throws Exception {
// Use Hugging Face model to generate embeddings for user input and item descriptions
String requestBody = "{ \"inputs\": \"" + userPreferences.replace("\"", "\\\"") + "\" }";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-inference.huggingface.co/models/" + MODEL_ID))
.header("Authorization", "Bearer " + HF_TOKEN)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Get recommendations based on cosine similarity between embeddings (simplified here)
List<String> recommendedItems = generateRecommendations(response.body());
return recommendedItems;
}
private List<String> generateRecommendations(String response) {
// Here we would process the embeddings and match with item features.
// In a real-world scenario, you'd compare embeddings to a database of items.
// For simplicity, we return some static recommendations.
return Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
}
}
๐ Hugging Face Model Selection
In the above code, we are using the sentence-transformers/all-MiniLM-L6-v2 model, which is designed for generating embeddings from text. This model converts text (such as user preferences or item descriptions) into numerical vectors, which can then be compared to recommend similar items.
๐งช Step 3: Writing the Test Case
Next, let's write a simple JUnit test to verify that our recommendation system works as expected.
package com.example.recommendation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class RecommendationControllerTest {
@Test
void testGetRecommendations() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/api/recommendations";
String userPreferences = "I love action movies with superheroes and thrillers";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(userPreferences, headers);
ResponseEntity<List<String>> response = restTemplate.exchange(url, HttpMethod.POST, request, List.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().size() > 0);
}
}
๐ Sample Response
Once you call the recommendation API with the preferences text, the system should return a list of recommended items:
[ "Item 1: Avengers: Endgame", "Item 2: The Dark Knight", "Item 3: Iron Man", "Item 4: Spider-Man: No Way Home" ]
๐ก Tips for Further Improvement
- Instead of static recommendations, store item descriptions in a database and compare the embeddings for better results.
- Use more sophisticated recommendation models such as collaborative filtering in addition to content-based filtering.
- Consider implementing personalization by incorporating user profiles or historical behavior for improved recommendations.
๐ Conclusion
Congratulations! You’ve now built a basic recommendation system that suggests items based on content similarity using Spring Boot and Hugging Face’s APIs. This approach can be extended to build more complex systems by incorporating features such as collaborative filtering, matrix factorization, and deep learning models.
Feel free to explore the Hugging Face API to discover more advanced models for text similarity and recommendation systems!
Comments
Post a Comment