xlsongc commented on code in PR #77478:
URL: https://github.com/apache/airflow/pull/77478#discussion_r4743453831


##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -56,6 +56,57 @@
 # cells count too. 1M characters is about 6000 rows of 10 columns; longer 
tables are skipped.
 _DOCX_TABLE_MAX_CHARS = 1_000_000
 
+# Unlike the table limits above, these end the whole document: the text read 
so far is kept and
+# the rest is left out with a warning. python-docx handles each paragraph, 
run, hyperlink, table,
+# row and cell in Python, at about 10 us each even when it holds no text, so 
each is counted as an
+# element before it is walked. The largest of about 2,300 real documents has 
87,000 elements.
+_DOCX_MAX_CHARS = 10_000_000
+_DOCX_MAX_ELEMENTS = 1_000_000
+
+
+class _DocxLimitReachedError(Exception):
+    """Stop reading a DOCX. Not a ValueError, which only skips the table being 
read."""
+
+
+class _DocxBudget:
+    """Count the characters and elements read from a DOCX against the document 
limits."""
+
+    def __init__(self) -> None:
+        from docx.oxml.ns import nsmap
+        from lxml import etree
+
+        self.chars = 0
+        self.elements = 0
+        # Paragraph.text runs an XPath query for each w:r and w:hyperlink 
child and each w:r in a
+        # hyperlink, so they are counted in C before it is read. The children 
of a run cost about
+        # 0.4 us each and are not counted. The counts are added rather than 
taken over a union,
+        # which libxml2 merges in quadratic time: 7M runs in hyperlinks took 
98 s to count that way.
+        self._count_paragraph_parts = etree.XPath(
+            "count(w:r) + count(w:hyperlink) + count(w:hyperlink/w:r)", 
namespaces=nsmap
+        )
+        # Rows and their cells are walked before any is read: once to find the 
column count of a
+        # table without w:tblGrid, and once per row to sum the w:gridSpan of 
its cells.
+        self._count_rows_and_cells = etree.XPath("count(w:tr) + 
count(w:tr/w:tc)", namespaces=nsmap)
+
+    def charge(self, *, chars: int = 0, elements: int = 0) -> None:
+        self.chars += chars
+        self.elements += elements
+        if self.chars > _DOCX_MAX_CHARS:
+            raise _DocxLimitReachedError(f"its text exceeds {_DOCX_MAX_CHARS} 
characters")
+        if self.elements > _DOCX_MAX_ELEMENTS:
+            raise _DocxLimitReachedError(
+                f"it has more than {_DOCX_MAX_ELEMENTS} paragraphs, runs, 
tables, rows and cells"
+            )
+
+    def charge_table(self, table: Table) -> None:
+        self.charge(elements=1 + int(self._count_rows_and_cells(table._tbl)))
+
+    def get_paragraph_text(self, paragraph: Paragraph) -> str:
+        self.charge(elements=1 + 
int(self._count_paragraph_parts(paragraph._p)))
+        text = paragraph.text

Review Comment:
   Thanks, you're right, and my "about 11 s" earlier was wrong: I had only 
tried one kind of child at a time. The body, cell, paragraph and run children 
are now walked with `iterchildren(...)` in document order, with `str(child)` 
for run children as `CT_R.text` does, so none of those unions runs. 160K 
alternating pairs of each kind now take 0.2-1.2 s, against 86-101 s on `main`.
   
   Each element is counted as it is reached, including the text, tab and break 
elements of a run, so a run of page breaks still stops at the limit. The text 
of all 2,425 corpus files is unchanged, and the shapes I tried under the limit 
are listed in the PR description (slowest 6.7 s).
   



##########
providers/common/ai/docs/operators/document_loader.rst:
##########
@@ -95,6 +95,16 @@ including any tables nested in it, would be longer than 
about 1,000,000
 characters. If a skipped table is nested inside a cell, only that table is left
 out.
 
+Reading stops with a warning once the text passes about 10,000,000 characters,
+or the document has more than 1,000,000 elements: paragraphs, runs of text,
+hyperlinks, tables, table rows and cells, including the empty cells that pad 
out
+a row. The text read up to that point is kept, the rest of the document is left
+out, and the document's metadata gets ``"truncated": True``. A table that 
reading

Review Comment:
   Good point, thanks. Added a line under "Metadata precedence" saying not to 
put `truncated` in `metadata_fields`.
   



##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -483,19 +511,24 @@ def _parse_docx_stream(self, stream: BinaryIO, *, 
source_hint: str) -> list[dict
             raise AirflowOptionalProviderFeatureException(e)
 
         doc = Document(stream)
+        budget = _DocxBudget()
         blocks = []
-        for block in doc.iter_inner_content():
-            if isinstance(block, Table):
-                rows = self._get_docx_table_rows_or_none(
-                    block, Table, _Cell, InvalidXmlError, 
source_hint=source_hint
-                )
-                if rows is None:
-                    continue
-                text = "\n".join(f"| {' | '.join(cells)} |" for cells in rows)
-            else:
-                text = block.text
-            if text.strip():
-                blocks.append(text)
+        try:
+            for block in doc.iter_inner_content():
+                if isinstance(block, Table):
+                    rows = self._get_docx_table_rows_or_none(
+                        block, Table, _Cell, InvalidXmlError, budget=budget, 
source_hint=source_hint
+                    )
+                    if rows is None:
+                        continue
+                    text = "\n".join(f"| {' | '.join(cells)} |" for cells in 
rows)
+                else:
+                    text = block.text
+                    budget.charge(len(text))
+                if text.strip():
+                    blocks.append(text)
+        except _DocxLimitReachedError as e:
+            self.log.warning("Stopped reading %s because %s; the rest is left 
out.", source_hint, e)
         text = "\n\n".join(blocks)
         return [{"text": text, "metadata": {}}]

Review Comment:
   Done, a skipped table now sets `truncated` too, and the docs say so. Thanks!
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to