💡 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 tabular pipeline, closes #134
davidmezzetti809151c3cc0b
diff --git a/setup.py b/setup.pyindex ff29eb35..af62fd71 100644--- a/setup.py+++ b/setup.py@@ -27,6 +27,7 @@ extras["pipeline"] = ["onnx>=1.10.1","onnxmltools>=1.9.1","onnxruntime>=1.8.1",+ "pandas>=1.1.0","sentencepiece>=0.1.91","soundfile>=0.10.3.post1","tika>=1.24",@@ -41,7 +42,7 @@ extras["similarity"] = ["sentence-transformers>=2.0.0",]-extras["workflow"] = ["apache-libcloud>=3.3.1", "pillow>=7.2.0", "requests>=2.24.0"]+extras["workflow"] = ["apache-libcloud>=3.3.1", "pillow>=7.2.0", "requests>=2.24.0", "xmltodict>=0.12.0"]extras["all"] = extras["api"] + extras["model"] + extras["pipeline"] + extras["similarity"] + extras["workflow"]diff --git a/src/python/txtai/pipeline/__init__.py b/src/python/txtai/pipeline/__init__.pyindex b298fa7c..030dc78c 100644--- a/src/python/txtai/pipeline/__init__.py+++ b/src/python/txtai/pipeline/__init__.py@@ -15,6 +15,7 @@ from .questions import Questionsfrom .segmentation import Segmentationfrom .similarity import Similarityfrom .summary import Summary+from .tabular import Tabularfrom .tensors import Tensorsfrom .textractor import Textractorfrom .tokenizer import Tokenizerdiff --git a/src/python/txtai/pipeline/tabular.py b/src/python/txtai/pipeline/tabular.pynew file mode 100644index 00000000..2aeddb14--- /dev/null+++ b/src/python/txtai/pipeline/tabular.py@@ -0,0 +1,110 @@+"""+Tabular module+"""++import os++# Conditional import+try:+ import pandas as pd++ PANDAS = True+except ImportError:+ PANDAS = False++from .base import Pipeline+++class Tabular(Pipeline):+ """+ Splits tabular data into rows and columns.+ """++ def __init__(self, idcolumn=None, textcolumns=None):+ """+ Creates a new Tabular pipeline.++ Args:+ idcolumn: column name to use for row id+ textcolumns: list of columns to combine as a text field+ """++ if not PANDAS:+ raise ImportError('Tabular pipeline is not available - install "pipeline" extra to enable')++ self.idcolumn = idcolumn+ self.textcolumns = textcolumns++ def __call__(self, data):+ """+ Splits data into rows and columns.++ Args:+ data: input data++ Returns:+ list of (id, text, tag)+ """++ items = [data] if not isinstance(data, list) else data++ # Combine all rows into single return element+ results = []+ dicts = []++ for item in items:+ # File path+ if isinstance(item, str):+ _, extension = os.path.splitext(item)+ extension = extension.replace(".", "").lower()++ if extension in ["xlsx", "xls"]:+ df = pd.read_excel(item)+ else:+ df = pd.read_csv(item)++ results.append(self.process(df))++ # Dict+ if isinstance(item, dict):+ dicts.append(item)++ # List of dicts+ elif isinstance(item, list):+ df = pd.DataFrame(item)+ results.append(self.process(df))++ if dicts:+ df = pd.DataFrame(dicts)+ results.extend(self.process(df))++ return results[0] if not isinstance(data, list) else results++ def process(self, df):+ """+ Extracts a list of (id, text, tag) tuples from a dataframe.++ Args:+ df: DataFrame to extract content from++ Returns:+ list of (id, text, tag)+ """++ rows = []++ # Columns to use for text+ columns = self.textcolumns+ if not columns:+ columns = list(df.columns)+ if self.idcolumn:+ columns.remove(self.idcolumn)++ # Transform into (id, text, tag) tuples+ for index, row in df.iterrows():+ uid = row[self.idcolumn] if self.idcolumn else index+ text = ". ".join([str(row[column]) for column in columns])++ rows.append((uid, text, None))++ return rowsdiff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 1cde1fd2..ecf6d0cd 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -8,7 +8,7 @@ import txtai.ann.factoryfrom txtai.ann import ANNFactoryfrom txtai.models import OnnxModel-from txtai.pipeline import HFOnnx, MLOnnx, Segmentation, Textractor, Transcription, Translation+from txtai.pipeline import HFOnnx, MLOnnx, Segmentation, Tabular, Textractor, Transcription, Translationfrom txtai.vectors import VectorsFactoryfrom txtai.workflow.task.image import ImageTaskfrom txtai.workflow.task.storage import StorageTask@@ -33,6 +33,7 @@ class TestOptional(unittest.TestCase):txtai.pipeline.hfonnx.ONNX_RUNTIME = not txtai.pipeline.hfonnx.ONNX_RUNTIMEtxtai.pipeline.mlonnx.ONNX_MLTOOLS = not txtai.pipeline.mlonnx.ONNX_MLTOOLStxtai.pipeline.segmentation.NLTK = not txtai.pipeline.segmentation.NLTK+ txtai.pipeline.tabular.PANDAS = not txtai.pipeline.tabular.PANDAStxtai.pipeline.textractor.TIKA = not txtai.pipeline.textractor.TIKAtxtai.pipeline.transcription.SOUNDFILE = not txtai.pipeline.transcription.SOUNDFILEtxtai.pipeline.translation.FASTTEXT = not txtai.pipeline.translation.FASTTEXT@@ -94,6 +95,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):Segmentation()+ with self.assertRaises(ImportError):+ Tabular()+with self.assertRaises(ImportError):Textractor()diff --git a/test/python/testtabular.py b/test/python/testtabular.pynew file mode 100644index 00000000..f9536963--- /dev/null+++ b/test/python/testtabular.py@@ -0,0 +1,80 @@+"""+Tabular module tests+"""++import unittest++from txtai.pipeline import Tabular++# pylint: disable = C0411+from utils import Utils+++class TestTabular(unittest.TestCase):+ """+ Tabular tests+ """++ @classmethod+ def setUpClass(cls):+ """+ Create single tabular instance+ """++ cls.tabular = Tabular("id", ["text"])++ def testCSV(self):+ """+ Tests parsing a CSV file+ """++ rows = self.tabular([Utils.PATH + "/tabular.csv"])+ uid, text, _ = rows[0][0]++ self.assertEqual(uid, 0)+ self.assertEqual(text, "The first sentence")++ def testDict(self):+ """+ Tests parsing a dict+ """++ rows = self.tabular([{"id": 0, "text": "This is a test"}])+ uid, text, _ = rows[0]++ self.assertEqual(uid, 0)+ self.assertEqual(text, "This is a test")++ def testList(self):+ """+ Tests parsing a list+ """++ rows = self.tabular([[{"id": 0, "text": "This is a test"}]])+ uid, text, _ = rows[0][0]++ self.assertEqual(uid, 0)+ self.assertEqual(text, "This is a test")++ def testNoColumns(self):+ """+ Tests creating text without specifying columns+ """++ tabular = Tabular("id")+ rows = tabular([{"id": 0, "text": "This is a test", "summary": "Describes text in more detail"}])+ uid, text, _ = rows[0]++ self.assertEqual(uid, 0)+ self.assertEqual(text, "This is a test. Describes text in more detail")++ def testXLSX(self):+ """+ Tests parsing a XLSX file+ """++ rows = self.tabular([Utils.PATH + "/tabular.xlsx"])+ uid, text, _ = rows[0][0]++ self.assertEqual(uid, 0)+ self.assertEqual(text, "The first sentence")