mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-07-23 17:06:42 +08:00
## 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)
152 lines
3.9 KiB
Go
152 lines
3.9 KiB
Go
package common
|
|
|
|
import "strings"
|
|
|
|
// InjectExtractorLLMID finds all Extractor component entries (keys prefixed
|
|
// with "extractor:" or "extractor_") in parserConfig and sets their llm_id
|
|
// to the given value. Returns whether any entry was updated.
|
|
func InjectExtractorLLMID(parserConfig map[string]interface{}, llmID string) bool {
|
|
if parserConfig == nil || llmID == "" {
|
|
return false
|
|
}
|
|
updated := false
|
|
for cid, raw := range parserConfig {
|
|
compMap, ok := raw.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
cidLower := strings.ToLower(cid)
|
|
if strings.HasPrefix(cidLower, "extractor:") || strings.HasPrefix(cidLower, "extractor_") {
|
|
if current, ok := compMap["llm_id"].(string); !ok || current == "" {
|
|
compMap["llm_id"] = llmID
|
|
updated = true
|
|
}
|
|
}
|
|
}
|
|
return updated
|
|
}
|
|
|
|
// deepCopyMap duplicates a JSON-like map so later merges do not mutate shared defaults.
|
|
func deepCopyMap(source map[string]interface{}) map[string]interface{} {
|
|
if source == nil {
|
|
return nil
|
|
}
|
|
|
|
cloned := make(map[string]interface{}, len(source))
|
|
for key, value := range source {
|
|
cloned[key] = deepCopyValue(value)
|
|
}
|
|
return cloned
|
|
}
|
|
|
|
// deepCopyValue recursively copies nested maps and slices inside parser_config values.
|
|
func deepCopyValue(value interface{}) interface{} {
|
|
switch typedValue := value.(type) {
|
|
case map[string]interface{}:
|
|
return deepCopyMap(typedValue)
|
|
case []interface{}:
|
|
cloned := make([]interface{}, len(typedValue))
|
|
for idx, item := range typedValue {
|
|
cloned[idx] = deepCopyValue(item)
|
|
}
|
|
return cloned
|
|
default:
|
|
return typedValue
|
|
}
|
|
}
|
|
|
|
// DeepMergeMaps applies override onto base while preserving nested defaults such as raptor/graphrag.
|
|
func DeepMergeMaps(base, override map[string]interface{}) map[string]interface{} {
|
|
merged := deepCopyMap(base)
|
|
if merged == nil {
|
|
merged = make(map[string]interface{})
|
|
}
|
|
if override == nil {
|
|
return merged
|
|
}
|
|
|
|
for key, value := range override {
|
|
overrideMap, overrideIsMap := value.(map[string]interface{})
|
|
existingMap, existingIsMap := merged[key].(map[string]interface{})
|
|
if overrideIsMap && existingIsMap {
|
|
merged[key] = DeepMergeMaps(existingMap, overrideMap)
|
|
continue
|
|
}
|
|
merged[key] = deepCopyValue(value)
|
|
}
|
|
return merged
|
|
}
|
|
|
|
// GetParserConfig builds the final parser_config stored on a dataset:
|
|
// base defaults -> chunk-method defaults -> caller overrides.
|
|
func GetParserConfig(parserID string, parserConfig map[string]interface{}) map[string]interface{} {
|
|
baseDefaults := map[string]interface{}{
|
|
"table_context_size": 0,
|
|
"image_context_size": 0,
|
|
}
|
|
|
|
defaultConfigs := map[string]map[string]interface{}{
|
|
"naive": {
|
|
"layout_recognize": "DeepDOC",
|
|
"chunk_token_num": 512,
|
|
"delimiter": "\n",
|
|
"auto_keywords": 0,
|
|
"auto_questions": 0,
|
|
"html4excel": false,
|
|
"topn_tags": 3,
|
|
},
|
|
"qa": nil,
|
|
"resume": nil,
|
|
"manual": nil,
|
|
"paper": nil,
|
|
"book": nil,
|
|
"laws": nil,
|
|
"presentation": nil,
|
|
}
|
|
|
|
merged := DeepMergeMaps(baseDefaults, defaultConfigs[parserID])
|
|
return DeepMergeMaps(merged, parserConfig)
|
|
}
|
|
|
|
func ExtractPipelineDefaults(dsl map[string]interface{}) map[string]interface{} {
|
|
if dsl == nil {
|
|
return nil
|
|
}
|
|
if inner, ok := dsl["dsl"].(map[string]interface{}); ok {
|
|
dsl = inner
|
|
}
|
|
components, _ := dsl["components"].(map[string]interface{})
|
|
if components == nil {
|
|
return nil
|
|
}
|
|
|
|
result := make(map[string]interface{})
|
|
hasAny := false
|
|
for cid, compVal := range components {
|
|
compMap, ok := compVal.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
obj, _ := compMap["obj"].(map[string]interface{})
|
|
if obj == nil {
|
|
continue
|
|
}
|
|
name, _ := obj["component_name"].(string)
|
|
if name == "" || name == "File" {
|
|
continue
|
|
}
|
|
params, _ := obj["params"].(map[string]interface{})
|
|
if params == nil {
|
|
continue
|
|
}
|
|
copy_ := deepCopyMap(params)
|
|
delete(copy_, "outputs")
|
|
result[cid] = copy_
|
|
hasAny = true
|
|
}
|
|
if !hasAny {
|
|
return nil
|
|
}
|
|
return result
|
|
}
|