fix(docparser): resolve MinerU results by upload filename stem

MinerU keys file_parse results by the uploaded filename stem, so preserving
real basenames requires dynamic response lookup instead of results.document.
Also append FileType when the basename has no extension.
main
wizardchen 2026-08-13 18:09:25 +08:00 committed by lyingbug
parent 0eac47490b
commit 2308593ca0
2 changed files with 183 additions and 34 deletions

View File

@ -103,18 +103,18 @@ func (c *MinerUReader) Read(ctx context.Context, req *types.ReadRequest) (*types
}, nil
}
// mineruFileParseResponse mirrors the relevant fields from the MinerU API response.
type mineruFileParseResponse struct {
Results struct {
Document struct {
MDContent string `json:"md_content"`
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
} `json:"document"`
Files struct {
MDContent string `json:"md_content"`
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
} `json:"files"`
} `json:"results"`
type mineruFileEntry struct {
MDContent string `json:"md_content"`
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
}
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 {
@ -129,17 +129,64 @@ func minerUUploadFileName(fileName, fileType string) string {
}, cleanName)
cleanName = strings.TrimSpace(cleanName)
if cleanName != "" && cleanName != "." && cleanName != ".." && cleanName != "/" {
if filepath.Ext(cleanName) == "" {
if cleanType := minerUCleanFileType(fileType); cleanType != "" {
return cleanName + "." + cleanType
}
}
return cleanName
}
cleanType := strings.ToLower(strings.TrimSpace(fileType))
cleanType = strings.TrimPrefix(cleanType, ".")
if minerUFileTypePattern.MatchString(cleanType) {
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
}
func (c *MinerUReader) callFileParse(
ctx context.Context,
content []byte,
@ -174,8 +221,10 @@ func (c *MinerUReader) callFileParse(
_ = writer.WriteField(k, v)
}
uploadFileName := minerUUploadFileName(fileName, fileType)
// File part
part, err := writer.CreateFormFile("files", minerUUploadFileName(fileName, fileType))
part, err := writer.CreateFormFile("files", uploadFileName)
if err != nil {
return "", nil, fmt.Errorf("create form file: %w", err)
}
@ -224,25 +273,16 @@ func (c *MinerUReader) callFileParse(
c.logMinerUResponseStructure(rawMap, "")
}
var result mineruFileParseResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", nil, fmt.Errorf("decode response: %w", err)
mdContent, imagesB64, resultKey, err := parseMinerUFileParseResponse(respBody, uploadFileName)
if err != nil {
return "", nil, err
}
if resultKey != "" {
logger.Infof(context.Background(), "[MinerU] Using response path: results.%s", resultKey)
return mdContent, imagesB64, nil
}
// MinerU response schema differs by version/deployment:
// - older/self-hosted variants: results.document.*
// - some variants: results.files.*
// Prefer document when available, then fallback to files.
if result.Results.Document.MDContent != "" || len(result.Results.Document.Images) > 0 {
logger.Infof(context.Background(), "[MinerU] Using response path: results.document")
return result.Results.Document.MDContent, result.Results.Document.Images, nil
}
if result.Results.Files.MDContent != "" || len(result.Results.Files.Images) > 0 {
logger.Infof(context.Background(), "[MinerU] Using response path: results.files")
return result.Results.Files.MDContent, result.Results.Files.Images, nil
}
logger.Errorf(context.Background(), "[MinerU] Response has no markdown/images under results.document or results.files")
logger.Errorf(context.Background(), "[MinerU] Response has no markdown/images under results")
return "", nil, nil
}

View File

@ -3,6 +3,7 @@ package docparser
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@ -35,6 +36,100 @@ func TestNewMinerUReaderResolvesParseMethod(t *testing.T) {
}
}
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() {
@ -73,6 +168,20 @@ func TestMinerUReaderPreservesMultipartFilename(t *testing.T) {
}
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) {
got := capturedRequest{method: r.Method, path: r.URL.Path}
file, header, err := r.FormFile("files")
@ -87,7 +196,7 @@ func TestMinerUReaderPreservesMultipartFilename(t *testing.T) {
}
captured <- got
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"results":{"document":{"md_content":"ok","images":{}}}}`)
_, _ = w.Write(responseBody)
}))
defer server.Close()