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 workflow scheduling, closes #206

davidmezzetti0162b5974ce7
diff --git a/setup.py b/setup.py
index 6ef316ae..bb7ce421 100644
--- a/setup.py
+++ b/setup.py
@@ -48,7 +48,7 @@ extras["similarity"] = [
"sentence-transformers>=2.1.0",
]
-extras["workflow"] = ["apache-libcloud>=3.3.1", "pillow>=7.2.0", "requests>=2.26.0", "xmltodict>=0.12.0"]
+extras["workflow"] = ["apache-libcloud>=3.3.1", "croniter>=1.2.0", "pillow>=7.2.0", "requests>=2.26.0", "xmltodict>=0.12.0"]
extras["all"] = extras["api"] + extras["database"] + extras["model"] + extras["pipeline"] + extras["similarity"] + extras["workflow"]
diff --git a/src/python/txtai/__init__.py b/src/python/txtai/__init__.py
index 4f0d67cc..b55a9cec 100644
--- a/src/python/txtai/__init__.py
+++ b/src/python/txtai/__init__.py
@@ -2,4 +2,10 @@
Version string
"""
+import logging
+
+# Set default logging format
+logging.basicConfig(format="%(asctime)s [%(levelname)s] %(funcName)s: %(message)s")
+
+# Current version tag
__version__ = "4.1.0"
diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.py
index 5b2a9e7b..0bd02371 100644
--- a/src/python/txtai/api/base.py
+++ b/src/python/txtai/api/base.py
@@ -4,6 +4,7 @@ API module
import os
+from multiprocessing.pool import ThreadPool
from threading import Lock
import yaml
@@ -14,6 +15,7 @@ from ..embeddings import Documents, Embeddings
from ..pipeline import PipelineFactory
from ..workflow import WorkflowFactory
+
# pylint: disable=R0904
class API:
"""
@@ -59,6 +61,9 @@ class API:
# Write lock - allows only a single thread to update embeddings
self.lock = Lock()
+ # ThreadPool - runs scheduled workflows
+ self.pool = ThreadPool()
+
# Local embeddings index
if self.config.get("path") and Embeddings().exists(self.config["path"]):
# Load existing index if available
@@ -78,6 +83,14 @@ class API:
# Create workflows
self.flows()
+ def __del__(self):
+ """
+ Close threadpool when this object is garbage collected.
+ """
+
+ if self.pool:
+ self.pool.close()
+
def pipes(self):
"""
Initialize pipelines.
@@ -118,11 +131,22 @@ class API:
# Create workflows
if "workflow" in self.config:
for workflow, config in self.config["workflow"].items():
+ # Create copy of config
+ config = config.copy()
+
# Resolve callable functions
for task in config["tasks"]:
self.resolve(task)
- self.workflows[workflow] = WorkflowFactory.create(config)
+ # Get scheduler config
+ schedule = config.pop("schedule", None)
+
+ # Create workflow
+ self.workflows[workflow] = WorkflowFactory.create(workflow, config)
+
+ # Schedule job if necessary
+ if schedule:
+ self.pool.apply_async(self.workflows[workflow].schedule, kwds=schedule)
def resolve(self, task):
"""
@@ -519,3 +543,13 @@ class API:
# Execute workflow
return self.workflows[name](elements)
+
+ def wait(self):
+ """
+ Closes threadpool and waits for completion.
+ """
+
+ if self.pool:
+ self.pool.close()
+ self.pool.join()
+ self.pool = None
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
index be730875..b8d4dd60 100644
--- a/src/python/txtai/database/base.py
+++ b/src/python/txtai/database/base.py
@@ -9,7 +9,6 @@ from .sql import SQL, SQLException, Token
# Logging configuration
logger = logging.getLogger(__name__)
-logging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(message)s")
class Database:
diff --git a/src/python/txtai/pipeline/data/tabular.py b/src/python/txtai/pipeline/data/tabular.py
index 1b0cffbd..fe77eaa1 100644
--- a/src/python/txtai/pipeline/data/tabular.py
+++ b/src/python/txtai/pipeline/data/tabular.py
@@ -104,6 +104,7 @@ class Tabular(Pipeline):
# Transform into (id, text, tag) tuples
for index, row in df.iterrows():
uid = row[self.idcolumn] if self.idcolumn else index
+ uid = uid if uid is not None else index
text = ". ".join([str(row[column]) for column in columns])
rows.append((uid, text, None))
diff --git a/src/python/txtai/workflow/base.py b/src/python/txtai/workflow/base.py
index f8bc5c79..86a5691a 100644
--- a/src/python/txtai/workflow/base.py
+++ b/src/python/txtai/workflow/base.py
@@ -2,15 +2,32 @@
Workflow module
"""
+import logging
+import time
+
+from datetime import datetime
+
+# Conditional import
+try:
+ from croniter import croniter
+
+ CRONITER = True
+except ImportError:
+ CRONITER = False
+
from .execute import Execute
+# Logging configuration
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.INFO)
+
class Workflow:
"""
Base class for all workflows.
"""
- def __init__(self, tasks, batch=100, workers=None):
+ def __init__(self, tasks, batch=100, workers=None, name=None):
"""
Creates a new workflow. Workflows are lists of tasks to execute.
@@ -18,11 +35,13 @@ class Workflow:
tasks: list of workflow tasks
batch: how many items to process at a time, defaults to 100
workers: number of concurrent workers
+ name: workflow name
"""
self.tasks = tasks
self.batch = batch
self.workers = workers
+ self.name = name
# Set default number of executor workers to max number of actions in a task
self.workers = max(len(task.action) for task in self.tasks) if not self.workers else self.workers
@@ -50,6 +69,39 @@ class Workflow:
# Run task finalizers
self.finalize()
+ def schedule(self, cron, elements, iterations=None):
+ """
+ Schedules a workflow using a cron expression and elements.
+
+ Args:
+ cron: cron expression
+ elements: iterable data elements passed to workflow each call
+ iterations: number of times to run workflow, defaults to run indefinitely
+ """
+
+ # Check that croniter is installed
+ if not CRONITER:
+ raise ImportError('Workflow scheduling is not available - install "workflow" extra to enable')
+
+ logger.info("'%s' scheduler started with schedule %s", self.name, cron)
+
+ maxiterations = iterations
+ while iterations is None or iterations > 0:
+ # Schedule using localtime
+ schedule = croniter(cron, datetime.now().astimezone()).get_next(datetime)
+ logger.info("'%s' next run scheduled for %s", self.name, schedule.isoformat())
+ time.sleep(schedule.timestamp() - time.time())
+
+ # Run workflow
+ for _ in self(elements):
+ pass
+
+ # Decrement iterations remaining, if necessary
+ if iterations is not None:
+ iterations -= 1
+
+ logger.info("'%s' max iterations (%d) reached", self.name, maxiterations)
+
def initialize(self):
"""
Runs task initializer methods (if any) before processing data.
diff --git a/src/python/txtai/workflow/factory.py b/src/python/txtai/workflow/factory.py
index 2713415b..3ee776d1 100644
--- a/src/python/txtai/workflow/factory.py
+++ b/src/python/txtai/workflow/factory.py
@@ -12,11 +12,12 @@ class WorkflowFactory:
"""
@staticmethod
- def create(config):
+ def create(name, config):
"""
Creates a new Workflow instance.
Args:
+ name: Workflow name
config: Workflow configuration
Returns:
@@ -32,4 +33,4 @@ class WorkflowFactory:
config["tasks"] = tasks
# Create workflow
- return Workflow(**config)
+ return Workflow(name=name, **config)
diff --git a/test/python/testapi/testworkflow.py b/test/python/testapi/testworkflow.py
index b2dfdf8d..ae9104c1 100644
--- a/test/python/testapi/testworkflow.py
+++ b/test/python/testapi/testworkflow.py
@@ -49,6 +49,14 @@ workflow:
args:
- [[positive, negative], false, True]
- null
+ schedule:
+ schedule:
+ cron: '* * * * * *'
+ elements:
+ - This is a test sentence. And another sentence to split.
+ iterations: 1
+ tasks:
+ - action: segmentation
segment:
tasks:
- action: segmentation
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index 76df4a39..d47abe8c 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -23,6 +23,7 @@ class TestOptional(unittest.TestCase):
modules = [
"annoy",
+ "croniter",
"fastapi",
"fasttext",
"hnswlib",
@@ -159,7 +160,7 @@ class TestOptional(unittest.TestCase):
Test missing workflow dependencies
"""
- from txtai.workflow import ImageTask, ServiceTask, StorageTask
+ from txtai.workflow import ImageTask, ServiceTask, StorageTask, Workflow
with self.assertRaises(ImportError):
ImageTask()
@@ -169,3 +170,6 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
StorageTask()
+
+ with self.assertRaises(ImportError):
+ Workflow([], workers=1).schedule(None, [])
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index 5fa1eaa9..14971acd 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -237,6 +237,35 @@ class TestWorkflow(unittest.TestCase):
results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))
self.assertTrue(results[0].endswith("books.jpg"))
+ def testScheduleWorkflow(self):
+ """
+ Tests workflow schedules
+ """
+
+ # Test workflow schedule with Python
+ workflow = Workflow([Task()])
+ workflow.schedule("* * * * * *", ["test"], 1)
+ self.assertEqual(len(workflow.tasks), 1)
+
+ # Test workflow schedule with YAML
+ workflow = """
+ segmentation:
+ sentences: true
+ workflow:
+ segment:
+ schedule:
+ cron: '* * * * * *'
+ elements:
+ - test
+ iterations: 1
+ tasks:
+ - action: segmentation
+ """
+
+ app = API(workflow)
+ app.wait()
+ self.assertIsNone(app.pool)
+
def testStorageWorkflow(self):
"""
Tests a storage task