Skip to content

Recommendation Model

How Does It Work?

Our recommendation model works by generating embeddings for the books and then calculating the cosine similarity between the embeddings of the input book and all other books. The books with the highest cosine similarity are recommended.

Additional Filtering

Additional filters can be applied to ensure the model works faster. One such filter is the availability of the book. If the book is not available, it will not be recommended. This filter can be turned off if you want to recommend books irrespective of their availability.

Current Functionality

As of now, the package has the following functionality in terms of recommendations:

kitab.recommendation_model.models

This module contains the functions for recommending books.

recommend_books(description, n, get_available=True, data=None)

Recommends a list of books based on a given description.

Examples:

>>> from kitab.recommendation_model.models import recommend_books
>>> description = "In this thrilling detective tale, a group of childhood friends accidentally stumble upon an ancient artifact hidden in their clubhouse. Little do they know, their discovery thrusts them into a dangerous conspiracy spanning centuries. As they uncover clues, they race against time to prevent a cataclysmic event that could reshape the world. Join them on a heart-pounding journey through shadows and secrets in this gripping mystery."
>>> recommend_books(description, n=5)

Parameters:

Name Type Description Default
description str

The description of the book.

required
n int

The number of books to recommend.

required
get_available bool

Whether to only recommend available books. Defaults to True.

True
data DataFrame

The data containing book information. Defaults to None.

None

Returns:

Type Description
list[dict]

list[dict]: A list of dictionaries representing the most similar books.

Source code in kitab\recommendation_model\models.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def recommend_books(description: str, n: int, get_available: bool = True, data : pd.DataFrame = None) -> list[dict]:
    """
    Recommends a list of books based on a given description.

    Examples:
        >>> from kitab.recommendation_model.models import recommend_books
        >>> description = "In this thrilling detective tale, a group of childhood friends accidentally stumble upon an ancient artifact hidden in their clubhouse. Little do they know, their discovery thrusts them into a dangerous conspiracy spanning centuries. As they uncover clues, they race against time to prevent a cataclysmic event that could reshape the world. Join them on a heart-pounding journey through shadows and secrets in this gripping mystery."
        >>> recommend_books(description, n=5)

    Parameters:
        description (str): The description of the book.
        n (int): The number of books to recommend.
        get_available (bool, optional): Whether to only recommend available books. Defaults to True.
        data (pd.DataFrame, optional): The data containing book information. Defaults to None.

    Returns:
        list[dict]: A list of dictionaries representing the most similar books.
    """
    if data is None:
        if get_available:
            data = get_table_from_db("book", conditions={"available": True})
        else:
            data = get_table_from_db("book")
    elif get_available:
        data = data[data["available"] == True]

    # Check that description is not empty
    if description == "": return []

    # Get the embedding of the description
    desc_embedding = get_embedding(description)

    # Get all the embeddings for the existing book descriptions
    embeddings = np.stack(data["embedding"].values)

    # Compute cosine similarities
    cosine_similarities = cos_mat_vec(embeddings, desc_embedding)

    # Find n most similar books
    most_similar_indices = np.argsort(cosine_similarities)[-n:][::-1]

    # Get the ISBNs of the books
    most_similar_books = data.iloc[most_similar_indices]
    most_similar_books.drop(columns=["embedding"], inplace=True)
    ISBNs = most_similar_books["isbn"].tolist()

    # Get a dict of authors and genres for the books
    authors = get_authors(ISBNs)
    genres = get_genres(ISBNs)

    # Convert the most similar books to a list of dictionaries
    books = most_similar_books.to_dict(orient="records")

    # Add the authors and genres to the books
    for book in books:
        book["authors"] = authors[book["isbn"]]
        book["genres"] = genres[book["isbn"]]

    # Return the most similar books
    return books

recommend_books_by_ISBN(ISBN, n, get_available=True)

Recommends a list of books based on the description of the book with the given ISBN.

Examples:

>>> from kitab.recommendation_model.models import recommend_books_by_ISBN
>>> recommend_books_by_ISBN(ISBN="1442942355", n=5)

Parameters:

Name Type Description Default
ISBN str

The ISBN of the book.

required
n int

The number of books to recommend.

required
get_available bool

Whether to only recommend available books. Defaults to True.

True

Returns:

Type Description
list[dict]

list[dict]: A list of dictionaries representing the most similar books.

Source code in kitab\recommendation_model\models.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def recommend_books_by_ISBN(ISBN: str, n: int, get_available: bool = True) -> list[dict]:
    """
    Recommends a list of books based on the description of the book with the given ISBN.

    Examples:
        >>> from kitab.recommendation_model.models import recommend_books_by_ISBN
        >>> recommend_books_by_ISBN(ISBN="1442942355", n=5)

    Parameters:
        ISBN (str): The ISBN of the book.
        n (int): The number of books to recommend.
        get_available (bool, optional): Whether to only recommend available books. Defaults to True.

    Returns:
        list[dict]: A list of dictionaries representing the most similar books.
    """
    data = get_table_from_db("book")

    # Check that ISBN is not empty
    if ISBN == "": return []

    # Check that ISBN is in the data
    if ISBN not in data["isbn"].values: return []

    # Get the book
    book = data[data["isbn"] == ISBN].iloc[0]

    # Return the recommendations
    return recommend_books(book["description"], n, get_available, data)

recommend_books_by_title(title, n, get_available=True)

Recommends a list of books based on the description of the book with the given title.

Examples:

>>> from kitab.recommendation_model.models import recommend_books_by_title
>>> recommend_books_by_title(title="The Ghostly Rental", n=5)

Parameters:

Name Type Description Default
title str

The title of the book.

required
n int

The number of books to recommend.

required
get_available bool

Whether to only recommend available books. Defaults to True.

True

Returns:

Type Description
list[dict]

list[dict]: A list of dictionaries representing the most similar books.

Source code in kitab\recommendation_model\models.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def recommend_books_by_title(title: str, n: int, get_available: bool = True) -> list[dict]:
    """
    Recommends a list of books based on the description of the book with the given title.

    Examples:
        >>> from kitab.recommendation_model.models import recommend_books_by_title
        >>> recommend_books_by_title(title="The Ghostly Rental", n=5)

    Parameters:
        title (str): The title of the book.
        n (int): The number of books to recommend.
        get_available (bool, optional): Whether to only recommend available books. Defaults to True.

    Returns:
        list[dict]: A list of dictionaries representing the most similar books.
    """    
    data = get_table_from_db("book")

    # Check that title is not empty
    if title == "": return []

    # Check that title is in the data
    if title not in data["title"].values: return []

    # Get the book
    book = data[data["title"] == title].iloc[0]

    # Return the recommendations
    return recommend_books(book["description"], n, get_available, data)