{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/ladka6/Projects/semantic-search/venv/lib/python3.9/site-packages/urllib3/__init__.py:34: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n", " warnings.warn(\n" ] } ], "source": [ "import re\n", "import nltk\n", "import numpy as np\n", "import pandas as pd\n", "from langdetect import detect\n", "from sentence_transformers import SentenceTransformer, InputExample, losses\n", "from sentence_transformers.util import semantic_search \n", "from torch.utils.data import DataLoader\n", "from nltk.corpus import stopwords\n", "from nltk.tokenize import word_tokenize\n", "from nltk.stem import PorterStemmer\n", "from sklearn.preprocessing import MultiLabelBinarizer\n", "import faiss\n", "from FlagEmbedding import FlagReranker\n", "from sklearn.model_selection import train_test_split\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "FILE_PATH = '../data/book_data.csv'\n", "\n", "df = pd.read_csv(FILE_PATH)\n", "\n", "df = df.dropna(subset=['Title', 'Description', 'Genres'])\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def preprocess_text(text):\n", " text = text.lower()\n", " text = re.sub(r'[^a-zA-Z\\s]', '', text)\n", " tokens = word_tokenize(text)\n", " stop_words = set(stopwords.words('english'))\n", " tokens = [token for token in tokens if token not in stop_words]\n", " text = ' '.join(tokens)\n", " return text\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# def title_description_genres_to_string(row):\n", "# genres = ' '.join([genre.strip() for genre in row['Genres'].split(',')])\n", "\n", "# title = row['Title']\n", "\n", "# descriptions = str(row['Description'])\n", "\n", "# tokens = word_tokenize(descriptions)\n", "\n", "# tokens = [word.lower() for word in tokens if word.isalpha()]\n", "\n", "# stop_words = set(stopwords.words('english'))\n", "# tokens = [word for word in tokens if word not in stop_words]\n", "\n", "# porter = PorterStemmer()\n", "# tokens = [porter.stem(word) for word in tokens]\n", "\n", "# preprocessed_text = ' '.join(tokens)\n", "\n", "# return \"%s %s %s\" %(title, genres, preprocessed_text)\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleAuthorRatingDescriptionGenresReviewsCombined
01BeowulfSeamus Heaney3.48Composed toward the end of the first millenniu...Classics, Poetry, Fiction, Fantasy, Mythology,...*bum bum* IN A WORLD . . . *bum bum* . . . FUL...Beowulf Classics Poetry Fiction Fantasy Mythol...
12The Evening and the MorningKen Follett4.38The thrilling and addictive prequel to The Pil...Historical Fiction, Fiction, Historical, Audio...It's 997 CE, the end of the Dark Ages in Engla...The Evening and the Morning Historical Fiction...
23The Abbot's TaleConn Iggulden4.05In the year 937, the new king of England, a gr...Historical Fiction, Fiction, Historical, Medie...There is never one truth, one love, or one ene...The Abbot's Tale Historical Fiction Fiction Hi...
34Ibn Fadlān and the Land of Darkness: Arab Trav...Ahmad ibn Fadlān3.87In 922 AD, an Arab envoy from Baghdad named Ib...History, Travel, Nonfiction, Classics, Islam, ...رسالة ابن فضلان .. أو ما يسمى برحلة ابن فضلان ...Ibn Fadlān and the Land of Darkness: Arab Trav...
45The Empty ThroneBernard Cornwell4.38This eighth entry in New York Times bestsellin...Historical Fiction, Fiction, Historical, Medie...The Empty Throne was an improvement over The P...The Empty Throne Historical Fiction Fiction Hi...
...........................
17801843The Soul of an OctopusSy Montgomery3.93In pursuit of the wild, solitary, predatory oc...Nonfiction, Science, Animals, Nature, Memoir, ...I'm kind of \"eh\" on this book. It bills itself...The Soul of an Octopus Nonfiction Science Anim...
17811844The Jim Corbett Omnibus: \"Man-eaters of Kumaon...Jim Corbett4.54Jim Corbett's riveting accounts of shikar in t...Nonfiction, Wildlife, Nature, Travel, Biograph...One of the best books ever written, this book ...The Jim Corbett Omnibus: \"Man-eaters of Kumaon...
17821845The Tiger: A True Story of Vengeance and SurvivalJohn Vaillant4.07It’s December 1997, and a man-eating tiger is ...Nonfiction, History, Nature, Animals, Russia, ...Fearful symmetry indeed. In 1997, during time ...The Tiger: A True Story of Vengeance and Survi...
17831846100 Heartbeats: The Race to Save Earth's Most ...Jeff Corwin4.17It's no secret that our planet―and the delicat...Nonfiction, Animals, Science, Nature, Conserva...I learned a lot reading this book. Frightening...100 Heartbeats: The Race to Save Earth's Most ...
17841847An Elephant in My KitchenFrançoise Malby-Anthony4.39A blonde, chic Parisienne, Francoise never exp...Nonfiction, Animals, Memoir, Africa, Nature, B...Thula Thula, South Africa, the sanctuary for e...An Elephant in My Kitchen Nonfiction Animals M...
\n", "

1779 rows × 8 columns

\n", "
" ], "text/plain": [ " Id Title \\\n", "0 1 Beowulf \n", "1 2 The Evening and the Morning \n", "2 3 The Abbot's Tale \n", "3 4 Ibn Fadlān and the Land of Darkness: Arab Trav... \n", "4 5 The Empty Throne \n", "... ... ... \n", "1780 1843 The Soul of an Octopus \n", "1781 1844 The Jim Corbett Omnibus: \"Man-eaters of Kumaon... \n", "1782 1845 The Tiger: A True Story of Vengeance and Survival \n", "1783 1846 100 Heartbeats: The Race to Save Earth's Most ... \n", "1784 1847 An Elephant in My Kitchen \n", "\n", " Author Rating \\\n", "0 Seamus Heaney 3.48 \n", "1 Ken Follett 4.38 \n", "2 Conn Iggulden 4.05 \n", "3 Ahmad ibn Fadlān 3.87 \n", "4 Bernard Cornwell 4.38 \n", "... ... ... \n", "1780 Sy Montgomery 3.93 \n", "1781 Jim Corbett 4.54 \n", "1782 John Vaillant 4.07 \n", "1783 Jeff Corwin 4.17 \n", "1784 Françoise Malby-Anthony 4.39 \n", "\n", " Description \\\n", "0 Composed toward the end of the first millenniu... \n", "1 The thrilling and addictive prequel to The Pil... \n", "2 In the year 937, the new king of England, a gr... \n", "3 In 922 AD, an Arab envoy from Baghdad named Ib... \n", "4 This eighth entry in New York Times bestsellin... \n", "... ... \n", "1780 In pursuit of the wild, solitary, predatory oc... \n", "1781 Jim Corbett's riveting accounts of shikar in t... \n", "1782 It’s December 1997, and a man-eating tiger is ... \n", "1783 It's no secret that our planet―and the delicat... \n", "1784 A blonde, chic Parisienne, Francoise never exp... \n", "\n", " Genres \\\n", "0 Classics, Poetry, Fiction, Fantasy, Mythology,... \n", "1 Historical Fiction, Fiction, Historical, Audio... \n", "2 Historical Fiction, Fiction, Historical, Medie... \n", "3 History, Travel, Nonfiction, Classics, Islam, ... \n", "4 Historical Fiction, Fiction, Historical, Medie... \n", "... ... \n", "1780 Nonfiction, Science, Animals, Nature, Memoir, ... \n", "1781 Nonfiction, Wildlife, Nature, Travel, Biograph... \n", "1782 Nonfiction, History, Nature, Animals, Russia, ... \n", "1783 Nonfiction, Animals, Science, Nature, Conserva... \n", "1784 Nonfiction, Animals, Memoir, Africa, Nature, B... \n", "\n", " Reviews \\\n", "0 *bum bum* IN A WORLD . . . *bum bum* . . . FUL... \n", "1 It's 997 CE, the end of the Dark Ages in Engla... \n", "2 There is never one truth, one love, or one ene... \n", "3 رسالة ابن فضلان .. أو ما يسمى برحلة ابن فضلان ... \n", "4 The Empty Throne was an improvement over The P... \n", "... ... \n", "1780 I'm kind of \"eh\" on this book. It bills itself... \n", "1781 One of the best books ever written, this book ... \n", "1782 Fearful symmetry indeed. In 1997, during time ... \n", "1783 I learned a lot reading this book. Frightening... \n", "1784 Thula Thula, South Africa, the sanctuary for e... \n", "\n", " Combined \n", "0 Beowulf Classics Poetry Fiction Fantasy Mythol... \n", "1 The Evening and the Morning Historical Fiction... \n", "2 The Abbot's Tale Historical Fiction Fiction Hi... \n", "3 Ibn Fadlān and the Land of Darkness: Arab Trav... \n", "4 The Empty Throne Historical Fiction Fiction Hi... \n", "... ... \n", "1780 The Soul of an Octopus Nonfiction Science Anim... \n", "1781 The Jim Corbett Omnibus: \"Man-eaters of Kumaon... \n", "1782 The Tiger: A True Story of Vengeance and Survi... \n", "1783 100 Heartbeats: The Race to Save Earth's Most ... \n", "1784 An Elephant in My Kitchen Nonfiction Animals M... \n", "\n", "[1779 rows x 8 columns]" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# df['Combined'] = df.apply(title_description_genres_to_string, axis=1)\n", "df['Title'] = preprocess_text(df['Title'])\n", "df['Description'] = preprocess_text(df['Description'])\n", "df['Genres'] = preprocess_text(df['Genres'])\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6295f3bbee6d43c1a32f8e626eaa31cc", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Epoch: 0%| | 0/1 [00:00 flag_threshold]\n", " reranked_results = sorted(reranked_results, key=lambda x: x[2], reverse=True)[:rerank_k]\n", " else:\n", " reranked_results = initial_results[:rerank_k]\n", "\n", " return reranked_results\n", "\n", "print(\"START\")\n", "query = \"Search for science fiction books with a focus on space exploration.\"\n", "flag_reranker = FlagReranker('BAAI/bge-small-en-v1.5', use_fp16=True) # Initialize the FlagReranker object\n", "results = semantic_search(query, flag_reranker=flag_reranker)\n", "\n", "for rank, (title, text, score) in enumerate(results, start=1):\n", " print(f\"Rank {rank}: {title} (Score: {score})\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 }