bestrag 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bestrag/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .best_rag import BestRAG
bestrag/best_rag.py ADDED
@@ -0,0 +1,226 @@
1
+ """B-RAG"""
2
+ # Authors: Abdul Samad Siddiqui <abdulsamadsid1@gmail.com>
3
+
4
+ import re
5
+ import uuid
6
+ from typing import List, Optional
7
+ from qdrant_client import QdrantClient, models
8
+ from qdrant_client.http.models import Distance, VectorParams
9
+ from fastembed import TextEmbedding
10
+ from fastembed.sparse.bm25 import Bm25
11
+ import PyPDF2
12
+
13
+
14
+ class BestRAG:
15
+ """
16
+ BestRAG (Best Retrieval Augmented by Qdrant) is a class that provides
17
+ functionality for storing and searching document embeddings in a Qdrant
18
+ vector database.
19
+
20
+ It supports both dense and sparse embeddings, as well as a late interaction
21
+ model for improved retrieval performance.
22
+
23
+ Args:
24
+ url (str): The URL of the Qdrant server.
25
+ api_key (str): The API key for the Qdrant server.
26
+ collection_name (str): The name of the Qdrant collection to use.
27
+ late_interaction_model_name (Optional[str]): The name of the late
28
+ interaction model to use. Defaults to "BAAI/bge-small-en-v1.5".
29
+ """
30
+
31
+ def __init__(self,
32
+ url: str,
33
+ api_key: str,
34
+ collection_name: str,
35
+ late_interaction_model_name: Optional[str] = "BAAI/bge-small-en-v1.5"
36
+ ):
37
+ self.collection_name = collection_name
38
+ self.client = QdrantClient(url=url, api_key=api_key)
39
+
40
+ self.dense_model = TextEmbedding()
41
+ self.late_interaction_model = TextEmbedding(
42
+ late_interaction_model_name)
43
+ self.sparse_model = Bm25("Qdrant/bm25")
44
+
45
+ self._create_or_use_collection()
46
+
47
+ def _create_or_use_collection(self):
48
+ """
49
+ Create a new Qdrant collection if it doesn't exist, or use an existing one.
50
+ """
51
+ collections = self.client.get_collections()
52
+ collection_names = [
53
+ collection.name for collection in collections.collections]
54
+
55
+ if self.collection_name not in collection_names:
56
+ self.client.create_collection(
57
+ collection_name=self.collection_name,
58
+ vectors_config={
59
+ "dense-vector": models.VectorParams(
60
+ size=384,
61
+ distance=Distance.COSINE
62
+ ),
63
+ "output-token-embeddings": models.VectorParams(
64
+ size=384,
65
+ distance=Distance.COSINE,
66
+ multivector_config=models.MultiVectorConfig(
67
+ comparator=models.MultiVectorComparator.MAX_SIM
68
+ )
69
+ ),
70
+ },
71
+ sparse_vectors_config={"sparse": models.SparseVectorParams()}
72
+ )
73
+ print(f"Created collection: {self.collection_name}")
74
+ else:
75
+ print(f"Using existing collection: {self.collection_name}")
76
+
77
+ def _clean_text(self, text: str) -> str:
78
+ """
79
+ Clean the input text by removing special characters and formatting.
80
+
81
+ Args:
82
+ text (str): The text to be cleaned.
83
+
84
+ Returns:
85
+ str: The cleaned text.
86
+ """
87
+ text = re.sub(r'_+', '', text)
88
+ text = text.replace('\n', ' ')
89
+ text = re.sub(r'\s{2,}', ' ', text)
90
+ text = re.sub(r'(\d+\.)\s', r'\n\1 ', text)
91
+ return text.strip()
92
+
93
+ def _get_dense_embedding(self, text: str):
94
+ """
95
+ Get the dense embedding for the given text.
96
+
97
+ Args:
98
+ text (str): The text to be embedded.
99
+
100
+ Returns:
101
+ List[float]: The dense embedding vector.
102
+ """
103
+ return list(self.dense_model.embed([text]))[0]
104
+
105
+ def _get_late_interaction_embedding(self, text: str):
106
+ """
107
+ Get the late interaction embedding for the given text.
108
+
109
+ Args:
110
+ text (str): The text to be embedded.
111
+
112
+ Returns:
113
+ List[float]: The late interaction embedding vector.
114
+ """
115
+ return list(self.late_interaction_model.embed([text]))[0]
116
+
117
+ def _get_sparse_embedding(self, text: str):
118
+ """
119
+ Get the sparse embedding for the given text.
120
+
121
+ Args:
122
+ text (str): The text to be embedded.
123
+
124
+ Returns:
125
+ models.SparseVector: The sparse embedding vector.
126
+ """
127
+ return next(self.sparse_model.embed(text))
128
+
129
+ def _extract_pdf_text_per_page(self, pdf_path: str) -> List[str]:
130
+ """
131
+ Load a PDF file and extract the text from each page.
132
+
133
+ Args:
134
+ pdf_path (str): The path to the PDF file.
135
+
136
+ Returns:
137
+ List[str]: The text from each page of the PDF.
138
+ """
139
+ with open(pdf_path, "rb") as pdf_file:
140
+ reader = PyPDF2.PdfReader(pdf_file)
141
+ return [page.extract_text() for page in reader.pages]
142
+
143
+ def store_pdf_embeddings(self, pdf_path: str):
144
+ """
145
+ Store the embeddings for each page of a PDF file in the Qdrant collection.
146
+
147
+ Args:
148
+ pdf_path (str): The path to the PDF file.
149
+ """
150
+ texts = self._extract_pdf_text_per_page(pdf_path)
151
+
152
+ for page_num, text in enumerate(texts):
153
+ clean_text = self._clean_text(text)
154
+ dense_embedding = self._get_dense_embedding(clean_text)
155
+ late_interaction_embedding = self._get_late_interaction_embedding(
156
+ clean_text)
157
+ sparse_embedding = self._get_sparse_embedding(clean_text)
158
+
159
+ hybrid_vector = {
160
+ "dense-vector": dense_embedding,
161
+ "output-token-embeddings": late_interaction_embedding,
162
+ "sparse": models.SparseVector(
163
+ indices=sparse_embedding.indices,
164
+ values=sparse_embedding.values,
165
+ )
166
+ }
167
+
168
+ payload = {
169
+ "text": clean_text,
170
+ "page_number": page_num + 1
171
+ }
172
+
173
+ point = models.PointStruct(
174
+ id=str(uuid.uuid4()),
175
+ vector=hybrid_vector,
176
+ payload=payload
177
+ )
178
+
179
+ self.client.upsert(
180
+ collection_name=self.collection_name,
181
+ points=[point]
182
+ )
183
+ print(
184
+ f"Stored embedding for page {page_num + 1} in collection '{self.collection_name}'.")
185
+
186
+ def search(self, query: str, limit: int = 10):
187
+ """
188
+ Search the Qdrant collection for documents that match the given query.
189
+
190
+ Args:
191
+ query (str): The search query.
192
+ limit (int): The maximum number of results to return. Defaults to 10.
193
+
194
+ Returns:
195
+ List[models.SearchResult]: The search results.
196
+ """
197
+ clean_query = self._clean_text(query)
198
+ dense_query = self._get_dense_embedding(clean_query)
199
+ late_interaction_query = self._get_late_interaction_embedding(
200
+ clean_query)
201
+ sparse_query = self._get_sparse_embedding(clean_query)
202
+
203
+ query_vector = {
204
+ "dense-vector": dense_query,
205
+ "output-token-embeddings": late_interaction_query,
206
+ "sparse": {
207
+ "indices": sparse_query.indices,
208
+ "values": sparse_query.values,
209
+ }
210
+ }
211
+
212
+ results = self.client.query_points(
213
+ collection_name=self.collection_name,
214
+ prefetch=[
215
+ models.Prefetch(
216
+ query=query_vector["dense-vector"],
217
+ using="dense-vector",
218
+ limit=50,
219
+ )
220
+ ],
221
+ query=query_vector["output-token-embeddings"],
222
+ using="output-token-embeddings",
223
+ limit=limit,
224
+ )
225
+
226
+ return results
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Abdul Samad Siddiqui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.1
2
+ Name: bestrag
3
+ Version: 0.0.1
4
+ Summary: BestRAG (Best Retrieval Augmented) is a library for storing and searching document embeddings in a Qdrant vector database. It uses a hybrid embedding technique combining dense, late interaction and sparse representations for better performance.
5
+ Home-page: https://github.com/samadpls/bestRAG
6
+ Author: samadpls
7
+ Author-email: abdulsamadsid1@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: fastembed==0.4.1
15
+ Requires-Dist: streamlit
16
+ Requires-Dist: pytest
17
+ Requires-Dist: flake8
18
+ Requires-Dist: PyPDF2
19
+ Requires-Dist: qdrant-client
20
+ Requires-Dist: onnxruntime==1.19.2
21
+
22
+
23
+ <img src="https://github.com/user-attachments/assets/e23d11d5-2d7b-44e2-aa11-59ddcb66bebc" align=left height=150px>
24
+
25
+ ![Supported python versions](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue)
26
+ [![PEP8](https://img.shields.io/badge/code%20style-pep8-black.svg)](https://www.python.org/dev/peps/pep-0008/)
27
+ [![License](https://img.shields.io/badge/License-MIT%202.0-blue.svg)](LICENSE)
28
+ [![Run Pytest](https://github.com/samadpls/BestRAG/actions/workflows/pytest.yml/badge.svg?branch=main)](https://github.com/samadpls/BestRAG/actions/workflows/pytest.yml)
29
+ ![GitHub stars](https://img.shields.io/github/stars/samadpls/BestRAG?color=red&label=stars&logoColor=black&style=social)
30
+
31
+
32
+ Welcome to **BestRAG**! This Python library enables you to efficiently store and retrieve embeddings using a hybrid Retrieval-Augmented Generation (RAG) approach. It combines dense, sparse, and late interaction embeddings to provide a robust solution for handling large datasets.
33
+
34
+ ---
35
+
36
+ ## πŸš€ Installation
37
+
38
+ To install **BestRAG**, simply run:
39
+
40
+ ```bash
41
+ pip install bestrag
42
+ ```
43
+
44
+ ## πŸ“¦ Usage
45
+
46
+ Here’s how you can use **BestRAG** in your projects:
47
+
48
+ ```python
49
+ from bestrag import BestRAG
50
+
51
+ rag = BestRAG(
52
+ url="https://YOUR_QDRANT_URL",
53
+ api_key="YOUR_API_KEY",
54
+ collection_name="YOUR_COLLECTION_NAME"
55
+ )
56
+
57
+ # Store embeddings from a PDF
58
+ rag.store_pdf_embeddings("your_pdf_file.pdf")
59
+
60
+ # Search using a query
61
+ results = rag.search(query="your search query", limit=10)
62
+ print(results)
63
+ ```
64
+
65
+ > **Note**: To generate your API key and endpoint, visit [Qdrant](https://qdrant.tech/).
66
+
67
+ ## ✨ Features
68
+
69
+ - **Hybrid RAG**: Utilizes dense, sparse, and late interaction embeddings for enhanced performance.
70
+ - **Easy Integration**: Simple API for storing and searching embeddings.
71
+ - **PDF Support**: Directly store embeddings from PDF documents.
72
+
73
+ ## 🀝 Contributing
74
+
75
+ Feel free to contribute to **BestRAG**! Whether it’s reporting bugs, suggesting features, or submitting pull requests, your contributions are welcome.
76
+
77
+ ## πŸ“ License
78
+
79
+ This project is licensed under the [MIT License](LICENSE).
80
+
81
+ ---
82
+
83
+ Created by [samadpls](https://github.com/samadpls) πŸŽ‰
@@ -0,0 +1,7 @@
1
+ bestrag/__init__.py,sha256=CMPL5pGf3noZiU7mUHPTwnNXQLYfnHb9lMX91Y-o824,29
2
+ bestrag/best_rag.py,sha256=IBQM36AagMimvraunr0lxGZ8eTyYfHgAyfbuznpaPPs,7636
3
+ bestrag-0.0.1.dist-info/LICENSE,sha256=y6Lb5TEHBlAqttntR2GfYXHoypofQwu9gwaMeTBtpKk,1076
4
+ bestrag-0.0.1.dist-info/METADATA,sha256=USG_NNhCQ6R_NR0QqHHxA18Yc-MftC7bNCwKjVr-P3k,2994
5
+ bestrag-0.0.1.dist-info/WHEEL,sha256=eOLhNAGa2EW3wWl_TU484h7q1UNgy0JXjjoqKoxAAQc,92
6
+ bestrag-0.0.1.dist-info/top_level.txt,sha256=7VPzc3Lm3_inRlEYxzkSQ03oC1J15Dgc9_Lb-vn-PmM,8
7
+ bestrag-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.44.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ bestrag