fix(docparser): preserve filename extension in MinerU multipart uploads
parent
4e53aa9d77
commit
0eac47490b
|
|
@ -11,6 +11,7 @@ import (
|
|||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
|
@ -23,7 +24,10 @@ import (
|
|||
|
||||
const mineruTimeout = 1000 * time.Second // large docs can take a while
|
||||
|
||||
var b64DataURIPattern = regexp.MustCompile(`^data:image/(\w+);base64,(.+)$`)
|
||||
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.
|
||||
type MinerUReader struct {
|
||||
|
|
@ -76,7 +80,7 @@ func (c *MinerUReader) Read(ctx context.Context, req *types.ReadRequest) (*types
|
|||
|
||||
logger.Infof(context.Background(), "[MinerU] Parsing file=%s size=%d via %s", req.FileName, len(content), c.endpoint)
|
||||
|
||||
mdContent, imagesB64, err := c.callFileParse(ctx, content)
|
||||
mdContent, imagesB64, err := c.callFileParse(ctx, content, req.FileName, req.FileType)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MinerU file_parse: %w", err)
|
||||
}
|
||||
|
|
@ -113,7 +117,35 @@ type mineruFileParseResponse struct {
|
|||
} `json:"results"`
|
||||
}
|
||||
|
||||
func (c *MinerUReader) callFileParse(ctx context.Context, content []byte) (string, map[string]string, error) {
|
||||
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 != "/" {
|
||||
return cleanName
|
||||
}
|
||||
|
||||
cleanType := strings.ToLower(strings.TrimSpace(fileType))
|
||||
cleanType = strings.TrimPrefix(cleanType, ".")
|
||||
if minerUFileTypePattern.MatchString(cleanType) {
|
||||
return "document." + cleanType
|
||||
}
|
||||
return "document"
|
||||
}
|
||||
|
||||
func (c *MinerUReader) callFileParse(
|
||||
ctx context.Context,
|
||||
content []byte,
|
||||
fileName string,
|
||||
fileType string,
|
||||
) (string, map[string]string, error) {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
|
|
@ -143,7 +175,7 @@ func (c *MinerUReader) callFileParse(ctx context.Context, content []byte) (strin
|
|||
}
|
||||
|
||||
// File part
|
||||
part, err := writer.CreateFormFile("files", "document")
|
||||
part, err := writer.CreateFormFile("files", minerUUploadFileName(fileName, fileType))
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("create form file: %w", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,16 @@
|
|||
package docparser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
func TestNewMinerUReaderResolvesParseMethod(t *testing.T) {
|
||||
|
|
@ -28,6 +35,95 @@ func TestNewMinerUReaderResolvesParseMethod(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
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)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
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")
|
||||
_, _ = io.WriteString(w, `{"results":{"document":{"md_content":"ok","images":{}}}}`)
|
||||
}))
|
||||
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",
|
||||
|
|
|
|||
Loading…
Reference in New Issue