Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(knowledge): feed OCR chunks to auto-tag classification (#4689)

LuckVd7aa881cac7b7
diff --git a/internal/application/service/knowledge_auto_tag.go b/internal/application/service/knowledge_auto_tag.go
index 87ab729e5..971abd5cd 100644
--- a/internal/application/service/knowledge_auto_tag.go
+++ b/internal/application/service/knowledge_auto_tag.go
@@ -40,7 +40,7 @@ type KnowledgeAutoTagService struct {
knowledgeRepo interfaces.KnowledgeRepository
tagRepo interfaces.KnowledgeTagRepository
kbService interfaces.KnowledgeBaseService
- chunkService interfaces.ChunkService
+ chunkRepo interfaces.ChunkRepository
modelService interfaces.ModelService
spanTracker SpanTracker
}
@@ -50,7 +50,7 @@ func NewKnowledgeAutoTagService(
knowledgeRepo interfaces.KnowledgeRepository,
tagRepo interfaces.KnowledgeTagRepository,
kbService interfaces.KnowledgeBaseService,
- chunkService interfaces.ChunkService,
+ chunkRepo interfaces.ChunkRepository,
modelService interfaces.ModelService,
spanTracker SpanTracker,
) interfaces.TaskHandler {
@@ -58,7 +58,7 @@ func NewKnowledgeAutoTagService(
knowledgeRepo: knowledgeRepo,
tagRepo: tagRepo,
kbService: kbService,
- chunkService: chunkService,
+ chunkRepo: chunkRepo,
modelService: modelService,
spanTracker: spanTracker,
}
@@ -217,11 +217,19 @@ func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task)
return skip("model_not_configured", nil)
}
- chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
+ // Ask for the image-derived chunk types too, the same way summary
+ // enrichment (getSummary), graph post-processing and wiki ingest do: for a
+ // scanned PDF parsed with OCR, the text chunks hold only image-reference
+ // placeholders while the real content lives in the image_ocr children.
+ // buildAutoTagDocumentContent already accepts these chunk types — until
+ // now the text-only fetch below could never deliver them.
+ chunks, err := s.chunkRepo.ListChunksByKnowledgeIDAndTypes(ctx, payload.TenantID, payload.KnowledgeID,
+ []types.ChunkType{types.ChunkTypeText, types.ChunkTypeImageOCR, types.ChunkTypeImageCaption})
if err != nil {
s.tracker().FailSpan(ctx, span, "AUTO_TAG_LIST_CHUNKS_FAILED", err.Error(), err)
return fmt.Errorf("list chunks for auto tag: %w", err)
}
+ inheritParentStartAt(chunks)
content := buildAutoTagDocumentContent(knowledge, chunks)
if strings.TrimSpace(content) == "" {
return skip("no_text_chunks", nil)
@@ -282,6 +290,28 @@ func (s *KnowledgeAutoTagService) Handle(ctx context.Context, task *asynq.Task)
return nil
}
+// inheritParentStartAt gives image children created without a StartAt (the
+// multimodal enrichment path) their text parent's position so the stable
+// document-order sort in buildAutoTagDocumentContent keeps each parent's
+// OCR/caption text adjacent to it instead of floating zero-valued children to
+// the front. Chunks that already carry a real StartAt are left untouched.
+func inheritParentStartAt(chunks []*types.Chunk) {
+ parentStartAt := make(map[string]int, len(chunks))
+ for _, c := range chunks {
+ if c != nil && c.ChunkType == types.ChunkTypeText {
+ parentStartAt[c.ID] = c.StartAt
+ }
+ }
+ for _, c := range chunks {
+ if c == nil || c.ParentChunkID == "" || c.StartAt != 0 {
+ continue
+ }
+ if startAt, ok := parentStartAt[c.ParentChunkID]; ok {
+ c.StartAt = startAt
+ }
+ }
+}
+
func buildAutoTagDocumentContent(knowledge *types.Knowledge, chunks []*types.Chunk) string {
parts := make([]string, 0, len(chunks)+2)
if name := strings.TrimSpace(knowledge.FileName); name != "" {
diff --git a/internal/application/service/knowledge_auto_tag_test.go b/internal/application/service/knowledge_auto_tag_test.go
index 2e662edc5..db084015a 100644
--- a/internal/application/service/knowledge_auto_tag_test.go
+++ b/internal/application/service/knowledge_auto_tag_test.go
@@ -92,15 +92,25 @@ func (s *autoTagKBService) GetKnowledgeBaseByIDOnly(
return s.kb, nil
}
-type autoTagChunkService struct {
- interfaces.ChunkService
+type autoTagChunkRepo struct {
+ interfaces.ChunkRepository
chunks []*types.Chunk
}
-func (s *autoTagChunkService) ListChunksByKnowledgeID(
- context.Context, string,
+func (r *autoTagChunkRepo) ListChunksByKnowledgeIDAndTypes(
+ _ context.Context, _ uint64, _ string, chunkTypes []types.ChunkType,
) ([]*types.Chunk, error) {
- return s.chunks, nil
+ wanted := make(map[types.ChunkType]struct{}, len(chunkTypes))
+ for _, t := range chunkTypes {
+ wanted[t] = struct{}{}
+ }
+ out := make([]*types.Chunk, 0, len(r.chunks))
+ for _, c := range r.chunks {
+ if _, ok := wanted[c.ChunkType]; ok {
+ out = append(out, c)
+ }
+ }
+ return out, nil
}
type autoTagChatModel struct {
@@ -152,7 +162,7 @@ func newAutoTagFixture(t *testing.T, response string, opts ...func(*autoTagFixtu
SummaryModelID: "model-1",
AutoTagConfig: &types.AutoTagConfig{Enabled: true, MaxTags: 3},
}},
- chunkService: &autoTagChunkService{chunks: []*types.Chunk{
+ chunkRepo: &autoTagChunkRepo{chunks: []*types.Chunk{
{ChunkType: types.ChunkTypeText, Content: "quarterly HR policy", StartAt: 1},
}},
modelService: &stubModelService{chatModel: chatModel},
@@ -372,3 +382,37 @@ func TestEnqueueAutoTagTaskCarriesScopeWithoutOwningFinalizingSlot(t *testing.T)
assert.Equal(t, "doc", payload.KnowledgeID)
assert.Equal(t, 4, payload.Attempt)
}
+
+// For a scanned PDF parsed with OCR the text chunks hold only image-reference
+// placeholders while the real content lives in the image_ocr / image_caption
+// children. The classifier must receive the OCR text, not placeholders alone.
+func TestAutoTagHandleFeedsOCRChunksToClassifier(t *testing.T) {
+ scanned := []*types.Chunk{
+ {
+ ID: "p1", ChunkType: types.ChunkTypeText,
+ Content: "![page_1.jpg](resource://k/scanned/page_1.jpg)", StartAt: 1,
+ },
+ {
+ ID: "ocr1", ChunkType: types.ChunkTypeImageOCR,
+ Content: "quarterly HR policy for construction safety", ParentChunkID: "p1",
+ },
+ {
+ ID: "cap1", ChunkType: types.ChunkTypeImageCaption,
+ Content: "figure: policy cover", ParentChunkID: "p1",
+ },
+ }
+ fixture := newAutoTagFixture(t, `{"matches":[{"index":1,"confidence":0.9}]}`)
+ fixture.service.chunkRepo = &autoTagChunkRepo{chunks: scanned}
+ require.NoError(t, fixture.handle(t))
+
+ prompt := ""
+ for _, m := range fixture.chatModel.messages {
+ prompt += m.Content + "\n"
+ }
+ assert.Contains(t, prompt, "quarterly HR policy for construction safety",
+ "OCR text must reach the classifier")
+ assert.Contains(t, prompt, "figure: policy cover", "captions must reach the classifier")
+ assert.Contains(t, prompt, "resource://k/scanned/page_1.jpg",
+ "the placeholder itself is still part of the document")
+ assert.Equal(t, []string{"tag-a"}, fixture.repo.added)
+}