Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add index archive support, closes #172

davidmezzetti600fd2e5ea0d
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
index e0338c3d..0f45d22c 100644
--- a/src/python/txtai/database/base.py
+++ b/src/python/txtai/database/base.py
@@ -65,6 +65,9 @@ class Database:
def save(self, path):
"""
Saves a database at path.
+
+ Args:
+ path: path to write database
"""
raise NotImplementedError
diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.py
index e721208c..33c9ca06 100644
--- a/src/python/txtai/database/sqlite.py
+++ b/src/python/txtai/database/sqlite.py
@@ -129,27 +129,30 @@ class SQLite(Database):
self.cursor.execute(SQLite.DELETE_SECTIONS)
def save(self, path):
- # Save the changes
- self.connection.commit()
-
- # If this is a temporary database, copy over to database at path
+ # Temporary database
if not self.path:
- # Delete existing file, if necessary
- if os.path.exists(path):
- os.remove(path)
+ # Save temporary database
+ self.connection.commit()
- # Create database. Thread locking must be handled externally.
- connection = sqlite3.connect(path, check_same_thread=False)
+ # Copy data from current to new
+ connection = self.copy(path)
- # Copy from existing database to new database
- self.connection.backup(connection)
+ # Close temporary database
self.connection.close()
- # Point connection to new database
+ # Point connection to new connection
self.connection = connection
self.cursor = self.connection.cursor()
self.path = path
+ # Paths are equal, commit changes
+ elif self.path == path:
+ self.connection.commit()
+
+ # New path is different from current path, copy data and continue using current connection
+ else:
+ self.copy(path).close()
+
def ids(self, ids):
# Batch ids and run query
self.batch(ids=ids)
@@ -158,6 +161,42 @@ class SQLite(Database):
# Format and return results
return self.cursor.fetchall()
+ def resolve(self, name, alias=False, compound=False):
+ # Standard column names
+ sections = ["indexid", "id", "tags", "entry"]
+ noprefix = ["data", "score", "text"]
+
+ # Alias JSON column expressions
+ if alias:
+ # Only apply aliases to non-standard columns or compound expressions
+ if name not in sections + noprefix or compound:
+ return f' as "{name}"'
+
+ # No alias
+ return None
+
+ # Standard columns - need prefixes
+ if name.lower() in sections:
+ return f"s.{name}"
+
+ # Standard columns - no prefixes
+ if name.lower() in noprefix:
+ return name
+
+ # Other columns come from documents.data JSON
+ return f'json_extract(data, "$.{name}")'
+
+ def embed(self, similarity, batch):
+ # Load similarity results id batch
+ self.batch(indexids=[i for i, _ in similarity[batch]], batch=batch)
+
+ # Average and load all similarity scores with first batch
+ if not batch:
+ self.scores(similarity)
+
+ # Return ids clause placeholder
+ return SQLite.IDS_CLAUSE % batch
+
def query(self, query, limit):
# Extract query components
select = query.get("select", self.defaults())
@@ -209,41 +248,50 @@ class SQLite(Database):
return results
- def resolve(self, name, alias=False, compound=False):
- # Standard column names
- sections = ["indexid", "id", "tags", "entry"]
- noprefix = ["data", "score", "text"]
+ def initialize(self):
+ """
+ Creates connection and initial database schema if no connection exists.
+ """
- # Alias JSON column expressions
- if alias:
- # Only apply aliases to non-standard columns or compound expressions
- if name not in sections + noprefix or compound:
- return f' as "{name}"'
+ if not self.connection:
+ # Create temporary database. Thread locking must be handled externally.
+ self.connection = sqlite3.connect("", check_same_thread=False)
+ self.cursor = self.connection.cursor()
- # No alias
- return None
+ # Create initial schema and indices
+ self.cursor.execute(SQLite.CREATE_DOCUMENTS)
+ self.cursor.execute(SQLite.CREATE_SECTIONS)
+ self.cursor.execute(SQLite.CREATE_SECTIONS_INDEX)
- # Standard columns - need prefixes
- if name.lower() in sections:
- return f"s.{name}"
+ def copy(self, path):
+ """
+ Copies the current database into path. This method will use the backup API if the current connection has no uncommitted changes.
+ Otherwise, iterdump is used, as the backup call will hang for an uncommitted connection.
- # Standard columns - no prefixes
- if name.lower() in noprefix:
- return name
+ Args:
+ path: path to write database
- # Other columns come from documents.data JSON
- return f'json_extract(data, "$.{name}")'
+ Returns:
+ new connection with data copied over
+ """
- def embed(self, similarity, batch):
- # Load similarity results id batch
- self.batch(indexids=[i for i, _ in similarity[batch]], batch=batch)
+ # Delete existing file, if necessary
+ if os.path.exists(path):
+ os.remove(path)
- # Average and load all similarity scores with first batch
- if not batch:
- self.scores(similarity)
+ # Create database. Thread locking must be handled externally.
+ connection = sqlite3.connect(path, check_same_thread=False)
- # Return ids clause placeholder
- return SQLite.IDS_CLAUSE % batch
+ if self.connection.in_transaction:
+ # The backup call will hang if there are uncommitted changes, need to copy over
+ # with iterdump (which is much slower)
+ for sql in self.connection.iterdump():
+ connection.execute(sql)
+ else:
+ # Database is up to date, can do a more efficient copy with SQLite C API
+ self.connection.backup(connection)
+
+ return connection
def defaults(self):
"""
@@ -255,21 +303,6 @@ class SQLite(Database):
return "s.id, text, score"
- def initialize(self):
- """
- Creates connection and initial database schema if no connection exists.
- """
-
- if not self.connection:
- # Create temporary database. Thread locking must be handled externally.
- self.connection = sqlite3.connect("", check_same_thread=False)
- self.cursor = self.connection.cursor()
-
- # Create initial schema and indices
- self.cursor.execute(SQLite.CREATE_DOCUMENTS)
- self.cursor.execute(SQLite.CREATE_SECTIONS)
- self.cursor.execute(SQLite.CREATE_SECTIONS_INDEX)
-
def batch(self, indexids=None, ids=None, batch=None):
"""
Loads ids to a temporary batch table for efficient query processing.
diff --git a/src/python/txtai/embeddings/__init__.py b/src/python/txtai/embeddings/__init__.py
index d6fc1ff6..cf310c3d 100644
--- a/src/python/txtai/embeddings/__init__.py
+++ b/src/python/txtai/embeddings/__init__.py
@@ -2,6 +2,7 @@
Embeddings imports
"""
+from .archive import Archive
from .base import Embeddings
from .documents import Documents
from .reducer import Reducer
diff --git a/src/python/txtai/embeddings/archive.py b/src/python/txtai/embeddings/archive.py
new file mode 100644
index 00000000..99a82b13
--- /dev/null
+++ b/src/python/txtai/embeddings/archive.py
@@ -0,0 +1,114 @@
+"""
+Archive module
+"""
+
+import os
+import tarfile
+
+from tempfile import TemporaryDirectory
+from zipfile import ZipFile, ZIP_DEFLATED
+
+
+class Archive:
+ """
+ Methods to load and save archive files.
+ """
+
+ def __init__(self, directory=None):
+ """
+ Creates a new archive instance.
+
+ Args:
+ directory: directory to use as working directory, defaults to a temporary directory
+ """
+
+ self.directory = directory
+
+ def isarchive(self, path):
+ """
+ Checks if path is an archive file based on the extension.
+
+ Args:
+ path: path to check
+
+ Returns:
+ True if the path ends with an archive extension, False otherwise
+ """
+
+ return any(path.lower().endswith(extension) for extension in [".tar.bz2", ".tar.gz", ".tar.xz", ".zip"])
+
+ def path(self):
+ """
+ Gets the current working directory for this archive instance.
+
+ Returns:
+ archive working directory
+ """
+
+ # Default to a temporary directory. All files created in this directory will be deleted
+ # when this archive instance goes out of scope.
+ if not self.directory:
+ # pylint: disable=R1732
+ self.directory = TemporaryDirectory()
+
+ return self.directory.name
+
+ def load(self, path):
+ """
+ Extracts file at path to archive working directory.
+
+ Args:
+ path: path to archive file
+ """
+
+ # Get compression type
+ compression = self.compression(path)
+
+ # Zip files
+ if compression == "zip":
+ with ZipFile(path, "r") as zfile:
+ zfile.extractall(self.path())
+
+ # Tar files
+ else:
+ with tarfile.open(path, f"r:{compression}") as tar:
+ tar.extractall(self.path())
+
+ def save(self, path):
+ """
+ Archives files in archive working directory to file at path.
+
+ Args:
+ path: path to archive file
+ """
+
+ # Get compression type
+ compression = self.compression(path)
+
+ # Create output directory, if necessary
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+
+ # Zip files
+ if compression == "zip":
+ with ZipFile(path, "w", ZIP_DEFLATED) as zfile:
+ for root, _, files in sorted(os.walk(self.path())):
+ for f in files:
+ zfile.write(os.path.join(root, f), arcname=f)
+
+ # Tar files
+ else:
+ with tarfile.open(path, f"w:{compression}") as tar:
+ tar.add(self.path(), arcname=".")
+
+ def compression(self, path):
+ """
+ Gets compression type for path.
+
+ Args:
+ path: path to archive file
+
+ Returns:
+ compression type
+ """
+
+ return path.lower().split(".")[-1]
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 5950f494..7c44eabb 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -13,6 +13,7 @@ from ..database import DatabaseFactory
from ..scoring import ScoringFactory
from ..vectors import VectorsFactory
+from .archive import Archive
from .reducer import Reducer
from .search import Search
@@ -27,7 +28,7 @@ class Embeddings:
# pylint: disable = W0231
def __init__(self, config=None):
"""
- Creates a new Embeddings model. Embeddings instances are thread-safe for read operations but writes must be
+ Creates a new embeddings index. Embeddings indexes are thread-safe for read operations but writes must be
synchronized.
Args:
@@ -55,6 +56,9 @@ class Embeddings:
# Document database
self.database = None
+ # Archiver
+ self.archive = None
+
def score(self, documents):
"""
Builds a scoring index.
@@ -309,9 +313,14 @@ class Embeddings:
Loads an existing index from path.
Args:
- path: input directory path
+ path: input path
"""
+ # Check if this is an archive file and extract
+ path, apath = self.checkarchive(path)
+ if apath:
+ self.archive.load(apath)
+
# Index configuration
with open(f"{path}/config", "rb") as handle:
self.config = pickle.load(handle)
@@ -347,7 +356,7 @@ class Embeddings:
Checks if an index exists at path.
Args:
- path: input directory path
+ path: input path
Returns:
True if index exists, False otherwise
@@ -357,13 +366,16 @@ class Embeddings:
def save(self, path):
"""
- Saves a model.
+ Saves an index.
Args:
- path: output directory path
+ path: output path
"""
if self.config:
+ # Check if this is an archive file
+ path, apath = self.checkarchive(path)
+
# Create output directory, if necessary
os.makedirs(path, exist_ok=True)
@@ -392,6 +404,31 @@ class Embeddings:
if self.database:
self.database.save(f"{path}/documents")
+ # If this is an archive, save it
+ if apath:
+ self.archive.save(apath)
+
+ 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 archiver 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
+
+ return path, None
+
def loadvectors(self):
"""
Loads a vector model set in config.
diff --git a/test/python/testdatabase/testembeddings.py b/test/python/testdatabase/testembeddings.py
index 06d8bc41..b3a27a30 100644
--- a/test/python/testdatabase/testembeddings.py
+++ b/test/python/testdatabase/testembeddings.py
@@ -33,6 +33,30 @@ class TestEmbeddings(unittest.TestCase):
# Create embeddings model, backed by sentence-transformers & transformers
cls.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": True})
+ def testArchive(self):
+ """
+ Tests embeddings index archiving
+ """
+
+ for extension in ["tar.bz2", "tar.gz", "tar.xz", "zip"]:
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{extension}")
+
+ self.embeddings.save(index)
+ self.embeddings.load(index)
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], self.data[4])
+
+ # Test offsets still work after save/load
+ self.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])
+ self.assertEqual(self.embeddings.count(), len(self.data))
+
def testData(self):
"""
Test content storage and retrieval
@@ -90,6 +114,40 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(result["text"], self.data[4])
+ def testMultiSave(self):
+ """
+ Tests multiple successive saves
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ # Generate temp file path
+ index = os.path.join(tempfile.gettempdir(), "embeddings")
+ self.embeddings.save(index)
+
+ # Modify index
+ self.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])
+
+ # Save to a different location
+ indexupdate = os.path.join(tempfile.gettempdir(), "embeddings-update")
+ self.embeddings.save(indexupdate)
+
+ # Save to same location
+ self.embeddings.save(index)
+
+ # Test all indexes match
+ result = self.embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
+
+ self.embeddings.load(index)
+ result = self.embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
+
+ self.embeddings.load(indexupdate)
+ result = self.embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
+
def testNotImplemented(self):
"""
Tests exceptions for non-implemented methods
@@ -126,7 +184,7 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(result["text"], self.data[4])
# Test offsets still work after save/load
- self.embeddings.upsert([(0, "Test insert", None)])
+ self.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])
self.assertEqual(self.embeddings.count(), len(self.data))
def testSQL(self):
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index 8c94ce65..0982425b 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -83,7 +83,7 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(uid, 4)
# Test offsets still work after save/load
- self.embeddings.upsert([(0, "Test insert", None)])
+ self.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])
self.assertEqual(self.embeddings.count(), len(self.data))
def testSimilarity(self):