feat(backend): improve parent-child chunk merge and imageinfo matching

Scope image info to matched text children during parent resolution and
add range/URL filtering utilities with unit tests.
This commit is contained in:
wizardchen
2026-06-16 00:49:16 +08:00
committed by lyingbug
parent 8dbc20b9b3
commit 2906c6656e
7 changed files with 457 additions and 128 deletions
+46
View File
@@ -260,6 +260,52 @@ func EnrichContentWithImageInfo(content string, imageInfoJSON string) string {
return content
}
// EnrichContentWithImageInfoForChat is like EnrichContentWithImageInfo but only
// wraps Markdown images that have a matching image_info entry. This avoids
// turning every parent thumbnail into an <image> block when only a few pages
// were retrieved, and skips appending orphan image_info extras.
func EnrichContentWithImageInfoForChat(content string, imageInfoJSON string) string {
var imageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil {
return content
}
if len(imageInfos) == 0 {
return content
}
imageInfoMap := make(map[string]*types.ImageInfo)
for i := range imageInfos {
if imageInfos[i].URL != "" {
imageInfoMap[imageInfos[i].URL] = &imageInfos[i]
}
if imageInfos[i].OriginalURL != "" {
imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i]
}
}
matches := MarkdownImageRegex.FindAllStringSubmatch(content, -1)
for _, match := range matches {
if len(match) < 3 {
continue
}
imgURL := match[2]
imgInfo, found := imageInfoMap[imgURL]
if !found || imgInfo == nil {
continue
}
inner := BuildImageInfoXML(imgInfo)
if inner == "" {
continue
}
var b strings.Builder
b.WriteString(fmt.Sprintf("<image url=\"%s\">\n", imgURL))
b.WriteString(inner)
b.WriteString("</image>")
content = strings.Replace(content, match[0], b.String(), 1)
}
return content
}
// BuildImageInfoXML returns XML-tagged caption / ocr for one image.
func BuildImageInfoXML(img *types.ImageInfo) string {
var b strings.Builder
+148
View File
@@ -0,0 +1,148 @@
package searchutil
import (
"encoding/json"
"strings"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/types"
)
// SliceContentByDocumentRange extracts the substring of content whose
// document-level rune offsets fall within [rangeStart, rangeEnd).
// contentStartAt is the document offset where content begins.
func SliceContentByDocumentRange(content string, contentStartAt, rangeStart, rangeEnd int) string {
if content == "" {
return content
}
relStart := rangeStart - contentStartAt
relEnd := rangeEnd - contentStartAt
runes := []rune(content)
if relStart < 0 {
relStart = 0
}
if relEnd > len(runes) {
relEnd = len(runes)
}
if relStart >= relEnd {
return ""
}
return string(runes[relStart:relEnd])
}
// ImageURLsInContent returns the set of image URLs referenced as Markdown
// images in content.
func ImageURLsInContent(content string) map[string]bool {
urls := make(map[string]bool)
for _, match := range MarkdownImageRegex.FindAllStringSubmatch(content, -1) {
if len(match) < 3 || match[2] == "" {
continue
}
urls[match[2]] = true
}
return urls
}
// FilterImageInfoByContentURLs keeps only image_info entries whose URL or
// OriginalURL appears as a Markdown image in content. Returns empty string
// when nothing matches or imageInfoJSON is invalid.
func FilterImageInfoByContentURLs(content string, imageInfoJSON string) string {
if imageInfoJSON == "" {
return ""
}
var infos []types.ImageInfo
if err := json.Unmarshal([]byte(imageInfoJSON), &infos); err != nil || len(infos) == 0 {
return ""
}
urls := ImageURLsInContent(content)
if len(urls) == 0 {
return ""
}
filtered := make([]types.ImageInfo, 0, len(infos))
for _, info := range infos {
if urls[info.URL] || urls[info.OriginalURL] {
filtered = append(filtered, info)
}
}
return marshalImageInfos(filtered)
}
// FilterImageInfoByMatchRange keeps image_info entries whose Markdown image
// reference falls within the document rune range [matchStart, matchEnd).
// Used when parent content is expanded for context but multimodal enrichment
// should only cover the retrieved child window.
func FilterImageInfoByMatchRange(
parentContent string,
parentStartAt, matchStart, matchEnd int,
imageInfoJSON string,
) string {
if imageInfoJSON == "" {
return ""
}
var infos []types.ImageInfo
if err := json.Unmarshal([]byte(imageInfoJSON), &infos); err != nil || len(infos) == 0 {
return ""
}
window := SliceContentByDocumentRange(parentContent, parentStartAt, matchStart, matchEnd)
urls := ImageURLsInContent(window)
if len(urls) == 0 {
return ""
}
filtered := make([]types.ImageInfo, 0, len(infos))
for _, info := range infos {
if urls[info.URL] || urls[info.OriginalURL] {
filtered = append(filtered, info)
}
}
return marshalImageInfos(filtered)
}
func marshalImageInfos(infos []types.ImageInfo) string {
if len(infos) == 0 {
return ""
}
data, err := json.Marshal(infos)
if err != nil {
return ""
}
return string(data)
}
// PruneMarkdownImagesOutsideRange removes Markdown image lines whose
// document-level rune offsets fall outside [matchStart, matchEnd). Non-image
// text is preserved so parent-child expansion still provides full textual
// context while dropping irrelevant page thumbnails.
func PruneMarkdownImagesOutsideRange(
content string,
contentStartAt, matchStart, matchEnd int,
) string {
locs := MarkdownImageRegex.FindAllStringIndex(content, -1)
if len(locs) == 0 {
return content
}
var b strings.Builder
last := 0
for _, loc := range locs {
if loc[0] < last || loc[1] > len(content) {
continue
}
docStart := contentStartAt + utf8.RuneCountInString(content[:loc[0]])
docEnd := contentStartAt + utf8.RuneCountInString(content[:loc[1]])
inRange := docStart < matchEnd && docEnd > matchStart
if inRange {
b.WriteString(content[last:loc[1]])
} else {
b.WriteString(content[last:loc[0]])
}
last = loc[1]
}
b.WriteString(content[last:])
return collapseBlankLines(b.String())
}
func collapseBlankLines(s string) string {
for strings.Contains(s, "\n\n\n") {
s = strings.ReplaceAll(s, "\n\n\n", "\n\n")
}
return strings.TrimSpace(s)
}
@@ -0,0 +1,95 @@
package searchutil
import (
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestSliceContentByDocumentRange(t *testing.T) {
parent := "aaaPAGE1bbbPAGE2ccc"
got := SliceContentByDocumentRange(parent, 100, 103, 108)
want := "PAGE1"
if got != want {
t.Fatalf("slice: got %q, want %q", got, want)
}
}
func TestFilterImageInfoByMatchRange(t *testing.T) {
parent := "![p1](u1)\n\n![p2](u2)\n\n![p3](u3)"
matchStart := len([]rune("![p1](u1)\n\n"))
matchEnd := matchStart + len([]rune("![p2](u2)"))
all := []types.ImageInfo{
{URL: "u1"}, {URL: "u2"}, {URL: "u3"},
}
raw, err := json.Marshal(all)
if err != nil {
t.Fatal(err)
}
got := FilterImageInfoByMatchRange(parent, 0, matchStart, matchEnd, string(raw))
var filtered []types.ImageInfo
if err := json.Unmarshal([]byte(got), &filtered); err != nil {
t.Fatal(err)
}
if len(filtered) != 1 || filtered[0].URL != "u2" {
t.Fatalf("filtered: %+v", filtered)
}
}
func TestFilterImageInfoByContentURLs(t *testing.T) {
content := "intro\n![page3](local://img3.jpg)\noutro"
all := []types.ImageInfo{
{URL: "local://img1.jpg", OCRText: "one"},
{URL: "local://img3.jpg", OCRText: "three"},
}
raw, err := json.Marshal(all)
if err != nil {
t.Fatal(err)
}
got := FilterImageInfoByContentURLs(content, string(raw))
var filtered []types.ImageInfo
if err := json.Unmarshal([]byte(got), &filtered); err != nil {
t.Fatalf("unmarshal filtered: %v", err)
}
if len(filtered) != 1 || filtered[0].URL != "local://img3.jpg" {
t.Fatalf("filtered: %+v", filtered)
}
}
func TestPruneMarkdownImagesOutsideRange(t *testing.T) {
parent := "![p1](u1)\n\n![p2](u2)\n\n![p3](u3)"
matchStart := len([]rune("![p1](u1)\n\n"))
matchEnd := matchStart + len([]rune("![p2](u2)"))
got := PruneMarkdownImagesOutsideRange(parent, 0, matchStart, matchEnd)
if got != "![p2](u2)" {
t.Fatalf("prune: got %q", got)
}
}
func TestEnrichContentWithImageInfoForChat_SkipsUnmatched(t *testing.T) {
content := "![p1](u1)\n\n![p2](u2)"
raw, _ := json.Marshal([]types.ImageInfo{{URL: "u2", OCRText: "two"}})
got := EnrichContentWithImageInfoForChat(content, string(raw))
if strings.Count(got, "<image url=") != 1 {
t.Fatalf("expected one image block, got: %s", got)
}
if !strings.Contains(got, "![p1](u1)") {
t.Fatalf("unmatched markdown should remain: %s", got)
}
if !strings.Contains(got, "<image_ocr>two</image_ocr>") {
t.Fatalf("matched image should be enriched: %s", got)
}
if strings.Contains(got, "<image_original>") {
t.Fatalf("chat enrich should not duplicate markdown in image_original: %s", got)
}
}
func TestImageURLsInContent(t *testing.T) {
content := "![a](u1) x ![b](u2)"
urls := ImageURLsInContent(content)
if !urls["u1"] || !urls["u2"] || len(urls) != 2 {
t.Fatalf("urls: %#v", urls)
}
}