fix: ignore non-utf8 words when saving to db
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
@@ -21,6 +22,9 @@ func NewChunkRepository(db *gorm.DB) interfaces.ChunkRepository {
|
||||
|
||||
// CreateChunks creates multiple chunks in batches
|
||||
func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chunk) error {
|
||||
for _, chunk := range chunks {
|
||||
chunk.Content = common.CleanInvalidUTF8(chunk.Content)
|
||||
}
|
||||
return r.db.WithContext(ctx).CreateInBatches(chunks, 100).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/pgvector/pgvector-go"
|
||||
)
|
||||
@@ -59,7 +60,7 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string
|
||||
ChunkID: indexInfo.ChunkID,
|
||||
KnowledgeID: indexInfo.KnowledgeID,
|
||||
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
|
||||
Content: indexInfo.Content,
|
||||
Content: common.CleanInvalidUTF8(indexInfo.Content),
|
||||
}
|
||||
// Add embedding data if available in additionalParams
|
||||
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ToInterfaceSlice converts a slice of strings to a slice of empty interfaces.
|
||||
@@ -73,3 +74,27 @@ func ParseLLMJsonResponse(content string, target interface{}) error {
|
||||
// If no code block found, return the original error
|
||||
return err
|
||||
}
|
||||
|
||||
// CleanInvalidUTF8 移除字符串中的非法 UTF-8 字符和 \x00
|
||||
func CleanInvalidUTF8(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
|
||||
for i := 0; i < len(s); {
|
||||
r, size := utf8.DecodeRuneInString(s[i:])
|
||||
if r == utf8.RuneError && size == 1 {
|
||||
// 非法 UTF-8 字节,跳过
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if r == 0 {
|
||||
// NULL 字符 \x00,跳过
|
||||
i += size
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
i += size
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user