diff --git a/internal/application/service/knowledge_post_process_graph_chunks_test.go b/internal/application/service/knowledge_post_process_graph_chunks_test.go index a7801dfb..1fddd6e1 100644 --- a/internal/application/service/knowledge_post_process_graph_chunks_test.go +++ b/internal/application/service/knowledge_post_process_graph_chunks_test.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/json" + "strings" "testing" "github.com/Tencent/WeKnora/internal/types" @@ -67,6 +68,114 @@ func TestSelectGraphChunks(t *testing.T) { assert.Equal(t, []string{"ocr-scanned", "text-prose", "ocr-orphan"}, gotIDs) } +func TestWikiIngestKeepsScannedPageOCR(t *testing.T) { + page := func(page int) types.SourceLocators { + return types.SourceLocators{{Type: types.SourceLocatorPDF, Page: page}} + } + chunks := []*types.Chunk{ + { + ID: "text-link", ChunkType: types.ChunkTypeText, IsEnabled: true, ChunkIndex: 2, + Content: "![page_1.jpg](resource://abc)", + }, + { + ID: "ocr-scanned", ChunkType: types.ChunkTypeImageOCR, IsEnabled: true, + ParentChunkID: "text-link", ChunkIndex: 0, SourceLocators: page(1), + Content: "第1章 総則 本标准规定了扫描件正文。", + }, + { + ID: "cap-scanned", ChunkType: types.ChunkTypeImageCaption, IsEnabled: true, + ParentChunkID: "text-link", Content: "a scanned page", + }, + { + ID: "text-prose", ChunkType: types.ChunkTypeText, IsEnabled: true, ChunkIndex: 1, + Content: "Contract between Alice and Bob.", + }, + { + ID: "ocr-figure", ChunkType: types.ChunkTypeImageOCR, IsEnabled: true, + ParentChunkID: "text-prose", Content: "ACME logo", + }, + { + ID: "ocr-page2", ChunkType: types.ChunkTypeImageOCR, IsEnabled: true, + ParentChunkID: "text-link", ChunkIndex: 0, SourceLocators: page(2), + Content: "第二节 扫描页应当排在第一章之后。", + }, + { + ID: "ocr-off", ChunkType: types.ChunkTypeImageOCR, IsEnabled: false, + ParentChunkID: "text-link", Content: "这条识别结果已经停用。", + }, + } + + scanned := appendScannedPageText( + reconstructEnrichedContent(context.Background(), nil, 1, chunks[:3]), + chunks[:3], + ) + if !strings.Contains(scanned, "第1章 総則") || strings.Contains(scanned, "a scanned page") { + t.Fatalf("scanned wiki content = %q", scanned) + } + if !hasSufficientTextContent(scanned) { + t.Fatal("scanned OCR should be enough text for wiki extraction") + } + if strings.Count(scanned, "第1章 総則") != 1 { + t.Fatalf("OCR was repeated: %q", scanned) + } + + already := appendScannedPageText(scanned, chunks[:3]) + if already != scanned { + t.Fatalf("inlined OCR was appended again: %q", already) + } + + mixed := appendScannedPageText( + reconstructEnrichedContent(context.Background(), nil, 1, []*types.Chunk{chunks[0], chunks[3]}), + chunks, + ) + if !strings.Contains(mixed, "Contract between Alice and Bob.") || !strings.Contains(mixed, "第1章 総則") { + t.Fatalf("mixed document dropped scanned OCR: %q", mixed) + } + chapter := strings.Index(mixed, "第1章 総則") + section := strings.Index(mixed, "第二节") + if chapter < 0 || section < chapter { + t.Fatalf("scanned pages are out of order: %q", mixed) + } + if strings.Contains(mixed, "ACME logo") || strings.Contains(mixed, "已经停用") { + t.Fatalf("figure or disabled OCR was appended: %q", mixed) + } + + disabledParent := []*types.Chunk{ + { + ID: "text-link", ChunkType: types.ChunkTypeText, IsEnabled: false, + Content: "![page](resource://abc)", + }, + { + ID: "ocr-scanned", ChunkType: types.ChunkTypeImageOCR, IsEnabled: true, + ParentChunkID: "text-link", Content: "第1章 総則 本标准规定了扫描件正文。", + }, + } + if got := appendScannedPageText("", disabledParent); got != "" { + t.Fatalf("disabled parent still contributed OCR: %q", got) + } + + cited := wikiCitationChunks(chunks) + var parent, prose *types.Chunk + for _, c := range cited { + switch c.ID { + case "text-link": + parent = c + case "text-prose": + prose = c + } + } + if parent == nil || !strings.Contains(parent.Content, "第1章 総則") || + !strings.Contains(parent.Content, "第二节") { + t.Fatalf("citation parent = %#v", parent) + } + if prose == nil || strings.Contains(prose.Content, "ACME logo") { + t.Fatalf("citation prose = %#v", prose) + } + if chunks[0].Content != "![page_1.jpg](resource://abc)" { + t.Fatal("citation copies mutated the stored text chunk") + } +} + func TestKnowledgePostProcessGraphEnqueueSelection(t *testing.T) { t.Setenv("NEO4J_ENABLE", "true") diff --git a/internal/application/service/wiki_ingest.go b/internal/application/service/wiki_ingest.go index ef523b00..307ea529 100644 --- a/internal/application/service/wiki_ingest.go +++ b/internal/application/service/wiki_ingest.go @@ -3183,6 +3183,134 @@ func reconstructEnrichedContent( return searchutil.EnrichContentWithImageInfo(content, mergedImageInfo) } +// appendScannedPageText adds OCR from pages whose parent text is only an +// image link. reconstructEnrichedContent inlines image_info when that JSON +// exists; scanned pages often keep the recognized text only on the image_ocr +// chunk. A document that already has some prose still receives those pages. +// Disabled chunks, OCR beside real prose, and text already present are left out. +func appendScannedPageText(content string, chunks []*types.Chunk) string { + var b strings.Builder + b.WriteString(content) + written := content + for _, c := range scannedOCRForWiki(chunks) { + text := strings.TrimSpace(c.Content) + if text == "" || strings.Contains(written, text) { + continue + } + if b.Len() > 0 { + b.WriteByte('\n') + } + b.WriteString(text) + written = b.String() + } + return b.String() +} + +// wikiCitationChunks gives the citation pass the scanned-page OCR on the +// parent text chunk. splitChunksIntoCitationBatches only reads text chunks, +// so an image-link parent would otherwise be cited without the page text. +// The returned chunks are copies; stored rows are not changed. +func wikiCitationChunks(chunks []*types.Chunk) []*types.Chunk { + ocrByParent := map[string][]*types.Chunk{} + var orphans []*types.Chunk + for _, c := range scannedOCRForWiki(chunks) { + if c.ParentChunkID == "" { + orphans = append(orphans, c) + continue + } + ocrByParent[c.ParentChunkID] = append(ocrByParent[c.ParentChunkID], c) + } + out := make([]*types.Chunk, 0, len(chunks)+len(orphans)) + for _, c := range chunks { + if c == nil || !c.IsEnabled { + continue + } + if c.ChunkType != types.ChunkTypeText && c.ChunkType != "" { + continue + } + ocrs := ocrByParent[c.ID] + if len(ocrs) == 0 || chunkHasExtractableText(c.Content) { + out = append(out, c) + continue + } + clone := *c + var b strings.Builder + b.WriteString(c.Content) + for _, o := range ocrs { + text := strings.TrimSpace(o.Content) + if text == "" || strings.Contains(b.String(), text) { + continue + } + b.WriteByte('\n') + b.WriteString(text) + } + clone.Content = b.String() + out = append(out, &clone) + } + for _, o := range orphans { + clone := *o + clone.ChunkType = types.ChunkTypeText + out = append(out, &clone) + } + return out +} + +// scannedOCRForWiki returns enabled OCR chunks whose parent is only an image +// link, ordered by the parent text chunk and then the PDF page. +func scannedOCRForWiki(chunks []*types.Chunk) []*types.Chunk { + parentIndex := make(map[string]int, len(chunks)) + disabledParent := make(map[string]bool) + for _, c := range chunks { + if c == nil || (c.ChunkType != types.ChunkTypeText && c.ChunkType != "") { + continue + } + parentIndex[c.ID] = c.ChunkIndex + if !c.IsEnabled { + disabledParent[c.ID] = true + } + } + enabled := make([]*types.Chunk, 0, len(chunks)) + for _, c := range chunks { + if c == nil || !c.IsEnabled || disabledParent[c.ParentChunkID] { + continue + } + enabled = append(enabled, c) + } + var ocr []*types.Chunk + for _, c := range selectGraphChunks(enabled) { + if c != nil && c.ChunkType == types.ChunkTypeImageOCR { + ocr = append(ocr, c) + } + } + sort.SliceStable(ocr, func(i, j int) bool { + pi, pj := parentIndex[ocr[i].ParentChunkID], parentIndex[ocr[j].ParentChunkID] + if pi != pj { + return pi < pj + } + pageI, pageJ := pdfPageOf(ocr[i]), pdfPageOf(ocr[j]) + if pageI != pageJ { + return pageI < pageJ + } + if ocr[i].ChunkIndex != ocr[j].ChunkIndex { + return ocr[i].ChunkIndex < ocr[j].ChunkIndex + } + return ocr[i].StartAt < ocr[j].StartAt + }) + return ocr +} + +func pdfPageOf(c *types.Chunk) int { + if c == nil { + return 0 + } + for _, loc := range c.SourceLocators { + if loc.Type == types.SourceLocatorPDF && loc.Page > 0 { + return loc.Page + } + } + return 0 +} + // slugify creates a URL-friendly slug from a string func slugify(s string) string { s = strings.ToLower(strings.TrimSpace(s)) diff --git a/internal/application/service/wiki_ingest_batch.go b/internal/application/service/wiki_ingest_batch.go index 6b44a5ad..edf2008f 100644 --- a/internal/application/service/wiki_ingest_batch.go +++ b/internal/application/service/wiki_ingest_batch.go @@ -1358,7 +1358,12 @@ func (s *wikiIngestService) mapOneDocument( return nil, nil, nil } - chunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, payload.TenantID, knowledgeID) + // Text chunks of a scanned PDF are image links. The readable prose lives on + // image_ocr chunks and is not always copied into image_info, so load those + // chunks and append the pages that are still missing. + chunks, err := s.chunkRepo.ListChunksByKnowledgeIDAndTypes(ctx, payload.TenantID, knowledgeID, []types.ChunkType{ + types.ChunkTypeText, types.ChunkTypeImageOCR, + }) if err != nil { s.tracker().FailSpan(ctx, wikiSpan, "LIST_CHUNKS_FAILED", err.Error(), err) return nil, nil, fmt.Errorf("get chunks: %w", err) @@ -1369,7 +1374,10 @@ func (s *wikiIngestService) mapOneDocument( return nil, nil, nil } - content := reconstructEnrichedContent(ctx, s.chunkRepo, payload.TenantID, chunks) + content := appendScannedPageText( + reconstructEnrichedContent(ctx, s.chunkRepo, payload.TenantID, chunks), + chunks, + ) rawRuneCount := len([]rune(content)) if len([]rune(content)) > maxContentForWiki { content = string([]rune(content)[:maxContentForWiki]) @@ -1527,7 +1535,9 @@ func (s *wikiIngestService) mapOneDocument( return } candidatesXML := renderCandidateSlugsXML(extractedEntities, extractedConcepts) - citations, newSlugs, batchCount = s.classifyChunkCitations(ctx, chatModel, candidatesXML, chunks, lang, batchCtx) + citations, newSlugs, batchCount = s.classifyChunkCitations( + ctx, chatModel, candidatesXML, wikiCitationChunks(chunks), lang, batchCtx, + ) s.tracker().EndSpan(ctx, classifySpan, types.JSONMap{ "cited_slugs": len(citations), "new_slugs": len(newSlugs), diff --git a/internal/application/service/wiki_ingest_cancellation_test.go b/internal/application/service/wiki_ingest_cancellation_test.go index 7e0bf094..adc3dc8e 100644 --- a/internal/application/service/wiki_ingest_cancellation_test.go +++ b/internal/application/service/wiki_ingest_cancellation_test.go @@ -163,6 +163,12 @@ func (wikiLookupEmptyChunks) ListChunksByKnowledgeID(context.Context, uint64, st return nil, nil } +func (wikiLookupEmptyChunks) ListChunksByKnowledgeIDAndTypes( + context.Context, uint64, string, []types.ChunkType, +) ([]*types.Chunk, error) { + return nil, nil +} + func newWikiLookupRecoveryService(t *testing.T, kbID string, rdb *redis.Client) (*wikiIngestService, *gorm.DB) { t.Helper() db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) diff --git a/internal/application/service/wiki_ingest_cite.go b/internal/application/service/wiki_ingest_cite.go index 97c18ead..03beb373 100644 --- a/internal/application/service/wiki_ingest_cite.go +++ b/internal/application/service/wiki_ingest_cite.go @@ -418,14 +418,39 @@ func (s *wikiIngestService) resolveCitedChunks( // "drop entirely" behavior on concept/entity pages. imageInfoByID := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, tenantID, ids) + // Citation enrichment is an in-memory copy. Reload OCR Content for the + // same image-only parents here so Reduce does not lose that evidence + // when image_info is missing. Keep ordinary prose on its existing path. + var scannedIDs []string for _, c := range chunks { - if c == nil || c.Content == "" { + if c != nil && c.IsEnabled && !chunkHasExtractableText(c.Content) { + scannedIDs = append(scannedIDs, c.ID) + } + } + ocrByParent := make(map[string][]*types.Chunk) + if len(scannedIDs) > 0 { + children, childErr := s.chunkRepo.ListChunksByParentIDs(ctx, tenantID, scannedIDs) + if childErr != nil { + logger.Warnf(ctx, "wiki ingest: failed to resolve cited OCR: %v", childErr) + } else { + inputs := append(append([]*types.Chunk(nil), chunks...), children...) + for _, child := range scannedOCRForWiki(inputs) { + ocrByParent[child.ParentChunkID] = append(ocrByParent[child.ParentChunkID], child) + } + } + } + + for _, c := range chunks { + if c == nil || !c.IsEnabled || c.Content == "" { continue } content := c.Content if info := imageInfoByID[c.ID]; info != "" { content = searchutil.EnrichContentWithImageInfo(content, info) } + if ocr := ocrByParent[c.ID]; len(ocr) > 0 { + content = appendScannedPageText(content, append([]*types.Chunk{c}, ocr...)) + } out[c.ID] = content } } diff --git a/internal/application/service/wiki_ingest_cite_resolve_test.go b/internal/application/service/wiki_ingest_cite_resolve_test.go index 78122172..947a310b 100644 --- a/internal/application/service/wiki_ingest_cite_resolve_test.go +++ b/internal/application/service/wiki_ingest_cite_resolve_test.go @@ -129,3 +129,61 @@ func TestResolveCitedChunksStillFallsBackWithoutRepoRows(t *testing.T) { t.Fatalf("unknown cited chunk must be skipped, got %v", out) } } + +// Classification and Reduce must consume the same OCR even though Reduce +// reloads the original, unenriched parent from storage. +func TestResolveCitedChunksRetainsScannedOCR(t *testing.T) { + const text = "The contractual amount is 123456 dollars." + for _, tc := range []struct { + name string + info string + }{ + {name: "missing image info"}, + {name: "caption without OCR", info: `[{"url":"resource://page","caption":"Contract page"}]`}, + {name: "existing OCR", info: `[{"url":"resource://page","ocr_text":"` + text + `"}]`}, + } { + t.Run(tc.name, func(t *testing.T) { + parent := citationChunk("page", "![page](resource://page)") + ocr := imageChildChunk("ocr", parent.ID, types.ChunkTypeImageOCR, tc.info, true) + ocr.Content = text + cited := wikiCitationChunks([]*types.Chunk{parent, ocr}) + if len(cited) != 1 || !strings.Contains(cited[0].Content, text) { + t.Fatal("classification did not receive OCR") + } + repo := &citedChunkRepo{ + byID: map[string][]*types.Chunk{parent.ID: {parent}}, + byParent: map[string][]*types.Chunk{parent.ID: {ocr}}, + } + svc := &wikiIngestService{chunkRepo: repo} + out := svc.resolveCitedChunks(context.Background(), 1, []SlugUpdate{ + {KnowledgeID: "kn-1", SourceChunks: []string{cited[0].ID}}, + }) + if strings.Count(out[parent.ID], text) != 1 { + t.Fatalf("Reduce must receive OCR exactly once: %q", out[parent.ID]) + } + }) + } +} + +func TestResolveCitedChunksExcludesDisabledScannedEvidence(t *testing.T) { + for _, disabledParent := range []bool{false, true} { + parent := citationChunk("page", "![page](resource://page)") + parent.IsEnabled = !disabledParent + ocr := imageChildChunk("ocr", parent.ID, types.ChunkTypeImageOCR, "", disabledParent) + ocr.Content = "DISABLED_TEXT" + repo := &citedChunkRepo{ + byID: map[string][]*types.Chunk{parent.ID: {parent}}, + byParent: map[string][]*types.Chunk{parent.ID: {ocr}}, + } + svc := &wikiIngestService{chunkRepo: repo} + out := svc.resolveCitedChunks(context.Background(), 1, []SlugUpdate{ + {KnowledgeID: "kn-1", SourceChunks: []string{parent.ID}}, + }) + if strings.Contains(out[parent.ID], "DISABLED_TEXT") { + t.Fatalf("disabled evidence reached Reduce: %q", out[parent.ID]) + } + if disabledParent && out[parent.ID] != "" { + t.Fatalf("disabled parent reached Reduce: %q", out[parent.ID]) + } + } +}