Implement similar books recommendation using metadata similarity (#145)
Co-authored-by: adityachandelgit <>
This commit is contained in:
co-authored by
adityachandelgit
parent
959d13b876
commit
6c12d3aae0
+8
-1
@@ -1,16 +1,17 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendation;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
|
||||
import com.adityachandel.booklore.service.BookRecommendationService;
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -22,6 +23,7 @@ import java.util.List;
|
||||
public class BookController {
|
||||
|
||||
private final BooksService booksService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
@@ -69,4 +71,9 @@ public class BookController {
|
||||
booksService.updateReadProgress(request);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/recommendations")
|
||||
public ResponseEntity<List<BookRecommendation>> getRecommendations(@PathVariable Long id, @RequestParam(defaultValue = "10") int limit) {
|
||||
return ResponseEntity.ok(bookRecommendationService.findSimilarBooks(id, limit));
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class BookRecommendation {
|
||||
private Book book;
|
||||
private double similarityScore;
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendation;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.AbstractMap.SimpleEntry;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BookRecommendationService {
|
||||
|
||||
private final BookSimilarityService similarityService;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapper bookMapper;
|
||||
|
||||
private static final int MAX_BOOKS_PER_AUTHOR = 3;
|
||||
|
||||
public List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
|
||||
BookEntity target = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookEntity> candidates = bookRepository.findAll();
|
||||
|
||||
List<SimpleEntry<BookEntity, Double>> scored = candidates.stream()
|
||||
.filter(candidate -> !candidate.getId().equals(bookId))
|
||||
.map(candidate -> new SimpleEntry<>(candidate, similarityService.calculateSimilarity(target, candidate)))
|
||||
.filter(entry -> entry.getValue() > 0.0)
|
||||
.sorted(Map.Entry.<BookEntity, Double>comparingByValue().reversed())
|
||||
.toList();
|
||||
|
||||
Map<String, Integer> authorCounts = new HashMap<>();
|
||||
List<BookRecommendation> recommendations = new ArrayList<>();
|
||||
|
||||
for (SimpleEntry<BookEntity, Double> entry : scored) {
|
||||
if (recommendations.size() >= limit) break;
|
||||
BookEntity book = entry.getKey();
|
||||
Set<String> authorNames = getAuthorNames(book);
|
||||
boolean allowed = authorNames.stream()
|
||||
.allMatch(name -> authorCounts.getOrDefault(name, 0) < MAX_BOOKS_PER_AUTHOR);
|
||||
if (allowed) {
|
||||
Book dto = bookMapper.toBookWithDescription(book, false);
|
||||
recommendations.add(new BookRecommendation(dto, entry.getValue()));
|
||||
authorNames.forEach(name -> authorCounts.merge(name, 1, Integer::sum));
|
||||
}
|
||||
}
|
||||
|
||||
return recommendations;
|
||||
}
|
||||
|
||||
private Set<String> getAuthorNames(BookEntity book) {
|
||||
if (book.getMetadata() == null || book.getMetadata().getAuthors() == null) return Collections.emptySet();
|
||||
return book.getMetadata().getAuthors().stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::toLowerCase)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class BookSimilarityService {
|
||||
|
||||
@Getter
|
||||
public enum SimilarityWeight {
|
||||
TITLE(1.5),
|
||||
SERIES(2.0),
|
||||
AUTHORS(3.0),
|
||||
CATEGORIES(3.5),
|
||||
RATING(0.6);
|
||||
|
||||
private final double weight;
|
||||
|
||||
SimilarityWeight(double weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
}
|
||||
|
||||
public double calculateSimilarity(BookEntity a, BookEntity b) {
|
||||
if (a.getMetadata() == null || b.getMetadata() == null) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
BookMetadataEntity metaA = a.getMetadata();
|
||||
BookMetadataEntity metaB = b.getMetadata();
|
||||
|
||||
double score = 0;
|
||||
|
||||
score += SimilarityWeight.AUTHORS.getWeight() *
|
||||
jaccardSimilarity(extractNames(metaA.getAuthors()), extractNames(metaB.getAuthors()));
|
||||
|
||||
score += SimilarityWeight.CATEGORIES.getWeight() *
|
||||
jaccardSimilarity(extractNames(metaA.getCategories()), extractNames(metaB.getCategories()));
|
||||
|
||||
score += SimilarityWeight.TITLE.getWeight() *
|
||||
cosineSimilarity(tokenize(metaA.getTitle()), tokenize(metaB.getTitle()));
|
||||
|
||||
if (isEqualIgnoreCase(metaA.getSeriesName(), metaB.getSeriesName())) {
|
||||
score += SimilarityWeight.SERIES.getWeight();
|
||||
}
|
||||
|
||||
score += SimilarityWeight.RATING.getWeight() *
|
||||
ratingSimilarity(metaA.getRating(), metaB.getRating());
|
||||
|
||||
return round(score, 5);
|
||||
}
|
||||
|
||||
private List<String> extractNames(List<?> entities) {
|
||||
if (entities == null) return Collections.emptyList();
|
||||
List<String> names = new ArrayList<>();
|
||||
for (Object obj : entities) {
|
||||
if (obj instanceof AuthorEntity author && author.getName() != null) {
|
||||
names.add(author.getName().toLowerCase());
|
||||
} else if (obj instanceof CategoryEntity category && category.getName() != null) {
|
||||
names.add(category.getName().toLowerCase());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private boolean isEqualIgnoreCase(String s1, String s2) {
|
||||
return s1 != null && s2 != null && s1.equalsIgnoreCase(s2);
|
||||
}
|
||||
|
||||
private double jaccardSimilarity(List<String> a, List<String> b) {
|
||||
if (a.isEmpty() || b.isEmpty()) return 0.0;
|
||||
Set<String> setA = new HashSet<>(a);
|
||||
Set<String> setB = new HashSet<>(b);
|
||||
|
||||
Set<String> intersection = new HashSet<>(setA);
|
||||
intersection.retainAll(setB);
|
||||
|
||||
Set<String> union = new HashSet<>(setA);
|
||||
union.addAll(setB);
|
||||
|
||||
return union.isEmpty() ? 0.0 : (double) intersection.size() / union.size();
|
||||
}
|
||||
|
||||
private Map<String, Integer> tokenize(String text) {
|
||||
Map<String, Integer> vector = new HashMap<>();
|
||||
if (text == null || text.isBlank()) return vector;
|
||||
|
||||
String[] tokens = text.toLowerCase().replaceAll("[^a-z0-9 ]", "").split("\\s+");
|
||||
for (String token : tokens) {
|
||||
vector.put(token, vector.getOrDefault(token, 0) + 1);
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
|
||||
private double cosineSimilarity(Map<String, Integer> vecA, Map<String, Integer> vecB) {
|
||||
if (vecA.isEmpty() || vecB.isEmpty()) return 0.0;
|
||||
|
||||
Set<String> keys = new HashSet<>();
|
||||
keys.addAll(vecA.keySet());
|
||||
keys.addAll(vecB.keySet());
|
||||
|
||||
double dotProduct = 0, normA = 0, normB = 0;
|
||||
|
||||
for (String key : keys) {
|
||||
int a = vecA.getOrDefault(key, 0);
|
||||
int b = vecB.getOrDefault(key, 0);
|
||||
dotProduct += a * b;
|
||||
normA += a * a;
|
||||
normB += b * b;
|
||||
}
|
||||
|
||||
return (normA == 0 || normB == 0) ? 0.0 : dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
||||
}
|
||||
|
||||
private double ratingSimilarity(Double a, Double b) {
|
||||
if (a == null || b == null) return 0.0;
|
||||
double diff = Math.abs(a - b);
|
||||
return 1.0 - Math.min(diff / 5.0, 1.0);
|
||||
}
|
||||
|
||||
private double round(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
long factor = (long) Math.pow(10, places);
|
||||
return Math.round(value * factor) / (double) factor;
|
||||
}
|
||||
}
|
||||
@@ -97,3 +97,8 @@ export interface BookSetting {
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface BookRecommendation {
|
||||
book: Book;
|
||||
similarityScore: number;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, map, tap} from 'rxjs/operators';
|
||||
import {Book, BookMetadata, BookSetting} from '../model/book.model';
|
||||
import {Book, BookMetadata, BookRecommendation, BookSetting} from '../model/book.model';
|
||||
import {BookState} from '../model/state/book-state.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
|
||||
@@ -274,6 +274,12 @@ export class BookService {
|
||||
return this.url + '/' + bookId + "/metadata/cover"
|
||||
}
|
||||
|
||||
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
|
||||
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
||||
params: { limit: limit.toString() }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/*------------------ All the websocket handlers go below ------------------*/
|
||||
|
||||
|
||||
Reference in New Issue
Block a user