-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* working services * black * tests * CR
- Loading branch information
Showing
9 changed files
with
158 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
from .base import DocumentsManager | ||
from .pickle import DocumentsPickle | ||
from .service import DocumentsService | ||
from .sqlite import DocumentsDB | ||
|
||
__all__ = [DocumentsManager, DocumentsPickle, DocumentsDB] | ||
__all__ = [DocumentsManager, DocumentsPickle, DocumentsDB, DocumentsService] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import os | ||
|
||
import pandas as pd | ||
import pinecone | ||
from pymongo.mongo_client import MongoClient | ||
from pymongo.server_api import ServerApi | ||
|
||
from buster.documents.base import DocumentsManager | ||
|
||
|
||
class DocumentsService(DocumentsManager): | ||
"""Manager to use in production. Mixed Pinecone and MongoDB backend.""" | ||
|
||
def __init__( | ||
self, | ||
pinecone_api_key: str, | ||
pinecone_env: str, | ||
pinecone_index: str, | ||
mongo_uri: str, | ||
mongo_db_name: str, | ||
**kwargs, | ||
): | ||
super().__init__(**kwargs) | ||
|
||
pinecone.init(api_key=pinecone_api_key, environment=pinecone_env) | ||
|
||
self.index = pinecone.Index(pinecone_index) | ||
|
||
self.client = MongoClient(mongo_uri, server_api=ServerApi("1")) | ||
self.db = self.client[mongo_db_name] | ||
|
||
def __repr__(self): | ||
return "DocumentsService" | ||
|
||
def get_source_id(self, source: str) -> str: | ||
"""Get the id of a source.""" | ||
return str(self.db.sources.find_one({"name": source})["_id"]) | ||
|
||
def add(self, source: str, df: pd.DataFrame): | ||
"""Write all documents from the dataframe into the db as a new version.""" | ||
source_exists = self.db.sources.find_one({"name": source}) | ||
if source_exists is None: | ||
self.db.sources.insert_one({"name": source}) | ||
|
||
source_id = self.get_source_id(source) | ||
|
||
for _, row in df.iterrows(): | ||
document = { | ||
"title": row["title"], | ||
"url": row["url"], | ||
"content": row["content"], | ||
"n_tokens": row["n_tokens"], | ||
"source_id": source_id, | ||
} | ||
document_id = str(self.db.documents.insert_one(document).inserted_id) | ||
self.index.upsert([(document_id, row["embedding"].tolist(), {"source": source})]) | ||
|
||
def update_source(self, source: str, display_name: str = None, note: str = None): | ||
"""Update the display name and/or note of a source. Also create the source if it does not exist.""" | ||
self.db.sources.update_one( | ||
{"name": source}, {"$set": {"display_name": display_name, "note": note}}, upsert=True | ||
) | ||
|
||
def delete_source(self, source: str) -> tuple[int, int]: | ||
"""Delete a source and all its documents. Return if the source was deleted and the number of deleted documents.""" | ||
source_id = self.get_source_id(source) | ||
|
||
# MongoDB | ||
source_deleted = self.db.sources.delete_one({"name": source}).deleted_count | ||
documents_deleted = self.db.documents.delete_many({"source_id": source_id}).deleted_count | ||
|
||
# Pinecone | ||
self.index.delete(filter={"source": source}) | ||
|
||
return source_deleted, documents_deleted |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
from .base import Retriever | ||
from .pickle import PickleRetriever | ||
from .service import ServiceRetriever | ||
from .sqlite import SQLiteRetriever | ||
|
||
__all__ = [Retriever, PickleRetriever, SQLiteRetriever] | ||
__all__ = [Retriever, PickleRetriever, SQLiteRetriever, ServiceRetriever] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import pandas as pd | ||
import pinecone | ||
from bson.objectid import ObjectId | ||
from pymongo.mongo_client import MongoClient | ||
from pymongo.server_api import ServerApi | ||
|
||
from buster.retriever.base import ALL_SOURCES, Retriever | ||
|
||
|
||
class ServiceRetriever(Retriever): | ||
def __init__( | ||
self, | ||
pinecone_api_key: str, | ||
pinecone_env: str, | ||
pinecone_index: str, | ||
mongo_uri: str, | ||
mongo_db_name: str, | ||
**kwargs, | ||
): | ||
super().__init__(**kwargs) | ||
|
||
pinecone.init(api_key=pinecone_api_key, environment=pinecone_env) | ||
|
||
self.index = pinecone.Index(pinecone_index) | ||
|
||
self.client = MongoClient(mongo_uri, server_api=ServerApi("1")) | ||
self.db = self.client[mongo_db_name] | ||
|
||
def get_documents(self, source: str) -> pd.DataFrame: | ||
"""Get all current documents from a given source.""" | ||
return self.db.documents.find({"source_id": source}) | ||
|
||
def get_source_display_name(self, source: str) -> str: | ||
"""Get the display name of a source.""" | ||
if source == "": | ||
return ALL_SOURCES | ||
else: | ||
display_name = self.db.sources.find_one({"name": source})["display_name"] | ||
return display_name | ||
|
||
def retrieve(self, query_embedding: list[float], top_k: int, source: str = None) -> pd.DataFrame: | ||
# Pinecone retrieval | ||
matches = self.index.query(query_embedding, top_k=top_k, filter={"source": {"$eq": source}})["matches"] | ||
matching_ids = [ObjectId(match.id) for match in matches] | ||
matching_scores = {match.id: match.score for match in matches} | ||
|
||
if len(matching_ids) == 0: | ||
return pd.DataFrame() | ||
|
||
# MongoDB retrieval | ||
matched_documents = self.db.documents.find({"_id": {"$in": matching_ids}}) | ||
matched_documents = pd.DataFrame(list(matched_documents)) | ||
matched_documents["similarity"] = matched_documents["_id"].apply(lambda x: matching_scores[str(x)]) | ||
|
||
return matched_documents |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters