💡 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
Enhance markdown support for Textractor, closes #758
davidmezzetti923b12d449ad
diff --git a/src/python/txtai/pipeline/data/textractor.py b/src/python/txtai/pipeline/data/textractor.pyindex 6707c111..db92ddbf 100644--- a/src/python/txtai/pipeline/data/textractor.py+++ b/src/python/txtai/pipeline/data/textractor.py@@ -4,6 +4,7 @@ Textractor moduleimport contextlibimport os+import reimport tempfilefrom subprocess import Popen@@ -165,9 +166,9 @@ class Textractor(Segmentation):html"""- # Skip if file is already HTML+ # Skip parsing if input is plain text or HTMLmimetype = detector.from_file(path)- if mimetype in ("text/html", "text/xhtml"):+ if mimetype in ("text/plain", "text/html", "text/xhtml"):return self.retrieve(path)# Parse content to XHTML@@ -177,8 +178,8 @@ class Textractor(Segmentation):class Extract:"""- HTML to Text extractor. A limited set of Markdown is applied for organizing container elements such as tables and lists.- Visual formatting is not included (bold, italic, styling etc).+ HTML to Text extractor. Markdown formatting is applied for headings, blockquotes, lists, code, tables and text.+ Visual formatting is also included (bold, italic etc)."""def __init__(self, paragraphs, sections):@@ -195,13 +196,13 @@ class Extract:def __call__(self, html):"""- Transforms input HTML into formatted text.+ Transforms input HTML into Markdown formatted text.Args:html: input htmlReturns:- formatted text+ markdown formatted text"""# HTML Parser@@ -211,20 +212,22 @@ class Extract:for script in soup.find_all(["script", "style"]):script.decompose()- # Check if articles are embedded in this html- article = soup.find("article") is not None+ # Check for article sections+ article = next((x for x in ["article", "main"] if soup.find(x)), None)# Extract text from each section elementnodes = []- for node in soup.find_all("article" if article else "body"):- nodes.append(self.process(node, article))+ for node in soup.find_all(article if article else "body"):+ # Skip article sections without at least 1 paragraph+ if not article or node.find("p"):+ nodes.append(self.process(node, article))# Return extracted text, fallback to default text extraction if no nodes found- return "\n".join(self.metadata(soup) + nodes) if nodes else soup.get_text()+ return "\n".join(self.metadata(soup) + nodes) if nodes else self.default(soup)def process(self, node, article):"""- Extracts text from a node. This method applies transforms for containers, tables, lists and text.+ Extracts text from a node. This method applies transforms for headings, blockquotes, lists, code, tables and text.Page breaks are detected and reflected in the output text as a page break character.Args:@@ -235,15 +238,25 @@ class Extract:node text"""- if node.name == "table":- return self.table(node, article)+ if self.isheader(node):+ return self.header(node, article)- if node.name == "pre":+ if node.name in ("blockquote", "q"):return self.block(node)if node.name in ("ul", "ol"):return self.items(node, article)+ if node.name in ("code", "pre"):+ return self.code(node)++ if node.name == "table":+ return self.table(node, article)++ # Nodes to skip+ if node.name in ("aside",) + (() if article else ("header", "footer")):+ return ""+# Get page break symbol, if availablepage = node.name and node.get("class") and "page" in node.get("class")@@ -273,11 +286,11 @@ class Extract:"""title = node.find("title")- metadata = [title.text] if title else []+ metadata = [f"**{title.text.strip()}**"] if title and title.text else []description = node.find("meta", attrs={"name": "description"})if description and description["content"]:- metadata.append(f"\n{description['content']}")+ metadata.append(f"\n*{description['content'].strip()}*")# Add separatorif metadata:@@ -285,6 +298,24 @@ class Extract:return metadata+ def default(self, soup):+ """+ Default text handler when valid HTML isn't detected.++ Args:+ soup: BeautifulSoup object++ Returns:+ text+ """++ lines = []+ for line in soup.get_text().split("\n"):+ # Detect markdown headings and add page breaks+ lines.append(f"\f{line}" if self.sections and re.search(r"^#+ ", line) else line)++ return "\n".join(lines)+def text(self, node, article):"""Text handler. This method flattens a node and it's children to text.@@ -301,8 +332,23 @@ class Extract:items = self.children(node)items = items if items else [node]+ # Apply emphasis and link formatting+ texts = []+ for x in items:+ target, text = x if x.name else node, x.text++ if text.strip():+ if target.name in ("b", "strong"):+ text = f"**{text.strip()}** "+ elif target.name in ("i", "em"):+ text = f"*{text.strip()}* "+ elif target.name == "a":+ text = f"[{text.strip()}]({target.get('href')}) "++ texts.append(text)+# Join text elements- text = "".join(x.text for x in items)+ text = "".join(texts)# Article text processingtext = self.articletext(node, text) if article else text@@ -312,41 +358,32 @@ class Extract:return text- def table(self, node, article):+ def header(self, node, article):"""- Table handler. This method transforms a HTML table into a Markdown formatted table.+ Header handler. This method transforms a HTML heading into a Markdown formatted heading.Args:node: input nodearticle: True if the main section node is an articleReturns:- table as markdown+ heading as markdown"""- elements, header = [], False+ # Get heading level and text+ level = "#" * int(node.name[1])+ text = self.text(node, article)- # Process all rows- rows = node.find_all("tr")- for row in rows:- # Get list of columns for row- columns = row.find_all(lambda tag: tag.name in ("th", "td"))+ # Add section break or newline, if necessary+ level = f"\f{level}" if self.sections else f"\n{level}"- # Add columns with separator- elements.append(f"|{'|'.join(self.process(column, article) for column in columns)}|")-- # If there are multiple rows, add header format row- if not header and len(rows) > 1:- elements.append(f"{'|---' * len(columns)}|")- header = True-- # Join elements together as string- return "\n".join(elements)+ # Return formatted header. Remove leading whitespace as it was added before level in step above.+ return f"{level} {text.lstrip()}" if text.strip() else ""def block(self, node):"""- Pre-formatted block handler. This method transforms a HTML pre block into a Markdown formatted- code block.+ Blockquote handler. This method transforms a HTML blockquote or q block into a Markdown formatted+ blockquoteArgs:node: input node@@ -355,7 +392,7 @@ class Extract:block as markdown"""- text = f"```\n{node.text}\n```"+ text = "\n".join(f"> {x}" for x in node.text.strip().split("\n"))return f"{text}\n\n" if self.paragraphs else f"{text}\n"def items(self, node, article):@@ -380,7 +417,53 @@ class Extract:# Add list elementif text:- elements.append(f" {prefix} {text}")+ elements.append(f"{prefix} {text}")++ # Join elements together as string+ return "\n".join(elements)++ def code(self, node):+ """+ Code block handler. This method transforms a HTML pre or code block into a Markdown formatted+ code block.++ Args:+ node: input node++ Returns:+ code as markdown+ """++ text = f"```\n{node.text.strip()}\n```"+ return f"{text}\n\n" if self.paragraphs else f"{text}\n"++ def table(self, node, article):+ """+ Table handler. This method transforms a HTML table into a Markdown formatted table.++ Args:+ node: input node+ article: True if the main section node is an article++ Returns:+ table as markdown+ """++ elements, header = [], False++ # Process all rows+ rows = node.find_all("tr")+ for row in rows:+ # Get list of columns for row+ columns = row.find_all(lambda tag: tag.name in ("th", "td"))++ # Add columns with separator+ elements.append(f"|{'|'.join(self.process(column, article) for column in columns)}|")++ # If there are multiple rows, add header format row+ if not header and len(rows) > 1:+ elements.append(f"{'|---' * len(columns)}|")+ header = True# Join elements together as stringreturn "\n".join(elements)@@ -388,7 +471,7 @@ class Extract:def iscontainer(self, node, children):"""Analyzes a node and it's children to determine if this is a container element. A container- element is defined as being a div, body or not having any string elements as children.+ element is defined as being a div, body, article or not having any string elements as children.Args:node: input node@@ -430,8 +513,11 @@ class Extract:article text"""+ # List of valid text nodes+ valid = ["p", "th", "td", "li", "a", "b", "strong", "i", "em"]+# Check if text is valid article text- text = text if (node.name in ["p", "th", "td", "li", "a"] or self.isheader(node)) and not self.islink(node) else ""+ text = text if (node.name in valid or self.isheader(node)) and not self.islink(node) else ""if text:# Replace non-breaking space plus newline with double newlinetext = text.replace("\xa0\n", "\n\n")@@ -440,10 +526,6 @@ class Extract:if node.name == "p":text = f"{text.strip()}\n\n" if self.paragraphs else f"{text.strip()}\n"- # Format header whitespace- if self.sections and self.isheader(node):- text = f"\f{text.strip()}\n"-return textdef isheader(self, node):diff --git a/test/python/testapi/testpipelines.py b/test/python/testapi/testpipelines.pyindex 98bee028..5025e248 100644--- a/test/python/testapi/testpipelines.py+++ b/test/python/testapi/testpipelines.py@@ -305,7 +305,7 @@ class TestPipelines(unittest.TestCase):text = self.client.get(f"textract?file={Utils.PATH}/article.pdf").json()# Check length of text is as expected- self.assertEqual(len(text), 2333)+ self.assertEqual(len(text), 2471)def testTextractorBatch(self):"""@@ -315,7 +315,7 @@ class TestPipelines(unittest.TestCase):path = Utils.PATH + "/article.pdf"texts = self.client.post("batchtextract", json=[path, path]).json()- self.assertEqual((len(texts[0]), len(texts[1])), (2333, 2333))+ self.assertEqual((len(texts[0]), len(texts[1])), (2471, 2471))def testTranscribe(self):"""diff --git a/test/python/testpipeline/testtextractor.py b/test/python/testpipeline/testtextractor.pyindex 5a0336ad..7280cf74 100644--- a/test/python/testpipeline/testtextractor.py+++ b/test/python/testpipeline/testtextractor.py@@ -15,15 +15,6 @@ class TestTextractor(unittest.TestCase):Textractor tests."""- def testBeautifulSoup(self):- """- Test text extraction using Beautiful Soup- """-- textractor = Textractor(tika=False)- text = textractor(Utils.PATH + "/tabular.csv")- self.assertEqual(len(text), 125)-def testCheckJava(self):"""Test the checkjava method@@ -32,16 +23,22 @@ class TestTextractor(unittest.TestCase):textractor = Textractor()self.assertFalse(textractor.checkjava("1112444abc"))- def testHTML(self):+ def testDefault(self):"""- Tests input as HTML strings+ Test default text extraction"""- textractor = Textractor()+ # Text input+ textractor = Textractor(tika=False)+ text = textractor(Utils.PATH + "/tabular.csv")+ self.assertEqual(len(text), 125)++ # Markdown input+ textractor = Textractor(sections=True)+ sections = textractor("# Heading 1\nText1\n\n# Heading 2\nText2\n")- # Extract from HTML string- text = textractor("<html><body><p>This is a test</p></body></html>")- self.assertEqual(text, "This is a test")+ # Check number of sections is as expected+ self.assertEqual(len(sections), 2)def testLines(self):"""@@ -56,6 +53,47 @@ class TestTextractor(unittest.TestCase):# Check number of lines is as expectedself.assertEqual(len(lines), 35)+ def testHTML(self):+ """+ Test HTML to Markdown+ """++ # Headings+ self.assertMarkdown("<h1>This is a test</h1>", "# This is a test")+ self.assertMarkdown("<h6>This is a test</h6>", "###### This is a test")++ # Blockquotes+ self.assertMarkdown("<blockquote>This is a test</blockquote>", "> This is a test")++ # Lists+ self.assertMarkdown("<ul><li>Test1</li><li>Test2</li></ul>", "- Test1\n- Test2")+ self.assertMarkdown("<ol><li>Test1</li><li>Test2</li></ol>", "1. Test1\n2. Test2")++ # Code+ self.assertMarkdown("<code>This is a test</code>", "```\nThis is a test\n```")+ self.assertMarkdown("<pre>This is a test</pre>", "```\nThis is a test\n```")++ # Tables+ self.assertMarkdown(+ "<table><tr><th>Header1</th><th>Header2</th></tr><tr><td>Test1</td><td>Test2</td></tr></table>",+ "|Header1|Header2|\n|---|---|\n|Test1|Test2|",+ )++ # Ignore list+ self.assertMarkdown("<aside>This is a test</aside>", "")++ # Text formatting+ self.assertMarkdown("<p>This is a test</p>", "This is a test")+ self.assertMarkdown("<p>This is a <b>test</b</p>", "This is a **test**")+ self.assertMarkdown("<p>This is a <strong>test</strong></p>", "This is a **test**")+ self.assertMarkdown("<p>This is a <i>test</i></p>", "This is a *test*")+ self.assertMarkdown("<p>This is a <em>test</em></p>", "This is a *test*")+ self.assertMarkdown("<p>This is a <a href='link'>test</a>", "This is a [test](link)")++ # Collapse to outer tag+ self.assertMarkdown("<p>This is a <strong><em>test</em></strong></p>", "This is a **test**")+ self.assertMarkdown("<p>This is a <em><strong>test</strong></em></p>", "This is a *test*")+def testParagraphs(self):"""Test extraction to paragraphs@@ -77,10 +115,10 @@ class TestTextractor(unittest.TestCase):textractor = Textractor(sections=True)# Extract as sections- paragraphs = textractor(Utils.PATH + "/document.pdf")+ sections = textractor(Utils.PATH + "/document.pdf")# Check number of sections is as expected- self.assertEqual(len(paragraphs), 3)+ self.assertEqual(len(sections), 3)def testSentences(self):"""@@ -106,7 +144,7 @@ class TestTextractor(unittest.TestCase):text = textractor(Utils.PATH + "/article.pdf")# Check length of text is as expected- self.assertEqual(len(text), 2333)+ self.assertEqual(len(text), 2471)def testTable(self):"""@@ -127,6 +165,18 @@ class TestTextractor(unittest.TestCase):Test parsing a remote URL"""- textractor = Textractor(sections=True, join=True)+ textractor = Textractor()text = textractor("https://github.com/neuml/txtai")self.assertTrue("txtai is an all-in-one embeddings database" in text)++ def assertMarkdown(self, html, expected):+ """+ Helper method to assert generated markdown is as expected.++ Args:+ html: input html snippet+ expected: expected markdown text+ """++ textractor = Textractor()+ self.assertEqual(textractor(f"<html><body>{html}</body></html>"), expected)