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()