Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(parse): extract text held in DOCX text boxes (#2127)
张梁e1489f78838c
diff --git a/semantica/parse/docx_parser.py b/semantica/parse/docx_parser.pyindex 9a8f1d50..0a8680c3 100644--- a/semantica/parse/docx_parser.py+++ b/semantica/parse/docx_parser.py@@ -51,6 +51,41 @@ from ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker+# Text boxes.+#+# `Paragraph.text` concatenates only the `w:t` children of each direct `w:r`.+# Text box content sits one level deeper -- `w:txbxContent` holds its own+# `w:p`/`w:r`/`w:t` tree -- so a callout written in a text box is invisible to+# that API and gets dropped without a warning. Word also stores the same text+# box twice, as DrawingML under `mc:Choice` and as VML under `mc:Fallback`, so+# walking every `w:t` under the paragraph would report the text twice.+_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"+_TXBX_CONTENT = _W + "txbxContent"+_W_P = _W + "p"+_W_T = _W + "t"+_MC_FALLBACK = "{http://schemas.openxmlformats.org/markup-compatibility/2006}Fallback"+++def _textbox_text(paragraph: Paragraph) -> str:+ """Text held in the text boxes anchored to ``paragraph``."""+ blocks: List[str] = []+ for container in paragraph._p.iter(_TXBX_CONTENT):+ if any(parent.tag == _MC_FALLBACK for parent in container.iterancestors()):+ # The VML copy of a text box already covered by `mc:Choice`.+ continue+ for inner in container.iter(_W_P):+ text = "".join(node.text or "" for node in inner.iter(_W_T))+ if text.strip():+ blocks.append(text.strip())+ return "\n".join(blocks)+++def _paragraph_text(paragraph: Paragraph) -> str:+ """``Paragraph.text`` plus the text of any text boxes it anchors."""+ return "\n".join(+ part for part in (paragraph.text, _textbox_text(paragraph)) if part+ )+@dataclassclass DocxSection:@@ -142,8 +177,9 @@ class DOCXParser:# Extract paragraphsparagraphs = []for para in doc.paragraphs:- if para.text.strip():- paragraphs.append(para.text.strip())+ text = _paragraph_text(para).strip()+ if text:+ paragraphs.append(text)# Extract tablestables = []@@ -168,7 +204,9 @@ class DOCXParser:self.progress_tracker.stop_tracking(tracking_id,status="completed",- message=f"Parsed {len(paragraphs)} paragraphs, {len(tables)} tables",+ message=(+ f"Parsed {len(paragraphs)} paragraphs, {len(tables)} tables"+ ),)return {"metadata": metadata.__dict__,@@ -237,7 +275,10 @@ class DOCXParser:for row in table.rows:row_data = []for cell in row.cells:- row_data.append(cell.text.strip())+ cell_text = "\n".join(+ _paragraph_text(p) for p in cell.paragraphs+ ).strip()+ row_data.append(cell_text)table_data["rows"].append(row_data)return table_data@@ -250,6 +291,7 @@ class DOCXParser:current_section = Nonefor para in doc.paragraphs:+ text = _paragraph_text(para).strip()# Check if paragraph is a headingif para.style.name.startswith("Heading"):# Get heading level@@ -265,7 +307,7 @@ class DOCXParser:# Create new sectioncurrent_section = DocxSection(- heading=para.text.strip(),+ heading=text,level=level,content="",paragraphs=[],@@ -273,9 +315,9 @@ class DOCXParser:)elif current_section:# Add paragraph to current section- if para.text.strip():- current_section.paragraphs.append(para.text.strip())- current_section.content += para.text.strip() + "\n\n"+ if text:+ current_section.paragraphs.append(text)+ current_section.content += text + "\n\n"# Add last sectionif current_section:diff --git a/tests/parse/test_docx_textbox.py b/tests/parse/test_docx_textbox.pynew file mode 100644index 00000000..d8d80bc5--- /dev/null+++ b/tests/parse/test_docx_textbox.py@@ -0,0 +1,150 @@+"""Text boxes must contribute to the text ``DOCXParser`` extracts.++``Paragraph.text`` concatenates only the ``w:t`` children of each direct+``w:r``. Text box content sits one level deeper, inside ``w:txbxContent``, so a+document whose callout text lives in a text box parses as if that text did not+exist: no exception, no warning, just missing content.++Word writes a text box twice -- DrawingML under ``mc:Choice`` and the VML+rendering under ``mc:Fallback`` -- so a reader that simply walks every ``w:t``+under the paragraph would return the same callout twice.+"""++import pytest++from semantica.parse.docx_parser import DOCXParser++docx = pytest.importorskip(+ "docx", reason="python-docx comes from the 'documents' extra"+)+oxml = pytest.importorskip("docx.oxml")++_NSDECLS = (+ 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '+ 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" '+ 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" '+ 'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/'+ 'wordprocessingDrawing" '+ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" '+ 'xmlns:v="urn:schemas-microsoft-com:vml"'+)++_WPS_GRAPHIC = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"+++def _vml_textbox(text: str) -> str:+ """A paragraph whose only content is a VML text box."""+ return f"""+<w:p {_NSDECLS}>+ <w:r>+ <w:pict>+ <v:shape id="_x0000_s1026" type="#_x0000_t202"+ style="width:180pt;height:60pt">+ <v:textbox>+ <w:txbxContent>+ <w:p><w:r><w:t>{text}</w:t></w:r></w:p>+ </w:txbxContent>+ </v:textbox>+ </v:shape>+ </w:pict>+ </w:r>+</w:p>+"""+++def _alternate_content_textbox(text: str) -> str:+ """The same callout as Word writes it: DrawingML plus a VML fallback."""+ return f"""+<w:p {_NSDECLS}>+ <w:r>+ <mc:AlternateContent>+ <mc:Choice Requires="wps">+ <w:drawing>+ <wp:inline>+ <wp:extent cx="1828800" cy="457200"/>+ <a:graphic>+ <a:graphicData uri="{_WPS_GRAPHIC}">+ <wps:wsp>+ <wps:txbx>+ <w:txbxContent>+ <w:p><w:r><w:t>{text}</w:t></w:r></w:p>+ </w:txbxContent>+ </wps:txbx>+ </wps:wsp>+ </a:graphicData>+ </a:graphic>+ </wp:inline>+ </w:drawing>+ </mc:Choice>+ <mc:Fallback>+ <w:pict>+ <v:shape id="_x0000_s1027" type="#_x0000_t202">+ <v:textbox>+ <w:txbxContent>+ <w:p><w:r><w:t>{text}</w:t></w:r></w:p>+ </w:txbxContent>+ </v:textbox>+ </v:shape>+ </w:pict>+ </mc:Fallback>+ </mc:AlternateContent>+ </w:r>+</w:p>+"""+++def _insert_after(paragraph, xml: str) -> None:+ """Insert a raw ``w:p`` right after ``paragraph``.++ Going through ``add_paragraph`` keeps the insert point legal: appending to+ ``document.element.body`` directly puts the paragraph after ``w:sectPr``,+ which is not the position Word writes.+ """+ paragraph._p.addnext(oxml.parse_xml(xml))+++def _parse(document, tmp_path) -> dict:+ path = tmp_path / "textbox.docx"+ document.save(str(path))+ return DOCXParser().parse(str(path))+++def test_body_text_box_text_is_extracted(tmp_path):+ document = docx.Document()+ document.add_paragraph("BODY_TEXT")+ _insert_after(document.paragraphs[-1], _vml_textbox("CALLOUT_TEXT"))++ result = _parse(document, tmp_path)++ assert "BODY_TEXT" in result["full_text"]+ assert "CALLOUT_TEXT" in result["full_text"]+++def test_alternate_content_text_box_is_extracted_once(tmp_path):+ document = docx.Document()+ document.add_paragraph("BODY_TEXT")+ _insert_after(document.paragraphs[-1], _alternate_content_textbox("CALLOUT_TEXT"))++ result = _parse(document, tmp_path)++ assert result["full_text"].count("CALLOUT_TEXT") == 1+++def test_text_box_in_table_cell_is_extracted(tmp_path):+ document = docx.Document()+ table = document.add_table(rows=1, cols=1)+ _insert_after(table.cell(0, 0).paragraphs[0], _vml_textbox("CELL_CALLOUT"))++ result = _parse(document, tmp_path)++ assert "CELL_CALLOUT" in result["tables"][0]["rows"][0][0]+++def test_section_content_includes_text_box_text(tmp_path):+ document = docx.Document()+ document.add_heading("Heading One", level=1)+ _insert_after(document.paragraphs[-1], _vml_textbox("CALLOUT_TEXT"))++ result = _parse(document, tmp_path)++ assert "CALLOUT_TEXT" in result["sections"][0]["content"]