Files
ragflow/internal/ingestion/component/chunker/group.go
Jack 8669c469d5 fix(ingestion): align laws DSL with Python — heading fallback, colon-title, short-line filter, remove_toc, and image extension mapping (#17200)
## Summary

This PR aligns the Go ingestion pipeline's **Laws** DSL template with
the Python implementation by fixing heading-detection gaps, adds
image-extension support, refactors the **Extractor** component's LLM
resolution, hardens heading detection for CJK text, and makes the
Extractor accept the Python DSL prompt key names
(`sys_prompt`/`prompts`) alongside the Go names.

## Changes

### 1. Picture file-type detection (`internal/utility/file.go`)

Adds explicit mapping for common image extensions (png, jpg, jpeg, gif,
bmp, tiff, tif, webp, svg, ico, avif, heic, apng) → `FileTypeVISUAL`,
with regression tests.

### 2. Laws DSL heading-detection alignment
(`internal/ingestion/component/chunker/`)

Four fixes to `resolveTitleLevels`:

| Fix | What changed | Why |
|-----|-------------|-----|
| **DOCX `ck_type` fallback** | `ckType` field on `lineRecord`,
propagated from `ChunkDoc.CKType` in `recordsFromStructured`. When
`ck_type=="heading"`, assign `fallbackLevel`. | office_oxide extracts
DOCX heading metadata, but the info was lost before reaching the heading
detector. Word headings whose text doesn't match any regex (e.g.
"Introduction") were treated as body. |
| **`make_colon_as_title` promotion** | `isColonTitle()`: promotes lines
ending with `:`/`:` that have sentence-ending punctuation before the
colon and ≥32 runes between them. | Mirrors Python's
`make_colon_as_title` in `rag/nlp/__init__.py`. Triple guard prevents
false positives. |
| **Short/numeric line filter** | Lines with ≤1 rune or purely numeric
are pinned to body level. | Mirrors Python `tree_merge`'s filter of
`sections` where `len(...) <= 1` or `re.match(r"[0-9]+$", ...)`. |
| **PDF `remove_toc`** | `"remove_toc": true` added to the PDF parser
setup in `ingestion_pipeline_laws.json`. | The Go PDF parser already
supports TOC removal; the Book template already enables it. |

### 3. Extractor llm_id resolution
(`internal/ingestion/component/extractor.go`)

Refactored to handle both **bare tenant_model UUIDs** and **composite
model@provider** strings via the shared `resolveModelConfig`
(`dispatch_model.go`):

- **`resolveExtractorChatConfig`** — UUID path calls
`resolveModelConfigByID` directly (one DB hit); composite path goes
through `resolveModelConfig`. Added `isBareTenantModelID` pre-check for
clear errors when a UUID doesn't exist.
- **`resolveExtractorChatTarget`** — propagates resolution errors
instead of silently returning empty driver.
- **`Chat()`** — removed `driver = "dummy"` fallback. Missing driver is
now an explicit error.
- **Removed dead code**: `splitExtractorLLID`,
`findExtractorSoleActiveInstance`.

### 4. `InjectExtractorLLMID` — fallback when no user config
(`internal/common/parser_config.go`)

Injects the tenant's global default LLM into extractor components **only
when their `llm_id` is empty**. Preserves user-selected UUID or
model@provider values.

Priority: user-configured llm_id > tenant global default > error (no
silent dummy fallback).

### 5. `ResponseHeaderTimeout` increase
(`internal/entity/models/base_model.go`)

`ResponseHeaderTimeout` 60s → 120s in `NewDriverHTTPClient`. Reasoning
models with large extraction prompts can take longer than 60s to produce
the first response token.

### 6. CJK rune-aware heading detection
(`internal/ingestion/component/chunker/title.go`)

Two byte-vs-rune bugs that only manifest on CJK text:

| Fix | What changed | Why |
|-----|-------------|-----|
| **`isColonTitle` byte offset** | `body[lastPunct+1:]` →
`body[lastPunct+runeLen:]` via `utf8.DecodeRuneInString` |
`strings.LastIndexAny` returns a byte index; `+1` skips only 1 byte,
corrupting multi-byte CJK punctuation (e.g. `。` = 3 bytes) and inflating
the rune count past the 32-rune threshold → false-positive heading
promotion. |
| **Short-line filter byte count** | `len(text) <= 1` →
`utf8.RuneCountInString(text) <= 1` | Go `len` is UTF-8 bytes; a single
CJK char (3 bytes) passed the filter, but Python's `len` returns 1 →
mismatch. |

### 7. `extractor_tag.go` — log error when llm fails

When `resolveExtractorChatTarget` returned an error, `runAutoTags` will
log error.

### 8. Python DSL prompt-key compatibility
(`internal/ingestion/component/extractor.go`)

The Resume DSL template uses Python-side key names (`sys_prompt`,
`prompts`). `NewExtractorComponent` now accepts them as fallbacks
alongside the Go names:

- `system_prompt` (Go) ← `sys_prompt` (Python) as fallback
- `prompt` (Go string) ← `prompts` (Python array `[{"role","content"}]`,
takes `[0].content`) as fallback

Mirrors the alias pattern already in `internal/agent/component/llm.go`.
`resolveInputs` accepts per-call `sys_prompt` override too.

## Remaining gaps vs Python

| Gap | Scope | Impact |
|-----|-------|--------|
| **TOC removal for TXT/MD/HTML** | Python's `remove_contents_table`
works on all text formats; Go's `remove_toc` is PDF-only. | Low —
plain-text documents rarely contain structured TOCs. |
| **Regex pattern details** | Minor differences in quantifiers, missing
H5/H6 markdown patterns, missing 4-level numbering pattern. | Low — Go's
variants are stricter; DOCX headings are covered by `ck_type` fallback.
|

## Testing

- `TestHierarchyTitleChunker_CKTypeHeadingFallback` — DOCX `ck_type`
heading promotion
- `TestHierarchyTitleChunker_ColonTitlePromotion` /
`_ColonTitleShortLine_Negative` — colon-title promotion + guard
- `TestIsColonTitle_CJKEdgeCase` / `TestIsColonTitle_ASCII_NoRegression`
— CJK byte-offset fix + ASCII regression
- `TestHierarchyTitleChunker_ColonTitlePromotion_CJK_EdgeCase` — CJK
colon edge case through full pipeline
- `TestHierarchyTitleChunker_ShortSingleCJKLineFilter` — single CJK char
filtered to body
- `TestHierarchyTitleChunker_ShortNumericLineFilter` — purely numeric
lines filtered
- `TestGetFileType_ImageExtensions` / `_ExistingFormats_NoRegression` —
image extension mapping
- `TestInjectExtractorLLMID_SkipWhenUUID` / `_SkipWhenComposite` /
`_InjectWhenEmpty` — llm_id injection guard
- `TestIsBareTenantModelID` — UUID detection
- `TestResolveExtractorChatTarget_AtSplitFallback` / `_NoDriver` — @
split fallback without DB
- `TestNewExtractorComponent_SysPromptAlias` / `_PromptsArray` /
`_PromptsArray_PromptWins` / `_SystemPromptWinsOverSysPrompt` — Python
key compatibility
- `TestBuildDOCXJSONSections_List` / `_TextBox` / `_MixedWithList` —
DOCX list/text_box parsing
- Full ingestion test suite passes (chunker, pipeline, task, service,
component packages)
2026-07-22 19:14:32 +08:00

413 lines
12 KiB
Go

//
// 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.
//
// SCOPE (honest) for group.go:
//
// - Implements the GroupTitleChunker variant: aggregates adjacent
// text records into chunks that span multiple body records while
// staying inside one heading section.
//
// Heading detection stays sequential; grouping work is local to
// one invocation.
//
// - MIRRORS python `_build_section_ids` + `GroupTitleChunker.build_chunks`:
// consecutive records with the same (target_level-derived) sec_id
// are merged up to MIN_GROUP_TOKENS / MAX_GROUP_TOKENS, then
// emitted as one chunk per group.
//
// - No PDF-position merge is performed (mirrors TokenChunker SCOPE
// notes — those land with the deepdoc/parser port).
package chunker
import (
"context"
"encoding/json"
"fmt"
"strings"
"go.uber.org/zap"
"ragflow/internal/agent/runtime"
"ragflow/internal/common"
"ragflow/internal/ingestion/component/globals"
"ragflow/internal/ingestion/component/schema"
"ragflow/internal/tokenizer"
)
const ComponentNameGroupTitleChunker = "GroupTitleChunker"
// MIN_GROUP_TOKENS / MAX_GROUP_TOKENS mirror the python constants in
// group_chunker.py:22-23. They drive the merge heuristic for adjacent
// text records.
const (
minGroupTokens = 32
maxGroupTokens = 1024
)
// resolveTargetLevel mirrors common.py:resolve_target_level: pick the
// n-th smallest heading level from the per-line `levels` vector.
func resolveTargetLevel(levels []int, hierarchy int) int {
tiers := make([]int, 0, len(levels))
seen := make(map[int]bool)
for _, l := range levels {
if l > 0 && l < bodyLevel && !seen[l] {
seen[l] = true
tiers = append(tiers, l)
}
}
if len(tiers) == 0 {
return 0
}
// ascending
for i := 1; i < len(tiers); i++ {
for j := i; j > 0 && tiers[j-1] > tiers[j]; j-- {
tiers[j-1], tiers[j] = tiers[j], tiers[j-1]
}
}
if hierarchy < 1 {
hierarchy = 1
}
if hierarchy > len(tiers) {
hierarchy = len(tiers)
}
return tiers[hierarchy-1]
}
// _buildSectionIDs computes, for each input level, the section id
// (`sid`) under which that record falls. Each heading encounter
// increments sid by 1; body lines share the active sid.
func buildSectionIDs(levels []int, targetLevel int) []int {
secIDs := make([]int, len(levels))
sid := 0
for i, lvl := range levels {
if i > 0 && targetLevel > 0 && lvl <= targetLevel {
sid++
}
secIDs[i] = sid
}
return secIDs
}
// invokeGroup runs the GroupTitleChunker strategy against the
// supplied inputs. Detected headings + adjacent merges happen in two
// goroutines (heading detection sequential, then a fan-out over
// record-buckets for the merge pass).
func invokeGroup(_ context.Context, inputs map[string]any, p *titleChunkerParam) (map[string]any, error) {
records := extractLineRecords(inputs)
common.Debug("chunker stage",
zap.String("component", "Chunker"),
zap.String("variant", "group"),
zap.Int("records", len(records)),
)
if len(records) == 0 {
return emptyOutputs(), nil
}
ctx := newLevelContext(records, p)
levels := ctx.Levels()
// Count heading level distribution for debugging.
headingCounts := make(map[int]int)
for _, lvl := range levels {
if lvl < bodyLevel {
headingCounts[lvl]++
}
}
bodyCount := len(levels)
for _, c := range headingCounts {
bodyCount -= c
}
common.Debug("chunker stage",
zap.String("component", "Chunker"),
zap.String("variant", "group"),
zap.Int("records", len(records)),
zap.Int("body_level", bodyCount),
zap.Any("heading_levels", headingCounts),
)
// Mirror python group_chunker._resolve_group_target_level: when
// `hierarchy` is unset the target level is `most_level` directly
// (NOT resolve_target_level — that would re-rank the distinct
// heading levels and pick the wrong depth when the heading levels
// are not contiguous from 1). When `hierarchy` is set, it defers to
// resolve_target_level.
targetLevel := resolveGroupTargetLevel(levels, p, ctx.mostLevel)
secIDs := buildSectionIDs(levels, targetLevel)
groups := groupRecords(records, secIDs, p)
common.Debug("chunker stage",
zap.String("component", "Chunker"),
zap.String("variant", "group"),
zap.Int("groups", len(groups)),
)
chunks := buildChunksFromRecordGroups(groups, p, isPlainTextFormat(inputs))
common.Debug("chunker stage",
zap.String("component", "Chunker"),
zap.String("variant", "group"),
zap.Int("chunks", len(chunks)),
zap.Bool("plain_text", isPlainTextFormat(inputs)),
)
if len(chunks) == 0 {
return emptyOutputs(), nil
}
out := map[string]any{
"output_format": "chunks",
"chunks": chunks,
}
return out, nil
}
// groupRecords mirrors `GroupTitleChunker.build_chunks`: merges
// adjacent text records while staying inside the same logical section
// (matching last_sid) and token-budget constraints.
func groupRecords(records []lineRecord, secIDs []int, p *titleChunkerParam) [][]lineRecord {
if len(records) == 0 {
return nil
}
var recordGroups [][]lineRecord
var currentGroup []lineRecord
tkCnt := 0
lastSID := -2
for i, rec := range records {
secID := secIDs[i]
if !rec.isText() {
if len(currentGroup) > 0 {
recordGroups = append(recordGroups, append([]lineRecord(nil), currentGroup...))
}
recordGroups = append(recordGroups, []lineRecord{rec})
currentGroup = currentGroup[:0]
tkCnt = 0
lastSID = -2
continue
}
text := trim(rec.text)
if text == "" {
continue
}
tokenCount := tokenizer.NumTokensFromString(text)
shouldMerge := len(currentGroup) > 0 &&
currentGroup[0].isText() &&
(tkCnt < minGroupTokens || (tkCnt < maxGroupTokens && secID == lastSID))
if shouldMerge {
currentGroup = append(currentGroup, rec)
tkCnt += tokenCount
} else {
if len(currentGroup) > 0 {
recordGroups = append(recordGroups, append([]lineRecord(nil), currentGroup...))
}
currentGroup = []lineRecord{rec}
tkCnt = tokenCount
}
lastSID = secID
}
if len(currentGroup) > 0 {
recordGroups = append(recordGroups, currentGroup)
}
return recordGroups
}
// joinGroupText mirrors python's `"".join(record["text"] + "\n" for
// record in records)` — every record's text followed by a newline
// (including the last), matching the python text join exactly.
func joinGroupText(g []lineRecord) string {
var sb strings.Builder
for _, r := range g {
sb.WriteString(r.text)
sb.WriteByte('\n')
}
return sb.String()
}
// isPlainTextFormat mirrors the `output_format in ["markdown", "text",
// "html"]` branch of common.py:build_chunks_from_record_groups. Plain
// payloads emit only "text"; structured payloads (chunks/json) also
// carry doc_type_kwd and img_id.
func isPlainTextFormat(inputs map[string]any) bool {
if f, ok := inputs["output_format"].(string); ok {
return f == "markdown" || f == "text" || f == "html"
}
return false
}
// buildChunksFromRecordGroups mirrors common.py:build_chunks_from_record_groups
// (minus the deepdoc-only remove_tag / merge_pdf_positions steps):
// - plain payloads: {"text": joined}
// - structured payloads: text plus doc_type_kwd / img_id from the
// group's leading record.
//
// root_chunk_as_heading is applied here, exactly as python does (post
// materialisation): the root chunk's text is prepended to every
// following chunk and the root chunk is dropped.
func buildChunksFromRecordGroups(groups [][]lineRecord, p *titleChunkerParam, plain bool) []map[string]any {
chunks := make([]map[string]any, 0, len(groups))
for _, g := range groups {
if len(g) == 0 {
continue
}
chunk := map[string]any{"text": joinGroupText(g)}
if !plain {
first := g[0]
if first.docType != "" {
chunk["doc_type_kwd"] = first.docType
}
if first.imgID != nil {
chunk["img_id"] = *first.imgID
}
}
chunks = append(chunks, chunk)
}
if p.RootChunkAsHeading && len(chunks) > 1 {
rootText := toString(chunks[0]["text"])
for i := 1; i < len(chunks); i++ {
chunks[i]["text"] = rootText + "\n" + toString(chunks[i]["text"])
}
chunks = chunks[1:]
}
return chunks
}
// extractLineRecords reads the chunker inputs in the same order the
// python BaseTitleChunker.extract_line_records uses:
//
// 1. If upstream emitted chunks (output_format == "chunks") OR
// upstream emitted JSON, normalise from the list payload.
// 2. Otherwise, treat text/markdown/html as a "one record per line"
// stream (preserving indentation for non-text formats, strip-only
// for the text format).
func extractLineRecords(inputs map[string]any) []lineRecord {
if docs := chunksFromInputs(inputs); docs != nil {
return recordsFromStructured(docs)
}
text, _ := stringFromInputs(inputs, "text", "content", "markdown", "html")
if text == "" {
return nil
}
return lineRecordsFromText(text)
}
func recordsFromStructured(items []schema.ChunkDoc) []lineRecord {
out := make([]lineRecord, 0, len(items))
for _, it := range items {
text := itemTextOrFallback(it)
if text == "" {
continue
}
dt := it.DocType
if dt == "" {
dt = "text"
}
var imgID *string
if it.ImgID != "" {
img := it.ImgID
imgID = &img
}
meta := make(map[string]any)
if it.ContentLtks != "" {
meta["content_ltks"] = it.ContentLtks
}
if it.ContentSmLtks != "" {
meta["content_sm_ltks"] = it.ContentSmLtks
}
if it.ContentWithWeight != "" {
meta["content_with_weight"] = it.ContentWithWeight
}
if it.TitleTks != "" {
meta["title_tks"] = it.TitleTks
}
if it.TitleSmTks != "" {
meta["title_sm_tks"] = it.TitleSmTks
}
for k, v := range it.Extra {
meta[k] = json.RawMessage(v)
}
out = append(out, lineRecord{
text: text,
docType: dt,
imgID: imgID,
layout: it.Layout,
ckType: it.CKType,
parentMeta: meta,
})
}
return out
}
// resolveGroupTargetLevel mirrors group_chunker._resolve_group_target_level:
// when `hierarchy` is set (>0) the target depth is resolve_target_level,
// otherwise it is the frequency-derived `most_level` directly.
func resolveGroupTargetLevel(levels []int, p *titleChunkerParam, mostLevel int) int {
if p.Hierarchy != nil && *p.Hierarchy > 0 {
return resolveTargetLevel(levels, *p.Hierarchy)
}
return mostLevel
}
// GroupTitleChunkerComponent is the standalone variant entry point.
// It is registered separately so canvas authors can pick the strategy
// directly. TitleChunker's dispatcher routes to invokeGroup /
// invokeHierarchy as well.
type GroupTitleChunkerComponent struct {
name string
param titleChunkerParam
}
// NewGroupTitleChunker constructs the variant component with method
// pre-set to "group".
func NewGroupTitleChunker(params map[string]any) (runtime.Component, error) {
conf := map[string]any{"method": "group"}
for k, v := range params {
conf[k] = v
}
p := defaultsTitle()
p.Update(conf)
if err := p.TitleChunkerParam.Validate(); err != nil {
return nil, fmt.Errorf("GroupTitleChunker: %w", err)
}
return &GroupTitleChunkerComponent{
name: ComponentNameGroupTitleChunker,
param: p,
}, nil
}
func (c *GroupTitleChunkerComponent) Inputs() map[string]string {
return ChunkerInputs
}
func (c *GroupTitleChunkerComponent) Outputs() map[string]string {
return ChunkerOutputs
}
func (c *GroupTitleChunkerComponent) Invoke(ctx context.Context, inputs map[string]any) (map[string]any, error) {
if inputs == nil {
inputs = map[string]any{}
}
// `name` is read from the workflow-wide Globals bag (seeded at
// pipeline start, published by the File component), not from the
// upstream output map.
name := globals.GlobalOrInput(ctx, inputs, "name", "")
if name == "" {
return map[string]any{
"output_format": "chunks",
"chunks": []map[string]any{},
"_ERROR": "GroupTitleChunker: missing required upstream field \"name\"",
}, nil
}
return invokeGroup(ctx, withName(inputs, name), &c.param)
}
// init registers GroupTitleChunker under CategoryIngestion.
func init() {
MustRegisterChunker(ComponentNameGroupTitleChunker)
}