A lightweight semantic search engine using transformer embeddings.
Project description
Search Engine - README
Overview
This Search Engine class provides a simple way to store, search, and remove sentences/phrases using embeddings generated from a pre-trained transformer model (all-MiniLM-L6-v2). It utilizes the Hugging Face AutoModel and AutoTokenizer for encoding sentences into dense vector embeddings, then allows for cosine similarity-based searches.
Features
- Add Sentence: Add a sentence to the dataset if it's not already present.
- Search: Find similar sentences based on cosine similarity.
- Remove Sentence: Remove a sentence by exact match if present.
- Clear All: Remove all stored data (vectors and sentences).
Requirements
- Python >= 3.7
transformerslibrary (for Hugging Face models)torch(PyTorch)scikit-learn(for cosine similarity)
Installation & Setup
-
Clone the Repository: First, clone the repository to your local machine.
git clone <repository_url> cd <repository_name>
-
Install Required Dependencies: Install the necessary Python dependencies via
pip:pip install -r requirements.txt
Where
requirements.txtincludes:transformers==4.x torch==1.x scikit-learn==0.24 -
Download Pre-trained Model: You can either download the model from Hugging Face and save it locally or use a pre-downloaded model. Make sure the model is located in
./my_local_model/all-MiniLM-L6-v2.- To download the model directly using
transformers, run:
python -c "from transformers import AutoModel, AutoTokenizer; AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2'); AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')"
- To download the model directly using
-
Run the Python Code: After setup, you can start using the search engine class by running the Python script that contains the
Search_engineclass.Example:
python search_engine.py
Bash Script for Setup and Execution
#!/bin/bash
# Step 1: Install Python and required packages
echo "Checking Python version..."
python3 --version
if [ $? -ne 0 ]; then
echo "Python3 is not installed. Installing Python3..."
sudo apt update
sudo apt install python3 python3-pip -y
fi
# Install dependencies
echo "Installing required dependencies..."
pip install -r requirements.txt
# Step 2: Download Pre-trained Model (if not already downloaded)
MODEL_DIR="./my_local_model/all-MiniLM-L6-v2"
if [ ! -d "$MODEL_DIR" ]; then
echo "Model not found, downloading..."
python -c "from transformers import AutoModel, AutoTokenizer; AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2'); AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')"
else
echo "Model already downloaded at $MODEL_DIR."
fi
# Step 3: Run the Python script (assumes the script is named search_engine.py)
echo "Running the Search Engine..."
python search_engine.py
Code Walkthrough
Search_engine Class:
-
Initialization (
__init__):- Loads the model and tokenizer from the specified directory.
- Initializes empty lists to store sentence vectors (
vector_data) and sentences (base_data). - Sets a similarity threshold (
threshold).
-
get_cls_vector:- Converts a sentence to its vector representation using the pre-trained model.
- Returns the embedding corresponding to the
[CLS]token.
-
similarity:- Calculates the cosine similarity between two vectors
XandY.
- Calculates the cosine similarity between two vectors
-
add_one:- Converts a sentence to its vector and checks if a similar sentence already exists. If not, it stores the sentence and its vector.
-
add_more:- Adds multiple sentences to the search engine.
-
search_one:- Searches for the most similar sentences to a given input sentence, returning results that exceed the defined similarity threshold.
-
remove_one:- Removes a sentence if it has an exact match based on similarity.
-
remove_all:- Clears all stored sentences and vectors.
Example Usage
# Initialize the Search Engine
search_engine = Search_engine()
# Add sentences
search_engine.add_one("I love machine learning.")
search_engine.add_one("Artificial Intelligence is fascinating.")
# Search for similar sentences
results = search_engine.search_one("I enjoy AI.", metadata=True)
for score, sentence, index in results:
print(f"Score: {score}, Sentence: {sentence}, Index: {index}")
# Remove a sentence
search_engine.remove_one("I love machine learning.")
# Clear all data
search_engine.remove_all()
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file searchengine_v1-0.2.tar.gz.
File metadata
- Download URL: searchengine_v1-0.2.tar.gz
- Upload date:
- Size: 4.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
178bb0df924fcd1caebb4059fd455f90a7f0a708c214fef877c42d1d55c3eb77
|
|
| MD5 |
788ba63e88cc72d20d7ffcf02534a775
|
|
| BLAKE2b-256 |
52ceb01be024d29eeff58216078ce9b1a97ba60875da4dd7d78a9c5012e7d6a1
|
File details
Details for the file searchengine_v1-0.2-py3-none-any.whl.
File metadata
- Download URL: searchengine_v1-0.2-py3-none-any.whl
- Upload date:
- Size: 4.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ad1fcc5aa78f02ea09ec72dbab79abf5bfc0e4c5e6f61049f3b70b2796793d24
|
|
| MD5 |
26a9818c7eefc22e01dee961a078771b
|
|
| BLAKE2b-256 |
778f84a29513e5b5fc97f8206b4beeebcb8f51311150b58e9d68d1584a928af3
|