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() chatbot = gr.ChatInterface( fn=respond, title="BookBuddy", description="Ask me for book recommendation on genre, age range, or what kind of story you want" ) if __name__ == "__main__": chatbot.launch()