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 framework, closes #69

davidmezzetti3d9fa986679c
diff --git a/src/python/txtai/workflow/__init__.py b/src/python/txtai/workflow/__init__.py
new file mode 100644
index 00000000..fbdda280
--- /dev/null
+++ b/src/python/txtai/workflow/__init__.py
@@ -0,0 +1,6 @@
+"""
+Workflow imports
+"""
+
+from .base import Workflow
+from .task import *
diff --git a/src/python/txtai/workflow/base.py b/src/python/txtai/workflow/base.py
new file mode 100644
index 00000000..f4f5ec9c
--- /dev/null
+++ b/src/python/txtai/workflow/base.py
@@ -0,0 +1,124 @@
+"""
+Workflow module
+"""
+
+
+class Workflow:
+ """
+ Base class for all workflows.
+ """
+
+ def __init__(self, tasks, batch=100):
+ """
+ Creates a new workflow. Workflows are lists of tasks to execute.
+
+ Args:
+ tasks: list of workflow tasks
+ batch: how many items to process at a time, defaults to 100
+ """
+
+ self.tasks = tasks
+ self.batch = batch
+
+ def __call__(self, elements):
+ """
+ Executes a workflow for input elements.
+
+ Args:
+ elements: list of data elements
+
+ Returns:
+ transformed data elements
+ """
+
+ batch = []
+ for x in elements:
+ batch.append(x)
+
+ if len(batch) == self.batch:
+ yield from self.process(batch)
+
+ if batch:
+ yield from self.process(batch)
+
+ def process(self, elements):
+ """
+ Processes a batch of data elements.
+
+ Args:
+ elements: list of data elements
+
+ Returns:
+ transformed data elements
+ """
+
+ for task in self.tasks:
+ # Build list of elements with unique process ids
+ indexed = list(enumerate(elements))
+
+ # Filter data down to data this task handles
+ data = [(x, self.unpack(element) if task.unpack else element) for x, element in indexed if task.accept(self.unpack(element))]
+
+ # Get list of filtered process ids
+ ids = [x for x, _ in data]
+
+ # Execute task action
+ results = task([element for _, element in data])
+
+ # Update with transformed elements. Handle one to many transformations.
+ elements = []
+ for x, element in indexed:
+ if x in ids:
+ # Get result for process id
+ result = results[ids.index(x)]
+
+ if isinstance(result, list):
+ # One-many transformations
+ elements.extend([self.pack(element, r) if task.unpack else r for r in result])
+ else:
+ # One-one transformations
+ elements.append(self.pack(element, result) if task.unpack else result)
+ else:
+ # Pass unprocessed elements through
+ elements.append(element)
+
+ # Remove process index and yield results
+ yield from elements
+
+ def unpack(self, element):
+ """
+ Unpacks data for processing.
+
+ Args:
+ element: input data element
+
+ Returns:
+ data
+ """
+
+ # Extract data from (id, data, tag) formatted elements
+ if isinstance(element, tuple):
+ return element[1]
+
+ return element
+
+ def pack(self, element, data):
+ """
+ Packs data for delivery to the next workflow task.
+
+ Args:
+ element: transformed data element
+ data: item to pack element into
+
+ Returns:
+ packed data
+ """
+
+ # Package data into (id, data, tag) formatted elements
+ if isinstance(element, tuple):
+ # Create a copy of tuple, update data element and return
+ element = list(element)
+ element[1] = data
+ return tuple(element)
+
+ return data
diff --git a/src/python/txtai/workflow/task/__init__.py b/src/python/txtai/workflow/task/__init__.py
new file mode 100644
index 00000000..ee3390d9
--- /dev/null
+++ b/src/python/txtai/workflow/task/__init__.py
@@ -0,0 +1,8 @@
+"""
+Task imports
+"""
+
+from .base import Task
+from .file import FileTask
+from .image import ImageTask
+from .workflow import WorkflowTask
diff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.py
new file mode 100644
index 00000000..db186e83
--- /dev/null
+++ b/src/python/txtai/workflow/task/base.py
@@ -0,0 +1,69 @@
+"""
+Task module
+"""
+
+import re
+
+
+class Task:
+ """
+ Base class for all workflow tasks.
+ """
+
+ def __init__(self, action, select=None, unpack=True):
+ """
+ Creates a new task. A task defines two methods, type of data it accepts and the action to execute
+ for each data element. Actions are callable functions.
+
+ Args:
+ action: action to execute on each data element
+ select: filter(s) used to select data to process
+ unpack: if data elements should be unpacked or unwrapped from (id, data, tag) tuples
+ """
+
+ self.action = action
+ self.select = select
+ self.unpack = unpack
+
+ def __call__(self, elements):
+ """
+ Executes action for a list of data elements.
+
+ Args:
+ elements: list of data elements
+
+ Returns:
+ transformed data elements
+ """
+
+ # Run data preparation routines
+ elements = [self.prepare(element) for element in elements]
+
+ # Run data elements through workflow action
+ return self.action(elements)
+
+ def accept(self, element):
+ """
+ Determines if this task can handle the input data format.
+
+ Args:
+ element: input data element
+
+ Returns:
+ True if this task can process this data element, False otherwise
+ """
+
+ return (isinstance(element, str) and re.search(self.select, element.lower())) if element and self.select else True
+
+ def prepare(self, element):
+ """
+ Method that allows downstream tasks to prepare data element for processing.
+
+ Args:
+ element: input data element
+
+ Returns:
+ data element ready for processing
+ """
+
+ return element
diff --git a/src/python/txtai/workflow/task/file.py b/src/python/txtai/workflow/task/file.py
new file mode 100644
index 00000000..421bf561
--- /dev/null
+++ b/src/python/txtai/workflow/task/file.py
@@ -0,0 +1,25 @@
+"""
+FileTask module
+"""
+
+import os
+import re
+
+from urllib.parse import urlparse
+
+from .base import Task
+
+
+class FileTask(Task):
+ """
+ Task that processes file urls
+ """
+
+ def accept(self, element):
+ # Only accept file URLs
+ return super().accept(element) and re.match(r"file:\/\/", element.lower())
+
+ def prepare(self, element):
+ # Transform file urls to local paths
+ url = urlparse(element)
+ return os.path.abspath(os.path.join(url.netloc, url.path))
diff --git a/src/python/txtai/workflow/task/image.py b/src/python/txtai/workflow/task/image.py
new file mode 100644
index 00000000..3c908eed
--- /dev/null
+++ b/src/python/txtai/workflow/task/image.py
@@ -0,0 +1,17 @@
+"""
+ImageTask module
+"""
+
+import re
+
+from .file import FileTask
+
+
+class ImageTask(FileTask):
+ """
+ Task that processes image file urls
+ """
+
+ def accept(self, element):
+ # Only accept file URLs
+ return super().accept(element) and re.search(r"\.(gif|bmp|jpg|jpeg|png|webp)$", element.lower())
diff --git a/src/python/txtai/workflow/task/workflow.py b/src/python/txtai/workflow/task/workflow.py
new file mode 100644
index 00000000..8dd63418
--- /dev/null
+++ b/src/python/txtai/workflow/task/workflow.py
@@ -0,0 +1,14 @@
+"""
+WorkflowTask module
+"""
+
+from .base import Task
+
+
+class WorkflowTask(Task):
+ """
+ Task that executes a separate Workflow
+ """
+
+ def __call__(self, elements):
+ return list(super().__call__(elements))