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 text extraction with LiteParse, closes #1118

davidmezzettiae898e69055d
diff --git a/docs/pipeline/data/filetohtml.md b/docs/pipeline/data/filetohtml.md
index 61a4a6ed..600389b6 100644
--- a/docs/pipeline/data/filetohtml.md
+++ b/docs/pipeline/data/filetohtml.md
@@ -17,6 +17,12 @@ Apache Tika requires [Java](https://en.wikipedia.org/wiki/Java_(programming_lang
See [this link](https://github.com/DS4SD/docling?tab=readme-ov-file#features) for a list of supported document formats.
+## LiteParse
+
+[LiteParse](https://github.com/run-llama/liteparse) is a fast, helpful, and open-source document parser. It supports PDF out of the box with additional format support via third-party packages.
+
+See [this link](https://github.com/run-llama/liteparse#multi-format-input-support) for more.
+
## Example
The following shows a simple example using this pipeline.
diff --git a/src/python/txtai/pipeline/data/filetohtml.py b/src/python/txtai/pipeline/data/filetohtml.py
index c50ed58f..a875115d 100644
--- a/src/python/txtai/pipeline/data/filetohtml.py
+++ b/src/python/txtai/pipeline/data/filetohtml.py
@@ -23,6 +23,14 @@ try:
except ImportError:
DOCLING = False
+# Conditional import
+try:
+ import liteparse
+
+ LITEPARSE = True
+except ImportError:
+ LITEPARSE = False
+
from ..base import Pipeline
@@ -36,7 +44,8 @@ class FileToHTML(Pipeline):
Creates a new File to HTML pipeline.
Args:
- backend: backend to use to extract content, supports "tika", "docling" or "available" (default) which finds the first available
+ backend: backend to use to extract content, supports "tika", "docling", "liteparse" or
+ "available" (default) which finds the first available
"""
# Lowercase backend parameter
@@ -44,10 +53,10 @@ class FileToHTML(Pipeline):
# Check for available backend
if backend == "available":
- backend = "tika" if Tika.available() else "docling" if Docling.available() else None
+ backend = "tika" if Tika.available() else "docling" if Docling.available() else "liteparse" if LiteParse.available() else None
# Create backend instance
- self.backend = Tika() if backend == "tika" else Docling() if backend == "docling" else None
+ self.backend = Tika() if backend == "tika" else Docling() if backend == "docling" else LiteParse() if backend == "liteparse" else None
def __call__(self, path):
"""
@@ -63,7 +72,32 @@ class FileToHTML(Pipeline):
return self.backend(path) if self.backend else None
-class Tika:
+class Backend:
+ """
+ Base File to HTML conversion backend.
+ """
+
+ def ishtml(self, path):
+ """
+ Detects if this file looks like HTML.
+
+ Args:
+ path: file path
+
+ Returns:
+ True if this is HTML
+ """
+
+ with open(path, "rb") as f:
+ # Read first 1024 bytes, ignore encoding errors and strip leading/trailing whitespace
+ content = f.read(1024)
+ content = content.decode("ascii", errors="ignore").lower().strip()
+
+ # Check for HTML
+ return re.search(r"<!doctype\s+html|<html|<head|<body", content)
+
+
+class Tika(Backend):
"""
File to HTML conversion via Apache Tika.
"""
@@ -119,7 +153,7 @@ class Tika:
return parsed["content"]
-class Docling:
+class Docling(Backend):
"""
File to HTML conversion via Docling.
"""
@@ -166,25 +200,6 @@ class Docling:
# Normalize HTML and return
return self.normalize(html)
- def ishtml(self, path):
- """
- Detects if this file looks like HTML.
-
- Args:
- path: file path
-
- Returns:
- True if this is HTML
- """
-
- with open(path, "rb") as f:
- # Read first 1024 bytes, ignore encoding errors and strip leading/trailing whitespace
- content = f.read(1024)
- content = content.decode("ascii", errors="ignore").lower().strip()
-
- # Check for HTML
- return re.search(r"<!doctype\s+html|<html|<head|<body", content)
-
def normalize(self, html):
"""
Applies normalization rules to make HTML consistent with other text extraction backends.
@@ -204,3 +219,56 @@ class Docling:
# Add spacing between paragraphs
return html.replace("</p>", "</p><p/>")
+
+
+class LiteParse(Backend):
+ """
+ File to HTML conversion via LiteParse.
+ """
+
+ @staticmethod
+ def available():
+ """
+ Checks if LiteParse is available.
+
+ Returns:
+ True if LiteParse is available, False otherwise
+ """
+
+ return LITEPARSE
+
+ def __init__(self):
+ """
+ Creates a new LiteParse instance.
+ """
+
+ if not LiteParse.available():
+ raise ImportError('LiteParse is not available - install "pipeline" extra to enable')
+
+ self.liteparse = liteparse.LiteParse(output_format="markdown")
+
+ def __call__(self, path):
+ """
+ Parses content to HTML.
+
+ Args:
+ path: file path
+
+ Returns:
+ html
+ """
+
+ # Skip parsing if input is HTML
+ if self.ishtml(path):
+ return None
+
+ # Output text
+ output = ["<html><body>"]
+
+ # Iterate over each parsed page
+ for page in self.liteparse.parse(path).text.split("\n\n-----\n\n"):
+ output.append(f"<div class='page'>{page}</div>")
+
+ output.append("</body></html>")
+
+ return "\n".join(output)
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index 892970a6..560d6f25 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -41,6 +41,7 @@ class TestOptional(unittest.TestCase):
"imagehash",
"libcloud.storage.providers",
"litellm",
+ "liteparse",
"litert_lm",
"llama_cpp",
"model2vec",
@@ -223,6 +224,7 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
OnnxModel(None)
+ # pylint: disable=R0915
def testPipeline(self):
"""
Test missing pipeline dependencies
@@ -268,6 +270,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
FileToHTML(backend="docling")
+ with self.assertRaises(ImportError):
+ FileToHTML(backend="liteparse")
+
with self.assertRaises(ImportError):
FileToHTML(backend="tika")
diff --git a/test/python/testpipeline/testdata/testtextractor.py b/test/python/testpipeline/testdata/testtextractor.py
index 5fbd81d8..1c2acf25 100644
--- a/test/python/testpipeline/testdata/testtextractor.py
+++ b/test/python/testpipeline/testdata/testtextractor.py
@@ -88,6 +88,17 @@ class TestTextractor(unittest.TestCase):
# Check number of lines is as expected
self.assertEqual(len(lines), 35)
+ def testLiteParse(self):
+ """
+ Test liteparse backend
+ """
+
+ textractor = Textractor(backend="liteparse")
+
+ # Extract text and check for Markdown formatting
+ text = textractor(Utils.PATH + "/article.pdf")
+ self.assertTrue("# Introducing txtai" in text)
+
def testHTML(self):
"""
Test HTML to Markdown
@@ -224,7 +235,7 @@ class TestTextractor(unittest.TestCase):
"""
# Test parsing URLs for each backend
- for backend in ["docling", "tika"]:
+ for backend in ["docling", "liteparse", "tika"]:
textractor = Textractor(backend=backend)
text = textractor("https://github.com/neuml/txtai")
self.assertTrue("txtai is an all-in-one AI framework" in text)