💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add close methods to database and embeddings, closes #173
davidmezzettid15df0f3c915
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.pyindex 0f45d22c..e56b5387 100644--- a/src/python/txtai/database/base.py+++ b/src/python/txtai/database/base.py@@ -72,6 +72,13 @@ class Database:raise NotImplementedError+ def close(self):+ """+ Closes the database.+ """++ raise NotImplementedError+def ids(self, ids):"""Retrieves the internal indexids for a list of ids. Multiple indexids may be present for an id in casesdiff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.pyindex 33c9ca06..51594648 100644--- a/src/python/txtai/database/sqlite.py+++ b/src/python/txtai/database/sqlite.py@@ -153,6 +153,11 @@ class SQLite(Database):else:self.copy(path).close()+ def close(self):+ # Close connection+ if self.connection:+ self.connection.close()+def ids(self, ids):# Batch ids and run queryself.batch(ids=ids)diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex 4ca7ab97..3755adbb 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -17,7 +17,7 @@ from .archive import Archivefrom .reducer import Reducerfrom .search import Search-+# pylint: disable=R0904class Embeddings:"""Embeddings is the engine that delivers semantic search. Text is transformed into embeddings vectors where similar concepts@@ -99,7 +99,8 @@ class Embeddings:# Build the indexself.ann.index(embeddings)- self.database = DatabaseFactory.create(self.config)+ # Create document database+ self.database = self.createdatabase()if self.database:# Add documents to databaseself.database.insert(documents)@@ -350,7 +351,7 @@ class Embeddings:self.model = self.loadvectors()# Document database - stores document content- self.database = DatabaseFactory.create(self.config)+ self.database = self.createdatabase()if self.database:self.database.load(f"{path}/documents")@@ -411,26 +412,17 @@ class Embeddings:if apath:self.archive.save(apath)- def checkarchive(self, path):+ def close(self):"""- Checks if path is an archive file.-- Args:- path: path to check-- Returns:- (working directory, current path) if this is an archive, original path otherwise+ Closes this embeddings index and frees all resources."""- # Create archive instance, if necessary- self.archive = self.archive if self.archive else Archive()-- # Check if path if an archive file- if self.archive.isarchive(path):- # Return temporary archive working directory and original path- return self.archive.path(), path+ self.config, self.ann, self.reducer, self.scoring, self.model, self.archive = None, None, None, None, None, None- return path, None+ # Close database connection if open+ if self.database:+ self.database.close()+ self.database = Nonedef loadvectors(self):"""@@ -467,20 +459,6 @@ class Embeddings:return (ids, dimensions, embeddings)- def normalize(self, embeddings):- """- Normalizes embeddings using L2 normalization. Operation applied directly on array.-- Args:- embeddings: input embeddings matrix- """-- # Calculation is different for matrices vs vectors- if len(embeddings.shape) > 1:- embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]- else:- embeddings /= np.linalg.norm(embeddings)-def gettext(self, documents):"""Selects documents that have text to vectorize for similarity indexing.@@ -502,3 +480,53 @@ class Embeddings:yield documentelif isinstance(document[1], dict) and "text" in document[1]:yield (document[0], document[1]["text"], document[2])++ def checkarchive(self, path):+ """+ Checks if path is an archive file.++ Args:+ path: path to check++ Returns:+ (working directory, current path) if this is an archive, original path otherwise+ """++ # Create archive instance, if necessary+ self.archive = self.archive if self.archive else Archive()++ # Check if path is an archive file+ if self.archive.isarchive(path):+ # Return temporary archive working directory and original path+ return self.archive.path(), path++ return path, None++ def createdatabase(self):+ """+ Creates a database from config. This method will also close any existing database connection.++ Returns:+ new database, if enabled in config+ """++ # Free existing database resources+ if self.database:+ self.database.close()++ # Create database from config and return+ return DatabaseFactory.create(self.config)++ def normalize(self, embeddings):+ """+ Normalizes embeddings using L2 normalization. Operation applied directly on array.++ Args:+ embeddings: input embeddings matrix+ """++ # Calculation is different for matrices vs vectors+ if len(embeddings.shape) > 1:+ embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]+ else:+ embeddings /= np.linalg.norm(embeddings)diff --git a/src/python/txtai/pipeline/train/hfonnx.py b/src/python/txtai/pipeline/train/hfonnx.pyindex 9a0274bc..048b5ae8 100644--- a/src/python/txtai/pipeline/train/hfonnx.py+++ b/src/python/txtai/pipeline/train/hfonnx.py@@ -164,7 +164,7 @@ class HFOnnx(Tensors):class MeanPoolingOnnx(MeanPooling):"""- Extends MeanPooling class to explicitly name inputs to model, which is required+ Extends MeanPooling class to name inputs to model, which is requiredto export to ONNX."""diff --git a/test/python/testdatabase/testembeddings.py b/test/python/testdatabase/testembeddings.pyindex 05409c44..7426bf86 100644--- a/test/python/testdatabase/testembeddings.py+++ b/test/python/testdatabase/testembeddings.py@@ -6,8 +6,6 @@ import osimport tempfileimport unittest-from pathlib import Path-from txtai.embeddings import Embeddingsfrom txtai.database import Database, SQLException@@ -59,6 +57,25 @@ class TestEmbeddings(unittest.TestCase):self.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])self.assertEqual(self.embeddings.count(), len(self.data))+ def testClose(self):+ """+ Tests embeddings close+ """++ # Create index twice to test open/close and ensure resources are freed+ for _ in range(2):+ embeddings = Embeddings({"path": "google/bert_uncased_L-2_H-128_A-2", "content": True})++ # Add record to index+ embeddings.index([(0, "Close test", None)])++ # Save index+ index = os.path.join(tempfile.gettempdir(), "embeddings.close")+ embeddings.save(index)++ # Close index+ embeddings.close()+def testData(self):"""Test content storage and retrieval@@ -133,10 +150,6 @@ class TestEmbeddings(unittest.TestCase):# Save to a different locationindexupdate = os.path.join(tempfile.gettempdir(), "embeddings.update")-- # Create existing file to test file save conflicts- Path.touch(os.path.join(indexupdate, "documents"))-self.embeddings.save(indexupdate)# Save to same location@@ -165,6 +178,7 @@ class TestEmbeddings(unittest.TestCase):self.assertRaises(NotImplementedError, database.insert, None)self.assertRaises(NotImplementedError, database.delete, None)self.assertRaises(NotImplementedError, database.save, None)+ self.assertRaises(NotImplementedError, database.close)self.assertRaises(NotImplementedError, database.ids, None)self.assertRaises(NotImplementedError, database.resolve, None, None)self.assertRaises(NotImplementedError, database.embed, None, None)