File size: 2,359 Bytes
857fc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
import gradio as gr
import pandas as pd
import ast
import torch
import numpy as np
from huggingface_hub import hf_hub_download
from sentence_transformers import SentenceTransformer, util

# πŸ”Ή Load model
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

# πŸ”Ή Download book embeddings from Hugging Face Hub
repo_id = "AventIQ-AI/all-MiniLM-L6-v2-book-recommendation-system"
filename = "book_embeddings.csv"
csv_path = hf_hub_download(repo_id=repo_id, filename=filename)

# πŸ”Ή Load embeddings
df_embeddings = pd.read_csv(csv_path)
df_embeddings["embedding"] = df_embeddings["embedding"].apply(ast.literal_eval)
book_embeddings = torch.tensor(df_embeddings["embedding"].tolist())

# πŸ”Ή Function to get book recommendations
def get_book_recommendations(query, top_k=5):
    query_embedding = model.encode(query, convert_to_tensor=True)

    similarities = util.pytorch_cos_sim(query_embedding, book_embeddings).squeeze(0)
    top_k_values, top_k_indices = torch.topk(similarities, k=top_k)

    recommended_titles = df_embeddings.iloc[top_k_indices.cpu().numpy()]["title"].tolist()
    recommended_scores = top_k_values.cpu().numpy().tolist()

    return [f"πŸ“š {title} - Score: {score:.4f}" for title, score in zip(recommended_titles, recommended_scores)]

# πŸ”Ή Define Gradio UI
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("## πŸ“– AI-Powered Book Recommendation System")
    gr.Markdown("πŸ” **Find your next favorite book!** Enter a description or a genre, and the AI will suggest books.")

    with gr.Row():
        query_input = gr.Textbox(label="Enter Book Description / Genre", placeholder="E.g. A thrilling mystery novel...")
        recommend_button = gr.Button("Get Recommendations 🎯")

    output = gr.Textbox(label="Recommended Books", lines=5)

    examples = [
        ["A horror novel with ghosts and dark nights"],
        ["A sci-fi adventure with aliens and space travel"],
        ["A romance story set in Paris"],
        ["A detective novel solving crimes in the city"],
        ["An inspiring self-help book for personal growth"]
    ]

    gr.Examples(examples, inputs=[query_input])

    recommend_button.click(fn=get_book_recommendations, inputs=[query_input], outputs=[output])

# πŸ”Ή Launch the Gradio app
demo.launch()