feat: Leverage fuzzy logic for more accurate metadata resolution and support Amazon cookies
- Improved metadata matching using fuzzy string comparison with threshold-based author validation - Added support for optional Amazon session cookie to enhance data retrieval and bypass rate limiting
This commit is contained in:
committed by
Aditya Chandel
parent
b6e9a73cf9
commit
204a155582
@@ -69,6 +69,7 @@ dependencies {
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6'
|
||||
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||
implementation 'com.github.junrar:junrar:7.5.5'
|
||||
implementation 'org.apache.commons:commons-text:1.13.1'
|
||||
}
|
||||
|
||||
hibernate {
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ public class MetadataProviderSettings {
|
||||
@Data
|
||||
public static class Amazon {
|
||||
private boolean enabled;
|
||||
private String cookie;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -128,6 +128,7 @@ public class AppSettingService {
|
||||
|
||||
MetadataProviderSettings.Amazon defaultAmazon = new MetadataProviderSettings.Amazon();
|
||||
defaultAmazon.setEnabled(true);
|
||||
defaultAmazon.setCookie(null);
|
||||
MetadataProviderSettings.Google defaultGoogle = new MetadataProviderSettings.Google();
|
||||
defaultGoogle.setEnabled(true);
|
||||
MetadataProviderSettings.Goodreads defaultGoodreads = new MetadataProviderSettings.Goodreads();
|
||||
|
||||
+48
-34
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.service.AppSettingService;
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -26,8 +27,8 @@ import java.util.stream.Collectors;
|
||||
public class AmazonBookParser implements BookParser {
|
||||
|
||||
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
||||
private static final String BASE_SEARCH_URL = "https://www.amazon.com/s/?search-alias=stripbooks&unfiltered=1&sort=relevanceexprank";
|
||||
private static final String BASE_BOOK_URL = "https://www.amazon.com/dp/";
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
@@ -75,6 +76,18 @@ public class AmazonBookParser implements BookParser {
|
||||
log.error("No items found in the search results.");
|
||||
} else {
|
||||
for (Element item : items) {
|
||||
if (item.text().contains("Collects books from")) {
|
||||
log.debug("Skipping box set item (collects books): {}", extractAmazonBookId(item));
|
||||
continue;
|
||||
}
|
||||
Element titleDiv = item.selectFirst("div[data-cy=title-recipe]");
|
||||
if (titleDiv != null) {
|
||||
String titleText = titleDiv.text();
|
||||
if (titleText.contains("Books Set")) {
|
||||
log.debug("Skipping box set item (Books Set in title): {}", extractAmazonBookId(item));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
bookIds.add(extractAmazonBookId(item));
|
||||
}
|
||||
}
|
||||
@@ -138,40 +151,35 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
|
||||
private String buildQueryUrl(FetchMetadataRequest fetchMetadataRequest, Book book) {
|
||||
StringBuilder queryBuilder = new StringBuilder(BASE_SEARCH_URL);
|
||||
StringBuilder searchTerm = new StringBuilder();
|
||||
|
||||
/*// Always add ISBN if present
|
||||
if (fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isEmpty()) {
|
||||
queryBuilder.append("&field-isbn=").append(fetchMetadataRequest.getIsbn());
|
||||
}*/
|
||||
|
||||
// Add title if present, otherwise check filename if title is absent
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
if (title != null && !title.isEmpty()) {
|
||||
title = BookUtils.cleanAndTruncateSearchTerm(title);
|
||||
queryBuilder.append("&field-title=").append(title.replace(" ", "%20"));
|
||||
searchTerm.append(title.trim());
|
||||
} else {
|
||||
String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getFileName()));
|
||||
if (filename != null && !filename.isEmpty()) {
|
||||
queryBuilder.append("&field-title=").append(filename.replace(" ", "%20"));
|
||||
if (!filename.isEmpty()) {
|
||||
searchTerm.append(filename.trim());
|
||||
}
|
||||
}
|
||||
|
||||
// Add author only if title or filename is present
|
||||
if ((title != null && !title.isEmpty()) || (fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isEmpty())) {
|
||||
String author = fetchMetadataRequest.getAuthor();
|
||||
if (author != null && !author.isEmpty()) {
|
||||
queryBuilder.append("&field-author=").append(author.replace(" ", "%20"));
|
||||
String author = fetchMetadataRequest.getAuthor();
|
||||
if (author != null && !author.isEmpty()) {
|
||||
if (!searchTerm.isEmpty()) {
|
||||
searchTerm.append(" ");
|
||||
}
|
||||
searchTerm.append(author.trim());
|
||||
}
|
||||
|
||||
// If ISBN, Title, or Filename is missing, return null
|
||||
if (fetchMetadataRequest.getIsbn() == null && (title == null || title.isEmpty()) && (book.getFileName() == null || book.getFileName().isEmpty())) {
|
||||
if (searchTerm.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
log.info("Query URL: {}", queryBuilder.toString());
|
||||
return queryBuilder.toString();
|
||||
String encodedSearchTerm = searchTerm.toString().replace(" ", "+");
|
||||
String url = "https://www.amazon.com/s?k=" + encodedSearchTerm;
|
||||
|
||||
log.info("Query URL: {}", url);
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getTitle(Document doc) {
|
||||
@@ -370,11 +378,11 @@ public class AmazonBookParser implements BookParser {
|
||||
|
||||
private Double getRating(Document doc) {
|
||||
try {
|
||||
Element reviewDiv = doc.select("div#averageCustomerReviews_feature_div").first();
|
||||
Element reviewDiv = doc.selectFirst("div#averageCustomerReviews_feature_div");
|
||||
if (reviewDiv != null) {
|
||||
Elements ratingElements = reviewDiv.select("span#acrPopover span.a-size-base.a-color-base");
|
||||
if (!ratingElements.isEmpty()) {
|
||||
String text = Objects.requireNonNull(ratingElements.first()).text();
|
||||
Element ratingSpan = reviewDiv.selectFirst("span#acrPopover span.a-size-small.a-color-base");
|
||||
if (ratingSpan != null) {
|
||||
String text = ratingSpan.text().trim();
|
||||
if (!text.isEmpty()) {
|
||||
return Double.parseDouble(text);
|
||||
}
|
||||
@@ -392,10 +400,10 @@ public class AmazonBookParser implements BookParser {
|
||||
if (reviewDiv != null) {
|
||||
Element reviewCountElement = reviewDiv.getElementById("acrCustomerReviewText");
|
||||
if (reviewCountElement != null) {
|
||||
String reviewCount = Objects.requireNonNull(reviewCountElement).text().split(" ")[0];
|
||||
if (!reviewCount.isEmpty()) {
|
||||
reviewCount = reviewCount.replace(",", "");
|
||||
return Integer.parseInt(reviewCount);
|
||||
String reviewCountRaw = reviewCountElement.text().split(" ")[0];
|
||||
String reviewCountClean = reviewCountRaw.replaceAll("[^\\d]", "");
|
||||
if (!reviewCountClean.isEmpty()) {
|
||||
return Integer.parseInt(reviewCountClean);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,7 +444,8 @@ public class AmazonBookParser implements BookParser {
|
||||
|
||||
private Document fetchDocument(String url) {
|
||||
try {
|
||||
Connection.Response response = Jsoup.connect(url)
|
||||
String amazonCookie = appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getCookie();
|
||||
Connection connection = Jsoup.connect(url)
|
||||
.header("accept", "text/html, application/json")
|
||||
.header("accept-language", "en-US,en;q=0.9")
|
||||
.header("content-type", "application/json")
|
||||
@@ -449,19 +458,24 @@ public class AmazonBookParser implements BookParser {
|
||||
.header("rtt", "50")
|
||||
.header("sec-ch-device-memory", "8")
|
||||
.header("sec-ch-dpr", "2")
|
||||
.header("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"")
|
||||
.header("sec-ch-ua", "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not_A Brand\";v=\"24\"")
|
||||
.header("sec-ch-ua-mobile", "?0")
|
||||
.header("sec-ch-ua-platform", "\"macOS\"")
|
||||
.header("sec-ch-viewport-width", "1170")
|
||||
.header("sec-fetch-dest", "empty")
|
||||
.header("sec-fetch-mode", "cors")
|
||||
.header("sec-fetch-site", "same-origin")
|
||||
.header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
||||
.header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36")
|
||||
.header("viewport-width", "1170")
|
||||
.header("x-amz-amabot-click-attributes", "disable")
|
||||
.header("x-requested-with", "XMLHttpRequest")
|
||||
.method(Connection.Method.GET)
|
||||
.execute();
|
||||
.method(Connection.Method.GET);
|
||||
|
||||
if (amazonCookie != null && !amazonCookie.isBlank()) {
|
||||
connection.header("cookie", amazonCookie);
|
||||
}
|
||||
|
||||
Connection.Response response = connection.execute();
|
||||
return response.parse();
|
||||
} catch (IOException e) {
|
||||
log.error("Error parsing url: {}", url, e);
|
||||
|
||||
+14
-1
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser;
|
||||
|
||||
import org.apache.commons.text.similarity.FuzzyScore;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Award;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
@@ -335,11 +337,22 @@ public class GoodReadsParser implements BookParser {
|
||||
String searchUrl = generateSearchUrl(searchTerm);
|
||||
Elements previewBooks = fetchDoc(searchUrl).select("table.tableList").first().select("tr[itemtype=http://schema.org/Book]");
|
||||
List<BookMetadata> metadataPreviews = new ArrayList<>();
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String queryAuthor = request.getAuthor();
|
||||
for (Element previewBook : previewBooks) {
|
||||
List<String> authors = extractAuthorsPreview(previewBook);
|
||||
if (queryAuthor != null && !queryAuthor.isEmpty()) {
|
||||
boolean matches = authors.stream().anyMatch(author ->
|
||||
(double) fuzzyScore.fuzzyScore(author, queryAuthor) / Math.max(author.length(), queryAuthor.length()) >= 0.8
|
||||
);
|
||||
if (!matches) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
BookMetadata previewMetadata = BookMetadata.builder()
|
||||
.providerBookId(String.valueOf(extractGoodReadsIdPreview(previewBook)))
|
||||
.title(extractTitlePreview(previewBook))
|
||||
.authors(extractAuthorsPreview(previewBook))
|
||||
.authors(authors)
|
||||
.build();
|
||||
metadataPreviews.add(previewMetadata);
|
||||
}
|
||||
|
||||
+46
-33
@@ -9,6 +9,8 @@ import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBoo
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.apache.commons.text.similarity.FuzzyScore;
|
||||
import java.util.Locale;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
@@ -28,53 +30,64 @@ public class HardcoverParser implements BookParser {
|
||||
|
||||
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getTitle());
|
||||
|
||||
return hits.stream().map(hit -> {
|
||||
GraphQLResponse.Document doc = hit.getDocument();
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
metadata.setProviderBookId(doc.getSlug());
|
||||
metadata.setTitle(doc.getTitle());
|
||||
metadata.setDescription(doc.getDescription());
|
||||
metadata.setAuthors(doc.getAuthorNames());
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String searchAuthor = fetchMetadataRequest.getAuthor() != null ? fetchMetadataRequest.getAuthor() : "";
|
||||
|
||||
if (doc.getFeaturedSeries() != null) {
|
||||
if (doc.getFeaturedSeries().getSeries() != null) {
|
||||
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
|
||||
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
|
||||
}
|
||||
if (doc.getFeaturedSeries().getPosition() != null) {
|
||||
try {
|
||||
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return hits.stream()
|
||||
.filter(hit -> {
|
||||
String author = String.join(" ", hit.getDocument().getAuthorNames());
|
||||
int score = fuzzyScore.fuzzyScore(author, searchAuthor);
|
||||
int maxScore = Math.max(fuzzyScore.fuzzyScore(searchAuthor, searchAuthor), fuzzyScore.fuzzyScore(author, author));
|
||||
double similarity = maxScore > 0 ? (double) score / maxScore : 0;
|
||||
return similarity >= 0.8;
|
||||
})
|
||||
.map(hit -> {
|
||||
GraphQLResponse.Document doc = hit.getDocument();
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
metadata.setProviderBookId(doc.getSlug());
|
||||
metadata.setTitle(doc.getTitle());
|
||||
metadata.setDescription(doc.getDescription());
|
||||
metadata.setAuthors(doc.getAuthorNames());
|
||||
|
||||
if (doc.getFeaturedSeries() != null) {
|
||||
if (doc.getFeaturedSeries().getSeries() != null) {
|
||||
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
|
||||
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
|
||||
}
|
||||
if (doc.getFeaturedSeries().getPosition() != null) {
|
||||
try {
|
||||
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
|
||||
} catch (NumberFormatException ignored) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.getRating() != null) {
|
||||
BigDecimal roundedRating = BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP);
|
||||
metadata.setHardcoverRating(roundedRating.doubleValue());
|
||||
}
|
||||
metadata.setHardcoverReviewCount(doc.getRatingsCount());
|
||||
metadata.setPageCount(doc.getPages());
|
||||
metadata.setPublishedDate(doc.getReleaseDate() != null ? LocalDate.parse(doc.getReleaseDate()) : null);
|
||||
metadata.setCategories(doc.getGenres());
|
||||
if (doc.getRating() != null) {
|
||||
BigDecimal roundedRating = BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP);
|
||||
metadata.setHardcoverRating(roundedRating.doubleValue());
|
||||
}
|
||||
metadata.setHardcoverReviewCount(doc.getRatingsCount());
|
||||
metadata.setPageCount(doc.getPages());
|
||||
metadata.setPublishedDate(doc.getReleaseDate() != null ? LocalDate.parse(doc.getReleaseDate()) : null);
|
||||
metadata.setCategories(doc.getGenres());
|
||||
|
||||
if (doc.getIsbns() != null) {
|
||||
metadata.setIsbn10(doc.getIsbns().stream()
|
||||
if (doc.getIsbns() != null) {
|
||||
metadata.setIsbn10(doc.getIsbns().stream()
|
||||
.filter(isbn -> isbn.length() == 10)
|
||||
.findFirst()
|
||||
.orElse(null));
|
||||
|
||||
metadata.setIsbn13(doc.getIsbns().stream()
|
||||
metadata.setIsbn13(doc.getIsbns().stream()
|
||||
.filter(isbn -> isbn.length() == 13)
|
||||
.findFirst()
|
||||
.orElse(null));
|
||||
}
|
||||
}
|
||||
|
||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
return metadata;
|
||||
}).toList();
|
||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
return metadata;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface MetadataProviderSettings {
|
||||
|
||||
export interface Amazon {
|
||||
enabled: boolean;
|
||||
cookie: string;
|
||||
}
|
||||
|
||||
export interface Google {
|
||||
|
||||
+21
-5
@@ -1,7 +1,7 @@
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
Enabled Metadata Providers:
|
||||
<i
|
||||
class="pi pi-info-circle"
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Enable or configure third-party metadata sources for enhanced book information."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
@@ -10,9 +10,25 @@
|
||||
|
||||
<div class="flex flex-col gap-4 p-4">
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<p-checkbox [(ngModel)]="amazonEnabled" [binary]="true"></p-checkbox>
|
||||
<label>Amazon</label>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-4">
|
||||
<p-checkbox [(ngModel)]="amazonEnabled" [binary]="true"></p-checkbox>
|
||||
<label>Amazon</label>
|
||||
</div>
|
||||
<div class="flex items-center gap-4 pl-6">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
placeholder="Amazon Cookie (Optional)"
|
||||
class="w-full max-w-3xl"
|
||||
[(ngModel)]="amazonCookie" />
|
||||
<i
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Providing your Amazon session cookie allows the app to access richer book metadata and bypass rate limits. Optional but recommended for best results."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
@@ -39,7 +55,7 @@
|
||||
type="text"
|
||||
pInputText
|
||||
placeholder="API Token"
|
||||
class="w-full max-w-sm"
|
||||
class="w-full max-w-3xl"
|
||||
[(ngModel)]="hardcoverToken"
|
||||
(ngModelChange)="onTokenChange($event)" />
|
||||
</div>
|
||||
|
||||
+6
-1
@@ -26,6 +26,7 @@ import {AppSettingKey} from '../../../core/model/app-settings.model';
|
||||
})
|
||||
export class MetadataProviderSettingsComponent implements OnInit {
|
||||
hardcoverToken: string = '';
|
||||
amazonCookie: string = '';
|
||||
hardcoverEnabled: boolean = false;
|
||||
amazonEnabled: boolean = false;
|
||||
goodreadsEnabled: boolean = false;
|
||||
@@ -45,6 +46,7 @@ export class MetadataProviderSettingsComponent implements OnInit {
|
||||
.subscribe(settings => {
|
||||
const metadataProviderSettings = settings!.metadataProviderSettings;
|
||||
this.amazonEnabled = metadataProviderSettings?.amazon?.enabled ?? false;
|
||||
this.amazonCookie = metadataProviderSettings?.amazon?.cookie ?? "";
|
||||
this.goodreadsEnabled = metadataProviderSettings?.goodReads?.enabled ?? false;
|
||||
this.googleEnabled = metadataProviderSettings?.google?.enabled ?? false;
|
||||
this.hardcoverToken = metadataProviderSettings?.hardcover?.apiKey ?? '';
|
||||
@@ -64,7 +66,10 @@ export class MetadataProviderSettingsComponent implements OnInit {
|
||||
{
|
||||
key: AppSettingKey.METADATA_PROVIDER_SETTINGS,
|
||||
newValue: {
|
||||
amazon: {enabled: this.amazonEnabled},
|
||||
amazon: {
|
||||
enabled: this.amazonEnabled,
|
||||
cookie: this.amazonCookie
|
||||
},
|
||||
goodReads: {enabled: this.goodreadsEnabled},
|
||||
google: {enabled: this.googleEnabled},
|
||||
hardcover: {
|
||||
|
||||
Reference in New Issue
Block a user