Skip to content

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

fix(docparser): decode GBK and UTF-16 text files in the simple reader (#4446)

Lukas12ffe1afe4c7
diff --git a/internal/infrastructure/docparser/builtin_converter.go b/internal/infrastructure/docparser/builtin_converter.go
index 2f20bc591..5ffa676a0 100644
--- a/internal/infrastructure/docparser/builtin_converter.go
+++ b/internal/infrastructure/docparser/builtin_converter.go
@@ -1,14 +1,19 @@
package docparser
import (
+ "bytes"
"context"
"fmt"
"net/http"
"net/url"
"path/filepath"
"strings"
+ "unicode/utf8"
"github.com/Tencent/WeKnora/internal/types"
+ "golang.org/x/text/encoding/charmap"
+ "golang.org/x/text/encoding/simplifiedchinese"
+ "golang.org/x/text/encoding/unicode"
)
// simpleFormats lists file extensions that Go can handle without the Python service.
@@ -55,11 +60,11 @@ func (b *SimpleFormatReader) Read(ctx context.Context, req *types.ReadRequest) (
switch {
case ft == "md" || ft == "markdown":
- return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
+ return &types.ReadResult{MarkdownContent: string(decodeText(req.FileContent))}, nil
case ft == "txt" || ft == "text":
- return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
+ return &types.ReadResult{MarkdownContent: string(decodeText(req.FileContent))}, nil
case ft == "csv":
- md, err := csvToMarkdownContext(ctx, req.FileContent, maxCSVMarkdownBytes)
+ md, err := csvToMarkdownContext(ctx, decodeText(req.FileContent), maxCSVMarkdownBytes)
if err != nil {
return nil, fmt.Errorf("csv conversion failed: %w", err)
}
@@ -186,6 +191,42 @@ func ensureOriginalImageRef(req *types.ReadRequest, mdContent string, imageRefs
return mdContent, imageRefs
}
+// decodeText returns a text file as UTF-8. Windows tools often save text in
+// another encoding: UTF-16 with a byte order mark (Notepad's "Unicode"), or
+// the code page of a Chinese locale, GBK, which Excel also writes for "CSV
+// (Comma delimited)". Taken as UTF-8, such a file reached the index as
+// invalid bytes. The order follows decode_bytes in docreader/utils/endecode.py,
+// which docreader's Markdown parser reads text with: UTF-8, then GB18030 (a
+// superset of GBK and GB2312), then Latin-1, which decodes any byte. Before
+// Latin-1 comes Windows-1252, what Western Windows tools save as "ANSI": it
+// differs from Latin-1 only in bytes 0x80-0x9F, which Latin-1 reads as
+// control characters where Windows-1252 has the curly quotes, dashes and
+// euro sign. A UTF-8 file, byte order mark included, is returned unchanged.
+func decodeText(data []byte) []byte {
+ if bytes.HasPrefix(data, []byte{0xff, 0xfe}) || bytes.HasPrefix(data, []byte{0xfe, 0xff}) {
+ if text, err := unicode.UTF16(unicode.BigEndian, unicode.ExpectBOM).NewDecoder().Bytes(data); err == nil {
+ return text
+ }
+ }
+ if utf8.Valid(data) {
+ return data
+ }
+ // The decoder writes U+FFFD for a byte sequence GB18030 does not define
+ // instead of failing, so that marks a file in some other encoding.
+ text, err := simplifiedchinese.GB18030.NewDecoder().Bytes(data)
+ if err == nil && !bytes.ContainsRune(text, utf8.RuneError) {
+ return text
+ }
+ // Windows-1252 leaves five bytes undefined and writes U+FFFD for them;
+ // Latin-1 then reads the file.
+ text, err = charmap.Windows1252.NewDecoder().Bytes(data)
+ if err == nil && !bytes.ContainsRune(text, utf8.RuneError) {
+ return text
+ }
+ text, _ = charmap.ISO8859_1.NewDecoder().Bytes(data)
+ return text
+}
+
// 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.
diff --git a/internal/infrastructure/docparser/text_decode_test.go b/internal/infrastructure/docparser/text_decode_test.go
new file mode 100644
index 000000000..facfba85e
--- /dev/null
+++ b/internal/infrastructure/docparser/text_decode_test.go
@@ -0,0 +1,70 @@
+package docparser
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "golang.org/x/text/encoding/simplifiedchinese"
+ "golang.org/x/text/encoding/unicode"
+)
+
+// TestSimpleFormatReaderDecodesTextEncodings checks that text files saved in
+// an encoding other than UTF-8 are read as text. They were passed on as raw
+// bytes, so a GBK .txt, a CSV from a Chinese Excel and a UTF-16 file from
+// Notepad reached the index as invalid UTF-8.
+func TestSimpleFormatReaderDecodesTextEncodings(t *testing.T) {
+ gbk := func(s string) []byte {
+ b, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(s))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ utf16 := func(order unicode.Endianness, s string) []byte {
+ b, err := unicode.UTF16(order, unicode.UseBOM).NewEncoder().Bytes([]byte(s))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ tests := []struct {
+ name string
+ fileType string
+ content []byte
+ want string
+ }{
+ {"GBK text", "txt", gbk("中文内容,测试"), "中文内容,测试"},
+ {"GBK markdown", "md", gbk("# 标题\n\n正文"), "# 标题\n\n正文"},
+ {"GBK CSV from Excel", "csv", gbk("姓名,城市\n张三,北京\n"), "| 姓名 | 城市 |\n| --- | --- |\n| 张三 | 北京 |\n"},
+ {"UTF-16LE with BOM", "txt", utf16(unicode.LittleEndian, "Hello 世界"), "Hello 世界"},
+ {"UTF-16BE with BOM", "txt", utf16(unicode.BigEndian, "Hello 世界"), "Hello 世界"},
+ {"Latin-1 fallback", "txt", []byte("caf\xe9 \x81 menu"), "café \u0081 menu"},
+ // Notepad's "ANSI" on a Western Windows: GB18030 rejects the bytes
+ // around the quotes, and Latin-1 read them as control characters.
+ {
+ "Windows-1252 punctuation", "txt",
+ []byte("\x93Quoted\x94 text \x96 costs 5 \x80."),
+ "\u201cQuoted\u201d text \u2013 costs 5 \u20ac.",
+ },
+ {"UTF-8 unchanged", "txt", []byte("plain UTF-8 文本"), "plain UTF-8 文本"},
+ // Kept byte for byte: the source locators map a verbatim UTF-8 text
+ // file onto itself and count past its byte order mark.
+ {"UTF-8 BOM kept", "md", []byte("\xef\xbb\xbf# Title\n"), "\xef\xbb\xbf# Title\n"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ res, err := (&SimpleFormatReader{}).Read(context.Background(), &types.ReadRequest{
+ FileType: tt.fileType,
+ FileName: "file." + tt.fileType,
+ FileContent: tt.content,
+ })
+ if err != nil {
+ t.Fatalf("Read: %v", err)
+ }
+ if res.MarkdownContent != tt.want {
+ t.Errorf("MarkdownContent = %q, want %q", res.MarkdownContent, tt.want)
+ }
+ })
+ }
+}