feat: introduce WeKnora Lite edition with lightweight configuration and deployment
- Added a new `.env.lite.example` file for the Lite version, providing a minimal configuration template. - Updated `.env.example` to remove deprecated variables and include new Docreader settings. - Enhanced Docker configurations to support the Lite version, including a new Dockerfile for the Docreader service. - Introduced a Makefile target for building and running the Lite version, along with packaging capabilities. - Created GitHub workflows for building and releasing Lite binaries, including Homebrew formula support. - Implemented a new service file for managing the Lite version as a system service. This update enables a streamlined, single-binary deployment of WeKnora, reducing external dependencies and simplifying setup.
This commit is contained in:
@@ -0,0 +1,334 @@
|
||||
// Package chunker implements text splitting for document chunking.
|
||||
//
|
||||
// Ported from the Python docreader/splitter/splitter.py recursive text splitter.
|
||||
package chunker
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Chunk represents a piece of split text with position tracking.
|
||||
type Chunk struct {
|
||||
Content string
|
||||
Seq int
|
||||
Start int
|
||||
End int
|
||||
}
|
||||
|
||||
// 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.
|
||||
type SplitterConfig struct {
|
||||
ChunkSize int
|
||||
ChunkOverlap int
|
||||
Separators []string
|
||||
}
|
||||
|
||||
// DefaultConfig returns sensible defaults.
|
||||
func DefaultConfig() SplitterConfig {
|
||||
return SplitterConfig{
|
||||
ChunkSize: 512,
|
||||
ChunkOverlap: 50,
|
||||
Separators: []string{"\n\n", "\n", "。"},
|
||||
}
|
||||
}
|
||||
|
||||
// protectedPatterns are regex patterns for content that must not be split.
|
||||
var protectedPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?s)\$\$.*?\$\$`), // LaTeX block math
|
||||
regexp.MustCompile(`!\[[^\]]*\]\([^)]+\)`), // Markdown images
|
||||
regexp.MustCompile(`\[[^\]]*\]\([^)]+\)`), // Markdown links
|
||||
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
|
||||
}
|
||||
|
||||
type span struct {
|
||||
start, end int
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Sort by start, then by length descending
|
||||
for i := 1; i < len(all); i++ {
|
||||
for j := i; j > 0; j-- {
|
||||
if all[j].start < all[j-1].start ||
|
||||
(all[j].start == all[j-1].start && (all[j].end-all[j].start) > (all[j-1].end-all[j-1].start)) {
|
||||
all[j], all[j-1] = all[j-1], all[j]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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, keeping separators.
|
||||
func splitBySeparators(text string, separators []string) []string {
|
||||
if len(separators) == 0 || text == "" {
|
||||
return []string{text}
|
||||
}
|
||||
|
||||
// Build regex that captures separators
|
||||
var parts []string
|
||||
for _, sep := range separators {
|
||||
parts = append(parts, regexp.QuoteMeta(sep))
|
||||
}
|
||||
pattern := "(" + strings.Join(parts, "|") + ")"
|
||||
re := regexp.MustCompile(pattern)
|
||||
|
||||
splits := re.Split(text, -1)
|
||||
matches := re.FindAllString(text, -1)
|
||||
|
||||
var result []string
|
||||
for i, s := range splits {
|
||||
if s != "" {
|
||||
result = append(result, s)
|
||||
}
|
||||
if i < len(matches) && matches[i] != "" {
|
||||
result = append(result, matches[i])
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 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
|
||||
units := buildUnitsWithProtection(text, protected, separators)
|
||||
|
||||
// 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.
|
||||
func buildUnitsWithProtection(text string, protected []span, separators []string) []splitUnit {
|
||||
var units []splitUnit
|
||||
bytePos := 0
|
||||
runePos := 0
|
||||
|
||||
for _, p := range protected {
|
||||
if p.start > bytePos {
|
||||
pre := text[bytePos:p.start]
|
||||
parts := splitBySeparators(pre, separators)
|
||||
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)
|
||||
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)
|
||||
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.
|
||||
func mergeUnits(units []splitUnit, chunkSize, chunkOverlap int) []Chunk {
|
||||
if len(units) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var chunks []Chunk
|
||||
var current []splitUnit
|
||||
curLen := 0
|
||||
|
||||
for _, u := range units {
|
||||
uLen := runeLen(u.text)
|
||||
|
||||
// If adding this unit exceeds chunk size and we have content, flush
|
||||
if curLen+uLen > 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)
|
||||
}
|
||||
|
||||
current = append(current, u)
|
||||
curLen += uLen
|
||||
}
|
||||
|
||||
// Flush remaining
|
||||
if len(current) > 0 {
|
||||
chunks = append(chunks, buildChunk(current, len(chunks)))
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
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 units to keep for overlap and their total rune length.
|
||||
func computeOverlap(current []splitUnit, chunkOverlap, chunkSize, nextLen int) ([]splitUnit, int) {
|
||||
if chunkOverlap <= 0 {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// Walk backward from end, accumulating overlap
|
||||
overlapLen := 0
|
||||
startIdx := len(current)
|
||||
for i := len(current) - 1; i >= 0; i-- {
|
||||
uLen := runeLen(current[i].text)
|
||||
if overlapLen+uLen > chunkOverlap {
|
||||
break
|
||||
}
|
||||
// Check that overlap + next unit fits in chunk
|
||||
if overlapLen+uLen+nextLen > chunkSize {
|
||||
break
|
||||
}
|
||||
overlapLen += uLen
|
||||
startIdx = i
|
||||
}
|
||||
|
||||
// Skip leading separators-only units in the overlap
|
||||
for startIdx < len(current) {
|
||||
u := current[startIdx]
|
||||
trimmed := strings.TrimSpace(u.text)
|
||||
if trimmed == "" || isSeparatorOnly(u.text) {
|
||||
overlapLen -= runeLen(u.text)
|
||||
startIdx++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if startIdx >= len(current) {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
overlap := make([]splitUnit, len(current)-startIdx)
|
||||
copy(overlap, current[startIdx:])
|
||||
return overlap, overlapLen
|
||||
}
|
||||
|
||||
func isSeparatorOnly(s string) bool {
|
||||
for _, r := range s {
|
||||
if r != '\n' && r != '\r' && r != ' ' && r != '\t' && r != '。' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ExtractImageRefs extracts markdown image references from text.
|
||||
var imageRefPattern = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
|
||||
|
||||
func ExtractImageRefs(text string) []ImageRef {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package chunker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestSplitText_BasicASCII(t *testing.T) {
|
||||
text := "Hello world. This is a test."
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{". "}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) == 0 {
|
||||
t.Fatal("expected at least one chunk")
|
||||
}
|
||||
combined := ""
|
||||
for _, c := range chunks {
|
||||
combined += c.Content
|
||||
}
|
||||
if combined != text {
|
||||
t.Errorf("combined content mismatch:\n got: %q\n want: %q", combined, text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ChineseText_StartEndAreRuneOffsets(t *testing.T) {
|
||||
// Each Chinese character is 3 bytes in UTF-8 but 1 rune.
|
||||
// This test ensures Start/End are rune offsets, not byte offsets.
|
||||
text := "你好世界这是一个测试文本用于检验分割位置"
|
||||
runeCount := utf8.RuneCountInString(text)
|
||||
byteCount := len(text)
|
||||
if runeCount == byteCount {
|
||||
t.Fatal("test requires multi-byte characters")
|
||||
}
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
|
||||
c := chunks[0]
|
||||
if c.Start != 0 {
|
||||
t.Errorf("Start: got %d, want 0", c.Start)
|
||||
}
|
||||
if c.End != runeCount {
|
||||
t.Errorf("End: got %d, want %d (runeCount); byteCount would be %d",
|
||||
c.End, runeCount, byteCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ChineseMultiChunk_StartEndConsistency(t *testing.T) {
|
||||
// Build a long Chinese text that will be split into multiple chunks.
|
||||
line := "这是一段中文内容用于测试分割功能是否正确。"
|
||||
text := strings.Repeat(line+"\n\n", 20)
|
||||
text = strings.TrimRight(text, "\n")
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 30, ChunkOverlap: 5, Separators: []string{"\n\n", "\n", "。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) < 2 {
|
||||
t.Fatalf("expected multiple chunks, got %d", len(chunks))
|
||||
}
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
contentRunes := []rune(c.Content)
|
||||
contentRuneLen := len(contentRunes)
|
||||
|
||||
// End - Start must equal the rune length of the content
|
||||
spanLen := c.End - c.Start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: End(%d) - Start(%d) = %d, but rune len of content = %d",
|
||||
i, c.End, c.Start, spanLen, contentRuneLen)
|
||||
}
|
||||
|
||||
// Start must be non-negative and End must not exceed total rune count
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: Start is negative: %d", i, c.Start)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d exceeds total rune count %d", i, c.End, len(textRunes))
|
||||
}
|
||||
|
||||
// Content from rune slice must match the chunk content
|
||||
if c.Start >= 0 && c.End <= len(textRunes) {
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: content mismatch via rune slice:\n got: %q\n want: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_MixedChineseAndASCII(t *testing.T) {
|
||||
text := "Hello你好World世界Test测试"
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
c := chunks[0]
|
||||
expectedRuneLen := utf8.RuneCountInString(text)
|
||||
if c.End-c.Start != expectedRuneLen {
|
||||
t.Errorf("End(%d) - Start(%d) = %d, want rune len %d (byte len would be %d)",
|
||||
c.End, c.Start, c.End-c.Start, expectedRuneLen, len(text))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ProtectedPattern_ChineseContext(t *testing.T) {
|
||||
// Test protected markdown images in Chinese context.
|
||||
text := "这是前面的中文内容。这是后面的中文内容。"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 || c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: out of rune range [%d, %d), total runes %d",
|
||||
i, c.Start, c.End, len(textRunes))
|
||||
continue
|
||||
}
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: rune-slice mismatch:\n sliced: %q\n content: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_SimulateMergeSlicing(t *testing.T) {
|
||||
// Simulate what merge.go:104-106 does to ensure it won't panic.
|
||||
// This is the exact pattern that caused the production crash.
|
||||
line := "这是第一段内容用于模拟知识库问答的文本"
|
||||
text := line + "\n\n" + line + "\n\n" + line
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 25, ChunkOverlap: 5, Separators: []string{"\n\n", "\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) < 2 {
|
||||
t.Fatalf("need at least 2 chunks for overlap test, got %d", len(chunks))
|
||||
}
|
||||
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
prev := chunks[i-1]
|
||||
curr := chunks[i]
|
||||
|
||||
if curr.Start > prev.End {
|
||||
continue // non-overlapping, no merge needed
|
||||
}
|
||||
|
||||
// This is the exact merge.go logic:
|
||||
contentRunes := []rune(curr.Content)
|
||||
offset := len(contentRunes) - (curr.End - prev.End)
|
||||
|
||||
if offset < 0 {
|
||||
t.Fatalf("chunk[%d] merge panic: offset=%d < 0 (contentRunes=%d, curr.End=%d, prev.End=%d)",
|
||||
i, offset, len(contentRunes), curr.End, prev.End)
|
||||
}
|
||||
if offset > len(contentRunes) {
|
||||
t.Fatalf("chunk[%d] merge panic: offset=%d > len(contentRunes)=%d",
|
||||
i, offset, len(contentRunes))
|
||||
}
|
||||
|
||||
_ = string(contentRunes[offset:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_Empty(t *testing.T) {
|
||||
chunks := SplitText("", DefaultConfig())
|
||||
if len(chunks) != 0 {
|
||||
t.Errorf("expected 0 chunks for empty text, got %d", len(chunks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_SingleCharChinese(t *testing.T) {
|
||||
text := "你"
|
||||
cfg := SplitterConfig{ChunkSize: 10, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
if chunks[0].Start != 0 || chunks[0].End != 1 {
|
||||
t.Errorf("expected [0,1), got [%d,%d)", chunks[0].Start, chunks[0].End)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_LaTeXBlockInChinese(t *testing.T) {
|
||||
text := "前面的文字$$E=mc^2$$后面的文字"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
spanLen := c.End - c.Start
|
||||
contentRuneLen := utf8.RuneCountInString(c.Content)
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: span %d != rune len %d", i, spanLen, contentRuneLen)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d > total runes %d", i, c.End, len(textRunes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_CodeBlockInChinese(t *testing.T) {
|
||||
text := "中文描述\n```python\nprint('hello')\n```\n继续中文"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"\n\n", "\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 || c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: out of range [%d,%d), total %d", i, c.Start, c.End, len(textRunes))
|
||||
continue
|
||||
}
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: rune-slice mismatch:\n sliced: %q\n content: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_OverlapChunks_NonNegativeStart(t *testing.T) {
|
||||
// When overlap is used, start of the next chunk could go before 0 if broken.
|
||||
text := strings.Repeat("中文测试内容,", 50)
|
||||
cfg := SplitterConfig{ChunkSize: 20, ChunkOverlap: 5, Separators: []string{","}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: negative Start %d", i, c.Start)
|
||||
}
|
||||
if c.End < c.Start {
|
||||
t.Errorf("chunk[%d]: End %d < Start %d", i, c.End, c.Start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUnitsWithProtection_RuneOffsets(t *testing.T) {
|
||||
text := "你好世界"
|
||||
units := buildUnitsWithProtection(text, nil, []string{"\n"})
|
||||
|
||||
if len(units) != 1 {
|
||||
t.Fatalf("expected 1 unit, got %d", len(units))
|
||||
}
|
||||
|
||||
u := units[0]
|
||||
expectedRuneLen := 4 // 4 Chinese characters
|
||||
byteLen := len(text) // 12 bytes
|
||||
|
||||
if u.start != 0 {
|
||||
t.Errorf("start: got %d, want 0", u.start)
|
||||
}
|
||||
if u.end != expectedRuneLen {
|
||||
t.Errorf("end: got %d, want %d (rune len); byte len is %d", u.end, expectedRuneLen, byteLen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUnitsWithProtection_WithProtectedSpan(t *testing.T) {
|
||||
text := "前面后面"
|
||||
protected := protectedSpans(text)
|
||||
units := buildUnitsWithProtection(text, protected, []string{"\n"})
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, u := range units {
|
||||
contentRuneLen := utf8.RuneCountInString(u.text)
|
||||
spanLen := u.end - u.start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("unit[%d] %q: span %d != rune len %d (byte len %d)",
|
||||
i, u.text, spanLen, contentRuneLen, len(u.text))
|
||||
}
|
||||
if u.start < 0 || u.end > len(textRunes) {
|
||||
t.Errorf("unit[%d]: out of range [%d,%d), total runes %d",
|
||||
i, u.start, u.end, len(textRunes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitBySeparators(t *testing.T) {
|
||||
tests := []struct {
|
||||
text string
|
||||
separators []string
|
||||
wantParts int
|
||||
}{
|
||||
{"a\n\nb\n\nc", []string{"\n\n"}, 5},
|
||||
{"abc", []string{"\n"}, 1},
|
||||
{"a\nb\nc", []string{"\n"}, 5},
|
||||
{"", []string{"\n"}, 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
parts := splitBySeparators(tt.text, tt.separators)
|
||||
if len(parts) != tt.wantParts {
|
||||
t.Errorf("splitBySeparators(%q, %v): got %d parts %v, want %d",
|
||||
tt.text, tt.separators, len(parts), parts, tt.wantParts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractImageRefs(t *testing.T) {
|
||||
text := "hello  world  end"
|
||||
refs := ExtractImageRefs(text)
|
||||
if len(refs) != 2 {
|
||||
t.Fatalf("expected 2 refs, got %d", len(refs))
|
||||
}
|
||||
if refs[0].OriginalRef != "url1" || refs[0].AltText != "alt1" {
|
||||
t.Errorf("ref[0] mismatch: %+v", refs[0])
|
||||
}
|
||||
if refs[1].OriginalRef != "url2" || refs[1].AltText != "alt2" {
|
||||
t.Errorf("ref[1] mismatch: %+v", refs[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_LargeChineseDocument(t *testing.T) {
|
||||
// Simulate a real document with paragraphs of Chinese text.
|
||||
var sb strings.Builder
|
||||
for i := 0; i < 100; i++ {
|
||||
sb.WriteString(fmt.Sprintf("第%d段:这是一段用于测试的中文内容,包含各种常见的汉字和标点符号。", i))
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
text := sb.String()
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 50, ChunkOverlap: 10, Separators: []string{"\n\n", "\n", "。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
contentRuneLen := utf8.RuneCountInString(c.Content)
|
||||
spanLen := c.End - c.Start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: End(%d)-Start(%d)=%d != runeLen(%d)",
|
||||
i, c.End, c.Start, spanLen, contentRuneLen)
|
||||
}
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: negative Start %d", i, c.Start)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d > total runes %d", i, c.End, len(textRunes))
|
||||
}
|
||||
if c.Start >= 0 && c.End <= len(textRunes) {
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: content mismatch via rune-slice", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate merge.go logic on all overlapping chunk pairs
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
prev := chunks[i-1]
|
||||
curr := chunks[i]
|
||||
if curr.Start > prev.End {
|
||||
continue
|
||||
}
|
||||
contentRunes := []rune(curr.Content)
|
||||
offset := len(contentRunes) - (curr.End - prev.End)
|
||||
if offset < 0 || offset > len(contentRunes) {
|
||||
t.Fatalf("chunk[%d] merge would panic: offset=%d, contentRunes=%d, curr.End=%d, prev.End=%d",
|
||||
i, offset, len(contentRunes), curr.End, prev.End)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user