Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(parser): caption DOCX tables with their heading hierarchy (#21202)

xugangqiang4c036bd75075
diff --git a/internal/parser/parser/docx_caption_cgo_test.go b/internal/parser/parser/docx_caption_cgo_test.go
new file mode 100644
index 0000000000..12c944dbc0
--- /dev/null
+++ b/internal/parser/parser/docx_caption_cgo_test.go
@@ -0,0 +1,172 @@
+//go:build cgo
+
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package parser
+
+import (
+ "archive/zip"
+ "bytes"
+ "strings"
+ "testing"
+
+ "ragflow/internal/entity"
+ "ragflow/internal/parser/tableutil"
+)
+
+// docxCaptionZip builds a minimal .docx package from the given parts.
+func docxCaptionZip(t *testing.T, parts map[string]string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, body := range parts {
+ writeZipFile(t, zw, name, body)
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatalf("zip close: %v", err)
+ }
+ return buf.Bytes()
+}
+
+// docxCaptionStylesXML defines the built-in Heading1 and Caption styles.
+// office_oxide resolves heading levels through the style sheet, so a
+// document without it degrades headings to plain paragraphs.
+const docxCaptionStylesXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
+ <w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/></w:style>
+ <w:style w:type="paragraph" w:styleId="Caption"><w:name w:val="caption"/></w:style>
+</w:styles>`
+
+// docxCaptionBody wraps the given <w:body> children in a document.
+func docxCaptionBody(inner string) string {
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:body>` + inner + `
+ </w:body>
+</w:document>`
+}
+
+func docxCaptionPara(styleID, text string) string {
+ return `<w:p><w:pPr><w:pStyle w:val="` + styleID + `"/></w:pPr><w:r><w:t>` + text + `</w:t></w:r></w:p>`
+}
+
+func docxCaptionTable() string {
+ return `<w:tbl>
+ <w:tr>
+ <w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc>
+ <w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc>
+ </w:tr>
+</w:tbl>`
+}
+
+func docxCaptionTestDOCX(t *testing.T, bodyInner string) []byte {
+ t.Helper()
+ return docxCaptionZip(t, map[string]string{
+ "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
+ <Default Extension="xml" ContentType="application/xml"/>
+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
+ <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
+</Types>`,
+ "_rels/.rels": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
+</Relationships>`,
+ "word/_rels/document.xml.rels": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
+</Relationships>`,
+ "word/styles.xml": docxCaptionStylesXML,
+ "word/document.xml": docxCaptionBody(bodyInner),
+ })
+}
+
+// docxCaptionFindTable returns the single TableData from a parse result.
+func docxCaptionFindTable(t *testing.T, res ParseResult) *entity.TableData {
+ t.Helper()
+ for _, item := range res.JSON {
+ if ti, ok := item.(TableItem); ok && ti.Table != nil {
+ return ti.Table
+ }
+ }
+ t.Fatal("no table item in parse result")
+ return nil
+}
+
+func docxCaptionParse(t *testing.T, bodyInner string) ParseResult {
+ p := NewDOCXParser()
+ p.outputFormat = "json"
+ res := p.ParseWithResult(t.Context(), "caption.docx", docxCaptionTestDOCX(t, bodyInner))
+ if res.Err != nil {
+ t.Fatalf("ParseWithResult: %v", res.Err)
+ }
+ return res
+}
+
+// TestDOCXParser_TableCaptionFromHeading_EndToEnd runs a real .docx
+// (heading immediately above a table) through the native office_oxide
+// extraction and asserts the table chunk carries the heading-location
+// caption, rendered into the table HTML the chunker persists.
+func TestDOCXParser_TableCaptionFromHeading_EndToEnd(t *testing.T) {
+ res := docxCaptionParse(t, docxCaptionPara("Heading1", "设备台账")+docxCaptionTable())
+ td := docxCaptionFindTable(t, res)
+ if td.Caption != "Table Location: 设备台账" {
+ t.Errorf("table caption = %q, want %q", td.Caption, "Table Location: 设备台账")
+ }
+ rendered := tableutil.RenderTableHTML(td)
+ if !strings.Contains(rendered, "<caption>Table Location: 设备台账</caption>") {
+ t.Errorf("rendered table HTML missing caption:\n%s", rendered)
+ }
+}
+
+// TestDOCXParser_CaptionStyledParagraphBecomesTableCaption_EndToEnd pins the
+// Go-side temporary stopgap (docx_caption_scan.go): a "Caption"-styled
+// paragraph immediately above a table is attached as the table caption and is
+// NOT emitted as its own text section. (office_oxide itself never surfaces the
+// paragraph style; the Go parser recovers it by re-parsing document.xml.)
+func TestDOCXParser_CaptionStyledParagraphBecomesTableCaption_EndToEnd(t *testing.T) {
+ res := docxCaptionParse(t, docxCaptionPara("Caption", "设备流转明细")+docxCaptionTable())
+ td := docxCaptionFindTable(t, res)
+ if td.Caption != "设备流转明细" {
+ t.Errorf("table caption = %q, want %q", td.Caption, "设备流转明细")
+ }
+ rendered := tableutil.RenderTableHTML(td)
+ if !strings.Contains(rendered, "<caption>设备流转明细</caption>") {
+ t.Errorf("rendered table HTML missing caption:\n%s", rendered)
+ }
+ for _, item := range res.JSON {
+ if ti, ok := item.(TextItem); ok && ti.Text == "设备流转明细" {
+ t.Errorf("Caption-styled paragraph must be consumed as a caption, not left as a text section")
+ }
+ }
+}
+
+// TestDOCXParser_CaptionPreferredOverHeading_EndToEnd asserts that when both a
+// heading and a Caption-styled paragraph precede the table, the explicit
+// caption wins over the synthesized heading-location caption.
+func TestDOCXParser_CaptionPreferredOverHeading_EndToEnd(t *testing.T) {
+ res := docxCaptionParse(t,
+ docxCaptionPara("Heading1", "设备台账")+
+ docxCaptionPara("Caption", "设备流转明细")+
+ docxCaptionTable())
+ td := docxCaptionFindTable(t, res)
+ if td.Caption != "设备流转明细" {
+ t.Errorf("table caption = %q, want explicit caption %q", td.Caption, "设备流转明细")
+ }
+}
diff --git a/internal/parser/parser/docx_caption_scan.go b/internal/parser/parser/docx_caption_scan.go
new file mode 100644
index 0000000000..d95d7280e9
--- /dev/null
+++ b/internal/parser/parser/docx_caption_scan.go
@@ -0,0 +1,171 @@
+// Package-level note: this file is a TEMPORARY stopgap, not a permanent fix.
+//
+// Problem it works around: office_oxide's IR JSON (the structured output the
+// Go DOCX parser builds sections from) does NOT expose paragraph style names
+// for non-heading paragraphs. It resolves Word heading styles into
+// type "heading" + level, but a paragraph styled with the built-in "Caption"
+// style (or the Chinese "题注") is emitted as a plain {"type":"paragraph"}
+// with no style field. As a result the Go parser cannot tell a caption
+// paragraph from ordinary body text, so a table's visible caption is lost
+// (see the user-reported case "设备流转明细").
+//
+// The correct, robust fix lives upstream: teach office_oxide to emit the
+// paragraph style name so this detection is unnecessary. That is tracked in
+// yfedoseev/office_oxide#455 ("Expose paragraph style name (w:pStyle) in the
+// IR JSON for non-heading paragraphs").
+//
+// Until that lands and office_oxide is upgraded in this repo, we recover the
+// caption the cheap way: re-parse word/document.xml ourselves and pair a
+// caption-styled paragraph with the table that immediately follows it. This
+// MUST be removed once office_oxide emits paragraph styles — do not extend it,
+// do not rely on it from new code. The position-based pairing (document-body
+// table order vs office_oxide IR table order) is approximate and documented at
+// buildDOCXJSONSectionsCore.
+package parser
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// docxCaptionStyleNames are the Word paragraph style identifiers that mark a
+// paragraph as a table caption for the temporary detection above. The built-in
+// caption style's styleId is "Caption" in every locale; "题注" covers documents
+// where a caption style was created with the localized display name.
+var docxCaptionStyleNames = map[string]bool{
+ "caption": true,
+ "题注": true,
+}
+
+func isDOCXCaptionStyle(styleID string) bool {
+ return docxCaptionStyleNames[strings.ToLower(strings.TrimSpace(styleID))]
+}
+
+// extractDOCXTableCaptions re-parses word/document.xml to recover table
+// captions. It returns one entry per table in document-body reading order: the
+// trimmed text of the paragraph immediately above the table when that
+// paragraph carries a caption style, otherwise "".
+//
+// It is intentionally limited to the common case: paragraphs and tables that
+// are direct children of w:body, in order. Nested tables (e.g. inside a text
+// box) are ignored, matching how office_oxide flattens the typical document.
+// Errors are returned to the caller, which falls back to no captions.
+//
+// TEMPORARY: see the package note at the top of this file.
+func extractDOCXTableCaptions(docx []byte) ([]string, error) {
+ zr, err := zip.NewReader(bytes.NewReader(docx), int64(len(docx)))
+ if err != nil {
+ return nil, fmt.Errorf("docx caption scan: open zip: %w", err)
+ }
+ var bodyXML []byte
+ for _, f := range zr.File {
+ if f.Name == "word/document.xml" {
+ rc, err := f.Open()
+ if err != nil {
+ return nil, fmt.Errorf("docx caption scan: open document.xml: %w", err)
+ }
+ bodyXML, err = io.ReadAll(rc)
+ rc.Close()
+ if err != nil {
+ return nil, fmt.Errorf("docx caption scan: read document.xml: %w", err)
+ }
+ break
+ }
+ }
+ if bodyXML == nil {
+ return nil, fmt.Errorf("docx caption scan: word/document.xml not found")
+ }
+
+ dec := xml.NewDecoder(bytes.NewReader(bodyXML))
+ var captions []string
+ var pendingCaption string
+
+ var inBody bool
+ var bodyDepth int // depth relative to <w:body>; 1 == direct child of body
+ var inPara bool
+ var paraIsCaption bool
+ var inText bool
+ var paraText strings.Builder
+
+ flushPara := func() {
+ if paraIsCaption {
+ pendingCaption = strings.TrimSpace(paraText.String())
+ } else {
+ // Any non-caption paragraph clears a caption that was pending
+ // for the next table, so only an *immediately* preceding caption
+ // is attached.
+ pendingCaption = ""
+ }
+ inPara = false
+ paraIsCaption = false
+ inText = false
+ paraText.Reset()
+ }
+
+ for {
+ tok, err := dec.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, fmt.Errorf("docx caption scan: xml: %w", err)
+ }
+ switch t := tok.(type) {
+ case xml.StartElement:
+ local := t.Name.Local
+ if !inBody {
+ if local == "body" {
+ inBody = true
+ bodyDepth = 0
+ }
+ continue
+ }
+ bodyDepth++
+ switch {
+ case bodyDepth == 1 && local == "p":
+ inPara = true
+ paraIsCaption = false
+ inText = false
+ paraText.Reset()
+ case bodyDepth == 1 && local == "tbl":
+ captions = append(captions, pendingCaption)
+ pendingCaption = ""
+ case inPara && local == "pStyle":
+ for _, a := range t.Attr {
+ if a.Name.Local == "val" {
+ paraIsCaption = isDOCXCaptionStyle(a.Value)
+ }
+ }
+ case inPara && local == "t":
+ inText = true
+ }
+ case xml.CharData:
+ if inPara && inText {
+ paraText.Write(t)
+ }
+ case xml.EndElement:
+ local := t.Name.Local
+ if !inBody {
+ continue
+ }
+ switch {
+ case bodyDepth == 1 && local == "p" && inPara:
+ flushPara()
+ case inPara && local == "t":
+ inText = false
+ case inPara && local == "pStyle":
+ // nothing to reset; paraIsCaption stays until paragraph end
+ }
+ bodyDepth--
+ if local == "body" {
+ inBody = false
+ }
+ }
+ }
+ // A trailing caption paragraph with no following table is discarded.
+ return captions, nil
+}
diff --git a/internal/parser/parser/docx_caption_scan_test.go b/internal/parser/parser/docx_caption_scan_test.go
new file mode 100644
index 0000000000..9107069c6c
--- /dev/null
+++ b/internal/parser/parser/docx_caption_scan_test.go
@@ -0,0 +1,141 @@
+package parser
+
+import (
+ "archive/zip"
+ "bytes"
+ "testing"
+)
+
+// buildSampleDOCX constructs a minimal but valid .docx (ZIP/OOXML) in memory
+// from the given body children of <w:body>. The caller supplies the inner XML
+// of <w:body> (paragraphs and tables). A default styles.xml is included so the
+// document is well-formed; style names are referenced by w:pStyle w:val.
+func buildSampleDOCX(t *testing.T, bodyInner string) []byte {
+ t.Helper()
+ document := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
+ `<w:body>` + bodyInner + `</w:body></w:document>`
+ styles := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
+ `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Caption"><w:name w:val="caption"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="题注"><w:name w:val="caption"/></w:style>` +
+ `</w:styles>`
+ contentTypes := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
+ `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
+ `<Default Extension="xml" ContentType="application/xml"/>` +
+ `<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
+ `<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
+ `</Types>`
+ rels := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
+ `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
+ `</Relationships>`
+ docRels := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
+ `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
+ `</Relationships>`
+
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ files := map[string]string{
+ "[Content_Types].xml": contentTypes,
+ "_rels/.rels": rels,
+ "word/document.xml": document,
+ "word/styles.xml": styles,
+ "word/_rels/document.xml.rels": docRels,
+ }
+ for name, content := range files {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatalf("zip create %s: %v", name, err)
+ }
+ if _, err := w.Write([]byte(content)); err != nil {
+ t.Fatalf("zip write %s: %v", name, err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatalf("zip close: %v", err)
+ }
+ return buf.Bytes()
+}
+
+func docxScanPara(styleID, text string) string {
+ return `<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
+ `<w:pPr><w:pStyle w:val="` + styleID + `"/></w:pPr>` +
+ `<w:r><w:t>` + text + `</w:t></w:r></w:p>`
+}
+
+func plainPara(text string) string {
+ return `<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
+ `<w:r><w:t>` + text + `</w:t></w:r></w:p>`
+}
+
+func docxScanTable() string {
+ return `<w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
+ `<w:tr><w:tc><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc>` +
+ `<w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr></w:tbl>`
+}
+
+// A Caption-styled paragraph immediately above a table is recovered.
+func TestExtractDOCXTableCaptions_CaptionBeforeTable(t *testing.T) {
+ doc := buildSampleDOCX(t,
+ docxScanPara("Heading1", "设备台账")+
+ docxScanPara("Caption", "设备流转明细")+
+ docxScanTable()+
+ plainPara("普通正文"))
+ caps, err := extractDOCXTableCaptions(doc)
+ if err != nil {
+ t.Fatalf("extractDOCXTableCaptions: %v", err)
+ }
+ if len(caps) != 1 {
+ t.Fatalf("want 1 table caption, got %d: %v", len(caps), caps)
+ }
+ if caps[0] != "设备流转明细" {
+ t.Errorf("caption = %q, want %q", caps[0], "设备流转明细")
+ }
+}
+
+// The Chinese caption style "题注" is detected the same way.
+func TestExtractDOCXTableCaptions_ChineseCaption(t *testing.T) {
+ doc := buildSampleDOCX(t, docxScanPara("题注", "设备明细表")+docxScanTable())
+ caps, err := extractDOCXTableCaptions(doc)
+ if err != nil {
+ t.Fatalf("extractDOCXTableCaptions: %v", err)
+ }
+ if len(caps) != 1 || caps[0] != "设备明细表" {
+ t.Fatalf("caption = %v, want [设备明细表]", caps)
+ }
+}
+
+// A non-caption paragraph between the caption and the table detaches it.
+func TestExtractDOCXTableCaptions_CaptionNotImmediate(t *testing.T) {
+ doc := buildSampleDOCX(t,
+ docxScanPara("Caption", "设备流转明细")+
+ plainPara("中间说明文字")+
+ docxScanTable())
+ caps, err := extractDOCXTableCaptions(doc)
+ if err != nil {
+ t.Fatalf("extractDOCXTableCaptions: %v", err)
+ }
+ if len(caps) != 1 || caps[0] != "" {
+ t.Fatalf("caption = %v, want [\"\"]", caps)
+ }
+}
+
+// Multiple tables get the caption of their own preceding caption paragraph.
+func TestExtractDOCXTableCaptions_MultipleTables(t *testing.T) {
+ doc := buildSampleDOCX(t,
+ docxScanPara("Caption", "第一表")+docxScanTable()+
+ plainPara("分隔")+
+ docxScanPara("Caption", "第二表")+docxScanTable())
+ caps, err := extractDOCXTableCaptions(doc)
+ if err != nil {
+ t.Fatalf("extractDOCXTableCaptions: %v", err)
+ }
+ if len(caps) != 2 || caps[0] != "第一表" || caps[1] != "第二表" {
+ t.Fatalf("captions = %v, want [第一表 第二表]", caps)
+ }
+}
diff --git a/internal/parser/parser/docx_caption_test.go b/internal/parser/parser/docx_caption_test.go
new file mode 100644
index 0000000000..194c45296b
--- /dev/null
+++ b/internal/parser/parser/docx_caption_test.go
@@ -0,0 +1,190 @@
+package parser
+
+import (
+ "strings"
+ "testing"
+
+ "ragflow/internal/entity"
+)
+
+// docxCaptionTableIR wraps a single table element in a minimal IR document.
+func docxCaptionTableIR(elements ...string) string {
+ return `{"sections":[{"title":"","elements":[` + strings.Join(elements, ",") + `]}]}`
+}
+
+const docxCaptionTableBody = `{"type":"table","rows":[{"cells":[{"content":[{"type":"paragraph","content":[{"type":"text","text":"A1"}]}]},{"content":[{"type":"paragraph","content":[{"type":"text","text":"B1"}]}]}]}]}`
+
+// docxCaptionFindTableCaption returns the Caption of the (single) table
+// section, which buildDOCXJSONSections stores on the structured
+// entity.TableData (after projectPDFTable parses the injected <caption>
+// out of the table HTML).
+func docxCaptionFindTableCaption(t *testing.T, sections []map[string]any) string {
+ t.Helper()
+ for _, s := range sections {
+ if dt, _ := s["doc_type_kwd"].(string); dt == "table" {
+ td, ok := s["table"].(*entity.TableData)
+ if !ok || td == nil {
+ t.Fatalf("table section missing *entity.TableData")
+ }
+ return td.Caption
+ }
+ }
+ t.Fatal("no table section found")
+ return ""
+}
+
+// Happy path: a heading immediately before a table yields a "Table Location"
+// caption built from the heading hierarchy (mirrors Python __get_nearest_title).
+func TestBuildDOCXJSONSections_TableCaption_ByHeading(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"设备台账"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: 设备台账" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: 设备台账")
+ }
+}
+
+// Nested heading hierarchy collapses to "A > B > C" before the table. The
+// caption round-trips through HTML (escaped on injection, unescaped by
+// ParseTableHTML), so TableData.Caption holds the plain text form.
+func TestBuildDOCXJSONSections_TableCaption_NestedHeading(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"H1"}]}`,
+ `{"type":"heading","level":2,"content":[{"type":"text","text":"H2"}]}`,
+ `{"type":"heading","level":3,"content":[{"type":"text","text":"H3"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: H1 > H2 > H3" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: H1 > H2 > H3")
+ }
+}
+
+// A heading AFTER the table must not leak into the caption.
+func TestBuildDOCXJSONSections_TableCaption_HeadingAfterTable(t *testing.T) {
+ ir := docxCaptionTableIR(
+ docxCaptionTableBody,
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"后续标题"}]}`,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "" {
+ t.Errorf("table should have no caption when heading is after it, got %q", got)
+ }
+}
+
+// A sibling heading supersedes the deeper one: the outline holds only the
+// ancestors of the table, not abandoned deeper headings.
+func TestBuildDOCXJSONSections_TableCaption_SiblingHeadingSupersedes(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"H1"}]}`,
+ `{"type":"heading","level":2,"content":[{"type":"text","text":"H2a"}]}`,
+ `{"type":"heading","level":3,"content":[{"type":"text","text":"H3"}]}`,
+ `{"type":"heading","level":2,"content":[{"type":"text","text":"H2b"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: H1 > H2b" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: H1 > H2b")
+ }
+}
+
+// A heading with a deeper level after the table's parent must not resurrect
+// an abandoned branch: the outline keeps only true ancestors.
+func TestBuildDOCXJSONSections_TableCaption_DeeperHeadingAfterSibling(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":2,"content":[{"type":"text","text":"H2a"}]}`,
+ `{"type":"heading","level":3,"content":[{"type":"text","text":"H3a"}]}`,
+ `{"type":"heading","level":2,"content":[{"type":"text","text":"H2b"}]}`,
+ `{"type":"heading","level":3,"content":[{"type":"text","text":"H3b"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: H2b > H3b" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: H2b > H3b")
+ }
+}
+
+// An empty heading between a real heading and the table is ignored, so it
+// neither truncates the outline nor becomes part of the caption.
+func TestBuildDOCXJSONSections_TableCaption_EmptyHeadingIgnored(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"H1"}]}`,
+ `{"type":"heading","level":2,"content":[{"type":"text","text":" "}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: H1" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: H1")
+ }
+}
+
+// The heading outline spans IR sections: a heading in an earlier section
+// still captions a table in a later one.
+func TestBuildDOCXJSONSections_TableCaption_OutlineSpansSections(t *testing.T) {
+ ir := `{"sections":[
+ {"title":"","elements":[{"type":"heading","level":1,"content":[{"type":"text","text":"第一章"}]}]},
+ {"title":"","elements":[` + docxCaptionTableBody + `]}
+ ]}`
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: 第一章" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: 第一章")
+ }
+}
+
+// A plain (non-heading) paragraph before a table is NOT turned into a
+// caption — only the heading hierarchy is used.
+func TestBuildDOCXJSONSections_TableCaption_PlainParagraphNotCaption(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"paragraph","content":[{"type":"text","text":"设备流转明细"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSections(ir, newEmbeddedMediaBudget())
+ if got := docxCaptionFindTableCaption(t, sections); got != "" {
+ t.Errorf("plain paragraph must not become a caption, got %q", got)
+ }
+}
+
+// Corner: empty IR yields no sections.
+func TestBuildDOCXJSONSections_TableCaption_Empty(t *testing.T) {
+ sections := buildDOCXJSONSections(`{"sections":[]}`, newEmbeddedMediaBudget())
+ if len(sections) != 0 {
+ t.Errorf("empty IR should yield no sections, got %d", len(sections))
+ }
+}
+
+// TEMPORARY Caption-style detection (docx_caption_scan.go): an explicit
+// caption supplied for the table overrides the synthesized heading-location
+// caption.
+func TestBuildDOCXJSONSections_TableCaption_ExplicitPreferredOverLocation(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"设备台账"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSectionsWithCaptions(ir, newEmbeddedMediaBudget(), []string{"设备流转明细"})
+ if got := docxCaptionFindTableCaption(t, sections); got != "设备流转明细" {
+ t.Errorf("explicit caption = %q, want %q", got, "设备流转明细")
+ }
+}
+
+// An explicit caption is attached even when the table sits under no heading.
+func TestBuildDOCXJSONSections_TableCaption_ExplicitWithNoHeading(t *testing.T) {
+ ir := docxCaptionTableIR(docxCaptionTableBody)
+ sections := buildDOCXJSONSectionsWithCaptions(ir, newEmbeddedMediaBudget(), []string{"设备流转明细"})
+ if got := docxCaptionFindTableCaption(t, sections); got != "设备流转明细" {
+ t.Errorf("explicit caption = %q, want %q", got, "设备流转明细")
+ }
+}
+
+// A blank entry never overrides a valid heading-location caption.
+func TestBuildDOCXJSONSections_TableCaption_BlankDoesNotOverrideLocation(t *testing.T) {
+ ir := docxCaptionTableIR(
+ `{"type":"heading","level":1,"content":[{"type":"text","text":"设备台账"}]}`,
+ docxCaptionTableBody,
+ )
+ sections := buildDOCXJSONSectionsWithCaptions(ir, newEmbeddedMediaBudget(), []string{""})
+ if got := docxCaptionFindTableCaption(t, sections); got != "Table Location: 设备台账" {
+ t.Errorf("caption = %q, want %q", got, "Table Location: 设备台账")
+ }
+}
diff --git a/internal/parser/parser/docx_ir.go b/internal/parser/parser/docx_ir.go
index b4188238af..f47832d11a 100644
--- a/internal/parser/parser/docx_ir.go
+++ b/internal/parser/parser/docx_ir.go
@@ -189,9 +189,17 @@ func joinCellText(cell docxIRCell) string {
}
// docxIRTableToHTML converts a table IR element to an HTML table string.
-func docxIRTableToHTML(el docxIRElement) string {
+// A non-empty caption is emitted as a leading <caption> element so the
+// structured TableData contract (ParseTableHTML) carries it through to the
+// chunk renderer, which escapes it again on output.
+func docxIRTableToHTML(el docxIRElement, caption string) string {
var sb strings.Builder
sb.WriteString("<table>")
+ if caption != "" {
+ sb.WriteString("<caption>")
+ sb.WriteString(html.EscapeString(caption))
+ sb.WriteString("</caption>")
+ }
for _, row := range el.Rows {
sb.WriteString("<tr>")
for _, cell := range row.Cells {
@@ -326,10 +334,76 @@ func docxElementText(el docxIRElement, cellSep string) string {
}
}
+// docxHeading is one entry of the heading outline stack.
+type docxHeading struct {
+ level int
+ text string
+}
+
+// pushDOCXHeading folds a heading into the outline stack: a heading at
+// level L supersedes every entry at level >= L (sibling and deeper
+// headings end), then becomes the innermost entry. Empty headings are
+// ignored so they never truncate the outline.
+func pushDOCXHeading(stack []docxHeading, level int, text string) []docxHeading {
+ text = strings.TrimSpace(text)
+ if text == "" {
+ return stack
+ }
+ for len(stack) > 0 && stack[len(stack)-1].level >= level {
+ stack = stack[:len(stack)-1]
+ }
+ return append(stack, docxHeading{level: level, text: text})
+}
+
+// docxHeadingLocationCaption renders the heading outline as a table
+// location caption, mirroring Python's Docx.__get_nearest_title, which
+// injected "<caption>Table Location: {hierarchy}</caption>" into the table
+// HTML. It returns "" when the table sits under no heading.
+func docxHeadingLocationCaption(headings []docxHeading) string {
+ if len(headings) == 0 {
+ return ""
+ }
+ titles := make([]string, len(headings))
+ for i, h := range headings {
+ titles[i] = h.text
+ }
+ return "Table Location: " + strings.Join(titles, " > ")
+}
+
// buildDOCXJSONSections converts an office_oxide IR JSON string into a
// slice of structured items compatible with the chunker's JSON input
// contract. Each item carries at least text and doc_type_kwd.
+//
+// A table carries the heading hierarchy it sits under as its caption,
+// mirroring Python's Docx.__get_nearest_title. office_oxide resolves Word
+// heading styles into element type "heading" plus a level, so the outline
+// is tracked from those elements alone.
+//
+// This is the caption-only (heading hierarchy) entry point. Use
+// buildDOCXJSONSectionsWithCaptions to also attach Caption-styled paragraph
+// text (a temporary stopgap; see docx_caption_scan.go).
func buildDOCXJSONSections(irJSON string, budget *embeddedMediaBudget) []map[string]any {
+ return buildDOCXJSONSectionsCore(irJSON, budget, nil)
+}
+
+// buildDOCXJSONSectionsWithCaptions is buildDOCXJSONSections plus the
+// TEMPORARY Caption-styled-paragraph detection. tableCaptions must be aligned
+// by position with the tables in the IR (see docx_caption_scan.go).
+//
+// TEMPORARY: remove once office_oxide emits paragraph styles
+// (yfedoseev/office_oxide#455).
+func buildDOCXJSONSectionsWithCaptions(irJSON string, budget *embeddedMediaBudget, tableCaptions []string) []map[string]any {
+ return buildDOCXJSONSectionsCore(irJSON, budget, tableCaptions)
+}
+
+// buildDOCXJSONSectionsCore is the shared implementation of the two entry
+// points above. tableCaptions, when non-nil, supplies a descriptive caption
+// for each table indexed by reading order; an explicit caption is preferred
+// over the synthesized heading-location caption. The position alignment
+// between tableCaptions and the IR tables is approximate (document-body order
+// vs office_oxide IR order) and is a known limitation of the temporary
+// Caption-style stopgap in docx_caption_scan.go.
+func buildDOCXJSONSectionsCore(irJSON string, budget *embeddedMediaBudget, tableCaptions []string) []map[string]any {
var ir docxIRDocument
if err := json.Unmarshal([]byte(irJSON), &ir); err != nil {
return nil
@@ -339,10 +413,30 @@ func buildDOCXJSONSections(irJSON string, budget *embeddedMediaBudget) []map[str
}
var sections []map[string]any
tableSequence := 0
+ var headings []docxHeading
for _, sec := range ir.Sections {
for _, el := range sec.Elements {
switch el.Type {
case "paragraph", "heading":
+ if el.Type == "heading" {
+ level := el.Level
+ if level <= 0 {
+ level = 1
+ }
+ headings = pushDOCXHeading(headings, level, docxElementText(el, "\n"))
+ }
+ // TEMPORARY (docx_caption_scan.go): when a paragraph's text
+ // exactly matches the Caption recovered for the next table,
+ // suppress it as a standalone text section — it is attached
+ // to that table as the caption instead. The text match keeps
+ // this safe if the document scan and the IR element order
+ // ever desync: a non-matching paragraph is never dropped.
+ if tableSequence < len(tableCaptions) {
+ if explicit := strings.TrimSpace(tableCaptions[tableSequence]); explicit != "" &&
+ strings.TrimSpace(docxElementText(el, " ")) == explicit {
+ continue
+ }
+ }
sections = appendDOCXParagraphSections(sections, el, el.Type == "heading", budget)
case "image":
@@ -350,10 +444,19 @@ func buildDOCXJSONSections(irJSON string, budget *embeddedMediaBudget) []map[str
case "table":
tableSequence++
- html := docxIRTableToHTML(el)
- if html == "<table></table>" {
+ if len(el.Rows) == 0 {
continue
}
+ // Prefer an explicit Caption-styled paragraph (temporary
+ // stopgap, see docx_caption_scan.go) over the synthesized
+ // heading-location caption.
+ caption := docxHeadingLocationCaption(headings)
+ if idx := tableSequence - 1; idx >= 0 && idx < len(tableCaptions) {
+ if explicit := strings.TrimSpace(tableCaptions[idx]); explicit != "" {
+ caption = explicit
+ }
+ }
+ html := docxIRTableToHTML(el, caption)
table := map[string]any{
"text": html,
"image": nil,
diff --git a/internal/parser/parser/docx_ir_test.go b/internal/parser/parser/docx_ir_test.go
index 29792c98f8..6d29a1b530 100644
--- a/internal/parser/parser/docx_ir_test.go
+++ b/internal/parser/parser/docx_ir_test.go
@@ -32,7 +32,9 @@ func TestBuildDOCXJSONSections_FromJSON(t *testing.T) {
{"text": "Title", "image": nil, "doc_type_kwd": "text", "ck_type": "heading"},
{"text": "Hello", "image": nil, "doc_type_kwd": "text"},
{"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"},
- {"image": nil, "doc_type_kwd": "table", "table": &entity.TableData{Grid: [][]entity.TableCell{{{Text: "cell", ColSpan: 1, RowSpan: 1}}}, HeaderRows: 1}},
+ // The table sits under heading "Title", so it carries the
+ // heading-location caption (mirrors Python __get_nearest_title).
+ {"image": nil, "doc_type_kwd": "table", "table": &entity.TableData{Grid: [][]entity.TableCell{{{Text: "cell", ColSpan: 1, RowSpan: 1}}}, HeaderRows: 1, Caption: "Table Location: Title"}},
{"text": "item1", "image": nil, "doc_type_kwd": "text"},
}
if !reflect.DeepEqual(got, want) {
@@ -41,8 +43,7 @@ func TestBuildDOCXJSONSections_FromJSON(t *testing.T) {
}
// TestBuildDOCXJSONSections_EmptyTableSkipped verifies that a table
-// with no rows renders as "<table></table>" and is dropped by the
-// "if html == \"<table></table>\" { continue }" guard.
+// with no rows is dropped before it can become a section.
func TestBuildDOCXJSONSections_EmptyTableSkipped(t *testing.T) {
irJSON := `{"sections":[{"elements":[
{"type":"paragraph","content":[{"type":"text","text":"keep"}]},
diff --git a/internal/parser/parser/docx_parser.go b/internal/parser/parser/docx_parser.go
index 21ef9ffaf4..d0c3aa982c 100644
--- a/internal/parser/parser/docx_parser.go
+++ b/internal/parser/parser/docx_parser.go
@@ -127,7 +127,14 @@ func (p *DOCXParser) ParseWithResult(ctx context.Context, filename string, data
if irJSON == "" {
return ParseResult{Err: fmt.Errorf("docx extract: empty IR, cannot build JSON output")}
}
- sections := buildDOCXJSONSections(irJSON, budget)
+ // TEMPORARY Caption-styled-paragraph detection (office_oxide does
+ // not yet expose paragraph styles; yfedoseev/office_oxide#455).
+ // Remove once office_oxide is upgraded to emit them.
+ tableCaptions, capErr := extractDOCXTableCaptions(data)
+ if capErr != nil {
+ tableCaptions = nil
+ }
+ sections := buildDOCXJSONSectionsWithCaptions(irJSON, budget, tableCaptions)
if err := ctx.Err(); err != nil {
return ParseResult{Err: err}
}
diff --git a/internal/parser/parser/docx_parser_test.go b/internal/parser/parser/docx_parser_test.go
index 0e35118c95..fe4de3724e 100644
--- a/internal/parser/parser/docx_parser_test.go
+++ b/internal/parser/parser/docx_parser_test.go
@@ -228,7 +228,7 @@ func TestBuildDOCXJSONSections_EmptySkipped(t *testing.T) {
func TestDocxIRTableToHTML_Empty(t *testing.T) {
el := docxIRElement{Type: "table", Rows: []docxIRRow{}}
- html := docxIRTableToHTML(el)
+ html := docxIRTableToHTML(el, "")
if html != "<table></table>" {
t.Errorf("empty table html = %q, want %q", html, "<table></table>")
}
@@ -246,7 +246,7 @@ func TestDocxIRTableToHTML_Single(t *testing.T) {
}},
}},
}
- html := docxIRTableToHTML(el)
+ html := docxIRTableToHTML(el, "")
want := "<table><tr><td>hello</td></tr></table>"
if html != want {
t.Errorf("single cell html = %q, want %q", html, want)
@@ -269,7 +269,7 @@ func TestDocxIRTableToHTML_MultiRowCol(t *testing.T) {
{Cells: []docxIRCell{cell("A2"), cell("B2")}},
},
}
- html := docxIRTableToHTML(el)
+ html := docxIRTableToHTML(el, "")
want := "<table><tr><td>A1</td><td>B1</td></tr><tr><td>A2</td><td>B2</td></tr></table>"
if html != want {
t.Errorf("multi cell html = %q, want %q", html, want)