import gradio as gr import pandas as pd from huggingface_hub import InferenceClient client = InferenceClient("Qwen/Qwen2.5-7B-Instruct") #load the book knowledge base books = pd.read_csv("knowledge_base.csv") books = books[["Title", "Author", "Genre", "Age_Range", "Description"]] books = books.dropna(subset=["Title", "Author", "Genre", "Description"]) def search_books(ques, max_givenbooks=5): """Searches the dataframe for rows matching keywords in the user's message. Looks across Title, Genre, and Description columns. """ if not ques: return "" ques = str(ques).lower() keywords = ques.split() matches = pd.Series(False, index=books.index) for word in keywords: matches = matches | ( books["Title"].str.lower().str.contains(word, na=False) | books["Genre"].str.lower().str.contains(word, na=False) | books["Description"].str.lower().str.contains(word, na=False) ) matched_books = books[matches].head(max_givenbooks) if matched_books.empty: return "No exact matches found in the catalog for this description." results_in = "Available books in our catalog matching your request:\n" for idx, row in matched_books.iterrows(): results_in += f" - **Title** : {row['Title']} | **Author** : {row['Author']} | **Genre** : {row['Genre']} | **Age** : {row['Age_Range']}\n" results_in += f" *Description* : {row['Description']}\n\n" return results_in def respond(message, history): catalog_info = search_books(message) instructions = f"""You are the BookBuddy, who is a specialized book recommendation chatbot. Your goal is to recommend books to the user based on what they want. Use the catalog from our database to answer the user. Prioritize the recommending books from this list if they match the user's perferences: {catalog_info}""" messages = [{"role": "system", "content": instructions}] if history: messages.extend(history) messages.append({"role": "user", "content": message}) response = client.chat_completion( messages=messages, max_tokens=220 ) return response.choices[0].message.content.strip() with gr.Blocks( theme=gr.themes.Soft(primary_hue="pink"), css=""" body { background-color: #ffccc7; } """ ) as demo: gr.Image("BookBuddy.png", show_label=False) gr.Markdown( """ # 📚 BookBuddy AI ### Your personal AI book recommender powered, BookBuddy. Ask for genres, moods, or books you love. """ ) chatbot = gr.ChatInterface( fn=respond, examples=[ "I want a sad romance book", "Give me a fantasy book for teens", "Something like The Hunger Games", "A mystery with twists", "I liked Harry Potter, what should I read?", "I'm 15 and love contemporary books, what should I read?", "Recommend a fast-paced dystopian story", "Give me a book that will make me cry" ] ) gr.Markdown( """