chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,53 @@
package chunker
import "strings"
// markdownFence tracks top-level backtick and tilde fences during line scans.
// It deliberately does not parse Markdown container blocks (lists/quotes).
type markdownFence struct {
marker byte
length int
}
// consume reports whether line belongs to fenced code, including delimiters.
// The second result identifies opening/closing delimiters, so the profiler can
// count code content without counting fence lines. An unclosed fence remains
// active through the end of the scan.
func (f *markdownFence) consume(line string) (code, delimiter bool) {
inside := f.length > 0
// Scanners split on LF; remove the line ending's CR for CRLF documents.
line = strings.TrimSuffix(line, "\r")
indent := 0
for indent < len(line) && line[indent] == ' ' {
indent++
}
if indent > 3 || indent == len(line) {
return inside, false
}
line = line[indent:]
marker := line[0]
if marker != '`' && marker != '~' {
return inside, false
}
length := 0
for length < len(line) && line[length] == marker {
length++
}
if length < 3 {
return inside, false
}
rest := line[length:]
if inside {
if marker == f.marker && length >= f.length && strings.Trim(rest, " \t") == "" {
*f = markdownFence{}
return true, true
}
return true, false
}
// Backtick info strings cannot themselves contain backticks.
if marker == '`' && strings.Contains(rest, "`") {
return false, false
}
f.marker, f.length = marker, length
return true, true
}
@@ -0,0 +1,145 @@
package chunker
import (
"math"
"strings"
"testing"
"unicode/utf8"
)
func TestHeadingScansRespectFences(t *testing.T) {
cases := []struct {
name, open, body, close string
}{
{"backticks", "```go", "# Fake\n## Fake sub", "```"},
{"tildes", "~~~markdown", "# Fake\n## Fake sub", "~~~"},
{"long backticks", "````markdown", "```\n# Fake\n## Fake sub", "````"},
{"long tildes", "~~~~", "~~~\n# Fake\n## Fake sub", "~~~~~"},
{"mismatched closer", "```", "~~~\n# Fake\n## Fake sub", "```"},
{"closer with text", "```", "``` trailing\n# Fake\n## Fake sub", "```"},
{"indented closer", "```", " ```\n# Fake\n## Fake sub", "```"},
{"tab indented closer", "```", "\t```\n# Fake\n## Fake sub", "```"},
{"indented fences", " ~~~go", "# Fake\n## Fake sub", " ~~~~ \t"},
{"backtick info", "```go title=example", "# Fake\n## Fake sub", "```"},
{"tilde info with backtick", "~~~go `example`", "# Fake\n## Fake sub", "~~~"},
{"unclosed", "~~~", "# Fake\n## Fake sub", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
doc := "# Real\n" + tc.open + "\n" + tc.body
wantTotal := 1
if tc.close != "" {
doc += "\n" + tc.close + "\n# After\n## Real sub"
wantTotal = 3
}
p := ProfileDocument(doc)
if p.MdHeadingTotal != wantTotal || p.MdHeadingCounts[1] != wantTotal/2+1 ||
p.MdHeadingCounts[2] != wantTotal/2 {
t.Errorf("unexpected heading counts: %v (total %d)", p.MdHeadingCounts, p.MdHeadingTotal)
}
codeChars := 0
for _, line := range strings.Split(tc.body, "\n") {
codeChars += utf8.RuneCountInString(line)
}
wantRatio := float64(codeChars) / float64(utf8.RuneCountInString(doc))
if !p.HasCode || math.Abs(p.CodeRatio-wantRatio) > 1e-12 {
t.Errorf("HasCode=%v CodeRatio=%g, want true and %g", p.HasCode, p.CodeRatio, wantRatio)
}
bounds := findHeadingBoundaries(doc, 1)
if len(bounds) != wantTotal/2+1 || bounds[0].line != "# Real" {
t.Errorf("unexpected boundaries: %+v", bounds)
}
if tc.close != "" && len(bounds) == 2 {
wantOffset := utf8.RuneCountInString(doc[:strings.Index(doc, "# After")])
if bounds[1].line != "# After" || bounds[1].runeStart != wantOffset {
t.Errorf("unexpected closing boundary: %+v, want offset %d", bounds[1], wantOffset)
}
}
seed := NewHeadingHierarchy()
seed.Observe("# Real")
bcs := sectionBreadcrumbs([]rune(doc), 1, *seed)
observeSubHeadings([]rune(doc), 1, seed)
wantBreadcrumb := "# Real"
if tc.close != "" {
wantBreadcrumb += "\n## Real sub"
}
if seed.BreadcrumbWithHashes() != wantBreadcrumb || len(bcs) != wantTotal/2+1 ||
bcs[len(bcs)-1].breadcrumb != wantBreadcrumb {
t.Errorf("unexpected heading context: %q, breadcrumbs: %+v", seed.BreadcrumbWithHashes(), bcs)
}
})
}
}
func TestHeadingScansRejectInvalidFenceOpeners(t *testing.T) {
for _, open := range []string{"``", "~~", " ```", "\t~~~", "```go `example`", "`~`"} {
t.Run(open, func(t *testing.T) {
doc := open + "\n# Real\n## Real sub"
p := ProfileDocument(doc)
if p.HasCode || p.CodeRatio != 0 || p.MdHeadingTotal != 2 {
t.Errorf("invalid opener hid headings or counted code: %+v", p)
}
bounds := findHeadingBoundaries(doc, 1)
if len(bounds) != 2 || bounds[1].line != "# Real" {
t.Errorf("unexpected boundaries: %+v", bounds)
}
h := NewHeadingHierarchy()
h.Observe("# Seed")
bcs := sectionBreadcrumbs([]rune(doc), 1, *h)
observeSubHeadings([]rune(doc), 1, h)
if h.BreadcrumbWithHashes() != "# Seed\n## Real sub" || len(bcs) != 2 {
t.Errorf("unexpected context: %q, breadcrumbs: %+v", h.BreadcrumbWithHashes(), bcs)
}
})
}
}
func TestSplitByHeadings_FencedSubHeadingContext(t *testing.T) {
for _, fence := range []string{"~~~", "````"} {
for _, newline := range []string{"\n", "\r\n"} {
t.Run(fence+newline, func(t *testing.T) {
filler := strings.Repeat("中文 clause body sentence. ", 25)
doc := "# Real\n" + filler + "\n## Section\n" + filler + "\n" +
fence + "markdown\n```\n### Fake\n" + filler + "\n" + fence + "\n" +
filler + "AFTER_CODE_MARKER\n" + filler + "\n### Real sub\n" + filler +
"REAL_SUB_MARKER\n" + filler + "\n## Next\n" + filler + "\n## Last\n" + filler
doc = strings.ReplaceAll(doc, "\n", newline)
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{". "}}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) < 4 {
t.Fatalf("expected large section to be sub-split, got %d chunks", len(chunks))
}
runes := []rune(doc)
seenCode, seenSub := false, false
for i, c := range chunks {
if c.Seq != i || c.Start < 0 || c.End < c.Start || c.End > len(runes) {
t.Fatalf("invalid chunk position or sequence: %+v", c)
}
if c.End-c.Start != utf8.RuneCountInString(c.Content) || string(runes[c.Start:c.End]) != c.Content {
t.Errorf("chunk %d does not match its source slice", i)
}
if strings.Contains(c.ContextHeader, "Fake") {
t.Errorf("chunk %d contains code heading in context: %q", i, c.ContextHeader)
}
if strings.Contains(c.Content, "AFTER_CODE_MARKER") {
seenCode = true
if c.ContextHeader != "# Real\n## Section" {
t.Errorf("context after code = %q", c.ContextHeader)
}
}
if strings.Contains(c.Content, "REAL_SUB_MARKER") {
seenSub = true
if c.ContextHeader != "# Real\n## Section\n### Real sub" {
t.Errorf("context after real sub-heading = %q", c.ContextHeader)
}
}
}
if !seenCode || !seenSub {
t.Error("marker content lost during chunking")
}
})
}
}
}
@@ -0,0 +1,290 @@
// Package chunker - header_tracker.go implements context-preserving header
// tracking for document chunking, ported from docreader/splitter/header_hook.py.
//
// When a large Markdown table is split across multiple chunks, each chunk after
// the first would lose the table header context. The headerTracker detects table
// headers and signals the merge logic to prepend them to subsequent chunks.
package chunker
import (
"regexp"
"sort"
"strings"
)
// headerTrackerHook defines a pattern pair for detecting contextual headers.
// When startPattern matches a unit's text, that text becomes an "active header".
// The header stays active until endPattern matches a subsequent unit.
type headerTrackerHook struct {
startPattern *regexp.Regexp
endPattern *regexp.Regexp
priority int
}
// defaultHeaderHooks returns header tracking hooks matching the Python defaults
// in docreader/splitter/header_hook.py.
var defaultHeaderHooks = []headerTrackerHook{
{
// Markdown table: header row + separator row (e.g. "| A | B |\n| --- | --- |\n")
startPattern: regexp.MustCompile(`(?si)^\s*(?:\|[^|\n]*)+[\r\n]+\s*(?:\|\s*:?-{3,}:?\s*)+\|?[\r\n]+$`),
// Empty/whitespace line or a line that doesn't start with | or whitespace
endPattern: regexp.MustCompile(`(?si)^\s*$|^\s*[^|\s].*$`),
priority: 15,
},
}
// tableRowPattern matches a single Markdown table row: "| cell | cell | ... |\n"
var tableRowPattern = regexp.MustCompile(`(?m)^\s*(?:\|[^|\n]*)+\|\s*$`)
// markdownTableHookPriority matches DEFAULT_CONFIGS / defaultHeaderHooks table hook.
const markdownTableHookPriority = 15
// headerTracker maintains the state of active headers across split units.
type headerTracker struct {
hooks []headerTrackerHook
activeHeaders map[int]string // priority -> header text
endedHeaders map[int]bool // priorities that have been ended
pendingExtend map[int]bool // headers with empty column names awaiting first data row
// pendingTableBreak is set when a table row unit ends with a paragraph break
// (the blank line between tables is consumed by \n\n splitting). The header
// stays active until the next unit is seen so we can detect a new table.
pendingTableBreak bool
// headerEndedThisUnit tells mergeUnits to flush before the current unit when a
// new table starts (column mismatch or pendingTableBreak + table row).
headerEndedThisUnit bool
}
func newHeaderTracker() *headerTracker {
return &headerTracker{
hooks: defaultHeaderHooks,
activeHeaders: make(map[int]string),
endedHeaders: make(map[int]bool),
pendingExtend: make(map[int]bool),
}
}
// update checks split text for header start/end markers and updates internal state.
func (ht *headerTracker) update(split string) {
ht.headerEndedThisUnit = false
if ht.pendingTableBreak {
ht.pendingTableBreak = false
if _, active := ht.activeHeaders[markdownTableHookPriority]; active {
if firstTableRowColumnCount(split) > 0 {
ht.clearTableHeader()
ht.headerEndedThisUnit = true
} else {
ht.clearTableHeader()
}
}
}
// 1. Check for header-end markers among currently active headers
for _, hook := range ht.hooks {
if _, active := ht.activeHeaders[hook.priority]; active {
if hook.endPattern.MatchString(split) {
ht.endedHeaders[hook.priority] = true
delete(ht.activeHeaders, hook.priority)
delete(ht.pendingExtend, hook.priority)
}
}
}
// 1b. Paragraph splits consume the blank line between tables. Mark a break
// after "| last row |\n\n" and resolve on the next unit; also end when a new
// table row has a different column count than the active header.
if _, active := ht.activeHeaders[markdownTableHookPriority]; active {
if !ht.pendingExtend[markdownTableHookPriority] {
if splitEndsWithParagraphBreak(split) {
ht.pendingTableBreak = true
} else {
ht.endTableHeaderOnColumnMismatch(split)
}
}
}
// 2. If a header has an empty column-name row (e.g. "||"), replace it with
// a proper Markdown table header using the first data row as column names.
//
// Before: "||" + "| --- | --- |\n"
// After: "| col1 | col2 |\n" + "| --- | --- |\n"
for p := range ht.pendingExtend {
if _, active := ht.activeHeaders[p]; active && tableRowPattern.MatchString(split) {
sep := extractSeparatorLine(ht.activeHeaders[p])
ht.activeHeaders[p] = split + sep
}
delete(ht.pendingExtend, p)
}
// 3. Check for new header-start markers (only for hooks that are neither active nor ended)
for _, hook := range ht.hooks {
if _, active := ht.activeHeaders[hook.priority]; active {
continue
}
if ht.endedHeaders[hook.priority] {
continue
}
if loc := hook.startPattern.FindString(split); loc != "" {
ht.activeHeaders[hook.priority] = loc
if isEmptyTableHeaderRow(loc) {
ht.pendingExtend[hook.priority] = true
}
}
}
// 4. If all headers ended, clear the ended set so future tables can be tracked
if len(ht.activeHeaders) == 0 {
for k := range ht.endedHeaders {
delete(ht.endedHeaders, k)
}
}
}
// getHeaders returns all active headers concatenated, sorted by priority descending.
func (ht *headerTracker) getHeaders() string {
if len(ht.activeHeaders) == 0 {
return ""
}
type entry struct {
priority int
text string
}
entries := make([]entry, 0, len(ht.activeHeaders))
for p, t := range ht.activeHeaders {
entries = append(entries, entry{p, t})
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].priority > entries[j].priority
})
parts := make([]string, len(entries))
for i, e := range entries {
parts[i] = e.text
}
return strings.Join(parts, "\n")
}
// isEmptyTableHeaderRow checks if the header row (the line before the separator)
// contains only pipes and whitespace — meaning the column names are empty.
// This is common with MarkItDown and similar converters that produce tables like:
//
// ||
// | --- | --- |
// | real column A | real column B |
func isEmptyTableHeaderRow(header string) bool {
idx := strings.IndexByte(header, '\n')
if idx < 0 {
return false
}
row := strings.TrimSpace(header[:idx])
for _, r := range row {
if r != '|' && r != ' ' && r != '\t' {
return false
}
}
return true
}
// extractSeparatorLine returns the separator line (e.g. "| --- | --- |\n") from
// a table header string. It looks for the line containing "---".
func extractSeparatorLine(header string) string {
for _, line := range strings.Split(header, "\n") {
if strings.Contains(line, "---") {
return line + "\n"
}
}
return ""
}
func (ht *headerTracker) clearTableHeader() {
ht.endedHeaders[markdownTableHookPriority] = true
delete(ht.activeHeaders, markdownTableHookPriority)
delete(ht.pendingExtend, markdownTableHookPriority)
}
func (ht *headerTracker) endTableHeaderOnColumnMismatch(split string) {
header, ok := ht.activeHeaders[markdownTableHookPriority]
if !ok {
return
}
rowCols := firstTableRowColumnCount(split)
headerCols := headerTableColumnCount(header)
if rowCols > 0 && headerCols > 0 && rowCols != headerCols {
ht.clearTableHeader()
ht.headerEndedThisUnit = true
}
}
func splitEndsWithParagraphBreak(split string) bool {
trimmed := strings.TrimRight(split, " \t\r")
return strings.HasSuffix(trimmed, "\n\n") || strings.HasSuffix(trimmed, "\r\n\r\n")
}
func tableRowColumnCount(line string) int {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "|") {
return 0
}
parts := splitTableCells(line)
if len(parts) > 0 && strings.TrimSpace(parts[0]) == "" {
parts = parts[1:]
}
if len(parts) > 0 && strings.TrimSpace(parts[len(parts)-1]) == "" {
parts = parts[:len(parts)-1]
}
return len(parts)
}
// splitTableCells splits a table row at its cell delimiters. As in GFM, a pipe
// escaped as `\|` is text inside a cell, so a row whose cell holds one still
// matches the width of its header.
func splitTableCells(line string) []string {
var parts []string
start, backslashes := 0, 0
for i := 0; i < len(line); i++ {
switch line[i] {
case '\\':
backslashes++
continue
case '|':
if backslashes%2 == 0 {
parts = append(parts, line[start:i])
start = i + 1
}
}
backslashes = 0
}
return append(parts, line[start:])
}
func firstTableRowColumnCount(text string) int {
for _, line := range strings.Split(text, "\n") {
line = strings.TrimSpace(line)
if line != "" && tableRowPattern.MatchString(line) {
return tableRowColumnCount(line)
}
}
return 0
}
func headerTableColumnCount(header string) int {
for _, line := range strings.Split(header, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.Contains(line, "---") {
continue
}
if n := tableRowColumnCount(line); n > 0 {
return n
}
}
return 0
}
// headerColumnMismatch reports whether the next split unit starts a new table
// whose width differs from the active markdown table header.
func headerColumnMismatch(headers, nextUnit string) bool {
headerCols := headerTableColumnCount(headers)
rowCols := firstTableRowColumnCount(nextUnit)
return headerCols > 0 && rowCols > 0 && headerCols != rowCols
}
@@ -0,0 +1,111 @@
// Package chunker - heading_hierarchy.go tracks Markdown heading nesting so
// that the heading-aware splitter (heading_splitter.go) can prepend a
// breadcrumb like "# Top > ## Section > ### Subsection" to each chunk.
//
// Conceptually similar to header_tracker.go (which tracks table headers via
// start/end hooks) but a Markdown heading does not have an explicit end —
// it is ended by the next heading of equal or shallower depth. The hook
// abstraction in header_tracker.go does not fit that pattern, so we model
// it as an explicit level-stack.
package chunker
import "strings"
// HeadingHierarchy maintains a stack of active Markdown headings indexed by
// level (1..6). Pushing a level-N heading pops every entry of level >= N
// because the previous siblings/descendants are no longer in scope.
type HeadingHierarchy struct {
// stack[i] holds the heading text for level i+1 (so stack[0] = H1).
// Entries beyond the deepest active level are empty strings.
stack [6]string
depth int // current deepest active level (0 if no active heading)
}
// NewHeadingHierarchy returns an empty hierarchy.
func NewHeadingHierarchy() *HeadingHierarchy {
return &HeadingHierarchy{}
}
// Observe parses line and updates the hierarchy if line is a Markdown
// heading. Returns the (level, headingText) when a heading was recognized,
// or (0, "") otherwise. Lines that look like headings inside fenced code
// blocks are NOT detected here — callers must avoid feeding code-block
// content to Observe (the heading splitter does so).
func (h *HeadingHierarchy) Observe(line string) (int, string) {
m := MarkdownHeadingPattern.FindStringSubmatch(line)
if m == nil {
return 0, ""
}
level := len(m[1])
if level < 1 || level > 6 {
return 0, ""
}
heading := strings.TrimSpace(m[2])
// Replace this level and clear deeper ones — siblings/descendants of
// the previous heading at this level are no longer in scope.
h.stack[level-1] = heading
for i := level; i < 6; i++ {
h.stack[i] = ""
}
if level > h.depth {
h.depth = level
} else {
// Recompute depth: it might shrink if we just pushed a shallower heading.
h.depth = 0
for i := 0; i < 6; i++ {
if h.stack[i] != "" {
h.depth = i + 1
}
}
}
return level, heading
}
// Breadcrumb returns the current heading path joined by " > ", e.g.
// "Chapter 1 > Section 2 > Subsection a". Returns "" when no headings
// are active.
func (h *HeadingHierarchy) Breadcrumb() string {
if h.depth == 0 {
return ""
}
parts := make([]string, 0, h.depth)
for i := 0; i < h.depth; i++ {
if h.stack[i] != "" {
parts = append(parts, h.stack[i])
}
}
return strings.Join(parts, " > ")
}
// BreadcrumbWithHashes returns the path with the original `#` prefixes,
// suitable for embedding back into chunk content as a context header.
// Example: "# Chapter 1\n## Section 2\n### Subsection a"
func (h *HeadingHierarchy) BreadcrumbWithHashes() string {
if h.depth == 0 {
return ""
}
var sb strings.Builder
for i := 0; i < h.depth; i++ {
if h.stack[i] == "" {
continue
}
if sb.Len() > 0 {
sb.WriteByte('\n')
}
sb.WriteString(strings.Repeat("#", i+1))
sb.WriteByte(' ')
sb.WriteString(h.stack[i])
}
return sb.String()
}
// Depth returns the current deepest active heading level.
func (h *HeadingHierarchy) Depth() int { return h.depth }
// Reset clears all state.
func (h *HeadingHierarchy) Reset() {
for i := range h.stack {
h.stack[i] = ""
}
h.depth = 0
}
@@ -0,0 +1,88 @@
package chunker
import "testing"
func TestHeadingHierarchy_LinearNesting(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# Chapter 1")
h.Observe("## Section 1.1")
h.Observe("### Subsection 1.1.1")
if got := h.Breadcrumb(); got != "Chapter 1 > Section 1.1 > Subsection 1.1.1" {
t.Errorf("breadcrumb mismatch: %q", got)
}
}
func TestHeadingHierarchy_PopsDeeperOnSiblingHeading(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# Chapter 1")
h.Observe("## Section 1.1")
h.Observe("### Subsection 1.1.1")
h.Observe("## Section 1.2") // pops the H3
if got := h.Breadcrumb(); got != "Chapter 1 > Section 1.2" {
t.Errorf("breadcrumb after sibling: %q", got)
}
}
func TestHeadingHierarchy_PopsAllOnNewTopLevel(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# Chapter 1")
h.Observe("## Section A")
h.Observe("### Sub")
h.Observe("# Chapter 2")
if got := h.Breadcrumb(); got != "Chapter 2" {
t.Errorf("breadcrumb after new H1: %q", got)
}
if h.Depth() != 1 {
t.Errorf("depth should be 1, got %d", h.Depth())
}
}
func TestHeadingHierarchy_NonHeadingIgnored(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# Title")
level, txt := h.Observe("just a paragraph")
if level != 0 || txt != "" {
t.Errorf("non-heading should not register: %d %q", level, txt)
}
if got := h.Breadcrumb(); got != "Title" {
t.Errorf("breadcrumb after non-heading: %q", got)
}
}
func TestHeadingHierarchy_BreadcrumbWithHashes(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# A")
h.Observe("## B")
got := h.BreadcrumbWithHashes()
want := "# A\n## B"
if got != want {
t.Errorf("hashes breadcrumb:\n got: %q\n want: %q", got, want)
}
}
func TestHeadingHierarchy_EmptyState(t *testing.T) {
h := NewHeadingHierarchy()
if h.Breadcrumb() != "" || h.BreadcrumbWithHashes() != "" || h.Depth() != 0 {
t.Error("empty hierarchy should have no breadcrumb / depth=0")
}
}
func TestHeadingHierarchy_Reset(t *testing.T) {
h := NewHeadingHierarchy()
h.Observe("# A")
h.Observe("## B")
h.Reset()
if h.Breadcrumb() != "" || h.Depth() != 0 {
t.Error("Reset did not clear state")
}
}
func TestHeadingHierarchy_SkipLevels(t *testing.T) {
h := NewHeadingHierarchy()
// Document jumps from H1 directly to H3, skipping H2.
h.Observe("# Top")
h.Observe("### Deep")
if got := h.Breadcrumb(); got != "Top > Deep" {
t.Errorf("skipped-level breadcrumb: %q", got)
}
}
@@ -0,0 +1,319 @@
// Package chunker - heading_splitter.go implements Tier 1: Markdown
// heading-aware chunking. Documents with proper heading structure are split
// at heading boundaries and each chunk is prefixed with a breadcrumb of
// active heading context (e.g. "# Chapter 1\n## Section 1.2").
package chunker
import (
"strings"
"unicode/utf8"
)
// init wires this implementation into the strategy resolver.
func init() {
splitByHeadings = splitByHeadingsImpl
}
// headingBoundary marks where a section starts. The first boundary is at
// rune offset 0 (covers any preamble before the first heading), subsequent
// boundaries sit at headings whose level is <= primaryLevel.
type headingBoundary struct {
runeStart int
line string // raw heading line, "" when this is the leading boundary
}
// splitByHeadingsImpl is the Tier-1 implementation. It falls through to the
// legacy splitter when the document has no usable heading structure or when
// the heading split would produce a single section anyway.
//
// profile may be nil; we compute one on demand. When the strategy resolver
// already ran the profiler (auto strategy), the same profile is threaded
// through here so we don't re-scan the entire document.
func splitByHeadingsImpl(text string, cfg SplitterConfig, profile *DocProfile) []Chunk {
if text == "" {
return nil
}
if profile == nil {
profile = ProfileDocument(text)
}
primaryLevel := profile.DominantHeadingLevel()
if primaryLevel == 0 {
return SplitText(text, cfg)
}
bounds := findHeadingBoundaries(text, primaryLevel)
if len(bounds) <= 1 {
return SplitText(text, cfg)
}
runes := []rune(text)
hierarchy := NewHeadingHierarchy()
// Pre-walk every heading (not just primary-level) so the hierarchy
// reflects the full nesting context for each section's start. We only
// snapshot the breadcrumb at section boundaries; deeper sub-headings
// inside a section update the hierarchy but do not change the chunk's
// breadcrumb (chunks within a section share one breadcrumb).
var out []Chunk
seq := 0
for i, b := range bounds {
endRune := len(runes)
if i+1 < len(bounds) {
endRune = bounds[i+1].runeStart
}
if b.line != "" {
hierarchy.Observe(b.line)
}
// Catch sub-headings that occur between this primary boundary and
// the next so the hierarchy stays in sync for subsequent sections.
// We intentionally do this after observing the section header so
// the breadcrumb reflects the section-leading heading.
breadcrumb := hierarchy.BreadcrumbWithHashes()
sectionStart := *hierarchy
observeSubHeadings(runes[b.runeStart:endRune], primaryLevel, hierarchy)
sectionRunes := runes[b.runeStart:endRune]
sectionContent := string(sectionRunes)
secLen := len(sectionRunes)
if secLen == 0 {
continue
}
bcLen := utf8.RuneCountInString(breadcrumb)
// Single-chunk section: emit as-is, breadcrumb tracked separately.
// The breadcrumb is delivered via Chunk.ContextHeader (not Content)
// to preserve End-Start == len(Content) invariants relied on by
// document reconstruction (knowledge.go:2278+).
if bcLen+2+secLen <= cfg.ChunkSize {
out = append(out, Chunk{
Content: sectionContent,
ContextHeader: breadcrumb,
Seq: seq,
Start: b.runeStart,
End: endRune,
})
seq++
continue
}
// Section too large: defer to the legacy splitter for inner
// segmentation. We do NOT shrink the inner ChunkSize budget here
// because the breadcrumb no longer counts against Content size.
// Each sub-chunk gets a breadcrumb reflecting the deepest heading
// active at its start, so deep `###`/`####` sub-headings inside a
// long section aren't collapsed to the section-level header.
subBreadcrumbs := sectionBreadcrumbs(sectionRunes, primaryLevel, sectionStart)
subChunks := SplitText(sectionContent, cfg)
for _, sub := range subChunks {
out = append(out, Chunk{
Content: sub.Content,
ContextHeader: breadcrumbAtOffset(subBreadcrumbs, sub.Start, breadcrumb),
Seq: seq,
Start: b.runeStart + sub.Start,
End: b.runeStart + sub.End,
})
seq++
}
}
return coalesceTinyChunks(out, cfg.ChunkSize)
}
// coalesceTinyChunks merges adjacent small chunks under their shared heading
// context so that documents whose primary sections are mostly short (FAQs,
// install logs, change-lists) don't trip the validator's "too many tiny
// chunks" rule and fall through all the way to legacy. The merged breadcrumb
// is the line-prefix shared by both inputs; the original sub-headings remain
// visible because heading_splitter includes the heading line in each
// section's Content.
//
// Safety:
// - We only merge when cur.End == next.Start. That preserves the
// End-Start == len([]rune(Content)) invariant that document
// reconstruction relies on, and naturally skips legacy sub-chunks (which
// may overlap due to ChunkOverlap).
// - We stop accumulating once the running chunk reaches the merge target
// (≈ ChunkSize/2) so we don't aggressively pack chunks beyond what the
// validator considers comfortable.
func coalesceTinyChunks(in []Chunk, chunkSize int) []Chunk {
if len(in) <= 1 || chunkSize <= 0 {
return in
}
target := chunkSize / 2
if target < 200 {
target = 200
}
out := make([]Chunk, 0, len(in))
cur := in[0]
curLen := utf8.RuneCountInString(cur.Content)
for i := 1; i < len(in); i++ {
next := in[i]
nextLen := utf8.RuneCountInString(next.Content)
sharedHeader := commonHeadingPrefix(cur.ContextHeader, next.ContextHeader)
// Adjacent + still-small + would not blow the size budget → merge.
if sharedHeader != "" && cur.End == next.Start && curLen < target && curLen+nextLen <= chunkSize {
cur.Content += next.Content
cur.ContextHeader = sharedHeader
cur.End = next.End
curLen += nextLen
continue
}
out = append(out, cur)
cur = next
curLen = nextLen
}
out = append(out, cur)
// Re-sequence — downstream code (knowledge.go) expects Seq to be a dense
// 0..N-1 range over the returned slice.
for i := range out {
out[i].Seq = i
}
return out
}
// commonHeadingPrefix returns the longest line-aligned prefix shared by two
// breadcrumb strings. Heading hierarchies are emitted as
// "# Top\n## Section\n### Sub", so a line-by-line comparison is sufficient
// and avoids partial-line truncation that would corrupt the breadcrumb.
func commonHeadingPrefix(a, b string) string {
if a == b {
return a
}
la := strings.Split(a, "\n")
lb := strings.Split(b, "\n")
n := len(la)
if len(lb) < n {
n = len(lb)
}
common := 0
for i := 0; i < n; i++ {
if la[i] != lb[i] {
break
}
common = i + 1
}
if common == 0 {
return ""
}
return strings.Join(la[:common], "\n")
}
// findHeadingBoundaries returns one boundary at offset 0 plus one per
// Markdown heading at level <= primaryLevel that sits outside fenced code
// blocks. Heading detection is line-oriented — a heading must occupy a
// whole line to be recognized.
func findHeadingBoundaries(text string, primaryLevel int) []headingBoundary {
runes := []rune(text)
bounds := []headingBoundary{{runeStart: 0}}
if len(runes) == 0 {
return bounds
}
pos := 0
var fence markdownFence
lines := strings.Split(text, "\n")
for i, line := range lines {
if code, _ := fence.consume(line); !code {
m := MarkdownHeadingPattern.FindStringSubmatch(line)
if m != nil {
level := len(m[1])
if level >= 1 && level <= primaryLevel && pos > 0 {
bounds = append(bounds, headingBoundary{
runeStart: pos,
line: line,
})
}
if level >= 1 && level <= primaryLevel && pos == 0 {
// First line is a heading — replace the leading boundary
bounds[0].line = line
}
}
}
pos += utf8.RuneCountInString(line)
if i < len(lines)-1 {
pos++ // account for the \n that strings.Split removed
}
}
return bounds
}
// observeSubHeadings walks the section's lines and feeds every Markdown
// heading deeper than primaryLevel into the hierarchy. This keeps the
// hierarchy state correct so the breadcrumb at the next primary section
// reflects the truly active stack.
func observeSubHeadings(runes []rune, primaryLevel int, h *HeadingHierarchy) {
if len(runes) == 0 {
return
}
text := string(runes)
var fence markdownFence
for _, line := range strings.Split(text, "\n") {
if code, _ := fence.consume(line); code {
continue
}
m := MarkdownHeadingPattern.FindStringSubmatch(line)
if m == nil {
continue
}
level := len(m[1])
if level > primaryLevel {
h.Observe(line)
}
}
}
// sectionBreadcrumb pairs a rune offset within a section with the breadcrumb
// in effect from that offset onward.
type sectionBreadcrumb struct {
runeStart int
breadcrumb string
}
// sectionBreadcrumbs walks a section's deeper sub-headings (level >
// primaryLevel) and records, for each, the rune offset where it takes effect
// and the resulting breadcrumb. seed is the hierarchy state at the section's
// start (already including the section heading and its ancestors). The
// returned slice is ordered by runeStart and always begins with the seed
// breadcrumb at offset 0, so a sub-chunk sitting far below a deep heading
// still resolves to that heading's path rather than the section header.
func sectionBreadcrumbs(sectionRunes []rune, primaryLevel int, seed HeadingHierarchy) []sectionBreadcrumb {
h := seed
result := []sectionBreadcrumb{{runeStart: 0, breadcrumb: h.BreadcrumbWithHashes()}}
pos := 0
var fence markdownFence
lines := strings.Split(string(sectionRunes), "\n")
for i, line := range lines {
if code, _ := fence.consume(line); !code {
if m := MarkdownHeadingPattern.FindStringSubmatch(line); m != nil && len(m[1]) > primaryLevel {
h.Observe(line)
result = append(result, sectionBreadcrumb{
runeStart: pos,
breadcrumb: h.BreadcrumbWithHashes(),
})
}
}
pos += utf8.RuneCountInString(line)
if i < len(lines)-1 {
pos++
}
}
return result
}
// breadcrumbAtOffset returns the breadcrumb in effect at the given rune offset
// — the last entry whose runeStart <= offset. fallback covers the (unreachable
// in practice) empty-slice case.
func breadcrumbAtOffset(bcs []sectionBreadcrumb, offset int, fallback string) string {
bc := fallback
for _, e := range bcs {
if e.runeStart > offset {
break
}
bc = e.breadcrumb
}
return bc
}
@@ -0,0 +1,362 @@
package chunker
import (
"strings"
"testing"
)
func TestSplitByHeadings_BasicSections(t *testing.T) {
// Each section is intentionally larger than the merge-target (≈
// ChunkSize/2) so the post-split coalesce pass leaves them as distinct
// chunks. We're testing per-section emission + breadcrumb here, not
// merging.
body := strings.Repeat("Lorem ipsum dolor sit amet consectetur adipiscing elit. ", 4)
doc := "# Top\n" + body + "\n\n## Section A\n" + body + "\n\n## Section B\n" + body + "\n\n## Section C\n" + body
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) < 3 {
t.Fatalf("expected ≥3 chunks (one per section), got %d", len(chunks))
}
// Breadcrumb is delivered via ContextHeader, not Content.
for i, c := range chunks {
if !strings.Contains(c.ContextHeader, "# Top") {
t.Errorf("chunk %d missing H1 in ContextHeader:\n%q", i, c.ContextHeader)
}
// EmbeddingContent merges header + content for the embedder.
if !strings.Contains(c.EmbeddingContent(), "# Top") {
t.Errorf("chunk %d EmbeddingContent missing H1", i)
}
}
found := false
for _, c := range chunks {
if strings.Contains(c.Content, "## Section B") && strings.Contains(c.Content, "Lorem ipsum") {
found = true
}
}
if !found {
t.Error("no chunk contains Section B with its body")
}
}
func TestSplitByHeadings_FallsThroughForUnstructuredDoc(t *testing.T) {
doc := "Just a plain paragraph without any headings at all in this text."
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
// no headings → falls through to SplitText, which keeps the whole thing
if len(chunks) != 1 {
t.Errorf("expected fallthrough single chunk, got %d", len(chunks))
}
}
func TestSplitByHeadings_LargeSectionRecursesIntoLegacy(t *testing.T) {
body := strings.Repeat("This is a long sentence repeated many times. ", 50)
doc := "# Top\n## Big\n" + body
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 30, Separators: []string{". "}}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("large section should be sub-split, got %d chunks", len(chunks))
}
// Every sub-chunk should carry the breadcrumb via ContextHeader.
for i, c := range chunks {
if !strings.Contains(c.ContextHeader, "# Top") {
t.Errorf("sub-chunk %d missing H1 in ContextHeader", i)
}
}
}
func TestSplitByHeadings_BreadcrumbReflectsLatestPath(t *testing.T) {
// Sized so each section stays its own chunk after the tiny-section
// coalesce pass — we're verifying breadcrumb assignment per section,
// not the merge behavior.
body := strings.Repeat("Lorem ipsum dolor sit amet consectetur adipiscing elit. ", 4)
doc := "# Chapter 1\n" + body + "\n\n## Section A\n" + body + "\n\n## Section B\n" + body
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) < 3 {
t.Fatalf("expected ≥3 chunks, got %d", len(chunks))
}
for _, c := range chunks {
if strings.Contains(c.Content, "text B") {
if strings.Contains(c.ContextHeader, "## Section A") {
t.Errorf("Section B chunk should not include Section A in breadcrumb:\n%s", c.ContextHeader)
}
if !strings.Contains(c.ContextHeader, "## Section B") {
t.Errorf("Section B chunk should include its own heading in breadcrumb:\n%s", c.ContextHeader)
}
}
}
}
func TestSplitByHeadings_IgnoresHeadingsInsideCodeFence(t *testing.T) {
doc := "# Real\n\n```\n# Fake heading inside code\n```\n\nbody"
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
for _, c := range chunks {
if strings.Contains(c.ContextHeader, "# Real") || strings.Contains(c.Content, "# Real") {
return
}
}
t.Error("expected real H1 breadcrumb on some chunk")
}
func TestSplitByHeadings_PreservesPositionRelativeToOriginal(t *testing.T) {
doc := "# Top\nintro\n\n## A\nbody A\n\n## B\nbody B"
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
for i, c := range chunks {
if c.Start < 0 {
t.Errorf("chunk %d has negative Start", i)
}
if c.End < c.Start {
t.Errorf("chunk %d End < Start", i)
}
}
}
// TestSplitByHeadings_PositionInvariant ensures End-Start == len(Content)
// and runes[Start:End] == Content for every emitted chunk. This invariant
// is required by knowledge.go:2278+ document reconstruction logic.
func TestSplitByHeadings_PositionInvariant(t *testing.T) {
doc := `# Top
intro paragraph here.
## Section A
content of A here, several sentences.
## Section B
content of B here.
## Section C
content of C here.`
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) == 0 {
t.Fatal("expected chunks")
}
docRunes := []rune(doc)
for i, c := range chunks {
contentRuneLen := len([]rune(c.Content))
span := c.End - c.Start
if span != contentRuneLen {
t.Errorf("chunk %d: span(%d) != content_runes(%d)\nContent:\n%q", i, span, contentRuneLen, c.Content)
}
if c.Start >= 0 && c.End <= len(docRunes) {
if string(docRunes[c.Start:c.End]) != c.Content {
t.Errorf("chunk %d: runes[Start:End] != Content", i)
}
}
}
}
// TestSplitByHeadings_CoalescesTinyAdjacentSections covers the FAQ /
// install-log case where a parent heading hosts many short sub-sections.
// Without merging, each `##` becomes its own <50-char chunk and the
// validator rejects the tier with "too many tiny chunks". After merging,
// they collapse into a small number of properly-sized chunks while still
// surfacing the shared parent breadcrumb.
func TestSplitByHeadings_CoalescesTinyAdjacentSections(t *testing.T) {
doc := `# Install Log
## Docker镜像
使用 daocloud 部署 v0.3.1。
## 前端老版本
浏览器缓存了旧前端资源。
## 登录报错
ERROR: column missing.
## 解析失败
embedding 表缺列。`
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) == 0 {
t.Fatal("expected at least one chunk")
}
if len(chunks) >= 5 {
t.Errorf("expected coalesce to produce <5 chunks, got %d", len(chunks))
}
// Every merged chunk must carry the shared parent in its breadcrumb so
// retrieval can still answer "what document is this from".
for i, c := range chunks {
if !strings.Contains(c.ContextHeader, "# Install Log") {
t.Errorf("chunk %d missing parent H1 in breadcrumb: %q", i, c.ContextHeader)
}
}
// All four sub-section headings must remain visible somewhere in the
// merged content (heading_splitter keeps the heading line as part of
// each section's Content).
for _, h := range []string{"## Docker镜像", "## 前端老版本", "## 登录报错", "## 解析失败"} {
seen := false
for _, c := range chunks {
if strings.Contains(c.Content, h) {
seen = true
break
}
}
if !seen {
t.Errorf("merged chunks should still contain heading %q somewhere", h)
}
}
}
func TestSplitByHeadings_DoesNotCoalesceDistinctTopLevelHeadings(t *testing.T) {
doc := `# Intro
short intro.
# Usage
short usage.
# FAQ
short faq.`
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
if len(chunks) != 3 {
t.Fatalf("expected one chunk per top-level heading, got %d:\n%v", len(chunks), chunks)
}
for i, heading := range []string{"# Intro", "# Usage", "# FAQ"} {
if !strings.Contains(chunks[i].Content, heading) {
t.Errorf("chunk %d should contain heading %q, got:\n%s", i, heading, chunks[i].Content)
}
}
}
// TestSplitByHeadings_CoalescePreservesPositionInvariant guards the
// End-Start == len([]rune(Content)) invariant after merging. Adjacent
// chunks (cur.End == next.Start) must concatenate cleanly; the merge must
// refuse to combine non-adjacent chunks (e.g. legacy sub-chunks from an
// oversized section that overlap).
func TestSplitByHeadings_CoalescePreservesPositionInvariant(t *testing.T) {
doc := `# Top
## A
short A.
## B
short B.
## C
short C.`
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
docRunes := []rune(doc)
for i, c := range chunks {
contentRuneLen := len([]rune(c.Content))
if c.End-c.Start != contentRuneLen {
t.Errorf("chunk %d: End-Start(%d) != content_runes(%d) after merge",
i, c.End-c.Start, contentRuneLen)
}
if c.Start >= 0 && c.End <= len(docRunes) {
if string(docRunes[c.Start:c.End]) != c.Content {
t.Errorf("chunk %d: source[Start:End] != Content after merge", i)
}
}
}
}
// TestSplitByHeadings_CoalesceRespectsChunkSize ensures the merge target
// stays within the ChunkSize budget — the validator caps oversize chunks
// at 2x and we should never approach that line via merging.
func TestSplitByHeadings_CoalesceRespectsChunkSize(t *testing.T) {
const sections = 30
var sb strings.Builder
sb.WriteString("# Doc\n")
for i := 0; i < sections; i++ {
sb.WriteString("\n## Section ")
sb.WriteString(strings.Repeat("X", 1)) // unique-ish heading
sb.WriteString("\nshort body line.\n")
}
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(sb.String(), cfg, nil)
for i, c := range chunks {
if l := len([]rune(c.Content)); l > cfg.ChunkSize {
t.Errorf("chunk %d exceeds ChunkSize: %d > %d", i, l, cfg.ChunkSize)
}
}
}
// TestCommonHeadingPrefix exercises the breadcrumb-prefix helper directly.
func TestCommonHeadingPrefix(t *testing.T) {
cases := []struct {
a, b, want string
}{
{"# Top\n## A", "# Top\n## B", "# Top"},
{"# Top", "# Top", "# Top"},
{"# X", "# Y", ""},
{"# Top\n## A\n### x", "# Top\n## A\n### y", "# Top\n## A"},
{"", "# Top", ""},
}
for _, tc := range cases {
got := commonHeadingPrefix(tc.a, tc.b)
if got != tc.want {
t.Errorf("commonHeadingPrefix(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want)
}
}
}
// TestSplitByHeadings_NoBreadcrumbDuplication ensures the section's own
// heading line does not appear twice in the chunk content (once as part of
// the breadcrumb, once as the section's first line).
func TestSplitByHeadings_NoBreadcrumbDuplication(t *testing.T) {
doc := `# Chapter 1
intro.
## Section A
body A.
## Section B
body B.`
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0}
chunks := splitByHeadingsImpl(doc, cfg, nil)
for i, c := range chunks {
// Count occurrences of "## Section A" / "## Section B"
for _, heading := range []string{"## Section A", "## Section B"} {
n := strings.Count(c.Content, heading)
if n > 1 {
t.Errorf("chunk %d contains %q %d times — duplicated by breadcrumb prepend:\n%s",
i, heading, n, c.Content)
}
}
}
}
// TestSplitByHeadings_DeepSubHeadingInLargeSection covers issue #1674: when a
// shallow heading level repeats and therefore becomes the dominant split
// backbone, a long section split into sub-chunks must still carry the deep
// `###`/`####` heading that defines a sub-chunk's meaning, not just the
// section-level header. The marker line sits far below its deep heading, in a
// later sub-chunk that has no heading of its own.
func TestSplitByHeadings_DeepSubHeadingInLargeSection(t *testing.T) {
filler := strings.Repeat("clause body sentence that pads the section out. ", 20)
doc := "# Standard XYZ\n" +
"## Preface\n" + filler + "\n\n" +
"## 5 Classification\n" + filler + "\n\n" +
"### 5.9 Grade Nine\n" + filler + "\n\n" +
"#### 5.9.2 Clause Series\n" + filler + "\n\n" +
"the item users search for is MARKER_ITEM_23 graded here.\n\n" +
"## Appendix A\n" + filler + "\n\n" +
"## Appendix B\n" + filler + "\n\n" +
"## Appendix C\n" + filler
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 0, Separators: []string{". "}}
chunks := splitByHeadingsImpl(doc, cfg, nil)
var marker *Chunk
for i := range chunks {
if strings.Contains(chunks[i].Content, "MARKER_ITEM_23") {
marker = &chunks[i]
break
}
}
if marker == nil {
t.Fatal("no chunk contains the marker line")
}
if !strings.Contains(marker.ContextHeader, "#### 5.9.2 Clause Series") {
t.Errorf("marker chunk lost its deep sub-heading in the breadcrumb:\nContextHeader=%q", marker.ContextHeader)
}
if !strings.Contains(marker.ContextHeader, "## 5 Classification") {
t.Errorf("marker chunk lost its section heading in the breadcrumb:\nContextHeader=%q", marker.ContextHeader)
}
}
@@ -0,0 +1,313 @@
// Package chunker - heuristic_splitter.go implements Tier 2: boundary-driven
// chunking for documents that lack proper Markdown headings but contain
// recognizable structural cues (page breaks, numbered sections, multilingual
// chapter markers, visual separators, all-caps section titles, page footers).
//
// The algorithm finds all candidate boundary positions, then performs greedy
// bin-packing — accumulating blocks between boundaries into chunks until the
// next block would exceed cfg.ChunkSize. Blocks larger than ChunkSize are
// recursively delegated to the legacy splitter for inner segmentation.
package chunker
import (
"sort"
"strings"
"unicode/utf8"
)
func init() {
splitByHeuristics = splitByHeuristicsImpl
}
// boundary marks a candidate split point in the document.
type boundary struct {
runeStart int // rune offset where the next chunk should start
priority int
}
// splitByHeuristicsImpl is the Tier-2 implementation. Falls through to the
// legacy splitter when no heuristic boundaries are found.
//
// profile is currently unused (this tier scans for boundaries directly) but
// is accepted to keep the splitByHeadings / splitByHeuristics signatures
// uniform — see strategy.runTier.
func splitByHeuristicsImpl(text string, cfg SplitterConfig, _ *DocProfile) []Chunk {
if text == "" {
return nil
}
runes := []rune(text)
totalRunes := len(runes)
if totalRunes <= cfg.ChunkSize {
return SplitText(text, cfg)
}
bounds := findHeuristicBoundaries(text, cfg.Languages)
// Drop any boundary that falls strictly inside a protected region (table,
// fenced code block, LaTeX block, etc.) — splitting there would cut
// through atomic content. Boundaries on a span edge are kept since they
// align with the protected region start/end.
if prot := protectedSpansRune(text, protectedSpans(text)); len(prot) > 0 {
bounds = dropBoundsInsideSpans(bounds, prot)
}
if len(bounds) == 0 {
return SplitText(text, cfg)
}
// Append a sentinel at end-of-document so the bin-packer can flush.
bounds = append(bounds, boundary{runeStart: totalRunes})
// Always start with a boundary at offset 0 if not already there.
if bounds[0].runeStart != 0 {
bounds = append([]boundary{{runeStart: 0}}, bounds...)
}
// Greedy bin-packing.
var out []Chunk
seq := 0
chunkStart := bounds[0].runeStart
curEnd := chunkStart
minChunkSize := cfg.ChunkSize / 4
if minChunkSize < 50 {
minChunkSize = 50
}
for i := 1; i < len(bounds); i++ {
nextEnd := bounds[i].runeStart
blockLen := nextEnd - curEnd
if blockLen > cfg.ChunkSize {
// The block between the previous and this boundary is itself too
// large to fit in any chunk. Flush current accumulation, then
// recursively chunk the oversize block via the legacy splitter.
if curEnd-chunkStart > 0 {
out = appendChunk(out, runes, chunkStart, curEnd, &seq)
chunkStart = curEnd
}
out = appendOversizeBlock(out, runes, curEnd, nextEnd, cfg, &seq)
curEnd = nextEnd
chunkStart = nextEnd
continue
}
// Would adding this block exceed the budget?
accumulated := nextEnd - chunkStart
if accumulated > cfg.ChunkSize && curEnd-chunkStart >= minChunkSize {
// Flush accumulated content as a chunk, restart at curEnd.
out = appendChunk(out, runes, chunkStart, curEnd, &seq)
// Snap overlap start to the nearest semantic boundary or line
// break instead of slicing mid-line / mid-word.
chunkStart = applyOverlapAligned(runes, curEnd, cfg.ChunkOverlap, bounds)
}
curEnd = nextEnd
}
// Flush remaining content.
if curEnd > chunkStart {
out = appendChunk(out, runes, chunkStart, curEnd, &seq)
}
return out
}
// findHeuristicBoundaries scans text and returns boundary positions in
// ascending order. Lower-priority duplicates at the same offset are dropped.
func findHeuristicBoundaries(text string, langs []string) []boundary {
var bounds []boundary
// Form feeds — strongest single-character boundary.
for _, idx := range allRuneIndices(text, "\f") {
bounds = append(bounds, boundary{runeStart: idx, priority: PrioFormFeed})
}
// Per-line patterns walk the text once, line by line.
lines := strings.Split(text, "\n")
chapterPatterns := ChapterPatternsForLangs(langs)
pos := 0
inFence := false
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "```") {
inFence = !inFence
} else if !inFence {
runeStart := pos
added := false
for _, pat := range chapterPatterns {
if pat.MatchString(line) {
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioChapterMarker})
added = true
break
}
}
if !added && NumberedSectionPattern.MatchString(line) {
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioNumberedHead})
added = true
}
if !added && AllCapsHeadingPattern.MatchString(line) {
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioAllCapsHeading})
added = true
}
if !added && VisualSeparatorPattern.MatchString(line) {
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioVisualSep})
added = true
}
if !added && PageFooterPattern.MatchString(line) {
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioPageFooter})
}
}
pos += utf8.RuneCountInString(line)
if i < len(lines)-1 {
pos++ // \n
}
}
// Excessive blank blocks (\n{3,}). Match at the *start* of the run so we
// drop into the next paragraph cleanly.
for _, idx := range ExcessiveBlanksPattern.FindAllStringIndex(text, -1) {
runeStart := utf8.RuneCountInString(text[:idx[1]])
bounds = append(bounds, boundary{runeStart: runeStart, priority: PrioBlankBlock})
}
if len(bounds) == 0 {
return nil
}
// Sort by position; drop near-duplicate offsets keeping the highest priority.
sort.Slice(bounds, func(i, j int) bool {
if bounds[i].runeStart != bounds[j].runeStart {
return bounds[i].runeStart < bounds[j].runeStart
}
return bounds[i].priority > bounds[j].priority
})
deduped := bounds[:0]
prev := -1
for _, b := range bounds {
if b.runeStart != prev {
deduped = append(deduped, b)
prev = b.runeStart
}
}
return deduped
}
// dropBoundsInsideSpans returns bounds with entries that fall strictly
// inside any of the (rune-offset) protected spans removed. Bounds at a
// span's start or end are kept — they align with the span edge and don't
// split protected content. spans must be sorted by start.
func dropBoundsInsideSpans(bounds []boundary, spans []span) []boundary {
if len(spans) == 0 {
return bounds
}
out := bounds[:0]
boundLoop:
for _, b := range bounds {
for _, s := range spans {
if s.start >= b.runeStart {
break // remaining spans start at or after b — can't contain b
}
if b.runeStart < s.end {
continue boundLoop
}
}
out = append(out, b)
}
return out
}
// allRuneIndices returns every rune offset where needle starts in text.
// Only used for single-rune needles like form-feed.
func allRuneIndices(text, needle string) []int {
var out []int
if needle == "" {
return out
}
pos := 0
for _, r := range text {
if string(r) == needle {
out = append(out, pos)
}
pos++
}
return out
}
// appendChunk slices runes[start:end] into a Chunk and appends it to out.
// Pure-whitespace slices are skipped (boundary clustering can occasionally
// produce them). The Content stored is the raw slice — Start/End rune
// offsets must match utf8.RuneCountInString(Content) for downstream
// reconstruction code; whitespace stripping for embedding happens in
// Chunk.EmbeddingContent.
func appendChunk(out []Chunk, runes []rune, start, end int, seq *int) []Chunk {
if end <= start {
return out
}
raw := string(runes[start:end])
if strings.TrimSpace(raw) == "" {
return out
}
c := Chunk{Content: raw, Seq: *seq, Start: start, End: end}
*seq++
return append(out, c)
}
// appendOversizeBlock recursively chunks a region that is itself larger than
// cfg.ChunkSize, using the legacy splitter so internal length budgets and
// protected patterns are still respected.
func appendOversizeBlock(out []Chunk, runes []rune, start, end int, cfg SplitterConfig, seq *int) []Chunk {
if end <= start {
return out
}
subText := string(runes[start:end])
subs := SplitText(subText, cfg)
for _, s := range subs {
out = append(out, Chunk{
Content: s.Content,
Seq: *seq,
Start: start + s.Start,
End: start + s.End,
})
*seq++
}
return out
}
// applyOverlapAligned returns the rune offset where the next chunk should
// start. The target is `curEnd - overlap`, but we snap to the nearest
// preceding boundary (within 2x overlap) or, failing that, the previous
// newline so chunks don't begin mid-line / mid-word. Falls back to the raw
// target only if neither option is available.
//
// curEnd itself is always a boundary (the bin-packer flushes at boundary
// positions), so we exclude it from the search — picking it would yield
// zero overlap, defeating the purpose of this function.
func applyOverlapAligned(runes []rune, curEnd, overlap int, bounds []boundary) int {
if overlap <= 0 {
return curEnd
}
target := curEnd - overlap
if target < 0 {
target = 0
}
// Allowed search window: [curEnd - 2*overlap, curEnd)
windowStart := curEnd - 2*overlap
if windowStart < 0 {
windowStart = 0
}
// Prefer a semantic boundary strictly inside the window.
bestBound := -1
for _, b := range bounds {
if b.runeStart >= windowStart && b.runeStart < curEnd && b.runeStart > bestBound {
bestBound = b.runeStart
}
}
if bestBound >= 0 {
return bestBound
}
// Fallback: scan backwards from `target` to the previous newline, but
// not past windowStart so we keep the overlap roughly the right size.
for i := target; i > windowStart && i < len(runes); i-- {
if runes[i] == '\n' {
return i + 1
}
}
return target
}
@@ -0,0 +1,178 @@
package chunker
import (
"strings"
"testing"
)
func TestSplitByHeuristics_FormFeedBoundary(t *testing.T) {
doc := strings.Repeat("page one body text. ", 30) + "\f" + strings.Repeat("page two body. ", 30)
cfg := SplitterConfig{ChunkSize: 400, ChunkOverlap: 20, Separators: []string{". "}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("form feed should produce ≥2 chunks, got %d", len(chunks))
}
}
func TestSplitByHeuristics_NumberedSections(t *testing.T) {
body := strings.Repeat("body sentence. ", 8)
doc := "1. Introduction\n" + body + "\n\n2. Methods\n" + body + "\n\n3. Results\n" + body
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{". "}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("numbered sections should split: got %d chunks", len(chunks))
}
}
func TestSplitByHeuristics_GermanChapterMarkers(t *testing.T) {
body := strings.Repeat("Beispieltext. ", 10)
doc := "Kapitel 1: Einführung\n" + body + "\n\nKapitel 2: Hauptteil\n" + body
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{". "}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("German chapter markers should split: got %d", len(chunks))
}
}
func TestSplitByHeuristics_ChineseChapterMarkers(t *testing.T) {
body := strings.Repeat("内容内容内容。", 60)
doc := "第一章 引言\n" + body + "\n\n第二章 方法\n" + body
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{"。"}, Languages: []string{LangChinese}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("Chinese chapter markers should split: got %d", len(chunks))
}
}
func TestSplitByHeuristics_FallsThroughForUnstructuredDoc(t *testing.T) {
doc := strings.Repeat("plain prose without structure. ", 5)
cfg := SplitterConfig{ChunkSize: 1000, ChunkOverlap: 20}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) != 1 {
t.Errorf("unstructured short doc should be one chunk, got %d", len(chunks))
}
}
func TestSplitByHeuristics_OversizeBlockRecursesIntoLegacy(t *testing.T) {
huge := strings.Repeat("This is a long sentence. ", 200) // ~5000 chars
doc := "1. Intro\n" + huge
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 50, Separators: []string{". "}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 5 {
t.Errorf("oversize block should produce many sub-chunks, got %d", len(chunks))
}
// No single chunk should massively exceed the budget.
for i, c := range chunks {
if len([]rune(c.Content)) > 2*cfg.ChunkSize {
t.Errorf("chunk %d exceeds 2x size: %d runes", i, len([]rune(c.Content)))
}
}
}
func TestSplitByHeuristics_BoundariesAreOrdered(t *testing.T) {
doc := "Kapitel 1: A\nbody\n\n---\n\n2. Section B\nbody\n\nPage 3 of 10\n\n第三章 C\nbody"
bounds := findHeuristicBoundaries(doc, nil)
if len(bounds) < 2 {
t.Fatalf("expected multiple boundaries, got %d", len(bounds))
}
for i := 1; i < len(bounds); i++ {
if bounds[i].runeStart < bounds[i-1].runeStart {
t.Errorf("bounds not sorted: %d before %d", bounds[i].runeStart, bounds[i-1].runeStart)
}
}
}
func TestSplitByHeuristics_EmptyText(t *testing.T) {
if got := splitByHeuristicsImpl("", DefaultConfig(), nil); got != nil {
t.Errorf("empty doc should be nil, got %v", got)
}
}
// Regression: applyOverlapAligned previously included curEnd itself in its
// boundary search, and curEnd is always one of the bounds (the bin-packer
// flushes at boundary positions). The function therefore always returned
// curEnd, producing zero overlap regardless of cfg.ChunkOverlap.
func TestSplitByHeuristics_OverlapActuallyOverlaps(t *testing.T) {
// Build many small numbered sections so the bin-packer flushes mid-doc
// with at least one earlier boundary inside the overlap window.
var sb strings.Builder
for i := 1; i <= 12; i++ {
sb.WriteString("\n\n")
sb.WriteByte(byte('0' + i%10))
sb.WriteString(". ")
sb.WriteString(strings.Repeat("alpha beta gamma. ", 4)) // ~72 chars / section
}
doc := sb.String()
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 80, Separators: []string{". "}}
chunks := splitByHeuristicsImpl(doc, cfg, nil)
if len(chunks) < 2 {
t.Fatalf("need >=2 chunks to test overlap, got %d", len(chunks))
}
// At least one consecutive chunk pair must share a non-trivial suffix /
// prefix. We don't require *every* pair to overlap (oversize blocks
// short-circuit through legacy and reset chunkStart), but at least one
// regular flush boundary should produce real overlap.
saw := false
for i := 1; i < len(chunks); i++ {
prev := strings.TrimSpace(chunks[i-1].Content)
cur := strings.TrimSpace(chunks[i].Content)
// Walk back the longest suffix of prev that prefixes cur.
match := 0
maxScan := len(prev)
if len(cur) < maxScan {
maxScan = len(cur)
}
for n := 1; n <= maxScan; n++ {
if strings.HasPrefix(cur, prev[len(prev)-n:]) {
match = n
}
}
if match >= 20 {
saw = true
break
}
}
if !saw {
t.Fatalf("expected at least one chunk pair to overlap by >=20 chars, none did. chunk sizes: %v",
chunkLengths(chunks))
}
}
// Heuristic boundaries that fall inside protected regions (LaTeX block,
// table, link, etc.) must be dropped so the bin-packer doesn't break
// atomic content. Without the protected-span filter, a numbered-section
// looking line inside a $$...$$ math block would be picked as a boundary.
func TestSplitByHeuristics_DropsBoundariesInsideProtectedSpans(t *testing.T) {
body := strings.Repeat("filler. ", 30)
// LaTeX block whose middle line matches NumberedSectionPattern. The
// filter should drop that boundary so the math block stays intact.
doc := body + "\n\n$$\nx = 1\n1. equation step one\ny = 2\n$$\n\n" + body
bounds := findHeuristicBoundaries(doc, nil)
prot := protectedSpansRune(doc, protectedSpans(doc))
if len(prot) == 0 {
t.Fatalf("expected protected spans for doc, got none")
}
filtered := dropBoundsInsideSpans(bounds, prot)
for _, b := range filtered {
for _, s := range prot {
if b.runeStart > s.start && b.runeStart < s.end {
t.Errorf("boundary %d still inside protected span [%d,%d)", b.runeStart, s.start, s.end)
}
}
}
// And it should actually have removed at least one boundary.
if len(filtered) >= len(bounds) {
t.Errorf("filter removed nothing: before=%d after=%d", len(bounds), len(filtered))
}
}
func chunkLengths(chunks []Chunk) []int {
out := make([]int, len(chunks))
for i, c := range chunks {
out[i] = len([]rune(c.Content))
}
return out
}
@@ -0,0 +1,148 @@
package chunker
import (
"fmt"
"strings"
"testing"
"academy/internal/sourceloc"
"academy/internal/types"
)
func TestParentChildTableSourceOffsets(t *testing.T) {
splitters := []struct {
name string
split func(string, SplitterConfig, SplitterConfig) ParentChildResult
}{
{"legacy", SplitTextParentChild},
{"adaptive", SplitParentChild},
{"diagnostics", func(text string, parent, child SplitterConfig) ParentChildResult {
result, _ := SplitParentChildWithDiagnostics(text, parent, child)
return result
}},
}
for _, fixture := range []struct {
name, newline, row string
}{
{"ascii", "\n", "| apple | red |"},
{"unicode", "\n", "| 苹果🍎 | 北京 |"},
{"crlf", "\r\n", "| 苹果🍎 | 北京 |"},
} {
header := "| Item | City |" + fixture.newline + "| --- | --- |" + fixture.newline
// Repeated rows also catch attempts to recover positions with a text search.
text := "Intro" + fixture.newline + header +
strings.Repeat(fixture.row+fixture.newline, 12) + "| last | row |" + fixture.newline
parentCfg := SplitterConfig{
ChunkSize: 80, ChunkOverlap: 5, Separators: []string{"\n\n", "\n"}, Strategy: StrategyLegacy,
}
// Ensure this exercises a parent with a synthetic header, not merely
// children with headers inside a single source-backed parent.
parents := SplitText(text, parentCfg)
sawSyntheticParent := false
for _, parent := range parents {
if len([]rune(parent.Content)) > parent.End-parent.Start {
sawSyntheticParent = true
}
}
if !sawSyntheticParent {
t.Fatalf("%s fixture did not produce a parent with a synthetic header", fixture.name)
}
for _, splitter := range splitters {
// 12 isolates the virtual header as a child; 50 re-splits table
// rows; 160 keeps the parent intact (ParentIndex == -1).
for _, childSize := range []int{12, 50, 160} {
t.Run(fmt.Sprintf("%s/%s/child=%d", fixture.name, splitter.name, childSize), func(t *testing.T) {
childCfg := parentCfg
childCfg.ChunkSize = childSize
result := splitter.split(text, parentCfg, childCfg)
if len(result.Children) == 0 {
t.Fatal("expected children")
}
textRunes := []rune(text)
covered := make([]bool, len(textRunes))
var chunks []Chunk
for i, child := range result.Children {
if child.Seq != i {
t.Errorf("child %d has sequence %d", i, child.Seq)
}
if child.Start < 0 || child.End > len(textRunes) || child.Start >= child.End {
t.Fatalf("child %d has invalid source span [%d, %d), document length %d",
i, child.Start, child.End, len(textRunes))
}
content := []rune(child.Content)
span := child.End - child.Start
if span > len(content) {
t.Fatalf("child %d source span exceeds content length", i)
}
want := string(textRunes[child.Start:child.End])
if got := string(content[len(content)-span:]); got != want {
t.Fatalf("child %d source span [%d, %d): got suffix %q, want %q",
i, child.Start, child.End, got, want)
}
if child.ParentIndex >= 0 {
if child.ParentIndex >= len(result.Parents) {
t.Fatalf("child %d has invalid parent index %d", i, child.ParentIndex)
}
parent := result.Parents[child.ParentIndex]
if child.Start < parent.Start || child.End > parent.End {
t.Errorf("child %d source span escapes its parent", i)
}
} else if childSize == 160 && strings.Contains(child.Content, fixture.row) {
if !strings.Contains(child.Content, "| Item | City |") {
t.Errorf("child %d lost table header context", i)
}
}
for pos := child.Start; pos < child.End; pos++ {
covered[pos] = true
}
chunks = append(chunks, child.Chunk)
}
for pos, ok := range covered {
if !ok {
t.Fatalf("source rune %d is missing from children", pos)
}
}
if got := restoreTextFromChunks(chunks); got != text {
t.Fatalf("source reconstruction mismatch: got %q, want %q", got, text)
}
})
}
}
}
}
func TestParentChildTableCitationUsesSourceRow(t *testing.T) {
prefix := "| Item | City |\n| --- | --- |\n" + strings.Repeat("| 苹果🍎 | 北京 |\n", 12)
lastRow := "| last | row |\n"
text := prefix + lastRow
index := sourceloc.NewIndex(text, []types.SourceBlock{
{Start: 0, End: len([]rune(prefix)), Locator: types.SourceLocator{
Type: types.SourceLocatorSheet, Sheet: "Sheet1", RowStart: 1, RowEnd: 13,
}},
{Start: len([]rune(prefix)), End: len([]rune(text)), Locator: types.SourceLocator{
Type: types.SourceLocatorSheet, Sheet: "Sheet1", RowStart: 14, RowEnd: 14,
}},
})
parentCfg := SplitterConfig{
ChunkSize: 80, ChunkOverlap: 5, Separators: []string{"\n\n", "\n"}, Strategy: StrategyLegacy,
}
childCfg := parentCfg
childCfg.ChunkSize = 12
result := SplitParentChild(text, parentCfg, childCfg)
for _, child := range result.Children {
if child.Content != lastRow {
continue
}
// ProcessDocument assigns source evidence with these exact offsets.
locators := index.Locators(child.Start, child.End)
if len(locators) != 1 {
t.Fatalf("last row has %d source locators, want one", len(locators))
}
loc := locators[0]
if loc.Sheet != "Sheet1" || loc.RowStart != 14 || loc.RowEnd != 14 || loc.Quote != "| last | row |" {
t.Fatalf("last row points to the wrong source: %+v", loc)
}
return
}
t.Fatal("last table row was not retained as a child")
}
@@ -0,0 +1,97 @@
// Package chunker - patterns.go is the source of truth for multilingual
// regex patterns used by the heading-aware and heuristic splitters.
//
// Patterns are grouped by purpose (chapter markers, numbering, separators)
// and tagged with a priority that the heuristic splitter uses to rank
// candidate chunk boundaries.
package chunker
import "regexp"
// BoundaryPriority levels for heuristic chunk boundaries. Higher = stronger.
const (
PrioFormFeed = 100
PrioNumberedHead = 90
PrioChapterMarker = 85
PrioAllCapsHeading = 70
PrioVisualSep = 60
PrioPageFooter = 50
PrioBlankBlock = 40
)
// MarkdownHeadingPattern matches an ATX-style Markdown heading at line start.
// Capture groups: (1) hashes, (2) heading text.
var MarkdownHeadingPattern = regexp.MustCompile(`(?m)^(#{1,6})\s+(.+?)\s*#*\s*$`)
// FormFeedPattern matches the form-feed control character used by some PDF
// converters as a page break marker.
var FormFeedPattern = regexp.MustCompile(`\f`)
// NumberedSectionPattern matches lines starting with numeric or roman numbering
// followed by a non-empty title, e.g. "1. Intro", "2.3 Methods", "IV. Results",
// "2.2.1 用户与权限". The trailing dot after a multi-level numeral is optional
// because many technical documents write "1.1 Foo" without a closing dot.
var NumberedSectionPattern = regexp.MustCompile(`(?m)^[ \t]*(?:\d+(?:\.\d+){1,3}\.?|(?:\d+|[IVX]{1,5})\.)[ \t]+\S.{0,200}$`)
// AllCapsHeadingPattern matches short all-caps lines (likely section titles
// rendered without Markdown headings). It requires at least 4 letters and
// up to ~10 words. Trailing colons are tolerated.
var AllCapsHeadingPattern = regexp.MustCompile(`(?m)^[ \t]*([A-ZÄÖÜ][A-ZÄÖÜ \-]{3,80}):?\s*$`)
// VisualSeparatorPattern matches horizontal rules / divider lines used as
// section separators in plain text or pre-Markdown documents.
var VisualSeparatorPattern = regexp.MustCompile(`(?m)^[ \t]*(?:-{3,}|={3,}|\*{3,}|_{3,})[ \t]*$`)
// ExcessiveBlanksPattern matches three or more consecutive newlines, which
// usually denote a hard section break.
var ExcessiveBlanksPattern = regexp.MustCompile(`\n{3,}`)
// PageFooterPattern matches typical "Seite X von Y" / "Page X of Y" lines.
var PageFooterPattern = regexp.MustCompile(`(?mi)^[ \t]*(?:Seite|Page|页码?)\s+\d+(?:\s*(?:von|of|/)\s*\d+)?[ \t]*$`)
// GermanChapterPattern matches German chapter / section markers.
var GermanChapterPattern = regexp.MustCompile(`(?m)^[ \t]*(?:Kapitel|Abschnitt|Teil)\s+(?:[0-9]+|[IVX]{1,5})[\.: ].{0,200}$`)
// EnglishChapterPattern matches English chapter / section markers.
var EnglishChapterPattern = regexp.MustCompile(`(?m)^[ \t]*(?:Chapter|Section|Part)\s+(?:[0-9]+|[IVX]{1,5})[\.: ].{0,200}$`)
// ChineseChapterPattern matches CJK chapter / section markers like 第一章,
// 第3节, 第 1 章 (whitespace between 第 / numeral / unit is tolerated).
var ChineseChapterPattern = regexp.MustCompile(`(?m)^[ \t]*第[ \t]*[一二三四五六七八九十百千零〇0-9]+[ \t]*(?:章|节|節|部分|篇)[ \t]?.{0,200}$`)
// SentenceSeparators returns sentence-level separators tuned for the language.
// Used for fine-grained sub-splitting when a section is still too large.
func SentenceSeparators(lang string) []string {
switch lang {
case LangChinese:
return []string{"。", "!", "?", ";", "\n"}
case LangGerman, LangEnglish:
return []string{". ", "! ", "? ", "; ", "\n"}
default:
return []string{"。", "!", "?", ";", ". ", "! ", "? ", "; ", "\n"}
}
}
// ChapterPatternsForLangs returns the chapter-marker regexes that apply for
// the given language hints. An empty / unknown list returns all of them so
// that auto-detected documents still match.
func ChapterPatternsForLangs(langs []string) []*regexp.Regexp {
if len(langs) == 0 {
return []*regexp.Regexp{GermanChapterPattern, EnglishChapterPattern, ChineseChapterPattern}
}
var out []*regexp.Regexp
for _, l := range langs {
switch l {
case LangGerman:
out = append(out, GermanChapterPattern)
case LangEnglish:
out = append(out, EnglishChapterPattern)
case LangChinese:
out = append(out, ChineseChapterPattern)
}
}
if len(out) == 0 {
out = []*regexp.Regexp{GermanChapterPattern, EnglishChapterPattern, ChineseChapterPattern}
}
return out
}
@@ -0,0 +1,195 @@
package chunker
import "testing"
func TestMarkdownHeadingPattern_BasicLevels(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"# Heading 1", true},
{"## Heading 2", true},
{"###### Heading 6", true},
{"####### Too many", false},
{"#NoSpace", false},
{" # Indented", false},
{"plain text", false},
}
for _, c := range cases {
got := MarkdownHeadingPattern.MatchString(c.in)
if got != c.match {
t.Errorf("MarkdownHeadingPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestNumberedSectionPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"1. Introduction", true},
{"2.3 Methodology", true}, // multi-level numerals no longer require trailing dot
{"2.3. Methodology", true},
{"2.2.1 用户与权限", true}, // three-level numbering, Chinese title, no trailing dot
{"3.2.1 单机 Docker Compose", true},
{"IV. Results", true},
{"1.Introduction", false}, // requires whitespace
{"1.", false}, // requires title
{"1.1", false}, // requires title after numeral
{"1 NoDotSingleLevel", false}, // single-level numerals still need trailing dot
{"1.2.3.4.5 TooDeep", false}, // more than 3 sub-levels not accepted
{"plain text", false},
}
for _, c := range cases {
got := NumberedSectionPattern.MatchString(c.in)
if got != c.match {
t.Errorf("NumberedSectionPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestGermanChapterPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"Kapitel 1: Einführung", true},
{"Abschnitt 2.3 Methodik", true},
{"Abschnitt 3 Methodik", true},
{"Teil II Ergebnisse", true},
{"chapter 1", false},
}
for _, c := range cases {
got := GermanChapterPattern.MatchString(c.in)
if got != c.match {
t.Errorf("GermanChapterPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestEnglishChapterPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"Chapter 1: Intro", true},
{"Section 5 Methods", true},
{"Part IV Results", true},
{"Kapitel 1", false},
}
for _, c := range cases {
got := EnglishChapterPattern.MatchString(c.in)
if got != c.match {
t.Errorf("EnglishChapterPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestChineseChapterPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"第一章 引言", true},
{"第3节 方法论", true},
{"第二部分 结果", true},
{"第 1 章 引言", true}, // space between 第 / numeral / unit
{"第 一 章 引言", true},
{"第1章 引言", true},
{"Chapter 1", false},
{"第 章 空数字", false}, // missing numeral
}
for _, c := range cases {
got := ChineseChapterPattern.MatchString(c.in)
if got != c.match {
t.Errorf("ChineseChapterPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestVisualSeparatorPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"---", true},
{"========", true},
{"***", true},
{"____", true},
{"--", false}, // needs at least 3
{"-- text", false},
}
for _, c := range cases {
got := VisualSeparatorPattern.MatchString(c.in)
if got != c.match {
t.Errorf("VisualSeparatorPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestPageFooterPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"Seite 3 von 24", true},
{"Page 5 of 12", true},
{"page 7", true},
{"Seite 9", true},
{"页 3", true},
{"页码 3 / 12", true},
{"Some text", false},
}
for _, c := range cases {
got := PageFooterPattern.MatchString(c.in)
if got != c.match {
t.Errorf("PageFooterPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestAllCapsHeadingPattern(t *testing.T) {
cases := []struct {
in string
match bool
}{
{"INTRODUCTION", true},
{"METHODS AND MATERIALS", true},
{"Mixed Case Heading", false},
{"ABC", false}, // <4 chars
}
for _, c := range cases {
got := AllCapsHeadingPattern.MatchString(c.in)
if got != c.match {
t.Errorf("AllCapsHeadingPattern(%q): got %v want %v", c.in, got, c.match)
}
}
}
func TestSentenceSeparators(t *testing.T) {
if got := SentenceSeparators(LangChinese); got[0] != "。" {
t.Errorf("Chinese should start with 。, got %v", got)
}
if got := SentenceSeparators(LangEnglish); got[0] != ". " {
t.Errorf("English should start with '. ', got %v", got)
}
if got := SentenceSeparators("xx"); len(got) < 5 {
t.Errorf("Unknown lang should return mixed (>=5 separators), got %v", got)
}
}
func TestChapterPatternsForLangs(t *testing.T) {
if got := ChapterPatternsForLangs(nil); len(got) != 3 {
t.Errorf("nil langs should return all 3, got %d", len(got))
}
if got := ChapterPatternsForLangs([]string{LangGerman}); len(got) != 1 {
t.Errorf("only DE requested should return 1, got %d", len(got))
}
if got := ChapterPatternsForLangs([]string{LangGerman, LangChinese}); len(got) != 2 {
t.Errorf("DE+ZH requested should return 2, got %d", len(got))
}
if got := ChapterPatternsForLangs([]string{"xx"}); len(got) != 3 {
t.Errorf("unknown lang should fall back to all 3, got %d", len(got))
}
}
+236
View File
@@ -0,0 +1,236 @@
// Package chunker - profiler.go scans a document once to gather structure
// indicators that drive strategy selection (heading-aware vs. heuristic vs.
// recursive). Profiling is cheap (a few regex passes plus rune counting)
// and runs before any chunking decision is made.
package chunker
import (
"math"
"strings"
)
// DocProfile holds the document-level signals used to choose a chunking tier.
//
// The JSON shape (snake_case via struct tags) is part of the public preview
// endpoint API — keep field names stable. Internal callers should use the Go
// field names; only the preview handler relies on the wire format.
type DocProfile struct {
TotalChars int `json:"total_chars"`
TotalLines int `json:"total_lines"`
AvgLineLen float64 `json:"avg_line_len"`
StdLineLen float64 `json:"std_line_len"`
// Markdown structure
MdHeadingCounts map[int]int `json:"md_heading_counts"` // level (1..6) → count
MdHeadingTotal int `json:"md_heading_total"`
// Heuristic indicators
NumberedSectionCount int `json:"numbered_section_count"`
AllCapsShortLineCount int `json:"all_caps_short_line_count"`
BlankParagraphBreaks int `json:"blank_paragraph_breaks"`
FormFeedCount int `json:"form_feed_count"`
VisualSepCount int `json:"visual_sep_count"`
GermanChapterCount int `json:"german_chapter_count"`
EnglishChapterCount int `json:"english_chapter_count"`
ChineseChapterCount int `json:"chinese_chapter_count"`
RepeatedFooterCount int `json:"repeated_footer_count"`
// Content characteristics
HasTables bool `json:"has_tables"`
HasCode bool `json:"has_code"`
CodeRatio float64 `json:"code_ratio"`
// Detected language hints (best-effort)
DetectedLangs []string `json:"detected_langs"`
}
// HeadingDensity returns the share of lines that are Markdown headings.
func (p *DocProfile) HeadingDensity() float64 {
if p.TotalLines == 0 {
return 0
}
return float64(p.MdHeadingTotal) / float64(p.TotalLines)
}
// DominantHeadingLevel returns the heading level (1..6) that should drive
// section splitting. Preference order:
// 1. The lowest level (closest to root) that has at least 3 occurrences —
// a "real" structural backbone of the document.
// 2. Otherwise the deepest level present at least once — gives finer-grained
// boundaries for small documents that just have an H1 + a few H2s.
//
// Returns 0 when no Markdown headings exist.
func (p *DocProfile) DominantHeadingLevel() int {
if p.MdHeadingTotal == 0 {
return 0
}
for level := 1; level <= 6; level++ {
if p.MdHeadingCounts[level] >= 3 {
return level
}
}
for level := 6; level >= 1; level-- {
if p.MdHeadingCounts[level] > 0 {
return level
}
}
return 0
}
// HeuristicMarkerTotal sums the non-Markdown structural markers.
func (p *DocProfile) HeuristicMarkerTotal() int {
return p.NumberedSectionCount +
p.GermanChapterCount + p.EnglishChapterCount + p.ChineseChapterCount +
p.AllCapsShortLineCount + p.VisualSepCount + p.FormFeedCount
}
// ProfileDocument runs a single pass over text and returns its profile.
func ProfileDocument(text string) *DocProfile {
p := &DocProfile{
MdHeadingCounts: make(map[int]int),
}
if text == "" {
return p
}
p.TotalChars = len([]rune(text))
p.FormFeedCount = strings.Count(text, "\f")
lines := strings.Split(text, "\n")
p.TotalLines = len(lines)
// First pass: per-line markers and length stats
var lengths []float64
var fence markdownFence
codeChars := 0
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if code, delimiter := fence.consume(line); code {
p.HasCode = true
if !delimiter {
codeChars += len([]rune(line))
}
continue
}
runeLen := len([]rune(line))
lengths = append(lengths, float64(runeLen))
if matchHeading(line, &p.MdHeadingCounts) {
p.MdHeadingTotal++
continue
}
if NumberedSectionPattern.MatchString(line) {
p.NumberedSectionCount++
}
if GermanChapterPattern.MatchString(line) {
p.GermanChapterCount++
}
if EnglishChapterPattern.MatchString(line) {
p.EnglishChapterCount++
}
if ChineseChapterPattern.MatchString(line) {
p.ChineseChapterCount++
}
if AllCapsHeadingPattern.MatchString(line) {
p.AllCapsShortLineCount++
}
if VisualSeparatorPattern.MatchString(line) {
p.VisualSepCount++
}
if PageFooterPattern.MatchString(line) {
p.RepeatedFooterCount++
}
if strings.HasPrefix(trimmed, "|") && strings.HasSuffix(trimmed, "|") {
p.HasTables = true
}
}
if len(lengths) > 0 {
var sum float64
for _, l := range lengths {
sum += l
}
p.AvgLineLen = sum / float64(len(lengths))
var variance float64
for _, l := range lengths {
d := l - p.AvgLineLen
variance += d * d
}
variance /= float64(len(lengths))
p.StdLineLen = math.Sqrt(variance)
}
if p.TotalChars > 0 {
p.CodeRatio = float64(codeChars) / float64(p.TotalChars)
}
p.BlankParagraphBreaks = strings.Count(text, "\n\n\n")
// Sample a slice of the document for language detection — avoids paying
// O(N) scan cost on huge inputs while still giving a stable signal.
sample := text
if len(sample) > 4096 {
sample = sample[:4096]
}
lang := DetectLanguage(sample)
p.DetectedLangs = []string{lang}
if lang == LangMixed {
// Provide all three for downstream pattern selection.
p.DetectedLangs = []string{LangEnglish, LangGerman, LangChinese}
}
return p
}
// matchHeading checks whether line is an ATX heading and increments the
// appropriate level counter when so. Returns true on match.
func matchHeading(line string, counts *map[int]int) bool {
m := MarkdownHeadingPattern.FindStringSubmatch(line)
if m == nil {
return false
}
level := len(m[1])
if level < 1 || level > 6 {
return false
}
(*counts)[level]++
return true
}
// StrategyTier identifies which chunking implementation should run.
type StrategyTier string
const (
TierHeading StrategyTier = "heading"
TierHeuristic StrategyTier = "heuristic"
TierLegacy StrategyTier = "legacy"
)
// SelectStrategy returns the ordered tier chain to attempt for this document.
// The first tier is the primary choice; subsequent tiers are fallbacks if
// validation rejects the previous output. The "legacy" tier is appended as
// a final safety net so callers always receive at least one chunk-set.
func SelectStrategy(p *DocProfile) []StrategyTier {
if p == nil {
return []StrategyTier{TierLegacy}
}
var chain []StrategyTier
// Tier 1 candidate: Markdown heading-aware
if p.MdHeadingTotal >= 3 && p.HeadingDensity() > 0.005 && p.DominantHeadingLevel() > 0 {
chain = append(chain, TierHeading)
}
// Tier 2 candidate: heuristic boundary detection
if p.HeuristicMarkerTotal() >= 5 || p.FormFeedCount > 0 ||
p.GermanChapterCount+p.EnglishChapterCount+p.ChineseChapterCount > 0 {
chain = append(chain, TierHeuristic)
}
// Legacy is the ultimate fallback: always returns chunks even when
// validation fails, so callers never get an empty result.
chain = append(chain, TierLegacy)
return chain
}
@@ -0,0 +1,160 @@
package chunker
import (
"strings"
"testing"
)
func TestProfileDocument_Empty(t *testing.T) {
p := ProfileDocument("")
if p.TotalChars != 0 || p.TotalLines != 0 {
t.Errorf("empty doc should have zero stats, got %+v", p)
}
}
func TestProfileDocument_MarkdownHeadings(t *testing.T) {
doc := `# Title
Some intro text here.
## Section 1
Body of section 1.
## Section 2
Body of section 2.
### Subsection 2.1
Detail.
## Section 3
More body.`
p := ProfileDocument(doc)
if p.MdHeadingCounts[1] != 1 {
t.Errorf("expected 1 H1, got %d", p.MdHeadingCounts[1])
}
if p.MdHeadingCounts[2] != 3 {
t.Errorf("expected 3 H2, got %d", p.MdHeadingCounts[2])
}
if p.MdHeadingCounts[3] != 1 {
t.Errorf("expected 1 H3, got %d", p.MdHeadingCounts[3])
}
if p.MdHeadingTotal != 5 {
t.Errorf("expected 5 headings total, got %d", p.MdHeadingTotal)
}
if p.DominantHeadingLevel() != 2 {
t.Errorf("dominant level should be 2 (≥3 occurrences), got %d", p.DominantHeadingLevel())
}
}
func TestProfileDocument_DominantLevelFallback(t *testing.T) {
// No level reaches 3 occurrences — should fall back to most frequent.
doc := "# Single H1\n## H2 a\n## H2 b\n"
p := ProfileDocument(doc)
if p.DominantHeadingLevel() != 2 {
t.Errorf("expected fallback to level 2 (most frequent), got %d", p.DominantHeadingLevel())
}
}
func TestProfileDocument_NumberedSections(t *testing.T) {
doc := `1. Introduction
text
2. Methodology
text
3. Results
text`
p := ProfileDocument(doc)
if p.NumberedSectionCount < 3 {
t.Errorf("expected ≥3 numbered sections, got %d", p.NumberedSectionCount)
}
}
func TestProfileDocument_GermanChapters(t *testing.T) {
doc := "Kapitel 1: Einführung\n\nText\n\nKapitel 2: Hauptteil\n\nText"
p := ProfileDocument(doc)
if p.GermanChapterCount != 2 {
t.Errorf("expected 2 German chapters, got %d", p.GermanChapterCount)
}
}
func TestProfileDocument_ChineseChapters(t *testing.T) {
doc := "第一章 引言\n\n内容\n\n第二章 方法\n\n内容"
p := ProfileDocument(doc)
if p.ChineseChapterCount != 2 {
t.Errorf("expected 2 Chinese chapters, got %d", p.ChineseChapterCount)
}
}
func TestProfileDocument_FormFeed(t *testing.T) {
doc := "page 1 content\f\npage 2 content\f\npage 3 content"
p := ProfileDocument(doc)
if p.FormFeedCount != 2 {
t.Errorf("expected 2 form feeds, got %d", p.FormFeedCount)
}
}
func TestProfileDocument_DetectsCodeBlock(t *testing.T) {
doc := "Some prose.\n\n```go\nfunc main() {}\n```\n\nMore prose."
p := ProfileDocument(doc)
if !p.HasCode {
t.Error("expected HasCode=true for fenced block")
}
}
func TestProfileDocument_DetectsTable(t *testing.T) {
doc := "Intro.\n\n| col a | col b |\n| --- | --- |\n| 1 | 2 |\n"
p := ProfileDocument(doc)
if !p.HasTables {
t.Error("expected HasTables=true")
}
}
func TestProfileDocument_LineStatistics(t *testing.T) {
doc := "short\nthis is a longer line of text\nanother line here"
p := ProfileDocument(doc)
if p.TotalLines != 3 {
t.Errorf("expected 3 lines, got %d", p.TotalLines)
}
if p.AvgLineLen <= 0 {
t.Error("expected positive avg line len")
}
}
func TestSelectStrategy_HeadingDoc(t *testing.T) {
doc := "# A\nbody\n## B\nbody\n## C\nbody\n## D\nbody"
p := ProfileDocument(doc)
chain := SelectStrategy(p)
if chain[0] != TierHeading {
t.Errorf("expected heading tier first, got %v", chain)
}
}
func TestSelectStrategy_HeuristicDoc(t *testing.T) {
doc := strings.Repeat("Kapitel 1: Foo\nbody body body\n\n", 1) +
strings.Repeat("Kapitel 2: Bar\nbody body body\n\n", 1)
p := ProfileDocument(doc)
chain := SelectStrategy(p)
// no markdown headings → heuristic must come first (heading tier skipped)
if chain[0] != TierHeuristic {
t.Errorf("expected heuristic tier first, got %v", chain)
}
}
func TestSelectStrategy_PlainDoc(t *testing.T) {
doc := "just a paragraph of plain text without any structure indicators at all here"
p := ProfileDocument(doc)
chain := SelectStrategy(p)
if chain[0] != TierLegacy {
t.Errorf("expected legacy tier first for unstructured doc, got %v", chain)
}
}
func TestSelectStrategy_AlwaysFallsBackToLegacy(t *testing.T) {
for _, doc := range []string{"", "simple", "# H1\nbody"} {
p := ProfileDocument(doc)
chain := SelectStrategy(p)
if chain[len(chain)-1] != TierLegacy {
t.Errorf("chain must end with legacy, got %v for doc=%q", chain, doc)
}
}
}
@@ -0,0 +1,94 @@
package chunker
import (
"fmt"
"reflect"
"strings"
"testing"
)
func TestProtectedSpansMixedPatternsInDocumentOrder(t *testing.T) {
parts := []string{
"`示例 [link](url)`",
"![图](image.png)",
"$$x + y$$",
"| name | value |\n| --- | --- |\n",
"| cell | `code` |\n",
"```go\n[inside](code)\n```",
"[last](https://example.com)",
}
var docBuilder strings.Builder
for _, part := range parts {
docBuilder.WriteString(part)
if !strings.HasSuffix(part, "\n") {
docBuilder.WriteByte('\n')
}
}
doc := docBuilder.String()
var got []string
lastEnd := 0
for _, s := range protectedSpans(doc) {
if s.start < lastEnd {
t.Fatalf("overlapping or unordered span: %v after %d", s, lastEnd)
}
got = append(got, doc[s.start:s.end])
lastEnd = s.end
}
if !reflect.DeepEqual(got, parts) {
t.Fatalf("protected content = %q, want %q", got, parts)
}
// At the public entry point, overlapping inner matches must not split
// an inline-code span, table header, image or fenced block apart.
chunks := SplitText(doc, SplitterConfig{
ChunkSize: 64, ChunkOverlap: 0, Separators: []string{"\n", " "},
})
for _, part := range parts {
found := false
for _, chunk := range chunks {
if strings.Contains(chunk.Content, part) {
found = true
break
}
}
if !found {
t.Errorf("protected content split across chunks: %q", part)
}
}
}
func benchmarkMixedProtectedDocument(rows int) string {
return strings.Repeat("[link](https://example.com) and `inline code`\n", rows)
}
func BenchmarkProtectedSpansMixedPatterns(b *testing.B) {
for _, rows := range []int{1000, 4000, 16000} {
b.Run(fmt.Sprintf("rows_%d", rows), func(b *testing.B) {
doc := benchmarkMixedProtectedDocument(rows)
b.SetBytes(int64(len(doc)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
if len(protectedSpans(doc)) != 2*rows {
b.Fatal("missing protected spans")
}
}
})
}
}
func BenchmarkSplitTextMixedPatterns(b *testing.B) {
for _, rows := range []int{1000, 4000, 16000} {
b.Run(fmt.Sprintf("rows_%d", rows), func(b *testing.B) {
doc := benchmarkMixedProtectedDocument(rows)
cfg := DefaultConfig()
b.SetBytes(int64(len(doc)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
if len(SplitText(doc, cfg)) == 0 {
b.Fatal("missing chunks")
}
}
})
}
}
@@ -0,0 +1,135 @@
package chunker
import (
"strconv"
"strings"
"testing"
)
// buildOCRStrayBracketDoc models the OCR failure mode behind this regression:
// a full-width "【公章】" whose opening bracket was mis-read as the half-width
// '[' (closing bracket lost), followed later by an unrelated half-width
// "](...)" fragment. CommonMark forbids a link's text/destination from
// spanning a blank line, but the previous unbounded
// `\[[^\]]*\]\([^)]+\)` joined the stray '[' to the distant '](' and
// swallowed the entire document as one protected atomic span.
func buildOCRStrayBracketDoc() string {
var sb strings.Builder
sb.WriteString("[公章】\n\n")
for i := 0; i < 60; i++ {
sb.WriteString("这是第")
sb.WriteString(strconv.Itoa(i))
sb.WriteString("段用于测试切分的中文内容,包含常见标点符号。\n\n")
}
sb.WriteString("第三段(北京)\n\n")
sb.WriteString("[引用](来源)")
return sb.String()
}
func maxChunkRunes(chunks []Chunk) int {
best := 0
for _, c := range chunks {
if n := len([]rune(c.Content)); n > best {
best = n
}
}
return best
}
// TestSplitText_OCRStrayBracketDoesNotSwallowDocument is the core regression:
// before the fix the malformed '[' turned the whole document into a single
// protected span (~1700 runes) and SplitText returned one oversized chunk.
func TestSplitText_OCRStrayBracketDoesNotSwallowDocument(t *testing.T) {
doc := buildOCRStrayBracketDoc()
if !strings.Contains(doc, "[公章】") || !strings.Contains(doc, "](来源)") {
t.Fatalf("fixture missing malformed-bracket markers")
}
const chunkSize = 128
cfg := SplitterConfig{ChunkSize: chunkSize, ChunkOverlap: 0, Separators: []string{"\n\n", "\n", "。"}}
chunks := SplitText(doc, cfg)
t.Logf("doc=%d runes chunkSize=%d -> chunks=%d max=%d runes",
len([]rune(doc)), chunkSize, len(chunks), maxChunkRunes(chunks))
if len(chunks) < 2 {
t.Fatalf("expected multiple chunks, got %d (max=%d runes)", len(chunks), maxChunkRunes(chunks))
}
if got := maxChunkRunes(chunks); got > 2*chunkSize {
t.Fatalf("max chunk %d runes exceeds 2*chunkSize=%d: stray '[' swallowed the document", got, 2*chunkSize)
}
}
// TestSplit_OCRStrayBracketDoesNotSwallowDocument exercises the strategy-aware
// entry point with the legacy tier pinned, so the protected-pattern behaviour
// is what is under test rather than the profiler's tier selection.
func TestSplit_OCRStrayBracketDoesNotSwallowDocument(t *testing.T) {
doc := buildOCRStrayBracketDoc()
const chunkSize = 128
cfg := SplitterConfig{
ChunkSize: chunkSize,
ChunkOverlap: 0,
Separators: []string{"\n\n", "\n", "。"},
Strategy: StrategyLegacy,
}
chunks := Split(doc, cfg)
if len(chunks) < 2 {
t.Fatalf("expected multiple chunks, got %d (max=%d runes)", len(chunks), maxChunkRunes(chunks))
}
if got := maxChunkRunes(chunks); got > 2*chunkSize {
t.Fatalf("max chunk %d runes exceeds 2*chunkSize=%d: stray '[' swallowed the document", got, 2*chunkSize)
}
}
// TestProtectedSpans_NoCrossLineLinkOrImage asserts no protected span may
// contain a newline for the malformed document: link text and destination
// cannot span a blank line (CommonMark).
func TestProtectedSpans_NoCrossLineLinkOrImage(t *testing.T) {
doc := buildOCRStrayBracketDoc()
for _, s := range protectedSpans(doc) {
seg := doc[s.start:s.end]
if strings.Contains(seg, "\n") {
t.Fatalf("protected span spans a newline (%d runes): %q", len([]rune(seg)), seg)
}
}
}
// TestProtectedSpans_MarkdownLinksAndImagesStillProtected is the positive
// guard: the newline-bounded patterns must keep recognising well-formed
// single-line Markdown links and images.
func TestProtectedSpans_MarkdownLinksAndImagesStillProtected(t *testing.T) {
cases := []string{
"![alt](http://x/y.png)",
"[文字](http://x.com)",
`[link](url "title")`,
"![](resource://abc)",
}
for _, c := range cases {
spans := protectedSpans(c)
if len(spans) == 0 {
t.Errorf("expected %q to be protected, got no span", c)
continue
}
if spans[0].start != 0 || spans[0].end != len(c) {
t.Errorf("%q: protected span = [%d,%d), want [0,%d)", c, spans[0].start, spans[0].end, len(c))
}
}
}
// TestProtectedSpans_LiteralCrossLineExample documents that an isolated
// malformed bracket pair with NO complete '](...)' construct is never treated
// as a protected link/image region.
func TestProtectedSpans_MultilineLinkIntentionallyUnprotected(t *testing.T) {
// CommonMark allows a single soft line break in link text. The protected
// patterns still refuse it so a stray OCR '[' cannot swallow a paragraph.
doc := "[link\ntext](http://example.com)"
if spans := protectedSpans(doc); len(spans) != 0 {
t.Fatalf("expected multiline link to stay unprotected, got %v", spans)
}
}
func TestProtectedSpans_LiteralCrossLineExample(t *testing.T) {
doc := "[公章】\n\n第一段。\n\n第二段。\n\n第三段(北京)"
if spans := protectedSpans(doc); len(spans) != 0 {
t.Fatalf("expected no protected span, got %v", spans)
}
}
+932
View File
@@ -0,0 +1,932 @@
// Package chunker implements text splitting for document chunking.
//
// Ported from the Python docreader/splitter/splitter.py recursive text splitter.
package chunker
import (
"cmp"
"regexp"
"slices"
"strings"
"unicode/utf8"
"academy/internal/infrastructure/docparser"
)
// Chunk represents a piece of split text with position tracking.
//
// Content holds exactly the text from the original document between Start
// and End (rune offsets), so End-Start == utf8.RuneCountInString(Content).
// This invariant is relied on by document-reconstruction code paths
// (knowledge.go:2278+ for summary generation, UI highlighting, etc.).
//
// ContextHeader is a separately-tracked context string (e.g. a Markdown
// heading breadcrumb) that should be prepended at embedding/retrieval time
// but is NOT part of Content. Keeping the two apart preserves the
// position invariant while still letting embedding pipelines see the
// section context.
type Chunk struct {
Content string
ContextHeader string
Seq int
Start int
End int
}
// EmbeddingContent returns the text that should be fed to the embedding
// model — the ContextHeader prepended (when set) plus the chunk content.
// Use this where Content alone would lose semantic context (Tier-1 chunks).
//
// Content is returned verbatim from the source document (the End-Start
// rune-count invariant requires that), but for embedding we trim the
// surrounding whitespace so leading/trailing newlines from boundary slices
// don't dilute the embedded vector or waste tokens. Inner whitespace is
// preserved.
func (c Chunk) EmbeddingContent() string {
body := strings.TrimSpace(c.Content)
if c.ContextHeader == "" {
return body
}
return c.ContextHeader + "\n\n" + body
}
// ImageRef is an image reference found within a chunk's content.
type ImageRef struct {
OriginalRef string
AltText string
Start int // offset within the chunk content
End int
}
// SplitterConfig configures the text splitter. Strategy and TokenLimit are
// honored by the strategy entry point in strategy.go; the legacy SplitText
// path uses only ChunkSize/Overlap/Separators.
type SplitterConfig struct {
ChunkSize int
ChunkOverlap int
Separators []string
// Strategy selects an adaptive tier. Empty = legacy (backwards-compatible).
// See strategy.go for valid values.
Strategy string
// TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize chars.
TokenLimit int
// Languages hints multilingual heuristic patterns. Empty = auto-detect.
Languages []string
}
// Default chunk sizing constants. Single source of truth for the entire
// chunker package and the knowledge service via NormalizeSplitterConfig.
// The frontend KnowledgeBaseEditorModal mirrors these numbers in its initial
// form state — keep them in sync if you change either value here.
//
// DefaultChunkSize = 512 chars: ~100–130 English tokens / ~300 Chinese
// tokens. Validated as a strong baseline by the Vecta Feb-2026 benchmark
// across 50 academic papers. Use 200–400 for FAQ-style atomic content,
// 1000–2000 for narrative / argumentative documents.
//
// DefaultChunkOverlap = 80 chars (≈15% of DefaultChunkSize): community-
// recommended sweet spot between recall (an answer split across a
// boundary needs overlap to be retrievable) and storage cost. Use 0 for
// strictly atomic data (FAQ, JSON records), 150–200 for long narratives
// where reasoning crosses chunks.
//
// MIGRATION NOTE: Prior versions had three different overlap defaults
// (Go DefaultConfig: 64, knowledge.go buildSplitterConfig: 50, Python
// docreader: 100). All consolidated to 80 here.
//
// Existing knowledge bases that stored ChunkOverlap=0 in the DB pick
// this 80 up on next re-index; their previously-indexed embeddings will
// not match new ones bit-for-bit. Recall stays similar but search
// ranking can shift slightly. To freeze the old behavior on a per-KB
// basis, explicitly set ChunkingConfig.ChunkOverlap to 64 before
// re-indexing.
const (
DefaultChunkSize = 512
DefaultChunkOverlap = 80
)
// DefaultConfig returns sensible defaults.
func DefaultConfig() SplitterConfig {
return SplitterConfig{
ChunkSize: DefaultChunkSize,
ChunkOverlap: DefaultChunkOverlap,
Separators: []string{"\n\n", "\n", "。"},
}
}
// protectedPatterns are regex patterns for content that must not be split.
//
// The Markdown link/image patterns deliberately exclude '\n' and bound the
// link text / destination length: CommonMark forbids them from spanning a
// blank line, and the previous unbounded [^\]]* / [^)]+ let a stray '[' left
// behind by OCR swallow whole paragraphs as one "protected" atomic span,
// defeating chunking entirely.
var protectedPatterns = []*regexp.Regexp{
regexp.MustCompile(`(?s)\$\$.*?\$\$`), // LaTeX block math
// Markdown images / links: single line, bounded so a stray OCR '['
// cannot swallow a paragraph (CommonMark forbids blank-line spans).
regexp.MustCompile(`!\[[^\]\n]{0,200}\]\([^)\n]{1,500}\)`),
regexp.MustCompile(`\[[^\]\n]{1,200}\]\([^)\n]{1,500}\)`),
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+\\s*(?:\\|\\s*:?-{3,}:?\\s*)+\\|[\\r\\n]+"), // Table header+separator
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+"), // Table rows
regexp.MustCompile("(?s)```(?:\\w+)?[\\r\\n].*?```"), // Fenced code blocks
regexp.MustCompile("`[^`\\r\\n]+`"), // Markdown inline code
}
type span struct {
start, end int
}
// protectedSpansRune converts byte-offset protected spans to rune offsets
// in a single forward pass over text. Used by callers that work in rune
// space (e.g. the heuristic splitter) to avoid choosing chunk boundaries
// that cut through protected content. byteSpans must be sorted by start
// (protectedSpans guarantees this).
func protectedSpansRune(text string, byteSpans []span) []span {
if len(byteSpans) == 0 {
return nil
}
out := make([]span, 0, len(byteSpans))
runeIdx := 0
byteIdx := 0
for _, s := range byteSpans {
for byteIdx < s.start && byteIdx < len(text) {
_, size := utf8.DecodeRuneInString(text[byteIdx:])
byteIdx += size
runeIdx++
}
startRune := runeIdx
for byteIdx < s.end && byteIdx < len(text) {
_, size := utf8.DecodeRuneInString(text[byteIdx:])
byteIdx += size
runeIdx++
}
out = append(out, span{start: startRune, end: runeIdx})
}
return out
}
// protectedSpans finds all non-overlapping protected regions in text.
func protectedSpans(text string) []span {
type match struct {
start, end int
}
var all []match
for _, pat := range protectedPatterns {
locs := pat.FindAllStringIndex(text, -1)
for _, loc := range locs {
if loc[1]-loc[0] > 0 {
all = append(all, match{loc[0], loc[1]})
}
}
}
if len(all) == 0 {
return nil
}
// Matches are grouped by pattern, not document position. Avoid quadratic
// insertion sorting when a long document interleaves different patterns.
slices.SortFunc(all, func(a, b match) int {
if a.start != b.start {
return cmp.Compare(a.start, b.start)
}
return cmp.Compare(b.end, a.end)
})
// Remove overlaps
var result []span
lastEnd := 0
for _, m := range all {
if m.start >= lastEnd {
result = append(result, span{m.start, m.end})
lastEnd = m.end
}
}
return result
}
// splitUnit is a piece of text with its original position.
type splitUnit struct {
text string
start, end int
}
// splitBySeparators splits text by separators in priority order, recursively
// applying the next separator to any piece that is still larger than
// chunkSize. Mirrors the recursive priority semantics of the Python
// reference splitter (docreader/splitter/splitter.py:_split): if `\n\n`
// produces a piece that's still too big, `\n` (and subsequent separators)
// are applied within that piece — not to the whole text.
//
// chunkSize == 0 disables the recursion guard; callers that don't care
// about size budget (e.g. a final mergeUnits-style pass) pass 0.
func splitBySeparators(text string, separators []string, chunkSize int) []string {
if text == "" || len(separators) == 0 {
return []string{text}
}
if chunkSize > 0 && runeLen(text) <= chunkSize {
return []string{text}
}
for i, sep := range separators {
if sep == "" {
continue
}
re := regexp.MustCompile("(" + regexp.QuoteMeta(sep) + ")")
splits := re.Split(text, -1)
matches := re.FindAllString(text, -1)
if len(matches) == 0 {
continue
}
var pieces []string
for j, s := range splits {
if s != "" {
pieces = append(pieces, s)
}
if j < len(matches) && matches[j] != "" {
pieces = append(pieces, matches[j])
}
}
if len(pieces) <= 1 {
continue
}
// Recursively split any piece that is still too large with the
// remaining (lower-priority) separators.
var out []string
remaining := separators[i+1:]
for _, p := range pieces {
if chunkSize > 0 && runeLen(p) > chunkSize && len(remaining) > 0 {
out = append(out, splitBySeparators(p, remaining, chunkSize)...)
} else {
out = append(out, p)
}
}
return out
}
return []string{text}
}
// runeLen returns the number of runes in s.
func runeLen(s string) int {
return utf8.RuneCountInString(s)
}
// SplitText splits text into chunks with overlap, respecting protected patterns.
func SplitText(text string, cfg SplitterConfig) []Chunk {
if text == "" {
return nil
}
chunkSize := cfg.ChunkSize
chunkOverlap := cfg.ChunkOverlap
separators := cfg.Separators
if chunkSize <= 0 {
chunkSize = 512
}
if chunkOverlap < 0 {
chunkOverlap = 0
}
// Step 1: Find protected spans
protected := protectedSpans(text)
// Step 2: Split non-protected regions by separators, keep protected as atomic units.
// chunkSize is forwarded so splitBySeparators can recursively apply lower-priority
// separators to oversize pieces (Python-parity recursive split).
units := buildUnitsWithProtection(text, protected, separators, chunkSize)
// Step 3: Merge units into chunks with overlap
return mergeUnits(units, chunkSize, chunkOverlap)
}
// buildUnitsWithProtection splits text into units, preserving protected spans as atomic.
// Start/End positions in the returned units are rune offsets (not byte offsets),
// because downstream merge logic indexes content via []rune slicing.
// If a protected span exceeds maxProtectedSize, it will be forcibly split to prevent
// creating chunks that are too large for downstream processing (e.g., embedding APIs).
// chunkSize is forwarded to splitBySeparators so recursive splitting can keep pieces
// under the budget when one separator alone leaves a piece oversize.
func buildUnitsWithProtection(text string, protected []span, separators []string, chunkSize int) []splitUnit {
const maxProtectedSize = 7500 // Maximum size for a protected unit (留余量给标题等)
var units []splitUnit
bytePos := 0
runePos := 0
for _, p := range protected {
if p.start > bytePos {
pre := text[bytePos:p.start]
parts := splitBySeparators(pre, separators, chunkSize)
runeOffset := runePos
for _, part := range parts {
partRuneLen := runeLen(part)
units = append(units, splitUnit{
text: part,
start: runeOffset,
end: runeOffset + partRuneLen,
})
runeOffset += partRuneLen
}
runePos += runeLen(pre)
}
protText := text[p.start:p.end]
protRuneLen := runeLen(protText)
// If protected content is too large, forcibly split it
if protRuneLen > maxProtectedSize {
// Split into smaller chunks at line breaks or spaces
runes := []rune(protText)
offset := 0
for offset < len(runes) {
chunkEnd := offset + maxProtectedSize
if chunkEnd > len(runes) {
chunkEnd = len(runes)
} else {
// Try to break at a newline or space
for i := chunkEnd - 1; i > offset && i > chunkEnd-200; i-- {
if runes[i] == '\n' || runes[i] == ' ' {
chunkEnd = i + 1
break
}
}
}
chunkText := string(runes[offset:chunkEnd])
chunkLen := chunkEnd - offset
units = append(units, splitUnit{
text: chunkText,
start: runePos + offset,
end: runePos + offset + chunkLen,
})
offset = chunkEnd
}
} else {
// Normal case: keep protected content as a single unit
units = append(units, splitUnit{
text: protText,
start: runePos,
end: runePos + protRuneLen,
})
}
runePos += protRuneLen
bytePos = p.end
}
if bytePos < len(text) {
remaining := text[bytePos:]
parts := splitBySeparators(remaining, separators, chunkSize)
runeOffset := runePos
for _, part := range parts {
partRuneLen := runeLen(part)
units = append(units, splitUnit{
text: part,
start: runeOffset,
end: runeOffset + partRuneLen,
})
runeOffset += partRuneLen
}
}
return units
}
// mergeUnits combines split units into chunks with overlap tracking.
// Enforces an absolute maximum chunk size to prevent exceeding downstream limits (e.g., embedding APIs).
// Active contextual headers (e.g., Markdown table headers) are prepended to new
// chunks so that every chunk carries its own header context.
func mergeUnits(units []splitUnit, chunkSize, chunkOverlap int) []Chunk {
if len(units) == 0 {
return nil
}
const absoluteMaxSize = 7500
ht := newHeaderTracker()
var chunks []Chunk
var current []splitUnit
curLen := 0
for _, u := range units {
uLen := runeLen(u.text)
// If this single unit exceeds absolute max, force split it further
if uLen > absoluteMaxSize {
// Flush current chunk if any
if len(current) > 0 {
chunks = append(chunks, buildChunk(current, len(chunks)))
current = nil
curLen = 0
}
// Update header state even for oversized units
ht.update(u.text)
// Split this oversized unit into smaller chunks
runes := []rune(u.text)
offset := 0
for offset < len(runes) {
chunkEnd := offset + absoluteMaxSize
if chunkEnd > len(runes) {
chunkEnd = len(runes)
} else {
for i := chunkEnd - 1; i > offset && i > chunkEnd-200; i-- {
if runes[i] == '\n' || runes[i] == ' ' {
chunkEnd = i + 1
break
}
}
}
chunkText := string(runes[offset:chunkEnd])
chunks = append(chunks, Chunk{
Content: chunkText,
Seq: len(chunks),
Start: u.start + offset,
End: u.start + chunkEnd,
})
offset = chunkEnd
}
continue
}
// Update header tracking
ht.update(u.text)
// Flush at table boundary so the next table is not merged into a chunk
// that still carries the previous table's prepended header context.
if ht.headerEndedThisUnit && len(current) > 0 {
chunks = append(chunks, buildChunk(current, len(chunks)))
current = nil
curLen = 0
}
headers := ht.getHeaders()
headersLen := runeLen(headers)
if headersLen > chunkSize {
headers = ""
headersLen = 0
}
// If adding this unit (plus reserving space for headers in a potential
// next chunk) would exceed chunk size, flush the current chunk.
if curLen+uLen+headersLen > chunkSize && len(current) > 0 {
chunks = append(chunks, buildChunk(current, len(chunks)))
// Keep overlap from the end of current
current, curLen = computeOverlap(current, chunkOverlap, chunkSize, uLen)
// Shrink overlap further if needed to fit headers + next unit
if headers != "" && headersLen+uLen <= chunkSize {
for len(current) > 0 && curLen+uLen+headersLen > chunkSize {
curLen -= runeLen(current[0].text)
current = current[1:]
}
// Prepend headers if the column-name context is not already present
// in the overlap or the next unit being added.
overlapText := unitsText(current)
if !headerAlreadyPresent(headers, overlapText, u.text) &&
!headerColumnMismatch(headers, u.text) {
startPos := u.start
if len(current) > 0 {
startPos = current[0].start
}
hUnit := splitUnit{text: headers, start: startPos, end: startPos}
current = append([]splitUnit{hUnit}, current...)
curLen += headersLen
}
}
}
// Check if adding this unit would exceed absolute max
if curLen+uLen > absoluteMaxSize {
if len(current) > 0 {
chunks = append(chunks, buildChunk(current, len(chunks)))
current = nil
curLen = 0
}
}
current = append(current, u)
curLen += uLen
}
// Flush remaining
if len(current) > 0 {
chunks = append(chunks, buildChunk(current, len(chunks)))
}
return chunks
}
// unitsText concatenates the text of all units.
func unitsText(units []splitUnit) string {
var sb strings.Builder
for _, u := range units {
sb.WriteString(u.text)
}
return sb.String()
}
// headerAlreadyPresent returns true if the column-name row from the header
// is already present in the overlap or the next unit, preventing duplication.
func headerAlreadyPresent(headers, overlapText, unitText string) bool {
// Fast path: full header already in overlap or unit
if strings.Contains(overlapText, headers) || strings.Contains(unitText, headers) {
return true
}
// Extract the column-name row (first meaningful non-separator line).
// For a rewritten header like "| col1 | col2 |\n| --- | --- |\n",
// the first line is the column names.
colRow := headerColumnRow(headers)
if colRow == "" {
return false
}
return strings.Contains(overlapText, colRow) || strings.Contains(unitText, colRow)
}
// headerColumnRow extracts the column-name line from a header string.
// Returns empty string if the header has no meaningful column names.
func headerColumnRow(header string) string {
for _, line := range strings.Split(header, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.Contains(line, "---") {
continue
}
// Skip lines that are only pipes/whitespace (empty header rows)
onlyPipes := true
for _, r := range line {
if r != '|' && r != ' ' && r != '\t' {
onlyPipes = false
break
}
}
if !onlyPipes {
return line
}
}
return ""
}
func buildChunk(units []splitUnit, seq int) Chunk {
var sb strings.Builder
for _, u := range units {
sb.WriteString(u.text)
}
return Chunk{
Content: sb.String(),
Seq: seq,
Start: units[0].start,
End: units[len(units)-1].end,
}
}
// computeOverlap returns the semantic suffix to keep for overlap and its total
// rune length.
//
// The configured overlap is a hard upper bound, not a raw character slice.
// Boundary detection may inspect up to four additional runes immediately
// before that tail window so a separator cut by the window boundary remains
// visible. A candidate is eligible only when its last rune is at position -1
// relative to the original window, or later, so retained content never exceeds
// the overlap limit. Eligible boundaries use this priority:
//
// 1. paragraph break (\n\n / \r\n\r\n)
// 2. line break (\n / \r\n)
// 3. sentence end (。?!, ". ", "? ", "! ")
//
// Priority wins first; for boundaries with the same priority, the earliest
// one in the window wins so the useful overlap is as large as possible. The
// next chunk starts immediately after the selected separator. If the window
// has no valid semantic boundary, no overlap is retained. This keeps overlap
// deterministic and bounded while allowing a boundary inside a large split
// unit (the previous implementation could only retain whole units and often
// collapsed to zero overlap for ordinary paragraphs).
const semanticOverlapLookbehind = 4 // rune length of the longest separator: \r\n\r\n
func computeOverlap(current []splitUnit, chunkOverlap, chunkSize, nextLen int) ([]splitUnit, int) {
if chunkOverlap <= 0 {
return nil, 0
}
// Overlap is part of the next chunk's total size. When the incoming unit
// is already close to the chunk budget, shrink the search window rather
// than creating an oversized chunk.
maxOverlap := chunkOverlap
if remaining := chunkSize - nextLen; remaining < maxOverlap {
maxOverlap = remaining
}
if maxOverlap <= 0 {
return nil, 0
}
window := semanticOverlapWindow(current, maxOverlap+semanticOverlapLookbehind)
if len(window) == 0 {
return nil, 0
}
windowText := unitsText(window)
// Coordinates before originalWindowStart are the lookbehind region. With
// end-exclusive offsets, requiring boundaryEnd >= originalWindowStart is
// equivalent to requiring the separator's final rune to be at -1 or later.
originalWindowStart := runeLen(windowText) - maxOverlap
if originalWindowStart < 0 {
originalWindowStart = 0
}
boundaryEnd, ok := findSemanticOverlapBoundaryEndingAtOrAfter(windowText, originalWindowStart)
if !ok {
return nil, 0
}
overlap := trimUnitsPrefix(window, boundaryEnd)
overlapLen := 0
for _, u := range overlap {
overlapLen += runeLen(u.text)
}
if overlapLen <= 0 || overlapLen > maxOverlap || strings.TrimSpace(unitsText(overlap)) == "" {
return nil, 0
}
return overlap, overlapLen
}
// semanticOverlapWindow returns at most maxLen source-backed runes from the
// tail of current. It may slice inside the first retained splitUnit so a
// semantic boundary inside a large paragraph remains discoverable. Synthetic
// zero-width units (for example repeated table headers) form a hard barrier:
// crossing them would break the Start/End-to-Content source invariant.
func semanticOverlapWindow(current []splitUnit, maxLen int) []splitUnit {
if maxLen <= 0 || len(current) == 0 {
return nil
}
remaining := maxLen
reversed := make([]splitUnit, 0, len(current))
for i := len(current) - 1; i >= 0 && remaining > 0; i-- {
u := current[i]
uLen := runeLen(u.text)
if uLen == 0 {
continue
}
// Header markers contain generated text but occupy no source range.
// Do not include or cross them when deriving an overlap suffix.
if u.start == u.end || u.end-u.start != uLen {
break
}
if uLen <= remaining {
reversed = append(reversed, u)
remaining -= uLen
continue
}
runes := []rune(u.text)
start := uLen - remaining
reversed = append(reversed, splitUnit{
text: string(runes[start:]),
start: u.start + start,
end: u.end,
})
remaining = 0
}
if len(reversed) == 0 {
return nil
}
window := make([]splitUnit, len(reversed))
for i := range reversed {
window[len(reversed)-1-i] = reversed[i]
}
return window
}
type semanticOverlapBoundary struct {
start int
end int
priority int
}
// findSemanticOverlapBoundary returns the rune offset immediately after the
// selected separator. Boundaries inside protected Markdown/code/math regions
// are ignored, and a boundary is invalid when only whitespace follows it.
func findSemanticOverlapBoundary(text string) (int, bool) {
return findSemanticOverlapBoundaryEndingAtOrAfter(text, 0)
}
// findSemanticOverlapBoundaryEndingAtOrAfter applies the normal priority and
// earliest-position rules only to candidates whose end-exclusive rune offset
// is at least minEnd. Filtering before comparison prevents an earlier but
// ineligible lookbehind separator from hiding a later eligible boundary.
func findSemanticOverlapBoundaryEndingAtOrAfter(text string, minEnd int) (int, bool) {
runes := []rune(text)
if len(runes) == 0 {
return 0, false
}
if minEnd < 0 {
minEnd = 0
}
if minEnd > len(runes) {
return 0, false
}
protected := protectedSpansRune(text, protectedSpans(text))
insideProtected := func(pos int) bool {
for _, p := range protected {
if pos < p.start {
return false
}
if pos >= p.start && pos < p.end {
return true
}
}
return false
}
hasMeaningfulTail := func(end int) bool {
return end >= 0 && end < len(runes) && strings.TrimSpace(string(runes[end:])) != ""
}
var best semanticOverlapBoundary
found := false
consider := func(start, end, priority int) {
if start < 0 || end <= start || end < minEnd || end > len(runes) ||
insideProtected(start) || !hasMeaningfulTail(end) {
return
}
candidate := semanticOverlapBoundary{start: start, end: end, priority: priority}
if !found || candidate.priority < best.priority ||
(candidate.priority == best.priority && candidate.start < best.start) {
best = candidate
found = true
}
}
// Mark paragraph-break runes so their component newlines are not also
// emitted as lower-priority line-break candidates.
paragraphRune := make([]bool, len(runes))
for i := 0; i < len(runes); i++ {
switch {
case i+3 < len(runes) && runes[i] == '\r' && runes[i+1] == '\n' &&
runes[i+2] == '\r' && runes[i+3] == '\n':
consider(i, i+4, 1)
for j := i; j < i+4; j++ {
paragraphRune[j] = true
}
i += 3
case i+1 < len(runes) && runes[i] == '\n' && runes[i+1] == '\n':
consider(i, i+2, 1)
paragraphRune[i], paragraphRune[i+1] = true, true
i++
}
}
for i := 0; i < len(runes); i++ {
if paragraphRune[i] {
continue
}
if runes[i] == '\r' && i+1 < len(runes) && runes[i+1] == '\n' && !paragraphRune[i+1] {
consider(i, i+2, 2)
i++
continue
}
if runes[i] == '\n' {
consider(i, i+1, 2)
}
}
for i := 0; i < len(runes); i++ {
switch runes[i] {
case '。', '?', '!':
consider(i, i+1, 3)
case '.', '?', '!':
if i+1 < len(runes) && runes[i+1] == ' ' {
consider(i, i+2, 3)
}
}
}
if !found {
return 0, false
}
return best.end, true
}
// trimUnitsPrefix removes prefixLen source runes while preserving the
// remaining units' original positions. prefixLen is relative to unitsText.
func trimUnitsPrefix(units []splitUnit, prefixLen int) []splitUnit {
if prefixLen <= 0 {
out := make([]splitUnit, len(units))
copy(out, units)
return out
}
remaining := prefixLen
out := make([]splitUnit, 0, len(units))
for _, u := range units {
uLen := runeLen(u.text)
if remaining >= uLen {
remaining -= uLen
continue
}
if remaining > 0 {
runes := []rune(u.text)
u.text = string(runes[remaining:])
u.start += remaining
remaining = 0
}
out = append(out, u)
}
return out
}
// ParentChildResult holds the two-level chunking output.
// Parent chunks provide context (large window), child chunks are used for
// embedding/retrieval (small window). Each child carries its ParentIndex so
// the caller can wire up ParentChunkID after DB insertion.
type ParentChildResult struct {
Parents []Chunk
Children []ChildChunk
}
// ChildChunk extends Chunk with a reference to its parent.
type ChildChunk struct {
Chunk
ParentIndex int // index into ParentChildResult.Parents
}
// SplitTextParentChild performs two-level chunking:
// 1. Split text into large parent chunks (parentCfg).
// 2. Split each parent into smaller child chunks (childCfg) for embedding.
//
// The child Seq is globally unique across the entire document.
func SplitTextParentChild(text string, parentCfg, childCfg SplitterConfig) ParentChildResult {
parents := SplitText(text, parentCfg)
if len(parents) == 0 {
return ParentChildResult{}
}
var newParents []Chunk
var children []ChildChunk
childSeq := 0
for _, parent := range parents {
subs := mapChildrenToSource(parent, SplitText(parent.Content, childCfg))
parentIndex := -1
if len(subs) > 1 || (len(subs) == 1 && subs[0].Content != parent.Content) {
parentIndex = len(newParents)
newParents = append(newParents, parent)
}
for _, sub := range subs {
sub.Seq = childSeq
children = append(children, ChildChunk{
Chunk: sub,
ParentIndex: parentIndex,
})
childSeq++
}
}
return ParentChildResult{Parents: newParents, Children: children}
}
// mapChildrenToSource translates offsets in parent.Content to document offsets.
// A parent may start with a synthetic table header that occupies no source
// positions. Keep that context in Content, but exclude it from the mapped span
// and discard children that contain only this synthetic prefix.
func mapChildrenToSource(parent Chunk, children []Chunk) []Chunk {
offset := parent.End - runeLen(parent.Content)
out := children[:0]
for _, child := range children {
child.Start = max(parent.Start, offset+child.Start)
child.End += offset
if child.End <= child.Start {
continue
}
out = append(out, child)
}
return out
}
// ExtractImageRefs extracts markdown image references from text.
// The URL group supports one level of balanced parentheses so that URLs
// like https://example.com/item_(abc)/123 are captured in full.
var imageRefPattern = regexp.MustCompile(`!\[([^\]]*)\]\(([^()\s]*(?:\([^)]*\)[^()\s]*)*)\)`)
func ExtractImageRefs(text string) []ImageRef {
text = docparser.UnwrapLinkedImages(text)
matches := imageRefPattern.FindAllStringSubmatchIndex(text, -1)
var refs []ImageRef
for _, m := range matches {
refs = append(refs, ImageRef{
OriginalRef: text[m[4]:m[5]], // group 2: URL
AltText: text[m[2]:m[3]], // group 1: alt text
Start: m[0],
End: m[1],
})
}
return refs
}
File diff suppressed because it is too large. Load diff
+361
View File
@@ -0,0 +1,361 @@
// Package chunker - strategy.go is the public entry point for adaptive
// chunking. Callers invoke Split / SplitParentChild instead of the legacy
// SplitText / SplitTextParentChild functions; the strategy resolver picks
// a tier based on document profile and the SplitterConfig.Strategy hint.
//
// The legacy entry points still exist in splitter.go for backwards
// compatibility — strategy.go simply layers a tier-selector on top.
package chunker
import (
"context"
"strings"
"academy/internal/logger"
)
// Strategy values for SplitterConfig.Strategy.
const (
StrategyAuto = "auto"
StrategyHeading = "heading"
StrategyHeuristic = "heuristic"
StrategyRecursive = "recursive"
StrategyLegacy = "legacy"
)
// Split chunks text using the strategy configured in cfg. When cfg.Strategy
// is empty or "auto" the document profiler picks the tier. The function
// always returns a non-nil result: on tier failure the chain falls through
// to the legacy splitter, which is the original Tier 3 implementation.
//
// Hot path: avoids the Diagnostics struct allocation that
// SplitWithDiagnostics performs (matters in SplitParentChild where
// Split is called once per parent).
func Split(text string, cfg SplitterConfig) []Chunk {
if text == "" {
return nil
}
cfg = ensureDefaults(cfg)
chain, profile := resolveChainWithProfile(text, cfg)
totalChars := len([]rune(text))
var lastOut []Chunk
for i, tier := range chain {
out := runTier(tier, text, cfg, profile)
if v := ValidateChunks(out, totalChars, cfg.ChunkSize); v.OK {
return out
} else {
logger.Debugf(context.Background(), "chunker: tier %s rejected: %s", tier, v.Reason)
}
if tier == TierLegacy && i == len(chain)-1 {
lastOut = out
}
}
if lastOut != nil {
return lastOut
}
return SplitText(text, cfg)
}
// TierRejection records why a tier was rejected by the validator and the
// chain advanced to the next tier. Surfaced by SplitWithDiagnostics for
// the debug/preview endpoint.
type TierRejection struct {
Tier StrategyTier `json:"tier"`
Reason string `json:"reason"`
}
// Diagnostics captures which tier produced the returned chunks plus the
// chain that was attempted, any rejected tiers along the way, and the
// document profile that drove tier selection.
//
// Useful for surfacing in a debug UI; not produced by the normal Split
// path. The JSON shape is part of the public preview-endpoint API — keep
// field names stable.
type Diagnostics struct {
SelectedTier StrategyTier `json:"selected_tier"`
TierChain []StrategyTier `json:"tier_chain"`
Rejected []TierRejection `json:"rejected"`
// Profile is set when the auto strategy resolved the chain via the
// document profiler. nil when an explicit Strategy bypassed profiling.
Profile *DocProfile `json:"profile,omitempty"`
}
// SplitWithDiagnostics is the same as Split but also returns the
// diagnostic trace (selected tier, full chain, rejection reasons,
// profile when available). Use this for the chunker preview endpoint
// where the caller wants to know which tier won and why others lost.
func SplitWithDiagnostics(text string, cfg SplitterConfig) ([]Chunk, *Diagnostics) {
// Default selected tier to legacy so an empty diag never carries the
// zero string — that would render as a blank tag in the debug UI.
diag := &Diagnostics{SelectedTier: TierLegacy}
if text == "" {
return nil, diag
}
cfg = ensureDefaults(cfg)
chain, profile := resolveChainWithProfile(text, cfg)
diag.TierChain = chain
diag.Profile = profile
totalChars := len([]rune(text))
var lastOut []Chunk
var lastTier StrategyTier
for i, tier := range chain {
out := runTier(tier, text, cfg, profile)
v := ValidateChunks(out, totalChars, cfg.ChunkSize)
if v.OK {
diag.SelectedTier = tier
return out, diag
}
diag.Rejected = append(diag.Rejected, TierRejection{Tier: tier, Reason: v.Reason})
logger.Debugf(context.Background(), "chunker: tier %s rejected: %s", tier, v.Reason)
if tier == TierLegacy && i == len(chain)-1 {
lastOut = out
lastTier = tier
}
}
if lastOut != nil {
diag.SelectedTier = lastTier
return lastOut, diag
}
// Defensive last-ditch fallback.
return SplitText(text, cfg), diag
}
// SplitParentChild is the strategy-aware analog of SplitTextParentChild.
// It runs the tier selector for parent splitting, then re-splits each
// parent into children with the small-chunk config.
//
// Child splitting honours childCfg.Strategy. If it is empty/auto and a
// parent has its own internal structure (sub-headings, numbered sub-
// sections), the appropriate tier picks it up so child chunks carry a
// finer-grained breadcrumb than the parent's. Re-profiling each parent
// is bounded by O(sum(parent_size)) ≈ O(N) total, which is the same
// order as the original parent profiling pass.
func SplitParentChild(text string, parentCfg, childCfg SplitterConfig) ParentChildResult {
result, _ := splitParentChild(text, parentCfg, childCfg, false)
return result
}
// SplitParentChildWithDiagnostics is the diagnostics-aware form of
// SplitParentChild. The result is identical to SplitParentChild; diagnostics
// describe the strategy selected for the parent split over the full document.
// It is intended for debug surfaces rather than the ingestion hot path.
func SplitParentChildWithDiagnostics(text string, parentCfg, childCfg SplitterConfig) (ParentChildResult, *Diagnostics) {
return splitParentChild(text, parentCfg, childCfg, true)
}
func splitParentChild(text string, parentCfg, childCfg SplitterConfig, withDiagnostics bool) (ParentChildResult, *Diagnostics) {
parentCfg = ensureDefaults(parentCfg)
childCfg = ensureDefaults(childCfg)
var (
parents []Chunk
diag *Diagnostics
)
if withDiagnostics {
parents, diag = SplitWithDiagnostics(text, parentCfg)
} else {
parents = Split(text, parentCfg)
}
if len(parents) == 0 {
return ParentChildResult{}, diag
}
var newParents []Chunk
var children []ChildChunk
childSeq := 0
for _, parent := range parents {
subs := mapChildrenToSource(parent, Split(parent.Content, childCfg))
parentIndex := -1
if len(subs) > 1 || (len(subs) == 1 && subs[0].Content != parent.Content) {
parentIndex = len(newParents)
newParents = append(newParents, parent)
}
for _, sub := range subs {
sub.Seq = childSeq
sub.ContextHeader = mergeBreadcrumbs(parent.ContextHeader, sub.ContextHeader)
children = append(children, ChildChunk{Chunk: sub, ParentIndex: parentIndex})
childSeq++
}
}
return ParentChildResult{Parents: newParents, Children: children}, diag
}
// NormalizeSplitterConfig applies the same base splitter defaults used by
// knowledge ingestion before parent-child derivation or single-pass splitting.
func NormalizeSplitterConfig(cfg SplitterConfig) SplitterConfig {
if cfg.ChunkSize <= 0 {
cfg.ChunkSize = DefaultChunkSize
}
if cfg.ChunkOverlap <= 0 {
cfg.ChunkOverlap = DefaultChunkOverlap
}
if len(cfg.Separators) == 0 {
cfg.Separators = []string{"\n\n", "\n", "。"}
}
return cfg
}
// NormalizeLineEndings canonicalizes text before chunking. Browser textareas
// normalize pasted CRLF text to LF, while uploaded files preserve their
// original line endings; without this, the same document produces different
// character counts and chunk boundaries.
func NormalizeLineEndings(text string) string {
if !strings.Contains(text, "\r") {
return text
}
text = strings.ReplaceAll(text, "\r\n", "\n")
return strings.ReplaceAll(text, "\r", "\n")
}
// DeriveParentChildConfigs produces the exact parent and child splitter
// configurations used by knowledge ingestion. Keeping this here lets preview
// and ingestion remain in lockstep as the parent-child defaults evolve.
// Languages are copied to both levels so parent and child splitters use the same boundary rules.
// TokenLimit is copied only to children because parents keep the configured context window.
func DeriveParentChildConfigs(base SplitterConfig, parentSize, childSize int) (parent, child SplitterConfig) {
if parentSize <= 0 {
parentSize = 4096
}
if childSize <= 0 {
childSize = 384
}
parent = SplitterConfig{
ChunkSize: parentSize,
ChunkOverlap: base.ChunkOverlap,
Separators: base.Separators,
Strategy: base.Strategy,
Languages: base.Languages,
}
child = SplitterConfig{
ChunkSize: childSize,
ChunkOverlap: childSize / 5,
Separators: base.Separators,
Strategy: base.Strategy,
TokenLimit: base.TokenLimit,
Languages: base.Languages,
}
return
}
// mergeBreadcrumbs combines the parent and child heading breadcrumbs into a
// single ContextHeader. When the child re-runs heading detection on parent
// content, its first breadcrumb line typically duplicates the parent's last
// line (the parent's leading heading sits at the top of the child's input);
// drop that duplicate so the embedding context isn't redundant.
func mergeBreadcrumbs(parent, child string) string {
if parent == "" {
return child
}
if child == "" {
return parent
}
parentLines := strings.Split(parent, "\n")
childLines := strings.Split(child, "\n")
if len(parentLines) > 0 && len(childLines) > 0 &&
strings.TrimSpace(parentLines[len(parentLines)-1]) == strings.TrimSpace(childLines[0]) {
childLines = childLines[1:]
}
if len(childLines) == 0 {
return parent
}
return parent + "\n" + strings.Join(childLines, "\n")
}
// resolveChainWithProfile returns the strategy chain to attempt and, when
// the chain was selected by the profiler (auto strategy), the DocProfile
// that drove the selection. Profile is nil for explicit non-auto strategies
// so callers don't pay for an unused profiling pass.
func resolveChainWithProfile(text string, cfg SplitterConfig) ([]StrategyTier, *DocProfile) {
switch cfg.Strategy {
case StrategyHeading:
return []StrategyTier{TierHeading, TierLegacy}, nil
case StrategyHeuristic:
return []StrategyTier{TierHeuristic, TierLegacy}, nil
case StrategyRecursive:
// "recursive" is a public-API alias for "legacy": both invoke
// SplitText. Kept for backwards compatibility with stored configs.
return []StrategyTier{TierLegacy}, nil
case StrategyLegacy, "":
// Empty == legacy preserves backwards compatibility with stored
// ChunkingConfig rows that pre-date the Strategy field.
return []StrategyTier{TierLegacy}, nil
case StrategyAuto:
fallthrough
default:
profile := ProfileDocument(text)
return SelectStrategy(profile), profile
}
}
// runTier dispatches the splitter implementation for the given tier.
// splitByHeadings / splitByHeuristics are package-level vars overridden
// from heading_splitter.go / heuristic_splitter.go via init(); legacy
// runs SplitText. The default branch is defensive for future
// StrategyTier additions.
//
// profile may be nil when the caller did not run the document profiler
// (explicit non-auto strategies skip profiling); splitters that need a
// profile compute one on demand.
func runTier(tier StrategyTier, text string, cfg SplitterConfig, profile *DocProfile) []Chunk {
switch tier {
case TierHeading:
return splitByHeadings(text, cfg, profile)
case TierHeuristic:
return splitByHeuristics(text, cfg, profile)
case TierLegacy:
return SplitText(text, cfg)
}
return SplitText(text, cfg)
}
// ensureDefaults fills in zero-value config fields with sane defaults.
// NormalizeSplitterConfig also uses these defaults so service callers and
// direct callers of this package get the same numbers.
//
// When cfg.TokenLimit is set, ChunkSize is clamped to the character budget
// that fits within that token limit (with a 10% safety factor). This makes
// chunks safe for embedding APIs that have hard token caps.
func ensureDefaults(cfg SplitterConfig) SplitterConfig {
if cfg.ChunkSize <= 0 {
cfg.ChunkSize = DefaultChunkSize
}
if cfg.ChunkOverlap <= 0 {
cfg.ChunkOverlap = DefaultChunkOverlap
}
if len(cfg.Separators) == 0 {
cfg.Separators = []string{"\n\n", "\n", "。"}
}
if cfg.TokenLimit > 0 {
lang := LangMixed
if len(cfg.Languages) > 0 {
lang = cfg.Languages[0]
}
charBudget := CharsForTokenLimit(cfg.TokenLimit, lang)
if charBudget > 0 && (cfg.ChunkSize == 0 || charBudget < cfg.ChunkSize) {
cfg.ChunkSize = charBudget
}
}
// Guard against pathological overlap configurations: if Overlap exceeds
// half of ChunkSize, almost every chunk is duplicate content. Cap it at
// ChunkSize/2 so Overlap stays a useful smoothing band rather than a
// near-clone of the previous chunk.
if cfg.ChunkOverlap > cfg.ChunkSize/2 && cfg.ChunkSize > 0 {
cfg.ChunkOverlap = cfg.ChunkSize / 2
}
return cfg
}
// splitByHeadings is overridden by heading_splitter.go. The default no-op
// fallback ignores the profile (profile may be nil; the override computes
// one on demand when so).
var splitByHeadings = func(text string, cfg SplitterConfig, _ *DocProfile) []Chunk {
return SplitText(text, cfg)
}
// splitByHeuristics is overridden by heuristic_splitter.go. profile may be nil.
var splitByHeuristics = func(text string, cfg SplitterConfig, _ *DocProfile) []Chunk {
return SplitText(text, cfg)
}
@@ -0,0 +1,120 @@
package chunker
import (
"strings"
"testing"
)
func TestSplitWithDiagnostics_LegacyStrategy_ReportsLegacyTier(t *testing.T) {
// Splittable input so the validator accepts the legacy output cleanly.
text := strings.Repeat("Hello world.\n\nNext paragraph here.\n\n", 50)
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{"\n\n", "\n"}, Strategy: StrategyLegacy}
chunks, diag := SplitWithDiagnostics(text, cfg)
if len(chunks) == 0 {
t.Fatal("expected chunks")
}
if diag.SelectedTier != TierLegacy {
t.Errorf("expected SelectedTier=legacy, got %s", diag.SelectedTier)
}
if len(diag.TierChain) != 1 || diag.TierChain[0] != TierLegacy {
t.Errorf("expected single-tier chain [legacy], got %v", diag.TierChain)
}
if len(diag.Rejected) != 0 {
t.Errorf("expected no rejections for splittable input, got %v", diag.Rejected)
}
}
func TestSplitWithDiagnostics_AutoOnHeadingDoc_PicksHeading(t *testing.T) {
doc := strings.Repeat("# Top\nintro paragraph here.\n\n## Section A\nbody A here.\n\n## Section B\nbody B here.\n\n## Section C\nbody C here.\n\n", 1)
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 30, Strategy: StrategyAuto}
_, diag := SplitWithDiagnostics(doc, cfg)
if len(diag.TierChain) == 0 {
t.Fatal("expected non-empty tier chain")
}
// Heading tier should be tried first for this doc.
if diag.TierChain[0] != TierHeading {
t.Errorf("expected heading tier first, got chain %v", diag.TierChain)
}
}
func TestSplitWithDiagnostics_EmptyText(t *testing.T) {
chunks, diag := SplitWithDiagnostics("", DefaultConfig())
if chunks != nil {
t.Errorf("expected nil chunks for empty text, got %v", chunks)
}
if diag == nil {
t.Fatal("diag must never be nil")
}
}
// TestSplit_AndDiagnostics_AgreeOnChunks ensures Split (no diagnostics)
// and SplitWithDiagnostics produce the same chunk set for a given input.
// They run independent loops as of the post-audit refactor — this test
// is the regression wall against them drifting.
func TestSplit_AndDiagnostics_AgreeOnChunks(t *testing.T) {
text := "para one.\n\npara two.\n\npara three."
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 10}
a := Split(text, cfg)
b, diag := SplitWithDiagnostics(text, cfg)
if len(a) != len(b) {
t.Fatalf("chunk count disagrees: Split=%d Diagnostics=%d", len(a), len(b))
}
for i := range a {
if a[i].Content != b[i].Content || a[i].Start != b[i].Start || a[i].End != b[i].End {
t.Errorf("chunk %d differs:\n Split: %+v\n Diag : %+v", i, a[i], b[i])
}
}
if diag == nil {
t.Error("diagnostics must not be nil")
}
}
// TestSplitWithDiagnostics_ProfileSetForAuto verifies that auto-strategy
// returns the DocProfile that drove tier selection — required by the
// preview endpoint to avoid double-profiling.
func TestSplitWithDiagnostics_ProfileSetForAuto(t *testing.T) {
doc := "# Top\nintro.\n\n## A\nbody A.\n\n## B\nbody B."
_, diag := SplitWithDiagnostics(doc, SplitterConfig{ChunkSize: 200, Strategy: StrategyAuto})
if diag.Profile == nil {
t.Fatal("auto strategy must populate diag.Profile")
}
if diag.Profile.MdHeadingTotal == 0 {
t.Errorf("profile should have detected headings, got %+v", diag.Profile)
}
}
// TestSplitWithDiagnostics_ProfileNilForExplicit verifies the inverse:
// explicit strategies bypass profiling and leave Profile nil so the
// preview handler knows to materialize one if it needs stats.
func TestSplitWithDiagnostics_ProfileNilForExplicit(t *testing.T) {
for _, strat := range []string{StrategyHeading, StrategyHeuristic, StrategyRecursive, StrategyLegacy} {
t.Run(strat, func(t *testing.T) {
_, diag := SplitWithDiagnostics("plain text", SplitterConfig{ChunkSize: 200, Strategy: strat})
if diag.Profile != nil {
t.Errorf("strategy %q should leave Profile nil, got %+v", strat, diag.Profile)
}
})
}
}
func TestSplitParentChildWithDiagnostics_MatchesSplitParentChild(t *testing.T) {
text := strings.Repeat("## Record\n"+strings.Repeat("A sufficiently long entry body. ", 10)+"\n\n", 12)
parentCfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 30, Separators: []string{"\n\n", "\n"}, Strategy: StrategyHeading}
childCfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 20, Separators: []string{"\n\n", "\n"}, Strategy: StrategyHeading}
want := SplitParentChild(text, parentCfg, childCfg)
got, diag := SplitParentChildWithDiagnostics(text, parentCfg, childCfg)
if len(got.Parents) != len(want.Parents) || len(got.Children) != len(want.Children) {
t.Fatalf("parent-child result differs: got %d parents/%d children, want %d parents/%d children",
len(got.Parents), len(got.Children), len(want.Parents), len(want.Children))
}
for i := range want.Children {
if got.Children[i] != want.Children[i] {
t.Errorf("child %d differs:\n got: %+v\n want: %+v", i, got.Children[i], want.Children[i])
}
}
if diag == nil || diag.SelectedTier == "" {
t.Fatal("expected diagnostics for parent split")
}
}
@@ -0,0 +1,354 @@
package chunker
import (
"strings"
"testing"
)
func TestSplit_EmptyText(t *testing.T) {
if got := Split("", DefaultConfig()); got != nil {
t.Errorf("empty text should return nil, got %v", got)
}
}
func TestSplit_LegacyStrategy_MatchesSplitText(t *testing.T) {
text := strings.Repeat("Hello world.\n\n", 30)
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 20, Separators: []string{"\n\n"}, Strategy: StrategyLegacy}
a := Split(text, cfg)
b := SplitText(text, cfg)
if len(a) != len(b) {
t.Errorf("legacy strategy should match SplitText: got %d vs %d chunks", len(a), len(b))
}
for i := range a {
if a[i].Content != b[i].Content {
t.Errorf("chunk %d differs", i)
}
}
}
func TestSplit_EmptyStrategyEqualsLegacy(t *testing.T) {
text := strings.Repeat("Sentence one. Sentence two.\n", 20)
cfg := SplitterConfig{ChunkSize: 80, ChunkOverlap: 10}
a := Split(text, cfg)
cfg.Strategy = StrategyLegacy
b := Split(text, cfg)
if len(a) != len(b) {
t.Errorf("empty Strategy should equal legacy: %d vs %d", len(a), len(b))
}
}
func TestSplit_AutoStrategy_PicksHeadingForMarkdownDoc(t *testing.T) {
doc := strings.Repeat("# A\nbody\n## B\nbody\n## C\nbody\n## D\nbody\n", 1)
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Strategy: StrategyAuto}
// Until heading_splitter is wired, this falls through to SplitText —
// just assert we get a valid result.
chunks := Split(doc, cfg)
if len(chunks) == 0 {
t.Error("auto strategy should produce chunks")
}
}
func TestSplit_HeadingStrategyKeepsDistinctTopLevelHeadings(t *testing.T) {
doc := `# Intro
short intro.
# Usage
short usage.
# FAQ
short faq.`
cfg := SplitterConfig{ChunkSize: 500, ChunkOverlap: 0, Strategy: StrategyHeading}
chunks := Split(doc, cfg)
if len(chunks) != 3 {
t.Fatalf("expected one chunk per top-level heading, got %d:\n%v", len(chunks), chunks)
}
for i, heading := range []string{"# Intro", "# Usage", "# FAQ"} {
if !strings.Contains(chunks[i].Content, heading) {
t.Errorf("chunk %d should contain heading %q, got:\n%s", i, heading, chunks[i].Content)
}
}
}
// TestSplit_PreservesPositionInvariantAcrossTiers ensures every chunk's
// (Start, End, Content) triple stays consistent — End-Start must equal the
// rune length of Content, and runes[Start:End] must equal Content. This is
// the contract that knowledge.go:2278+ relies on for document reconstruction
// during summary generation.
func TestSplit_PreservesPositionInvariantAcrossTiers(t *testing.T) {
cases := map[string]string{
"heading-tier": "# Top\nintro paragraph here.\n\n## Section A\nbody A here.\n\n## Section B\nbody B here.\n\n## Section C\nbody C.",
"heuristic-tier": strings.Repeat("Kapitel 1: Einleitung\n", 1) + strings.Repeat("Beispieltext. ", 50) +
"\n\n" + strings.Repeat("Kapitel 2: Hauptteil\n", 1) + strings.Repeat("Mehr Text. ", 50),
"recursive-tier": strings.Repeat("plain prose without structure. ", 100),
}
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 30, Separators: []string{"\n\n", "\n", "。", ". "}, Strategy: StrategyAuto}
for name, doc := range cases {
t.Run(name, func(t *testing.T) {
runes := []rune(doc)
chunks := Split(doc, cfg)
if len(chunks) == 0 {
t.Fatal("expected chunks")
}
for i, c := range chunks {
contentRuneLen := len([]rune(c.Content))
spanLen := c.End - c.Start
if spanLen != contentRuneLen {
t.Errorf("chunk %d: End(%d)-Start(%d)=%d but Content has %d runes:\n%q",
i, c.End, c.Start, spanLen, contentRuneLen, c.Content)
}
if c.Start < 0 || c.End > len(runes) {
t.Errorf("chunk %d: position out of range Start=%d End=%d totalRunes=%d",
i, c.Start, c.End, len(runes))
}
if c.Start >= 0 && c.End <= len(runes) {
sliced := string(runes[c.Start:c.End])
if sliced != c.Content {
t.Errorf("chunk %d: runes[Start:End] differs from Content", i)
}
}
}
})
}
}
// Children should pick up sub-heading context when childCfg uses auto
// strategy on a heading-rich document. Previously child splitting was
// pinned to the recursive tier, so sub-chunks all shared the parent's
// top-level breadcrumb regardless of inner H2/H3 structure.
func TestSplitParentChild_AutoStrategyEnrichesChildBreadcrumbs(t *testing.T) {
body := strings.Repeat("Lorem ipsum dolor sit amet. ", 40)
doc := "# Chapter\n" + body +
"\n\n## Section A\n" + body +
"\n\n## Section B\n" + body +
"\n\n## Section C\n" + body
seps := []string{"\n\n", "\n", ". "}
parentCfg := SplitterConfig{ChunkSize: 800, ChunkOverlap: 80, Strategy: StrategyAuto, Separators: seps}
childCfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Strategy: StrategyAuto, Separators: seps}
res := SplitParentChild(doc, parentCfg, childCfg)
if len(res.Children) == 0 {
t.Fatal("expected children")
}
// At least one child should carry a breadcrumb that includes a
// sub-heading (## Section …) — that's only possible if the child
// splitter re-detected headings inside the parent.
saw := false
for _, c := range res.Children {
if strings.Contains(c.ContextHeader, "## Section") {
saw = true
break
}
}
if !saw {
t.Errorf("no child carries a sub-heading breadcrumb. samples:\n %q\n %q",
firstHeader(res.Children), lastHeader(res.Children))
}
// And no breadcrumb should contain the same line twice in a row
// (mergeBreadcrumbs deduplicates the parent/child seam).
for i, c := range res.Children {
lines := strings.Split(c.ContextHeader, "\n")
for j := 1; j < len(lines); j++ {
if strings.TrimSpace(lines[j]) != "" && lines[j] == lines[j-1] {
t.Errorf("child[%d] has duplicate breadcrumb lines: %q", i, c.ContextHeader)
break
}
}
}
}
func firstHeader(cs []ChildChunk) string {
if len(cs) == 0 {
return ""
}
return cs[0].ContextHeader
}
func lastHeader(cs []ChildChunk) string {
if len(cs) == 0 {
return ""
}
return cs[len(cs)-1].ContextHeader
}
func TestMergeBreadcrumbs(t *testing.T) {
cases := []struct {
name string
parent, child string
want string
}{
{"empty parent", "", "## Sub", "## Sub"},
{"empty child", "# Top", "", "# Top"},
{"both empty", "", "", ""},
{"disjoint", "# Top", "## Other", "# Top\n## Other"},
{"duplicate seam", "# Top\n## A", "## A\n### A1", "# Top\n## A\n### A1"},
{"deep duplicate", "# Top", "# Top", "# Top"},
{"only whitespace differs", "# Top\n## A", " ## A \n### A1", "# Top\n## A\n### A1"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := mergeBreadcrumbs(tc.parent, tc.child)
if got != tc.want {
t.Errorf("mergeBreadcrumbs(%q, %q) = %q, want %q", tc.parent, tc.child, got, tc.want)
}
})
}
}
func TestSplitParentChild_LegacyStrategy(t *testing.T) {
text := strings.Repeat("This is a sentence. Another one.\n\n", 50)
parentCfg := SplitterConfig{ChunkSize: 400, ChunkOverlap: 40, Strategy: StrategyLegacy}
childCfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 20, Strategy: StrategyLegacy}
res := SplitParentChild(text, parentCfg, childCfg)
if len(res.Children) == 0 {
t.Fatal("expected children chunks")
}
for i, c := range res.Children {
if c.ParentIndex >= 0 && c.ParentIndex >= len(res.Parents) {
t.Errorf("child[%d] has invalid ParentIndex %d (parents=%d)", i, c.ParentIndex, len(res.Parents))
}
}
}
func TestEnsureDefaults(t *testing.T) {
cfg := ensureDefaults(SplitterConfig{})
if cfg.ChunkSize != DefaultChunkSize {
t.Errorf("expected default ChunkSize %d, got %d", DefaultChunkSize, cfg.ChunkSize)
}
if cfg.ChunkOverlap != DefaultChunkOverlap {
t.Errorf("expected default ChunkOverlap %d, got %d", DefaultChunkOverlap, cfg.ChunkOverlap)
}
if len(cfg.Separators) == 0 {
t.Error("expected default separators")
}
}
func TestNormalizeSplitterConfig_MatchesIngestionDefaults(t *testing.T) {
cfg := NormalizeSplitterConfig(SplitterConfig{})
if cfg.ChunkSize != DefaultChunkSize {
t.Errorf("chunk size: got %d want %d", cfg.ChunkSize, DefaultChunkSize)
}
if cfg.ChunkOverlap != DefaultChunkOverlap {
t.Errorf("chunk overlap: got %d want %d", cfg.ChunkOverlap, DefaultChunkOverlap)
}
if len(cfg.Separators) != 3 {
t.Fatalf("separators: got %v", cfg.Separators)
}
}
func TestNormalizeLineEndings(t *testing.T) {
input := "first\r\nsecond\rthird\nfourth"
if got, want := NormalizeLineEndings(input), "first\nsecond\nthird\nfourth"; got != want {
t.Errorf("NormalizeLineEndings() = %q, want %q", got, want)
}
}
func TestDeriveParentChildConfigs_DefaultSizes(t *testing.T) {
base := SplitterConfig{
ChunkSize: 1000,
ChunkOverlap: 100,
Separators: []string{"\n\n", "\n"},
Strategy: StrategyHeading,
}
parent, child := DeriveParentChildConfigs(base, 0, 0)
if parent.ChunkSize != 4096 || child.ChunkSize != 384 {
t.Fatalf("default sizes: parent=%d child=%d", parent.ChunkSize, child.ChunkSize)
}
if parent.Strategy != StrategyHeading || child.Strategy != StrategyHeading {
t.Fatalf("strategy not propagated: parent=%q child=%q", parent.Strategy, child.Strategy)
}
if child.ChunkOverlap != 384/5 {
t.Fatalf("child overlap: got %d want %d", child.ChunkOverlap, 384/5)
}
}
func TestDeriveParentChildConfigs_AppliesEmbeddingTokenLimitOnlyToChildren(t *testing.T) {
const (
parentSize = 4096
childSize = 1024
tokenLimit = 200
)
base := SplitterConfig{
ChunkSize: DefaultChunkSize,
ChunkOverlap: DefaultChunkOverlap,
Separators: []string{"。"},
Strategy: StrategyLegacy,
TokenLimit: tokenLimit,
Languages: []string{LangChinese},
}
parent, child := DeriveParentChildConfigs(base, parentSize, childSize)
if parent.TokenLimit != 0 {
t.Fatalf("parent token limit: got %d want 0", parent.TokenLimit)
}
if len(parent.Languages) != 1 || parent.Languages[0] != LangChinese {
t.Fatalf("parent languages: got %v want [%s]", parent.Languages, LangChinese)
}
if child.TokenLimit != tokenLimit {
t.Fatalf("child token limit: got %d want %d", child.TokenLimit, tokenLimit)
}
if len(child.Languages) != 1 || child.Languages[0] != LangChinese {
t.Fatalf("child languages: got %v want [%s]", child.Languages, LangChinese)
}
text := strings.Repeat("这是用于验证中文分块预算的句子。", 100)
result := SplitParentChild(text, parent, child)
if len(result.Parents) != 1 {
t.Fatalf("parents: got %d want 1", len(result.Parents))
}
if got := len([]rune(result.Parents[0].Content)); got != len([]rune(text)) {
t.Fatalf("parent length: got %d want %d", got, len([]rune(text)))
}
budget := CharsForTokenLimit(tokenLimit, LangChinese)
for i, c := range result.Children {
if got := len([]rune(c.Content)); got > budget {
t.Fatalf("child[%d] length: got %d want <= %d", i, got, budget)
}
}
}
func TestValidateChunks_Empty(t *testing.T) {
if v := ValidateChunks(nil, 1000, 500); v.OK {
t.Error("nil chunks should be invalid")
}
}
func TestValidateChunks_SingleChunkLargeDoc(t *testing.T) {
c := []Chunk{{Content: strings.Repeat("a", 5000)}}
if v := ValidateChunks(c, 5000, 500); v.OK {
t.Error("single 10x-too-large chunk should be invalid")
}
}
func TestValidateChunks_AcceptsReasonableOutput(t *testing.T) {
chunks := []Chunk{
{Content: strings.Repeat("a", 480)},
{Content: strings.Repeat("b", 510)},
{Content: strings.Repeat("c", 460)},
}
if v := ValidateChunks(chunks, 1500, 512); !v.OK {
t.Errorf("reasonable chunks should validate, got: %s", v.Reason)
}
}
func TestValidateChunks_RejectsOversized(t *testing.T) {
chunks := []Chunk{
{Content: strings.Repeat("a", 100)},
{Content: strings.Repeat("b", 5000)}, // > 2x chunkSize
}
if v := ValidateChunks(chunks, 5100, 1000); v.OK {
t.Error("chunk >2x size should be invalid")
}
}
func TestValidateChunks_TolerantTinyTail(t *testing.T) {
chunks := []Chunk{
{Content: strings.Repeat("a", 480)},
{Content: strings.Repeat("b", 510)},
{Content: "tail"},
}
if v := ValidateChunks(chunks, 994, 512); !v.OK {
t.Errorf("tiny last chunk should be tolerated, got: %s", v.Reason)
}
}
@@ -0,0 +1,35 @@
package chunker
import "testing"
func TestEnsureDefaults_TokenLimitClampsChunkSize(t *testing.T) {
cfg := SplitterConfig{
ChunkSize: 10000, // huge
TokenLimit: 100,
Languages: []string{LangEnglish},
}
out := ensureDefaults(cfg)
// 100 tokens * 4 chars/token * 0.9 ≈ 360 chars
if out.ChunkSize >= 1000 {
t.Errorf("expected ChunkSize clamped by TokenLimit, got %d", out.ChunkSize)
}
if out.ChunkOverlap >= out.ChunkSize {
t.Errorf("overlap should be smaller than clamped chunk size: overlap=%d size=%d", out.ChunkOverlap, out.ChunkSize)
}
}
func TestEnsureDefaults_TokenLimitChineseTighter(t *testing.T) {
cfgEN := ensureDefaults(SplitterConfig{TokenLimit: 200, Languages: []string{LangEnglish}})
cfgZH := ensureDefaults(SplitterConfig{TokenLimit: 200, Languages: []string{LangChinese}})
if cfgZH.ChunkSize >= cfgEN.ChunkSize {
t.Errorf("Chinese char budget should be tighter than English: zh=%d en=%d", cfgZH.ChunkSize, cfgEN.ChunkSize)
}
}
func TestEnsureDefaults_NoTokenLimitKeepsChunkSize(t *testing.T) {
cfg := SplitterConfig{ChunkSize: 800}
out := ensureDefaults(cfg)
if out.ChunkSize != 800 {
t.Errorf("ChunkSize should stay 800, got %d", out.ChunkSize)
}
}
+159
View File
@@ -0,0 +1,159 @@
// Package chunker - tokens.go provides language-aware token count approximation.
//
// We avoid pulling in a tokenizer dependency (e.g. tiktoken) and instead use
// per-language chars-per-token ratios derived from common embedding model
// vocabularies. The numbers are conservative — they tend to slightly
// over-estimate token counts so that chunks stay safely under model limits.
package chunker
import (
"unicode"
"unicode/utf8"
)
// Language identifiers used by the token estimator and the heuristic splitter.
const (
LangEnglish = "en"
LangGerman = "de"
LangChinese = "zh"
LangMixed = "mixed"
)
// charsPerToken holds approximate chars/token ratios per language.
// Numbers err on the conservative side so estimates over-shoot a little.
var charsPerToken = map[string]float64{
LangEnglish: 4.0,
LangGerman: 4.5,
LangChinese: 1.7,
LangMixed: 3.0,
}
// ApproxTokenCount returns a conservative token estimate for s in the given
// language. An empty or unknown lang falls back to "mixed".
func ApproxTokenCount(s string, lang string) int {
if s == "" {
return 0
}
return ApproxTokenCountFromRuneLen(utf8.RuneCountInString(s), lang)
}
// ApproxTokenCountFromRuneLen is the allocation-free variant of
// ApproxTokenCount when the caller has already computed the rune length.
// Use this in hot loops where the same content's rune count would
// otherwise be recomputed multiple times (e.g. preview endpoint emitting
// per-chunk stats).
func ApproxTokenCountFromRuneLen(runeLen int, lang string) int {
if runeLen <= 0 {
return 0
}
ratio, ok := charsPerToken[lang]
if !ok {
ratio = charsPerToken[LangMixed]
}
approx := float64(runeLen) / ratio
if approx < 1 {
return 1
}
return int(approx + 0.5)
}
// DetectLanguage returns a coarse language label by counting CJK runes vs.
// Latin runes. The result is one of LangChinese, LangGerman, LangEnglish or
// LangMixed. Detection is cheap and meant only for heuristic dispatch — it
// is NOT a replacement for proper language identification.
func DetectLanguage(s string) string {
if s == "" {
return LangMixed
}
var cjk, latin, umlaut int
for _, r := range s {
switch {
case unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hangul, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r):
cjk++
case isGermanUmlaut(r):
umlaut++
latin++
case (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z'):
latin++
}
}
total := cjk + latin
if total == 0 {
return LangMixed
}
cjkRatio := float64(cjk) / float64(total)
latinRatio := float64(latin) / float64(total)
// Mixed: meaningful presence of both scripts (>=15% each).
if cjkRatio >= 0.15 && latinRatio >= 0.15 {
return LangMixed
}
if cjkRatio > 0.3 {
return LangChinese
}
if umlaut > 0 || hasGermanWords(s) {
return LangGerman
}
return LangEnglish
}
func isGermanUmlaut(r rune) bool {
switch r {
case 'ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß':
return true
}
return false
}
// hasGermanWords does a tiny stop-word check to bias towards "de" when the
// text uses common German function words. Cheap heuristic — false positives
// on borrowed terms are acceptable.
func hasGermanWords(s string) bool {
const sample = 512
if len(s) > sample {
s = s[:sample]
}
for _, w := range []string{" der ", " die ", " das ", " und ", " ist ", " nicht ", " mit ", " auf "} {
if containsLower(s, w) {
return true
}
}
return false
}
func containsLower(haystack, needle string) bool {
if len(haystack) < len(needle) {
return false
}
for i := 0; i+len(needle) <= len(haystack); i++ {
match := true
for j := 0; j < len(needle); j++ {
h := haystack[i+j]
if h >= 'A' && h <= 'Z' {
h += 'a' - 'A'
}
if h != needle[j] {
match = false
break
}
}
if match {
return true
}
}
return false
}
// CharsForTokenLimit converts a token limit into an approximate character
// budget for a given language. Used to size chunks so they fit within an
// embedding model's max-token window with a small safety margin.
func CharsForTokenLimit(tokens int, lang string) int {
if tokens <= 0 {
return 0
}
ratio, ok := charsPerToken[lang]
if !ok {
ratio = charsPerToken[LangMixed]
}
// 0.9 safety factor so we under-shoot the model limit instead of overshooting.
return int(float64(tokens) * ratio * 0.9)
}
@@ -0,0 +1,78 @@
package chunker
import "testing"
func TestApproxTokenCount_English(t *testing.T) {
got := ApproxTokenCount("The quick brown fox jumps over the lazy dog.", LangEnglish)
// 44 chars / 4 ≈ 11 tokens
if got < 9 || got > 13 {
t.Errorf("English token estimate out of range: got %d, want 9..13", got)
}
}
func TestApproxTokenCount_Chinese(t *testing.T) {
got := ApproxTokenCount("这是一段中文测试内容用于检验分词估算", LangChinese)
// 18 runes / 1.7 ≈ 10
if got < 9 || got > 12 {
t.Errorf("Chinese token estimate out of range: got %d, want 9..12", got)
}
}
func TestApproxTokenCount_Empty(t *testing.T) {
if got := ApproxTokenCount("", LangEnglish); got != 0 {
t.Errorf("empty string should return 0 tokens, got %d", got)
}
}
func TestApproxTokenCount_UnknownLang(t *testing.T) {
got := ApproxTokenCount("Hello world hello world", "xx")
if got <= 0 {
t.Errorf("unknown lang should fall back to mixed, got %d", got)
}
}
func TestDetectLanguage_English(t *testing.T) {
if got := DetectLanguage("The quick brown fox jumps over the lazy dog."); got != LangEnglish {
t.Errorf("expected English, got %s", got)
}
}
func TestDetectLanguage_German(t *testing.T) {
if got := DetectLanguage("Der schnelle braune Fuchs springt über den faulen Hund."); got != LangGerman {
t.Errorf("expected German, got %s", got)
}
}
func TestDetectLanguage_GermanByStopwords(t *testing.T) {
// No umlauts but plenty of German function words.
if got := DetectLanguage("Das ist ein Test und nicht mit Umlauten."); got != LangGerman {
t.Errorf("expected German via stopwords, got %s", got)
}
}
func TestDetectLanguage_Chinese(t *testing.T) {
if got := DetectLanguage("这是一段中文测试内容"); got != LangChinese {
t.Errorf("expected Chinese, got %s", got)
}
}
func TestDetectLanguage_Mixed(t *testing.T) {
got := DetectLanguage("This 这是 mixed 测试 content with 多语言 inside")
if got != LangMixed {
t.Errorf("expected Mixed, got %s", got)
}
}
func TestCharsForTokenLimit_AppliesSafetyMargin(t *testing.T) {
got := CharsForTokenLimit(1000, LangEnglish)
// 1000 * 4 * 0.9 = 3600
if got < 3500 || got > 3700 {
t.Errorf("char budget for 1000 EN tokens out of range: got %d", got)
}
}
func TestCharsForTokenLimit_ZeroTokens(t *testing.T) {
if got := CharsForTokenLimit(0, LangEnglish); got != 0 {
t.Errorf("zero tokens should give zero chars, got %d", got)
}
}
@@ -0,0 +1,75 @@
// Package chunker - validator.go inspects a tier's output and decides whether
// it is good enough to ship or whether the strategy chain should fall through
// to the next tier. The validator is intentionally permissive: a single
// "obviously broken" output is rejected, but plausible-looking variation is
// accepted so we don't oscillate between tiers.
package chunker
import "math"
// ValidationResult captures the verdict and reason for a chunk-set.
type ValidationResult struct {
OK bool
Reason string
}
// ValidateChunks checks whether the given chunks form a usable result for a
// document of totalChars characters with a target chunkSize. Returns OK=true
// when no broken-output indicator triggers.
func ValidateChunks(chunks []Chunk, totalChars, chunkSize int) ValidationResult {
if len(chunks) == 0 {
return ValidationResult{Reason: "no chunks produced"}
}
// A single chunk for a document much larger than chunkSize means the
// strategy did not actually split — fail so the next tier runs.
if len(chunks) == 1 && totalChars > 2*chunkSize {
return ValidationResult{Reason: "single chunk for large document"}
}
// Compute size statistics.
var sum, sumSq float64
maxLen, minLen := 0, math.MaxInt32
for _, c := range chunks {
l := len([]rune(c.Content))
sum += float64(l)
sumSq += float64(l * l)
if l > maxLen {
maxLen = l
}
if l < minLen {
minLen = l
}
}
avg := sum / float64(len(chunks))
// All but the last chunk should carry meaningful content. We allow the
// last chunk to be tiny because tail residue is normal.
tinyCount := 0
for i, c := range chunks {
if i == len(chunks)-1 {
continue
}
if len([]rune(c.Content)) < 50 {
tinyCount++
}
}
if tinyCount > len(chunks)/4 && tinyCount > 2 {
return ValidationResult{Reason: "too many tiny chunks"}
}
// Reject when no chunk reached at least 25% of the target — the splitter
// is fragmenting too aggressively to be useful.
if maxLen < chunkSize/4 && totalChars > chunkSize {
return ValidationResult{Reason: "all chunks far below target size"}
}
// Sanity check on absolute upper bound. Anything past 2x chunkSize is a
// red flag — the splitter ignored its size budget.
if maxLen > 2*chunkSize && chunkSize > 0 {
return ValidationResult{Reason: "chunk exceeds 2x target size"}
}
_ = avg
return ValidationResult{OK: true}
}
@@ -0,0 +1,255 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/utils"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/google/uuid"
)
const (
academyCloudReaderBaseURL = "https://weknora.weixin.qq.com/api/v1/doc"
// defaultAcademyCloudPollTimeout bounds how long one async task is polled;
// ACADEMY_ACADEMYCLOUD_TIMEOUT overrides it. It must stay below
// ACADEMY_DOCREADER_CALL_TIMEOUT (default 30m) or the hardcoded value, not
// the configured one, is what fails a slow parse.
defaultAcademyCloudPollTimeout = 20 * time.Minute
)
// AcademyCloudSignedDocumentReader implements the docreader HTTP protocol with AcademyCloud signing.
type AcademyCloudSignedDocumentReader struct {
appID string
apiKey string
client *http.Client
initialPollInterval time.Duration
maxPollInterval time.Duration
pollTimeout time.Duration
}
func NewAcademyCloudSignedDocumentReader(appID, apiKey string) (*AcademyCloudSignedDocumentReader, error) {
if appID == "" {
return nil, fmt.Errorf("AcademyCloud appID is required")
}
if apiKey == "" {
return nil, fmt.Errorf("AcademyCloud apiKey is required")
}
clientCfg := secutils.DefaultSSRFSafeHTTPClientConfig()
clientCfg.Timeout = 500 * time.Minute
return &AcademyCloudSignedDocumentReader{
appID: appID,
apiKey: apiKey,
initialPollInterval: 500 * time.Millisecond,
maxPollInterval: 10 * time.Second,
pollTimeout: requestTimeoutFromEnv("ACADEMY_ACADEMYCLOUD_TIMEOUT", defaultAcademyCloudPollTimeout),
client: secutils.NewSSRFSafeHTTPClient(clientCfg),
}, nil
}
func (p *AcademyCloudSignedDocumentReader) Reconnect(addr string) error {
return nil
}
func (p *AcademyCloudSignedDocumentReader) IsConnected() bool { return true }
func (p *AcademyCloudSignedDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
return []types.ParserEngineInfo{{
Name: AcademyCloudEngineName,
Description: "AcademyCloud signed docreader",
FileTypes: []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "pptx", "ppt"},
Available: true,
}}, nil
}
func (p *AcademyCloudSignedDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
logger.Infof(ctx, "[AcademyCloud] read start file=%q type=%q engine=%q hasURL=%v contentLen=%d requestID=%q",
req.FileName, req.FileType, req.ParserEngine, strings.TrimSpace(req.URL) != "", len(req.FileContent), req.RequestID)
body := httpReadRequest{
FileName: req.FileName,
FileType: req.FileType,
URL: req.URL,
Title: req.Title,
RequestID: req.RequestID,
Config: &httpReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
if len(req.FileContent) > 0 {
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
}
jsonBody, err := json.Marshal(body)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] marshal read request: %v", err)
return nil, fmt.Errorf("http marshal read request: %w", err)
}
httpReq, err := p.newSignedRequest(ctx, http.MethodPost, academyCloudReaderBaseURL+"/reader", jsonBody)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] signed read request: %v", err)
return nil, err
}
resp, err := p.client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http read request failed: %v", err)
return nil, fmt.Errorf("http read failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
logger.Errorf(context.Background(), "[AcademyCloud] http read unexpected status %d: %s", resp.StatusCode, string(bodyBytes))
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
}
var submit academyCloudAsyncSubmitResponse
if err := json.NewDecoder(resp.Body).Decode(&submit); err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] decode read submit response: %v", err)
return nil, fmt.Errorf("http decode read submit response: %w", err)
}
if strings.TrimSpace(submit.TaskID) == "" {
logger.Errorf(context.Background(), "[AcademyCloud] submit response missing task_id (status=%q message=%q)", submit.Status, submit.Message)
return nil, fmt.Errorf("academycloud docreader submit response missing task_id")
}
logger.Infof(ctx, "[AcademyCloud] task submitted task_id=%s file=%q type=%q", submit.TaskID, req.FileName, req.FileType)
return p.pollTaskResult(ctx, submit.TaskID)
}
type academyCloudAsyncSubmitResponse struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Message string `json:"message"`
CreatedAt int64 `json:"created_at"`
}
type academyCloudAsyncTaskResponse struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Message string `json:"message"`
Progress float64 `json:"progress"`
Result *httpReadResponse `json:"result"`
Error string `json:"error"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func (p *AcademyCloudSignedDocumentReader) pollTaskResult(ctx context.Context, taskID string) (*types.ReadResult, error) {
pollCtx := ctx
if p.pollTimeout > 0 {
var cancel context.CancelFunc
pollCtx, cancel = context.WithTimeout(ctx, p.pollTimeout)
defer cancel()
}
statusURL := academyCloudReaderBaseURL + "/" + taskID
currentInterval := p.initialPollInterval
for {
httpReq, err := p.newSignedRequest(pollCtx, http.MethodGet, statusURL, nil)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] poll signed request task_id=%s: %v", taskID, err)
return nil, err
}
resp, err := p.client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http poll task_id=%s failed: %v", taskID, err)
return nil, fmt.Errorf("http poll task failed: %w", err)
}
var taskResp academyCloudAsyncTaskResponse
func() {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("http poll task status %d: %s", resp.StatusCode, string(bodyBytes))
logger.Errorf(context.Background(), "[AcademyCloud] poll task_id=%s status %d: %s", taskID, resp.StatusCode, string(bodyBytes))
return
}
if decodeErr := json.NewDecoder(resp.Body).Decode(&taskResp); decodeErr != nil {
err = fmt.Errorf("http decode task response: %w", decodeErr)
logger.Errorf(context.Background(), "[AcademyCloud] poll task_id=%s decode response: %v", taskID, decodeErr)
}
}()
if err != nil {
return nil, err
}
switch taskResp.Status {
case "completed":
if taskResp.Result == nil {
logger.Infof(ctx, "[AcademyCloud] task_id=%s completed with no result payload", taskID)
return &types.ReadResult{}, nil
}
res := fromHTTPReadResponse(taskResp.Result)
if res.Error != "" {
logger.Errorf(ctx, "[AcademyCloud] task_id=%s completed with result.error: %s", taskID, res.Error)
} else {
logger.Debugf(ctx, "[AcademyCloud] task_id=%s completed ok markdownLen=%d", taskID, len(res.MarkdownContent))
}
return res, nil
case "failed":
if taskResp.Error != "" {
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s failed: %s", taskID, taskResp.Error)
return nil, fmt.Errorf("academycloud docreader task failed: %s", taskResp.Error)
}
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s failed: %s", taskID, taskResp.Message)
return nil, fmt.Errorf("academycloud docreader task failed: %s", taskResp.Message)
case "cancelled":
if taskResp.Error != "" {
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s cancelled: %s", taskID, taskResp.Error)
return nil, fmt.Errorf("academycloud docreader task cancelled: %s", taskResp.Error)
}
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s cancelled", taskID)
return nil, fmt.Errorf("academycloud docreader task cancelled")
}
if err := pollCtx.Err(); err != nil {
logger.Errorf(ctx, "[AcademyCloud] poll task_id=%s aborted before sleep: %v", taskID, err)
return nil, err
}
// Exponential backoff: multiply by 1.5 each time, cap at maxPollInterval
select {
case <-pollCtx.Done():
logger.Errorf(ctx, "[AcademyCloud] poll task_id=%s stopped: %v", taskID, pollCtx.Err())
return nil, pollCtx.Err()
case <-time.After(currentInterval):
// Update interval for next iteration
nextInterval := time.Duration(float64(currentInterval) * 1.5)
if nextInterval > p.maxPollInterval {
nextInterval = p.maxPollInterval
}
currentInterval = nextInterval
}
}
}
func (p *AcademyCloudSignedDocumentReader) newSignedRequest(ctx context.Context, method, url string, body []byte) (*http.Request, error) {
requestID := uuid.New().String()
if len(body) == 0 {
body = []byte("{}")
}
httpReq, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http new request %s %s: %v", method, url, err)
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.ContentLength = int64(len(body))
for k, v := range utils.Sign(p.appID, p.apiKey, requestID, string(body)) {
httpReq.Header.Set(k, v)
}
return httpReq, nil
}
// PreprocessImage is not offered by the cloud-signed reader: page straightening
// runs in the local docreader service, while this reader talks to AcademyCloud.
// It reports that as a verdict — fallback=true, no error — so the caller's only
// fallback (OCR the original bytes) needs no special case and nothing looks like
// a failure in the logs.
func (p *AcademyCloudSignedDocumentReader) PreprocessImage(_ context.Context, _ []byte) ([]byte, bool, error) {
return nil, true, nil
}
@@ -0,0 +1,231 @@
// Package anydoc converts office documents to Markdown inside the Go process,
// without the Python docreader service.
//
// The conversion itself is the anydoc Rust library, linked as a static archive
// through cgo (see third_party/anydoc-go). That archive needs a Rust toolchain
// to produce, so it is opt-in: only builds tagged `anydoc` link it. Every other
// build compiles the stub in backend_stub.go, where Available reports false and
// the engine registry hides the engine with a reason the UI can show.
//
// The exported surface is deliberately narrow — bytes in, Markdown and embedded
// images out — so the backend can be replaced (a WASI runtime, a future
// upstream Go module) without touching the parser code that calls it.
package anydoc
import (
"errors"
"fmt"
"path/filepath"
"slices"
"strings"
)
// ImageDir is the markdown path prefix for extracted images. The image
// resolver matches references by this path and swaps them for storage URLs.
const ImageDir = "images/"
// Result is one converted document.
type Result struct {
// Markdown is GitHub-Flavored Markdown for the whole document.
// When WithAssets is set, embedded images appear in place as
// `![alt](images/image-N.ext)` via anydoc's official serializer.
Markdown string
// Assets are the images embedded in the document, in document order.
// Always empty for PDF, which anydoc renders straight to Markdown
// without a document model.
Assets []Asset
// AssetsError explains why Assets is empty when images were asked for.
// The document-model parse is what both extracts images and places them
// in the markdown; when it fails, Markdown still comes from the text-only
// renderer so the conversion succeeds and the caller decides whether to
// log or ignore the loss.
AssetsError error
}
// Asset is one image embedded in a document.
type Asset struct {
// ID is the document-model asset index, as referenced by in-place image
// sources. It is stable for a single conversion.
ID uint64
// Name is a generated, extension-carrying file name ("image-1.png"):
// embedded assets have no name of their own inside the container.
Name string
// MediaType is the IANA media type the container declared.
MediaType string
// Data is the raw image bytes.
Data []byte
// Alt is the image's alternative text as the document author wrote it,
// empty when the document carries none.
Alt string
// Section is the text of the nearest heading above the image, empty when
// the image sits before the first heading.
Section string
}
// Options tunes a single conversion.
type Options struct {
// Format names the parser explicitly ("docx", "csv", ...). Empty means
// the format is detected from the content, which every format except
// CSV carries a signature for.
Format string
// WithAssets extracts embedded images and renders them in place in the
// markdown using anydoc's official GFM serializer (asset images are
// rewritten to `images/image-N.ext` links first). Ignored for PDF.
WithAssets bool
}
// ErrUnavailable is returned by Convert when the binding is not linked into
// this build. Callers that can fall back to another engine should check for it
// with errors.Is.
var ErrUnavailable = errors.New("anydoc: binding not built into this binary")
// ErrResourceLimit marks a permanent anydoc rejection: the document exceeds a
// parser budget (for example max_xml_nodes) and retrying the same bytes cannot
// succeed. Callers detect it with errors.Is. The wrapped error's text names
// the limit the converter reported.
var ErrResourceLimit = errors.New("document is too large for the parser")
// resourceLimiter is the method set anydoc's *ConvertError uses to report a
// parser budget failure. The cgo binding implements it; the default build does
// not import that package, so classification goes through this interface.
type resourceLimiter interface {
ResourceLimit() bool
LimitDetail() string
}
// permanentResourceLimit is the errors.Is(ErrResourceLimit) wrapper. Error
// keeps the user-facing reason and the converter's limit detail, without the
// transport prefixes that sit further down the chain.
type permanentResourceLimit struct {
detail string
cause error
}
func (e *permanentResourceLimit) Error() string {
if e.detail == "" {
return ErrResourceLimit.Error()
}
return ErrResourceLimit.Error() + ": " + e.detail
}
func (e *permanentResourceLimit) Unwrap() error { return e.cause }
func (e *permanentResourceLimit) Is(target error) bool { return target == ErrResourceLimit }
// markResourceLimit wraps a converter error whose kind is resource_limit.
// Other errors, including untyped text that merely mentions the kind, are
// returned unchanged so a transient failure can still be retried.
func markResourceLimit(err error) error {
if err == nil {
return nil
}
var limiter resourceLimiter
if !errors.As(err, &limiter) || !limiter.ResourceLimit() {
return err
}
return &permanentResourceLimit{detail: strings.TrimSpace(limiter.LimitDetail()), cause: err}
}
// supportedExtensions are the file types anydoc converts, mapped to the format
// name its parser selector uses. The list is static so that engine metadata
// (file types shown in the UI) is identical whether or not the binding is
// linked in.
var supportedExtensions = map[string]string{
"doc": "doc",
"docx": "docx",
"docm": "docx",
"odt": "odt",
"rtf": "rtf",
"ppt": "ppt",
"pptx": "pptx",
"pptm": "pptx",
"odp": "odp",
"xls": "xlsx",
"xlsx": "xlsx",
"xlsm": "xlsx",
"ods": "ods",
"epub": "epub",
"csv": "csv",
"pdf": "pdf",
}
// SupportedFileTypes returns the extensions anydoc can convert, sorted so the
// engine list is stable across restarts.
func SupportedFileTypes() []string {
types := make([]string, 0, len(supportedExtensions))
for ext := range supportedExtensions {
types = append(types, ext)
}
slices.Sort(types)
return types
}
// FormatForFile resolves the anydoc format name for a file type or file name.
// ok is false for anything anydoc does not convert.
func FormatForFile(fileType, fileName string) (format string, ok bool) {
ext := normalizeExt(fileType)
if ext == "" {
ext = normalizeExt(filepath.Ext(fileName))
}
format, ok = supportedExtensions[ext]
return format, ok
}
// Supports reports whether anydoc converts this file type, regardless of
// whether the binding is linked into this build.
func Supports(fileType, fileName string) bool {
_, ok := FormatForFile(fileType, fileName)
return ok
}
// Available reports whether conversions can actually run in this binary.
func Available() bool { return backendAvailable() }
// UnavailableReason explains, for the UI, why Available is false. It returns
// "" when the binding is available.
func UnavailableReason() string { return backendUnavailableReason() }
// Version reports the anydoc release the linked binding was built from, or ""
// when no binding is linked.
func Version() string { return backendVersion() }
// Convert turns document bytes into Markdown. It returns ErrUnavailable when
// the binding is not linked into this build.
func Convert(data []byte, opts Options) (*Result, error) {
if len(data) == 0 {
return nil, fmt.Errorf("anydoc: empty document")
}
if !backendAvailable() {
return nil, fmt.Errorf("%w: %s", ErrUnavailable, backendUnavailableReason())
}
// PDF has no document model, so asset extraction would only produce an
// error the caller has to special-case. Drop the request instead.
if opts.Format == "pdf" {
opts.WithAssets = false
}
result, err := backendConvert(data, opts)
if err != nil {
err = markResourceLimit(err)
}
return result, err
}
// PDFNeedsOCR reports whether a Convert error means the PDF has no usable
// text layer. Scanned exam papers fail this way; the caller should fall back
// to an engine that can rasterize pages for OCR.
func PDFNeedsOCR(err error) bool {
if err == nil {
return false
}
var ocrError interface{ NeedsOCR() bool }
if errors.As(err, &ocrError) && ocrError.NeedsOCR() {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "ocr is required") ||
strings.Contains(msg, "no extractable text")
}
func normalizeExt(s string) string {
return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s), "."))
}
@@ -0,0 +1,84 @@
package anydoc
import (
"errors"
"slices"
"testing"
)
func TestFormatForFileResolvesTypeAndName(t *testing.T) {
cases := []struct {
name string
fileType string
fileName string
wantFormat string
wantOK bool
}{
{name: "file type", fileType: "docx", wantFormat: "docx", wantOK: true},
{name: "dotted file type", fileType: ".DOCX", wantFormat: "docx", wantOK: true},
{name: "macro format maps to base format", fileType: "pptm", wantFormat: "pptx", wantOK: true},
{name: "legacy excel maps to xlsx parser", fileType: "xls", wantFormat: "xlsx", wantOK: true},
{name: "falls back to file name", fileName: "report.odt", wantFormat: "odt", wantOK: true},
{name: "unsupported type", fileType: "png", wantOK: false},
{name: "nothing to go on", wantOK: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
format, ok := FormatForFile(tc.fileType, tc.fileName)
if ok != tc.wantOK {
t.Fatalf("FormatForFile(%q, %q) ok = %v, want %v", tc.fileType, tc.fileName, ok, tc.wantOK)
}
if format != tc.wantFormat {
t.Fatalf("FormatForFile(%q, %q) = %q, want %q", tc.fileType, tc.fileName, format, tc.wantFormat)
}
})
}
}
// The engine list must look the same whether or not the converter is linked
// in, so that the UI can show the file types with a "not built in" reason.
func TestSupportedFileTypesIsStableAndSorted(t *testing.T) {
types := SupportedFileTypes()
if !slices.IsSorted(types) {
t.Fatalf("SupportedFileTypes is not sorted: %v", types)
}
for _, want := range []string{"docx", "pptx", "xlsx", "epub", "pdf", "csv"} {
if !slices.Contains(types, want) {
t.Errorf("SupportedFileTypes does not include %q: %v", want, types)
}
}
}
func TestPDFNeedsOCR(t *testing.T) {
if PDFNeedsOCR(nil) {
t.Fatal("nil error was treated as needing OCR")
}
if !PDFNeedsOCR(errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required")) {
t.Error("scanned-PDF error was not detected")
}
if PDFNeedsOCR(errors.New("not a readable zip archive")) {
t.Error("unrelated error was treated as needing OCR")
}
}
func TestConvertRejectsEmptyInput(t *testing.T) {
if _, err := Convert(nil, Options{Format: "docx"}); err == nil {
t.Fatal("Convert(nil) succeeded, want an error")
}
}
// Without the build tag there is no converter, and callers must be able to
// detect that so they can fall back to another engine.
func TestConvertReportsUnavailableBackend(t *testing.T) {
if Available() {
t.Skip("converter is linked into this build")
}
_, err := Convert([]byte("id,name\n1,a\n"), Options{Format: "csv"})
if !errors.Is(err, ErrUnavailable) {
t.Fatalf("Convert error = %v, want ErrUnavailable", err)
}
if UnavailableReason() == "" {
t.Error("UnavailableReason is empty while the converter is unavailable")
}
}
@@ -0,0 +1,227 @@
//go:build anydoc && cgo
package anydoc
import (
"fmt"
"strings"
upstream "github.com/firecrawl/anydoc/go"
)
// This build links the anydoc Rust archive through the upstream cgo bindings
// (vendored under third_party/anydoc-go until they are published as a module).
// Conversion runs in-process: no subprocess, no HTTP hop, no Python.
// *ConvertError must keep implementing resourceLimiter so Convert can classify
// a parser budget failure without this file's build tag.
var _ resourceLimiter = (*upstream.ConvertError)(nil)
func backendAvailable() bool { return true }
func backendUnavailableReason() string { return "" }
func backendVersion() string { return upstream.Version }
func backendConvert(data []byte, opts Options) (*Result, error) {
format, err := upstreamFormat(opts.Format)
if err != nil {
return nil, err
}
if !opts.WithAssets {
markdown, err := upstream.ToMarkdownBytes(data, format)
if err != nil {
return nil, fmt.Errorf("anydoc: markdown conversion failed: %w", err)
}
return &Result{Markdown: markdown}, nil
}
// Official GFM serializer after rewriting Asset images to External URLs
// (`images/image-N.ext`). One Rust parse supplies both the original model
// (for image bytes and placements) and the rendered Markdown.
document, markdown, err := upstream.ToDocumentWithAssetLinks(data, format)
if err != nil {
markdown, mdErr := upstream.ToMarkdownBytes(data, format)
if mdErr != nil {
return nil, fmt.Errorf("anydoc: markdown conversion failed: %w", mdErr)
}
return &Result{
Markdown: markdown,
AssetsError: fmt.Errorf("anydoc: image extraction failed: %w", err),
}, nil
}
return &Result{Markdown: markdown, Assets: collectAssets(document)}, nil
}
// upstreamFormat maps our format name onto the binding's constant. An empty
// name means "detect from content".
func upstreamFormat(name string) (*upstream.Format, error) {
if name == "" {
return nil, nil
}
format, ok := upstream.FormatFromExtension(name)
if !ok {
return nil, fmt.Errorf("anydoc: unsupported format %q", name)
}
return &format, nil
}
// collectAssets names each embedded image after its position in the document,
// because containers store assets without a usable file name of their own, and
// attaches the alt text and section the image appeared under.
func collectAssets(document *upstream.Document) []Asset {
if document == nil || len(document.Assets) == 0 {
return nil
}
placements := placeAssets(document.Blocks)
assets := make([]Asset, 0, len(document.Assets))
for i, asset := range document.Assets {
if len(asset.Data) == 0 {
continue
}
placement := placements[uint64(i)]
assets = append(assets, Asset{
ID: uint64(i),
Name: fmt.Sprintf("image-%d%s", i+1, extensionFor(asset.MediaType)),
MediaType: asset.MediaType,
Data: asset.Data,
Alt: placement.alt,
Section: placement.section,
})
}
return assets
}
// placement is where in the document an asset was referenced from.
type placement struct {
alt string
section string
}
// placeAssets walks the document body and records, per asset, the alt text of
// the image that referenced it and the heading it sat under. The walk
// recurses into lists, tables, and quotes, since an image can be nested
// anywhere a paragraph can.
func placeAssets(blocks []upstream.Block) map[uint64]placement {
placements := make(map[uint64]placement)
section := ""
walkBlocks(blocks, &section, placements)
return placements
}
func walkBlocks(blocks []upstream.Block, section *string, placements map[uint64]placement) {
for _, block := range blocks {
switch block.Kind {
case "heading":
*section = inlineText(block.Content)
walkInlines(block.Content, *section, placements)
case "paragraph":
walkInlines(block.Content, *section, placements)
case "block_quote":
walkBlocks(block.Blocks, section, placements)
case "list":
if block.List != nil {
for _, item := range block.List.Items {
walkBlocks(item.Blocks, section, placements)
}
}
case "table":
if block.Table != nil {
for _, row := range block.Table.Grid {
for _, slot := range row {
if slot.Cell != nil {
walkBlocks(slot.Cell.Blocks, section, placements)
}
}
}
}
}
}
}
func walkInlines(inlines []upstream.Inline, section string, placements map[uint64]placement) {
for _, inline := range inlines {
switch inline.Kind {
case "image":
if inline.Source == nil || inline.Source.Kind != "asset" || inline.Source.AssetID == nil {
continue
}
alt := ""
if inline.Alt != nil {
alt = strings.TrimSpace(*inline.Alt)
}
// First reference wins: the same asset can be placed more than
// once, and the earliest placement is the one a reader would
// associate it with.
if _, seen := placements[*inline.Source.AssetID]; !seen {
placements[*inline.Source.AssetID] = placement{alt: alt, section: section}
}
case "link":
walkInlines(inline.Content, section, placements)
}
}
}
// inlineText flattens inline content to plain text, which is all a heading is
// needed for here.
func inlineText(inlines []upstream.Inline) string {
var text strings.Builder
for _, inline := range inlines {
switch inline.Kind {
case "text", "math":
if inline.Text != nil {
text.WriteString(*inline.Text)
}
case "checkbox":
if inline.Checked != nil && *inline.Checked {
text.WriteString("[x]")
} else {
text.WriteString("[ ]")
}
case "link":
text.WriteString(inlineText(inline.Content))
}
}
return strings.TrimSpace(text.String())
}
// extensionFor returns the extension that the Markdown link for an embedded
// image carries.
//
// This table is one half of a contract with the Rust serializer. The link it
// writes (`images/image-N<ext>`, see third_party/anydoc-go/src/asset_links.rs)
// has to equal the ImageRef.OriginalRef built from this name, because
// ImageResolver looks the link up in a map keyed by that exact string. The
// media types and extensions below must therefore match `extension_for` in
// asset_links.rs exactly.
//
// It is deliberately a pure table. Asking the platform MIME registry made the
// answer depend on the host's /etc/mime.types, which is how EMF/WMF ended up
// as ".emf"/".wmf" here and ".bin" on the Rust side: the link never matched
// the ref and the image bytes were never stored. Unknown types fall back to
// ".bin" on both sides, so downstream storage never writes an extension-less
// blob.
func extensionFor(mediaType string) string {
switch strings.ToLower(strings.TrimSpace(mediaType)) {
case "image/jpeg", "image/jpg":
return ".jpg"
case "image/png":
return ".png"
case "image/gif":
return ".gif"
case "image/webp":
return ".webp"
case "image/bmp":
return ".bmp"
case "image/tiff":
return ".tiff"
case "image/svg+xml":
return ".svg"
case "image/emf":
return ".emf"
case "image/wmf":
return ".wmf"
}
return ".bin"
}
@@ -0,0 +1,24 @@
//go:build !anydoc || !cgo
package anydoc
// The default build links no converter: the anydoc archive is a Rust build
// artifact, and requiring a Rust toolchain to compile Academy would be a steep
// price for one optional engine. Everything still compiles and the engine
// registry simply reports the engine as unavailable.
const unavailableReason = "anydoc engine not built into this binary " +
"(rebuild with `make build-anydoc` / `-tags anydoc`; " +
"Docker images need `--build-arg WITH_ANYDOC=1`)"
func backendAvailable() bool { return false }
func backendUnavailableReason() string { return unavailableReason }
func backendVersion() string { return "" }
func backendConvert(_ []byte, _ Options) (*Result, error) {
// Convert checks Available first, so this is only reachable if a caller
// bypasses it.
return nil, ErrUnavailable
}
@@ -0,0 +1,151 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
var benchmarkDocuments = []string{
"doc/text.doc", "docx/text.docx", "ppt/pres.ppt", "pptx/pres.pptx",
"odt/text.odt", "ods/sheet.ods", "odp/pres.odp", "rtf/text.rtf",
"epub/book.epub", "xls/sheet.xls", "xlsx/sheet.xlsx",
"xlsb/handmade-sheet.xlsb", "csv/sheet.csv", "pdf/text.pdf",
}
// Synthetic size sweeps cover the Go/Rust document-copy path and the bounded
// hostile-PDF detector. They are separate from the upstream fixture comparison.
func BenchmarkConvertScaling(b *testing.B) {
for _, rows := range []int{100, 10000} {
b.Run(fmt.Sprintf("csv_%d_rows", rows), func(b *testing.B) {
data := []byte("name,quantity,description\n" +
strings.Repeat("widget,42,Quarterly shipping report\n", rows))
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := Convert(data, Options{Format: "csv", WithAssets: true})
if err != nil || result.AssetsError != nil {
b.Fatalf("conversion: %v", err)
}
}
})
}
for _, rows := range []int{100, 10000} {
b.Run(fmt.Sprintf("xlsx_%d_rows", rows), func(b *testing.B) {
data := largeWorkbook(b, rows)
result, err := Convert(data, Options{Format: "xlsx", WithAssets: true})
if err != nil || !strings.Contains(result.Markdown, fmt.Sprintf("row-%d", rows)) {
b.Fatalf("preflight: last row was lost, err=%v", err)
}
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := Convert(data, Options{Format: "xlsx", WithAssets: true})
if err != nil || result.AssetsError != nil {
b.Fatalf("conversion: %v", err)
}
}
})
}
for _, operators := range []int{40000, 200000} {
b.Run(fmt.Sprintf("pdf_%d_operators", operators), func(b *testing.B) {
data := unmatchedShowTextPDF(operators)
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
if _, err := Convert(data, Options{Format: "pdf"}); err != nil {
b.Fatal(err)
}
}
})
}
}
func largeWorkbook(t testing.TB, rows int) []byte {
t.Helper()
data := readFixture(t, "xlsx/sheet.xlsx")
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
var out bytes.Buffer
w := zip.NewWriter(&out)
for _, file := range r.File {
if file.Name == "xl/worksheets/sheet1.xml" {
continue
}
if err := w.Copy(file); err != nil {
t.Fatal(err)
}
}
var sheet strings.Builder
sheet.WriteString(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>`)
for row := 1; row <= rows; row++ {
fmt.Fprintf(&sheet, `<row r="%d"><c r="A%d" t="inlineStr"><is><t>row-%d</t></is></c>`+
`<c r="B%d"><v>42</v></c></row>`,
row, row, row, row)
}
sheet.WriteString(`</sheetData></worksheet>`)
part, err := w.Create("xl/worksheets/sheet1.xml")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte(sheet.String())); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
return out.Bytes()
}
func readFixture(t testing.TB, name string) []byte {
t.Helper()
data, err := os.ReadFile(filepath.Join("testdata", "upstream", name))
if err != nil {
t.Fatal(err)
}
return data
}
// WithAssets exercises the default reader path, including Rust parsing,
// the document ABI, Go decoding, image collection, and Markdown serialization.
// Input I/O is excluded. B/op measures Go allocations, not the Rust heap.
func BenchmarkConvert(b *testing.B) {
for _, name := range benchmarkDocuments {
b.Run(strings.Split(name, "/")[0], func(b *testing.B) {
data := readFixture(b, name)
format := strings.TrimPrefix(filepath.Ext(name), ".")
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
opts := Options{Format: format, WithAssets: true}
if result, err := Convert(data, opts); err != nil ||
result.Markdown == "" ||
result.AssetsError != nil {
b.Fatalf("preflight conversion: result=%+v err=%v", result, err)
}
b.ReportAllocs()
b.SetBytes(int64(len(data)))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
result, err := Convert(data, opts)
if err != nil || result.Markdown == "" || result.AssetsError != nil {
b.Errorf("conversion failed: result=%+v err=%v", result, err)
return
}
}
})
})
}
}
@@ -0,0 +1,379 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"fmt"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// These tests exercise the linked Rust converter, so they only build with the
// `anydoc` tag. Run them with:
//
// scripts/build-anydoc-lib.sh && go test -tags anydoc ./internal/infrastructure/docparser/...
// SupportedFileTypes is a static list, so that the engine can advertise its
// file types in builds that link no converter. This is the check that it still
// agrees with what the converter actually accepts, in either direction.
func TestSupportedFileTypesMatchTheConverter(t *testing.T) {
for _, fileType := range SupportedFileTypes() {
format, ok := FormatForFile(fileType, "")
if !ok {
t.Errorf("%q is advertised but maps to no format", fileType)
continue
}
if _, err := upstreamFormat(format); err != nil {
t.Errorf("%q maps to format %q, which the converter rejects: %v", fileType, format, err)
}
}
}
func TestConvertCSV(t *testing.T) {
result, err := Convert([]byte("quarter,widgets\nQ1,12\nQ2,15\n"), Options{Format: "csv"})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "| quarter | widgets |") {
t.Fatalf("expected a markdown table header, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "| Q1 | 12 |") {
t.Fatalf("expected the first data row, got:\n%s", result.Markdown)
}
}
func TestConvertDocxWithEmbeddedImage(t *testing.T) {
document := buildDocx(t)
result, err := Convert(document, Options{Format: "docx", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "# Quarterly report") {
t.Fatalf("expected the heading, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "Widgets shipped on time.") {
t.Fatalf("expected the body paragraph, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "Closing remarks.") {
t.Fatalf("expected the trailing paragraph, got:\n%s", result.Markdown)
}
if len(result.Assets) != 1 {
t.Fatalf("got %d assets, want 1", len(result.Assets))
}
asset := result.Assets[0]
if asset.Name != "image-1.png" {
t.Errorf("asset name = %q, want image-1.png", asset.Name)
}
if !bytes.Equal(asset.Data, onePixelPNG()) {
t.Errorf("asset data does not round-trip the embedded image")
}
if asset.Alt != "Shipping chart" {
t.Errorf("asset alt = %q, want %q", asset.Alt, "Shipping chart")
}
if asset.Section != "Quarterly report" {
t.Errorf("asset section = %q, want %q", asset.Section, "Quarterly report")
}
imageLink := "![Shipping chart](images/image-1.png)"
if !strings.Contains(result.Markdown, imageLink) {
t.Fatalf("expected the image in place, got:\n%s", result.Markdown)
}
before := strings.Index(result.Markdown, "Widgets shipped on time.")
at := strings.Index(result.Markdown, imageLink)
after := strings.Index(result.Markdown, "Closing remarks.")
if before < 0 || at < 0 || after < 0 || !(before < at && at < after) {
t.Fatalf("image is not between the surrounding paragraphs:\n%s", result.Markdown)
}
}
func TestConvertTextlessPDFNeedsOCR(t *testing.T) {
_, err := Convert(textlessPDF(), Options{Format: "pdf"})
if err == nil {
t.Fatal("Convert succeeded on a PDF with no text, want an error")
}
if !PDFNeedsOCR(err) {
t.Fatalf("Convert error = %v, want an OCR-required error", err)
}
}
// The ABI reports error messages through a thread-local slot that a second
// call reads, so a goroutine resumed on another OS thread would report an
// empty or someone else's message. The binding pins the goroutine for the
// pair; this is the regression test for that.
func TestErrorDetailSurvivesConcurrency(t *testing.T) {
const conversions = 4000
var wg sync.WaitGroup
var empty, crossed atomic.Int64
for i := 0; i < conversions; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// docx and xlsx failures carry distinctive messages, so a detail
// naming the other format proves it came from the wrong thread.
format, want, other := "docx", "not a readable zip archive", "not a readable workbook container"
if i%2 == 1 {
format, want, other = "xlsx", "not a readable workbook container", "not a readable zip archive"
}
_, err := Convert([]byte(fmt.Sprintf("garbage %d", i)), Options{Format: format})
if err == nil {
t.Errorf("Convert(garbage) succeeded")
return
}
detail := err.Error()
switch {
case strings.Contains(detail, other):
crossed.Add(1)
case !strings.Contains(detail, want):
empty.Add(1)
}
}(i)
}
wg.Wait()
if empty.Load() > 0 || crossed.Load() > 0 {
t.Fatalf("error details lost or crossed between goroutines: lost=%d crossed=%d (of %d)",
empty.Load(), crossed.Load(), conversions)
}
}
// Detection reads the container itself, so a document whose format is not
// named still converts.
func TestConvertDetectsFormatFromContent(t *testing.T) {
result, err := Convert(buildDocx(t), Options{})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "# Quarterly report") {
t.Fatalf("expected the heading, got:\n%s", result.Markdown)
}
}
func TestConvertRejectsGarbage(t *testing.T) {
if _, err := Convert([]byte("not a document at all"), Options{Format: "docx"}); err == nil {
t.Fatal("Convert succeeded on garbage input, want an error")
}
}
// PDF has no document model, so WithAssets has to be dropped rather than turn
// a working conversion into an error.
func TestConvertPDFIgnoresAssetRequest(t *testing.T) {
result, err := Convert(minimalPDF(), Options{Format: "pdf", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "Shipping summary") {
t.Fatalf("expected the page text, got:\n%s", result.Markdown)
}
if len(result.Assets) != 0 {
t.Errorf("got %d assets for a PDF, want 0", len(result.Assets))
}
}
// A PDF whose catalog holds a deeply nested array is the shape of
// RUSTSEC-2026-0187: lopdf 0.41 recursed per nesting level and killed the
// process with an uncatchable stack overflow, which no Go-side or Rust-side
// recover can contain. The pinned dependency in third_party/anydoc-go bounds
// the recursion, so this must come back as an ordinary error — and if a
// dependency bump ever reintroduces it, this test crashes rather than passing
// quietly.
func TestDeeplyNestedPDFFailsWithoutKillingTheProcess(t *testing.T) {
const depth = 50000
nested := strings.Repeat("[", depth) + strings.Repeat("]", depth)
_, err := Convert(nestedPDF(nested), Options{Format: "pdf"})
if err == nil {
t.Fatal("Convert succeeded on a PDF with no text, want an error")
}
}
// A show-text operator with no operand made the page-classification scan walk
// back over the whole content stream looking for one, so a stream of bare
// `] TJ` tokens cost time quadratic in its length: before pdf-inspector 1.14.2
// this input took 26 seconds of CPU, and a 2 MB one took nearly two minutes.
// Unbounded work is the half of the hostile-PDF problem that guarded() cannot
// catch — it never panics, it just holds the core — so the bound is pinned
// here. The budget is deliberately far above the ~7ms a bounded lookback needs:
// what it has to distinguish is linear from quadratic, not fast from slow.
func TestDetectorLookbackStaysLinear(t *testing.T) {
const (
operators = 200000
budget = 15 * time.Second
)
done := make(chan struct{})
go func() {
defer close(done)
// The result is irrelevant: the page carries one real text run, so
// this converts either way. Only how long it takes is under test.
_, _ = Convert(unmatchedShowTextPDF(operators), Options{Format: "pdf"})
}()
select {
case <-done:
case <-time.After(budget):
t.Fatalf("converting a PDF with %d unmatched TJ operators took over %s; "+
"the detector's operand lookback is no longer bounded", operators, budget)
}
}
// buildDocx writes the smallest OOXML package that carries a heading, a
// paragraph, and one embedded image.
func buildDocx(t *testing.T) []byte {
t.Helper()
parts := map[string]string{
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="png" ContentType="image/png"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>`,
"_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`,
"word/styles.xml": `<?xml version="1.0" encoding="UTF-8"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/>
<w:pPr><w:outlineLvl w:val="0"/></w:pPr>
</w:style>
</w:styles>`,
"word/_rels/document.xml.rels": `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>
</Relationships>`,
"word/document.xml": `<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Quarterly report</w:t></w:r></w:p>
<w:p><w:r><w:t>Widgets shipped on time.</w:t></w:r></w:p>
<w:p><w:r><w:drawing><wp:inline><wp:docPr id="1" name="Chart" descr="Shipping chart"/>
<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic><pic:nvPicPr><pic:cNvPr id="1" name="Chart"/><pic:cNvPicPr/></pic:nvPicPr>
<pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill>
<pic:spPr/></pic:pic>
</a:graphicData></a:graphic>
</wp:inline></w:drawing></w:r></w:p>
<w:p><w:r><w:t>Closing remarks.</w:t></w:r></w:p>
</w:body>
</w:document>`,
}
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
for name, content := range parts {
writer, err := archive.Create(name)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if _, err := writer.Write([]byte(content)); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
image, err := archive.Create("word/media/image1.png")
if err != nil {
t.Fatalf("create image part: %v", err)
}
if _, err := image.Write(onePixelPNG()); err != nil {
t.Fatalf("write image part: %v", err)
}
if err := archive.Close(); err != nil {
t.Fatalf("close archive: %v", err)
}
return buf.Bytes()
}
// onePixelPNG is a 1x1 transparent PNG: the smallest thing a container will
// accept as an image part.
func onePixelPNG() []byte {
return []byte{
0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 'I', 'H', 'D', 'R',
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89,
0x00, 0x00, 0x00, 0x0a, 'I', 'D', 'A', 'T',
0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01,
0x0d, 0x0a, 0x2d, 0xb4,
0x00, 0x00, 0x00, 0x00, 'I', 'E', 'N', 'D', 0xae, 0x42, 0x60, 0x82,
}
}
// minimalPDF is a one-page PDF with a single text run, written by hand so the
// test carries no binary fixture.
func minimalPDF() []byte {
content := "BT /F1 12 Tf 20 100 Td (Shipping summary) Tj ET\n"
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R " +
"/Resources << /Font << /F1 5 0 R >> >> >>",
fmt.Sprintf("<< /Length %d >>\nstream\n%sendstream", len(content), content),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
})
}
// nestedPDF is a one-page PDF carrying the given nested value in its catalog.
func nestedPDF(nested string) []byte {
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R /Nested " + nested + " >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
})
}
// unmatchedShowTextPDF is a one-page PDF whose content stream shows text once
// and then repeats a TJ operator whose array operand is never opened.
func unmatchedShowTextPDF(operators int) []byte {
content := "BT /F1 12 Tf 20 100 Td (Shipping summary) Tj ET\n" +
strings.Repeat("] TJ\n", operators)
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R " +
"/Resources << /Font << /F1 5 0 R >> >> >>",
fmt.Sprintf("<< /Length %d >>\nstream\n%sendstream", len(content), content),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
})
}
// textlessPDF is a one-page PDF with no text stream: the shape of a scanned
// exam paper as far as pdf-inspector is concerned.
func textlessPDF() []byte {
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
})
}
func writePDF(objects []string) []byte {
var pdf bytes.Buffer
offsets := make([]int, len(objects))
pdf.WriteString("%PDF-1.4\n")
for i, object := range objects {
offsets[i] = pdf.Len()
fmt.Fprintf(&pdf, "%d 0 obj\n%s\nendobj\n", i+1, object)
}
xref := pdf.Len()
fmt.Fprintf(&pdf, "xref\n0 %d\n0000000000 65535 f \n", len(objects)+1)
for _, offset := range offsets {
fmt.Fprintf(&pdf, "%010d 00000 n \n", offset)
}
fmt.Fprintf(&pdf, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, xref)
return pdf.Bytes()
}
@@ -0,0 +1,89 @@
//go:build anydoc && cgo
package anydoc
import (
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
upstream "github.com/firecrawl/anydoc/go"
)
// ANYDOC_UPSTREAM_DIR points to the checked-out release tag. This opt-in
// upgrade check runs the full upstream corpus through our actual Go ABI and
// compares Markdown/error details to the upstream Rust snapshots.
func TestUpstreamCorpus(t *testing.T) {
root := os.Getenv("ANYDOC_UPSTREAM_DIR")
if root == "" {
t.Skip("set ANYDOC_UPSTREAM_DIR to an anydoc release checkout")
}
snapshots, err := filepath.Glob(filepath.Join(root, "tests/snapshots/snapshots__*.snap"))
if err != nil || len(snapshots) == 0 {
t.Fatalf("no snapshots: %v", err)
}
for _, path := range snapshots {
name := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "snapshots__"), ".snap")
parts := strings.Split(name, "__")
if len(parts) != 2 {
continue
}
t.Run(name, func(t *testing.T) {
data, err := os.ReadFile(filepath.Join(root, "tests/fixtures", parts[0], parts[1]))
if err != nil {
t.Fatal(err)
}
snapshot, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
_, expected, ok := strings.Cut(string(snapshot[4:]), "---\n")
if !ok {
t.Fatal("invalid snapshot header")
}
format, ok := upstream.FormatFromExtension(strings.TrimPrefix(filepath.Ext(parts[1]), "."))
if !ok {
t.Fatal("unrecognized fixture extension")
}
// The Go binding rejects empty slices before entering C, retaining
// its established empty-input error instead of the ZIP diagnostic.
if len(data) == 0 {
if !strings.HasPrefix(expected, "ERROR:") {
t.Fatal("empty fixture should fail")
}
expected = "ERROR: empty input"
}
actual, err := upstream.ToMarkdownBytes(data, &format)
if err != nil {
var typed *upstream.ConvertError
if !errors.As(err, &typed) {
t.Fatal(err)
}
actual = "ERROR: " + typed.Detail
}
if strings.TrimSpace(actual) != strings.TrimSpace(expected) {
t.Fatalf("snapshot mismatch\nwant: %s\ngot: %s", expected, actual)
}
if err == nil && format != upstream.FormatPdf {
document, err := upstream.ToDocument(data, &format)
if err != nil {
t.Fatalf("document ABI: %v", err)
}
markdown, err := upstream.ToMarkdownWithAssetLinks(data, &format)
if err != nil {
t.Fatalf("asset renderer: %v", err)
}
combined, combinedMarkdown, err := upstream.ToDocumentWithAssetLinks(data, &format)
if err != nil {
t.Fatalf("combined ABI: %v", err)
}
if !reflect.DeepEqual(combined, document) || combinedMarkdown != markdown {
t.Fatal("single-parse output differs from independent document/Markdown APIs")
}
}
})
}
}
@@ -0,0 +1,85 @@
package anydoc
import (
"errors"
"fmt"
"strings"
"testing"
)
// fakeConvertError stands in for the cgo binding's *ConvertError. The
// production type exposes the same two methods; this fake lets the default
// build classify a resource_limit failure without linking the parser.
type fakeConvertError struct {
kind string
detail string
}
func (e *fakeConvertError) Error() string {
if e.detail == "" {
return "anydoc: " + e.kind
}
return "anydoc: " + e.kind + ": " + e.detail
}
func (e *fakeConvertError) ResourceLimit() bool { return e.kind == "resource_limit" }
func (e *fakeConvertError) LimitDetail() string { return e.detail }
func TestMarkResourceLimitClassifiesPermanentBudgetFailure(t *testing.T) {
const detail = "resource limit exceeded (max_xml_nodes): part exceeds 2000000 xml nodes"
raw := &fakeConvertError{kind: "resource_limit", detail: detail}
// Same wrap the cgo backend applies before the reader names the file.
backendErr := fmt.Errorf("anydoc: markdown conversion failed: %w", raw)
got := markResourceLimit(backendErr)
if !errors.Is(got, ErrResourceLimit) {
t.Fatalf("markResourceLimit() = %v, want errors.Is ErrResourceLimit", got)
}
// The reader keeps the chain with %w, which is what convert inspects.
readerErr := fmt.Errorf("anydoc conversion failed for %q: %w", "xlsx50k.xlsx", got)
if !errors.Is(readerErr, ErrResourceLimit) {
t.Fatalf("reader wrap = %v, want errors.Is ErrResourceLimit", readerErr)
}
message := readerErr.Error()
for _, want := range []string{"too large", "max_xml_nodes", "2000000"} {
if !strings.Contains(message, want) {
t.Errorf("message %q does not mention %q", message, want)
}
}
if strings.Contains(message, "DocReader") {
t.Errorf("message points at DocReader, which did not parse the file: %q", message)
}
if !errors.Is(got, raw) {
t.Fatal("resource-limit wrap dropped the converter error")
}
}
func TestMarkResourceLimitLeavesOtherFailuresRetryable(t *testing.T) {
malformed := &fakeConvertError{kind: "malformed", detail: "not a readable zip archive"}
in := fmt.Errorf("anydoc: markdown conversion failed: %w", malformed)
if got := markResourceLimit(in); got != in || errors.Is(got, ErrResourceLimit) {
t.Fatalf("malformed error = %v, want it unchanged and retryable", got)
}
// The kind has to be typed. A matching sentence from somewhere else is
// not a permanent parser rejection.
untyped := errors.New("anydoc: resource_limit: resource limit exceeded (max_xml_nodes): " +
"part exceeds 2000000 xml nodes")
if got := markResourceLimit(untyped); errors.Is(got, ErrResourceLimit) {
t.Fatalf("untyped error was classified as a resource limit: %v", got)
}
if got := markResourceLimit(nil); got != nil {
t.Fatalf("markResourceLimit(nil) = %v, want nil", got)
}
bare := &fakeConvertError{kind: "resource_limit"}
got := markResourceLimit(bare)
if !errors.Is(got, ErrResourceLimit) {
t.Fatalf("limit without detail = %v, want ErrResourceLimit", got)
}
if !strings.Contains(got.Error(), "too large") {
t.Fatalf("limit without detail = %q, want the permanent-failure reason", got.Error())
}
}
@@ -0,0 +1,94 @@
//go:build anydoc && cgo
package anydoc
import (
"bytes"
"os"
"runtime"
"sort"
"strings"
"sync"
"testing"
"time"
)
// Opt-in sustained mixed-format load through the production WithAssets path.
// Use /usr/bin/time -l (macOS) or -v (Linux) to measure native peak RSS too:
// Go's memory statistics do not include Rust allocations.
func TestConcurrentConversionStress(t *testing.T) {
setting := os.Getenv("ANYDOC_STRESS_DURATION")
if setting == "" {
t.Skip("set ANYDOC_STRESS_DURATION, e.g. 30s")
}
duration, err := time.ParseDuration(setting)
if err != nil || duration <= 0 {
t.Fatalf("invalid stress duration %q", setting)
}
type input struct {
data []byte
opts Options
want *Result
}
inputs := make([]input, 0, len(benchmarkDocuments))
for _, name := range benchmarkDocuments {
format := strings.Split(name, "/")[0]
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
i := input{data: readFixture(t, name), opts: Options{Format: format, WithAssets: true}}
i.want, err = Convert(i.data, i.opts)
if err != nil || i.want.AssetsError != nil {
t.Fatalf("preflight %s: %v", name, err)
}
inputs = append(inputs, i)
}
const workers = 8
samples := make([][]time.Duration, workers)
var wg sync.WaitGroup
start := time.Now()
deadline := start.Add(duration)
for worker := 0; worker < workers; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for n := worker; time.Now().Before(deadline); n++ {
i := inputs[n%len(inputs)]
began := time.Now()
got, err := Convert(i.data, i.opts)
samples[worker] = append(samples[worker], time.Since(began))
if err != nil ||
got.AssetsError != nil ||
got.Markdown != i.want.Markdown ||
len(got.Assets) != len(i.want.Assets) {
t.Errorf("worker %d: inconsistent conversion, err=%v", worker, err)
return
}
for j, asset := range got.Assets {
if !bytes.Equal(asset.Data, i.want.Assets[j].Data) ||
asset.Name != i.want.Assets[j].Name {
t.Errorf("worker %d: inconsistent asset %d", worker, j)
return
}
}
}
}(worker)
}
wg.Wait()
elapsed := time.Since(start)
var latencies []time.Duration
for _, sample := range samples {
latencies = append(latencies, sample...)
}
if len(latencies) == 0 {
t.Fatal("no conversions completed")
}
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
t.Logf("workers=%d conversions=%d elapsed=%s throughput=%.1f docs/s "+
"p50=%s p95=%s p99=%s GoHeapAlloc=%d GoTotalAlloc=%d",
workers, len(latencies), elapsed, float64(len(latencies))/elapsed.Seconds(),
latencies[len(latencies)*50/100], latencies[len(latencies)*95/100], latencies[len(latencies)*99/100],
memory.HeapAlloc, memory.TotalAlloc)
}
@@ -0,0 +1,2 @@
# Preserve PDF byte offsets and fixed-width xref records from upstream fixtures.
*.pdf binary
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Sideguide Technologies Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1 @@
Fixtures from [firecrawl/anydoc v0.2.4](https://github.com/firecrawl/anydoc/tree/42bf1c5ecdde9eb0d96d6bd75a9e6698cf93b14c/tests/fixtures), under the included MIT license. Used for Go ABI regression tests and repeatable conversion benchmarks. Files are copied unchanged.
@@ -0,0 +1,8 @@
Kind,Value,Note
Percent,15.5%,fifteen and a half
Currency,1234.5,dollars
Thousands,9876543,grouped
Date,2026-03-15,ides of March
Duration,26:30:15,over a day
Tiny,0.0000004,four ten-millionths
Boolean,TRUE,yes
1 Kind Value Note
2 Percent 15.5% fifteen and a half
3 Currency 1234.5 dollars
4 Thousands 9876543 grouped
5 Date 2026-03-15 ides of March
6 Duration 26:30:15 over a day
7 Tiny 0.0000004 four ten-millionths
8 Boolean TRUE yes
@@ -0,0 +1,50 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [5 0 R 7 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
4 0 obj
<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>
stream
€
endstream
endobj
5 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 6 0 R >>
endobj
6 0 obj
<< /Length 53 >>
stream
BT /F1 24 Tf 72 700 Td (Text on the first page) Tj ET
endstream
endobj
7 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 8 0 R >>
endobj
8 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
xref
0 9
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000191 00000 n
0000000335 00000 n
0000000487 00000 n
0000000590 00000 n
0000000742 00000 n
trailer
<< /Size 9 /Root 1 0 R >>
startxref
824
%%EOF
@@ -0,0 +1,50 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [5 0 R 7 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
4 0 obj
<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>
stream
€
endstream
endobj
5 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 6 0 R >>
endobj
6 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
7 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 8 0 R >>
endobj
8 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
xref
0 9
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000191 00000 n
0000000335 00000 n
0000000487 00000 n
0000000569 00000 n
0000000721 00000 n
trailer
<< /Size 9 /Root 1 0 R >>
startxref
803
%%EOF
@@ -0,0 +1,5 @@
{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0 Cambria Math;}}
\pard The roots are {\mmath{\*\moMath{\rtlch\fcs1 \af0 \ltrch\fcs0 \f0\insrsid1 }{\mr\mscr0\msty2 x}{\mr\mscr0\msty2 =}{\mf{\mfPr{\mctrlPr\f0 }}{\mnum{\mr\mscr0\msty2 -b\'b1}{\mrad{\mradPr{\mdegHide on}{\mctrlPr\f0 }}{\mdeg}{\me{\msSup{\me{\mr\mscr0\msty2 b}}{\msup{\mr\mscr0\msty2 2}}}{\mr\mscr0\msty2 -4ac}}}}{\mden{\mr\mscr0\msty2 2a}}}}{\mmathPict{\*\mmathPr}{\pict\pngblip\picw1\pich1 89504e47}}} for any a.\par
\pard {\mmath{\*\moMathPara{\moMathParaPr{\mjc centerGroup}}{\*\moMath{\mnary{\mnaryPr{\mchr \u8721 ?}{\mlimLoc undOvr}{\mctrlPr\f0 }}{\msub{\mr\mscr0\msty2 i=1}}{\msup{\mr\mscr0\msty2 n}}{\me{\msSub{\me{\mr\mscr0\msty2 x}}{\msub{\mr\mscr0\msty2 i}}}}}{\mr\mscr0\msty2 =}{\mfunc{\mfName{\mr\mscr0\msty0 sin}}{\me{\md{\mdPr{\mctrlPr\f0 }}{\me{\mr\mscr0\msty2 \u952 ?}}}}}}{\*\moMath{\mr\mnor where }{\mr\mscr0\msty2 \u8722 ?1<x}}}}\par
\pard A price of $5 or $6 is not math.\par
}
@@ -0,0 +1,177 @@
{\rtf1\ansi\deff3\adeflang1025
{\fonttbl{\f0\froman\fprq2\fcharset0 Times New Roman;}{\f1\froman\fprq2\fcharset2 Symbol;}{\f2\fswiss\fprq2\fcharset0 Arial;}{\f3\froman\fprq2\fcharset0 Liberation Serif{\*\falt Times New Roman};}{\f4\fswiss\fprq2\fcharset0 Liberation Sans{\*\falt Arial};}{\f5\fnil\fprq2\fcharset0 Microsoft YaHei;}{\f6\fnil\fprq2\fcharset0 Arial;}{\f7\fswiss\fprq0\fcharset128 Arial;}}
{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}
{\stylesheet{\s0\snext0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052 Normal;}
{\s1\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl0\outlinelevel0\nowidctlpar\hyphpar0\ltrpar\fs36\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 1;}
{\s2\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 2;}
{\s3\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl2\outlinelevel2\nowidctlpar\hyphpar0\ltrpar\fs26\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 3;}
{\*\cs15\snext15\loch\b0 NotBold;}
{\*\cs16\snext16\loch\b Bold;}
{\*\cs17\snext17\loch\i Italic;}
{\*\cs18\snext18\loch\strike Struck;}
{\*\cs19\snext19\loch\cf9\ul\ulc0 Hyperlink;}
{\*\cs20\snext20 Footnote Characters;}
{\*\cs21\snext21\loch\super footnote reference;}
{\*\cs22\snext22 Endnote Characters;}
{\*\cs23\snext23\loch\super endnote reference;}
{\s24\sbasedon0\snext25\rtlch\af6\afs28 \ltrch\hich\af4\loch\sb240\sa120\keepn\f4\fs28\dbch\af5 Heading;}
{\s25\sbasedon0\snext25\loch\sl276\slmult1\sb0\sa140 Body Text;}
{\s26\sbasedon25\snext26\rtlch\af7 \ltrch List;}
{\s27\sbasedon0\snext27\rtlch\af7\afs24\ai \ltrch\loch\sb120\sa120\noline\fs24\i caption;}
{\s28\sbasedon0\snext28\rtlch\af7 \ltrch\loch\noline Index;}
{\s29\snext29\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\b\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052 StrongPara;}
{\s30\sbasedon0\snext30\loch\nowidctlpar\noline Table Contents;}
{\s31\sbasedon0\snext31\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20 footnote text;}
{\s32\sbasedon0\snext32\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20 endnote text;}
{\s33\sbasedon0\snext33 Frame Contents;}
}{\*\listtable{\list\listtemplateid1
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}\listid1}
{\list\listtemplateid2
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'00.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc4\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'01);}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc2\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid2}
{\list\listtemplateid3
{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow2{\leveltext \'01\u8226 ?;}{\levelnumbers;}\f9\fi0\li0}
{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow2{\leveltext \'01\u9702 ?;}{\levelnumbers;}\f9\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi-360\li1440}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid3}
{\list\listtemplateid4
{\listlevel\levelnfc1\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'00.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'01.;}{\levelnumbers\'01;}\fi-360\li1080}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi-360\li1440}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid4}
}{\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}{\listoverride\listid3\listoverridecount0\ls3}{\listoverride\listid4\listoverridecount0\ls4}}{\*\generator LibreOffice/25.2.7.2$Windows_X86_64 LibreOffice_project/5cbfd1ab6520636bb5f7b99185aa69bd7456825d}{\info{\creatim\yr0\mo0\dy0\hr0\min0}{\revtim\yr0\mo0\dy0\hr0\min0}{\printim\yr0\mo0\dy0\hr0\min0}}{\*\userprops}\deftab709\deftab709\deftab709\deftab709\deftab709
\hyphauto1\viewscale100\formshade\nobrkwrptbl\paperh16838\paperw11906\margl1134\margr1134\margt1134\margb1134\sectd\sbknone\sftnnar\saftnnrlc\sectunlocked1\pgwsxn11906\pghsxn16838\marglsxn1134\margrsxn1134\margtsxn1134\margbsxn1134\ftnbj\ftnstart1\ftnrstcont\ftnnar\fet2\aftnrstcont\aftnstart1\aftnnrlc
{\*\ftnsep\chftnsep}\pgndec\pard\plain \s1\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl0\outlinelevel0\nowidctlpar\hyphpar0\ltrpar\fs36\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Fixture Document}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Plain paragraph with }{\loch\cs16\loch\b\loch
bold}{\loch
, }{\loch\cs17\loch\i\loch
italic}{\loch
, and }{\loch\cs18\loch\strike\loch
struck}{\loch
runs.}
\par \pard\plain \s29\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\b\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Style-bold paragraph with a }{\loch\cs15\loch\b0\loch
NotBold-styled span}{\loch
inside.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Lists}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 1.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
First numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 2.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Second numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain a)\tab}\ilvl1\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Alpha sub one}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain b)\tab}\ilvl1\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Alpha sub two}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain i.\tab}\ilvl2\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman sub sub}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 3.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Third numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Interrupting paragraph between lists.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 4.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Fourth, continuing the count}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain IV.\tab}\ilvl0\ls4 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman starting at four}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain V.\tab}\ilvl0\ls4 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman five}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u8226\'95\tab}\ilvl0\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Bullet one}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u8226\'95\tab}\ilvl0\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Bullet two}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u9702\'3f\tab}\ilvl1\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Nested bullet}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Table}
\par \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
Wide head}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
End}\cell\row\pard \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\clvmgf\cellx3213\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
Tall}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
B2}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
C2}\cell\row\pard \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\clvmrg\cellx3213\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar\loch
\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
B3}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
C3}\cell\row\pard \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Notes and special text}
\par \ql\fi-340\li340\lin340\noline\ltrpar\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Music clef \uc0 \u55348\uc1 \u56606\'3f appears before this footnote}{{\super \loch \chftn{\*\footnote \chftn\pard\plain \s31\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20{\loch
\tab Footnote after an astral character.}
}}
}{\loch
reference.}
\par \ql\fi-340\li340\lin340\noline\ltrpar\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
An endnote follows here}{{\super \loch \chftn{\*\footnote\ftnalt \chftn\pard\plain \s32\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20{\loch
\tab Endnote body text.}
}}
}{\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Persian with ZWNJ: }{
\u1605\'3f\u1740\'3f\u8204\'3f\u1582\'3f\u1608\'3f\u1575\'3f\u1607\'3f\u1605\'3f}{\loch
. Family emoji: \uc0 \u55357\uc1 \u56424\'3f\u8205\'3f\uc0 \u55357\uc1 \u56425\'3f\u8205\'3f\uc0 \u55357\uc1 \u56423\'3f.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Markdown specials: *stars* _under_ [bracket] `tick` #hash 1. dotted | pipe.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Links and anchors}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
External link to }{{\field{\*\fldinst HYPERLINK "https://example.com/page" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
example}{}}}\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Relative link to }{{\field{\*\fldinst HYPERLINK "file:///anydoc/tests/fixture-src/sibling.odt" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
a sibling file}{}}}\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
{\*\bkmkstart plainmark}{\*\bkmkend plainmark}This plain paragraph carries a bookmark.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Jump to }{{\field{\*\fldinst HYPERLINK "#plainmark" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
the bookmarked paragraph}{}}}\loch
.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Objects}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Inline image: }{\loch
{\pict{\*\picprop{\sp{\sn wzDescription}{\sv tiny red dot}}{\sp{\sn wzName}{\sv }}}\picscalex1700\picscaley1700\piccropl0\piccropr0\piccropt0\piccropb0\picw1\pich1\picwgoal10\pichgoal10\pngblip
89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63fccfc0500f000485018084a98c21000000004945
4e44ae426082}
}{\loch
done.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Text box: }{
{\shp{\*\shpinst\shpwr2\shpwrk0\shpbypara\shpbyignore\shptop-1362\shpbottom-228\shpbxcolumn\shpbxignore\shpleft0\shpright2835\shpz1{\sp{\sn shapeType}{\sv 202}}{\sp{\sn dxWrapDistLeft}{\sv 72390}}{\sp{\sn dxWrapDistRight}{\sv 72390}}{\sp{\sn dyWrapDistTop}{\sv 72390}}{\sp{\sn dyWrapDistBottom}{\sv 72390}}{\sp{\sn posrelv}{\sv 2}}{\sp{\sn posv}{\sv 1}}{\sp{\sn posrelh}{\sv 2}}{\sp{\sn posh}{\sv 2}}{\sp{\sn dxTextLeft}{\sv 53975}}{\sp{\sn dyTextTop}{\sv 53975}}{\sp{\sn dxTextRight}{\sv 53975}}{\sp{\sn dyTextBottom}{\sv 53975}}{\sp{\sn lineColor}{\sv 0}}{\sp{\sn lineWidth}{\sv 635}}{\shptxt\s33\ql{\loch
Inside the text box.}
\par \pard}}}
}{\loch
after the box.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Quote and code}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Value below one millionth: 0.0000004 should survive.}
\par }
@@ -0,0 +1,225 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"testing"
upstream "github.com/firecrawl/anydoc/go"
)
func TestConvertEquations(t *testing.T) {
for _, format := range []string{"docx", "pptx", "odt", "epub", "rtf"} {
t.Run(format, func(t *testing.T) {
data := readFixture(t, format+"/handmade-math."+format)
for _, assets := range []bool{false, true} {
result, err := Convert(data, Options{Format: format, WithAssets: assets})
if err != nil {
t.Fatal(err)
}
if result.AssetsError != nil {
t.Fatalf("document ABI failed: %v", result.AssetsError)
}
if !strings.Contains(result.Markdown, `\frac`) ||
!strings.Contains(result.Markdown, "$") {
t.Fatalf("equation lost (assets=%v): %s", assets, result.Markdown)
}
}
})
}
// Check the actual decoded fields, not only the independent Markdown path.
doc, err := upstream.ToDocument(readFixture(t, "docx/handmade-math.docx"), nil)
if err != nil {
t.Fatal(err)
}
var inline, block bool
for _, b := range doc.Blocks {
block = block || b.Kind == "math" && b.Text != nil && strings.Contains(*b.Text, `\sum`)
for _, in := range b.Content {
inline = inline || in.Kind == "math" && in.Text != nil && strings.Contains(*in.Text, `\frac`)
}
}
if !inline || !block {
t.Fatalf("decoded equation nodes missing: inline=%v block=%v", inline, block)
}
}
func TestConvertPDFReportsScannedPages(t *testing.T) {
for _, tc := range []struct{ file, detail string }{
{"handmade-mixed.pdf", "page 2 of 2 needs OCR"},
{"handmade-scanned.pdf", "all 2 pages need OCR"},
} {
t.Run(tc.file, func(t *testing.T) {
result, err := Convert(readFixture(t, "pdf/"+tc.file), Options{Format: "pdf", WithAssets: true})
var typed *upstream.ConvertError
if result != nil ||
!errors.As(err, &typed) ||
typed.Kind != "needs_ocr" ||
!strings.Contains(typed.Detail, tc.detail) {
t.Fatalf("want scanned-page error, got result=%+v err=%v", result, err)
}
if !PDFNeedsOCR(fmt.Errorf("reader: %w", err)) {
t.Fatal("wrapped typed error did not trigger OCR fallback")
}
})
}
if !PDFNeedsOCR(&upstream.ConvertError{Kind: "needs_ocr", Detail: "localized detail"}) {
t.Fatal("OCR detection still depends on English wording")
}
if PDFNeedsOCR(&upstream.ConvertError{Kind: "malformed", Detail: "invalid PDF"}) {
t.Fatal("malformed PDF incorrectly triggers OCR")
}
}
func TestConvertSpreadsheetCheckboxes(t *testing.T) {
// Add VML form controls to an upstream workbook. Both boolean states must
// survive Rust encoding and Go decoding, including subsequent table cells.
data := readFixture(t, "xlsx/sheet.xlsx")
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
var out bytes.Buffer
w := zip.NewWriter(&out)
for _, f := range reader.File {
if f.Name == "xl/worksheets/_rels/sheet1.xml.rels" {
continue
}
if err := w.Copy(f); err != nil {
t.Fatal(err)
}
}
parts := map[string]string{
"xl/worksheets/_rels/sheet1.xml.rels": `<Relationships ` +
`xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><` +
`Relationship Id="checkboxes" ` +
`Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing"` +
` Target="../drawings/checkboxes.vml"/></Relationships>`,
"xl/drawings/checkboxes.vml": `<xml xmlns:v="urn:schemas-microsoft-com:vml" ` +
`xmlns:x="urn:schemas-microsoft-com:office:excel"><v:shape><v:textbox>Approved</v:text` +
`box><x:ClientData ObjectType="Checkbox"><x:Anchor>0,0,0,0,1,0,1,0</x:Anchor><x:Checke` +
`d>1</x:Checked></x:ClientData></v:shape><v:shape><v:textbox>Pending</v:textbox><x:Cli` +
`entData ObjectType="Checkbox"><x:Anchor>1,0,0,0,2,0,1,0</x:Anchor></x:ClientData></v:` +
`shape></xml>`,
}
for name, content := range parts {
part, err := w.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte(content)); err != nil {
t.Fatal(err)
}
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
result, err := Convert(out.Bytes(), Options{Format: "xlsx", WithAssets: true})
if err != nil {
t.Fatal(err)
}
if result.AssetsError != nil ||
!strings.Contains(result.Markdown, "[x] Approved") ||
!strings.Contains(result.Markdown, "[ ] Pending") {
t.Fatalf("checkbox conversion: %+v", result)
}
doc, err := upstream.ToDocument(out.Bytes(), nil)
if err != nil {
t.Fatal(err)
}
states := map[bool]bool{}
for _, block := range doc.Blocks {
if block.Table == nil {
continue
}
for _, row := range block.Table.Grid {
for _, slot := range row {
if slot.Cell == nil {
continue
}
for _, b := range slot.Cell.Blocks {
for _, in := range b.Content {
if in.Kind == "checkbox" && in.Checked != nil {
states[*in.Checked] = true
}
}
}
}
}
}
if !states[false] || !states[true] {
t.Fatalf("decoded checkbox states: %v", states)
}
}
func TestConvertAllBenchmarkFormats(t *testing.T) {
for _, name := range benchmarkDocuments {
t.Run(name, func(t *testing.T) {
format := strings.Split(name, "/")[0]
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
result, err := Convert(readFixture(t, name), Options{Format: format, WithAssets: true})
if err != nil || result.Markdown == "" || result.AssetsError != nil {
t.Fatalf("conversion: result=%+v err=%v", result, err)
}
})
}
}
func TestCombinedConversionPreservesModelAndMarkdown(t *testing.T) {
// Exercise auto-detection as well as all normal formats, without requiring
// an external upstream checkout for this regression in CI.
for _, name := range benchmarkDocuments {
if strings.HasPrefix(name, "pdf/") {
continue
}
t.Run(name, func(t *testing.T) {
data := readFixture(t, name)
var format *upstream.Format
if strings.HasPrefix(name, "csv/") {
f := upstream.FormatCsv
format = &f
}
want, err := upstream.ToDocument(data, format)
if err != nil {
t.Fatal(err)
}
wantMarkdown, err := upstream.ToMarkdownWithAssetLinks(data, format)
if err != nil {
t.Fatal(err)
}
got, markdown, err := upstream.ToDocumentWithAssetLinks(data, format)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, want) || markdown != wantMarkdown {
t.Fatal("single parse changed model or Markdown")
}
})
}
for _, tc := range []struct {
name string
data []byte
format *upstream.Format
kind string
}{
{"empty", nil, nil, "unsupported"},
{"garbage", []byte("garbage"), nil, "unsupported"},
{"pdf", minimalPDF(), nil, "pdf_no_model"},
} {
t.Run(tc.name, func(t *testing.T) {
doc, md, err := upstream.ToDocumentWithAssetLinks(tc.data, tc.format)
var typed *upstream.ConvertError
if doc != nil || md != "" || !errors.As(err, &typed) || typed.Kind != tc.kind {
t.Fatalf("error contract: doc=%+v md=%q err=%v", doc, md, err)
}
})
}
}
@@ -0,0 +1,160 @@
package docparser
import (
"context"
"fmt"
"path/filepath"
"strings"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// AnydocReader converts office documents to markdown in this process, using
// the anydoc converter instead of the Python docreader service.
//
// Embedded images are rendered in place from the document model. PDFs with no
// text layer (scanned exam papers) cannot be converted by anydoc; when a
// fallback reader is configured (typically the builtin docreader) those files
// are handed off so pages can be rasterized for OCR.
type AnydocReader struct {
// extractImages controls whether embedded images are parsed and placed
// in the markdown. Off halves parse time for text-only indexing.
extractImages bool
// fallback is used when a PDF has no extractable text. Nil means the
// conversion error is returned to the caller.
fallback interfaces.DocReader
}
// NewAnydocReader builds a reader. The "anydoc_extract_images" override turns
// off image extraction. fallback may be nil.
func NewAnydocReader(overrides map[string]string, fallback interfaces.DocReader) *AnydocReader {
return &AnydocReader{
extractImages: !isFalsey(overrides["anydoc_extract_images"]),
fallback: fallback,
}
}
// Read converts the document carried by the request.
func (r *AnydocReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if req.URL != "" && len(req.FileContent) == 0 {
return nil, fmt.Errorf("anydoc engine reads uploaded documents, not URLs")
}
format, ok := anydoc.FormatForFile(req.FileType, req.FileName)
if !ok {
return nil, fmt.Errorf("anydoc engine does not support file type %q", fileTypeOf(req))
}
converted, err := anydoc.Convert(req.FileContent, anydoc.Options{
Format: format,
WithAssets: r.extractImages,
})
if format == "pdf" && (anydoc.PDFNeedsOCR(err) || pdfMarkdownIsEmpty(converted, err)) {
return r.readScannedPDF(ctx, req, err)
}
if err != nil {
return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, err)
}
if converted.AssetsError != nil {
logger.Warnf(ctx, "[anydoc] %q parsed as text but its images were dropped: %v",
req.FileName, converted.AssetsError)
}
return &types.ReadResult{
MarkdownContent: converted.Markdown,
ImageRefs: imageRefsFromAssets(converted.Assets),
Metadata: map[string]string{
"parser": AnydocEngineName,
"anydoc_version": anydoc.Version(),
"source_format": format,
},
}, nil
}
func pdfMarkdownIsEmpty(converted *anydoc.Result, err error) bool {
if err != nil || converted == nil {
return false
}
return strings.TrimSpace(converted.Markdown) == ""
}
func (r *AnydocReader) readScannedPDF(ctx context.Context, req *types.ReadRequest, convertErr error) (*types.ReadResult, error) {
if !r.canFallback() {
if convertErr != nil {
return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, convertErr)
}
return nil, fmt.Errorf("anydoc conversion failed for %q: PDF has no extractable text; OCR is required", req.FileName)
}
logger.Infof(ctx, "[anydoc] %q contains pages requiring OCR, falling back to builtin for scanned-PDF OCR",
req.FileName)
fallbackReq := *req
fallbackReq.ParserEngine = BuiltinEngineName
result, err := r.fallback.Read(ctx, &fallbackReq)
if err != nil {
return nil, fmt.Errorf("anydoc scanned-PDF fallback failed for %q: %w", req.FileName, err)
}
if result == nil {
return nil, fmt.Errorf("anydoc scanned-PDF fallback returned no result for %q", req.FileName)
}
if result.Metadata == nil {
result.Metadata = map[string]string{}
}
if result.Metadata["parser"] == "" {
result.Metadata["parser"] = BuiltinEngineName
}
result.Metadata["anydoc_fallback"] = "scanned_pdf"
if result.Metadata["image_source_type"] == "" {
result.Metadata["image_source_type"] = "scanned_pdf"
}
return result, nil
}
func (r *AnydocReader) canFallback() bool {
if r.fallback == nil {
return false
}
if connected, ok := r.fallback.(interface{ IsConnected() bool }); ok {
return connected.IsConnected()
}
return true
}
// imageRefsFromAssets turns extracted assets into ImageRefs that match the
// in-place markdown links renderMarkdown wrote.
func imageRefsFromAssets(assets []anydoc.Asset) []types.ImageRef {
if len(assets) == 0 {
return nil
}
refs := make([]types.ImageRef, 0, len(assets))
for _, asset := range assets {
ref := anydoc.ImageDir + asset.Name
refs = append(refs, types.ImageRef{
Filename: asset.Name,
OriginalRef: ref,
MimeType: asset.MediaType,
ImageData: asset.Data,
})
}
return refs
}
// fileTypeOf reports the request's file type, falling back to the file name's
// extension the way every reader in this package does.
func fileTypeOf(req *types.ReadRequest) string {
if ft := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(req.FileType)), "."); ft != "" {
return ft
}
return strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
func isFalsey(value string) bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "false", "0", "no", "off":
return true
}
return false
}
@@ -0,0 +1,35 @@
//go:build anydoc && cgo
package docparser
import (
"bytes"
"context"
"os"
"testing"
"academy/internal/types"
)
func TestAnydocReaderMixedPDFFallsBackThroughRead(t *testing.T) {
data, err := os.ReadFile("anydoc/testdata/upstream/pdf/handmade-mixed.pdf")
if err != nil {
t.Fatal(err)
}
fallback := &stubDocReader{result: &types.ReadResult{MarkdownContent: "Both pages including OCR"}}
req := &types.ReadRequest{FileName: "mixed.pdf", FileType: "pdf", FileContent: data}
result, err := NewAnydocReader(nil, fallback).Read(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if fallback.got == nil ||
!bytes.Equal(fallback.got.FileContent, req.FileContent) ||
fallback.got.ParserEngine != BuiltinEngineName ||
result.MarkdownContent != "Both pages including OCR" ||
result.Metadata["anydoc_fallback"] != "scanned_pdf" {
t.Fatalf("mixed PDF did not reach fallback intact: %+v", result)
}
if result, err := NewAnydocReader(nil, nil).Read(context.Background(), req); err == nil || result != nil {
t.Fatalf("mixed PDF without OCR returned partial success: result=%+v err=%v", result, err)
}
}
@@ -0,0 +1,144 @@
package docparser
import (
"context"
"errors"
"strings"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
)
func TestAnydocReaderRejectsUnsupportedFileType(t *testing.T) {
_, err := NewAnydocReader(nil, nil).Read(context.Background(), &types.ReadRequest{
FileName: "photo.png",
FileType: "png",
FileContent: []byte("not really a png"),
})
if err == nil {
t.Fatal("Read succeeded for an unsupported file type, want an error")
}
if !strings.Contains(err.Error(), "png") {
t.Errorf("error does not name the file type: %v", err)
}
}
func TestAnydocReaderRejectsURLs(t *testing.T) {
_, err := NewAnydocReader(nil, nil).Read(context.Background(), &types.ReadRequest{
URL: "https://example.com/report.docx",
FileType: "docx",
})
if err == nil {
t.Fatal("Read succeeded for a URL request, want an error")
}
}
func TestNewAnydocReaderHonoursImageExtractionOverride(t *testing.T) {
if !NewAnydocReader(nil, nil).extractImages {
t.Error("image extraction is off by default, want on")
}
if NewAnydocReader(map[string]string{"anydoc_extract_images": "false"}, nil).extractImages {
t.Error("image extraction stayed on after the override turned it off")
}
}
func TestImageRefsFromAssetsMatchInPlaceMarkdownPaths(t *testing.T) {
refs := imageRefsFromAssets([]anydoc.Asset{
{Name: "image-1.png", MediaType: "image/png", Data: []byte("first")},
{Name: "image-2.jpg", MediaType: "image/jpeg", Data: []byte("second")},
})
if len(refs) != 2 {
t.Fatalf("got %d image refs, want 2", len(refs))
}
if refs[0].OriginalRef != "images/image-1.png" {
t.Errorf("first OriginalRef = %q, want images/image-1.png", refs[0].OriginalRef)
}
if refs[1].MimeType != "image/jpeg" {
t.Errorf("second mime type = %q, want image/jpeg", refs[1].MimeType)
}
if len(refs[0].ImageData) == 0 {
t.Error("image ref carries no bytes")
}
}
func TestImageRefsFromAssetsEmpty(t *testing.T) {
if refs := imageRefsFromAssets(nil); refs != nil {
t.Errorf("got %d image refs, want none", len(refs))
}
}
func TestAnydocReaderFallsBackForScannedPDF(t *testing.T) {
fallback := &stubDocReader{result: &types.ReadResult{
MarkdownContent: "![page](images/page_1.jpg)",
ImageRefs: []types.ImageRef{{
Filename: "page_1.jpg",
OriginalRef: "images/page_1.jpg",
ImageData: []byte("jpeg"),
}},
Metadata: map[string]string{"image_source_type": "scanned_pdf"},
}}
result, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
FileType: "pdf",
}, errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required"))
if err != nil {
t.Fatalf("readScannedPDF: %v", err)
}
if !strings.Contains(result.MarkdownContent, "images/page_1.jpg") {
t.Errorf("fallback markdown missing page image:\n%s", result.MarkdownContent)
}
if result.Metadata["anydoc_fallback"] != "scanned_pdf" {
t.Errorf("anydoc_fallback = %q, want scanned_pdf", result.Metadata["anydoc_fallback"])
}
if result.Metadata["image_source_type"] != "scanned_pdf" {
t.Errorf("image_source_type = %q, want scanned_pdf", result.Metadata["image_source_type"])
}
if fallback.got == nil || fallback.got.ParserEngine != BuiltinEngineName {
t.Errorf("fallback request engine = %v, want builtin", fallback.got)
}
}
func TestAnydocReaderScannedPDFWithoutFallbackKeepsError(t *testing.T) {
_, err := NewAnydocReader(nil, nil).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
}, errors.New("PDF has no extractable text: OCR is required"))
if err == nil {
t.Fatal("readScannedPDF succeeded without a fallback, want an error")
}
if !strings.Contains(err.Error(), "OCR is required") {
t.Errorf("error does not mention OCR: %v", err)
}
}
func TestAnydocReaderDisconnectedFallbackKeepsError(t *testing.T) {
fallback := &disconnectedDocReader{}
_, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
}, errors.New("PDF has no extractable text: OCR is required"))
if err == nil {
t.Fatal("readScannedPDF succeeded with a disconnected fallback, want an error")
}
if !strings.Contains(err.Error(), "OCR is required") {
t.Errorf("error does not mention OCR: %v", err)
}
}
type stubDocReader struct {
got *types.ReadRequest
result *types.ReadResult
err error
}
func (s *stubDocReader) Read(_ context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
s.got = req
return s.result, s.err
}
type disconnectedDocReader struct{}
func (disconnectedDocReader) Read(context.Context, *types.ReadRequest) (*types.ReadResult, error) {
return nil, errors.New("should not be called")
}
func (disconnectedDocReader) IsConnected() bool { return false }
@@ -0,0 +1,228 @@
//go:build anydoc && cgo
package docparser
import (
"archive/zip"
"bytes"
"encoding/binary"
"path"
"sort"
"strconv"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
)
// TestEmbeddedVectorImageLinksResolve guards the string contract between
// anydoc's Rust serializer and this package's image resolver.
//
// anydoc renders an embedded image in place as `![alt](images/image-N<ext>)`,
// where `<ext>` comes from `asset_links.rs::extension_for(asset.media_type)`.
// ImageResolver looks that exact string up in a map keyed by
// `anydoc.ImageDir + Asset.Name`, and `Asset.Name` is built from
// `backend_cgo.go::extensionFor(asset.MediaType)`. Nothing normalises the two,
// so any disagreement about the extension makes the lookup miss and the image
// bytes are never stored, silently.
//
// EMF and WMF are what Word, Excel and PowerPoint use for pasted charts,
// equations and Visio drawings. The two sides used to disagree about them: the
// Rust table fell through to ".bin" while the Go side asked the platform MIME
// registry and got ".emf"/".wmf". This test converts a document carrying one of
// each and requires every Markdown image reference to resolve.
func TestEmbeddedVectorImageLinksResolve(t *testing.T) {
result, err := anydoc.Convert(vectorDocx(t), anydoc.Options{Format: "docx", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if result.AssetsError != nil {
t.Fatalf("image extraction failed: %v", result.AssetsError)
}
var mediaTypes []string
for _, asset := range result.Assets {
mediaTypes = append(mediaTypes, asset.MediaType)
}
sort.Strings(mediaTypes)
if want := []string{"image/emf", "image/wmf"}; !equalStrings(mediaTypes, want) {
t.Fatalf("extracted media types = %v, want %v", mediaTypes, want)
}
// Exactly what ImageResolver.ResolveAndStore builds before looking up the
// Markdown reference.
refMap := map[string]types.ImageRef{}
for _, ref := range imageRefsFromAssets(result.Assets) {
refMap[ref.OriginalRef] = ref
}
references := scanMarkdownImageTargets(result.Markdown)
if len(references) != len(result.Assets) {
t.Fatalf("markdown carries %d image references, want %d:\n%s",
len(references), len(result.Assets), result.Markdown)
}
for _, reference := range references {
raw := result.Markdown[reference.TargetStart:reference.TargetEnd]
if _, _, _, ok := splitMarkdownImageTarget(raw, refMap); !ok {
t.Errorf("markdown reference %q matches no ImageRef, so the image would never be stored (lookup keys: %v)",
raw, sortedRefKeys(refMap))
}
}
// Agreeing on ".bin" for everything would satisfy the loop above while
// still discarding the format, so pin the extensions too. Asset order
// follows the archive rather than the document, so compare the set.
var extensions []string
for key := range refMap {
extensions = append(extensions, path.Ext(key))
}
sort.Strings(extensions)
if want := []string{".emf", ".wmf"}; !equalStrings(extensions, want) {
t.Errorf("image reference extensions = %v, want %v (lookup keys: %v)",
extensions, want, sortedRefKeys(refMap))
}
}
func equalStrings(got, want []string) bool {
if len(got) != len(want) {
return false
}
for i := range got {
if got[i] != want[i] {
return false
}
}
return true
}
func sortedRefKeys(refMap map[string]types.ImageRef) []string {
keys := make([]string, 0, len(refMap))
for key := range refMap {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
// vectorDocx builds a minimal .docx holding one EMF and one WMF drawing. The
// payloads only need a recognisable header: anydoc addresses an embedded part
// through its relationship target and extension, not by decoding the image.
func vectorDocx(t *testing.T) []byte {
t.Helper()
const (
relsNS = "http://schemas.openxmlformats.org/package/2006/relationships"
wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
rNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
aNS = "http://schemas.openxmlformats.org/drawingml/2006/main"
wpNS = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
picNS = "http://schemas.openxmlformats.org/drawingml/2006/picture"
)
files := []struct {
name string
body string
}{
{"[Content_Types].xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="emf" ContentType="image/x-emf"/>
<Default Extension="wmf" ContentType="image/x-wmf"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>`},
{"_rels/.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + rNS + `/officeDocument" Target="word/document.xml"/></Relationships>`},
{"word/_rels/document.xml.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="` + relsNS + `">
<Relationship Id="rId1" Type="` + rNS + `/image" Target="media/image1.emf"/>
<Relationship Id="rId2" Type="` + rNS + `/image" Target="media/image2.wmf"/>
</Relationships>`},
{"word/document.xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="` + wNS + `" xmlns:r="` + rNS + `" xmlns:a="` + aNS + `" xmlns:wp="` + wpNS + `">
<w:body><w:p><w:r><w:t>vector images</w:t></w:r></w:p>` +
drawingParagraph(picNS, aNS, wpNS, rNS, "rId1", "chart.emf", 1) +
drawingParagraph(picNS, aNS, wpNS, rNS, "rId2", "equation.wmf", 2) +
`</w:body></w:document>`},
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, file := range files {
writer, err := zw.Create(file.name)
if err != nil {
t.Fatalf("zip create %s: %v", file.name, err)
}
if _, err := writer.Write([]byte(file.body)); err != nil {
t.Fatalf("zip write %s: %v", file.name, err)
}
}
for name, body := range map[string][]byte{
"word/media/image1.emf": emfHeader(),
"word/media/image2.wmf": wmfPlaceableHeader(),
} {
writer, err := zw.Create(name)
if err != nil {
t.Fatalf("zip create %s: %v", name, err)
}
if _, err := writer.Write(body); err != nil {
t.Fatalf("zip write %s: %v", name, err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("zip close: %v", err)
}
return buf.Bytes()
}
func drawingParagraph(picNS, aNS, wpNS, rNS, relID, name string, id int) string {
number := strconv.Itoa(id)
return `<w:p><w:r><w:drawing><wp:inline>
<wp:extent cx="914400" cy="914400"/>
<wp:docPr id="` + number + `" name="` + name + `" descr="` + name + `"/>
<a:graphic><a:graphicData uri="` + picNS + `">
<pic:pic xmlns:pic="` + picNS + `">
<pic:nvPicPr><pic:cNvPr id="` + number + `" name="` + name + `"/><pic:cNvPicPr/></pic:nvPicPr>
<pic:blipFill><a:blip r:embed="` + relID + `"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>
<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>
<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>
</pic:pic></a:graphicData></a:graphic>
</wp:inline></w:drawing></w:r></w:p>`
}
// emfHeader is a structurally valid EMR_HEADER record (MS-EMF 2.3.4.2).
func emfHeader() []byte {
buf := make([]byte, 0, 88)
buf = binary.LittleEndian.AppendUint32(buf, 1) // iType = EMR_HEADER
buf = binary.LittleEndian.AppendUint32(buf, 88)
for i := 0; i < 8; i++ { // rclBounds, rclFrame
buf = binary.LittleEndian.AppendUint32(buf, 914400)
}
buf = binary.LittleEndian.AppendUint32(buf, 0x464D4520) // dSignature = ' EMF'
buf = binary.LittleEndian.AppendUint32(buf, 0x00010000) // nVersion
buf = binary.LittleEndian.AppendUint32(buf, 88) // nBytes
buf = binary.LittleEndian.AppendUint32(buf, 16) // nRecords
buf = binary.LittleEndian.AppendUint16(buf, 0) // nHandles
buf = binary.LittleEndian.AppendUint16(buf, 0) // sReserved
for i := 0; i < 3; i++ { // nDescription, offDescription, nPalEntries
buf = binary.LittleEndian.AppendUint32(buf, 0)
}
for i := 0; i < 4; i++ { // szlDevice, szlMillimeters
buf = binary.LittleEndian.AppendUint32(buf, 0)
}
return append(buf, []byte("EMF-PAYLOAD")...)
}
// wmfPlaceableHeader is a placeable WMF header (MS-WMF 2.3.2.1).
func wmfPlaceableHeader() []byte {
buf := make([]byte, 0, 22)
buf = binary.LittleEndian.AppendUint32(buf, 0x9AC6CDD7) // key
buf = binary.LittleEndian.AppendUint16(buf, 0) // hmf
for i := 0; i < 4; i++ { // bbox
buf = binary.LittleEndian.AppendUint16(buf, 100)
}
buf = binary.LittleEndian.AppendUint16(buf, 96) // inch
buf = binary.LittleEndian.AppendUint32(buf, 0) // reserved
buf = binary.LittleEndian.AppendUint16(buf, 96) // checksum
return append(buf, []byte("WMF-PAYLOAD")...)
}
@@ -0,0 +1,240 @@
package docparser
import (
"bytes"
"context"
"encoding/csv"
"fmt"
"net/http"
"path/filepath"
"strings"
"academy/internal/types"
)
// simpleFormats lists file extensions that Go can handle without the Python service.
var simpleFormats = map[string]bool{
"md": true, "markdown": true,
"txt": true, "text": true,
"csv": true,
"json": true,
}
var imageFormats = map[string]bool{
"jpg": true, "jpeg": true, "png": true, "gif": true,
"bmp": true, "tiff": true, "webp": true,
}
var audioFormats = map[string]bool{
"mp3": true, "wav": true, "m4a": true, "flac": true, "ogg": true,
}
func init() {
for k := range imageFormats {
simpleFormats[k] = true
}
for k := range audioFormats {
simpleFormats[k] = true
}
}
// IsSimpleFormat returns true if the file type can be handled by the Go SimpleFormatReader.
func IsSimpleFormat(fileType string) bool {
return simpleFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// SimpleFormatReader handles simple file formats and images directly in Go,
// bypassing the Python docreader service.
type SimpleFormatReader struct{}
// Read reads simple format files and returns markdown.
func (b *SimpleFormatReader) Read(_ context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
switch {
case ft == "md" || ft == "markdown":
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
case ft == "txt" || ft == "text":
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
case ft == "csv":
md, err := csvToMarkdown(req.FileContent)
if err != nil {
return nil, fmt.Errorf("csv conversion failed: %w", err)
}
return &types.ReadResult{MarkdownContent: md}, nil
case ft == "json":
md, err := jsonToMarkdown(req.FileContent)
if err != nil {
return nil, fmt.Errorf("json conversion failed: %w", err)
}
return &types.ReadResult{MarkdownContent: md}, nil
case imageFormats[ft]:
return imageToResult(req.FileName, req.FileContent), nil
case audioFormats[ft]:
return audioToResult(req.FileName, req.FileContent), nil
default:
return nil, fmt.Errorf("unsupported simple format: %s", ft)
}
}
// imageToResult wraps a standalone image as a markdown image reference with
// the raw bytes in ImageRefs, matching Python ImageParser behaviour.
func imageToResult(fileName string, data []byte) *types.ReadResult {
if fileName == "" {
fileName = "image.png"
}
refPath := "images/" + fileName
// Encode spaces so the markdown URL is valid and matches the regex in ResolveAndStore.
safeRef := strings.ReplaceAll(refPath, " ", "%20")
mime := http.DetectContentType(data)
return &types.ReadResult{
MarkdownContent: fmt.Sprintf("![%s](%s)", fileName, safeRef),
ImageRefs: []types.ImageRef{
{
Filename: fileName,
OriginalRef: safeRef,
MimeType: mime,
ImageData: data,
IsOriginal: true,
},
},
}
}
// IsImageFormat returns true if the file type is a recognized image format.
func IsImageFormat(fileType string) bool {
return imageFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// IsAudioFormat returns true if the file type is a recognized audio format.
func IsAudioFormat(fileType string) bool {
return audioFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// audioToResult wraps a standalone audio file. The actual transcription is
// handled by the ASR model in the knowledge service pipeline. Here we just
// return a placeholder markdown with the raw bytes preserved for upstream
// processing.
func audioToResult(fileName string, data []byte) *types.ReadResult {
if fileName == "" {
fileName = "audio.mp3"
}
// Return a placeholder; the knowledge service will replace this with
// the ASR transcription result.
return &types.ReadResult{
MarkdownContent: fmt.Sprintf("[Audio file: %s]", fileName),
IsAudio: true,
AudioData: data,
}
}
// ensureOriginalImageRef checks whether the input file is an image and, if the
// returned markdown does not already contain a markdown image reference for it,
// prepends one and appends the raw bytes to imageRefs. This guarantees that
// when MinerU OCRs a standalone image, the downstream chunks still carry the
// original image link for retrieval display.
func ensureOriginalImageRef(req *types.ReadRequest, mdContent string, imageRefs []types.ImageRef) (string, []types.ImageRef) {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
if !imageFormats[ft] {
return mdContent, imageRefs
}
if len(req.FileContent) == 0 {
return mdContent, imageRefs
}
fileName := req.FileName
if fileName == "" {
fileName = "image." + ft
}
refPath := "images/" + fileName
if strings.Contains(mdContent, refPath) {
return mdContent, imageRefs
}
imgLine := fmt.Sprintf("![%s](%s)", fileName, refPath)
if strings.TrimSpace(mdContent) == "" {
mdContent = imgLine
} else {
mdContent = imgLine + "\n\n" + mdContent
}
mime := http.DetectContentType(req.FileContent)
imageRefs = append(imageRefs, types.ImageRef{
Filename: fileName,
OriginalRef: refPath,
MimeType: mime,
ImageData: req.FileContent,
IsOriginal: true,
})
return mdContent, imageRefs
}
func csvToMarkdown(data []byte) (string, error) {
// Excel's "CSV UTF-8" export starts the file with a byte order mark.
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
reader := csv.NewReader(bytes.NewReader(data))
reader.LazyQuotes = true
reader.TrimLeadingSpace = true
// Rows may differ in length. The default, the first row's length, made
// one short or long row fail the whole file.
reader.FieldsPerRecord = -1
records, err := reader.ReadAll()
if err != nil {
return "", err
}
if len(records) == 0 {
return "", nil
}
// The table is as wide as the widest row, so no field is dropped, and
// shorter rows are padded with empty cells.
width := 0
for _, record := range records {
width = max(width, len(record))
}
var sb strings.Builder
writeRow := func(record []string) {
cells := make([]string, width)
for i, cell := range record {
cells[i] = csvCellReplacer.Replace(cell)
}
sb.WriteString("| ")
sb.WriteString(strings.Join(cells, " | "))
sb.WriteString(" |\n")
}
// Header row
writeRow(records[0])
// Separator
sb.WriteString("|")
for range width {
sb.WriteString(" --- |")
}
sb.WriteString("\n")
// Data rows
for _, row := range records[1:] {
writeRow(row)
}
return sb.String(), nil
}
// csvCellReplacer escapes what would end a GFM table cell or row: a pipe, and
// the line breaks of a quoted multi-line field. They become <br />, as the
// html-to-markdown table plugin writes them.
// Escape existing backslashes too, so a literal backslash before a pipe does
// not consume the pipe's escape and turn it back into a column separator.
var csvCellReplacer = strings.NewReplacer(`\`, `\\`, "|", `\|`, "\r\n", "<br />", "\n", "<br />", "\r", "<br />")
@@ -0,0 +1,162 @@
package docparser
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPaddleOCRVLCloudTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", paddleOCRVLCloudTimeout},
{"whitespace", " ", paddleOCRVLCloudTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 5400s ", 90 * time.Minute},
{"invalid", "invalid", paddleOCRVLCloudTimeout},
{"unitless", "5400", paddleOCRVLCloudTimeout},
{"zero", "0s", paddleOCRVLCloudTimeout},
{"negative", "-1s", paddleOCRVLCloudTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", tt.value)
assert.Equal(t, tt.want, NewPaddleOCRVLCloudReader(nil).timeout)
})
}
}
// The configured timeout, not the old hardcoded 600s, must end a job that the
// cloud keeps reporting as running.
func TestPaddleOCRVLCloudPollStopsAtConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
t.Setenv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", "200ms")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"code":0,"data":{"state":"running"}}`)
}))
defer server.Close()
reader := NewPaddleOCRVLCloudReader(nil)
reader.baseURL = server.URL
reader.pollInterval = 10 * time.Millisecond
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Watchdog: without the configured budget this loop keeps polling for the
// old hardcoded 600s, which must fail the test instead of hanging it.
done := make(chan error, 1)
start := time.Now()
go func() {
_, pollErr := reader.pollJob(ctx, "job-1")
done <- pollErr
}()
select {
case err := <-done:
require.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("timed out after %s", 200*time.Millisecond))
assert.Less(t, time.Since(start), 5*time.Second)
case <-time.After(5 * time.Second):
t.Fatalf("poll loop ignored ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT")
}
}
func TestAcademyCloudPollTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", defaultAcademyCloudPollTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 3600s ", time.Hour},
{"invalid", "invalid", defaultAcademyCloudPollTimeout},
{"zero", "0s", defaultAcademyCloudPollTimeout},
{"negative", "-1s", defaultAcademyCloudPollTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_ACADEMYCLOUD_TIMEOUT", tt.value)
reader, err := NewAcademyCloudSignedDocumentReader("app-id", "api-key")
require.NoError(t, err)
assert.Equal(t, tt.want, reader.pollTimeout)
})
}
}
// academyCloudPollTransport answers every poll with "still running" so the
// configured poll budget is the only thing that can end the loop.
type academyCloudPollTransport struct {
polls atomic.Int64
}
func (t *academyCloudPollTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.polls.Add(1)
body := `{"task_id":"task-1","status":"processing","progress":0.1}`
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}
// The configured budget, not the old hardcoded 20m, must end the poll loop
// whether or not the caller has a deadline of its own. Ingestion always calls
// with a (much longer) DocReader deadline, so that case must not bypass it.
func TestAcademyCloudPollStopsAtConfiguredTimeout(t *testing.T) {
for _, tt := range []struct {
name string
parentCtx func() (context.Context, context.CancelFunc)
}{
{"no parent deadline", func() (context.Context, context.CancelFunc) {
return context.WithCancel(context.Background())
}},
{"longer parent deadline", func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Minute)
}},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_ACADEMYCLOUD_TIMEOUT", "300ms")
reader, err := NewAcademyCloudSignedDocumentReader("app-id", "api-key")
require.NoError(t, err)
transport := &academyCloudPollTransport{}
reader.client = &http.Client{Transport: transport}
reader.initialPollInterval = 5 * time.Millisecond
reader.maxPollInterval = 10 * time.Millisecond
ctx, cancel := tt.parentCtx()
defer cancel()
done := make(chan error, 1)
start := time.Now()
go func() {
_, pollErr := reader.pollTaskResult(ctx, "task-1")
done <- pollErr
}()
select {
case pollErr := <-done:
require.Error(t, pollErr)
assert.True(t, errors.Is(pollErr, context.DeadlineExceeded), "err = %v", pollErr)
assert.Less(t, time.Since(start), 5*time.Second)
assert.Greater(t, transport.polls.Load(), int64(1),
"the job must actually be polled before the budget ends it")
case <-time.After(5 * time.Second):
t.Fatalf("poll loop ignored ACADEMY_ACADEMYCLOUD_TIMEOUT after %d polls", transport.polls.Load())
}
})
}
}
@@ -0,0 +1,69 @@
package docparser
import "testing"
func TestCSVToMarkdown(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{
name: "rectangular",
in: "name,qty\npen,2\n",
want: "| name | qty |\n| --- | --- |\n| pen | 2 |\n",
},
{
// A short row failed the whole file with "wrong number of fields".
name: "short row is padded",
in: "name,qty,note\npen,2\nink,1,blue\n",
want: "| name | qty | note |\n| --- | --- | --- |\n| pen | 2 | |\n| ink | 1 | blue |\n",
},
{
name: "long row widens the table",
in: "name,qty\npen,2,spare\n",
want: "| name | qty | |\n| --- | --- | --- |\n| pen | 2 | spare |\n",
},
{
name: "pipe in a cell is escaped",
in: "expr,means\n\"a|b\",a or b\n",
want: "| expr | means |\n| --- | --- |\n| a\\|b | a or b |\n",
},
{
name: "backslash before pipe preserves both literal characters",
in: "expr,note\na\\|b,literal\n",
want: "| expr | note |\n| --- | --- |\n| " + `a\\\|b` + " | literal |\n",
},
{
name: "multiple and trailing backslashes stay inside the cell",
in: "expr,note\na\\\\|b\\,literal\n",
want: "| expr | note |\n| --- | --- |\n| " + `a\\\\\|b\\` + " | literal |\n",
},
{
name: "multi-line field stays in its row",
in: "name,address\nAnn,\"1 Main St\r\nSpringfield\"\n",
want: "| name | address |\n| --- | --- |\n| Ann | 1 Main St<br />Springfield |\n",
},
{
name: "byte order mark is not part of the first header",
in: "\xef\xbb\xbfname,qty\npen,2\n",
want: "| name | qty |\n| --- | --- |\n| pen | 2 |\n",
},
{
name: "empty file",
in: "",
want: "",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := csvToMarkdown([]byte(tc.in))
if err != nil {
t.Fatalf("csvToMarkdown(%q) error: %v", tc.in, err)
}
if got != tc.want {
t.Errorf("csvToMarkdown(%q)\n got: %q\nwant: %q", tc.in, got, tc.want)
}
})
}
}
+21
View File
@@ -0,0 +1,21 @@
// Package docparser turns uploaded files and URLs into Markdown plus the
// images they contain, which is the input the chunking and multimodal stages
// downstream expect.
//
// A parse request names a parser engine, and every engine is one entry in the
// registry:
//
// - engines.go declares the catalog — each engine's name, description,
// supported file types, availability probe, and the reader that does the
// work.
// - engine_registry.go turns an engine name into a reader (NewReader) and
// merges the local catalog with the engines the Python docreader reports
// over its ListEngines RPC (ListAllEngines).
//
// Readers differ in where the parsing happens: in this process
// (SimpleFormatReader, AnydocReader), in the docreader service over gRPC or
// HTTP (GRPCDocumentReader, HTTPDocumentReader), or in a remote API (MinerU,
// PaddleOCR-VL, Academy Cloud). They all return types.ReadResult, so the rest
// of the package — image resolution and storage, table normalization — is
// shared regardless of which engine ran.
package docparser
@@ -0,0 +1,151 @@
package docparser
import (
"context"
"fmt"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// EngineRegistration is what every locally registered parser engine provides:
// the metadata the engine list shows, and the reader that does the parsing.
// Remote-only engines (e.g. markitdown) live in the Python docreader, are
// discovered through its ListEngines RPC, and never register here — the
// registry routes them to the docreader client by default.
type EngineRegistration interface {
Name() string
Description() string
FileTypes(docreaderConnected bool) []string
CheckAvailable(docreaderConnected bool, overrides map[string]string) (available bool, reason string)
// NewReader builds the reader for one parse request. Returning an error
// means this engine cannot serve the request (missing credentials,
// unreachable service); the caller reports it rather than silently
// parsing with something else.
NewReader(ctx context.Context, deps ReaderDeps) (interfaces.DocReader, error)
}
// ReaderDeps carries everything an engine may need to build its reader but
// cannot construct itself: tenant configuration, tenant credentials, and the
// shared docreader connection.
type ReaderDeps struct {
// Overrides holds tenant-level engine configuration (service endpoints,
// API keys), as produced by ParserEngineConfig.ToOverridesMap.
Overrides map[string]string
// Remote is the docreader client. Nil when the service is not connected.
Remote interfaces.DocReader
// AcademyCloudCredentials resolves the tenant's Academy Cloud
// credentials. It is a function rather than a value because resolving
// them can hit the database, which most engines never need. Nil, or a
// nil return, means the tenant has not configured them.
AcademyCloudCredentials func(ctx context.Context) *types.AcademyCloudCredentials
}
// localEngines holds all locally registered parser engines, in registration
// order — which is also the order the engine list is shown in.
var localEngines []EngineRegistration
// RegisterEngine adds an engine to the local registry. Called from init().
func RegisterEngine(e EngineRegistration) {
localEngines = append(localEngines, e)
}
// lookupEngine returns the locally registered engine with this name.
func lookupEngine(name string) (EngineRegistration, bool) {
for _, engine := range localEngines {
if engine.Name() == name {
return engine, true
}
}
return nil, false
}
// NewReader builds the reader for an engine.
//
// An empty engine name means "no explicit choice": simple formats are handled
// in Go and everything else goes to the docreader service. An unknown name is
// routed to the docreader too, so engines that only exist in the Python
// service keep working without a Go-side registration.
func NewReader(
ctx context.Context, engine, fileType string, isURL bool, deps ReaderDeps,
) (interfaces.DocReader, error) {
if registration, ok := lookupEngine(engine); ok {
return registration.NewReader(ctx, deps)
}
if engine == "" && !isURL && IsSimpleFormat(fileType) {
return &SimpleFormatReader{}, nil
}
return remoteReader(deps)
}
// remoteReader returns the docreader client, or an error when the service is
// not connected — a nil interface value here would panic at the call site.
func remoteReader(deps ReaderDeps) (interfaces.DocReader, error) {
if deps.Remote == nil {
return nil, errNotConnected
}
return deps.Remote, nil
}
// ListAllEngines returns the merged engine list: locally registered engines
// plus engines discovered from the remote docreader via ListEngines RPC.
//
// Merge rules:
// - Local engines are always included, with Go-side availability checks.
// - For a remote engine whose name matches a local one, the remote's
// file_types and description take precedence (the remote service is
// authoritative for its own capabilities).
// - Remote engines not present locally are appended as-is, enabling
// auto-discovery of newly added docreader engines without Go changes.
func ListAllEngines(
docreaderConnected bool, overrides map[string]string, remoteEngines []types.ParserEngineInfo,
) []types.ParserEngineInfo {
remoteMap := make(map[string]types.ParserEngineInfo, len(remoteEngines))
for _, re := range remoteEngines {
remoteMap[re.Name] = re
}
seen := make(map[string]bool, len(localEngines))
result := make([]types.ParserEngineInfo, 0, len(localEngines)+len(remoteEngines))
for _, e := range localEngines {
name := e.Name()
seen[name] = true
fileTypes := e.FileTypes(docreaderConnected)
description := e.Description()
if re, ok := remoteMap[name]; ok {
if len(re.FileTypes) > 0 {
fileTypes = re.FileTypes
}
if re.Description != "" {
description = re.Description
}
}
available, reason := e.CheckAvailable(docreaderConnected, overrides)
result = append(result, types.ParserEngineInfo{
Name: name,
Description: description,
FileTypes: fileTypes,
Available: available,
UnavailableReason: reason,
})
}
for _, re := range remoteEngines {
if seen[re.Name] {
continue
}
result = append(result, re)
}
return result
}
// errEngineUnavailable reports an engine that is registered but cannot run for
// this tenant or this build.
func errEngineUnavailable(engine, reason string) error {
return fmt.Errorf("parser engine %q is unavailable: %s", engine, reason)
}
@@ -0,0 +1,112 @@
package docparser
import (
"context"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubRemote stands in for the docreader client. NewReader only ever hands it
// back, so the embedded interface is never called — and would panic if routing
// ever sent a parse here by mistake.
type stubRemote struct{ interfaces.DocReader }
func TestNewReaderRoutesByEngine(t *testing.T) {
ctx := context.Background()
remote := &stubRemote{}
deps := ReaderDeps{Remote: remote}
cases := []struct {
name string
engine string
fileType string
isURL bool
want any
}{
{name: "simple engine", engine: SimpleEngineName, fileType: "md", want: &SimpleFormatReader{}},
{name: "builtin engine goes remote", engine: BuiltinEngineName, fileType: "md", want: remote},
{name: "unset engine handles simple formats in Go", fileType: "csv", want: &SimpleFormatReader{}},
{name: "unset engine sends complex formats to docreader", fileType: "docx", want: remote},
{name: "default pptx engine is remote markitdown", engine: "markitdown", fileType: "pptx", want: remote},
{name: "URLs always go to docreader", fileType: "md", isURL: true, want: remote},
{name: "docreader-only engines fall through", engine: "markitdown", fileType: "docx", want: remote},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
reader, err := NewReader(ctx, tc.engine, tc.fileType, tc.isURL, deps)
if err != nil {
t.Fatalf("NewReader: %v", err)
}
if _, isSimple := tc.want.(*SimpleFormatReader); isSimple {
if _, ok := reader.(*SimpleFormatReader); !ok {
t.Fatalf("reader = %T, want *SimpleFormatReader", reader)
}
return
}
if reader != tc.want {
t.Fatalf("reader = %T, want the docreader client", reader)
}
})
}
}
// A disconnected docreader has to surface as an error, not as a nil reader the
// caller would dereference.
func TestNewReaderReportsDisconnectedDocReader(t *testing.T) {
if _, err := NewReader(context.Background(), BuiltinEngineName, "docx", false, ReaderDeps{}); err == nil {
t.Fatal("NewReader succeeded without a docreader connection, want an error")
}
}
func TestNewReaderRequiresAcademyCloudCredentials(t *testing.T) {
_, err := NewReader(context.Background(), AcademyCloudEngineName, "docx", false, ReaderDeps{
AcademyCloudCredentials: func(context.Context) *types.AcademyCloudCredentials { return nil },
})
if err == nil {
t.Fatal("NewReader succeeded without credentials, want an error")
}
}
// The anydoc engine is only linked into builds tagged `anydoc`; everywhere
// else it must be listed as unavailable and refuse to build a reader, so a
// knowledge base configured for it fails loudly instead of parsing with
// something else.
func TestAnydocEngineFollowsBuildAvailability(t *testing.T) {
reader, err := NewReader(context.Background(), AnydocEngineName, "docx", false, ReaderDeps{})
if anydoc.Available() {
if err != nil {
t.Fatalf("NewReader: %v", err)
}
if _, ok := reader.(*AnydocReader); !ok {
t.Fatalf("reader = %T, want *AnydocReader", reader)
}
return
}
if err == nil {
t.Fatal("NewReader succeeded without the converter linked in, want an error")
}
}
func TestListAllEnginesIncludesAnydoc(t *testing.T) {
for _, engine := range ListAllEngines(true, nil, nil) {
if engine.Name != AnydocEngineName {
continue
}
if engine.Available != anydoc.Available() {
t.Errorf("anydoc availability = %v, want %v", engine.Available, anydoc.Available())
}
if !engine.Available && engine.UnavailableReason == "" {
t.Error("anydoc is unavailable without a reason to show")
}
if len(engine.FileTypes) == 0 {
t.Error("anydoc lists no file types")
}
return
}
t.Fatal("anydoc engine not found in the engine list")
}
@@ -0,0 +1,91 @@
package docparser
import (
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/utils"
)
// Locally advertised parser formats must pass the shared import gate used by
// direct uploads, URL imports, workers and datasource connectors (#4598).
// Check metadata even when a converter is not linked into this test build.
func TestLocalParserFormatsPassImportValidation(t *testing.T) {
for _, engine := range ListAllEngines(true, nil, nil) {
t.Run(engine.Name, func(t *testing.T) {
for _, ext := range engine.FileTypes {
if !utils.IsSupportedImportExtension(ext) {
t.Errorf("engine advertises %q but the shared import gate rejects it", ext)
}
}
})
}
}
func TestListAllEnginesBuiltinIncludesDocumentFormats(t *testing.T) {
engines := ListAllEngines(true, nil, nil)
for _, engine := range engines {
if engine.Name != "builtin" {
continue
}
if !engine.Available {
t.Fatalf("builtin engine is unavailable: %s", engine.UnavailableReason)
}
fileTypes := make(map[string]bool, len(engine.FileTypes))
for _, fileType := range engine.FileTypes {
fileTypes[fileType] = true
}
for _, want := range []string{"html", "htm", "xmind", "ppt", "pptx"} {
if !fileTypes[want] {
t.Errorf("builtin engine file types do not include %q: %v", want, engine.FileTypes)
}
}
return
}
t.Fatal("builtin engine not found")
}
func TestDefaultParserEnginePrefersAnydocWhenLinked(t *testing.T) {
cases := []string{"pptx", "ppt", "docx"}
if anydoc.Available() {
for _, ft := range cases {
if got := types.DefaultParserEngine(ft); got != AnydocEngineName {
t.Errorf("DefaultParserEngine(%s) = %q, want anydoc when the binding is linked", ft, got)
}
}
if got := types.DefaultParserEngine("csv"); got != "" {
t.Errorf("DefaultParserEngine(csv) = %q, want empty so the Go simple reader stays default", got)
}
// anydoc claims pdf but cannot model one, so linking the binding must
// not move PDFs off builtin. This branch is where that is observable.
for _, ft := range []string{"pdf", ".PDF"} {
if got := types.DefaultParserEngine(ft); got != "" {
t.Errorf("DefaultParserEngine(%q) = %q, want empty so PDFs stay on builtin", ft, got)
}
}
return
}
if got := types.DefaultParserEngine("pptx"); got != "markitdown" {
t.Fatalf("DefaultParserEngine(pptx) = %q, want markitdown when anydoc is unavailable", got)
}
if got := types.DefaultParserEngine("docx"); got != "" {
t.Fatalf("DefaultParserEngine(docx) = %q, want empty when anydoc is unavailable", got)
}
}
// The PDF exclusion only matters because anydoc still claims the type. If a
// future anydoc drops pdf, the exclusion becomes dead code and should go with
// it — this guard runs in every build, tagged or not.
func TestPreferAnydocSkipsPDF(t *testing.T) {
if !anydoc.Supports("pdf", "") {
t.Fatal("anydoc no longer claims pdf; drop the explicit exclusion in preferAnydocWhenAvailable")
}
for _, ft := range []string{"pdf", ".PDF", " Pdf "} {
if got := preferAnydocWhenAvailable(ft); got != "" {
t.Errorf("preferAnydocWhenAvailable(%q) = %q, want empty so PDFs stay on builtin", ft, got)
}
}
}
@@ -0,0 +1,296 @@
package docparser
import (
"context"
"strings"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// Engine names, as stored in knowledge base parser rules and shown in the UI.
const (
// BuiltinEngineName is the DocReader (Python) parser suite.
BuiltinEngineName = "builtin"
// SimpleEngineName is Go-native handling of text formats and images.
SimpleEngineName = "simple"
// AnydocEngineName is the in-process anydoc office-document converter.
AnydocEngineName = "anydoc"
// AcademyCloudEngineName is the hosted Academy Cloud document reader.
AcademyCloudEngineName = "academycloud"
// MinerUEngineName is a self-hosted MinerU service.
MinerUEngineName = "mineru"
// MinerUCloudEngineName is the MinerU Cloud API.
MinerUCloudEngineName = "mineru_cloud"
// PaddleOCRVLEngineName is a self-hosted PaddleOCR-VL pipeline.
PaddleOCRVLEngineName = "paddleocr_vl"
// PaddleOCRVLCloudEngineName is the PaddleOCR-VL AI Studio cloud API.
PaddleOCRVLCloudEngineName = "paddleocr_vl_cloud"
)
func init() {
types.SetPreferParserEngine(preferAnydocWhenAvailable)
RegisterEngine(&builtinEngine{})
RegisterEngine(&simpleEngine{})
RegisterEngine(&anydocEngine{})
RegisterEngine(&academyCloudEngine{})
RegisterEngine(&mineruEngine{})
RegisterEngine(&mineruCloudEngine{})
RegisterEngine(&paddleOCRVLEngine{})
RegisterEngine(&paddleOCRVLCloudEngine{})
}
// preferAnydocWhenAvailable is the type-level default override: when the
// anydoc binding is linked and converts this file type, use it instead of
// builtin or the markitdown fallback. Simple formats stay on the Go reader.
//
// PDF is excluded. anydoc has no document model for it, so Convert force-
// disables asset extraction, and AnydocReader only falls back to builtin
// when the whole file yields no text at all. A born-digital PDF that yields
// a few characters is therefore reported as parsed while its figures,
// tables and layout are gone. The builtin parser classifies pages
// individually and routes scanned ones through OCR/VLM, so it is the better
// default for the one type anydoc cannot model.
func preferAnydocWhenAvailable(fileType string) string {
ft := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(fileType), "."))
if IsSimpleFormat(ft) || ft == "pdf" {
return ""
}
if anydoc.Available() && anydoc.Supports(ft, "") {
return AnydocEngineName
}
return ""
}
// ---------------------------------------------------------------------------
// builtin — DocReader-backed parser for complex document formats.
// ---------------------------------------------------------------------------
type builtinEngine struct{}
func (e *builtinEngine) Name() string { return BuiltinEngineName }
func (e *builtinEngine) Description() string { return "DocReader built-in parser engine" }
func (e *builtinEngine) FileTypes(_ bool) []string {
return []string{
"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls",
"pptx", "ppt", "epub",
"html", "htm", "mhtml", "xmind",
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
"mp3", "wav", "m4a", "flac", "ogg",
}
}
func (e *builtinEngine) CheckAvailable(docreaderConnected bool, _ map[string]string) (bool, string) {
if docreaderConnected {
return true, ""
}
return false, "DocReader service not connected"
}
// NewReader returns the docreader client. Selecting "builtin" explicitly means
// the docreader is wanted even for formats the simple reader could handle.
func (e *builtinEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return remoteReader(deps)
}
// ---------------------------------------------------------------------------
// simple — Go handles md/txt/csv/json natively, no external service needed.
// Distinct from docreader's "builtin", which uses Python libraries for complex
// formats (docx, pdf, ...).
// ---------------------------------------------------------------------------
type simpleEngine struct{}
func (e *simpleEngine) Name() string { return SimpleEngineName }
func (e *simpleEngine) Description() string {
return "Simple format & image parsing (no external service required)"
}
func (e *simpleEngine) FileTypes(_ bool) []string {
return []string{
"md", "markdown", "txt", "csv", "json",
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
"mp3", "wav", "m4a", "flac", "ogg",
}
}
func (e *simpleEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
return true, ""
}
func (e *simpleEngine) NewReader(_ context.Context, _ ReaderDeps) (interfaces.DocReader, error) {
return &SimpleFormatReader{}, nil
}
// ---------------------------------------------------------------------------
// anydoc — office documents converted in this process, no external service.
// Only present in builds that link the converter (see the anydoc package).
// ---------------------------------------------------------------------------
type anydocEngine struct{}
func (e *anydocEngine) Name() string { return AnydocEngineName }
func (e *anydocEngine) Description() string {
return "anydoc in-process office document converter (no external service required)"
}
func (e *anydocEngine) FileTypes(_ bool) []string { return anydoc.SupportedFileTypes() }
func (e *anydocEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
if anydoc.Available() {
return true, ""
}
return false, anydoc.UnavailableReason()
}
func (e *anydocEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
if !anydoc.Available() {
return nil, errEngineUnavailable(AnydocEngineName, anydoc.UnavailableReason())
}
return NewAnydocReader(deps.Overrides, deps.Remote), nil
}
// ---------------------------------------------------------------------------
// academycloud — Tenant-scoped AcademyCloud docreader with signed requests.
// ---------------------------------------------------------------------------
type academyCloudEngine struct{}
func (e *academyCloudEngine) Name() string { return AcademyCloudEngineName }
func (e *academyCloudEngine) Description() string { return "AcademyCloud document reader" }
func (e *academyCloudEngine) FileTypes(_ bool) []string {
return []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "pptx", "ppt"}
}
func (e *academyCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
if overrides["academycloud_app_id"] != "" {
return true, ""
}
return false, "Academy Cloud credentials not configured. Go to Settings → Academy Cloud to set up."
}
func (e *academyCloudEngine) NewReader(
ctx context.Context, deps ReaderDeps,
) (interfaces.DocReader, error) {
if deps.AcademyCloudCredentials == nil {
return nil, errEngineUnavailable(AcademyCloudEngineName, "no credential resolver configured")
}
creds := deps.AcademyCloudCredentials(ctx)
if creds == nil {
return nil, errEngineUnavailable(AcademyCloudEngineName, "tenant credentials not configured")
}
return NewAcademyCloudSignedDocumentReader(creds.AppID, creds.AppSecret)
}
// ---------------------------------------------------------------------------
// mineru — Go-native, calls self-hosted MinerU API directly
// ---------------------------------------------------------------------------
type mineruEngine struct{}
func (e *mineruEngine) Name() string { return MinerUEngineName }
func (e *mineruEngine) Description() string { return "MinerU self-hosted service" }
func (e *mineruEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
}
func (e *mineruEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
endpoint := strings.TrimSpace(overrides["mineru_endpoint"])
if endpoint == "" {
return false, "MinerU service not configured"
}
return PingMinerU(endpoint, overrides["mineru_server_api_key"])
}
func (e *mineruEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewMinerUReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// mineru_cloud — Go-native, calls MinerU Cloud API directly
// ---------------------------------------------------------------------------
type mineruCloudEngine struct{}
func (e *mineruCloudEngine) Name() string { return MinerUCloudEngineName }
func (e *mineruCloudEngine) Description() string { return "MinerU Cloud API" }
func (e *mineruCloudEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
}
func (e *mineruCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
apiKey := strings.TrimSpace(overrides["mineru_api_key"])
if apiKey == "" {
return false, "MinerU API Key not configured"
}
return PingMinerUCloud(apiKey)
}
func (e *mineruCloudEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewMinerUCloudReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// paddleocr_vl — Go-native, calls a self-hosted PaddleOCR-VL pipeline service
// ---------------------------------------------------------------------------
type paddleOCRVLEngine struct{}
func (e *paddleOCRVLEngine) Name() string { return PaddleOCRVLEngineName }
func (e *paddleOCRVLEngine) Description() string { return "PaddleOCR-VL self-hosted service" }
func (e *paddleOCRVLEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff"}
}
func (e *paddleOCRVLEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
endpoint := strings.TrimSpace(overrides["paddleocr_vl_endpoint"])
if endpoint == "" {
return false, "PaddleOCR-VL service not configured"
}
return PingPaddleOCRVL(endpoint)
}
func (e *paddleOCRVLEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewPaddleOCRVLReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// paddleocr_vl_cloud — Go-native, calls the PaddleOCR-VL AI Studio cloud API
// ---------------------------------------------------------------------------
type paddleOCRVLCloudEngine struct{}
func (e *paddleOCRVLCloudEngine) Name() string { return PaddleOCRVLCloudEngineName }
func (e *paddleOCRVLCloudEngine) Description() string { return "PaddleOCR-VL Cloud API" }
func (e *paddleOCRVLCloudEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff"}
}
func (e *paddleOCRVLCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
token := strings.TrimSpace(overrides["paddleocr_vl_cloud_token"])
if token == "" {
return false, "PaddleOCR-VL Cloud Token not configured"
}
return PingPaddleOCRVLCloud(token)
}
func (e *paddleOCRVLCloudEngine) NewReader(
_ context.Context, deps ReaderDeps,
) (interfaces.DocReader, error) {
return NewPaddleOCRVLCloudReader(deps.Overrides), nil
}
@@ -0,0 +1,275 @@
package docparser
import (
"context"
"fmt"
"io"
"os"
"strconv"
"sync"
"time"
docclient "academy/docreader/client"
"academy/docreader/proto"
"academy/internal/logger"
"academy/internal/types"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func getMaxMessageSize() int {
if sizeStr := os.Getenv("MAX_FILE_SIZE_MB"); sizeStr != "" {
if size, err := strconv.Atoi(sizeStr); err == nil && size > 0 {
return size * 1024 * 1024
}
}
return 50 * 1024 * 1024
}
// GRPCDocumentReader implements DocumentReader over gRPC.
type GRPCDocumentReader struct {
mu sync.RWMutex
conn *grpc.ClientConn
client proto.DocReaderClient
addr string
}
func NewGRPCDocumentReader(addr string) (*GRPCDocumentReader, error) {
p := &GRPCDocumentReader{}
if addr != "" {
if err := p.connect(addr); err != nil {
return nil, err
}
}
return p, nil
}
func (p *GRPCDocumentReader) connect(addr string) error {
authConfig := docclient.LoadAuthConfigFromEnv()
opts, err := authConfig.BuildDialOptions(getMaxMessageSize())
if err != nil {
return fmt.Errorf("failed to build docreader dial options: %w", err)
}
if authConfig.TLSEnabled {
logger.Infof(context.Background(), "TLS enabled for docreader gRPC client")
}
if authConfig.AuthToken != "" {
logger.Infof(context.Background(),
"Token authentication enabled for docreader gRPC client (TLS=%v)",
authConfig.TLSEnabled,
)
}
start := time.Now()
conn, err := grpc.Dial("dns:///"+addr, opts...)
if err != nil {
return fmt.Errorf("failed to connect to docreader: %w", err)
}
logger.Infof(context.Background(), "Connected to docreader in %v", time.Since(start))
p.conn = conn
p.client = proto.NewDocReaderClient(conn)
p.addr = addr
return nil
}
func (p *GRPCDocumentReader) Reconnect(addr string) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn != nil {
_ = p.conn.Close()
p.conn = nil
p.client = nil
p.addr = ""
}
return p.connect(addr)
}
func (p *GRPCDocumentReader) IsConnected() bool {
p.mu.RLock()
defer p.mu.RUnlock()
return p.conn != nil
}
func (p *GRPCDocumentReader) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn != nil {
return p.conn.Close()
}
return nil
}
var errNotConnected = status.Error(codes.Unavailable, "docreader service not connected")
func (p *GRPCDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, errNotConnected
}
protoReq := &proto.ReadRequest{
FileContent: req.FileContent,
FileName: req.FileName,
FileType: req.FileType,
Url: req.URL,
Title: req.Title,
RequestId: req.RequestID,
Config: &proto.ReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
// Use the streaming RPC so documents with many page images (large scanned
// PDFs) are not capped by the unary message-size limit. The meta frame
// arrives first, followed by one frame per image.
result, err := p.readStream(ctx, client, protoReq)
if err != nil {
// An older docreader build may not implement ReadStream. Fall back to
// the unary Read RPC so a version-skewed deployment still parses
// documents (small/medium docs only — the unary path remains capped by
// the gRPC message-size limit, which is exactly what streaming avoids).
if status.Code(err) == codes.Unimplemented {
logger.Warnf(ctx, "docreader ReadStream unimplemented, falling back to unary Read: %v", err)
return p.readUnary(ctx, client, protoReq)
}
return nil, err
}
return result, nil
}
// readStream consumes the server-streaming ReadStream RPC: one meta frame
// followed by one frame per image. Errors are returned verbatim so the caller
// can inspect the gRPC status code (e.g. Unimplemented) for fallback.
func (p *GRPCDocumentReader) readStream(
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
) (*types.ReadResult, error) {
stream, err := client.ReadStream(ctx, protoReq)
if err != nil {
return nil, fmt.Errorf("gRPC ReadStream failed: %w", err)
}
result := &types.ReadResult{}
gotMeta := false
for {
frame, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
return nil, fmt.Errorf("gRPC ReadStream recv failed: %w", recvErr)
}
if meta := frame.GetMeta(); meta != nil {
gotMeta = true
result.MarkdownContent = meta.GetMarkdownContent()
result.ImageDirPath = meta.GetImageDirPath()
result.Metadata = meta.GetMetadata()
result.Error = meta.GetError()
result.SourceBlocks = sourceBlocksFromProto(meta.GetSourceBlocks())
if n := meta.GetImageCount(); n > 0 {
result.ImageRefs = make([]types.ImageRef, 0, n)
}
continue
}
if img := frame.GetImage(); img != nil {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: img.GetFilename(),
OriginalRef: img.GetOriginalRef(),
MimeType: img.GetMimeType(),
StorageKey: img.GetStorageKey(),
ImageData: img.GetImageData(),
})
}
}
if !gotMeta {
return nil, fmt.Errorf("gRPC ReadStream returned no metadata frame")
}
return result, nil
}
// readUnary calls the legacy unary Read RPC. Used only as a compatibility
// fallback when the connected docreader does not implement ReadStream.
func (p *GRPCDocumentReader) readUnary(
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
) (*types.ReadResult, error) {
resp, err := client.Read(ctx, protoReq)
if err != nil {
return nil, fmt.Errorf("gRPC Read failed: %w", err)
}
result := &types.ReadResult{
MarkdownContent: resp.GetMarkdownContent(),
ImageDirPath: resp.GetImageDirPath(),
Metadata: resp.GetMetadata(),
Error: resp.GetError(),
SourceBlocks: sourceBlocksFromProto(resp.GetSourceBlocks()),
}
if refs := resp.GetImageRefs(); len(refs) > 0 {
result.ImageRefs = make([]types.ImageRef, 0, len(refs))
for _, img := range refs {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: img.GetFilename(),
OriginalRef: img.GetOriginalRef(),
MimeType: img.GetMimeType(),
StorageKey: img.GetStorageKey(),
ImageData: img.GetImageData(),
})
}
}
return result, nil
}
func (p *GRPCDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, errNotConnected
}
resp, err := client.ListEngines(ctx, &proto.ListEnginesRequest{ConfigOverrides: overrides})
if err != nil {
return nil, fmt.Errorf("gRPC ListEngines failed: %w", err)
}
result := make([]types.ParserEngineInfo, 0, len(resp.GetEngines()))
for _, e := range resp.GetEngines() {
result = append(result, types.ParserEngineInfo{
Name: e.GetName(),
Description: e.GetDescription(),
FileTypes: e.GetFileTypes(),
Available: e.GetAvailable(),
UnavailableReason: e.GetUnavailableReason(),
})
}
return result, nil
}
// PreprocessImage straightens and crops a photographed page before OCR runs.
// The docreader does the work; a page it declines to improve comes back as
// fallback=true with no bytes, which the caller reads as "use the original".
func (p *GRPCDocumentReader) PreprocessImage(ctx context.Context, image []byte) ([]byte, bool, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, true, errNotConnected
}
resp, err := client.PreprocessImage(ctx, &proto.PreprocessImageRequest{Image: image})
if err != nil {
return nil, true, fmt.Errorf("gRPC PreprocessImage failed: %w", err)
}
if resp.GetFallbackNeeded() || len(resp.GetImage()) == 0 {
return nil, true, nil
}
return resp.GetImage(), false, nil
}
@@ -0,0 +1,22 @@
package docparser
import (
"testing"
"google.golang.org/grpc/resolver"
)
func TestGRPCDocumentReaderDoesNotChangeGlobalResolver(t *testing.T) {
previous := resolver.GetDefaultScheme()
resolver.SetDefaultScheme("passthrough")
t.Cleanup(func() { resolver.SetDefaultScheme(previous) })
reader, err := NewGRPCDocumentReader("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reader.Close() })
if got := resolver.GetDefaultScheme(); got != "passthrough" {
t.Fatalf("DocReader changed global gRPC resolver to %q", got)
}
}
@@ -0,0 +1,130 @@
package docparser
import (
"context"
"fmt"
"os"
"sort"
"strings"
"time"
"academy/internal/logger"
)
// stringOr returns val (trimmed) if non-empty, otherwise fallback.
func stringOr(val, fallback string) string {
val = strings.TrimSpace(val)
if val == "" {
return fallback
}
return val
}
// parseBoolOr parses a truthy string ("true","1","yes"), returning fallback on empty.
func parseBoolOr(val string, fallback bool) bool {
val = strings.ToLower(strings.TrimSpace(val))
if val == "" {
return fallback
}
return val == "true" || val == "1" || val == "yes"
}
// requestTimeoutFromEnv reads a positive Go duration from env, falling back to
// fallback when the variable is unset, invalid or not positive. It bounds a
// self-hosted engine's request; the caller's context may impose an earlier
// deadline.
func requestTimeoutFromEnv(env string, fallback time.Duration) time.Duration {
value := strings.TrimSpace(os.Getenv(env))
if value == "" {
return fallback
}
timeout, err := time.ParseDuration(value)
if err != nil || timeout <= 0 {
logger.Warnf(context.Background(), "Invalid %s %q; using %s", env, value, fallback)
return fallback
}
return timeout
}
// firstNonEmpty returns the first non-empty string, or "" if all are empty.
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
// sleepCtx sleeps for d but returns early if ctx is cancelled.
func sleepCtx(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
case <-t.C:
}
}
// logResponseStructure recursively logs the structure of an API response,
// truncating large string values. label identifies the subsystem (e.g. "MinerU").
func logResponseStructure(label string, obj interface{}, prefix string) {
switch v := obj.(type) {
case map[string]interface{}:
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
logger.Infof(context.Background(), "[%s] %s = {object with %d keys: %s}", label, prefix, len(v), strings.Join(keys, ", "))
for _, key := range keys {
val := v[key]
path := prefix + "." + key
switch inner := val.(type) {
case map[string]interface{}:
logResponseStructure(label, inner, path)
case []interface{}:
logger.Infof(context.Background(), "[%s] %s = [array with %d items]", label, path, len(inner))
if len(inner) > 0 {
logger.Infof(context.Background(), "[%s] %s[0] type=%T", label, path, inner[0])
if len(inner) <= 3 {
for i, item := range inner {
logResponseStructure(label, item, fmt.Sprintf("%s[%d]", path, i))
}
} else {
logResponseStructure(label, inner[0], path+"[0]")
logger.Infof(context.Background(), "[%s] ... and %d more items in %s", label, len(inner)-1, path)
}
}
case string:
if len(inner) > 200 {
logger.Infof(context.Background(), "[%s] %s = string(%d chars): %.200s...", label, path, len(inner), inner)
} else {
logger.Infof(context.Background(), "[%s] %s = %q", label, path, inner)
}
case float64:
logger.Infof(context.Background(), "[%s] %s = %v (number)", label, path, inner)
case bool:
logger.Infof(context.Background(), "[%s] %s = %v (bool)", label, path, inner)
case nil:
logger.Infof(context.Background(), "[%s] %s = null", label, path)
default:
logger.Infof(context.Background(), "[%s] %s = %v (%T)", label, path, val, val)
}
}
case []interface{}:
logger.Infof(context.Background(), "[%s] %s = [array with %d items]", label, prefix, len(v))
if len(v) > 0 {
if len(v) <= 3 {
for i, item := range v {
logResponseStructure(label, item, fmt.Sprintf("%s[%d]", prefix, i))
}
} else {
logResponseStructure(label, v[0], prefix+"[0]")
logger.Infof(context.Background(), "[%s] ... and %d more items in %s", label, len(v)-1, prefix)
}
}
default:
logger.Infof(context.Background(), "[%s] %s = %v (%T)", label, prefix, v, v)
}
}
@@ -0,0 +1,159 @@
package docparser
import (
"regexp"
"strings"
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
)
var (
// htmlTableBlockPattern matches a single (non-nested) <table>...</table>
// block, the form OCR/layout engines such as PaddleOCR-VL emit tables in.
htmlTableBlockPattern = regexp.MustCompile(`(?is)<table\b[^>]*>.*?</table>`)
// fencedCodeBlockPattern matches CommonMark fenced code blocks so HTML
// <table> examples inside them are left untouched.
fencedCodeBlockPattern = regexp.MustCompile("(?s)(?:```|~~~)[^\\n]*\\n.*?(?:```|~~~)")
// htmlLayoutAttrPattern matches presentational HTML attributes that carry
// no semantic value (text-align styles, CSS classes, sizing). Structural
// attributes like rowspan/colspan are intentionally excluded.
htmlLayoutAttrPattern = regexp.MustCompile(
`(?is)\s+(?:style|class|align|valign|width|height|bgcolor)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)`,
)
// htmlSpanAttrPattern detects rowspan/colspan values greater than 1, which
// Markdown tables cannot represent; such tables keep their HTML form
// (attributes stripped) instead. Span values of 1 (and the invalid 0) do
// not merge anything and must stay convertible.
htmlSpanAttrPattern = regexp.MustCompile(`(?i)\b(?:row|col)span\s*=\s*["']?(?:[2-9]|\d{2,})`)
// htmlTableRowPattern matches the opening <tr> tag of each table row, used
// to put every row on its own line so the chunker can split degraded HTML
// tables at "\n" boundaries.
htmlTableRowPattern = regexp.MustCompile(`(?i)<tr\b`)
// markdownTableSeparatorPattern matches the |---| delimiter row that a
// valid GFM table must contain. The repeating column group is optional so
// single-column tables (|---|) are accepted; requiring two or more columns
// discarded successful conversions of MinerU figure/TOC tables.
markdownTableSeparatorPattern = regexp.MustCompile(`(?m)^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$`)
)
// NormalizeHTMLTables rewrites inline HTML <table> blocks embedded in OCR
// markdown output. PaddleOCR-VL emits tables as HTML with per-cell text-align
// styles, which (1) waste tokens on layout markup and (2) are not recognized
// by the chunker's table-protection logic, so large tables get split mid-row.
//
// Each table block is converted to a GFM Markdown table when possible. Tables
// that use rowspan/colspan (which Markdown cannot express), or that the
// converter cannot turn into a valid GFM table (cell <br>, nested lists, …),
// fall back to presentational-attribute stripping plus one row per line so
// the chunker can still split on "\n". Tables inside fenced code blocks are
// left unchanged.
func NormalizeHTMLTables(md string) string {
if !strings.Contains(strings.ToLower(md), "<table") {
return md
}
locs := htmlTableBlockPattern.FindAllStringIndex(md, -1)
if len(locs) == 0 {
return md
}
conv := converter.NewConverter(
converter.WithPlugins(
base.NewBasePlugin(),
commonmark.NewCommonmarkPlugin(),
table.NewTablePlugin(),
),
)
fences := fencedCodeBlockPattern.FindAllStringIndex(md, -1)
var b strings.Builder
last := 0
for _, loc := range locs {
b.WriteString(md[last:loc[0]])
block := md[loc[0]:loc[1]]
if indexInsideSpans(loc[0], fences) {
b.WriteString(block)
last = loc[1]
continue
}
// Isolate the rewritten table with blank lines without stacking pads
// on repeated NormalizeHTMLTables calls.
out := strings.TrimRight(b.String(), "\n")
b.Reset()
b.WriteString(out)
b.WriteString("\n\n")
b.WriteString(normalizeOneHTMLTable(conv, block))
last = loc[1]
for last < len(md) && md[last] == '\n' {
last++
}
b.WriteString("\n\n")
}
b.WriteString(md[last:])
return b.String()
}
func normalizeOneHTMLTable(conv *converter.Converter, block string) string {
fallback := func() string {
return splitHTMLTableRows(stripHTMLLayoutAttrs(block))
}
if htmlSpanAttrPattern.MatchString(block) {
return fallback()
}
converted, err := conv.ConvertString(block)
if err != nil {
return fallback()
}
converted = unescapeMarkdownImageSyntax(strings.TrimSpace(converted))
if converted == "" || !markdownTableSeparatorPattern.MatchString(converted) {
return fallback()
}
return converted
}
func indexInsideSpans(pos int, spans [][]int) bool {
for _, s := range spans {
if pos >= s[0] && pos < s[1] {
return true
}
}
return false
}
// stripHTMLLayoutAttrs removes presentational attributes from an HTML fragment
// while preserving structural attributes (rowspan/colspan) and text content.
func stripHTMLLayoutAttrs(html string) string {
return htmlLayoutAttrPattern.ReplaceAllString(html, "")
}
// splitHTMLTableRows puts each table row on its own line. The chunker splits
// on "\n", so a single-line HTML table would otherwise be unsplittable and get
// force-cut at the absolute max size. Whitespace between tags is insignificant
// in HTML, and newlines are only inserted before <tr> (never inside a tag).
// A <tr> that already starts on its own line is left alone.
func splitHTMLTableRows(block string) string {
locs := htmlTableRowPattern.FindAllStringIndex(block, -1)
if len(locs) == 0 {
return strings.TrimSpace(block)
}
var b strings.Builder
last := 0
for _, loc := range locs {
b.WriteString(block[last:loc[0]])
if loc[0] == 0 || block[loc[0]-1] != '\n' {
b.WriteByte('\n')
}
b.WriteString(block[loc[0]:loc[1]])
last = loc[1]
}
b.WriteString(block[last:])
return strings.TrimSpace(b.String())
}
@@ -0,0 +1,233 @@
package docparser
import (
"strings"
"testing"
)
func TestNormalizeHTMLTables_ConvertsStyledTableToMarkdown(t *testing.T) {
// Mirrors PaddleOCR-VL output: a data table where every cell carries a
// text-align style that wastes tokens.
input := `# 报告
<table><tr><td style="text-align:center;">指标</td><td style="text-align:center;">数值</td></tr>` +
`<tr><td style="text-align:center;">营收</td><td style="text-align:right;">10亿</td></tr>` +
`<tr><td style="text-align:center;">利润</td><td style="text-align:right;">2.3亿</td></tr></table>
结尾。`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected HTML table to be converted away, got:\n%s", got)
}
if strings.Contains(got, "text-align") {
t.Fatalf("expected style attributes removed, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"指标", "数值", "营收", "10亿", "利润", "2.3亿"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
if !strings.Contains(got, "# 报告") || !strings.Contains(got, "结尾。") {
t.Fatalf("expected surrounding markdown to be preserved, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_NoTableUnchanged(t *testing.T) {
input := "# 标题\n\n普通段落,没有表格。\n\n| a | b |\n| --- | --- |\n| 1 | 2 |"
if got := NormalizeHTMLTables(input); got != input {
t.Fatalf("expected content without HTML tables to be unchanged, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_SpanValueOneIsConvertible(t *testing.T) {
// rowspan=1 / colspan=1 merge nothing, so the table must still become GFM.
// Covers quoted, unquoted and space-padded attribute forms.
input := `<table><tr>` +
`<td rowspan="1" colspan="1" style="text-align:center;">指标</td>` +
`<td rowspan=1 colspan=1>数值</td></tr>` +
`<tr><td rowspan="1" colspan='1'>营收</td>` +
`<td rowspan = 1 colspan = 1>10亿</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected span=1 table to be converted away, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"指标", "数值", "营收", "10亿"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_RealSpanKeepsHTMLWithRowNewlines(t *testing.T) {
// Genuine merges (colspan>1 / rowspan>1) cannot be GFM, so the table stays
// HTML — but each row must start on its own line so the chunker can split it.
input := `<table><tr><td colspan="6" style="text-align:center;">合计</td></tr>` +
`<tr><td rowspan="3">A</td><td>1</td></tr>` +
`<tr><td rowspan = 2>B</td><td>2</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected real span table to remain HTML, got:\n%s", got)
}
if !strings.Contains(got, `colspan="6"`) || !strings.Contains(got, `rowspan="3"`) {
t.Fatalf("expected structural span attrs preserved, got:\n%s", got)
}
if !strings.Contains(got, "\n<tr") {
t.Fatalf("expected each <tr> to start on a new line, got:\n%q", got)
}
if !strings.Contains(got, "\n\n<table") {
t.Fatalf("expected block to be padded at the head with blank lines, got:\n%q", got)
}
if !strings.HasSuffix(got, "</table>\n\n") {
t.Fatalf("expected block to be padded at the tail with blank lines, got:\n%q", got)
}
if n := strings.Count(got, "\n<tr"); n != 3 {
t.Fatalf("expected 3 rows each preceded by a newline, got %d in:\n%q", n, got)
}
}
func assertHTMLRowsSplittable(t *testing.T, got string) {
t.Helper()
if !strings.Contains(got, "<tr") {
t.Fatalf("expected remaining HTML table rows, got:\n%s", got)
}
for i := 0; ; {
idx := strings.Index(got[i:], "<tr")
if idx < 0 {
return
}
abs := i + idx
if abs == 0 || got[abs-1] != '\n' {
t.Fatalf("remaining <tr> at offset %d is not preceded by a newline:\n%s", abs, got)
}
i = abs + 1
}
}
func TestNormalizeHTMLTables_StripsAttrsOnSpanTables(t *testing.T) {
// rowspan/colspan cannot be expressed in Markdown, so the table stays HTML
// but its presentational attributes are stripped and rows become splittable.
input := `<table><tr>` +
`<td colspan="2" style="text-align:center;" class="hdr">合计</td></tr>` +
`<tr><td style="text-align:left;">A</td><td width="80">B</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected span table to remain HTML, got:\n%s", got)
}
if !strings.Contains(got, `colspan="2"`) {
t.Fatalf("expected colspan to be preserved, got:\n%s", got)
}
for _, banned := range []string{"text-align", "class=", "width="} {
if strings.Contains(got, banned) {
t.Fatalf("expected %q to be stripped, got:\n%s", banned, got)
}
}
assertHTMLRowsSplittable(t, got)
}
func TestNormalizeHTMLTables_BRCellsStaySplittableHTML(t *testing.T) {
// <br> inside a cell makes the table plugin give up (it emits a newline).
// The HTML fallback must still put each <tr> on its own line.
input := `<table><tr><td>指标<br/>名称</td><td>数值<br/>单位</td></tr>` +
`<tr><td>拉伸强度<br/>MPa</td><td>合格<br/>A级</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected <br> table to remain HTML rather than flattened text, got:\n%s", got)
}
assertHTMLRowsSplittable(t, got)
for _, want := range []string{"指标", "名称", "拉伸强度", "合格"} {
if !strings.Contains(got, want) {
t.Fatalf("expected fallback HTML to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_ListInCellFallsBackToSplittableHTML(t *testing.T) {
input := `<table><tr><td><ul><li>a</li><li>b</li></ul></td><td>x</td></tr>` +
`<tr><td>c</td><td>d</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected list-in-cell table to remain HTML, got:\n%s", got)
}
assertHTMLRowsSplittable(t, got)
}
func TestNormalizeHTMLTables_SingleColumnConvertsToGFM(t *testing.T) {
input := `<table><tr><td>目录</td></tr><tr><td>第一章</td></tr><tr><td>第二章</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected single-column table to convert to GFM, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"目录", "第一章", "第二章"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_ImgInSingleColumnBecomesGFM(t *testing.T) {
input := `<table><tr><td><img src="local://images/profile.png" alt="profile"/></td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected single-column image table to convert to GFM, got:\n%s", got)
}
if !strings.Contains(got, "![profile](local://images/profile.png)") {
t.Fatalf("expected markdown image to be preserved, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_MarkdownImageInCellNotEscaped(t *testing.T) {
input := `<table><tr><td>![cover](local://images/cover.png)</td><td>说明</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, `!\[`) {
t.Fatalf("markdown image syntax escaped:\n%s", got)
}
if !strings.Contains(got, "![cover](local://images/cover.png)") {
t.Fatalf("expected markdown image to survive conversion, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_CodeFenceTableLeftAlone(t *testing.T) {
input := "示例:\n\n```html\n<table><tr><td>a</td><td>b</td></tr></table>\n```\n"
got := NormalizeHTMLTables(input)
if got != input {
t.Fatalf("expected fenced HTML table to be unchanged, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_SpanTableIdempotent(t *testing.T) {
input := `<table><tr><td colspan="6">汇总</td></tr><tr><td colspan="6">备注</td></tr></table>`
once := NormalizeHTMLTables(input)
twice := NormalizeHTMLTables(once)
if once != twice {
t.Fatalf("NormalizeHTMLTables is not idempotent for span tables:\n1=%q\n2=%q", once, twice)
}
}
@@ -0,0 +1,256 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
)
const (
PathRead = "/read"
PathListEngines = "/list-engines"
)
// --- JSON DTOs ---
type httpReadConfig struct {
ParserEngine string `json:"parser_engine,omitempty"`
ParserEngineOverrides map[string]string `json:"parser_engine_overrides,omitempty"`
}
type httpReadRequest struct {
FileContent string `json:"file_content,omitempty"` // base64
FileName string `json:"file_name,omitempty"`
FileType string `json:"file_type,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Config *httpReadConfig `json:"config,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
type httpImageRef struct {
Filename string `json:"filename"`
OriginalRef string `json:"original_ref"`
MimeType string `json:"mime_type"`
StorageKey string `json:"storage_key,omitempty"`
ImageData []byte `json:"image_data,omitempty"`
}
type httpReadResponse struct {
MarkdownContent string `json:"markdown_content"`
ImageRefs []httpImageRef `json:"image_refs,omitempty"`
ImageDirPath string `json:"image_dir_path,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Error string `json:"error,omitempty"`
SourceBlocks []wireSourceBlock `json:"source_blocks,omitempty"`
}
// HTTPDocumentReader implements DocumentReader over HTTP/JSON.
type HTTPDocumentReader struct {
mu sync.RWMutex
baseURL string
client *http.Client
}
func NewHTTPDocumentReader(baseURL string) (*HTTPDocumentReader, error) {
baseURL = strings.TrimSuffix(strings.TrimSpace(baseURL), "/")
if baseURL != "" {
if err := secutils.ValidateURLForSSRF(baseURL); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
}
clientCfg := secutils.DefaultSSRFSafeHTTPClientConfig()
clientCfg.Timeout = 5 * time.Minute
p := &HTTPDocumentReader{
baseURL: baseURL,
client: secutils.NewSSRFSafeHTTPClient(clientCfg),
}
if p.baseURL != "" {
logger.Infof(context.Background(), "INFO: HTTP docreader base URL: %s", p.baseURL)
}
return p, nil
}
func (p *HTTPDocumentReader) base() string {
p.mu.RLock()
defer p.mu.RUnlock()
return p.baseURL
}
func (p *HTTPDocumentReader) Reconnect(addr string) error {
addr = strings.TrimSuffix(strings.TrimSpace(addr), "/")
if addr != "" {
if err := secutils.ValidateURLForSSRF(addr); err != nil {
return fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
}
p.mu.Lock()
defer p.mu.Unlock()
p.baseURL = addr
logger.Infof(context.Background(), "INFO: HTTP docreader base URL set to %s", p.baseURL)
return nil
}
func (p *HTTPDocumentReader) IsConnected() bool {
p.mu.RLock()
defer p.mu.RUnlock()
return p.baseURL != ""
}
func (p *HTTPDocumentReader) Close() error { return nil }
type httpListEnginesRequest struct {
ConfigOverrides map[string]string `json:"config_overrides,omitempty"`
}
type httpParserEngineInfo struct {
Name string `json:"name"`
Description string `json:"description"`
FileTypes []string `json:"file_types"`
Available bool `json:"available"`
UnavailableReason string `json:"unavailable_reason,omitempty"`
}
type httpListEnginesResponse struct {
Engines []httpParserEngineInfo `json:"engines"`
}
func (p *HTTPDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
base := p.base()
if base == "" {
return nil, errNotConnected
}
if err := secutils.ValidateURLForSSRF(base); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
body := httpListEnginesRequest{ConfigOverrides: overrides}
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("http marshal list-engines request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathListEngines, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("http list-engines failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("http list-engines status %d: %s", resp.StatusCode, string(respBytes))
}
var out httpListEnginesResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("http decode list-engines response: %w", err)
}
result := make([]types.ParserEngineInfo, 0, len(out.Engines))
for _, e := range out.Engines {
result = append(result, types.ParserEngineInfo{
Name: e.Name,
Description: e.Description,
FileTypes: e.FileTypes,
Available: e.Available,
UnavailableReason: e.UnavailableReason,
})
}
return result, nil
}
func fromHTTPReadResponse(resp *httpReadResponse) *types.ReadResult {
result := &types.ReadResult{
MarkdownContent: resp.MarkdownContent,
ImageDirPath: resp.ImageDirPath,
Metadata: resp.Metadata,
Error: resp.Error,
SourceBlocks: sourceBlocksFromWire(resp.SourceBlocks),
}
for _, ref := range resp.ImageRefs {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: ref.Filename,
OriginalRef: ref.OriginalRef,
MimeType: ref.MimeType,
StorageKey: ref.StorageKey,
ImageData: ref.ImageData,
})
}
return result
}
func (p *HTTPDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
base := p.base()
if base == "" {
return nil, errNotConnected
}
if err := secutils.ValidateURLForSSRF(base); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
body := httpReadRequest{
FileName: req.FileName,
FileType: req.FileType,
URL: req.URL,
Title: req.Title,
RequestID: req.RequestID,
Config: &httpReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
if len(req.FileContent) > 0 {
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
}
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("http marshal read request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathRead, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.ContentLength = int64(len(jsonBody))
resp, err := p.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("http read failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
}
var out httpReadResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("http decode read response: %w", err)
}
return fromHTTPReadResponse(&out), nil
}
// PreprocessImage is not offered over the HTTP transport: page straightening
// lives in the docreader service, and this reader speaks to a different
// surface. It reports that as a verdict — fallback=true, no error — so the
// caller's single fallback (OCR the original bytes) is the only outcome, with
// nothing logged that looks like a failure.
func (p *HTTPDocumentReader) PreprocessImage(_ context.Context, _ []byte) ([]byte, bool, error) {
return nil, true, nil
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,80 @@
package docparser
import (
"context"
"strings"
"testing"
"academy/internal/types"
)
func TestResolveAndStoreRelativeHTMLImages(t *testing.T) {
png := createTestPNG(200, 150)
result := &types.ReadResult{
MarkdownContent: `<table><tr><td><img src="images/profile.jpg" alt="profile"/></td></tr></table>`,
ImageRefs: []types.ImageRef{
{
Filename: "profile.jpg",
OriginalRef: "images/profile.jpg",
MimeType: "image/png",
ImageData: png,
},
},
}
svc := &captureSaveBytes{}
r := NewImageResolver()
out, imgs, err := r.ResolveAndStore(context.Background(), result, svc, 1)
if err != nil {
t.Fatal(err)
}
if len(imgs) != 1 {
t.Fatalf("expected 1 stored image but got %d", len(imgs))
}
if len(svc.saved) != 1 {
t.Fatalf("expected SaveBytes to be called once but got %d", len(svc.saved))
}
if strings.Contains(out, `src="images/profile.jpg"`) {
t.Fatalf("expected relative html img src to be replaced, got: %s", out)
}
if !strings.Contains(out, `src="local://test/`) {
t.Fatalf("expected stored file url in html img src, got: %s", out)
}
}
// TestResolveAndStoreDedupsSameImageRefVariants ensures that when the same
// MinerU image is referenced under multiple path forms (e.g. "images/foo.png"
// and "./images/foo.png"), the bytes are uploaded to object storage only once.
func TestResolveAndStoreDedupsSameImageRefVariants(t *testing.T) {
png := createTestPNG(200, 150)
result := &types.ReadResult{
MarkdownContent: strings.Join([]string{
"![](images/foo.png)",
`<img src="./images/foo.png"/>`,
}, "\n"),
ImageRefs: []types.ImageRef{
{
Filename: "foo.png",
OriginalRef: "images/foo.png",
MimeType: "image/png",
ImageData: png,
},
{
Filename: "foo.png",
OriginalRef: "./images/foo.png",
MimeType: "image/png",
ImageData: png,
},
},
}
svc := &captureSaveBytes{}
r := NewImageResolver()
_, _, err := r.ResolveAndStore(context.Background(), result, svc, 1)
if err != nil {
t.Fatal(err)
}
if len(svc.saved) != 1 {
t.Fatalf("expected SaveBytes to be called once for duplicate refs, got %d", len(svc.saved))
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,301 @@
package docparser
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
// defaultJSONChunkSize is the target chunk size in bytes for JSON semantic
// splitting. Approximates 512 tokens (1 token ≈ 3-4 bytes for mixed content).
const defaultJSONChunkSize = 1536
// minJSONChunkSize is the minimum chunk size. A new chunk is only started
// when the current chunk has reached at least this size.
var minJSONChunkSize = defaultJSONChunkSize - 200
// Errors returned by ValidateJSONContent.
var (
ErrEmptyJSONContent = errors.New("empty JSON content")
ErrInvalidJSONContent = errors.New("invalid JSON content")
)
// ValidateJSONContent reports whether data is well-formed JSON after stripping
// a leading UTF-8 BOM. Upload paths call this before enqueueing parse work so
// JSONC / truncated payloads fail immediately instead of after async retries.
func ValidateJSONContent(data []byte) error {
data = trimBOM(data)
if len(data) == 0 {
return ErrEmptyJSONContent
}
if !json.Valid(data) {
return ErrInvalidJSONContent
}
return nil
}
// jsonToMarkdown converts raw JSON bytes into markdown text
//
// Key properties:
// - Every output chunk is a **valid JSON object** (not a fragment).
// - Nested paths from root to leaf are **fully preserved** in each chunk.
// - Arrays are converted to index-keyed dicts so the algorithm is uniform.
// - Small objects that fit within maxChunkSize are kept intact (not split).
// - The output is a series of fenced ```json code blocks separated by \n\n,
// which the downstream text chunker can split at block boundaries.
func jsonToMarkdown(data []byte) (string, error) {
if err := ValidateJSONContent(data); err != nil {
return "", err
}
data = trimBOM(data)
// UseNumber keeps each number as written. Decoded into a float64, an id
// above 2^53 changed digits: 12345678901234567890 came out as
// 12345678901234567000. ValidateJSONContent above has already rejected
// anything after the value.
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var parsed interface{}
if err := decoder.Decode(&parsed); err != nil {
return "", fmt.Errorf("failed to parse JSON: %w", err)
}
// Normalize: convert top-level arrays to index-keyed dicts
normalized := listToDictPreprocess(parsed)
// If the whole thing fits in one chunk, just format it
wholeSize := jsonSize(normalized)
if wholeSize <= defaultJSONChunkSize {
formatted := formatValue(normalized)
return wrapCodeBlock(formatted), nil
}
// Recursive split
chunks := recursiveJSONSplit(normalized, nil, nil)
// Convert each chunk dict to a fenced code block
blocks := make([]string, 0, len(chunks))
for _, chunk := range chunks {
if len(chunk) == 0 {
continue
}
blocks = append(blocks, wrapCodeBlock(formatValue(chunk)))
}
if len(blocks) == 0 {
return wrapCodeBlock(formatValue(normalized)), nil
}
return strings.Join(blocks, "\n\n"), nil
}
// ---------------------------------------------------------------------------
// RecursiveJsonSplitter core algorithm
// ---------------------------------------------------------------------------
// recursiveJSONSplit splits a JSON dict into a list of JSON dicts,
// each fitting within defaultJSONChunkSize. It preserves the full nested
// path from root to each leaf by using setNestedDict.
//
// This is a Go port of LangChain's RecursiveJsonSplitter._json_split.
func recursiveJSONSplit(
data interface{},
currentPath []string,
chunks []map[string]interface{},
) []map[string]interface{} {
if chunks == nil {
chunks = []map[string]interface{}{{}}
}
dict, ok := data.(map[string]interface{})
if !ok {
// Scalar or already-processed value: place it at the current path
if len(currentPath) > 0 && len(chunks) > 0 {
setNestedDict(chunks[len(chunks)-1], currentPath, data)
}
return chunks
}
// Sort keys for deterministic output
keys := sortedKeys(dict)
for _, key := range keys {
value := dict[key]
newPath := append(append([]string{}, currentPath...), key)
// Measure sizes
chunkSize := jsonSize(chunks[len(chunks)-1])
itemSize := jsonSize(map[string]interface{}{key: value})
remaining := defaultJSONChunkSize - chunkSize
if itemSize <= remaining {
// Item fits in the current chunk — add it preserving the path
setNestedDict(chunks[len(chunks)-1], newPath, value)
} else {
// Item doesn't fit
if chunkSize >= minJSONChunkSize {
// Current chunk is big enough, start a new one
chunks = append(chunks, map[string]interface{}{})
}
// Check if the value itself is a dict/list that can be recursed into
normalized := listToDictPreprocess(value)
if subDict, isDict := normalized.(map[string]interface{}); isDict && canSplitDict(subDict) {
// Recurse into the sub-object
chunks = recursiveJSONSplit(subDict, newPath, chunks)
} else {
// Cannot split further (scalar or single-key dict) — place as-is
setNestedDict(chunks[len(chunks)-1], newPath, value)
}
}
}
return chunks
}
// setNestedDict sets a value in a nested dict structure, creating
// intermediate dicts as needed. This preserves the full JSON path.
//
// Example: setNestedDict(d, ["config","db","host"], "localhost")
// produces: {"config": {"db": {"host": "localhost"}}}
func setNestedDict(d map[string]interface{}, path []string, value interface{}) {
if len(path) == 0 {
return
}
current := d
for _, key := range path[:len(path)-1] {
next, ok := current[key]
if !ok {
next = map[string]interface{}{}
current[key] = next
}
if nextDict, ok := next.(map[string]interface{}); ok {
current = nextDict
} else {
// Path conflict (existing value is not a dict) — overwrite
newDict := map[string]interface{}{}
current[key] = newDict
current = newDict
}
}
current[path[len(path)-1]] = value
}
// listToDictPreprocess recursively converts JSON arrays to index-keyed
// dicts so the splitter can treat everything uniformly.
//
// Example: ["a","b","c"] → {"0":"a", "1":"b", "2":"c"}
func listToDictPreprocess(data interface{}) interface{} {
switch v := data.(type) {
case map[string]interface{}:
result := make(map[string]interface{}, len(v))
for k, val := range v {
result[k] = listToDictPreprocess(val)
}
return result
case []interface{}:
result := make(map[string]interface{}, len(v))
for i, item := range v {
result[fmt.Sprintf("%d", i)] = listToDictPreprocess(item)
}
return result
default:
return data
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// jsonSize returns the serialized JSON byte length of a value.
func jsonSize(v interface{}) int {
b, err := marshalJSON(v, "")
if err != nil {
return 0
}
return len(b)
}
// formatValue formats a JSON value with indentation.
func formatValue(v interface{}) string {
b, err := marshalJSON(v, " ")
if err != nil {
b, _ = marshalJSON(v, "")
}
return string(b)
}
// marshalJSON encodes v like json.Marshal, indented when indent is set, but
// leaves <, > and & as they are. json.Marshal writes them as \u003c, \u003e
// and \u0026, which is meant for embedding in HTML and only garbles the text
// a chunk is read and searched as.
func marshalJSON(v interface{}, indent string) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", indent)
if err := encoder.Encode(v); err != nil {
return nil, err
}
return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil
}
// wrapCodeBlock wraps content in a fenced JSON code block.
func wrapCodeBlock(content string) string {
return "```json\n" + content + "\n```"
}
// trimBOM removes a UTF-8 BOM prefix if present.
func trimBOM(data []byte) []byte {
if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
return data[3:]
}
return data
}
// canSplitDict returns true if a dict can be meaningfully split.
// A dict with multiple keys can be split by distributing keys across chunks.
// A dict with a single key can still be split if its value is a splittable dict.
func canSplitDict(d map[string]interface{}) bool {
if len(d) > 1 {
return true
}
if len(d) == 1 {
for _, v := range d {
if sub, ok := v.(map[string]interface{}); ok && len(sub) > 1 {
return true
}
}
}
return false
}
// sortedKeys returns the keys of a map in sorted order.
// When all keys are numeric strings (from array-to-dict conversion),
// sorts numerically so "2" comes before "10".
func sortedKeys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
allNumeric := true
for k := range m {
keys = append(keys, k)
if allNumeric {
if _, err := strconv.Atoi(k); err != nil {
allNumeric = false
}
}
}
if allNumeric {
sort.Slice(keys, func(i, j int) bool {
ni, _ := strconv.Atoi(keys[i])
nj, _ := strconv.Atoi(keys[j])
return ni < nj
})
} else {
sort.Strings(keys)
}
return keys
}
@@ -0,0 +1,778 @@
package docparser
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"academy/internal/types"
)
// ═══════════════════════════════════════════════════════════════════════════
// Helper: visual test reporter
// ═══════════════════════════════════════════════════════════════════════════
func visualReport(t *testing.T, label string, input string, result string, err error, checks []checkResult) {
t.Helper()
const width = 72
bar := strings.Repeat("─", width)
thickBar := strings.Repeat("━", width)
t.Logf("\n%s", thickBar)
t.Logf("📋 TEST: %s", label)
t.Logf("%s", bar)
// ── Input ──
inputPreview := input
if len(inputPreview) > 200 {
inputPreview = inputPreview[:200] + fmt.Sprintf("... (%d bytes total)", len(input))
}
t.Logf("📥 INPUT (%d bytes):", len(input))
for _, line := range strings.Split(inputPreview, "\n") {
t.Logf(" %s", line)
}
t.Logf("%s", bar)
// ── Output / Error ──
if err != nil {
t.Logf("❌ ERROR: %v", err)
} else {
blockCount := strings.Count(result, "```json")
totalLen := len(result)
t.Logf("📤 OUTPUT: %d code block(s), %d bytes total", blockCount, totalLen)
t.Logf("%s", bar)
blocks := splitBlocks(result)
for i, blk := range blocks {
preview := blk
lines := strings.Split(preview, "\n")
if len(lines) > 10 {
preview = strings.Join(lines[:4], "\n") +
fmt.Sprintf("\n ... (%d lines omitted) ...\n", len(lines)-8) +
strings.Join(lines[len(lines)-4:], "\n")
}
t.Logf(" 📦 Block #%d (%d bytes):", i+1, len(blk))
for _, line := range strings.Split(preview, "\n") {
t.Logf(" │ %s", line)
}
}
}
t.Logf("%s", bar)
// ── Checks ──
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
}
t.Logf("%s %s", icon, c.desc)
if !c.pass {
t.Errorf("FAIL: %s", c.desc)
}
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("%s\n", thickBar)
}
// splitBlocks extracts the content between ```json and ``` fences.
func splitBlocks(result string) []string {
var blocks []string
rest := result
for {
start := strings.Index(rest, "```json\n")
if start < 0 {
break
}
rest = rest[start+len("```json\n"):]
end := strings.Index(rest, "\n```")
if end < 0 {
blocks = append(blocks, rest)
break
}
blocks = append(blocks, rest[:end])
rest = rest[end+len("\n```"):]
}
return blocks
}
type checkResult struct {
desc string
pass bool
}
func check(desc string, pass bool) checkResult { return checkResult{desc, pass} }
// blockIsValidJSON checks that each code block inside the result is valid JSON.
func allBlocksValidJSON(result string) bool {
for _, blk := range splitBlocks(result) {
if !json.Valid([]byte(blk)) {
return false
}
}
return true
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 1: Small inputs — kept intact, NOT split
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_SmallObject(t *testing.T) {
input := `{"name": "test", "version": "1.0"}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Small Object → single block, kept intact", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains key 'name'", strings.Contains(result, `"name"`)),
check("contains key 'version'", strings.Contains(result, `"version"`)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
check("both keys in SAME block (not split apart)",
strings.Contains(result, `"name"`) && strings.Contains(result, `"version"`) && blocks == 1),
})
}
func TestJsonToMarkdown_SmallArray(t *testing.T) {
input := `[{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Small Array → single block, kept intact", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_EmptyObject(t *testing.T) {
input := `{}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Object {}", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '{}'", strings.Contains(result, "{}")),
})
}
func TestJsonToMarkdown_EmptyArray(t *testing.T) {
input := `[]`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Array []", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '{}'", strings.Contains(result, "{}")), // [] → {} after list-to-dict
})
}
func TestJsonToMarkdown_PrimitiveString(t *testing.T) {
input := `"hello world"`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive String", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'hello world'", strings.Contains(result, "hello world")),
})
}
func TestJsonToMarkdown_PrimitiveNumber(t *testing.T) {
input := `42`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Number", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '42'", strings.Contains(result, "42")),
})
}
func TestJsonToMarkdown_PrimitiveBoolean(t *testing.T) {
input := `true`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Boolean", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'true'", strings.Contains(result, "true")),
})
}
func TestJsonToMarkdown_PrimitiveNull(t *testing.T) {
input := `null`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Null", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'null'", strings.Contains(result, "null")),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 2: Large data — smart recursive splitting
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_LargeObject(t *testing.T) {
obj := make(map[string]interface{})
for i := 0; i < 50; i++ {
obj[fmt.Sprintf("key_%02d", i)] = strings.Repeat("value", 50)
}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Large Object (50 keys) → multiple blocks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_LargeArray(t *testing.T) {
arr := make([]interface{}, 100)
for i := range arr {
arr[i] = map[string]interface{}{
"id": i,
"name": strings.Repeat("name", 20),
"description": strings.Repeat("desc", 30),
}
}
data, _ := json.Marshal(arr)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Large Array (100 elements) → multiple blocks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_RecursiveSplitLargeKey(t *testing.T) {
inner := make(map[string]interface{})
for i := 0; i < 30; i++ {
inner[fmt.Sprintf("sub_%02d", i)] = strings.Repeat("val", 50)
}
obj := map[string]interface{}{"bigkey": inner}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Recursive Split: 1 big key with 30 sub-keys", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
check("path preserved: chunks contain 'bigkey'", strings.Contains(result, "bigkey")),
})
}
func TestJsonToMarkdown_PathPreservation(t *testing.T) {
// Core test: verify that nested paths are preserved in each chunk
inner := make(map[string]interface{})
for i := 0; i < 40; i++ {
inner[fmt.Sprintf("field_%02d", i)] = strings.Repeat("data", 60)
}
obj := map[string]interface{}{
"config": map[string]interface{}{
"database": inner,
},
}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := splitBlocks(result)
// Every block should contain the full path "config" → "database"
allHavePath := true
for _, blk := range blocks {
if !strings.Contains(blk, `"config"`) || !strings.Contains(blk, `"database"`) {
allHavePath = false
break
}
}
visualReport(t, "Path Preservation: config.database.* across chunks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", len(blocks)), len(blocks) >= 2),
check("ALL blocks preserve path: config → database", allHavePath),
})
}
func TestJsonToMarkdown_MixedArrayElements(t *testing.T) {
arr := []interface{}{
map[string]interface{}{"id": 1},
map[string]interface{}{"id": 2},
map[string]interface{}{"id": 3, "data": strings.Repeat("x", 2000)},
map[string]interface{}{"id": 4},
}
data, _ := json.Marshal(arr)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Mixed Array: 3 small + 1 large element", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("at least 2 blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_DeepNested(t *testing.T) {
input := `{"l1": {"l2": {"l3": {"data": "` + strings.Repeat("x", 2000) + `"}}}}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Deep Nested (3 levels, large leaf)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("block count ≥ 1 (got %d)", blocks), blocks >= 1),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 3: Error Handling
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_InvalidJSON(t *testing.T) {
input := `{invalid json}`
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Invalid JSON → error", input, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'invalid JSON'",
err != nil && strings.Contains(err.Error(), "invalid JSON")),
})
}
func TestJsonToMarkdown_EmptyInput(t *testing.T) {
input := ""
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Input → error", input, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'empty'",
err != nil && strings.Contains(err.Error(), "empty")),
})
}
func TestJsonToMarkdown_WhitespaceOnly(t *testing.T) {
input := " \n\t "
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Whitespace-Only Input → error", input, "", err, []checkResult{
check("returns error", err != nil),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 4: Edge Cases & Encoding
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_BOM(t *testing.T) {
raw := append([]byte{0xEF, 0xBB, 0xBF}, []byte(`{"key": "value"}`)...)
result, err := jsonToMarkdown(raw)
visualReport(t, "UTF-8 BOM prefix → stripped", string(raw), result, err, []checkResult{
check("no error", err == nil),
check("contains key after BOM removal", strings.Contains(result, `"key"`)),
})
}
func TestJsonToMarkdown_UnicodeContent(t *testing.T) {
input := `{"名称": "Academy 知识库", "描述": "支持中文 JSON 🎉", "emoji": "🚀"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Unicode / Chinese / Emoji", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains Chinese", strings.Contains(result, "知识库")),
check("contains emoji", strings.Contains(result, "🚀")),
})
}
func TestJsonToMarkdown_SpecialCharsInStrings(t *testing.T) {
input := `{"html": "<div class=\"test\">hello</div>", "path": "C:\\Users\\test", "newline": "line1\nline2"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Special characters (HTML, backslash, newline)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
})
}
func TestJsonToMarkdown_KeepsNumbersAsWritten(t *testing.T) {
// Decoded into a float64, an id above 2^53 changed digits.
input := `{"order_id": 12345678901234567890, "big": 9007199254740993, "price": 1.50, "ratio": 1e5}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Numbers keep the digits they were written with", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("order_id keeps all 20 digits", strings.Contains(result, `"order_id": 12345678901234567890`)),
check("2^53+1 is not rounded to 2^53", strings.Contains(result, `"big": 9007199254740993`)),
check("1.50 keeps its trailing zero", strings.Contains(result, `"price": 1.50`)),
check("1e5 keeps its exponent", strings.Contains(result, `"ratio": 1e5`)),
})
}
func TestJsonToMarkdown_KeepsNumbersAsWrittenAcrossChunks(t *testing.T) {
// Large enough to take the recursive split path.
items := make([]string, 0, 60)
for i := 0; i < 60; i++ {
item := fmt.Sprintf(`"item_%02d": {"id": 1234567890123456789%d, "label": "entry %d"}`, i, i%10, i)
items = append(items, item)
}
input := "{" + strings.Join(items, ", ") + "}"
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Numbers keep their digits in a split document", input, result, err, []checkResult{
check("no error", err == nil),
check("split into several blocks", len(splitBlocks(result)) > 1),
check("first id kept", strings.Contains(result, `"id": 12345678901234567890`)),
check("last id kept", strings.Contains(result, `"id": 12345678901234567899`)),
})
}
func TestJsonToMarkdown_KeepsAngleBracketsAndAmpersands(t *testing.T) {
// json.Marshal writes <, > and & as \u003c, \u003e and \u0026.
input := `{"note": "a < b && c > d", "html": "<b>bold</b>"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "<, > and & stay readable", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("comparison text kept", strings.Contains(result, `"note": "a < b && c > d"`)),
check("markup kept", strings.Contains(result, `"html": "<b>bold</b>"`)),
check("no \\u003c escapes", !strings.Contains(result, `\u003c`)),
})
}
func TestJsonToMarkdown_NullValues(t *testing.T) {
input := `{"name": "test", "value": null, "list": [null, 1, null]}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Object with null values", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains 'null'", strings.Contains(result, "null")),
})
}
func TestJsonToMarkdown_MixedValueTypes(t *testing.T) {
input := `{"str": "hello", "num": 42, "float": 3.14, "bool": true, "null_val": null, "arr": [1,2], "obj": {"a":1}}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Mixed value types in one object", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains string", strings.Contains(result, "hello")),
check("contains number", strings.Contains(result, "42")),
check("contains float", strings.Contains(result, "3.14")),
})
}
func TestJsonToMarkdown_NestedArrayOfArrays(t *testing.T) {
input := `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Nested Array of Arrays (matrix)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
})
}
func TestJsonToMarkdown_LargePrimitiveString(t *testing.T) {
bigStr := strings.Repeat("abcdefghij", 300)
input := fmt.Sprintf(`"%s"`, bigStr)
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Large Primitive String (3000 chars) → fallback", input, result, err, []checkResult{
check("no error", err == nil),
check("content preserved", strings.Contains(result, "abcdefghij")),
})
}
func TestJsonToMarkdown_SingleKeyObject(t *testing.T) {
input := `{"only_key": "only_value"}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Single-Key Object", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_SingleElementArray(t *testing.T) {
input := `[{"id": 1, "name": "solo"}]`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Single-Element Array", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 5: Realistic Scenarios
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_RealisticConfig(t *testing.T) {
input := `{
"app": {"name": "Academy", "version": "2.0.0", "debug": false},
"database": {"host": "localhost", "port": 5432, "name": "academy_db", "pool_size": 10},
"redis": {"host": "localhost", "port": 6379},
"features": {"json_upload": true, "multimodel": true, "graph_extraction": false}
}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Realistic: App Config (fits in 1 block)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains 'Academy'", strings.Contains(result, "Academy")),
check("contains 'database'", strings.Contains(result, "database")),
check(fmt.Sprintf("single block (fits, got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_RealisticAPIResponse(t *testing.T) {
users := make([]interface{}, 40)
for i := range users {
users[i] = map[string]interface{}{
"id": i + 1,
"username": fmt.Sprintf("user_%03d", i+1),
"email": fmt.Sprintf("user%03d@example.com", i+1),
"role": "editor",
"active": i%3 != 0,
}
}
apiResp := map[string]interface{}{
"status": "ok",
"total": 40,
"page": 1,
"data": users,
}
data, _ := json.Marshal(apiResp)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Realistic: API Response (40 user records)", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains user data", strings.Contains(result, "user_001")),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_RealisticLargeNestedConfig(t *testing.T) {
// A config where one section is huge and must be recursively split,
// while other sections are small
rules := make(map[string]interface{})
for i := 0; i < 30; i++ {
rules[fmt.Sprintf("rule_%02d", i)] = map[string]interface{}{
"pattern": strings.Repeat("pattern", 10),
"action": "allow",
"priority": i,
}
}
config := map[string]interface{}{
"version": "3.0",
"metadata": map[string]interface{}{"author": "admin", "updated": "2026-03-24"},
"firewall": map[string]interface{}{
"enabled": true,
"rules": rules,
},
}
data, _ := json.Marshal(config)
result, err := jsonToMarkdown(data)
blocks := splitBlocks(result)
// Each block should still have the path "firewall" → "rules" where applicable
visualReport(t, "Realistic: Nested config with 30 firewall rules", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks needed (got %d)", len(blocks)), len(blocks) >= 2),
check("contains 'firewall'", strings.Contains(result, "firewall")),
check("contains 'version'", strings.Contains(result, "version")),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 6: Integration — SimpleFormatReader
// ═══════════════════════════════════════════════════════════════════════════
func TestSimpleFormatReader_JSON(t *testing.T) {
reader := &SimpleFormatReader{}
input := `{"test": "integration", "count": 42}`
req := &types.ReadRequest{
FileName: "config.json",
FileType: "json",
FileContent: []byte(input),
}
result, err := reader.Read(context.Background(), req)
var resultStr string
if result != nil {
resultStr = result.MarkdownContent
}
visualReport(t, "SimpleFormatReader.Read() with .json file", input, resultStr, err, []checkResult{
check("no error", err == nil),
check("result not nil", result != nil),
check("markdown contains 'test'",
result != nil && strings.Contains(result.MarkdownContent, "test")),
check("markdown has code block",
result != nil && strings.Contains(result.MarkdownContent, "```json")),
check("output is valid JSON inside block",
result != nil && allBlocksValidJSON(result.MarkdownContent)),
})
}
func TestSimpleFormatReader_JSON_Invalid(t *testing.T) {
reader := &SimpleFormatReader{}
req := &types.ReadRequest{
FileName: "bad.json",
FileType: "json",
FileContent: []byte(`{not valid json}`),
}
_, err := reader.Read(context.Background(), req)
visualReport(t, "SimpleFormatReader with invalid JSON → error", `{not valid json}`, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'json'",
err != nil && strings.Contains(strings.ToLower(err.Error()), "json")),
})
}
func TestValidateJSONContent(t *testing.T) {
tests := []struct {
name string
data string
wantErr string
}{
{name: "object", data: `{"a":1}`},
{name: "array", data: `[1,2]`},
{name: "bom object", data: "\ufeff{\"a\":1}"},
{name: "empty", data: "", wantErr: "empty JSON content"},
{name: "jsonc", data: "{\n// x\n}", wantErr: "invalid JSON content"},
{name: "truncated", data: `{"a":`, wantErr: "invalid JSON content"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateJSONContent([]byte(tt.data))
if tt.wantErr == "" {
if err != nil {
t.Fatalf("ValidateJSONContent() err = %v", err)
}
return
}
if err == nil || err.Error() != tt.wantErr {
t.Fatalf("ValidateJSONContent() err = %v, want %q", err, tt.wantErr)
}
})
}
}
func TestIsSimpleFormat_JSON(t *testing.T) {
cases := []struct {
input string
want bool
}{
{"json", true}, {"JSON", true}, {".json", true}, {"Json", true},
{"txt", true}, {"csv", true},
{"pdf", false}, {"docx", false},
}
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: IsSimpleFormat() recognizes JSON")
t.Logf("─────────────────────────────────────────────────────────")
allPass := true
for _, tc := range cases {
got := IsSimpleFormat(tc.input)
icon := "✅"
if got != tc.want {
icon = "💥"
allPass = false
t.Errorf("IsSimpleFormat(%q) = %v, want %v", tc.input, got, tc.want)
}
t.Logf("%s IsSimpleFormat(%q) = %v (want %v)", icon, tc.input, got, tc.want)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 7: list-to-dict preprocessing
// ═══════════════════════════════════════════════════════════════════════════
func TestListToDictPreprocess(t *testing.T) {
// Simulate what json.Unmarshal produces: numbers become float64
input := []interface{}{"a", "b", map[string]interface{}{"nested": []interface{}{float64(1), float64(2)}}}
result := listToDictPreprocess(input)
dict, ok := result.(map[string]interface{})
if !ok {
t.Fatalf("expected map, got %T", result)
}
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: listToDictPreprocess")
t.Logf("─────────────────────────────────────────────────────────")
t.Logf("📥 INPUT: [\"a\", \"b\", {\"nested\": [1, 2]}]")
t.Logf("📤 OUTPUT: %s", formatValue(dict))
t.Logf("─────────────────────────────────────────────────────────")
checks := []checkResult{
check("top level is dict", ok),
check(`key "0" = "a"`, dict["0"] == "a"),
check(`key "1" = "b"`, dict["1"] == "b"),
}
// Check nested array also converted
if nested, ok2 := dict["2"].(map[string]interface{}); ok2 {
if innerNested, ok3 := nested["nested"].(map[string]interface{}); ok3 {
checks = append(checks, check(`nested array converted to dict`, innerNested["0"] == float64(1)))
} else {
checks = append(checks, check(`nested array converted to dict`, false))
}
}
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
t.Errorf("FAIL: %s", c.desc)
}
t.Logf("%s %s", icon, c.desc)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
func TestSetNestedDict(t *testing.T) {
d := map[string]interface{}{}
setNestedDict(d, []string{"config", "database", "host"}, "localhost")
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: setNestedDict path preservation")
t.Logf("─────────────────────────────────────────────────────────")
t.Logf("📥 path: [\"config\", \"database\", \"host\"]")
t.Logf("📥 value: \"localhost\"")
t.Logf("📤 result: %s", formatValue(d))
t.Logf("─────────────────────────────────────────────────────────")
// Verify the structure
config, ok1 := d["config"].(map[string]interface{})
db, ok2 := map[string]interface{}{}, false
host := ""
if ok1 {
db, ok2 = config["database"].(map[string]interface{})
}
if ok2 {
host, _ = db["host"].(string)
}
checks := []checkResult{
check(`d["config"] is dict`, ok1),
check(`d["config"]["database"] is dict`, ok2),
check(`d["config"]["database"]["host"] = "localhost"`, host == "localhost"),
}
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
t.Errorf("FAIL: %s", c.desc)
}
t.Logf("%s %s", icon, c.desc)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
@@ -0,0 +1,290 @@
package docparser
import (
"strings"
"academy/internal/types"
)
type markdownImageTargetSpan struct {
ImageStart int
TargetStart int
TargetEnd int
}
func scanMarkdownImageTargets(markdown string) []markdownImageTargetSpan {
var spans []markdownImageTargetSpan
for i := 0; i+1 < len(markdown); i++ {
if markdown[i] != '!' || markdown[i+1] != '[' || isEscaped(markdown, i) {
continue
}
altEnd := findMarkdownImageAltEnd(markdown, i+2)
if altEnd == -1 {
continue
}
targetStart := altEnd + 2
targetEnd, ok := findMarkdownImageTargetEnd(markdown, targetStart)
if !ok {
i = altEnd
continue
}
spans = append(spans, markdownImageTargetSpan{
ImageStart: i,
TargetStart: targetStart,
TargetEnd: targetEnd,
})
i = targetEnd
}
return spans
}
// StripMarkdownImages removes complete ![alt](destination) constructs,
// including destinations and titles that contain parentheses. Leftover
// prose is preserved so callers can tell whether a chunk still has
// extractable text after image placeholders are gone.
func StripMarkdownImages(markdown string) string {
spans := scanMarkdownImageTargets(markdown)
if len(spans) == 0 {
return markdown
}
var b strings.Builder
b.Grow(len(markdown))
last := 0
for _, span := range spans {
if span.ImageStart < last {
continue
}
b.WriteString(markdown[last:span.ImageStart])
last = span.TargetEnd + 1
if last > len(markdown) {
last = len(markdown)
}
}
b.WriteString(markdown[last:])
return b.String()
}
func findMarkdownImageAltEnd(markdown string, start int) int {
for i := start; i+1 < len(markdown); i++ {
if markdown[i] == ']' && markdown[i+1] == '(' && !isEscaped(markdown, i) {
return i
}
}
return -1
}
func findMarkdownImageTargetEnd(markdown string, start int) (int, bool) {
parenDepth := 1
inAngleDestination := false
seenNonSpace := false
var inQuote byte
for i := start; i < len(markdown); i++ {
ch := markdown[i]
if ch == '\\' {
i++
continue
}
if !seenNonSpace && !isMarkdownSpace(ch) {
seenNonSpace = true
if ch == '<' {
inAngleDestination = true
continue
}
}
if inAngleDestination {
if ch == '>' {
inAngleDestination = false
}
continue
}
if inQuote != 0 {
if ch == inQuote {
inQuote = 0
}
continue
}
if (ch == '"' || ch == '\'') && i > start && isMarkdownSpace(markdown[i-1]) {
inQuote = ch
continue
}
switch ch {
case '(':
parenDepth++
case ')':
parenDepth--
if parenDepth == 0 {
return i, true
}
}
}
return 0, false
}
func splitMarkdownImageTarget(
raw string,
refMap map[string]types.ImageRef,
) (path string, pathStart int, pathEnd int, ok bool) {
start, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if start >= end {
return "", 0, 0, false
}
trimmed := raw[start:end]
if _, found := refMap[trimmed]; found {
return trimmed, start, end, true
}
if raw[start] == '<' {
return splitAngleMarkdownImageTarget(raw, start, end, refMap)
}
titleStart, found := parseMarkdownImageTitleSuffix(trimmed)
if !found {
return "", 0, 0, false
}
pathEnd = start + titleStart
for pathEnd > start && isMarkdownSpace(raw[pathEnd-1]) {
pathEnd--
}
if pathEnd == start {
return "", 0, 0, false
}
path = raw[start:pathEnd]
if _, found := refMap[path]; !found {
return "", 0, 0, false
}
return path, start, pathEnd, true
}
func splitAngleMarkdownImageTarget(
raw string,
start int,
end int,
refMap map[string]types.ImageRef,
) (path string, pathStart int, pathEnd int, ok bool) {
closeIdx := -1
for i := start + 1; i < end; i++ {
if raw[i] == '>' && !isEscaped(raw, i) {
closeIdx = i
break
}
}
if closeIdx == -1 {
return "", 0, 0, false
}
path = raw[start+1 : closeIdx]
if _, found := refMap[path]; !found {
return "", 0, 0, false
}
if !isEmptyOrMarkdownImageTitleSuffix(raw[closeIdx+1 : end]) {
return "", 0, 0, false
}
return path, start + 1, closeIdx, true
}
func parseMarkdownImageTitleSuffix(raw string) (titleStart int, ok bool) {
_, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if end == 0 {
return 0, false
}
switch raw[end-1] {
case '"', '\'':
quote := raw[end-1]
for i := end - 2; i >= 0; i-- {
if raw[i] != quote || isEscaped(raw, i) {
continue
}
if i == 0 || !isMarkdownSpace(raw[i-1]) {
return 0, false
}
if markdownTitleHasBlankLine(raw[i+1 : end-1]) {
return 0, false
}
return i, true
}
case ')':
depth := 0
for i := end - 2; i >= 0; i-- {
if isEscaped(raw, i) {
continue
}
switch raw[i] {
case ')':
depth++
case '(':
if depth == 0 {
if i == 0 || !isMarkdownSpace(raw[i-1]) {
return 0, false
}
if markdownTitleHasBlankLine(raw[i+1 : end-1]) {
return 0, false
}
return i, true
}
depth--
}
}
}
return 0, false
}
func isEmptyOrMarkdownImageTitleSuffix(raw string) bool {
start, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if start == end {
return true
}
titleStart, ok := parseMarkdownImageTitleSuffix(raw[:end])
return ok && isAllMarkdownSpace(raw[:titleStart])
}
func markdownTitleHasBlankLine(title string) bool {
for _, line := range strings.Split(title, "\n") {
if strings.Trim(line, " \t") == "" {
return true
}
}
return false
}
func isAllMarkdownSpace(raw string) bool {
for i := 0; i < len(raw); i++ {
if !isMarkdownSpace(raw[i]) {
return false
}
}
return true
}
func trimMarkdownSpaceBounds(raw string, start int, end int) (int, int) {
for start < end && isMarkdownSpace(raw[start]) {
start++
}
for end > start && isMarkdownSpace(raw[end-1]) {
end--
}
return start, end
}
func isMarkdownSpace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
func isEscaped(s string, pos int) bool {
backslashes := 0
for i := pos - 1; i >= 0 && s[i] == '\\'; i-- {
backslashes++
}
return backslashes%2 == 1
}
@@ -0,0 +1,239 @@
package docparser
import (
"strings"
"testing"
"academy/internal/types"
)
func TestScanMarkdownImageTargets(t *testing.T) {
tests := []struct {
name string
input string
targets []string
}{
{
name: "without title",
input: `before ![a](images/a.png) after`,
targets: []string{`images/a.png`},
},
{
name: "double quoted title",
input: `![a](images/a.png "图")`,
targets: []string{`images/a.png "图"`},
},
{
name: "single quoted title",
input: `![a](images/a.png '图')`,
targets: []string{`images/a.png '图'`},
},
{
name: "parenthesized title",
input: `![a](images/a.png (图))`,
targets: []string{`images/a.png (图)`},
},
{
name: "title containing right paren",
input: `![a](images/a.png "阶段 1) 结果")`,
targets: []string{`images/a.png "阶段 1) 结果"`},
},
{
name: "title containing both parens",
input: `![a](images/a.png '阶段 (1) 结果')`,
targets: []string{`images/a.png '阶段 (1) 结果'`},
},
{
name: "escaped quote in title",
input: `![a](images/a.png "阶段 \"1\"")`,
targets: []string{`images/a.png "阶段 \"1\""`},
},
{
name: "multiline title",
input: "![a](images/a.png\n \"多行 title\")",
targets: []string{"images/a.png\n \"多行 title\""},
},
{
name: "spaced path",
input: `![a](images/第 1 页.png)`,
targets: []string{`images/第 1 页.png`},
},
{
name: "path containing balanced parens",
input: `![a](images/a_(1).png "title")`,
targets: []string{`images/a_(1).png "title"`},
},
{
name: "angle destination",
input: `![a](<images/a b.png> "title")`,
targets: []string{`<images/a b.png> "title"`},
},
{
name: "malformed image is skipped",
input: `![a](images/a.png "unterminated title) after ![b](images/b.png)`,
targets: []string{`images/b.png`},
},
{
name: "escaped image marker is skipped",
input: `\![a](images/a.png) ![b](images/b.png)`,
targets: []string{`images/b.png`},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spans := scanMarkdownImageTargets(tt.input)
if len(spans) != len(tt.targets) {
t.Fatalf("got %d spans, want %d: %#v", len(spans), len(tt.targets), spans)
}
for i, span := range spans {
got := tt.input[span.TargetStart:span.TargetEnd]
if got != tt.targets[i] {
t.Fatalf("target %d = %q, want %q", i, got, tt.targets[i])
}
}
})
}
}
func TestSplitMarkdownImageTarget(t *testing.T) {
refMap := map[string]types.ImageRef{
"images/a.png": {OriginalRef: "images/a.png"},
"images/第 1 页.png": {OriginalRef: "images/第 1 页.png"},
"images/a_(1).png": {OriginalRef: "images/a_(1).png"},
"images/第 1 页 (测试).gif": {OriginalRef: "images/第 1 页 (测试).gif"},
}
tests := []struct {
name string
raw string
wantPath string
wantText string
wantOK bool
}{
{
name: "without title",
raw: `images/a.png`,
wantPath: `images/a.png`,
wantText: `local://stored`,
wantOK: true,
},
{
name: "double quoted title",
raw: `images/a.png "图"`,
wantPath: `images/a.png`,
wantText: `local://stored "图"`,
wantOK: true,
},
{
name: "single quoted title",
raw: `images/a.png '图'`,
wantPath: `images/a.png`,
wantText: `local://stored '图'`,
wantOK: true,
},
{
name: "parenthesized title",
raw: `images/a.png (阶段 (1) 结果)`,
wantPath: `images/a.png`,
wantText: `local://stored (阶段 (1) 结果)`,
wantOK: true,
},
{
name: "multiline title",
raw: "images/a.png\n \"多行 title\"",
wantPath: `images/a.png`,
wantText: "local://stored\n \"多行 title\"",
wantOK: true,
},
{
name: "path with spaces wins without title",
raw: `images/第 1 页.png`,
wantPath: `images/第 1 页.png`,
wantText: `local://stored`,
wantOK: true,
},
{
name: "path with balanced parens",
raw: `images/a_(1).png "title"`,
wantPath: `images/a_(1).png`,
wantText: `local://stored "title"`,
wantOK: true,
},
{
name: "angle destination replaces only inner path",
raw: `<images/第 1 页 (测试).gif> "阶段 1) 图片"`,
wantPath: `images/第 1 页 (测试).gif`,
wantText: `<local://stored> "阶段 1) 图片"`,
wantOK: true,
},
{
name: "unknown reference",
raw: `images/missing.png "title"`,
wantOK: false,
},
{
name: "blank line in title is invalid",
raw: "images/a.png \"line1\n\nline2\"",
wantOK: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path, pathStart, pathEnd, ok := splitMarkdownImageTarget(tt.raw, refMap)
if ok != tt.wantOK {
t.Fatalf("ok = %v, want %v", ok, tt.wantOK)
}
if !ok {
return
}
if path != tt.wantPath {
t.Fatalf("path = %q, want %q", path, tt.wantPath)
}
replaced := tt.raw[:pathStart] + "local://stored" + tt.raw[pathEnd:]
if replaced != tt.wantText {
t.Fatalf("replacement = %q, want %q", replaced, tt.wantText)
}
if strings.Contains(replaced, tt.wantPath) {
t.Fatalf("replacement still contains original path: %q", replaced)
}
})
}
}
func TestStripMarkdownImages(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "simple image",
input: "before ![a](images/a.png) after",
want: "before after",
},
{
name: "title containing right paren",
input: `![a](images/a.png "阶段 1) 结果")`,
want: "",
},
{
name: "prose around image",
input: "See figure: ![fig](resource://x) below.",
want: "See figure: below.",
},
{
name: "escaped image marker is kept",
input: `\![a](images/a.png) kept`,
want: `\![a](images/a.png) kept`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StripMarkdownImages(tt.input); got != tt.want {
t.Fatalf("StripMarkdownImages(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
@@ -0,0 +1,549 @@
package docparser
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"sort"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
"github.com/google/uuid"
)
const (
defaultPollInterval = 3 * time.Second
// defaultCloudTimeout bounds how long one batch is polled;
// ACADEMY_MINERU_CLOUD_TIMEOUT overrides it for documents that take longer.
defaultCloudTimeout = 600 * time.Second
defaultBaseURL = "https://mineru.net/api/v4"
)
// MinerUCloudReader calls the MinerU Cloud API (mineru.net) to read/convert documents.
// Flow: POST /file-urls/batch → PUT file → poll GET /extract-results/batch/{batch_id}.
type MinerUCloudReader struct {
apiKey string
baseURL string
timeout time.Duration
pollInterval time.Duration
model string
formulaEnable bool
tableEnable bool
ocrEnable bool
language string
}
// NewMinerUCloudReader creates a reader from ParserEngineOverrides.
func NewMinerUCloudReader(overrides map[string]string) *MinerUCloudReader {
return &MinerUCloudReader{
apiKey: strings.TrimSpace(overrides["mineru_api_key"]),
baseURL: defaultBaseURL,
timeout: requestTimeoutFromEnv("ACADEMY_MINERU_CLOUD_TIMEOUT", defaultCloudTimeout),
pollInterval: defaultPollInterval,
model: stringOr(overrides["mineru_cloud_model"], "pipeline"),
formulaEnable: parseBoolOr(overrides["mineru_cloud_enable_formula"], true),
tableEnable: parseBoolOr(overrides["mineru_cloud_enable_table"], true),
ocrEnable: parseBoolOr(overrides["mineru_cloud_enable_ocr"], true),
language: stringOr(overrides["mineru_cloud_language"], "ch"),
}
}
func (c *MinerUCloudReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.apiKey == "" {
return &types.ReadResult{Error: "MinerU Cloud API key is not configured"}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[MinerUCloud] Parsing file=%s size=%d via %s", req.FileName, len(content), c.baseURL)
ext := filepath.Ext(req.FileName)
if ext == "" && req.FileType != "" {
ext = "." + req.FileType
}
if ext == "" {
ext = ".pdf"
}
fileName := strings.TrimSuffix(req.FileName, ext) + ext
if fileName == ext {
fileName = "document" + ext
}
batchID, uploadURL, err := c.applyUploadURLs(ctx, fileName, ext)
if err != nil {
return nil, fmt.Errorf("MinerU Cloud apply upload URLs: %w", err)
}
if err := c.uploadFile(ctx, uploadURL, content); err != nil {
return nil, fmt.Errorf("MinerU Cloud file upload: %w", err)
}
mdContent, imageRefs, contentList, err := c.pollBatchResult(ctx, batchID)
if err != nil {
return nil, fmt.Errorf("MinerU Cloud poll: %w", err)
}
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
// --- batch upload API ---
type batchApplyResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
BatchID string `json:"batch_id"`
FileURLs []string `json:"file_urls"`
} `json:"data"`
}
func (c *MinerUCloudReader) applyUploadURLs(ctx context.Context, fileName, ext string) (string, string, error) {
modelVersion := c.model
if strings.ToLower(ext) == ".html" {
modelVersion = "MinerU-HTML"
}
payload := map[string]interface{}{
"files": []map[string]string{{"name": fileName, "data_id": uuid.New().String()}},
"model_version": modelVersion,
"is_ocr": c.ocrEnable,
"enable_formula": c.formulaEnable,
"enable_table": c.tableEnable,
"language": c.language,
}
body, err := json.Marshal(payload)
if err != nil {
return "", "", fmt.Errorf("marshal payload: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/file-urls/batch", bytes.NewReader(body))
if err != nil {
return "", "", fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
httpReq.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return "", "", fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return "", "", fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody))
}
var result batchApplyResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", "", fmt.Errorf("decode response: %w", err)
}
if result.Code != 0 {
return "", "", fmt.Errorf("API error: %s", result.Msg)
}
if len(result.Data.FileURLs) == 0 {
return "", "", fmt.Errorf("API returned no file_urls")
}
logger.Infof(context.Background(), "[MinerUCloud] batch apply ok: batch_id=%s, urls=%d", result.Data.BatchID, len(result.Data.FileURLs))
return result.Data.BatchID, result.Data.FileURLs[0], nil
}
func (c *MinerUCloudReader) uploadFile(ctx context.Context, uploadURL string, content []byte) error {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(content))
if err != nil {
return fmt.Errorf("create PUT request: %w", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return fmt.Errorf("PUT upload: %w", err)
}
resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("PUT upload status %d", resp.StatusCode)
}
logger.Infof(context.Background(), "[MinerUCloud] file uploaded, status=%d", resp.StatusCode)
return nil
}
// --- polling ---
type batchPollResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
ExtractResult json.RawMessage `json:"extract_result"` // can be object or array
} `json:"data"`
}
type extractResultItem struct {
State string `json:"state"`
FileName string `json:"file_name"`
Markdown string `json:"markdown"`
Content string `json:"content"`
Text string `json:"text"`
ErrMsg string `json:"err_msg"`
Progress struct {
ExtractedPages int `json:"extracted_pages"`
TotalPages int `json:"total_pages"`
} `json:"extract_progress"`
FullZipURL string `json:"full_zip_url"`
}
func (c *MinerUCloudReader) pollBatchResult(
ctx context.Context, batchID string,
) (string, []types.ImageRef, []byte, error) {
deadline := time.Now().Add(c.timeout)
pollCount := 0
headers := map[string]string{
"Authorization": "Bearer " + c.apiKey,
}
for time.Now().Before(deadline) {
// Bail out promptly on caller cancellation instead of spinning:
// fetchBatchStatus fails immediately and sleepCtx returns at once on a
// cancelled ctx, so without this guard the loop busy-hammers the cloud
// API and floods logs until the deadline.
if err := ctx.Err(); err != nil {
return "", nil, nil, err
}
pollCount++
items, err := c.fetchBatchStatus(ctx, batchID, headers)
if err != nil {
logger.Errorf(context.Background(), "[MinerUCloud] poll #%d failed: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
if len(items) == 0 {
if pollCount <= 3 || pollCount%10 == 0 {
logger.Infof(context.Background(), "[MinerUCloud] poll #%d: extract_result empty, retrying", pollCount)
}
sleepCtx(ctx, c.pollInterval)
continue
}
item := items[0]
state := strings.ToLower(item.State)
if pollCount == 1 || pollCount%10 == 0 || state == "done" || state == "failed" {
logger.Infof(context.Background(), "[MinerUCloud] poll #%d: file=%s state=%s pages=%d/%d",
pollCount, item.FileName, state, item.Progress.ExtractedPages, item.Progress.TotalPages)
}
if state == "failed" {
return "", nil, nil, fmt.Errorf("MinerU Cloud task failed: %s", item.ErrMsg)
}
if state == "done" {
return c.extractDoneResult(ctx, &item)
}
sleepCtx(ctx, c.pollInterval)
}
return "", nil, nil, fmt.Errorf("MinerU Cloud task timed out after %s (%d polls)", c.timeout, pollCount)
}
func (c *MinerUCloudReader) fetchBatchStatus(ctx context.Context, batchID string, headers map[string]string) ([]extractResultItem, error) {
url := fmt.Sprintf("%s/extract-results/batch/%s", c.baseURL, batchID)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
httpReq.Header.Set(k, v)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read poll response body: %w", err)
}
var pollResp batchPollResponse
if err := json.Unmarshal(respBody, &pollResp); err != nil {
return nil, fmt.Errorf("decode poll response: %w", err)
}
if pollResp.Code != 0 {
return nil, fmt.Errorf("poll error code=%d msg=%s", pollResp.Code, pollResp.Msg)
}
if len(pollResp.Data.ExtractResult) == 0 {
return nil, nil
}
// Dump the raw extract_result JSON for debugging
rawExtract := string(pollResp.Data.ExtractResult)
if len(rawExtract) > 4000 {
logger.Infof(context.Background(), "[MinerUCloud] Raw extract_result (truncated to 4000 chars): %s ...", rawExtract[:4000])
} else {
logger.Infof(context.Background(), "[MinerUCloud] Raw extract_result: %s", rawExtract)
}
// Pretty-print the structure to reveal all available fields
var rawObj interface{}
if err := json.Unmarshal(pollResp.Data.ExtractResult, &rawObj); err == nil {
logResponseStructure("MinerUCloud", rawObj, "extract_result")
}
// The extract_result can be either a single object or an array
var items []extractResultItem
if pollResp.Data.ExtractResult[0] == '[' {
if err := json.Unmarshal(pollResp.Data.ExtractResult, &items); err != nil {
return nil, fmt.Errorf("decode extract_result array: %w", err)
}
} else {
var single extractResultItem
if err := json.Unmarshal(pollResp.Data.ExtractResult, &single); err != nil {
return nil, fmt.Errorf("decode extract_result object: %w", err)
}
items = []extractResultItem{single}
}
return items, nil
}
// extractDoneResult extracts markdown and images from a completed batch item.
// Prefers inline markdown/content fields; falls back to downloading full_zip_url.
func (c *MinerUCloudReader) extractDoneResult(
_ context.Context, item *extractResultItem,
) (string, []types.ImageRef, []byte, error) {
text := firstNonEmpty(item.Markdown, item.Content, item.Text)
if text != "" {
logger.Infof(context.Background(), "[MinerUCloud] parsed (inline), length=%d", len(text))
return text, nil, nil, nil
}
if item.FullZipURL == "" {
return "", nil, nil, fmt.Errorf("MinerU Cloud state=done but no markdown/content or full_zip_url")
}
md, imageRefs, contentList, err := downloadAndExtractZip(item.FullZipURL)
if err != nil {
return "", nil, nil, fmt.Errorf("extract zip: %w", err)
}
logger.Infof(context.Background(), "[MinerUCloud] parsed (zip), markdown=%d chars, images=%d", len(md), len(imageRefs))
return md, imageRefs, contentList, nil
}
// --- ZIP handling ---
// downloadAndExtractZip also returns the content_list of the package, if any.
func downloadAndExtractZip(zipURL string) (string, []types.ImageRef, []byte, error) {
if err := utils.ValidateURLForSSRF(zipURL); err != nil {
return "", nil, nil, fmt.Errorf("zip URL blocked by SSRF check: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Get(zipURL)
if err != nil {
return "", nil, nil, fmt.Errorf("download zip: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("download zip status %d", resp.StatusCode)
}
zipData, err := readResultPackage(resp.Body, maxResultPackageBytes)
if err != nil {
return "", nil, nil, fmt.Errorf("read zip body: %w", err)
}
md, imageRefs, err := extractMarkdownZip(zipData, "MinerUCloud")
if err != nil {
return "", nil, nil, err
}
return md, imageRefs, minerUContentListFromZip(zipData), nil
}
// extractMarkdownZip reads the shallowest .md file of a MinerU result package
// and the images it references, via markdown or inline HTML <img> syntax.
func extractMarkdownZip(zipData []byte, logLabel string) (string, []types.ImageRef, error) {
return extractMarkdownZipBounded(zipData, logLabel, maxZipImagesTotalBytes)
}
// extractMarkdownZipBounded is extractMarkdownZip with the accumulated-image
// budget as a parameter, so a test can exercise the limit without materialising
// the production figure.
func extractMarkdownZipBounded(zipData []byte, logLabel string, maxImages int64) (string, []types.ImageRef, error) {
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err != nil {
return "", nil, fmt.Errorf("open zip: %w", err)
}
// Find .md files
var mdFiles []string
entries := make(map[string]*zip.File)
for _, f := range zr.File {
entries[f.Name] = f
if strings.HasSuffix(f.Name, ".md") {
mdFiles = append(mdFiles, f.Name)
}
}
if len(mdFiles) == 0 {
return "", nil, fmt.Errorf("no .md file found in zip")
}
sort.Slice(mdFiles, func(i, j int) bool {
di, dj := strings.Count(mdFiles[i], "/"), strings.Count(mdFiles[j], "/")
if di != dj {
return di < dj
}
return mdFiles[i] < mdFiles[j]
})
mdText, err := readZipEntry(entries[mdFiles[0]])
if err != nil {
return "", nil, fmt.Errorf("read md file: %w", err)
}
mdDir := filepath.Dir(mdFiles[0])
// Extract referenced images
var imageRefs []types.ImageRef
// Every image below is kept in memory until the caller hands the slice on,
// so the package needs a total budget as well as a per-entry cap: a package
// of thousands of small entries expands without ever tripping the latter.
var imageBytes int64
seen := map[string]bool{}
for _, imgPath := range extractImageRefsFromContent(mdText) {
if strings.HasPrefix(imgPath, "http://") || strings.HasPrefix(imgPath, "https://") || strings.HasPrefix(imgPath, "data:") {
continue
}
if seen[imgPath] {
continue
}
seen[imgPath] = true
resolved := resolveInZip(imgPath, mdDir, entries)
if resolved == nil {
logger.Errorf(context.Background(), "[%s] image not found in zip: %s", logLabel, imgPath)
continue
}
imgData, err := readZipEntryBytes(resolved)
if err != nil {
logger.Errorf(context.Background(), "[%s] failed to read zip image %s: %v", logLabel, imgPath, err)
continue
}
if imageBytes+int64(len(imgData)) > maxImages {
return "", nil, fmt.Errorf("%w: images in %q exceed %d bytes",
errResultPackageTooLarge, logLabel, maxImages)
}
imageBytes += int64(len(imgData))
ext := strings.ToLower(filepath.Ext(resolved.Name))
if ext == "" {
ext = ".png"
}
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
mimeType = "image/png"
}
imageRefs = append(imageRefs, types.ImageRef{
Filename: filepath.Base(resolved.Name),
OriginalRef: imgPath,
MimeType: mimeType,
ImageData: imgData,
})
}
return mdText, imageRefs, nil
}
func resolveInZip(imgPath, mdDir string, entries map[string]*zip.File) *zip.File {
candidates := []string{strings.ReplaceAll(imgPath, "\\", "/")}
if decoded, err := url.PathUnescape(candidates[0]); err == nil && decoded != candidates[0] {
candidates = append(candidates, decoded)
}
for _, c := range candidates {
c = strings.TrimPrefix(c, "./")
if f, ok := entries[c]; ok {
return f
}
if mdDir != "" && mdDir != "." {
if f, ok := entries[mdDir+"/"+c]; ok {
return f
}
}
}
return nil
}
// readZipEntry reads a text entry (the package markdown) under the per-entry cap.
func readZipEntry(f *zip.File) (string, error) {
data, err := readZipEntryCapped(f, maxZipEntryBytes)
if err != nil {
return "", err
}
return string(data), nil
}
// readZipEntryBytes reads a binary entry (an extracted image) under the
// per-entry cap.
func readZipEntryBytes(f *zip.File) ([]byte, error) {
return readZipEntryCapped(f, maxZipEntryBytes)
}
// PingMinerUCloud checks if the MinerU Cloud API is reachable with the given API key.
func PingMinerUCloud(apiKey string) (bool, string) {
apiKey = strings.TrimSpace(apiKey)
if apiKey == "" {
return false, "未配置 MinerU Cloud API Key"
}
targetURL := defaultBaseURL + "/file-urls/batch"
payload := []byte(`{"files":[],"model_version":"pipeline"}`)
req, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewReader(payload))
if err != nil {
return false, fmt.Sprintf("构建请求失败: %v", err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 10 * time.Second,
MaxRedirects: 5,
})
resp, err := client.Do(req)
if err != nil {
return false, fmt.Sprintf("MinerU Cloud 不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return false, "MinerU Cloud API Key 无效"
}
return true, ""
}
@@ -0,0 +1,582 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
)
// defaultMinerUTimeout bounds one self-hosted parse; ACADEMY_MINERU_TIMEOUT
// overrides it for documents that take longer.
const defaultMinerUTimeout = 1000 * time.Second // large docs can take a while
var (
b64DataURIPattern = regexp.MustCompile(`^data:image/(\w+);base64,(.+)$`)
minerUFileTypePattern = regexp.MustCompile(`^[a-z0-9]+$`)
)
// MinerUReader calls a self-hosted MinerU API to read/convert documents.
// MinerU >= 4.0 is driven through the V1 API; older servers through the
// legacy /file_parse endpoint. The protocol is detected per request, so an
// in-place MinerU upgrade needs no configuration change.
type MinerUReader struct {
endpoint string
timeout time.Duration
apiKey string // V1 only: the server's --api-key
tier string // V1 only: flash, basic, standard, advanced; "" = server default
// Legacy (<= 3.x) only; MinerU 4.0 dropped these request parameters.
backend string // "pipeline", "vlm-*", "hybrid-*"
vlmServerURL string // vLLM server URL for vlm-http-client / hybrid-http-client
formulaEnable bool
tableEnable bool
language string
// Shared: legacy parse_method / V1 ocr_mode take the same values.
parseMethod string
}
// NewMinerUReader creates a reader from ParserEngineOverrides.
func NewMinerUReader(overrides map[string]string) *MinerUReader {
var legacyOCREnabled *bool
if raw, ok := overrides["mineru_enable_ocr"]; ok {
value := parseBoolOr(raw, true)
legacyOCREnabled = &value
}
c := &MinerUReader{
endpoint: strings.TrimRight(overrides["mineru_endpoint"], "/"),
timeout: requestTimeoutFromEnv("ACADEMY_MINERU_TIMEOUT", defaultMinerUTimeout),
apiKey: strings.TrimSpace(overrides["mineru_server_api_key"]),
tier: resolveMinerUTier(overrides["mineru_tier"]),
backend: stringOr(overrides["mineru_model"], "pipeline"),
vlmServerURL: overrides["mineru_vlm_server_url"],
formulaEnable: parseBoolOr(overrides["mineru_enable_formula"], true),
tableEnable: parseBoolOr(overrides["mineru_enable_table"], true),
parseMethod: types.ResolveMinerUParseMethod(overrides["mineru_parse_method"], legacyOCREnabled),
language: stringOr(overrides["mineru_language"], "ch"),
}
return c
}
// resolveMinerUTier keeps only tiers MinerU 4.0 understands; anything else
// falls back to the server's default selection.
func resolveMinerUTier(raw string) string {
tier := strings.ToLower(strings.TrimSpace(raw))
if _, ok := mineruV1Tiers[tier]; ok {
return tier
}
return ""
}
func (c *MinerUReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.endpoint == "" {
return &types.ReadResult{Error: "MinerU endpoint is not configured"}, nil
}
if err := validateMinerUOutboundURL(c.endpoint); err != nil {
return &types.ReadResult{Error: err.Error()}, nil
}
if c.vlmServerURL != "" {
if err := validateMinerUOutboundURL(c.vlmServerURL); err != nil {
return &types.ReadResult{Error: err.Error()}, nil
}
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
protocol, err := detectMinerUProtocol(ctx, utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: mineruV1APITimeout,
MaxRedirects: 5,
}), c.endpoint)
if err != nil {
return nil, fmt.Errorf("MinerU protocol detection: %w", err)
}
if protocol == minerUProtocolV1 {
logger.Infof(ctx, "[MinerU] Parsing file=%s size=%d via %s (V1 API)", req.FileName, len(content), c.endpoint)
return c.readV1(ctx, req)
}
logger.Infof(ctx, "[MinerU] Parsing file=%s size=%d via %s (legacy /file_parse)",
req.FileName, len(content), c.endpoint)
mdContent, imagesB64, contentList, err := c.callFileParse(ctx, content, req.FileName, req.FileType)
if err != nil {
return nil, fmt.Errorf("MinerU file_parse: %w", err)
}
// MinerU already returns markdown with embedded HTML blocks (e.g. <table>, <details>).
// Re-running the whole document through html-to-markdown corrupts valid markdown
// by escaping headings and image syntax. Only apply narrow compatibility fixes.
mdContent = normalizeMinerUMarkdown(mdContent)
// Process images: decode base64, build ImageRef list, replace refs in markdown
imageRefs, mdContent := c.processImages(mdContent, imagesB64)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[MinerU] Parsed successfully, markdown=%d chars, images=%d", len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
func (c *MinerUReader) readV1(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
client := newMinerUV1Client(c.endpoint, c.apiKey, c.timeout)
mdContent, imageRefs, contentList, err := client.ParseWithLayout(ctx, req.FileContent,
minerUUploadFileName(req.FileName, req.FileType),
minerUV1ParseOptions{Tier: c.tier, OCRMode: c.parseMethod})
if err != nil {
return nil, fmt.Errorf("MinerU V1: %w", err)
}
mdContent = normalizeMinerUMarkdown(mdContent)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(ctx, "[MinerU] Parsed successfully (V1), markdown=%d chars, images=%d", len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
type mineruFileEntry struct {
MDContent string `json:"md_content"`
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
// ContentList is the layout block list (page and box per block), as a
// JSON array or a string holding one depending on the MinerU version.
ContentList json.RawMessage `json:"content_list"`
}
func minerUCleanFileType(fileType string) string {
cleanType := strings.ToLower(strings.TrimSpace(fileType))
cleanType = strings.TrimPrefix(cleanType, ".")
if minerUFileTypePattern.MatchString(cleanType) {
return cleanType
}
return ""
}
func minerUUploadFileName(fileName, fileType string) string {
cleanName := strings.TrimSpace(fileName)
cleanName = strings.ReplaceAll(cleanName, `\`, "/")
cleanName = path.Base(cleanName)
cleanName = strings.Map(func(r rune) rune {
if r == '\r' || r == '\n' || r == 0 {
return -1
}
return r
}, cleanName)
cleanName = strings.TrimSpace(cleanName)
if cleanName != "" && cleanName != "." && cleanName != ".." && cleanName != "/" {
if filepath.Ext(cleanName) == "" {
if cleanType := minerUCleanFileType(fileType); cleanType != "" {
return cleanName + "." + cleanType
}
}
return cleanName
}
if cleanType := minerUCleanFileType(fileType); cleanType != "" {
return "document." + cleanType
}
return "document"
}
// minerUResultStem mirrors MinerU's upload.stem: the basename without extension.
func minerUResultStem(uploadFileName string) string {
stem := strings.TrimSuffix(path.Base(uploadFileName), filepath.Ext(uploadFileName))
if stem == "" || stem == "." {
return ""
}
return stem
}
func minerUResultLookupKeys(uploadFileName string) []string {
keys := make([]string, 0, 3)
if stem := minerUResultStem(uploadFileName); stem != "" {
keys = append(keys, stem)
}
return append(keys, "document", "files")
}
func parseMinerUFileParseResponse(respBody []byte, uploadFileName string) (string, map[string]string, string, error) {
var envelope struct {
Results map[string]mineruFileEntry `json:"results"`
}
if err := json.Unmarshal(respBody, &envelope); err != nil {
return "", nil, "", fmt.Errorf("decode response: %w", err)
}
if len(envelope.Results) == 0 {
return "", nil, "", nil
}
for _, key := range minerUResultLookupKeys(uploadFileName) {
if entry, ok := envelope.Results[key]; ok {
if entry.MDContent != "" || len(entry.Images) > 0 {
return entry.MDContent, entry.Images, key, nil
}
}
}
for key, entry := range envelope.Results {
if entry.MDContent != "" || len(entry.Images) > 0 {
return entry.MDContent, entry.Images, key, nil
}
}
return "", nil, "", nil
}
// minerUFileParseContentList returns the content_list of the result entry
// that supplied the markdown.
func minerUFileParseContentList(respBody []byte, resultKey string) json.RawMessage {
var envelope struct {
Results map[string]mineruFileEntry `json:"results"`
}
if json.Unmarshal(respBody, &envelope) != nil {
return nil
}
return envelope.Results[resultKey].ContentList
}
func (c *MinerUReader) callFileParse(
ctx context.Context,
content []byte,
fileName string,
fileType string,
) (string, map[string]string, json.RawMessage, error) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// Form fields
fields := map[string]string{
"return_md": "true",
"return_images": "true",
"table_enable": fmt.Sprintf("%v", c.tableEnable),
"formula_enable": fmt.Sprintf("%v", c.formulaEnable),
"parse_method": c.parseMethod,
"start_page_id": "0",
"end_page_id": "99999",
"backend": c.backend,
"response_format_zip": "false",
"return_middle_json": "false",
"return_model_output": "false",
"return_content_list": "true",
}
if c.language != "" {
fields["lang_list"] = c.language
}
if c.vlmServerURL != "" && (strings.HasPrefix(c.backend, "vlm-http-client") || strings.HasPrefix(c.backend, "hybrid-http-client")) {
fields["server_url"] = c.vlmServerURL
}
for k, v := range fields {
_ = writer.WriteField(k, v)
}
uploadFileName := minerUUploadFileName(fileName, fileType)
// File part
part, err := writer.CreateFormFile("files", uploadFileName)
if err != nil {
return "", nil, nil, fmt.Errorf("create form file: %w", err)
}
if _, err := part.Write(content); err != nil {
return "", nil, nil, fmt.Errorf("write file content: %w", err)
}
writer.Close()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint+"/file_parse", &body)
if err != nil {
return "", nil, nil, fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: c.timeout,
MaxRedirects: 5,
})
resp, err := client.Do(httpReq)
if err != nil {
return "", nil, nil, fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return "", nil, nil, fmt.Errorf("MinerU API status %d: %s", resp.StatusCode, string(respBody))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read response body: %w", err)
}
// Dump raw response for debugging (truncate if too large)
rawStr := string(respBody)
if len(rawStr) > 4000 {
logger.Infof(context.Background(), "[MinerU] Raw response (truncated to 4000 chars): %s ...", rawStr[:4000])
} else {
logger.Infof(context.Background(), "[MinerU] Raw response: %s", rawStr)
}
// Also pretty-print the top-level structure (without large base64 blobs)
var rawMap map[string]interface{}
if err := json.Unmarshal(respBody, &rawMap); err == nil {
c.logMinerUResponseStructure(rawMap, "")
}
mdContent, imagesB64, resultKey, err := parseMinerUFileParseResponse(respBody, uploadFileName)
if err != nil {
return "", nil, nil, err
}
if resultKey != "" {
logger.Infof(context.Background(), "[MinerU] Using response path: results.%s", resultKey)
return mdContent, imagesB64, minerUFileParseContentList(respBody, resultKey), nil
}
logger.Errorf(context.Background(), "[MinerU] Response has no markdown/images under results")
return "", nil, nil, nil
}
// processImages decodes base64 images from MinerU response and returns ImageRef list.
// It also replaces image references in the markdown content.
func (c *MinerUReader) processImages(mdContent string, imagesB64 map[string]string) ([]types.ImageRef, string) {
var refs []types.ImageRef
for ipath, b64Str := range imagesB64 {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
var imgBytes []byte
var ext string
if m := b64DataURIPattern.FindStringSubmatch(b64Str); len(m) == 3 {
ext = m[1]
decoded, err := base64.StdEncoding.DecodeString(m[2])
if err != nil {
logger.Errorf(context.Background(), "[MinerU] Failed to decode base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
} else {
// raw base64 without data URI prefix
decoded, err := base64.StdEncoding.DecodeString(b64Str)
if err != nil {
logger.Errorf(context.Background(), "[MinerU] Failed to decode raw base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
ext = strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs, mdContent
}
// logMinerUResponseStructure logs the structure of the MinerU API response.
func (c *MinerUReader) logMinerUResponseStructure(obj interface{}, prefix string) {
logResponseStructure("MinerU", obj, prefix)
}
// validateMinerUOutboundURL rejects MinerU endpoints that would reach private
// or otherwise restricted hosts when parsed or probed from the app server.
func validateMinerUOutboundURL(rawURL string) error {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
return nil
}
if err := utils.ValidateURLForSSRF(rawURL); err != nil {
return fmt.Errorf("MinerU URL blocked by SSRF check: %v", err)
}
return nil
}
// PingMinerU checks if the self-hosted MinerU service is reachable. For
// MinerU 4.0 it also verifies the configured API key, since /v1/health itself
// is served without authentication.
func PingMinerU(endpoint, apiKey string) (bool, string) {
endpoint = strings.TrimRight(endpoint, "/")
if endpoint == "" {
return false, "未配置 MinerU 端点"
}
if err := validateMinerUOutboundURL(endpoint); err != nil {
return false, err.Error()
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 5 * time.Second,
MaxRedirects: 5,
})
ctx := context.Background()
protocol, err := detectMinerUProtocol(ctx, client, endpoint)
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可用: %v", err)
}
if protocol == minerUProtocolV1 {
return pingMinerUV1Auth(ctx, client, endpoint, apiKey)
}
resp, err := client.Get(endpoint + "/docs")
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode >= 400 {
return false, fmt.Sprintf("MinerU 服务返回状态 %d", resp.StatusCode)
}
return true, ""
}
// pingMinerUV1Auth hits an authenticated V1 endpoint: a server started with
// --api-key answers 401 when the key is missing or wrong.
func pingMinerUV1Auth(ctx context.Context, client *http.Client, endpoint, apiKey string) (bool, string) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint+"/v1/parse/jobs?limit=1", nil)
if err != nil {
return false, fmt.Sprintf("构建请求失败: %v", err)
}
if apiKey = strings.TrimSpace(apiKey); apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
resp, err := client.Do(req)
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可达: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
if apiKey == "" {
return false, "MinerU 服务已启用鉴权,请配置 API Key"
}
return false, "MinerU API Key 无效"
}
return true, ""
}
// escapedImageSyntaxPattern matches markdown image references whose `[` was
// over-escaped to `\[` by html-to-markdown. The URL group mirrors the
// downstream image-extraction regex so escapes are only stripped for actual
// image references.
var escapedImageSyntaxPattern = regexp.MustCompile(`!\\\[(.*?)\\?\]\(([^()\n]*(?:\([^)]*\)[^()\n]*)*)\)`)
// escapedHeadingPattern restores markdown headings that were over-escaped to
// \# Heading. We only touch line-leading heading markers to avoid rewriting
// body text that intentionally contains escaped # characters.
var escapedHeadingPattern = regexp.MustCompile(`(?m)^\\(#{1,6})(\s+)`)
// unescapeMarkdownImageSyntax restores `![alt](url)` from html-to-markdown's
// over-escaped `!\[alt\](url)` form. Without this, the downstream image regex
// in ImageResolver fails to match and images are never persisted.
func unescapeMarkdownImageSyntax(content string) string {
return escapedImageSyntaxPattern.ReplaceAllString(content, "![$1]($2)")
}
func normalizeEscapedMarkdownHeadings(content string) string {
return escapedHeadingPattern.ReplaceAllString(content, `$1$2`)
}
func normalizeMinerUMarkdown(content string) string {
content = unescapeMarkdownImageSyntax(content)
content = normalizeEscapedMarkdownHeadings(content)
return content
}
func mineruImageOriginalRefs(mdContent, imagePath string) []string {
normalizedTarget := normalizeMinerUImagePath(imagePath)
if normalizedTarget == "" {
return nil
}
referenced := extractImageRefsFromContent(mdContent)
seen := make(map[string]struct{}, len(referenced))
var matched []string
for _, refPath := range referenced {
if normalizeMinerUImagePath(refPath) != normalizedTarget {
continue
}
if _, ok := seen[refPath]; ok {
continue
}
matched = append(matched, refPath)
seen[refPath] = struct{}{}
}
return matched
}
// imgMarkdownPatternAllowSpaces matches markdown image syntax while allowing
// spaces in the URL group, so that paths like "images/第 1 页.jpg" produced by
// MinerU on Chinese documents are still detected as image references.
var imgMarkdownPatternAllowSpaces = regexp.MustCompile(
`!\[(.*?)\]\(([^()\n]*(?:\([^)]*\)[^()\n]*)*)\)`,
)
func extractImageRefsFromContent(content string) []string {
var refs []string
for _, match := range imgMarkdownPatternAllowSpaces.FindAllStringSubmatch(content, -1) {
if len(match) >= 3 {
refs = append(refs, strings.TrimSpace(match[2]))
}
}
for _, match := range imgHTMLSrc.FindAllStringSubmatch(content, -1) {
if len(match) >= 3 {
refs = append(refs, match[2])
}
}
return refs
}
func normalizeMinerUImagePath(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
if decoded, err := url.PathUnescape(p); err == nil && decoded != "" {
p = decoded
}
p = strings.TrimPrefix(p, "./")
p = strings.TrimPrefix(p, "/")
p = strings.TrimPrefix(p, "images/")
return p
}
@@ -0,0 +1,20 @@
package docparser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateMinerUOutboundURL_RejectsLoopback(t *testing.T) {
err := validateMinerUOutboundURL("http://127.0.0.1:8080")
require.Error(t, err)
assert.Contains(t, err.Error(), "SSRF")
}
func TestPingMinerU_RejectsPrivateEndpoint(t *testing.T) {
ok, msg := PingMinerU("http://127.0.0.1:8080", "")
assert.False(t, ok)
assert.Contains(t, msg, "SSRF")
}
@@ -0,0 +1,321 @@
package docparser
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/types"
"academy/internal/utils"
)
func TestNewMinerUReaderResolvesParseMethod(t *testing.T) {
tests := []struct {
name string
overrides map[string]string
want string
}{
{name: "default is auto", overrides: map[string]string{}, want: "auto"},
{name: "legacy enabled becomes auto", overrides: map[string]string{"mineru_enable_ocr": "true"}, want: "auto"},
{name: "legacy disabled becomes text", overrides: map[string]string{"mineru_enable_ocr": "false"}, want: "txt"},
{name: "explicit method wins", overrides: map[string]string{"mineru_parse_method": "ocr", "mineru_enable_ocr": "false"}, want: "ocr"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reader := NewMinerUReader(tt.overrides)
if reader.parseMethod != tt.want {
t.Fatalf("parseMethod = %q, want %q", reader.parseMethod, tt.want)
}
})
}
}
func TestMinerUUploadFileName(t *testing.T) {
tests := []struct {
name string
fileName string
fileType string
want string
}{
{name: "original basename", fileName: "reports/Illustrator 研报.pdf", fileType: "pdf", want: "Illustrator 研报.pdf"},
{
name: "strip multipart controls",
fileName: "reports/\r\nIllustrator\x00 export.pdf",
fileType: "pdf",
want: "Illustrator export.pdf",
},
{name: "append extension from type", fileName: "report", fileType: "pdf", want: "report.pdf"},
{name: "fallback from bare type", fileType: "pdf", want: "document.pdf"},
{name: "fallback from dotted uppercase type", fileType: ".PDF", want: "document.pdf"},
{name: "fallback from path-only name", fileName: "/", fileType: "pdf", want: "document.pdf"},
{name: "legacy fallback without metadata", want: "document"},
{name: "reject unsafe fallback type", fileType: "../pdf", want: "document"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := minerUUploadFileName(tt.fileName, tt.fileType); got != tt.want {
t.Fatalf("minerUUploadFileName() = %q, want %q", got, tt.want)
}
})
}
}
func TestParseMinerUFileParseResponse(t *testing.T) {
tests := []struct {
name string
uploadFileName string
response map[string]any
wantMarkdown string
wantResultKey string
}{
{
name: "match upload stem",
uploadFileName: "Illustrator 研报.pdf",
response: map[string]any{
"results": map[string]any{
"Illustrator 研报": map[string]any{"md_content": "from-stem", "images": map[string]any{}},
},
},
wantMarkdown: "from-stem",
wantResultKey: "Illustrator 研报",
},
{
name: "legacy document key",
uploadFileName: "document",
response: map[string]any{
"results": map[string]any{
"document": map[string]any{"md_content": "legacy", "images": map[string]any{}},
},
},
wantMarkdown: "legacy",
wantResultKey: "document",
},
{
name: "files variant",
uploadFileName: "document.pdf",
response: map[string]any{
"results": map[string]any{
"files": map[string]any{"md_content": "from-files", "images": map[string]any{}},
},
},
wantMarkdown: "from-files",
wantResultKey: "files",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
respBody, err := json.Marshal(tt.response)
if err != nil {
t.Fatalf("marshal response: %v", err)
}
gotMarkdown, _, gotKey, err := parseMinerUFileParseResponse(respBody, tt.uploadFileName)
if err != nil {
t.Fatalf("parseMinerUFileParseResponse() error: %v", err)
}
if gotMarkdown != tt.wantMarkdown {
t.Fatalf("markdown = %q, want %q", gotMarkdown, tt.wantMarkdown)
}
if gotKey != tt.wantResultKey {
t.Fatalf("result key = %q, want %q", gotKey, tt.wantResultKey)
}
})
}
}
func TestMinerUReaderPreservesMultipartFilename(t *testing.T) {
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() {
utils.SetSSRFWhitelistFromRaw("")
})
const fileContent = "%PDF-1.7 synthetic test content"
tests := []struct {
name string
fileName string
fileType string
want string
}{
{name: "original basename", fileName: "reports/Illustrator 研报.pdf", fileType: "pdf", want: "Illustrator 研报.pdf"},
{
name: "strip multipart controls",
fileName: "reports/\r\nIllustrator\x00 export.pdf",
fileType: "pdf",
want: "Illustrator export.pdf",
},
{name: "fallback from bare type", fileType: "pdf", want: "document.pdf"},
{name: "fallback from dotted uppercase type", fileType: ".PDF", want: "document.pdf"},
{name: "fallback from path-only name", fileName: "/", fileType: "pdf", want: "document.pdf"},
{name: "legacy fallback without metadata", want: "document"},
{name: "reject unsafe fallback type", fileType: "../pdf", want: "document"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
type capturedRequest struct {
method string
path string
fileName string
content string
err error
}
captured := make(chan capturedRequest, 1)
uploadName := minerUUploadFileName(tt.fileName, tt.fileType)
resultStem := minerUResultStem(uploadName)
responseBody, err := json.Marshal(map[string]any{
"results": map[string]any{
resultStem: map[string]any{
"md_content": "ok",
"images": map[string]any{},
},
},
})
if err != nil {
t.Fatalf("marshal response: %v", err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/health" {
// MinerU <= 3.x has no V1 API.
http.NotFound(w, r)
return
}
got := capturedRequest{method: r.Method, path: r.URL.Path}
file, header, err := r.FormFile("files")
if err != nil {
got.err = err
} else {
got.fileName = header.Filename
content, readErr := io.ReadAll(file)
got.content = string(content)
got.err = readErr
_ = file.Close()
}
captured <- got
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(responseBody)
}))
defer server.Close()
reader := NewMinerUReader(map[string]string{"mineru_endpoint": server.URL})
result, err := reader.Read(context.Background(), &types.ReadRequest{
FileContent: []byte(fileContent),
FileName: tt.fileName,
FileType: tt.fileType,
})
if err != nil {
t.Fatalf("Read returned error: %v", err)
}
if result.MarkdownContent != "ok" {
t.Fatalf("MarkdownContent = %q, want %q", result.MarkdownContent, "ok")
}
request := <-captured
if request.err != nil {
t.Fatalf("capture multipart request: %v", request.err)
}
if request.method != http.MethodPost {
t.Errorf("method = %q, want %q", request.method, http.MethodPost)
}
if request.path != "/file_parse" {
t.Errorf("path = %q, want %q", request.path, "/file_parse")
}
if request.fileName != tt.want {
t.Errorf("multipart filename = %q, want %q", request.fileName, tt.want)
}
if request.content != fileContent {
t.Errorf("multipart content = %q, want %q", request.content, fileContent)
}
})
}
}
func TestNormalizeMinerUMarkdownPreservesMarkdownAndHTML(t *testing.T) {
input := strings.Join([]string{
"# Heading",
"",
"![](images/cover.jpg)",
"",
`<details><summary>text_image</summary>caption</details>`,
"",
`<table><tr><td><img src="images/profile.jpg"/></td></tr></table>`,
}, "\n")
got := normalizeMinerUMarkdown(input)
if !strings.Contains(got, "# Heading") {
t.Fatalf("expected heading to stay intact, got: %q", got)
}
if strings.Contains(got, `\# Heading`) {
t.Fatalf("expected heading to avoid escaped form, got: %q", got)
}
if !strings.Contains(got, "![](images/cover.jpg)") {
t.Fatalf("expected markdown image syntax to stay intact, got: %q", got)
}
if strings.Contains(got, `!\[](images/cover.jpg)`) {
t.Fatalf("expected markdown image syntax to avoid escaped form, got: %q", got)
}
if !strings.Contains(got, `<details><summary>text_image</summary>caption</details>`) {
t.Fatalf("expected details/summary block to be preserved, got: %q", got)
}
if !strings.Contains(got, `<img src="images/profile.jpg"/>`) {
t.Fatalf("expected html img tag to be preserved, got: %q", got)
}
}
func TestProcessImagesKeepsReferencedVariants(t *testing.T) {
reader := &MinerUReader{}
mdContent := strings.Join([]string{
"![](images/cover.jpg)",
`<img src="./images/profile.jpg"/>`,
`![](plain.jpg)`,
}, "\n")
png := createTestPNG(200, 150)
b64 := base64.StdEncoding.EncodeToString(png)
images := map[string]string{
"cover.jpg": "data:image/png;base64," + b64,
"profile.jpg": "data:image/png;base64," + b64,
"plain.jpg": "data:image/png;base64," + b64,
}
refs, gotMarkdown := reader.processImages(mdContent, images)
if gotMarkdown != mdContent {
t.Fatalf("processImages should not rewrite markdown content")
}
if len(refs) != 3 {
t.Fatalf("expected 3 image refs, got %d", len(refs))
}
}
// TestProcessImagesMatchesPathsWithSpaces guards against a regression where
// MinerU image filenames containing spaces (common on Chinese documents,
// e.g. "images/第 1 页.jpg") would be silently dropped because the markdown
// regex used to extract refs disallowed whitespace inside the URL group.
func TestProcessImagesMatchesPathsWithSpaces(t *testing.T) {
reader := &MinerUReader{}
mdContent := "![](images/第 1 页.jpg)"
png := createTestPNG(200, 150)
b64 := base64.StdEncoding.EncodeToString(png)
images := map[string]string{
"第 1 页.jpg": "data:image/png;base64," + b64,
}
refs, _ := reader.processImages(mdContent, images)
if len(refs) != 1 {
t.Fatalf("expected 1 image ref for path with spaces, got %d", len(refs))
}
if refs[0].OriginalRef != "images/第 1 页.jpg" {
t.Fatalf("unexpected OriginalRef: %q", refs[0].OriginalRef)
}
}
@@ -0,0 +1,298 @@
package docparser
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"html"
"math"
"regexp"
"sort"
"strings"
"academy/internal/sourceloc"
"academy/internal/types"
)
// minerUBBoxScale is the coordinate range of content_list bounding boxes:
// MinerU normalizes them to 0-1000 of the page, origin at the top-left.
const minerUBBoxScale = 1000.0
// minerUContentItem is one layout block of MinerU's content_list output.
type minerUContentItem struct {
Type string `json:"type"`
Text string `json:"text"`
PageIdx *int `json:"page_idx"`
BBox []float64 `json:"bbox"`
TableBody string `json:"table_body"`
TableCaption json.RawMessage `json:"table_caption"`
ImageCaption json.RawMessage `json:"image_caption"`
ListItems json.RawMessage `json:"list_items"`
CodeBody string `json:"code_body"`
}
var minerUHTMLTagRe = regexp.MustCompile(`<[^>]+>`)
// text is the block's searchable text, in the order MinerU renders it to
// markdown: captions above tables and figures, then the body.
func (it minerUContentItem) text() string {
parts := []string{it.Text}
parts = append(parts, rawStrings(it.TableCaption)...)
parts = append(parts, rawStrings(it.ImageCaption)...)
if it.TableBody != "" {
parts = append(parts, minerUHTMLTagRe.ReplaceAllString(it.TableBody, " "))
}
parts = append(parts, it.CodeBody)
parts = append(parts, rawStrings(it.ListItems)...)
return strings.TrimSpace(strings.Join(parts, " "))
}
// rawStrings reads a JSON string or array of strings.
func rawStrings(raw json.RawMessage) []string {
if len(raw) == 0 {
return nil
}
var list []string
if json.Unmarshal(raw, &list) == nil {
return list
}
var one string
if json.Unmarshal(raw, &one) == nil {
return []string{one}
}
return nil
}
// decodeMinerUContentList accepts the list itself or the list serialized as
// a JSON string, which is how some MinerU API versions return it.
func decodeMinerUContentList(raw []byte) []minerUContentItem {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
return nil
}
if raw[0] == '"' {
var inner string
if json.Unmarshal(raw, &inner) != nil {
return nil
}
raw = []byte(inner)
}
var items []minerUContentItem
if json.Unmarshal(raw, &items) != nil {
return nil
}
return items
}
// minerUContentListFromZip prefers supported MiddleJson 2.0 geometry and
// falls back to legacy content_list.json for older MinerU packages.
func minerUContentListFromZip(zipData []byte) []byte {
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err != nil {
return nil
}
var candidates []*zip.File
for _, f := range zr.File {
name := strings.ToLower(f.Name)
if strings.HasSuffix(name, "middle_json.json") || strings.HasSuffix(name, "content_list.json") {
candidates = append(candidates, f)
}
}
if len(candidates) == 0 {
return nil
}
sort.Slice(candidates, func(i, j int) bool {
mi,
mj := strings.HasSuffix(strings.ToLower(candidates[i].Name),
"middle_json.json"),
strings.HasSuffix(strings.ToLower(candidates[j].Name),
"middle_json.json")
if mi != mj {
return mi
}
di, dj := strings.Count(candidates[i].Name, "/"), strings.Count(candidates[j].Name, "/")
if di != dj {
return di < dj
}
return candidates[i].Name < candidates[j].Name
})
for _, candidate := range candidates {
data, err := readZipEntryCapped(candidate, maxZipEntryBytes)
if err != nil {
continue
}
if strings.HasSuffix(strings.ToLower(candidate.Name), "middle_json.json") {
var doc minerUMiddle
if json.Unmarshal(data, &doc) != nil || doc.Schema != "docvortex.middle" || doc.Version != "2.0" {
continue
}
}
return data
}
return nil
}
// minerUSourceBlocks aligns MinerU's layout blocks against its markdown so
// each paragraph, table and figure points back at its page and region. Only
// PDFs and images have pages a viewer can show; for office files MinerU's
// pages belong to an intermediate PDF, so those are left to the structure
// aligner.
func minerUSourceBlocks(markdown string, contentList []byte, fileType string) []types.SourceBlock {
ft := strings.ToLower(strings.TrimPrefix(fileType, "."))
if ft != "pdf" && !IsImageFormat(ft) {
return nil
}
raw := bytes.TrimSpace(contentList)
if len(raw) > 0 && raw[0] == '{' {
return minerUMiddleSourceBlocks(markdown, raw)
}
items := decodeMinerUContentList(contentList)
if len(items) == 0 {
return nil
}
units := make([]sourceloc.Unit, 0, len(items))
for i, it := range items {
if it.PageIdx == nil || *it.PageIdx < 0 {
continue
}
loc := types.SourceLocator{
Type: types.SourceLocatorPDF,
Page: *it.PageIdx + 1,
SourceID: fmt.Sprintf("mineru:legacy:%d:%d",
*it.PageIdx,
i),
}
if bbox, ok := minerUBBox(it.BBox); ok {
loc.BBox = bbox
}
units = append(units, sourceloc.Unit{Text: it.text(), Locator: loc})
}
return sourceloc.Align(markdown, units)
}
// minerUBBox converts a 0-1000 content_list box to page fractions. Boxes
// outside that range come from MinerU versions that report other units and
// are dropped rather than drawn in the wrong place.
func minerUBBox(b []float64) ([]float64, bool) {
if len(b) != 4 || b[2] <= b[0] || b[3] <= b[1] {
return nil, false
}
for _, v := range b {
if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > minerUBBoxScale {
return nil, false
}
}
out := make([]float64, 4)
for i, v := range b {
out[i] = v / minerUBBoxScale
}
return out, true
}
// MiddleJson 2.0 uses [0,1] normalized boxes (NOT legacy 0..1000).
// Child annotations keep their own geometry. Inline spans have no geometry.
type minerUMiddleBlock struct {
Type string `json:"type"`
Index *int `json:"index"`
BBox []float64 `json:"bbox"`
Content json.RawMessage `json:"content"`
}
type minerUMiddle struct {
Schema string `json:"schema"`
Version string `json:"schema_version"`
Pages []struct {
PageIdx *int `json:"page_idx"`
Blocks []minerUMiddleBlock `json:"blocks"`
} `json:"pages"`
}
func minerUMiddleSourceBlocks(markdown string, raw []byte) []types.SourceBlock {
var doc minerUMiddle
if json.Unmarshal(raw, &doc) != nil || doc.Schema != "docvortex.middle" || doc.Version != "2.0" {
return nil
}
var units []sourceloc.Unit
previousPage := -1
for _, page := range doc.Pages {
if page.PageIdx == nil || *page.PageIdx <= previousPage {
return nil
}
previousPage = *page.PageIdx
previousBlock := -1
for _, block := range page.Blocks {
if block.Index == nil || *block.Index <= previousBlock {
return nil
}
previousBlock = *block.Index
ref := fmt.Sprintf("mineru:2:%d:%d", *page.PageIdx, *block.Index)
units = append(units, minerUMiddleUnits(block, *page.PageIdx+1, ref, nil)...)
}
}
return sourceloc.Align(markdown, units)
}
func minerUMiddleUnits(block minerUMiddleBlock, page int, ref string, parentBox []float64) []sourceloc.Unit {
box := block.BBox
if len(box) == 0 {
box = parentBox
}
loc := types.SourceLocator{Type: types.SourceLocatorPDF, Page: page, SourceID: ref}
if normalizedMinerUBox(box) {
loc.BBox = append([]float64(nil), box...)
}
// These containers contain blocks; text and hyperlinks contain inline spans.
switch block.Type {
case "list", "index", "table", "image", "chart", "code":
var children []minerUMiddleBlock
if json.Unmarshal(block.Content, &children) != nil {
return nil
}
var out []sourceloc.Unit
for i, child := range children {
out = append(out, minerUMiddleUnits(child, page, fmt.Sprintf("%s/%d", ref, i), box)...)
}
return out
default:
text := minerUMiddleText(block.Content)
if block.Type == "table_body" || block.Type == "chart_body" {
text = html.UnescapeString(minerUHTMLTagRe.ReplaceAllString(text, " "))
}
if strings.TrimSpace(text) == "" {
return nil
}
return []sourceloc.Unit{{Text: text, Locator: loc}}
}
}
func minerUMiddleText(raw json.RawMessage) string {
var text string
if json.Unmarshal(raw, &text) == nil {
return text
}
var spans []struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(raw, &spans) != nil {
return ""
}
var out strings.Builder
for _, span := range spans {
out.WriteString(minerUMiddleText(span.Content))
}
return out.String()
}
func normalizedMinerUBox(box []float64) bool {
if len(box) != 4 || box[0] >= box[2] || box[1] >= box[3] {
return false
}
for _, v := range box {
if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 1 {
return false
}
}
return true
}
@@ -0,0 +1,172 @@
package docparser
import (
"archive/zip"
"bytes"
"encoding/json"
"math"
"testing"
"github.com/stretchr/testify/require"
)
// Contract fixture for DocVortex MiddleJson 2.0. Bboxes are normalized
// fractions, page indices are original source indices, and captions are
// child blocks. This is deliberately not a legacy content_list payload.
const middleFixture = `{
"schema": "docvortex.middle",
"schema_version": "2.0",
"is_full_document": true,
"metadata": {
"file_suffix": "pdf",
"producer": {
"name": "mineru",
"version": "4.0.0"
}
},
"pages": [
{
"page_idx": 4,
"blocks": [
{
"type": "text",
"index": 0,
"bbox": [
0.1,
0.2,
0.9,
0.3
],
"content": [
{
"type": "text",
"content": "设备"
},
{
"type": "hyperlink",
"url": "https://example.org",
"content": [
{
"type": "text",
"content": "验收合格"
}
]
}
]
},
{
"type": "table",
"index": 1,
"bbox": [
0.1,
0.4,
0.9,
0.8
],
"content": [
{
"type": "table_caption",
"bbox": [
0.1,
0.4,
0.9,
0.45
],
"content": [
{
"type": "text",
"content": "设备参数表"
}
]
},
{
"type": "table_body",
"bbox": [
0.1,
0.46,
0.9,
0.8
],
"content": "<table><tr><td>限值</td><td>1.5毫米</td></tr></table>"
}
]
}
]
}
]
}`
func TestMinerUMiddleNormalizedGeometryAndNestedBlocks(t *testing.T) {
blocks := minerUSourceBlocks("设备验收合格\n\n设备参数表\n\n|限值|1.5毫米|", []byte(middleFixture), "pdf")
require.Len(t, blocks, 3)
require.Equal(t, 5, blocks[0].Locator.Page)
require.Equal(t, []float64{0.1, 0.2, 0.9, 0.3}, blocks[0].Locator.BBox)
require.Equal(t, "mineru:2:4:0", blocks[0].Locator.SourceID)
require.Equal(t, "exact", blocks[0].Locator.Mapping)
require.Equal(t, []float64{0.1, 0.46, 0.9, 0.8}, blocks[2].Locator.BBox)
}
func TestMinerUMiddleZIPPreferredToLegacy(t *testing.T) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
for name, body := range map[string]string{
"markdown.md": "设备验收合格",
"middle_json.json": middleFixture,
"doc_content_list.json": "[]",
} {
w, err := z.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(body))
require.NoError(t, err)
}
require.NoError(t, z.Close())
require.JSONEq(t, middleFixture, string(minerUContentListFromZip(buf.Bytes())))
}
func TestMinerUMiddleRejectsUnknownSchemaAndInvalidIndices(t *testing.T) {
for _, mutate := range []func(map[string]any){
func(d map[string]any) { d["schema"] = "docvortex.model" },
func(d map[string]any) { d["schema_version"] = "9.0" },
func(d map[string]any) { delete(d["pages"].([]any)[0].(map[string]any), "page_idx") },
func(d map[string]any) { d["pages"].([]any)[0].(map[string]any)["page_idx"] = -1 },
} {
var d map[string]any
require.NoError(t, json.Unmarshal([]byte(middleFixture), &d))
mutate(d)
raw, err := json.Marshal(d)
require.NoError(t, err)
require.Empty(t, minerUSourceBlocks("设备验收合格", raw, "pdf"))
}
}
func TestMinerULegacyMissingPageIsNotPageOne(t *testing.T) {
require.Empty(t, minerUSourceBlocks("设备验收合格", []byte(`[{"type":"text","text":"设备验收合格"}]`), "pdf"))
}
func TestMinerUBoxesRejectNonFiniteAndWrongUnits(t *testing.T) {
for _, box := range [][]float64{{0, 0, math.NaN(), 1}, {0, 0, math.Inf(1), 1}, {0, 0, 900, 600}, {.9, 0, .1, 1}} {
require.False(t, normalizedMinerUBox(box))
}
_, ok := minerUBBox([]float64{0, 0, math.NaN(), 100})
require.False(t, ok)
}
func TestMinerULegacyZIPWithUnsupportedMiddleKeepsContentList(t *testing.T) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
legacy := `[{"type":"text","text":"设备验收合格","page_idx":1,"bbox":[100,200,900,300]}]`
for name, body := range map[string]string{
"doc_middle_json.json": `{"pdf_info":[]}`,
"doc_content_list.json": legacy,
} {
w, err := z.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(body))
require.NoError(t, err)
}
require.NoError(t, z.Close())
blocks := minerUSourceBlocks("设备验收合格", minerUContentListFromZip(buf.Bytes()), "pdf")
require.Len(t, blocks, 1)
require.Equal(t, 2, blocks[0].Locator.Page)
require.Equal(t, []float64{.1, .2, .9, .3}, blocks[0].Locator.BBox)
}
@@ -0,0 +1,117 @@
package docparser
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
func TestMinerUTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", defaultMinerUTimeout},
{"whitespace", " ", defaultMinerUTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 5400s ", 90 * time.Minute},
{"invalid", "invalid", defaultMinerUTimeout},
{"unitless", "5400", defaultMinerUTimeout},
{"zero", "0s", defaultMinerUTimeout},
{"negative", "-1s", defaultMinerUTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", tt.value)
assert.Equal(t, tt.want, NewMinerUReader(nil).timeout)
})
}
}
// The configured timeout, not the old hardcoded 1000s, must end a parse on
// both protocols, and it must fire before the caller's own deadline.
func TestMinerUReaderHonorsConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
req := &types.ReadRequest{FileContent: []byte("%PDF"), FileName: "a.pdf", FileType: "pdf"}
t.Run("v1", func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", "200ms")
statuses := make([]string, 1000)
for i := range statuses {
statuses[i] = "running"
}
fake := &fakeMinerUV1{t: t, pollStatuses: statuses}
server := httptest.NewServer(fake.handler())
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewMinerUReader(map[string]string{"mineru_endpoint": server.URL}).Read(ctx, req)
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.NoError(t, ctx.Err(), "the configured timeout, not the caller's deadline, should stop the parse")
assert.True(t, fake.canceled, "abandoned job should be canceled on the server")
})
t.Run("legacy", func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", "100ms")
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/health" {
http.NotFound(w, r)
return
}
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-r.Context().Done():
case <-release:
}
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewMinerUReader(map[string]string{"mineru_endpoint": server.URL}).Read(ctx, req)
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.NoError(t, ctx.Err(), "the configured timeout, not the caller's deadline, should stop the parse")
})
}
func TestMinerUCloudTimeoutConfig(t *testing.T) {
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "")
assert.Equal(t, defaultCloudTimeout, NewMinerUCloudReader(nil).timeout)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "45m")
assert.Equal(t, 45*time.Minute, NewMinerUCloudReader(nil).timeout)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "0s")
assert.Equal(t, defaultCloudTimeout, NewMinerUCloudReader(nil).timeout)
}
func TestMinerUCloudPollStopsAtConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "200ms")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"code":0,"data":{"extract_result":[{"state":"running"}]}}`)
}))
defer server.Close()
reader := NewMinerUCloudReader(nil)
reader.baseURL = server.URL
reader.pollInterval = 10 * time.Millisecond
start := time.Now()
_, _, _, err := reader.pollBatchResult(context.Background(), "batch-1")
require.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("timed out after %s", 200*time.Millisecond))
assert.Less(t, time.Since(start), 5*time.Second)
}
@@ -0,0 +1,606 @@
package docparser
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
)
// MinerU 4.0 replaced the synchronous /file_parse endpoint with the V1 API:
// upload → parse job → poll → download artifacts. See
// https://opendatalab.github.io/MinerU/usage/http_api/.
const (
mineruV1PollInitial = 2 * time.Second
mineruV1PollMax = 30 * time.Second
mineruV1APITimeout = 30 * time.Second
mineruV1MaxZipBytes = 1 << 30
mineruV1CancelBudget = 10 * time.Second
)
// MinerU V1 tiers accepted by POST /v1/parse/jobs. An empty tier means the
// server's default selection policy (standard → basic for PDF/image).
var mineruV1Tiers = map[string]struct{}{
"flash": {},
"basic": {},
"standard": {},
"advanced": {},
}
type minerUProtocol int
const (
minerUProtocolLegacy minerUProtocol = iota // MinerU <= 3.x: POST /file_parse
minerUProtocolV1 // MinerU >= 4.0: /v1/*
)
// minerUV1Client talks to any MinerU V1 deployment (self-hosted api-server or
// the official mineru.net/api).
type minerUV1Client struct {
baseURL string // without the /v1 suffix
apiKey string
apiClient *http.Client // small JSON calls
bulkClient *http.Client // byte upload and artifact download
pollInitial time.Duration
pollMax time.Duration
jobTimeout time.Duration
maxZipBytes int64
logLabel string
cancelBudget time.Duration
}
type minerUV1ParseOptions struct {
Tier string // "" → server default
OCRMode string // auto, txt, ocr
}
func newMinerUV1Client(baseURL, apiKey string, jobTimeout time.Duration) *minerUV1Client {
return &minerUV1Client{
baseURL: strings.TrimRight(baseURL, "/"),
apiKey: strings.TrimSpace(apiKey),
apiClient: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: mineruV1APITimeout,
MaxRedirects: 5,
}),
bulkClient: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: jobTimeout,
MaxRedirects: 5,
}),
pollInitial: mineruV1PollInitial,
pollMax: mineruV1PollMax,
jobTimeout: jobTimeout,
maxZipBytes: mineruV1MaxZipBytes,
logLabel: "MinerU",
cancelBudget: mineruV1CancelBudget,
}
}
// --- wire types ---
type minerUV1ErrorEnvelope struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code"`
} `json:"error"`
}
type minerUV1File struct {
ID string `json:"id"`
}
type minerUV1Upload struct {
ID string `json:"id"`
Status string `json:"status"`
UploadURL string `json:"upload_url"`
UploadMethod string `json:"upload_method"`
UploadHeaders map[string]string `json:"upload_headers"`
File *minerUV1File `json:"file"`
}
type minerUV1FileRef struct {
FileID string `json:"file_id"`
Bytes int64 `json:"bytes"`
}
type minerUV1JobFile struct {
Name string `json:"name"`
Status string `json:"status"`
OutputFiles map[string]minerUV1FileRef `json:"output_files"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
Parse *struct {
ModelUsed string `json:"model_used"`
DurationMS int64 `json:"duration_ms"`
ParserVersion string `json:"parser_version"`
} `json:"parse"`
}
type minerUV1Job struct {
JobID string `json:"job_id"`
Status string `json:"status"`
Tier string `json:"tier"`
Files []minerUV1JobFile `json:"files"`
}
func minerUV1JobTerminal(status string) bool {
switch status {
case "completed", "partial", "failed", "canceled":
return true
}
return false
}
// --- protocol detection ---
// detectMinerUProtocol probes GET /v1/health. MinerU 4.0 answers 200 (or 503
// while models are still preloading); older servers have no such route and
// answer 404/405.
func detectMinerUProtocol(ctx context.Context, client *http.Client, endpoint string) (minerUProtocol, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint+"/v1/health", nil)
if err != nil {
return minerUProtocolLegacy, fmt.Errorf("create health request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return minerUProtocolLegacy, fmt.Errorf("MinerU service unreachable: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
switch resp.StatusCode {
case http.StatusOK:
var health struct {
Status string `json:"status"`
}
if err := json.Unmarshal(body, &health); err != nil || health.Status != "ok" {
return minerUProtocolLegacy, fmt.Errorf("unexpected /v1/health response: %s",
truncateForLog(string(body), 300))
}
return minerUProtocolV1, nil
case http.StatusNotFound, http.StatusMethodNotAllowed:
return minerUProtocolLegacy, nil
default:
if msg := minerUV1ErrorMessage(body); msg != "" {
return minerUProtocolV1, fmt.Errorf("MinerU service not ready (status %d): %s", resp.StatusCode, msg)
}
return minerUProtocolLegacy, fmt.Errorf("MinerU /v1/health status %d: %s",
resp.StatusCode, truncateForLog(string(body), 300))
}
}
func minerUV1ErrorMessage(body []byte) string {
var env minerUV1ErrorEnvelope
if err := json.Unmarshal(body, &env); err != nil {
return ""
}
if env.Error.Code != "" && env.Error.Message != "" {
return env.Error.Code + ": " + env.Error.Message
}
return firstNonEmpty(env.Error.Message, env.Error.Code)
}
func truncateForLog(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
// --- parse flow ---
// Parse uploads content, runs a parse job and returns the markdown and
// images extracted from the job's zip artifact.
func (c *minerUV1Client) Parse(
ctx context.Context,
content []byte,
fileName string,
opts minerUV1ParseOptions,
) (string, []types.ImageRef, error) {
md, refs, _, err := c.ParseWithLayout(ctx, content, fileName, opts)
return md, refs, err
}
// ParseWithLayout is Parse plus the package's content_list, the per-block
// page and box layout (nil when the package carried none).
func (c *minerUV1Client) ParseWithLayout(
ctx context.Context,
content []byte,
fileName string,
opts minerUV1ParseOptions,
) (string, []types.ImageRef, []byte, error) {
ctx, cancel := context.WithTimeout(ctx, c.jobTimeout)
defer cancel()
fileID, err := c.upload(ctx, content, fileName)
if err != nil {
return "", nil, nil, fmt.Errorf("upload: %w", err)
}
jobID, err := c.createJob(ctx, fileID, opts)
if err != nil {
return "", nil, nil, fmt.Errorf("create parse job: %w", err)
}
logger.Infof(ctx, "[%s] parse job created: job_id=%s file_id=%s tier=%q ocr_mode=%s",
c.logLabel, jobID, fileID, opts.Tier, opts.OCRMode)
job, err := c.waitJob(ctx, jobID)
if err != nil {
c.cancelJob(jobID)
return "", nil, nil, err
}
zipRef, err := minerUV1ZipOutput(job)
if err != nil {
return "", nil, nil, err
}
zipData, err := c.downloadFile(ctx, zipRef.FileID)
if err != nil {
return "", nil, nil, fmt.Errorf("download zip artifact: %w", err)
}
md, imageRefs, err := extractMarkdownZip(zipData, c.logLabel)
if err != nil {
return "", nil, nil, fmt.Errorf("extract zip artifact: %w", err)
}
return md, imageRefs, minerUContentListFromZip(zipData), nil
}
func (c *minerUV1Client) upload(ctx context.Context, content []byte, fileName string) (string, error) {
sum := sha256.Sum256(content)
sha := hex.EncodeToString(sum[:])
var created minerUV1Upload
err := c.doJSON(ctx, http.MethodPost, "/v1/uploads", map[string]interface{}{
"filename": fileName,
"bytes": len(content),
"mime_type": minerUV1MimeType(fileName),
"purpose": "parse",
"sha256sum": sha,
}, &created)
if err != nil {
return "", err
}
switch created.Status {
case "completed":
// Same bytes already stored on the server: no transfer needed.
if created.File == nil || created.File.ID == "" {
return "", fmt.Errorf("upload completed without file id")
}
return created.File.ID, nil
case "pending":
default:
return "", fmt.Errorf("unexpected upload status %q", created.Status)
}
if created.ID == "" || created.UploadURL == "" {
return "", fmt.Errorf("pending upload missing id or upload_url")
}
if err := c.putBytes(ctx, &created, content); err != nil {
return "", err
}
var completed minerUV1Upload
err = c.doJSON(ctx, http.MethodPost, "/v1/uploads/"+url.PathEscape(created.ID)+"/complete",
map[string]string{"sha256sum": sha}, &completed)
if err != nil {
return "", fmt.Errorf("complete upload: %w", err)
}
if completed.File == nil || completed.File.ID == "" {
return "", fmt.Errorf("complete upload returned no file id (status %q)", completed.Status)
}
return completed.File.ID, nil
}
// putBytes sends the file to the URL returned by POST /v1/uploads. The MinerU
// API key is attached only when that URL is same-origin with the configured
// endpoint: the official API hands out pre-signed object-storage URLs that
// carry their own authorization and must never receive our key.
func (c *minerUV1Client) putBytes(ctx context.Context, up *minerUV1Upload, content []byte) error {
target, err := c.resolveURL(up.UploadURL)
if err != nil {
return fmt.Errorf("invalid upload_url: %w", err)
}
method := strings.ToUpper(stringOr(up.UploadMethod, http.MethodPut))
req, err := http.NewRequestWithContext(ctx, method, target.String(), bytes.NewReader(content))
if err != nil {
return fmt.Errorf("create upload request: %w", err)
}
for k, v := range up.UploadHeaders {
req.Header.Set(k, v)
}
if c.sameOrigin(target) {
c.setAuth(req)
}
resp, err := c.bulkClient.Do(req)
if err != nil {
return fmt.Errorf("upload bytes: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
return fmt.Errorf("upload bytes status %d: %s", resp.StatusCode, truncateForLog(string(body), 300))
}
return nil
}
func (c *minerUV1Client) createJob(ctx context.Context, fileID string, opts minerUV1ParseOptions) (string, error) {
payload := map[string]interface{}{
"files": []map[string]interface{}{
{"source": map[string]string{"type": "file_id", "file_id": fileID}},
},
"output_formats": []string{"zip"},
}
if opts.Tier != "" {
payload["tier"] = opts.Tier
}
if opts.OCRMode != "" {
payload["ocr_mode"] = opts.OCRMode
}
var job minerUV1Job
if err := c.doJSON(ctx, http.MethodPost, "/v1/parse/jobs", payload, &job); err != nil {
return "", err
}
if job.JobID == "" {
return "", fmt.Errorf("response has no job_id")
}
return job.JobID, nil
}
func (c *minerUV1Client) waitJob(ctx context.Context, jobID string) (*minerUV1Job, error) {
interval := c.pollInitial
for poll := 1; ; poll++ {
var job minerUV1Job
err := c.doJSON(ctx, http.MethodGet, "/v1/parse/jobs/"+url.PathEscape(jobID), nil, &job)
if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("parse job %s: %w", jobID, ctxErr)
}
var apiErr *minerUV1APIError
if errors.As(err, &apiErr) && apiErr.status == http.StatusNotFound {
// Job state lives in process memory; a restarted server forgets it.
return nil, fmt.Errorf("parse job %s no longer exists (MinerU restarted?): %w", jobID, err)
}
logger.Warnf(ctx, "[%s] poll #%d for job %s failed: %v", c.logLabel, poll, jobID, err)
} else {
if poll == 1 || poll%10 == 0 || minerUV1JobTerminal(job.Status) {
logger.Infof(ctx, "[%s] poll #%d: job=%s status=%s", c.logLabel, poll, jobID, job.Status)
}
if minerUV1JobTerminal(job.Status) {
return &job, nil
}
}
sleepCtx(ctx, interval)
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("parse job %s: %w", jobID, ctxErr)
}
interval *= 2
if interval > c.pollMax {
interval = c.pollMax
}
}
}
// cancelJob best-effort cancels a job we stopped waiting for so the server
// does not keep burning GPU time on it. It runs on a fresh context because the
// caller's context is usually already done.
func (c *minerUV1Client) cancelJob(jobID string) {
ctx, cancel := context.WithTimeout(context.Background(), c.cancelBudget)
defer cancel()
if err := c.doJSON(ctx, http.MethodDelete, "/v1/parse/jobs/"+url.PathEscape(jobID), nil, nil); err != nil {
logger.Warnf(ctx, "[%s] cancel job %s: %v", c.logLabel, jobID, err)
}
}
// minerUV1ZipOutput returns the zip artifact of the single submitted file, or
// the per-file error when parsing did not succeed.
func minerUV1ZipOutput(job *minerUV1Job) (minerUV1FileRef, error) {
if len(job.Files) == 0 {
return minerUV1FileRef{}, fmt.Errorf("parse job %s ended %s without file results", job.JobID, job.Status)
}
f := job.Files[0]
if f.Status != "completed" {
reason := job.Status
if f.Error != nil {
reason = firstNonEmpty(strings.TrimSpace(f.Error.Code+": "+f.Error.Message), job.Status)
}
return minerUV1FileRef{}, fmt.Errorf("parse job %s %s: %s", job.JobID, job.Status, reason)
}
ref, ok := f.OutputFiles["zip"]
if !ok || ref.FileID == "" {
return minerUV1FileRef{}, fmt.Errorf("parse job %s completed without zip output", job.JobID)
}
return ref, nil
}
func (c *minerUV1Client) downloadFile(ctx context.Context, fileID string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
c.baseURL+"/v1/files/"+url.PathEscape(fileID)+"/content", nil)
if err != nil {
return nil, err
}
// Go drops Authorization when following a redirect to another host, so a
// 302 to a CDN (official API) does not leak the key.
c.setAuth(req)
resp, err := c.bulkClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
return nil, newMinerUV1APIError(resp.StatusCode, body)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, c.maxZipBytes+1))
if err != nil {
return nil, err
}
if int64(len(data)) > c.maxZipBytes {
return nil, fmt.Errorf("artifact exceeds %d bytes", c.maxZipBytes)
}
return data, nil
}
// --- HTTP helpers ---
type minerUV1APIError struct {
status int
msg string
}
func (e *minerUV1APIError) Error() string {
return fmt.Sprintf("MinerU API status %d: %s", e.status, e.msg)
}
func newMinerUV1APIError(status int, body []byte) *minerUV1APIError {
msg := minerUV1ErrorMessage(body)
if msg == "" {
msg = truncateForLog(string(body), 500)
}
return &minerUV1APIError{status: status, msg: msg}
}
func (c *minerUV1Client) doJSON(ctx context.Context, method, path string, in, out interface{}) error {
var body io.Reader
if in != nil {
raw, err := json.Marshal(in)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
c.setAuth(req)
resp, err := c.apiClient.Do(req)
if err != nil {
return fmt.Errorf("%s %s: %w", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return fmt.Errorf("read response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return newMinerUV1APIError(resp.StatusCode, respBody)
}
if out == nil {
return nil
}
if err := json.Unmarshal(respBody, out); err != nil {
return fmt.Errorf("decode %s %s response: %w", method, path, err)
}
return nil
}
func (c *minerUV1Client) setAuth(req *http.Request) {
if c.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
}
}
func (c *minerUV1Client) resolveURL(raw string) (*url.URL, error) {
base, err := url.Parse(c.baseURL + "/")
if err != nil {
return nil, err
}
ref, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return nil, err
}
resolved := base.ResolveReference(ref)
if resolved.Scheme != "http" && resolved.Scheme != "https" {
return nil, fmt.Errorf("unsupported scheme %q", resolved.Scheme)
}
return resolved, nil
}
// sameOrigin compares scheme, host and effective port with the base URL.
func (c *minerUV1Client) sameOrigin(u *url.URL) bool {
base, err := url.Parse(c.baseURL)
if err != nil {
return false
}
return strings.EqualFold(base.Scheme, u.Scheme) &&
strings.EqualFold(base.Hostname(), u.Hostname()) &&
effectivePort(base) == effectivePort(u)
}
func effectivePort(u *url.URL) string {
if p := u.Port(); p != "" {
return p
}
switch strings.ToLower(u.Scheme) {
case "https":
return "443"
case "http":
return "80"
}
return ""
}
// Slim container images often ship without /etc/mime.types, where Go only
// knows a handful of extensions; cover the formats MinerU accepts explicitly.
var minerUV1MimeTypes = map[string]string{
".pdf": "application/pdf",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".ppt": "application/vnd.ms-powerpoint",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".bmp": "image/bmp",
".tif": "image/tiff",
".tiff": "image/tiff",
".html": "text/html",
".htm": "text/html",
}
func minerUV1MimeType(fileName string) string {
ext := strings.ToLower(filepath.Ext(fileName))
if t, ok := minerUV1MimeTypes[ext]; ok {
return t
}
if ext != "" {
if t := mime.TypeByExtension(ext); t != "" {
if mediaType, _, err := mime.ParseMediaType(t); err == nil {
return mediaType
}
return t
}
}
return "application/octet-stream"
}
@@ -0,0 +1,433 @@
package docparser
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"academy/internal/types"
"academy/internal/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeMinerUV1 is a minimal in-memory MinerU 4.0 api-server.
type fakeMinerUV1 struct {
t *testing.T
apiKey string
mu sync.Mutex
uploadURL string // absolute or relative; defaults to same-origin relative path
dedupHit bool // POST /v1/uploads answers "completed" directly
uploaded []byte
putAuth string
uploadMime string
jobPayload map[string]any
pollStatuses []string // statuses returned by successive GET job calls
polls int
fileError *map[string]string
canceled bool
zipData []byte
downloadCalls int
}
func (f *fakeMinerUV1) handler() http.Handler {
mux := http.NewServeMux()
writeJSON := func(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
authed := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if f.apiKey != "" && r.Header.Get("Authorization") != "Bearer "+f.apiKey {
writeJSON(w, http.StatusUnauthorized, map[string]any{
"error": map[string]string{"message": "bad key", "type": "auth_error", "code": "invalid_api_key"},
})
return
}
next(w, r)
}
}
mux.HandleFunc("GET /v1/health", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "version": "1.0.0"})
})
mux.HandleFunc("POST /v1/uploads", authed(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(f.t, json.NewDecoder(r.Body).Decode(&body))
f.mu.Lock()
defer f.mu.Unlock()
f.uploadMime, _ = body["mime_type"].(string)
if f.dedupHit {
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "completed", "file": map[string]any{"id": "file-src"},
})
return
}
uploadURL := f.uploadURL
if uploadURL == "" {
uploadURL = "/v1/uploads/upload_1/content"
}
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "pending", "upload_url": uploadURL, "upload_method": "PUT",
"upload_headers": map[string]string{"Content-Type": f.uploadMime},
})
}))
mux.HandleFunc("PUT /v1/uploads/upload_1/content", f.handlePut)
mux.HandleFunc("POST /v1/uploads/upload_1/complete", authed(func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "completed", "file": map[string]any{"id": "file-src"},
})
}))
mux.HandleFunc("POST /v1/parse/jobs", authed(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(f.t, json.NewDecoder(r.Body).Decode(&body))
f.mu.Lock()
f.jobPayload = body
f.mu.Unlock()
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": "job_1", "status": "queued"})
}))
mux.HandleFunc("GET /v1/parse/jobs/job_1", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
status := "completed"
if f.polls < len(f.pollStatuses) {
status = f.pollStatuses[f.polls]
}
f.polls++
file := map[string]any{"name": "report.pdf", "status": status}
switch status {
case "completed":
file["output_files"] = map[string]any{"zip": map[string]any{"file_id": "file-zip", "bytes": len(f.zipData)}}
case "failed":
file["error"] = *f.fileError
}
writeJSON(w, http.StatusOK, map[string]any{"job_id": "job_1", "status": status, "files": []any{file}})
}))
mux.HandleFunc("DELETE /v1/parse/jobs/job_1", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
f.canceled = true
f.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"job_id": "job_1", "status": "canceled"})
}))
mux.HandleFunc("GET /v1/parse/jobs", authed(func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": []any{}})
}))
mux.HandleFunc("GET /v1/files/file-zip/content", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
f.downloadCalls++
f.mu.Unlock()
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(f.zipData)
}))
return mux
}
func (f *fakeMinerUV1) handlePut(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
require.NoError(f.t, err)
f.mu.Lock()
f.uploaded = data
f.putAuth = r.Header.Get("Authorization")
f.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func buildMinerUZip(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range files {
w, err := zw.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, zw.Close())
return buf.Bytes()
}
func allowLoopbackSSRF(t *testing.T) {
t.Helper()
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
}
func fastV1Client(baseURL, apiKey string) *minerUV1Client {
c := newMinerUV1Client(baseURL, apiKey, 10*time.Second)
c.pollInitial = time.Millisecond
c.pollMax = 5 * time.Millisecond
return c
}
const v1TestMarkdown = "# Report\n\n![](images/page_0_image_1.png)\n\n" +
"<table><tr><td><img src=\"images/page_0_table_image_2_1.png\"></td></tr></table>\n"
func v1TestZip(t *testing.T) []byte {
return buildMinerUZip(t, map[string]string{
"markdown.md": v1TestMarkdown,
"middle_json.json": "{}",
"images/page_0_image_1.png": "png-bytes-1",
"images/page_0_table_image_2_1.png": "png-bytes-2",
"images/page_1_image_unreferenced.png": "unused",
})
}
func TestMinerUV1ClientParseFullFlow(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{
t: t,
apiKey: "server-key",
pollStatuses: []string{"queued", "running", "completed"},
zipData: v1TestZip(t),
}
server := httptest.NewServer(fake.handler())
defer server.Close()
client := fastV1Client(server.URL, "server-key")
md, refs, err := client.Parse(context.Background(), []byte("%PDF-1.7 body"), "report.pdf",
minerUV1ParseOptions{Tier: "advanced", OCRMode: "txt"})
require.NoError(t, err)
assert.Equal(t, v1TestMarkdown, md)
require.Len(t, refs, 2)
byRef := map[string]types.ImageRef{}
for _, ref := range refs {
byRef[ref.OriginalRef] = ref
}
assert.Equal(t, []byte("png-bytes-1"), byRef["images/page_0_image_1.png"].ImageData)
assert.Equal(t, []byte("png-bytes-2"), byRef["images/page_0_table_image_2_1.png"].ImageData)
assert.Equal(t, "image/png", byRef["images/page_0_image_1.png"].MimeType)
assert.Equal(t, []byte("%PDF-1.7 body"), fake.uploaded)
assert.Equal(t, "Bearer server-key", fake.putAuth, "same-origin upload must carry the API key")
assert.Equal(t, "application/pdf", fake.uploadMime)
assert.Equal(t, 3, fake.polls)
assert.False(t, fake.canceled)
assert.Equal(t, "advanced", fake.jobPayload["tier"])
assert.Equal(t, "txt", fake.jobPayload["ocr_mode"])
assert.Equal(t, []any{"zip"}, fake.jobPayload["output_formats"])
files := fake.jobPayload["files"].([]any)
source := files[0].(map[string]any)["source"].(map[string]any)
assert.Equal(t, map[string]any{"type": "file_id", "file_id": "file-src"}, source)
}
func TestMinerUV1ClientOmitsTierForServerDefault(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{OCRMode: "auto"})
require.NoError(t, err)
_, hasTier := fake.jobPayload["tier"]
assert.False(t, hasTier)
}
func TestMinerUV1ClientCrossOriginUploadOmitsAPIKey(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key", zipData: v1TestZip(t)}
// A different port on the same host is a different origin, like a
// pre-signed object-storage URL handed out by the official API.
storage := httptest.NewServer(http.HandlerFunc(fake.handlePut))
defer storage.Close()
fake.uploadURL = storage.URL + "/v1/uploads/upload_1/content?Signature=abc"
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "server-key").Parse(context.Background(), []byte("bytes"), "a.pdf",
minerUV1ParseOptions{})
require.NoError(t, err)
assert.Equal(t, []byte("bytes"), fake.uploaded)
assert.Empty(t, fake.putAuth, "API key must not leak to a cross-origin upload URL")
}
func TestMinerUV1ClientDedupSkipsByteUpload(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, dedupHit: true, zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("bytes"), "a.pdf",
minerUV1ParseOptions{})
require.NoError(t, err)
assert.Nil(t, fake.uploaded)
}
func TestMinerUV1ClientFailedJobReportsFileError(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{
t: t,
pollStatuses: []string{"failed"},
fileError: &map[string]string{"code": "parse_failed", "message": "corrupt pdf"},
}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "parse_failed: corrupt pdf")
assert.Zero(t, fake.downloadCalls)
}
func TestMinerUV1ClientCancelsJobOnTimeout(t *testing.T) {
allowLoopbackSSRF(t)
statuses := make([]string, 1000)
for i := range statuses {
statuses[i] = "running"
}
fake := &fakeMinerUV1{t: t, pollStatuses: statuses}
server := httptest.NewServer(fake.handler())
defer server.Close()
client := fastV1Client(server.URL, "")
client.jobTimeout = 100 * time.Millisecond
_, _, err := client.Parse(context.Background(), []byte("x"), "a.pdf", minerUV1ParseOptions{})
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.True(t, fake.canceled, "abandoned job should be canceled on the server")
}
func TestMinerUV1ClientAPIErrorMessage(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key"}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "wrong").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "401")
assert.Contains(t, err.Error(), "invalid_api_key: bad key")
}
func TestDetectMinerUProtocol(t *testing.T) {
allowLoopbackSSRF(t)
tests := []struct {
name string
status int
body string
want minerUProtocol
wantErr string
}{
{name: "v1 healthy", status: 200, body: `{"status":"ok","version":"1.0.0"}`, want: minerUProtocolV1},
{name: "legacy 404", status: 404, body: `{"detail":"Not Found"}`, want: minerUProtocolLegacy},
{name: "legacy 405", status: 405, body: ``, want: minerUProtocolLegacy},
{
name: "v1 preloading models",
status: 503,
body: `{"error":{"message":"weights missing","type":"engine_error",` +
`"code":"model_preload_files_missing"}}`,
want: minerUProtocolV1,
wantErr: "model_preload_files_missing: weights missing",
},
{name: "proxy error", status: 502, body: `bad gateway`, wantErr: "status 502"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/v1/health", r.URL.Path)
w.WriteHeader(tt.status)
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
got, err := detectMinerUProtocol(context.Background(), http.DefaultClient, server.URL)
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
func TestMinerUReaderUsesV1WhenAvailable(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key", zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
reader := NewMinerUReader(map[string]string{
"mineru_endpoint": server.URL,
"mineru_server_api_key": "server-key",
"mineru_tier": "Standard",
"mineru_parse_method": "ocr",
// Legacy-only knobs are ignored by the V1 path.
"mineru_model": "pipeline",
"mineru_enable_formula": "false",
})
result, err := reader.Read(context.Background(), &types.ReadRequest{
FileContent: []byte("%PDF"),
FileName: "dir/report.pdf",
FileType: "pdf",
})
require.NoError(t, err)
require.Empty(t, result.Error)
assert.True(t, strings.HasPrefix(result.MarkdownContent, "# Report"))
assert.Len(t, result.ImageRefs, 2)
assert.Equal(t, "standard", fake.jobPayload["tier"])
assert.Equal(t, "ocr", fake.jobPayload["ocr_mode"])
}
func TestResolveMinerUTier(t *testing.T) {
assert.Equal(t, "", resolveMinerUTier(""))
assert.Equal(t, "flash", resolveMinerUTier(" Flash "))
assert.Equal(t, "advanced", resolveMinerUTier("advanced"))
assert.Equal(t, "", resolveMinerUTier("pipeline"), "legacy backend names are not tiers")
assert.Equal(t, "", resolveMinerUTier("auto"))
}
func TestPingMinerUV1(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key"}
server := httptest.NewServer(fake.handler())
defer server.Close()
ok, msg := PingMinerU(server.URL, "server-key")
assert.True(t, ok, msg)
ok, msg = PingMinerU(server.URL, "wrong")
assert.False(t, ok)
assert.Contains(t, msg, "API Key 无效")
ok, msg = PingMinerU(server.URL, "")
assert.False(t, ok)
assert.Contains(t, msg, "配置 API Key")
open := &fakeMinerUV1{t: t}
openServer := httptest.NewServer(open.handler())
defer openServer.Close()
ok, msg = PingMinerU(openServer.URL, "")
assert.True(t, ok, msg)
}
func TestExtractMarkdownZipResolvesEncodedAndNestedPaths(t *testing.T) {
data := buildMinerUZip(t, map[string]string{
"report/report.md": "![](images/%E7%AC%AC%201%20%E9%A1%B5.png)\n![](./images/b.jpg)",
"report/images/第 1 页.png": "p1",
"report/images/b.jpg": "p2",
})
md, refs, err := extractMarkdownZip(data, "test")
require.NoError(t, err)
assert.Contains(t, md, "images/")
require.Len(t, refs, 2)
assert.Equal(t, []byte("p1"), refs[0].ImageData)
assert.Equal(t, "image/jpeg", refs[1].MimeType)
}
@@ -0,0 +1,375 @@
package docparser
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/sourceloc"
"academy/internal/types"
"academy/internal/utils"
)
const (
paddleOCRVLCloudDefaultBaseURL = "https://paddleocr.aistudio-app.com/api/v2/ocr/jobs"
paddleOCRVLCloudDefaultModel = "PaddleOCR-VL-1.6"
paddleOCRVLCloudPollInterval = 5 * time.Second
// paddleOCRVLCloudTimeout bounds how long one job is polled;
// ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT overrides it for documents that take
// longer, mirroring ACADEMY_MINERU_CLOUD_TIMEOUT on the MinerU cloud reader.
paddleOCRVLCloudTimeout = 600 * time.Second
)
// PaddleOCRVLCloudReader calls the PaddleOCR-VL AI Studio cloud API.
// Flow: POST /jobs (multipart) → poll GET /jobs/{id} → download result JSONL,
// then fetch each referenced image URL.
type PaddleOCRVLCloudReader struct {
token string
baseURL string
model string
useSeal bool
useChart bool
timeout time.Duration
pollInterval time.Duration
}
// NewPaddleOCRVLCloudReader creates a reader from ParserEngineOverrides.
func NewPaddleOCRVLCloudReader(overrides map[string]string) *PaddleOCRVLCloudReader {
return &PaddleOCRVLCloudReader{
token: strings.TrimSpace(overrides["paddleocr_vl_cloud_token"]),
baseURL: strings.TrimRight(stringOr(
overrides["paddleocr_vl_cloud_base_url"], paddleOCRVLCloudDefaultBaseURL,
), "/"),
model: stringOr(overrides["paddleocr_vl_cloud_model"], paddleOCRVLCloudDefaultModel),
useSeal: parseBoolOr(overrides["paddleocr_vl_cloud_use_seal_recognition"], true),
useChart: parseBoolOr(overrides["paddleocr_vl_cloud_use_chart_recognition"], false),
timeout: requestTimeoutFromEnv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", paddleOCRVLCloudTimeout),
pollInterval: paddleOCRVLCloudPollInterval,
}
}
func (c *PaddleOCRVLCloudReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.token == "" {
return &types.ReadResult{Error: "PaddleOCR-VL Cloud token is not configured"}, nil
}
if err := utils.ValidateURLForSSRF(c.baseURL); err != nil {
return &types.ReadResult{Error: fmt.Sprintf("PaddleOCR-VL Cloud base URL blocked by SSRF policy: %v", err)}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] Parsing file=%s size=%d model=%s",
req.FileName, len(content), c.model)
jobID, err := c.submitJob(ctx, req, content)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud submit: %w", err)
}
jsonlURL, err := c.pollJob(ctx, jobID)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud poll: %w", err)
}
mdContent, imagesURL, layoutUnits, err := c.fetchResults(jsonlURL)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud fetch results: %w", err)
}
mdContent = NormalizeHTMLTables(mdContent)
imageRefs := c.downloadImages(mdContent, imagesURL)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] Parsed successfully, markdown=%d chars, images=%d",
len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: paddleOCRVLSourceBlocks(mdContent, layoutUnits, req.FileType),
}, nil
}
func (c *PaddleOCRVLCloudReader) optionalPayload() map[string]interface{} {
// Shared with the self-hosted engine so both produce identical output.
return paddleOCRVLRecognitionParams(c.useSeal, c.useChart)
}
// --- job submit ---
type paddleOCRVLCloudSubmitResponse struct {
Data struct {
JobID string `json:"jobId"`
} `json:"data"`
ErrorCode int `json:"errorCode"`
ErrorMsg string `json:"errorMsg"`
}
func (c *PaddleOCRVLCloudReader) submitJob(ctx context.Context, req *types.ReadRequest, content []byte) (string, error) {
optional, err := json.Marshal(c.optionalPayload())
if err != nil {
return "", fmt.Errorf("marshal optionalPayload: %w", err)
}
fileName := req.FileName
if fileName == "" {
ext := strings.TrimPrefix(req.FileType, ".")
if ext == "" {
ext = "pdf"
}
fileName = "document." + ext
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
_ = writer.WriteField("model", c.model)
_ = writer.WriteField("optionalPayload", string(optional))
part, err := writer.CreateFormFile("file", filepath.Base(fileName))
if err != nil {
return "", fmt.Errorf("create form file: %w", err)
}
if _, err := part.Write(content); err != nil {
return "", fmt.Errorf("write file content: %w", err)
}
writer.Close()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL, &body)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Authorization", "bearer "+c.token)
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 60 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return "", fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody))
}
var result paddleOCRVLCloudSubmitResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", fmt.Errorf("decode response: %w", err)
}
if result.Data.JobID == "" {
return "", fmt.Errorf("API returned no jobId: %s", string(respBody))
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] job submitted: jobId=%s", result.Data.JobID)
return result.Data.JobID, nil
}
// --- polling ---
type paddleOCRVLCloudPollResponse struct {
Data struct {
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
ExtractProgress struct {
TotalPages int `json:"totalPages"`
ExtractedPages int `json:"extractedPages"`
} `json:"extractProgress"`
ResultURL struct {
JSONURL string `json:"jsonUrl"`
} `json:"resultUrl"`
} `json:"data"`
}
func (c *PaddleOCRVLCloudReader) pollJob(ctx context.Context, jobID string) (string, error) {
deadline := time.Now().Add(c.timeout)
pollCount := 0
url := c.baseURL + "/" + jobID
for time.Now().Before(deadline) {
// Bail out promptly when the caller cancels (task cancelled / timed
// out) instead of spinning: client.Do would fail immediately and
// sleepCtx returns at once on a cancelled ctx, so without this guard
// the loop busy-hammers the cloud API and floods logs until deadline.
if err := ctx.Err(); err != nil {
return "", err
}
pollCount++
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("create poll request: %w", err)
}
httpReq.Header.Set("Authorization", "bearer "+c.token)
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d failed: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
respBody, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d status %d: %s", pollCount, resp.StatusCode, string(respBody))
sleepCtx(ctx, c.pollInterval)
continue
}
var pollResp paddleOCRVLCloudPollResponse
if err := json.Unmarshal(respBody, &pollResp); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d decode error: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
state := strings.ToLower(pollResp.Data.State)
if pollCount == 1 || pollCount%6 == 0 || state == "done" || state == "failed" {
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] poll #%d: state=%s pages=%d/%d",
pollCount, state, pollResp.Data.ExtractProgress.ExtractedPages, pollResp.Data.ExtractProgress.TotalPages)
}
switch state {
case "done":
if pollResp.Data.ResultURL.JSONURL == "" {
return "", fmt.Errorf("state=done but no jsonUrl")
}
return pollResp.Data.ResultURL.JSONURL, nil
case "failed":
return "", fmt.Errorf("task failed: %s", pollResp.Data.ErrorMsg)
}
sleepCtx(ctx, c.pollInterval)
}
return "", fmt.Errorf("PaddleOCR-VL Cloud task timed out after %s (%d polls)", c.timeout, pollCount)
}
// --- result parsing ---
type paddleOCRVLCloudResultLine struct {
Result struct {
LayoutParsingResults []paddleOCRVLPage `json:"layoutParsingResults"`
} `json:"result"`
}
func (c *PaddleOCRVLCloudReader) fetchResults(jsonlURL string) (string, map[string]string, []sourceloc.Unit, error) {
if err := utils.ValidateURLForSSRF(jsonlURL); err != nil {
return "", nil, nil, fmt.Errorf("jsonl URL blocked by SSRF check: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Get(jsonlURL)
if err != nil {
return "", nil, nil, fmt.Errorf("download jsonl: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("download jsonl status %d", resp.StatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read jsonl body: %w", err)
}
texts := make([]string, 0)
images := make(map[string]string)
var units []sourceloc.Unit
pageNumber := 0
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
var parsed paddleOCRVLCloudResultLine
if err := json.Unmarshal([]byte(line), &parsed); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] skip malformed jsonl line: %v", err)
continue
}
for _, p := range parsed.Result.LayoutParsingResults {
pageNumber++
units = append(units, paddleOCRVLPageUnits(pageNumber, p)...)
if t := strings.TrimSpace(p.Markdown.Text); t != "" {
texts = append(texts, p.Markdown.Text)
}
for path, u := range p.Markdown.Images {
if _, ok := images[path]; !ok {
images[path] = u
}
}
}
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] fetched %d page(s), images=%d", len(texts), len(images))
return strings.Join(texts, "\n\n"), images, units, nil
}
// downloadImages fetches each referenced image URL and builds ImageRef entries.
func (c *PaddleOCRVLCloudReader) downloadImages(mdContent string, imagesURL map[string]string) []types.ImageRef {
var refs []types.ImageRef
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 60 * time.Second, MaxRedirects: 5})
for ipath, u := range imagesURL {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
if err := utils.ValidateURLForSSRF(u); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] image URL blocked %s: %v", ipath, err)
continue
}
resp, err := client.Get(u)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] download image %s: %v", ipath, err)
continue
}
imgBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || resp.StatusCode != http.StatusOK {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] read image %s status=%d err=%v", ipath, resp.StatusCode, err)
continue
}
ext := strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs
}
// PingPaddleOCRVLCloud checks whether the cloud token is present (the API has
// no lightweight health endpoint, so we only validate configuration here).
func PingPaddleOCRVLCloud(token string) (bool, string) {
if strings.TrimSpace(token) == "" {
return false, "未配置 PaddleOCR-VL Cloud Token"
}
return true, ""
}
@@ -0,0 +1,293 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/sourceloc"
"academy/internal/types"
"academy/internal/utils"
)
const defaultPaddleOCRVLTimeout = 1000 * time.Second // large scanned PDFs can take a while
// PaddleOCRVLReader calls a self-hosted PaddleOCR-VL pipeline service
// (the full document-parsing API, not the bare VLM inference server).
//
// Flow: POST {endpoint}/layout-parsing with base64 file → synchronous JSON
// response containing per-page markdown + inline base64 images.
type PaddleOCRVLReader struct {
endpoint string
timeout time.Duration
useSeal bool
useChart bool
}
// NewPaddleOCRVLReader creates a reader from ParserEngineOverrides.
func NewPaddleOCRVLReader(overrides map[string]string) *PaddleOCRVLReader {
return &PaddleOCRVLReader{
timeout: requestTimeoutFromEnv("ACADEMY_PADDLEOCR_VL_TIMEOUT", defaultPaddleOCRVLTimeout),
endpoint: strings.TrimRight(overrides["paddleocr_vl_endpoint"], "/"),
useSeal: parseBoolOr(overrides["paddleocr_vl_use_seal_recognition"], true),
useChart: parseBoolOr(overrides["paddleocr_vl_use_chart_recognition"], false),
}
}
func (c *PaddleOCRVLReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.endpoint == "" {
return &types.ReadResult{Error: "PaddleOCR-VL endpoint is not configured"}, nil
}
if err := utils.ValidateURLForSSRF(c.endpoint); err != nil {
return &types.ReadResult{Error: fmt.Sprintf("PaddleOCR-VL endpoint blocked by SSRF policy: %v", err)}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[PaddleOCR-VL] Parsing file=%s size=%d via %s",
req.FileName, len(content), c.endpoint)
mdContent, imagesB64, layoutUnits, err := c.callLayoutParsing(ctx, req, content)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL layout-parsing: %w", err)
}
// PaddleOCR-VL renders tables as styled HTML (per-cell text-align), which
// wastes tokens and defeats the chunker's table-protection logic. Convert
// them to Markdown tables (or strip layout attributes when conversion is
// not possible) before downstream processing.
mdContent = NormalizeHTMLTables(mdContent)
imageRefs, mdContent := c.processImages(mdContent, imagesB64)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[PaddleOCR-VL] Parsed successfully, markdown=%d chars, images=%d",
len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: paddleOCRVLSourceBlocks(mdContent, layoutUnits, req.FileType),
}, nil
}
// paddleOCRVLRecognitionParams returns the recognition / page-restructuring
// parameters shared by the self-hosted (/layout-parsing, top-level body) and
// cloud (optionalPayload) request bodies. Keeping both identical ensures the
// self-hosted engine reproduces the cloud output: cross-page table merging,
// multi-level heading reconstruction, header/footer stripping, and the same
// sampling / resolution settings used by the AI Studio service.
func paddleOCRVLRecognitionParams(useSeal, useChart bool) map[string]interface{} {
return map[string]interface{}{
"markdownIgnoreLabels": []string{
"header", "header_image", "footer", "footer_image",
"number", "footnote", "aside_text",
},
"useDocOrientationClassify": false,
"useDocUnwarping": false,
"useLayoutDetection": true,
"useChartRecognition": useChart,
"useSealRecognition": useSeal,
"useOcrForImageBlock": false,
"mergeTables": true,
"relevelTitles": true,
"restructurePages": true,
"layoutShapeMode": "auto",
"promptLabel": "ocr",
"layoutNms": true,
"repetitionPenalty": 1,
"temperature": 0,
"topP": 1,
"minPixels": 147384,
"maxPixels": 2822400,
}
}
// fileTypeCode maps a request to the PaddleOCR-VL fileType field:
// 0 = PDF, 1 = image (including TIFF).
func fileTypeCode(req *types.ReadRequest) int {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
if ft == "pdf" {
return 0
}
return 1
}
// paddleOCRVLResponse mirrors the relevant fields of the PaddleX serving
// /layout-parsing response. The service returns one entry per page.
type paddleOCRVLResponse struct {
ErrorCode int `json:"errorCode"`
ErrorMsg string `json:"errorMsg"`
Result struct {
LayoutParsingResults []paddleOCRVLPage `json:"layoutParsingResults"`
} `json:"result"`
}
func (c *PaddleOCRVLReader) callLayoutParsing(
ctx context.Context, req *types.ReadRequest, content []byte,
) (string, map[string]string, []sourceloc.Unit, error) {
payload := paddleOCRVLRecognitionParams(c.useSeal, c.useChart)
payload["file"] = base64.StdEncoding.EncodeToString(content)
payload["fileType"] = fileTypeCode(req)
payload["visualize"] = false
body, err := json.Marshal(payload)
if err != nil {
return "", nil, nil, fmt.Errorf("marshal payload: %w", err)
}
httpReq, err := http.NewRequestWithContext(
ctx, http.MethodPost, c.endpoint+"/layout-parsing", bytes.NewReader(body),
)
if err != nil {
return "", nil, nil, fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: c.timeout,
MaxRedirects: 5,
})
resp, err := client.Do(httpReq)
if err != nil {
return "", nil, nil, fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("PaddleOCR-VL API status %d: %s", resp.StatusCode, string(respBody))
}
var result paddleOCRVLResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", nil, nil, fmt.Errorf("decode response: %w", err)
}
if result.ErrorCode != 0 {
return "", nil, nil, fmt.Errorf("PaddleOCR-VL error %d: %s", result.ErrorCode, result.ErrorMsg)
}
pages := result.Result.LayoutParsingResults
if len(pages) == 0 {
logger.Errorf(context.Background(), "[PaddleOCR-VL] response has no layoutParsingResults")
return "", nil, nil, nil
}
// Merge per-page markdown and image dicts into one document.
texts := make([]string, 0, len(pages))
images := make(map[string]string)
var units []sourceloc.Unit
for i, p := range pages {
units = append(units, paddleOCRVLPageUnits(i+1, p)...)
if t := strings.TrimSpace(p.Markdown.Text); t != "" {
texts = append(texts, p.Markdown.Text)
}
for path, data := range p.Markdown.Images {
if _, ok := images[path]; !ok {
images[path] = data
}
}
}
logger.Infof(context.Background(), "[PaddleOCR-VL] parsed %d page(s), images=%d", len(pages), len(images))
return strings.Join(texts, "\n\n"), images, units, nil
}
// processImages decodes the inline base64 images returned by PaddleOCR-VL and
// builds ImageRef entries, matching them against references in the markdown.
func (c *PaddleOCRVLReader) processImages(
mdContent string, imagesB64 map[string]string,
) ([]types.ImageRef, string) {
var refs []types.ImageRef
for ipath, b64Str := range imagesB64 {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
var imgBytes []byte
var ext string
if m := b64DataURIPattern.FindStringSubmatch(b64Str); len(m) == 3 {
ext = m[1]
decoded, err := base64.StdEncoding.DecodeString(m[2])
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL] decode base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
} else {
decoded, err := base64.StdEncoding.DecodeString(b64Str)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL] decode raw base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
ext = strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs, mdContent
}
// PingPaddleOCRVL checks whether a self-hosted PaddleOCR-VL service is reachable.
func PingPaddleOCRVL(endpoint string) (bool, string) {
endpoint = strings.TrimRight(endpoint, "/")
if endpoint == "" {
return false, "未配置 PaddleOCR-VL 端点"
}
if err := utils.ValidateURLForSSRF(endpoint); err != nil {
return false, fmt.Sprintf("PaddleOCR-VL 端点未通过 SSRF 校验: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 5 * time.Second,
MaxRedirects: 5,
})
// The pipeline only exposes POST /layout-parsing; an empty GET should still
// produce a routed HTTP response (e.g. 404/405) when the service is up.
resp, err := client.Get(endpoint + "/layout-parsing")
if err != nil {
return false, fmt.Sprintf("PaddleOCR-VL 服务不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode >= 500 {
return false, fmt.Sprintf("PaddleOCR-VL 服务返回状态 %d", resp.StatusCode)
}
return true, ""
}
@@ -0,0 +1,119 @@
package docparser
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"academy/internal/types"
"academy/internal/utils"
)
func TestPaddleOCRVLTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"unset", "", 1000 * time.Second},
{"empty", "", 1000 * time.Second},
{"whitespace", " ", 1000 * time.Second},
{"seconds", "5400s", 90 * time.Minute},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 90m ", 90 * time.Minute},
{"invalid", "invalid", 1000 * time.Second},
{"unitless", "5400", 1000 * time.Second},
{"zero", "0s", 1000 * time.Second},
{"negative", "-1s", 1000 * time.Second},
{"overflow", "999999999999999999999h", 1000 * time.Second},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", tt.value)
if tt.name == "unset" {
if err := os.Unsetenv("ACADEMY_PADDLEOCR_VL_TIMEOUT"); err != nil {
t.Fatal(err)
}
}
reader := NewPaddleOCRVLReader(nil)
if reader.timeout != tt.want {
t.Fatalf("timeout = %s, want %s", reader.timeout, tt.want)
}
})
}
}
func TestPaddleOCRVLReadTimeout(t *testing.T) {
// Earlier parser tests may have initialized the runtime whitelist.
utils.SetSSRFWhitelistFromRaw("127.0.0.1,localhost")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
for _, mode := range []string{"success", "http timeout", "parent deadline", "parent cancellation"} {
t.Run(mode, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", "10s")
if mode == "http timeout" {
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", "100ms")
}
arrived := make(chan struct{})
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
close(arrived)
if mode == "success" {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"errorCode":0,"result":{"layoutParsingResults":[
{"markdown":{"text":"parsed document","images":{}}}]}}`)
return
}
select {
case <-r.Context().Done():
case <-release:
}
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if mode == "parent deadline" {
var stop context.CancelFunc
ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond)
defer stop()
}
if mode == "parent cancellation" {
go func() {
select {
case <-arrived:
cancel()
case <-ctx.Done():
}
}()
}
reader := NewPaddleOCRVLReader(map[string]string{"paddleocr_vl_endpoint": server.URL})
result, err := reader.Read(ctx, &types.ReadRequest{
FileName: "test.pdf", FileType: "pdf", FileContent: []byte("test"),
})
if mode == "success" {
if err != nil {
t.Fatal(err)
}
if result.MarkdownContent != "parsed document" {
t.Fatalf("unexpected result: %+v", result)
}
return
}
want := context.DeadlineExceeded
if mode == "parent cancellation" {
want = context.Canceled
}
if !errors.Is(err, want) {
t.Fatalf("error = %v, want %v", err, want)
}
if mode == "http timeout" && ctx.Err() != nil {
t.Fatalf("request only stopped at parent deadline: %v", ctx.Err())
}
})
}
}
@@ -0,0 +1,82 @@
package docparser
import (
"encoding/json"
"strings"
"academy/internal/sourceloc"
"academy/internal/types"
)
// paddleOCRVLPage is one page of a PaddleOCR-VL layout-parsing result.
type paddleOCRVLPage struct {
Markdown struct {
Text string `json:"text"`
Images map[string]string `json:"images"`
} `json:"markdown"`
// PrunedResult carries the page's layout blocks; decoded lazily and
// only for the fields source locators need.
PrunedResult json.RawMessage `json:"prunedResult"`
}
type paddleOCRVLLayout struct {
Width float64 `json:"width"`
Height float64 `json:"height"`
ParsingResList []struct {
BlockContent string `json:"block_content"`
BlockBBox []float64 `json:"block_bbox"`
} `json:"parsing_res_list"`
}
// paddleOCRVLPageUnits lists a page's layout blocks, each boxed in page
// fractions, for aligning against the merged markdown. Without layout
// blocks the page's markdown paragraphs are listed with the page alone.
func paddleOCRVLPageUnits(pageNumber int, page paddleOCRVLPage) []sourceloc.Unit {
pageOnly := types.SourceLocator{Type: types.SourceLocatorPDF, Page: pageNumber}
var layout paddleOCRVLLayout
if len(page.PrunedResult) > 0 && json.Unmarshal(page.PrunedResult, &layout) == nil &&
layout.Width > 0 && layout.Height > 0 && len(layout.ParsingResList) > 0 {
units := make([]sourceloc.Unit, 0, len(layout.ParsingResList))
for _, b := range layout.ParsingResList {
loc := pageOnly
if len(b.BlockBBox) == 4 && b.BlockBBox[2] > b.BlockBBox[0] && b.BlockBBox[3] > b.BlockBBox[1] {
loc.BBox = []float64{
clampUnit(b.BlockBBox[0] / layout.Width), clampUnit(b.BlockBBox[1] / layout.Height),
clampUnit(b.BlockBBox[2] / layout.Width), clampUnit(b.BlockBBox[3] / layout.Height),
}
}
units = append(units, sourceloc.Unit{
Text: minerUHTMLTagRe.ReplaceAllString(b.BlockContent, " "),
Locator: loc,
})
}
return units
}
var units []sourceloc.Unit
for _, para := range strings.Split(page.Markdown.Text, "\n\n") {
if strings.TrimSpace(para) != "" {
units = append(units, sourceloc.Unit{Text: para, Locator: pageOnly})
}
}
return units
}
// paddleOCRVLSourceBlocks aligns layout units against the final markdown
// for file types a viewer shows page by page.
func paddleOCRVLSourceBlocks(markdown string, units []sourceloc.Unit, fileType string) []types.SourceBlock {
ft := strings.ToLower(strings.TrimPrefix(fileType, "."))
if ft != "pdf" && !IsImageFormat(ft) {
return nil
}
return sourceloc.Align(markdown, units)
}
func clampUnit(v float64) float64 {
if v < 0 {
return 0
}
if v > 1 {
return 1
}
return v
}
@@ -0,0 +1,406 @@
package docparser
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"academy/internal/types"
secutils "academy/internal/utils"
)
// remoteImageServer serves a valid PNG for every request and counts the hits so
// that budget and dedup behaviour can be asserted directly.
func remoteImageServer(t *testing.T) (*httptest.Server, *int64) {
t.Helper()
var hits int64
png := createTestPNG(200, 200)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&hits, 1)
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(png)
}))
t.Cleanup(ts.Close)
return ts, &hits
}
func allowLocalhost(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
secutils.ResetSSRFWhitelistForTest()
}
func resolve(t *testing.T, markdown string) (string, []StoredImage, *mockFileService) {
t.Helper()
fSvc := &mockFileService{}
updated, images, err := NewImageResolver().ResolveRemoteImages(
context.Background(), markdown, fSvc, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return updated, images, fSvc
}
func TestResolveRemoteImages_HTMLTagRewritesSrcAndKeepsTag(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
markdown := fmt.Sprintf(
`<p><img class="screenshot" src="%s/a.png" alt="login screen" width="600"></p>`, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("original URL still present: %s", updated)
}
if !strings.Contains(updated, images[0].ServingURL) {
t.Errorf("serving URL missing from output: %s", updated)
}
// The surrounding markup is the reason these documents use HTML at all.
for _, want := range []string{`<img`, `class="screenshot"`, `alt="login screen"`, `width="600"`, `</p>`} {
if !strings.Contains(updated, want) {
t.Errorf("tag structure lost, %q missing from: %s", want, updated)
}
}
if strings.Contains(updated, "![") {
t.Errorf("tag was converted to markdown syntax: %s", updated)
}
}
func TestResolveRemoteImages_MarkdownAndHTMLBothResolved(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
markdown := fmt.Sprintf("![md](%s/md.png)\n\n<img src=\"%s/html.png\">", ts.URL, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 2 {
t.Fatalf("expected 2 stored images, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("a remote URL survived: %s", updated)
}
}
func TestResolveRemoteImages_IndependentBudgetPerSyntax(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Adding HTML support must not reduce how many Markdown images a document
// already gets resolved: each syntax carries its own budget.
var b strings.Builder
for i := 0; i < maxRemoteImages; i++ {
fmt.Fprintf(&b, "![md%d](%s/md%d.png)\n\n", i, ts.URL, i)
}
for i := 0; i < 5; i++ {
fmt.Fprintf(&b, "<img src=\"%s/html%d.png\">\n\n", ts.URL, i)
}
updated, images, _ := resolve(t, b.String())
if len(images) != maxRemoteImages+5 {
t.Fatalf("expected %d stored images, got %d", maxRemoteImages+5, len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("a remote URL survived: %s", updated)
}
}
func TestResolveRemoteImages_HTMLSrcNormalization(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
t.Run("uppercase scheme", func(t *testing.T) {
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
updated, images, _ := resolve(t, fmt.Sprintf(`<img SRC="%s/up.png">`, upper))
if len(images) != 1 {
t.Fatalf("expected uppercase scheme to be fetched, got %d", len(images))
}
// The scheme is normalized because every fetcher downstream compares it
// byte-for-byte; an image counted as resolved but unfetchable is worse
// than one left alone.
if strings.Contains(images[0].OriginalRef, "HTTP://") {
t.Errorf("scheme was not normalized: %q", images[0].OriginalRef)
}
if strings.Contains(updated, "HTTP://") {
t.Errorf("document still carries the uppercase scheme: %s", updated)
}
})
t.Run("markdown uppercase scheme is left alone", func(t *testing.T) {
// Markdown targets are handed through unchanged, so a document that
// upstream leaves untouched stays untouched.
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
markdown := fmt.Sprintf("![x](%s/md-up.png)", upper)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no markdown behaviour change, got %d image(s)", len(images))
}
if updated != markdown {
t.Errorf("markdown content changed:\n got %q\nwant %q", updated, markdown)
}
})
t.Run("padded src", func(t *testing.T) {
_, images, _ := resolve(t, fmt.Sprintf(`<img src=" %s/pad.png ">`, ts.URL))
if len(images) != 1 {
t.Fatalf("expected padded src to be fetched, got %d", len(images))
}
})
t.Run("entity encoded query", func(t *testing.T) {
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.URL.RawQuery
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(createTestPNG(200, 200))
}))
defer srv.Close()
_, images, _ := resolve(t, fmt.Sprintf(`<img src="%s/q.png?a=1&amp;b=2">`, srv.URL))
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if got != "a=1&b=2" {
t.Errorf("entities were not decoded before the request: raw query %q", got)
}
})
}
func TestResolveRemoteImages_HTMLSrcFormsOutOfScope(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
cases := map[string]string{
"unquoted src": fmt.Sprintf(`<img src=%s/unquoted.png>`, ts.URL),
"srcset only": fmt.Sprintf(`<img srcset="%s/set.png 2x">`, ts.URL),
"relative src": `<img src="./images/local.png">`,
"data uri src": `<img src="data:image/png;base64,AAAA">`,
"provider src": `<img src="local://images/x.png">`,
"non-img tag": fmt.Sprintf(`<video src="%s/v.mp4">`, ts.URL),
}
for name, markdown := range cases {
t.Run(name, func(t *testing.T) {
before := atomic.LoadInt64(hits)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no stored images, got %d", len(images))
}
if updated != markdown {
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
}
if got := atomic.LoadInt64(hits) - before; got != 0 {
t.Errorf("expected no fetch, got %d", got)
}
})
}
}
func TestResolveRemoteImages_HyphenatedAttributeIsNotSrc(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// A lazy-loading tag carries a placeholder in src and the real image in
// data-src. Treating data-src as src would capture whichever came first and
// leave the other unvisited, so only src counts.
markdown := fmt.Sprintf(`<img data-src="/placeholder.svg" src="%s/real.png">`, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected the src image to be resolved, got %d", len(images))
}
if images[0].OriginalRef != ts.URL+"/real.png" {
t.Errorf("expected src to be the fetched reference, got %s", images[0].OriginalRef)
}
if !strings.Contains(updated, `data-src="/placeholder.svg"`) {
t.Errorf("data-src must be left alone: %s", updated)
}
if strings.Contains(updated, ts.URL) {
t.Errorf("src was not rewritten: %s", updated)
}
}
func TestResolveRemoteImages_HyphenatedAttributeOnlyIsNotResolved(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
// The other half of the same trade-off, pinned deliberately. Requiring
// whitespace before src means a tag carrying only a hyphenated *-src is no
// longer treated as an image at all — the previous boundary did resolve it.
// Recovering that needs an attribute parser rather than a regex; capturing a
// lazy-loading placeholder while the real src goes unvisited is the worse of
// the two failures.
for _, attr := range []string{"data-src", "ng-src", "data-original-src"} {
t.Run(attr, func(t *testing.T) {
before := atomic.LoadInt64(hits)
markdown := fmt.Sprintf(`<img %s="%s/only.png">`, attr, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no stored images, got %d", len(images))
}
if updated != markdown {
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
}
if got := atomic.LoadInt64(hits) - before; got != 0 {
t.Errorf("expected no fetch, got %d", got)
}
})
}
}
func TestResolveRemoteImages_WhitelistedHostAgreesWithDocument(t *testing.T) {
var hits int64
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&hits, 1)
if got := r.URL.RawQuery; got != "a=1&b=2" {
t.Errorf("expected entities decoded for the request, got raw query %q", got)
}
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(createTestPNG(200, 200))
}))
defer ts.Close()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
t.Setenv("IMAGE_HOST_KEEP_URL", strings.TrimPrefix(ts.URL, "http://"))
secutils.ResetSSRFWhitelistForTest()
markdown := fmt.Sprintf(`<img src=" %s/q.png?a=1&amp;b=2 " alt="kept">`, ts.URL)
updated, images, fSvc := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if atomic.LoadInt64(&hits) != 1 {
t.Fatalf("expected the image to be downloaded once, got %d", hits)
}
if len(fSvc.saved) != 0 {
t.Errorf("a whitelisted image must not be uploaded, got %d uploads", len(fSvc.saved))
}
serving := images[0].ServingURL
// ServingURL carries two obligations that have to agree: later stages locate
// the image by searching the document for it, and the multimodal stage fetches
// that same string.
if !strings.Contains(updated, serving) {
t.Errorf("ServingURL %q is not present in the document %q", serving, updated)
}
if serving != ts.URL+"/q.png?a=1&b=2" {
t.Errorf("ServingURL must be the normalized fetchable URL, got %q", serving)
}
if strings.TrimSpace(serving) != serving {
t.Errorf("ServingURL must not carry padding: %q", serving)
}
if strings.Contains(serving, "&amp;") {
t.Errorf("ServingURL must not carry HTML entities: %q", serving)
}
if !strings.Contains(updated, `alt="kept"`) {
t.Errorf("the rest of the tag must survive: %s", updated)
}
}
func TestResolveRemoteImages_CodeExampleIsRewritten(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Accepted limitation: this resolver does not parse Markdown structure, so a
// tag shown as a documentation example inside a fence is rewritten like any
// other. Recognising code spans reliably needs a Markdown parser; a
// hand-rolled scanner risks the opposite and far worse failure of treating a
// document's real screenshots as examples.
markdown := fmt.Sprintf("```html\n<img src=\"%s/example.png\">\n```", ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected the example to be resolved, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("expected the example to be rewritten: %s", updated)
}
}
func TestResolveRemoteImages_CancelledContextStops(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
var b strings.Builder
for i := 0; i < 5; i++ {
fmt.Fprintf(&b, "<img src=\"%s/c%d.png\">\n\n", ts.URL, i)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, images, err := NewImageResolver().ResolveRemoteImages(ctx, b.String(), &mockFileService{}, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected no images after cancellation, got %d", len(images))
}
if got := atomic.LoadInt64(hits); got != 0 {
t.Errorf("expected no fetch after cancellation, got %d", got)
}
}
func TestResolveAndStoreThenResolveRemoteImages(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Mirrors the real ingest order, where ResolveAndStore runs first and
// ResolveRemoteImages then works on its output. This is the only place the
// two HTML resolvers can interfere with each other.
markdown := fmt.Sprintf(
"<img src=\"images/relative.png\">\n\n<img src=\"%s/remote.png\">", ts.URL)
fSvc := &mockFileService{}
resolver := NewImageResolver()
afterStore, storeImages, err := resolver.ResolveAndStore(context.Background(), &types.ReadResult{
MarkdownContent: markdown,
ImageRefs: []types.ImageRef{{
OriginalRef: "images/relative.png",
Filename: "relative.png",
MimeType: "image/png",
ImageData: createTestPNG(200, 200),
}},
}, fSvc, 42)
if err != nil {
t.Fatalf("ResolveAndStore: %v", err)
}
if len(storeImages) != 1 {
t.Fatalf("expected the relative image stored, got %d", len(storeImages))
}
afterRemote, remoteImages, err := resolver.ResolveRemoteImages(
context.Background(), afterStore, fSvc, 42)
if err != nil {
t.Fatalf("ResolveRemoteImages: %v", err)
}
if len(remoteImages) != 1 {
t.Fatalf("expected the remote image stored, got %d", len(remoteImages))
}
if strings.Contains(afterRemote, ts.URL) {
t.Errorf("remote URL survived: %s", afterRemote)
}
if strings.Contains(afterRemote, "images/relative.png") {
t.Errorf("relative reference was not rewritten by the earlier pass: %s", afterRemote)
}
if n := strings.Count(afterRemote, "<img"); n != 2 {
t.Errorf("expected both tags preserved, found %d", n)
}
}
@@ -0,0 +1,264 @@
package docparser
import (
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// mockFileService is a minimal FileService implementation for testing.
type mockFileService struct {
saved []savedEntry
}
type savedEntry struct {
Data []byte
TenantID uint64
FileName string
}
func (m *mockFileService) CheckConnectivity(ctx context.Context) error { return nil }
func (m *mockFileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
return "", nil
}
func (m *mockFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
m.saved = append(m.saved, savedEntry{Data: data, TenantID: tenantID, FileName: fileName})
return fmt.Sprintf("local://images/%s", fileName), nil
}
func (m *mockFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
return nil, nil
}
func (m *mockFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
return filePath, nil
}
func (m *mockFileService) DeleteFile(ctx context.Context, filePath string) error { return nil }
func (m *mockFileService) CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string) (string, error) {
return "", nil
}
func TestResolveRemoteImages_NormalDownload(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
// Create a test HTTP server that serves a real PNG image.
pngData := createTestPNG(200, 200)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
w.Write(pngData)
}))
defer ts.Close()
markdown := fmt.Sprintf("# Hello\n\n![photo](%s/image.png)\n\nSome text", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
// URL should have been replaced.
if strings.Contains(updated, ts.URL) {
t.Errorf("original URL should have been replaced in markdown, got: %s", updated)
}
if !strings.Contains(updated, "local://images/") {
t.Errorf("expected local:// URL in markdown, got: %s", updated)
}
// Verify saved data.
if len(fSvc.saved) != 1 {
t.Fatalf("expected 1 saved entry, got %d", len(fSvc.saved))
}
if fSvc.saved[0].TenantID != 42 {
t.Errorf("expected tenantID 42, got %d", fSvc.saved[0].TenantID)
}
}
func TestResolveRemoteImages_SSRFBlocked(t *testing.T) {
// URLs pointing to private IPs should be blocked by SSRF check.
markdown := "![evil](http://127.0.0.1:8080/secret.png)\n\n![also-evil](http://169.254.169.254/metadata)"
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Both images should be left unchanged (SSRF blocked).
if len(images) != 0 {
t.Errorf("expected 0 stored images (SSRF blocked), got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged when SSRF blocked")
}
}
func TestResolveRemoteImages_NonImageContentType(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write([]byte("<html>not an image</html>"))
}))
defer ts.Close()
markdown := fmt.Sprintf("![bad](%s/page.html)", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for non-image content type, got %d", len(images))
}
// Original URL should be preserved.
if !strings.Contains(updated, ts.URL) {
t.Errorf("original URL should be preserved for non-image content")
}
}
func TestResolveRemoteImages_ProviderSchemeSkipped(t *testing.T) {
markdown := "![already](local://images/abc.png)\n![also](minio://bucket/key.jpg)"
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for provider:// URLs, got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged for provider:// URLs")
}
}
func TestResolveRemoteImages_MultipleImages(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
pngData := createTestPNG(256, 256)
callCount := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
w.Write(pngData)
}))
defer ts.Close()
markdown := fmt.Sprintf("![img1](%s/a.png)\n\ntext\n\n![img2](%s/b.png)\n\n![img3](%s/c.png)",
ts.URL, ts.URL, ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 10)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 3 {
t.Fatalf("expected 3 stored images, got %d", len(images))
}
if callCount != 3 {
t.Errorf("expected 3 HTTP requests, got %d", callCount)
}
if strings.Contains(updated, ts.URL) {
t.Errorf("all original URLs should have been replaced")
}
}
func TestResolveRemoteImages_NoImages(t *testing.T) {
markdown := "# Just text\n\nNo images here."
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images, got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged")
}
}
func TestResolveRemoteImages_Server404(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer ts.Close()
markdown := fmt.Sprintf("![missing](%s/nope.png)", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for 404, got %d", len(images))
}
// Original URL preserved on failure.
if !strings.Contains(updated, ts.URL) {
t.Errorf("original URL should be preserved on download failure")
}
}
func TestExtFromURLPath(t *testing.T) {
tests := []struct {
url string
expect string
}{
{"https://example.com/photo.jpg", ".jpg"},
{"https://example.com/photo.JPEG", ".jpeg"},
{"https://example.com/photo.png?v=2", ""}, // query param — path.Ext won't catch it cleanly but that's ok
{"https://example.com/photo.gif", ".gif"},
{"https://example.com/photo.webp", ".webp"},
{"https://example.com/photo.bmp", ".bmp"},
{"https://example.com/photo.svg", ".svg"},
{"https://example.com/photo.pdf", ""},
{"https://example.com/noext", ""},
}
for _, tt := range tests {
t.Run(tt.url, func(t *testing.T) {
got := extFromURLPath(tt.url)
if got != tt.expect {
t.Errorf("extFromURLPath(%q) = %q, want %q", tt.url, got, tt.expect)
}
})
}
}
Loaded 100 of 5767 files, more files were not shown because too many files have changed in this diff. Show more