chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,255 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/utils"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/google/uuid"
)
const (
academyCloudReaderBaseURL = "https://weknora.weixin.qq.com/api/v1/doc"
// defaultAcademyCloudPollTimeout bounds how long one async task is polled;
// ACADEMY_ACADEMYCLOUD_TIMEOUT overrides it. It must stay below
// ACADEMY_DOCREADER_CALL_TIMEOUT (default 30m) or the hardcoded value, not
// the configured one, is what fails a slow parse.
defaultAcademyCloudPollTimeout = 20 * time.Minute
)
// AcademyCloudSignedDocumentReader implements the docreader HTTP protocol with AcademyCloud signing.
type AcademyCloudSignedDocumentReader struct {
appID string
apiKey string
client *http.Client
initialPollInterval time.Duration
maxPollInterval time.Duration
pollTimeout time.Duration
}
func NewAcademyCloudSignedDocumentReader(appID, apiKey string) (*AcademyCloudSignedDocumentReader, error) {
if appID == "" {
return nil, fmt.Errorf("AcademyCloud appID is required")
}
if apiKey == "" {
return nil, fmt.Errorf("AcademyCloud apiKey is required")
}
clientCfg := secutils.DefaultSSRFSafeHTTPClientConfig()
clientCfg.Timeout = 500 * time.Minute
return &AcademyCloudSignedDocumentReader{
appID: appID,
apiKey: apiKey,
initialPollInterval: 500 * time.Millisecond,
maxPollInterval: 10 * time.Second,
pollTimeout: requestTimeoutFromEnv("ACADEMY_ACADEMYCLOUD_TIMEOUT", defaultAcademyCloudPollTimeout),
client: secutils.NewSSRFSafeHTTPClient(clientCfg),
}, nil
}
func (p *AcademyCloudSignedDocumentReader) Reconnect(addr string) error {
return nil
}
func (p *AcademyCloudSignedDocumentReader) IsConnected() bool { return true }
func (p *AcademyCloudSignedDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
return []types.ParserEngineInfo{{
Name: AcademyCloudEngineName,
Description: "AcademyCloud signed docreader",
FileTypes: []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "pptx", "ppt"},
Available: true,
}}, nil
}
func (p *AcademyCloudSignedDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
logger.Infof(ctx, "[AcademyCloud] read start file=%q type=%q engine=%q hasURL=%v contentLen=%d requestID=%q",
req.FileName, req.FileType, req.ParserEngine, strings.TrimSpace(req.URL) != "", len(req.FileContent), req.RequestID)
body := httpReadRequest{
FileName: req.FileName,
FileType: req.FileType,
URL: req.URL,
Title: req.Title,
RequestID: req.RequestID,
Config: &httpReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
if len(req.FileContent) > 0 {
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
}
jsonBody, err := json.Marshal(body)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] marshal read request: %v", err)
return nil, fmt.Errorf("http marshal read request: %w", err)
}
httpReq, err := p.newSignedRequest(ctx, http.MethodPost, academyCloudReaderBaseURL+"/reader", jsonBody)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] signed read request: %v", err)
return nil, err
}
resp, err := p.client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http read request failed: %v", err)
return nil, fmt.Errorf("http read failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
logger.Errorf(context.Background(), "[AcademyCloud] http read unexpected status %d: %s", resp.StatusCode, string(bodyBytes))
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
}
var submit academyCloudAsyncSubmitResponse
if err := json.NewDecoder(resp.Body).Decode(&submit); err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] decode read submit response: %v", err)
return nil, fmt.Errorf("http decode read submit response: %w", err)
}
if strings.TrimSpace(submit.TaskID) == "" {
logger.Errorf(context.Background(), "[AcademyCloud] submit response missing task_id (status=%q message=%q)", submit.Status, submit.Message)
return nil, fmt.Errorf("academycloud docreader submit response missing task_id")
}
logger.Infof(ctx, "[AcademyCloud] task submitted task_id=%s file=%q type=%q", submit.TaskID, req.FileName, req.FileType)
return p.pollTaskResult(ctx, submit.TaskID)
}
type academyCloudAsyncSubmitResponse struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Message string `json:"message"`
CreatedAt int64 `json:"created_at"`
}
type academyCloudAsyncTaskResponse struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Message string `json:"message"`
Progress float64 `json:"progress"`
Result *httpReadResponse `json:"result"`
Error string `json:"error"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func (p *AcademyCloudSignedDocumentReader) pollTaskResult(ctx context.Context, taskID string) (*types.ReadResult, error) {
pollCtx := ctx
if p.pollTimeout > 0 {
var cancel context.CancelFunc
pollCtx, cancel = context.WithTimeout(ctx, p.pollTimeout)
defer cancel()
}
statusURL := academyCloudReaderBaseURL + "/" + taskID
currentInterval := p.initialPollInterval
for {
httpReq, err := p.newSignedRequest(pollCtx, http.MethodGet, statusURL, nil)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] poll signed request task_id=%s: %v", taskID, err)
return nil, err
}
resp, err := p.client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http poll task_id=%s failed: %v", taskID, err)
return nil, fmt.Errorf("http poll task failed: %w", err)
}
var taskResp academyCloudAsyncTaskResponse
func() {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("http poll task status %d: %s", resp.StatusCode, string(bodyBytes))
logger.Errorf(context.Background(), "[AcademyCloud] poll task_id=%s status %d: %s", taskID, resp.StatusCode, string(bodyBytes))
return
}
if decodeErr := json.NewDecoder(resp.Body).Decode(&taskResp); decodeErr != nil {
err = fmt.Errorf("http decode task response: %w", decodeErr)
logger.Errorf(context.Background(), "[AcademyCloud] poll task_id=%s decode response: %v", taskID, decodeErr)
}
}()
if err != nil {
return nil, err
}
switch taskResp.Status {
case "completed":
if taskResp.Result == nil {
logger.Infof(ctx, "[AcademyCloud] task_id=%s completed with no result payload", taskID)
return &types.ReadResult{}, nil
}
res := fromHTTPReadResponse(taskResp.Result)
if res.Error != "" {
logger.Errorf(ctx, "[AcademyCloud] task_id=%s completed with result.error: %s", taskID, res.Error)
} else {
logger.Debugf(ctx, "[AcademyCloud] task_id=%s completed ok markdownLen=%d", taskID, len(res.MarkdownContent))
}
return res, nil
case "failed":
if taskResp.Error != "" {
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s failed: %s", taskID, taskResp.Error)
return nil, fmt.Errorf("academycloud docreader task failed: %s", taskResp.Error)
}
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s failed: %s", taskID, taskResp.Message)
return nil, fmt.Errorf("academycloud docreader task failed: %s", taskResp.Message)
case "cancelled":
if taskResp.Error != "" {
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s cancelled: %s", taskID, taskResp.Error)
return nil, fmt.Errorf("academycloud docreader task cancelled: %s", taskResp.Error)
}
logger.Errorf(context.Background(), "[AcademyCloud] task_id=%s cancelled", taskID)
return nil, fmt.Errorf("academycloud docreader task cancelled")
}
if err := pollCtx.Err(); err != nil {
logger.Errorf(ctx, "[AcademyCloud] poll task_id=%s aborted before sleep: %v", taskID, err)
return nil, err
}
// Exponential backoff: multiply by 1.5 each time, cap at maxPollInterval
select {
case <-pollCtx.Done():
logger.Errorf(ctx, "[AcademyCloud] poll task_id=%s stopped: %v", taskID, pollCtx.Err())
return nil, pollCtx.Err()
case <-time.After(currentInterval):
// Update interval for next iteration
nextInterval := time.Duration(float64(currentInterval) * 1.5)
if nextInterval > p.maxPollInterval {
nextInterval = p.maxPollInterval
}
currentInterval = nextInterval
}
}
}
func (p *AcademyCloudSignedDocumentReader) newSignedRequest(ctx context.Context, method, url string, body []byte) (*http.Request, error) {
requestID := uuid.New().String()
if len(body) == 0 {
body = []byte("{}")
}
httpReq, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
if err != nil {
logger.Errorf(context.Background(), "[AcademyCloud] http new request %s %s: %v", method, url, err)
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.ContentLength = int64(len(body))
for k, v := range utils.Sign(p.appID, p.apiKey, requestID, string(body)) {
httpReq.Header.Set(k, v)
}
return httpReq, nil
}
// PreprocessImage is not offered by the cloud-signed reader: page straightening
// runs in the local docreader service, while this reader talks to AcademyCloud.
// It reports that as a verdict — fallback=true, no error — so the caller's only
// fallback (OCR the original bytes) needs no special case and nothing looks like
// a failure in the logs.
func (p *AcademyCloudSignedDocumentReader) PreprocessImage(_ context.Context, _ []byte) ([]byte, bool, error) {
return nil, true, nil
}
@@ -0,0 +1,231 @@
// Package anydoc converts office documents to Markdown inside the Go process,
// without the Python docreader service.
//
// The conversion itself is the anydoc Rust library, linked as a static archive
// through cgo (see third_party/anydoc-go). That archive needs a Rust toolchain
// to produce, so it is opt-in: only builds tagged `anydoc` link it. Every other
// build compiles the stub in backend_stub.go, where Available reports false and
// the engine registry hides the engine with a reason the UI can show.
//
// The exported surface is deliberately narrow — bytes in, Markdown and embedded
// images out — so the backend can be replaced (a WASI runtime, a future
// upstream Go module) without touching the parser code that calls it.
package anydoc
import (
"errors"
"fmt"
"path/filepath"
"slices"
"strings"
)
// ImageDir is the markdown path prefix for extracted images. The image
// resolver matches references by this path and swaps them for storage URLs.
const ImageDir = "images/"
// Result is one converted document.
type Result struct {
// Markdown is GitHub-Flavored Markdown for the whole document.
// When WithAssets is set, embedded images appear in place as
// `![alt](images/image-N.ext)` via anydoc's official serializer.
Markdown string
// Assets are the images embedded in the document, in document order.
// Always empty for PDF, which anydoc renders straight to Markdown
// without a document model.
Assets []Asset
// AssetsError explains why Assets is empty when images were asked for.
// The document-model parse is what both extracts images and places them
// in the markdown; when it fails, Markdown still comes from the text-only
// renderer so the conversion succeeds and the caller decides whether to
// log or ignore the loss.
AssetsError error
}
// Asset is one image embedded in a document.
type Asset struct {
// ID is the document-model asset index, as referenced by in-place image
// sources. It is stable for a single conversion.
ID uint64
// Name is a generated, extension-carrying file name ("image-1.png"):
// embedded assets have no name of their own inside the container.
Name string
// MediaType is the IANA media type the container declared.
MediaType string
// Data is the raw image bytes.
Data []byte
// Alt is the image's alternative text as the document author wrote it,
// empty when the document carries none.
Alt string
// Section is the text of the nearest heading above the image, empty when
// the image sits before the first heading.
Section string
}
// Options tunes a single conversion.
type Options struct {
// Format names the parser explicitly ("docx", "csv", ...). Empty means
// the format is detected from the content, which every format except
// CSV carries a signature for.
Format string
// WithAssets extracts embedded images and renders them in place in the
// markdown using anydoc's official GFM serializer (asset images are
// rewritten to `images/image-N.ext` links first). Ignored for PDF.
WithAssets bool
}
// ErrUnavailable is returned by Convert when the binding is not linked into
// this build. Callers that can fall back to another engine should check for it
// with errors.Is.
var ErrUnavailable = errors.New("anydoc: binding not built into this binary")
// ErrResourceLimit marks a permanent anydoc rejection: the document exceeds a
// parser budget (for example max_xml_nodes) and retrying the same bytes cannot
// succeed. Callers detect it with errors.Is. The wrapped error's text names
// the limit the converter reported.
var ErrResourceLimit = errors.New("document is too large for the parser")
// resourceLimiter is the method set anydoc's *ConvertError uses to report a
// parser budget failure. The cgo binding implements it; the default build does
// not import that package, so classification goes through this interface.
type resourceLimiter interface {
ResourceLimit() bool
LimitDetail() string
}
// permanentResourceLimit is the errors.Is(ErrResourceLimit) wrapper. Error
// keeps the user-facing reason and the converter's limit detail, without the
// transport prefixes that sit further down the chain.
type permanentResourceLimit struct {
detail string
cause error
}
func (e *permanentResourceLimit) Error() string {
if e.detail == "" {
return ErrResourceLimit.Error()
}
return ErrResourceLimit.Error() + ": " + e.detail
}
func (e *permanentResourceLimit) Unwrap() error { return e.cause }
func (e *permanentResourceLimit) Is(target error) bool { return target == ErrResourceLimit }
// markResourceLimit wraps a converter error whose kind is resource_limit.
// Other errors, including untyped text that merely mentions the kind, are
// returned unchanged so a transient failure can still be retried.
func markResourceLimit(err error) error {
if err == nil {
return nil
}
var limiter resourceLimiter
if !errors.As(err, &limiter) || !limiter.ResourceLimit() {
return err
}
return &permanentResourceLimit{detail: strings.TrimSpace(limiter.LimitDetail()), cause: err}
}
// supportedExtensions are the file types anydoc converts, mapped to the format
// name its parser selector uses. The list is static so that engine metadata
// (file types shown in the UI) is identical whether or not the binding is
// linked in.
var supportedExtensions = map[string]string{
"doc": "doc",
"docx": "docx",
"docm": "docx",
"odt": "odt",
"rtf": "rtf",
"ppt": "ppt",
"pptx": "pptx",
"pptm": "pptx",
"odp": "odp",
"xls": "xlsx",
"xlsx": "xlsx",
"xlsm": "xlsx",
"ods": "ods",
"epub": "epub",
"csv": "csv",
"pdf": "pdf",
}
// SupportedFileTypes returns the extensions anydoc can convert, sorted so the
// engine list is stable across restarts.
func SupportedFileTypes() []string {
types := make([]string, 0, len(supportedExtensions))
for ext := range supportedExtensions {
types = append(types, ext)
}
slices.Sort(types)
return types
}
// FormatForFile resolves the anydoc format name for a file type or file name.
// ok is false for anything anydoc does not convert.
func FormatForFile(fileType, fileName string) (format string, ok bool) {
ext := normalizeExt(fileType)
if ext == "" {
ext = normalizeExt(filepath.Ext(fileName))
}
format, ok = supportedExtensions[ext]
return format, ok
}
// Supports reports whether anydoc converts this file type, regardless of
// whether the binding is linked into this build.
func Supports(fileType, fileName string) bool {
_, ok := FormatForFile(fileType, fileName)
return ok
}
// Available reports whether conversions can actually run in this binary.
func Available() bool { return backendAvailable() }
// UnavailableReason explains, for the UI, why Available is false. It returns
// "" when the binding is available.
func UnavailableReason() string { return backendUnavailableReason() }
// Version reports the anydoc release the linked binding was built from, or ""
// when no binding is linked.
func Version() string { return backendVersion() }
// Convert turns document bytes into Markdown. It returns ErrUnavailable when
// the binding is not linked into this build.
func Convert(data []byte, opts Options) (*Result, error) {
if len(data) == 0 {
return nil, fmt.Errorf("anydoc: empty document")
}
if !backendAvailable() {
return nil, fmt.Errorf("%w: %s", ErrUnavailable, backendUnavailableReason())
}
// PDF has no document model, so asset extraction would only produce an
// error the caller has to special-case. Drop the request instead.
if opts.Format == "pdf" {
opts.WithAssets = false
}
result, err := backendConvert(data, opts)
if err != nil {
err = markResourceLimit(err)
}
return result, err
}
// PDFNeedsOCR reports whether a Convert error means the PDF has no usable
// text layer. Scanned exam papers fail this way; the caller should fall back
// to an engine that can rasterize pages for OCR.
func PDFNeedsOCR(err error) bool {
if err == nil {
return false
}
var ocrError interface{ NeedsOCR() bool }
if errors.As(err, &ocrError) && ocrError.NeedsOCR() {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "ocr is required") ||
strings.Contains(msg, "no extractable text")
}
func normalizeExt(s string) string {
return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s), "."))
}
@@ -0,0 +1,84 @@
package anydoc
import (
"errors"
"slices"
"testing"
)
func TestFormatForFileResolvesTypeAndName(t *testing.T) {
cases := []struct {
name string
fileType string
fileName string
wantFormat string
wantOK bool
}{
{name: "file type", fileType: "docx", wantFormat: "docx", wantOK: true},
{name: "dotted file type", fileType: ".DOCX", wantFormat: "docx", wantOK: true},
{name: "macro format maps to base format", fileType: "pptm", wantFormat: "pptx", wantOK: true},
{name: "legacy excel maps to xlsx parser", fileType: "xls", wantFormat: "xlsx", wantOK: true},
{name: "falls back to file name", fileName: "report.odt", wantFormat: "odt", wantOK: true},
{name: "unsupported type", fileType: "png", wantOK: false},
{name: "nothing to go on", wantOK: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
format, ok := FormatForFile(tc.fileType, tc.fileName)
if ok != tc.wantOK {
t.Fatalf("FormatForFile(%q, %q) ok = %v, want %v", tc.fileType, tc.fileName, ok, tc.wantOK)
}
if format != tc.wantFormat {
t.Fatalf("FormatForFile(%q, %q) = %q, want %q", tc.fileType, tc.fileName, format, tc.wantFormat)
}
})
}
}
// The engine list must look the same whether or not the converter is linked
// in, so that the UI can show the file types with a "not built in" reason.
func TestSupportedFileTypesIsStableAndSorted(t *testing.T) {
types := SupportedFileTypes()
if !slices.IsSorted(types) {
t.Fatalf("SupportedFileTypes is not sorted: %v", types)
}
for _, want := range []string{"docx", "pptx", "xlsx", "epub", "pdf", "csv"} {
if !slices.Contains(types, want) {
t.Errorf("SupportedFileTypes does not include %q: %v", want, types)
}
}
}
func TestPDFNeedsOCR(t *testing.T) {
if PDFNeedsOCR(nil) {
t.Fatal("nil error was treated as needing OCR")
}
if !PDFNeedsOCR(errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required")) {
t.Error("scanned-PDF error was not detected")
}
if PDFNeedsOCR(errors.New("not a readable zip archive")) {
t.Error("unrelated error was treated as needing OCR")
}
}
func TestConvertRejectsEmptyInput(t *testing.T) {
if _, err := Convert(nil, Options{Format: "docx"}); err == nil {
t.Fatal("Convert(nil) succeeded, want an error")
}
}
// Without the build tag there is no converter, and callers must be able to
// detect that so they can fall back to another engine.
func TestConvertReportsUnavailableBackend(t *testing.T) {
if Available() {
t.Skip("converter is linked into this build")
}
_, err := Convert([]byte("id,name\n1,a\n"), Options{Format: "csv"})
if !errors.Is(err, ErrUnavailable) {
t.Fatalf("Convert error = %v, want ErrUnavailable", err)
}
if UnavailableReason() == "" {
t.Error("UnavailableReason is empty while the converter is unavailable")
}
}
@@ -0,0 +1,227 @@
//go:build anydoc && cgo
package anydoc
import (
"fmt"
"strings"
upstream "github.com/firecrawl/anydoc/go"
)
// This build links the anydoc Rust archive through the upstream cgo bindings
// (vendored under third_party/anydoc-go until they are published as a module).
// Conversion runs in-process: no subprocess, no HTTP hop, no Python.
// *ConvertError must keep implementing resourceLimiter so Convert can classify
// a parser budget failure without this file's build tag.
var _ resourceLimiter = (*upstream.ConvertError)(nil)
func backendAvailable() bool { return true }
func backendUnavailableReason() string { return "" }
func backendVersion() string { return upstream.Version }
func backendConvert(data []byte, opts Options) (*Result, error) {
format, err := upstreamFormat(opts.Format)
if err != nil {
return nil, err
}
if !opts.WithAssets {
markdown, err := upstream.ToMarkdownBytes(data, format)
if err != nil {
return nil, fmt.Errorf("anydoc: markdown conversion failed: %w", err)
}
return &Result{Markdown: markdown}, nil
}
// Official GFM serializer after rewriting Asset images to External URLs
// (`images/image-N.ext`). One Rust parse supplies both the original model
// (for image bytes and placements) and the rendered Markdown.
document, markdown, err := upstream.ToDocumentWithAssetLinks(data, format)
if err != nil {
markdown, mdErr := upstream.ToMarkdownBytes(data, format)
if mdErr != nil {
return nil, fmt.Errorf("anydoc: markdown conversion failed: %w", mdErr)
}
return &Result{
Markdown: markdown,
AssetsError: fmt.Errorf("anydoc: image extraction failed: %w", err),
}, nil
}
return &Result{Markdown: markdown, Assets: collectAssets(document)}, nil
}
// upstreamFormat maps our format name onto the binding's constant. An empty
// name means "detect from content".
func upstreamFormat(name string) (*upstream.Format, error) {
if name == "" {
return nil, nil
}
format, ok := upstream.FormatFromExtension(name)
if !ok {
return nil, fmt.Errorf("anydoc: unsupported format %q", name)
}
return &format, nil
}
// collectAssets names each embedded image after its position in the document,
// because containers store assets without a usable file name of their own, and
// attaches the alt text and section the image appeared under.
func collectAssets(document *upstream.Document) []Asset {
if document == nil || len(document.Assets) == 0 {
return nil
}
placements := placeAssets(document.Blocks)
assets := make([]Asset, 0, len(document.Assets))
for i, asset := range document.Assets {
if len(asset.Data) == 0 {
continue
}
placement := placements[uint64(i)]
assets = append(assets, Asset{
ID: uint64(i),
Name: fmt.Sprintf("image-%d%s", i+1, extensionFor(asset.MediaType)),
MediaType: asset.MediaType,
Data: asset.Data,
Alt: placement.alt,
Section: placement.section,
})
}
return assets
}
// placement is where in the document an asset was referenced from.
type placement struct {
alt string
section string
}
// placeAssets walks the document body and records, per asset, the alt text of
// the image that referenced it and the heading it sat under. The walk
// recurses into lists, tables, and quotes, since an image can be nested
// anywhere a paragraph can.
func placeAssets(blocks []upstream.Block) map[uint64]placement {
placements := make(map[uint64]placement)
section := ""
walkBlocks(blocks, &section, placements)
return placements
}
func walkBlocks(blocks []upstream.Block, section *string, placements map[uint64]placement) {
for _, block := range blocks {
switch block.Kind {
case "heading":
*section = inlineText(block.Content)
walkInlines(block.Content, *section, placements)
case "paragraph":
walkInlines(block.Content, *section, placements)
case "block_quote":
walkBlocks(block.Blocks, section, placements)
case "list":
if block.List != nil {
for _, item := range block.List.Items {
walkBlocks(item.Blocks, section, placements)
}
}
case "table":
if block.Table != nil {
for _, row := range block.Table.Grid {
for _, slot := range row {
if slot.Cell != nil {
walkBlocks(slot.Cell.Blocks, section, placements)
}
}
}
}
}
}
}
func walkInlines(inlines []upstream.Inline, section string, placements map[uint64]placement) {
for _, inline := range inlines {
switch inline.Kind {
case "image":
if inline.Source == nil || inline.Source.Kind != "asset" || inline.Source.AssetID == nil {
continue
}
alt := ""
if inline.Alt != nil {
alt = strings.TrimSpace(*inline.Alt)
}
// First reference wins: the same asset can be placed more than
// once, and the earliest placement is the one a reader would
// associate it with.
if _, seen := placements[*inline.Source.AssetID]; !seen {
placements[*inline.Source.AssetID] = placement{alt: alt, section: section}
}
case "link":
walkInlines(inline.Content, section, placements)
}
}
}
// inlineText flattens inline content to plain text, which is all a heading is
// needed for here.
func inlineText(inlines []upstream.Inline) string {
var text strings.Builder
for _, inline := range inlines {
switch inline.Kind {
case "text", "math":
if inline.Text != nil {
text.WriteString(*inline.Text)
}
case "checkbox":
if inline.Checked != nil && *inline.Checked {
text.WriteString("[x]")
} else {
text.WriteString("[ ]")
}
case "link":
text.WriteString(inlineText(inline.Content))
}
}
return strings.TrimSpace(text.String())
}
// extensionFor returns the extension that the Markdown link for an embedded
// image carries.
//
// This table is one half of a contract with the Rust serializer. The link it
// writes (`images/image-N<ext>`, see third_party/anydoc-go/src/asset_links.rs)
// has to equal the ImageRef.OriginalRef built from this name, because
// ImageResolver looks the link up in a map keyed by that exact string. The
// media types and extensions below must therefore match `extension_for` in
// asset_links.rs exactly.
//
// It is deliberately a pure table. Asking the platform MIME registry made the
// answer depend on the host's /etc/mime.types, which is how EMF/WMF ended up
// as ".emf"/".wmf" here and ".bin" on the Rust side: the link never matched
// the ref and the image bytes were never stored. Unknown types fall back to
// ".bin" on both sides, so downstream storage never writes an extension-less
// blob.
func extensionFor(mediaType string) string {
switch strings.ToLower(strings.TrimSpace(mediaType)) {
case "image/jpeg", "image/jpg":
return ".jpg"
case "image/png":
return ".png"
case "image/gif":
return ".gif"
case "image/webp":
return ".webp"
case "image/bmp":
return ".bmp"
case "image/tiff":
return ".tiff"
case "image/svg+xml":
return ".svg"
case "image/emf":
return ".emf"
case "image/wmf":
return ".wmf"
}
return ".bin"
}
@@ -0,0 +1,24 @@
//go:build !anydoc || !cgo
package anydoc
// The default build links no converter: the anydoc archive is a Rust build
// artifact, and requiring a Rust toolchain to compile Academy would be a steep
// price for one optional engine. Everything still compiles and the engine
// registry simply reports the engine as unavailable.
const unavailableReason = "anydoc engine not built into this binary " +
"(rebuild with `make build-anydoc` / `-tags anydoc`; " +
"Docker images need `--build-arg WITH_ANYDOC=1`)"
func backendAvailable() bool { return false }
func backendUnavailableReason() string { return unavailableReason }
func backendVersion() string { return "" }
func backendConvert(_ []byte, _ Options) (*Result, error) {
// Convert checks Available first, so this is only reachable if a caller
// bypasses it.
return nil, ErrUnavailable
}
@@ -0,0 +1,151 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
var benchmarkDocuments = []string{
"doc/text.doc", "docx/text.docx", "ppt/pres.ppt", "pptx/pres.pptx",
"odt/text.odt", "ods/sheet.ods", "odp/pres.odp", "rtf/text.rtf",
"epub/book.epub", "xls/sheet.xls", "xlsx/sheet.xlsx",
"xlsb/handmade-sheet.xlsb", "csv/sheet.csv", "pdf/text.pdf",
}
// Synthetic size sweeps cover the Go/Rust document-copy path and the bounded
// hostile-PDF detector. They are separate from the upstream fixture comparison.
func BenchmarkConvertScaling(b *testing.B) {
for _, rows := range []int{100, 10000} {
b.Run(fmt.Sprintf("csv_%d_rows", rows), func(b *testing.B) {
data := []byte("name,quantity,description\n" +
strings.Repeat("widget,42,Quarterly shipping report\n", rows))
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := Convert(data, Options{Format: "csv", WithAssets: true})
if err != nil || result.AssetsError != nil {
b.Fatalf("conversion: %v", err)
}
}
})
}
for _, rows := range []int{100, 10000} {
b.Run(fmt.Sprintf("xlsx_%d_rows", rows), func(b *testing.B) {
data := largeWorkbook(b, rows)
result, err := Convert(data, Options{Format: "xlsx", WithAssets: true})
if err != nil || !strings.Contains(result.Markdown, fmt.Sprintf("row-%d", rows)) {
b.Fatalf("preflight: last row was lost, err=%v", err)
}
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
result, err := Convert(data, Options{Format: "xlsx", WithAssets: true})
if err != nil || result.AssetsError != nil {
b.Fatalf("conversion: %v", err)
}
}
})
}
for _, operators := range []int{40000, 200000} {
b.Run(fmt.Sprintf("pdf_%d_operators", operators), func(b *testing.B) {
data := unmatchedShowTextPDF(operators)
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
if _, err := Convert(data, Options{Format: "pdf"}); err != nil {
b.Fatal(err)
}
}
})
}
}
func largeWorkbook(t testing.TB, rows int) []byte {
t.Helper()
data := readFixture(t, "xlsx/sheet.xlsx")
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
var out bytes.Buffer
w := zip.NewWriter(&out)
for _, file := range r.File {
if file.Name == "xl/worksheets/sheet1.xml" {
continue
}
if err := w.Copy(file); err != nil {
t.Fatal(err)
}
}
var sheet strings.Builder
sheet.WriteString(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>`)
for row := 1; row <= rows; row++ {
fmt.Fprintf(&sheet, `<row r="%d"><c r="A%d" t="inlineStr"><is><t>row-%d</t></is></c>`+
`<c r="B%d"><v>42</v></c></row>`,
row, row, row, row)
}
sheet.WriteString(`</sheetData></worksheet>`)
part, err := w.Create("xl/worksheets/sheet1.xml")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte(sheet.String())); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
return out.Bytes()
}
func readFixture(t testing.TB, name string) []byte {
t.Helper()
data, err := os.ReadFile(filepath.Join("testdata", "upstream", name))
if err != nil {
t.Fatal(err)
}
return data
}
// WithAssets exercises the default reader path, including Rust parsing,
// the document ABI, Go decoding, image collection, and Markdown serialization.
// Input I/O is excluded. B/op measures Go allocations, not the Rust heap.
func BenchmarkConvert(b *testing.B) {
for _, name := range benchmarkDocuments {
b.Run(strings.Split(name, "/")[0], func(b *testing.B) {
data := readFixture(b, name)
format := strings.TrimPrefix(filepath.Ext(name), ".")
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
opts := Options{Format: format, WithAssets: true}
if result, err := Convert(data, opts); err != nil ||
result.Markdown == "" ||
result.AssetsError != nil {
b.Fatalf("preflight conversion: result=%+v err=%v", result, err)
}
b.ReportAllocs()
b.SetBytes(int64(len(data)))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
result, err := Convert(data, opts)
if err != nil || result.Markdown == "" || result.AssetsError != nil {
b.Errorf("conversion failed: result=%+v err=%v", result, err)
return
}
}
})
})
}
}
@@ -0,0 +1,379 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"fmt"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// These tests exercise the linked Rust converter, so they only build with the
// `anydoc` tag. Run them with:
//
// scripts/build-anydoc-lib.sh && go test -tags anydoc ./internal/infrastructure/docparser/...
// SupportedFileTypes is a static list, so that the engine can advertise its
// file types in builds that link no converter. This is the check that it still
// agrees with what the converter actually accepts, in either direction.
func TestSupportedFileTypesMatchTheConverter(t *testing.T) {
for _, fileType := range SupportedFileTypes() {
format, ok := FormatForFile(fileType, "")
if !ok {
t.Errorf("%q is advertised but maps to no format", fileType)
continue
}
if _, err := upstreamFormat(format); err != nil {
t.Errorf("%q maps to format %q, which the converter rejects: %v", fileType, format, err)
}
}
}
func TestConvertCSV(t *testing.T) {
result, err := Convert([]byte("quarter,widgets\nQ1,12\nQ2,15\n"), Options{Format: "csv"})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "| quarter | widgets |") {
t.Fatalf("expected a markdown table header, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "| Q1 | 12 |") {
t.Fatalf("expected the first data row, got:\n%s", result.Markdown)
}
}
func TestConvertDocxWithEmbeddedImage(t *testing.T) {
document := buildDocx(t)
result, err := Convert(document, Options{Format: "docx", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "# Quarterly report") {
t.Fatalf("expected the heading, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "Widgets shipped on time.") {
t.Fatalf("expected the body paragraph, got:\n%s", result.Markdown)
}
if !strings.Contains(result.Markdown, "Closing remarks.") {
t.Fatalf("expected the trailing paragraph, got:\n%s", result.Markdown)
}
if len(result.Assets) != 1 {
t.Fatalf("got %d assets, want 1", len(result.Assets))
}
asset := result.Assets[0]
if asset.Name != "image-1.png" {
t.Errorf("asset name = %q, want image-1.png", asset.Name)
}
if !bytes.Equal(asset.Data, onePixelPNG()) {
t.Errorf("asset data does not round-trip the embedded image")
}
if asset.Alt != "Shipping chart" {
t.Errorf("asset alt = %q, want %q", asset.Alt, "Shipping chart")
}
if asset.Section != "Quarterly report" {
t.Errorf("asset section = %q, want %q", asset.Section, "Quarterly report")
}
imageLink := "![Shipping chart](images/image-1.png)"
if !strings.Contains(result.Markdown, imageLink) {
t.Fatalf("expected the image in place, got:\n%s", result.Markdown)
}
before := strings.Index(result.Markdown, "Widgets shipped on time.")
at := strings.Index(result.Markdown, imageLink)
after := strings.Index(result.Markdown, "Closing remarks.")
if before < 0 || at < 0 || after < 0 || !(before < at && at < after) {
t.Fatalf("image is not between the surrounding paragraphs:\n%s", result.Markdown)
}
}
func TestConvertTextlessPDFNeedsOCR(t *testing.T) {
_, err := Convert(textlessPDF(), Options{Format: "pdf"})
if err == nil {
t.Fatal("Convert succeeded on a PDF with no text, want an error")
}
if !PDFNeedsOCR(err) {
t.Fatalf("Convert error = %v, want an OCR-required error", err)
}
}
// The ABI reports error messages through a thread-local slot that a second
// call reads, so a goroutine resumed on another OS thread would report an
// empty or someone else's message. The binding pins the goroutine for the
// pair; this is the regression test for that.
func TestErrorDetailSurvivesConcurrency(t *testing.T) {
const conversions = 4000
var wg sync.WaitGroup
var empty, crossed atomic.Int64
for i := 0; i < conversions; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// docx and xlsx failures carry distinctive messages, so a detail
// naming the other format proves it came from the wrong thread.
format, want, other := "docx", "not a readable zip archive", "not a readable workbook container"
if i%2 == 1 {
format, want, other = "xlsx", "not a readable workbook container", "not a readable zip archive"
}
_, err := Convert([]byte(fmt.Sprintf("garbage %d", i)), Options{Format: format})
if err == nil {
t.Errorf("Convert(garbage) succeeded")
return
}
detail := err.Error()
switch {
case strings.Contains(detail, other):
crossed.Add(1)
case !strings.Contains(detail, want):
empty.Add(1)
}
}(i)
}
wg.Wait()
if empty.Load() > 0 || crossed.Load() > 0 {
t.Fatalf("error details lost or crossed between goroutines: lost=%d crossed=%d (of %d)",
empty.Load(), crossed.Load(), conversions)
}
}
// Detection reads the container itself, so a document whose format is not
// named still converts.
func TestConvertDetectsFormatFromContent(t *testing.T) {
result, err := Convert(buildDocx(t), Options{})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "# Quarterly report") {
t.Fatalf("expected the heading, got:\n%s", result.Markdown)
}
}
func TestConvertRejectsGarbage(t *testing.T) {
if _, err := Convert([]byte("not a document at all"), Options{Format: "docx"}); err == nil {
t.Fatal("Convert succeeded on garbage input, want an error")
}
}
// PDF has no document model, so WithAssets has to be dropped rather than turn
// a working conversion into an error.
func TestConvertPDFIgnoresAssetRequest(t *testing.T) {
result, err := Convert(minimalPDF(), Options{Format: "pdf", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if !strings.Contains(result.Markdown, "Shipping summary") {
t.Fatalf("expected the page text, got:\n%s", result.Markdown)
}
if len(result.Assets) != 0 {
t.Errorf("got %d assets for a PDF, want 0", len(result.Assets))
}
}
// A PDF whose catalog holds a deeply nested array is the shape of
// RUSTSEC-2026-0187: lopdf 0.41 recursed per nesting level and killed the
// process with an uncatchable stack overflow, which no Go-side or Rust-side
// recover can contain. The pinned dependency in third_party/anydoc-go bounds
// the recursion, so this must come back as an ordinary error — and if a
// dependency bump ever reintroduces it, this test crashes rather than passing
// quietly.
func TestDeeplyNestedPDFFailsWithoutKillingTheProcess(t *testing.T) {
const depth = 50000
nested := strings.Repeat("[", depth) + strings.Repeat("]", depth)
_, err := Convert(nestedPDF(nested), Options{Format: "pdf"})
if err == nil {
t.Fatal("Convert succeeded on a PDF with no text, want an error")
}
}
// A show-text operator with no operand made the page-classification scan walk
// back over the whole content stream looking for one, so a stream of bare
// `] TJ` tokens cost time quadratic in its length: before pdf-inspector 1.14.2
// this input took 26 seconds of CPU, and a 2 MB one took nearly two minutes.
// Unbounded work is the half of the hostile-PDF problem that guarded() cannot
// catch — it never panics, it just holds the core — so the bound is pinned
// here. The budget is deliberately far above the ~7ms a bounded lookback needs:
// what it has to distinguish is linear from quadratic, not fast from slow.
func TestDetectorLookbackStaysLinear(t *testing.T) {
const (
operators = 200000
budget = 15 * time.Second
)
done := make(chan struct{})
go func() {
defer close(done)
// The result is irrelevant: the page carries one real text run, so
// this converts either way. Only how long it takes is under test.
_, _ = Convert(unmatchedShowTextPDF(operators), Options{Format: "pdf"})
}()
select {
case <-done:
case <-time.After(budget):
t.Fatalf("converting a PDF with %d unmatched TJ operators took over %s; "+
"the detector's operand lookback is no longer bounded", operators, budget)
}
}
// buildDocx writes the smallest OOXML package that carries a heading, a
// paragraph, and one embedded image.
func buildDocx(t *testing.T) []byte {
t.Helper()
parts := map[string]string{
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="png" ContentType="image/png"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>`,
"_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`,
"word/styles.xml": `<?xml version="1.0" encoding="UTF-8"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/>
<w:pPr><w:outlineLvl w:val="0"/></w:pPr>
</w:style>
</w:styles>`,
"word/_rels/document.xml.rels": `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/>
</Relationships>`,
"word/document.xml": `<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Quarterly report</w:t></w:r></w:p>
<w:p><w:r><w:t>Widgets shipped on time.</w:t></w:r></w:p>
<w:p><w:r><w:drawing><wp:inline><wp:docPr id="1" name="Chart" descr="Shipping chart"/>
<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic><pic:nvPicPr><pic:cNvPr id="1" name="Chart"/><pic:cNvPicPr/></pic:nvPicPr>
<pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill>
<pic:spPr/></pic:pic>
</a:graphicData></a:graphic>
</wp:inline></w:drawing></w:r></w:p>
<w:p><w:r><w:t>Closing remarks.</w:t></w:r></w:p>
</w:body>
</w:document>`,
}
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
for name, content := range parts {
writer, err := archive.Create(name)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if _, err := writer.Write([]byte(content)); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
image, err := archive.Create("word/media/image1.png")
if err != nil {
t.Fatalf("create image part: %v", err)
}
if _, err := image.Write(onePixelPNG()); err != nil {
t.Fatalf("write image part: %v", err)
}
if err := archive.Close(); err != nil {
t.Fatalf("close archive: %v", err)
}
return buf.Bytes()
}
// onePixelPNG is a 1x1 transparent PNG: the smallest thing a container will
// accept as an image part.
func onePixelPNG() []byte {
return []byte{
0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 'I', 'H', 'D', 'R',
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89,
0x00, 0x00, 0x00, 0x0a, 'I', 'D', 'A', 'T',
0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01,
0x0d, 0x0a, 0x2d, 0xb4,
0x00, 0x00, 0x00, 0x00, 'I', 'E', 'N', 'D', 0xae, 0x42, 0x60, 0x82,
}
}
// minimalPDF is a one-page PDF with a single text run, written by hand so the
// test carries no binary fixture.
func minimalPDF() []byte {
content := "BT /F1 12 Tf 20 100 Td (Shipping summary) Tj ET\n"
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R " +
"/Resources << /Font << /F1 5 0 R >> >> >>",
fmt.Sprintf("<< /Length %d >>\nstream\n%sendstream", len(content), content),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
})
}
// nestedPDF is a one-page PDF carrying the given nested value in its catalog.
func nestedPDF(nested string) []byte {
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R /Nested " + nested + " >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
})
}
// unmatchedShowTextPDF is a one-page PDF whose content stream shows text once
// and then repeats a TJ operator whose array operand is never opened.
func unmatchedShowTextPDF(operators int) []byte {
content := "BT /F1 12 Tf 20 100 Td (Shipping summary) Tj ET\n" +
strings.Repeat("] TJ\n", operators)
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R " +
"/Resources << /Font << /F1 5 0 R >> >> >>",
fmt.Sprintf("<< /Length %d >>\nstream\n%sendstream", len(content), content),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
})
}
// textlessPDF is a one-page PDF with no text stream: the shape of a scanned
// exam paper as far as pdf-inspector is concerned.
func textlessPDF() []byte {
return writePDF([]string{
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
})
}
func writePDF(objects []string) []byte {
var pdf bytes.Buffer
offsets := make([]int, len(objects))
pdf.WriteString("%PDF-1.4\n")
for i, object := range objects {
offsets[i] = pdf.Len()
fmt.Fprintf(&pdf, "%d 0 obj\n%s\nendobj\n", i+1, object)
}
xref := pdf.Len()
fmt.Fprintf(&pdf, "xref\n0 %d\n0000000000 65535 f \n", len(objects)+1)
for _, offset := range offsets {
fmt.Fprintf(&pdf, "%010d 00000 n \n", offset)
}
fmt.Fprintf(&pdf, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, xref)
return pdf.Bytes()
}
@@ -0,0 +1,89 @@
//go:build anydoc && cgo
package anydoc
import (
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
upstream "github.com/firecrawl/anydoc/go"
)
// ANYDOC_UPSTREAM_DIR points to the checked-out release tag. This opt-in
// upgrade check runs the full upstream corpus through our actual Go ABI and
// compares Markdown/error details to the upstream Rust snapshots.
func TestUpstreamCorpus(t *testing.T) {
root := os.Getenv("ANYDOC_UPSTREAM_DIR")
if root == "" {
t.Skip("set ANYDOC_UPSTREAM_DIR to an anydoc release checkout")
}
snapshots, err := filepath.Glob(filepath.Join(root, "tests/snapshots/snapshots__*.snap"))
if err != nil || len(snapshots) == 0 {
t.Fatalf("no snapshots: %v", err)
}
for _, path := range snapshots {
name := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "snapshots__"), ".snap")
parts := strings.Split(name, "__")
if len(parts) != 2 {
continue
}
t.Run(name, func(t *testing.T) {
data, err := os.ReadFile(filepath.Join(root, "tests/fixtures", parts[0], parts[1]))
if err != nil {
t.Fatal(err)
}
snapshot, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
_, expected, ok := strings.Cut(string(snapshot[4:]), "---\n")
if !ok {
t.Fatal("invalid snapshot header")
}
format, ok := upstream.FormatFromExtension(strings.TrimPrefix(filepath.Ext(parts[1]), "."))
if !ok {
t.Fatal("unrecognized fixture extension")
}
// The Go binding rejects empty slices before entering C, retaining
// its established empty-input error instead of the ZIP diagnostic.
if len(data) == 0 {
if !strings.HasPrefix(expected, "ERROR:") {
t.Fatal("empty fixture should fail")
}
expected = "ERROR: empty input"
}
actual, err := upstream.ToMarkdownBytes(data, &format)
if err != nil {
var typed *upstream.ConvertError
if !errors.As(err, &typed) {
t.Fatal(err)
}
actual = "ERROR: " + typed.Detail
}
if strings.TrimSpace(actual) != strings.TrimSpace(expected) {
t.Fatalf("snapshot mismatch\nwant: %s\ngot: %s", expected, actual)
}
if err == nil && format != upstream.FormatPdf {
document, err := upstream.ToDocument(data, &format)
if err != nil {
t.Fatalf("document ABI: %v", err)
}
markdown, err := upstream.ToMarkdownWithAssetLinks(data, &format)
if err != nil {
t.Fatalf("asset renderer: %v", err)
}
combined, combinedMarkdown, err := upstream.ToDocumentWithAssetLinks(data, &format)
if err != nil {
t.Fatalf("combined ABI: %v", err)
}
if !reflect.DeepEqual(combined, document) || combinedMarkdown != markdown {
t.Fatal("single-parse output differs from independent document/Markdown APIs")
}
}
})
}
}
@@ -0,0 +1,85 @@
package anydoc
import (
"errors"
"fmt"
"strings"
"testing"
)
// fakeConvertError stands in for the cgo binding's *ConvertError. The
// production type exposes the same two methods; this fake lets the default
// build classify a resource_limit failure without linking the parser.
type fakeConvertError struct {
kind string
detail string
}
func (e *fakeConvertError) Error() string {
if e.detail == "" {
return "anydoc: " + e.kind
}
return "anydoc: " + e.kind + ": " + e.detail
}
func (e *fakeConvertError) ResourceLimit() bool { return e.kind == "resource_limit" }
func (e *fakeConvertError) LimitDetail() string { return e.detail }
func TestMarkResourceLimitClassifiesPermanentBudgetFailure(t *testing.T) {
const detail = "resource limit exceeded (max_xml_nodes): part exceeds 2000000 xml nodes"
raw := &fakeConvertError{kind: "resource_limit", detail: detail}
// Same wrap the cgo backend applies before the reader names the file.
backendErr := fmt.Errorf("anydoc: markdown conversion failed: %w", raw)
got := markResourceLimit(backendErr)
if !errors.Is(got, ErrResourceLimit) {
t.Fatalf("markResourceLimit() = %v, want errors.Is ErrResourceLimit", got)
}
// The reader keeps the chain with %w, which is what convert inspects.
readerErr := fmt.Errorf("anydoc conversion failed for %q: %w", "xlsx50k.xlsx", got)
if !errors.Is(readerErr, ErrResourceLimit) {
t.Fatalf("reader wrap = %v, want errors.Is ErrResourceLimit", readerErr)
}
message := readerErr.Error()
for _, want := range []string{"too large", "max_xml_nodes", "2000000"} {
if !strings.Contains(message, want) {
t.Errorf("message %q does not mention %q", message, want)
}
}
if strings.Contains(message, "DocReader") {
t.Errorf("message points at DocReader, which did not parse the file: %q", message)
}
if !errors.Is(got, raw) {
t.Fatal("resource-limit wrap dropped the converter error")
}
}
func TestMarkResourceLimitLeavesOtherFailuresRetryable(t *testing.T) {
malformed := &fakeConvertError{kind: "malformed", detail: "not a readable zip archive"}
in := fmt.Errorf("anydoc: markdown conversion failed: %w", malformed)
if got := markResourceLimit(in); got != in || errors.Is(got, ErrResourceLimit) {
t.Fatalf("malformed error = %v, want it unchanged and retryable", got)
}
// The kind has to be typed. A matching sentence from somewhere else is
// not a permanent parser rejection.
untyped := errors.New("anydoc: resource_limit: resource limit exceeded (max_xml_nodes): " +
"part exceeds 2000000 xml nodes")
if got := markResourceLimit(untyped); errors.Is(got, ErrResourceLimit) {
t.Fatalf("untyped error was classified as a resource limit: %v", got)
}
if got := markResourceLimit(nil); got != nil {
t.Fatalf("markResourceLimit(nil) = %v, want nil", got)
}
bare := &fakeConvertError{kind: "resource_limit"}
got := markResourceLimit(bare)
if !errors.Is(got, ErrResourceLimit) {
t.Fatalf("limit without detail = %v, want ErrResourceLimit", got)
}
if !strings.Contains(got.Error(), "too large") {
t.Fatalf("limit without detail = %q, want the permanent-failure reason", got.Error())
}
}
@@ -0,0 +1,94 @@
//go:build anydoc && cgo
package anydoc
import (
"bytes"
"os"
"runtime"
"sort"
"strings"
"sync"
"testing"
"time"
)
// Opt-in sustained mixed-format load through the production WithAssets path.
// Use /usr/bin/time -l (macOS) or -v (Linux) to measure native peak RSS too:
// Go's memory statistics do not include Rust allocations.
func TestConcurrentConversionStress(t *testing.T) {
setting := os.Getenv("ANYDOC_STRESS_DURATION")
if setting == "" {
t.Skip("set ANYDOC_STRESS_DURATION, e.g. 30s")
}
duration, err := time.ParseDuration(setting)
if err != nil || duration <= 0 {
t.Fatalf("invalid stress duration %q", setting)
}
type input struct {
data []byte
opts Options
want *Result
}
inputs := make([]input, 0, len(benchmarkDocuments))
for _, name := range benchmarkDocuments {
format := strings.Split(name, "/")[0]
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
i := input{data: readFixture(t, name), opts: Options{Format: format, WithAssets: true}}
i.want, err = Convert(i.data, i.opts)
if err != nil || i.want.AssetsError != nil {
t.Fatalf("preflight %s: %v", name, err)
}
inputs = append(inputs, i)
}
const workers = 8
samples := make([][]time.Duration, workers)
var wg sync.WaitGroup
start := time.Now()
deadline := start.Add(duration)
for worker := 0; worker < workers; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for n := worker; time.Now().Before(deadline); n++ {
i := inputs[n%len(inputs)]
began := time.Now()
got, err := Convert(i.data, i.opts)
samples[worker] = append(samples[worker], time.Since(began))
if err != nil ||
got.AssetsError != nil ||
got.Markdown != i.want.Markdown ||
len(got.Assets) != len(i.want.Assets) {
t.Errorf("worker %d: inconsistent conversion, err=%v", worker, err)
return
}
for j, asset := range got.Assets {
if !bytes.Equal(asset.Data, i.want.Assets[j].Data) ||
asset.Name != i.want.Assets[j].Name {
t.Errorf("worker %d: inconsistent asset %d", worker, j)
return
}
}
}
}(worker)
}
wg.Wait()
elapsed := time.Since(start)
var latencies []time.Duration
for _, sample := range samples {
latencies = append(latencies, sample...)
}
if len(latencies) == 0 {
t.Fatal("no conversions completed")
}
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
t.Logf("workers=%d conversions=%d elapsed=%s throughput=%.1f docs/s "+
"p50=%s p95=%s p99=%s GoHeapAlloc=%d GoTotalAlloc=%d",
workers, len(latencies), elapsed, float64(len(latencies))/elapsed.Seconds(),
latencies[len(latencies)*50/100], latencies[len(latencies)*95/100], latencies[len(latencies)*99/100],
memory.HeapAlloc, memory.TotalAlloc)
}
@@ -0,0 +1,2 @@
# Preserve PDF byte offsets and fixed-width xref records from upstream fixtures.
*.pdf binary
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Sideguide Technologies Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1 @@
Fixtures from [firecrawl/anydoc v0.2.4](https://github.com/firecrawl/anydoc/tree/42bf1c5ecdde9eb0d96d6bd75a9e6698cf93b14c/tests/fixtures), under the included MIT license. Used for Go ABI regression tests and repeatable conversion benchmarks. Files are copied unchanged.
@@ -0,0 +1,8 @@
Kind,Value,Note
Percent,15.5%,fifteen and a half
Currency,1234.5,dollars
Thousands,9876543,grouped
Date,2026-03-15,ides of March
Duration,26:30:15,over a day
Tiny,0.0000004,four ten-millionths
Boolean,TRUE,yes
1 Kind Value Note
2 Percent 15.5% fifteen and a half
3 Currency 1234.5 dollars
4 Thousands 9876543 grouped
5 Date 2026-03-15 ides of March
6 Duration 26:30:15 over a day
7 Tiny 0.0000004 four ten-millionths
8 Boolean TRUE yes
@@ -0,0 +1,50 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [5 0 R 7 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
4 0 obj
<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>
stream
€
endstream
endobj
5 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 6 0 R >>
endobj
6 0 obj
<< /Length 53 >>
stream
BT /F1 24 Tf 72 700 Td (Text on the first page) Tj ET
endstream
endobj
7 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 8 0 R >>
endobj
8 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
xref
0 9
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000191 00000 n
0000000335 00000 n
0000000487 00000 n
0000000590 00000 n
0000000742 00000 n
trailer
<< /Size 9 /Root 1 0 R >>
startxref
824
%%EOF
@@ -0,0 +1,50 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [5 0 R 7 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
4 0 obj
<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>
stream
€
endstream
endobj
5 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 6 0 R >>
endobj
6 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
7 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> >> /Contents 8 0 R >>
endobj
8 0 obj
<< /Length 32 >>
stream
q 468 0 0 648 72 72 cm /Im1 Do Q
endstream
endobj
xref
0 9
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000191 00000 n
0000000335 00000 n
0000000487 00000 n
0000000569 00000 n
0000000721 00000 n
trailer
<< /Size 9 /Root 1 0 R >>
startxref
803
%%EOF
@@ -0,0 +1,5 @@
{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0 Cambria Math;}}
\pard The roots are {\mmath{\*\moMath{\rtlch\fcs1 \af0 \ltrch\fcs0 \f0\insrsid1 }{\mr\mscr0\msty2 x}{\mr\mscr0\msty2 =}{\mf{\mfPr{\mctrlPr\f0 }}{\mnum{\mr\mscr0\msty2 -b\'b1}{\mrad{\mradPr{\mdegHide on}{\mctrlPr\f0 }}{\mdeg}{\me{\msSup{\me{\mr\mscr0\msty2 b}}{\msup{\mr\mscr0\msty2 2}}}{\mr\mscr0\msty2 -4ac}}}}{\mden{\mr\mscr0\msty2 2a}}}}{\mmathPict{\*\mmathPr}{\pict\pngblip\picw1\pich1 89504e47}}} for any a.\par
\pard {\mmath{\*\moMathPara{\moMathParaPr{\mjc centerGroup}}{\*\moMath{\mnary{\mnaryPr{\mchr \u8721 ?}{\mlimLoc undOvr}{\mctrlPr\f0 }}{\msub{\mr\mscr0\msty2 i=1}}{\msup{\mr\mscr0\msty2 n}}{\me{\msSub{\me{\mr\mscr0\msty2 x}}{\msub{\mr\mscr0\msty2 i}}}}}{\mr\mscr0\msty2 =}{\mfunc{\mfName{\mr\mscr0\msty0 sin}}{\me{\md{\mdPr{\mctrlPr\f0 }}{\me{\mr\mscr0\msty2 \u952 ?}}}}}}{\*\moMath{\mr\mnor where }{\mr\mscr0\msty2 \u8722 ?1<x}}}}\par
\pard A price of $5 or $6 is not math.\par
}
@@ -0,0 +1,177 @@
{\rtf1\ansi\deff3\adeflang1025
{\fonttbl{\f0\froman\fprq2\fcharset0 Times New Roman;}{\f1\froman\fprq2\fcharset2 Symbol;}{\f2\fswiss\fprq2\fcharset0 Arial;}{\f3\froman\fprq2\fcharset0 Liberation Serif{\*\falt Times New Roman};}{\f4\fswiss\fprq2\fcharset0 Liberation Sans{\*\falt Arial};}{\f5\fnil\fprq2\fcharset0 Microsoft YaHei;}{\f6\fnil\fprq2\fcharset0 Arial;}{\f7\fswiss\fprq0\fcharset128 Arial;}}
{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}
{\stylesheet{\s0\snext0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052 Normal;}
{\s1\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl0\outlinelevel0\nowidctlpar\hyphpar0\ltrpar\fs36\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 1;}
{\s2\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 2;}
{\s3\snext25\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl2\outlinelevel2\nowidctlpar\hyphpar0\ltrpar\fs26\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052 heading 3;}
{\*\cs15\snext15\loch\b0 NotBold;}
{\*\cs16\snext16\loch\b Bold;}
{\*\cs17\snext17\loch\i Italic;}
{\*\cs18\snext18\loch\strike Struck;}
{\*\cs19\snext19\loch\cf9\ul\ulc0 Hyperlink;}
{\*\cs20\snext20 Footnote Characters;}
{\*\cs21\snext21\loch\super footnote reference;}
{\*\cs22\snext22 Endnote Characters;}
{\*\cs23\snext23\loch\super endnote reference;}
{\s24\sbasedon0\snext25\rtlch\af6\afs28 \ltrch\hich\af4\loch\sb240\sa120\keepn\f4\fs28\dbch\af5 Heading;}
{\s25\sbasedon0\snext25\loch\sl276\slmult1\sb0\sa140 Body Text;}
{\s26\sbasedon25\snext26\rtlch\af7 \ltrch List;}
{\s27\sbasedon0\snext27\rtlch\af7\afs24\ai \ltrch\loch\sb120\sa120\noline\fs24\i caption;}
{\s28\sbasedon0\snext28\rtlch\af7 \ltrch\loch\noline Index;}
{\s29\snext29\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\b\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052 StrongPara;}
{\s30\sbasedon0\snext30\loch\nowidctlpar\noline Table Contents;}
{\s31\sbasedon0\snext31\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20 footnote text;}
{\s32\sbasedon0\snext32\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20 endnote text;}
{\s33\sbasedon0\snext33 Frame Contents;}
}{\*\listtable{\list\listtemplateid1
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}
{\listlevel\levelnfc255\leveljc0\levelstartat1\levelfollow2{\leveltext \'00;}{\levelnumbers;}\fi0\li0}\listid1}
{\list\listtemplateid2
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'00.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc4\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'01);}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc2\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid2}
{\list\listtemplateid3
{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow2{\leveltext \'01\u8226 ?;}{\levelnumbers;}\f9\fi0\li0}
{\listlevel\levelnfc23\leveljc0\levelstartat1\levelfollow2{\leveltext \'01\u9702 ?;}{\levelnumbers;}\f9\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi-360\li1440}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid3}
{\list\listtemplateid4
{\listlevel\levelnfc1\leveljc0\levelstartat1\levelfollow2{\leveltext \'02\'00.;}{\levelnumbers\'01;}\fi0\li0}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'01.;}{\levelnumbers\'01;}\fi-360\li1080}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'02.;}{\levelnumbers\'01;}\fi-360\li1440}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'03.;}{\levelnumbers\'01;}\fi-360\li1800}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'04.;}{\levelnumbers\'01;}\fi-360\li2160}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'05.;}{\levelnumbers\'01;}\fi-360\li2520}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'06.;}{\levelnumbers\'01;}\fi-360\li2880}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'07.;}{\levelnumbers\'01;}\fi-360\li3240}
{\listlevel\levelnfc0\leveljc0\levelstartat1\levelfollow0{\leveltext \'02\'08.;}{\levelnumbers\'01;}\fi-360\li3600}\listid4}
}{\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}{\listoverride\listid3\listoverridecount0\ls3}{\listoverride\listid4\listoverridecount0\ls4}}{\*\generator LibreOffice/25.2.7.2$Windows_X86_64 LibreOffice_project/5cbfd1ab6520636bb5f7b99185aa69bd7456825d}{\info{\creatim\yr0\mo0\dy0\hr0\min0}{\revtim\yr0\mo0\dy0\hr0\min0}{\printim\yr0\mo0\dy0\hr0\min0}}{\*\userprops}\deftab709\deftab709\deftab709\deftab709\deftab709
\hyphauto1\viewscale100\formshade\nobrkwrptbl\paperh16838\paperw11906\margl1134\margr1134\margt1134\margb1134\sectd\sbknone\sftnnar\saftnnrlc\sectunlocked1\pgwsxn11906\pghsxn16838\marglsxn1134\margrsxn1134\margtsxn1134\margbsxn1134\ftnbj\ftnstart1\ftnrstcont\ftnnar\fet2\aftnrstcont\aftnstart1\aftnnrlc
{\*\ftnsep\chftnsep}\pgndec\pard\plain \s1\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl0\outlinelevel0\nowidctlpar\hyphpar0\ltrpar\fs36\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Fixture Document}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Plain paragraph with }{\loch\cs16\loch\b\loch
bold}{\loch
, }{\loch\cs17\loch\i\loch
italic}{\loch
, and }{\loch\cs18\loch\strike\loch
struck}{\loch
runs.}
\par \pard\plain \s29\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\b\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Style-bold paragraph with a }{\loch\cs15\loch\b0\loch
NotBold-styled span}{\loch
inside.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Lists}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 1.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
First numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 2.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Second numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain a)\tab}\ilvl1\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Alpha sub one}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain b)\tab}\ilvl1\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Alpha sub two}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain i.\tab}\ilvl2\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman sub sub}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 3.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Third numbered}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Interrupting paragraph between lists.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain 4.\tab}\ilvl0\ls2 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Fourth, continuing the count}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain IV.\tab}\ilvl0\ls4 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman starting at four}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain V.\tab}\ilvl0\ls4 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Roman five}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u8226\'95\tab}\ilvl0\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Bullet one}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u8226\'95\tab}\ilvl0\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Bullet two}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \u9702\'3f\tab}\ilvl1\ls3 \fi0\li0\lin0\ql\tx0\fi0\li0\lin0\ltrpar{\loch
Nested bullet}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Table}
\par \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
Wide head}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
End}\cell\row\pard \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\clvmgf\cellx3213\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
Tall}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
B2}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
C2}\cell\row\pard \trowd\trql\ltrrow\trpaddft3\trpaddt0\trpaddfl3\trpaddl0\trpaddfb3\trpaddb0\trpaddfr3\trpaddr0\clvmrg\cellx3213\cellx6425\cellx9638\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar\loch
\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
B3}\cell\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\intbl\ql\ltrpar{\loch
C3}\cell\row\pard \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Notes and special text}
\par \ql\fi-340\li340\lin340\noline\ltrpar\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Music clef \uc0 \u55348\uc1 \u56606\'3f appears before this footnote}{{\super \loch \chftn{\*\footnote \chftn\pard\plain \s31\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20{\loch
\tab Footnote after an astral character.}
}}
}{\loch
reference.}
\par \ql\fi-340\li340\lin340\noline\ltrpar\pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
An endnote follows here}{{\super \loch \chftn{\*\footnote\ftnalt \chftn\pard\plain \s32\rtlch\afs20 \ltrch\loch\fi-340\li340\lin340\noline\fs20{\loch
\tab Endnote body text.}
}}
}{\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Persian with ZWNJ: }{
\u1605\'3f\u1740\'3f\u8204\'3f\u1582\'3f\u1608\'3f\u1575\'3f\u1607\'3f\u1605\'3f}{\loch
. Family emoji: \uc0 \u55357\uc1 \u56424\'3f\u8205\'3f\uc0 \u55357\uc1 \u56425\'3f\u8205\'3f\uc0 \u55357\uc1 \u56423\'3f.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Markdown specials: *stars* _under_ [bracket] `tick` #hash 1. dotted | pipe.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Links and anchors}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
External link to }{{\field{\*\fldinst HYPERLINK "https://example.com/page" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
example}{}}}\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Relative link to }{{\field{\*\fldinst HYPERLINK "file:///anydoc/tests/fixture-src/sibling.odt" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
a sibling file}{}}}\loch
.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
{\*\bkmkstart plainmark}{\*\bkmkend plainmark}This plain paragraph carries a bookmark.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Jump to }{{\field{\*\fldinst HYPERLINK "#plainmark" }{\fldrslt {\loch\loch\cf9\ul\ulc0\loch
the bookmarked paragraph}{}}}\loch
.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Objects}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Inline image: }{\loch
{\pict{\*\picprop{\sp{\sn wzDescription}{\sv tiny red dot}}{\sp{\sn wzName}{\sv }}}\picscalex1700\picscaley1700\piccropl0\piccropr0\piccropt0\piccropb0\picw1\pich1\picwgoal10\pichgoal10\pngblip
89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63fccfc0500f000485018084a98c21000000004945
4e44ae426082}
}{\loch
done.}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Text box: }{
{\shp{\*\shpinst\shpwr2\shpwrk0\shpbypara\shpbyignore\shptop-1362\shpbottom-228\shpbxcolumn\shpbxignore\shpleft0\shpright2835\shpz1{\sp{\sn shapeType}{\sv 202}}{\sp{\sn dxWrapDistLeft}{\sv 72390}}{\sp{\sn dxWrapDistRight}{\sv 72390}}{\sp{\sn dyWrapDistTop}{\sv 72390}}{\sp{\sn dyWrapDistBottom}{\sv 72390}}{\sp{\sn posrelv}{\sv 2}}{\sp{\sn posv}{\sv 1}}{\sp{\sn posrelh}{\sv 2}}{\sp{\sn posh}{\sv 2}}{\sp{\sn dxTextLeft}{\sv 53975}}{\sp{\sn dyTextTop}{\sv 53975}}{\sp{\sn dxTextRight}{\sv 53975}}{\sp{\sn dyTextBottom}{\sv 53975}}{\sp{\sn lineColor}{\sv 0}}{\sp{\sn lineWidth}{\sv 635}}{\shptxt\s33\ql{\loch
Inside the text box.}
\par \pard}}}
}{\loch
after the box.}
\par \pard\plain \s2\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\ilvl1\outlinelevel1\nowidctlpar\hyphpar0\ltrpar\fs30\b\cf0\f3\lang2057\kerning1\dbch\af8\langfe2052{\listtext\pard\plain \tab}\ls1 \fi0\li0\lin0\ql\fi0\li0\lin0\ltrpar{\loch
Quote and code}
\par \pard\plain \s0\rtlch\af6\afs24\alang1081 \ltrch\lang2057\langfe2052\hich\af3\loch\nowidctlpar\hyphpar0\ltrpar\cf0\f3\fs24\lang2057\kerning1\dbch\af8\langfe2052\ql\ltrpar{\loch
Value below one millionth: 0.0000004 should survive.}
\par }
@@ -0,0 +1,225 @@
//go:build anydoc && cgo
package anydoc
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"testing"
upstream "github.com/firecrawl/anydoc/go"
)
func TestConvertEquations(t *testing.T) {
for _, format := range []string{"docx", "pptx", "odt", "epub", "rtf"} {
t.Run(format, func(t *testing.T) {
data := readFixture(t, format+"/handmade-math."+format)
for _, assets := range []bool{false, true} {
result, err := Convert(data, Options{Format: format, WithAssets: assets})
if err != nil {
t.Fatal(err)
}
if result.AssetsError != nil {
t.Fatalf("document ABI failed: %v", result.AssetsError)
}
if !strings.Contains(result.Markdown, `\frac`) ||
!strings.Contains(result.Markdown, "$") {
t.Fatalf("equation lost (assets=%v): %s", assets, result.Markdown)
}
}
})
}
// Check the actual decoded fields, not only the independent Markdown path.
doc, err := upstream.ToDocument(readFixture(t, "docx/handmade-math.docx"), nil)
if err != nil {
t.Fatal(err)
}
var inline, block bool
for _, b := range doc.Blocks {
block = block || b.Kind == "math" && b.Text != nil && strings.Contains(*b.Text, `\sum`)
for _, in := range b.Content {
inline = inline || in.Kind == "math" && in.Text != nil && strings.Contains(*in.Text, `\frac`)
}
}
if !inline || !block {
t.Fatalf("decoded equation nodes missing: inline=%v block=%v", inline, block)
}
}
func TestConvertPDFReportsScannedPages(t *testing.T) {
for _, tc := range []struct{ file, detail string }{
{"handmade-mixed.pdf", "page 2 of 2 needs OCR"},
{"handmade-scanned.pdf", "all 2 pages need OCR"},
} {
t.Run(tc.file, func(t *testing.T) {
result, err := Convert(readFixture(t, "pdf/"+tc.file), Options{Format: "pdf", WithAssets: true})
var typed *upstream.ConvertError
if result != nil ||
!errors.As(err, &typed) ||
typed.Kind != "needs_ocr" ||
!strings.Contains(typed.Detail, tc.detail) {
t.Fatalf("want scanned-page error, got result=%+v err=%v", result, err)
}
if !PDFNeedsOCR(fmt.Errorf("reader: %w", err)) {
t.Fatal("wrapped typed error did not trigger OCR fallback")
}
})
}
if !PDFNeedsOCR(&upstream.ConvertError{Kind: "needs_ocr", Detail: "localized detail"}) {
t.Fatal("OCR detection still depends on English wording")
}
if PDFNeedsOCR(&upstream.ConvertError{Kind: "malformed", Detail: "invalid PDF"}) {
t.Fatal("malformed PDF incorrectly triggers OCR")
}
}
func TestConvertSpreadsheetCheckboxes(t *testing.T) {
// Add VML form controls to an upstream workbook. Both boolean states must
// survive Rust encoding and Go decoding, including subsequent table cells.
data := readFixture(t, "xlsx/sheet.xlsx")
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
var out bytes.Buffer
w := zip.NewWriter(&out)
for _, f := range reader.File {
if f.Name == "xl/worksheets/_rels/sheet1.xml.rels" {
continue
}
if err := w.Copy(f); err != nil {
t.Fatal(err)
}
}
parts := map[string]string{
"xl/worksheets/_rels/sheet1.xml.rels": `<Relationships ` +
`xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><` +
`Relationship Id="checkboxes" ` +
`Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing"` +
` Target="../drawings/checkboxes.vml"/></Relationships>`,
"xl/drawings/checkboxes.vml": `<xml xmlns:v="urn:schemas-microsoft-com:vml" ` +
`xmlns:x="urn:schemas-microsoft-com:office:excel"><v:shape><v:textbox>Approved</v:text` +
`box><x:ClientData ObjectType="Checkbox"><x:Anchor>0,0,0,0,1,0,1,0</x:Anchor><x:Checke` +
`d>1</x:Checked></x:ClientData></v:shape><v:shape><v:textbox>Pending</v:textbox><x:Cli` +
`entData ObjectType="Checkbox"><x:Anchor>1,0,0,0,2,0,1,0</x:Anchor></x:ClientData></v:` +
`shape></xml>`,
}
for name, content := range parts {
part, err := w.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte(content)); err != nil {
t.Fatal(err)
}
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
result, err := Convert(out.Bytes(), Options{Format: "xlsx", WithAssets: true})
if err != nil {
t.Fatal(err)
}
if result.AssetsError != nil ||
!strings.Contains(result.Markdown, "[x] Approved") ||
!strings.Contains(result.Markdown, "[ ] Pending") {
t.Fatalf("checkbox conversion: %+v", result)
}
doc, err := upstream.ToDocument(out.Bytes(), nil)
if err != nil {
t.Fatal(err)
}
states := map[bool]bool{}
for _, block := range doc.Blocks {
if block.Table == nil {
continue
}
for _, row := range block.Table.Grid {
for _, slot := range row {
if slot.Cell == nil {
continue
}
for _, b := range slot.Cell.Blocks {
for _, in := range b.Content {
if in.Kind == "checkbox" && in.Checked != nil {
states[*in.Checked] = true
}
}
}
}
}
}
if !states[false] || !states[true] {
t.Fatalf("decoded checkbox states: %v", states)
}
}
func TestConvertAllBenchmarkFormats(t *testing.T) {
for _, name := range benchmarkDocuments {
t.Run(name, func(t *testing.T) {
format := strings.Split(name, "/")[0]
if format == "xls" || format == "xlsb" {
format = "xlsx"
}
result, err := Convert(readFixture(t, name), Options{Format: format, WithAssets: true})
if err != nil || result.Markdown == "" || result.AssetsError != nil {
t.Fatalf("conversion: result=%+v err=%v", result, err)
}
})
}
}
func TestCombinedConversionPreservesModelAndMarkdown(t *testing.T) {
// Exercise auto-detection as well as all normal formats, without requiring
// an external upstream checkout for this regression in CI.
for _, name := range benchmarkDocuments {
if strings.HasPrefix(name, "pdf/") {
continue
}
t.Run(name, func(t *testing.T) {
data := readFixture(t, name)
var format *upstream.Format
if strings.HasPrefix(name, "csv/") {
f := upstream.FormatCsv
format = &f
}
want, err := upstream.ToDocument(data, format)
if err != nil {
t.Fatal(err)
}
wantMarkdown, err := upstream.ToMarkdownWithAssetLinks(data, format)
if err != nil {
t.Fatal(err)
}
got, markdown, err := upstream.ToDocumentWithAssetLinks(data, format)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, want) || markdown != wantMarkdown {
t.Fatal("single parse changed model or Markdown")
}
})
}
for _, tc := range []struct {
name string
data []byte
format *upstream.Format
kind string
}{
{"empty", nil, nil, "unsupported"},
{"garbage", []byte("garbage"), nil, "unsupported"},
{"pdf", minimalPDF(), nil, "pdf_no_model"},
} {
t.Run(tc.name, func(t *testing.T) {
doc, md, err := upstream.ToDocumentWithAssetLinks(tc.data, tc.format)
var typed *upstream.ConvertError
if doc != nil || md != "" || !errors.As(err, &typed) || typed.Kind != tc.kind {
t.Fatalf("error contract: doc=%+v md=%q err=%v", doc, md, err)
}
})
}
}
@@ -0,0 +1,160 @@
package docparser
import (
"context"
"fmt"
"path/filepath"
"strings"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// AnydocReader converts office documents to markdown in this process, using
// the anydoc converter instead of the Python docreader service.
//
// Embedded images are rendered in place from the document model. PDFs with no
// text layer (scanned exam papers) cannot be converted by anydoc; when a
// fallback reader is configured (typically the builtin docreader) those files
// are handed off so pages can be rasterized for OCR.
type AnydocReader struct {
// extractImages controls whether embedded images are parsed and placed
// in the markdown. Off halves parse time for text-only indexing.
extractImages bool
// fallback is used when a PDF has no extractable text. Nil means the
// conversion error is returned to the caller.
fallback interfaces.DocReader
}
// NewAnydocReader builds a reader. The "anydoc_extract_images" override turns
// off image extraction. fallback may be nil.
func NewAnydocReader(overrides map[string]string, fallback interfaces.DocReader) *AnydocReader {
return &AnydocReader{
extractImages: !isFalsey(overrides["anydoc_extract_images"]),
fallback: fallback,
}
}
// Read converts the document carried by the request.
func (r *AnydocReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if req.URL != "" && len(req.FileContent) == 0 {
return nil, fmt.Errorf("anydoc engine reads uploaded documents, not URLs")
}
format, ok := anydoc.FormatForFile(req.FileType, req.FileName)
if !ok {
return nil, fmt.Errorf("anydoc engine does not support file type %q", fileTypeOf(req))
}
converted, err := anydoc.Convert(req.FileContent, anydoc.Options{
Format: format,
WithAssets: r.extractImages,
})
if format == "pdf" && (anydoc.PDFNeedsOCR(err) || pdfMarkdownIsEmpty(converted, err)) {
return r.readScannedPDF(ctx, req, err)
}
if err != nil {
return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, err)
}
if converted.AssetsError != nil {
logger.Warnf(ctx, "[anydoc] %q parsed as text but its images were dropped: %v",
req.FileName, converted.AssetsError)
}
return &types.ReadResult{
MarkdownContent: converted.Markdown,
ImageRefs: imageRefsFromAssets(converted.Assets),
Metadata: map[string]string{
"parser": AnydocEngineName,
"anydoc_version": anydoc.Version(),
"source_format": format,
},
}, nil
}
func pdfMarkdownIsEmpty(converted *anydoc.Result, err error) bool {
if err != nil || converted == nil {
return false
}
return strings.TrimSpace(converted.Markdown) == ""
}
func (r *AnydocReader) readScannedPDF(ctx context.Context, req *types.ReadRequest, convertErr error) (*types.ReadResult, error) {
if !r.canFallback() {
if convertErr != nil {
return nil, fmt.Errorf("anydoc conversion failed for %q: %w", req.FileName, convertErr)
}
return nil, fmt.Errorf("anydoc conversion failed for %q: PDF has no extractable text; OCR is required", req.FileName)
}
logger.Infof(ctx, "[anydoc] %q contains pages requiring OCR, falling back to builtin for scanned-PDF OCR",
req.FileName)
fallbackReq := *req
fallbackReq.ParserEngine = BuiltinEngineName
result, err := r.fallback.Read(ctx, &fallbackReq)
if err != nil {
return nil, fmt.Errorf("anydoc scanned-PDF fallback failed for %q: %w", req.FileName, err)
}
if result == nil {
return nil, fmt.Errorf("anydoc scanned-PDF fallback returned no result for %q", req.FileName)
}
if result.Metadata == nil {
result.Metadata = map[string]string{}
}
if result.Metadata["parser"] == "" {
result.Metadata["parser"] = BuiltinEngineName
}
result.Metadata["anydoc_fallback"] = "scanned_pdf"
if result.Metadata["image_source_type"] == "" {
result.Metadata["image_source_type"] = "scanned_pdf"
}
return result, nil
}
func (r *AnydocReader) canFallback() bool {
if r.fallback == nil {
return false
}
if connected, ok := r.fallback.(interface{ IsConnected() bool }); ok {
return connected.IsConnected()
}
return true
}
// imageRefsFromAssets turns extracted assets into ImageRefs that match the
// in-place markdown links renderMarkdown wrote.
func imageRefsFromAssets(assets []anydoc.Asset) []types.ImageRef {
if len(assets) == 0 {
return nil
}
refs := make([]types.ImageRef, 0, len(assets))
for _, asset := range assets {
ref := anydoc.ImageDir + asset.Name
refs = append(refs, types.ImageRef{
Filename: asset.Name,
OriginalRef: ref,
MimeType: asset.MediaType,
ImageData: asset.Data,
})
}
return refs
}
// fileTypeOf reports the request's file type, falling back to the file name's
// extension the way every reader in this package does.
func fileTypeOf(req *types.ReadRequest) string {
if ft := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(req.FileType)), "."); ft != "" {
return ft
}
return strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
func isFalsey(value string) bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "false", "0", "no", "off":
return true
}
return false
}
@@ -0,0 +1,35 @@
//go:build anydoc && cgo
package docparser
import (
"bytes"
"context"
"os"
"testing"
"academy/internal/types"
)
func TestAnydocReaderMixedPDFFallsBackThroughRead(t *testing.T) {
data, err := os.ReadFile("anydoc/testdata/upstream/pdf/handmade-mixed.pdf")
if err != nil {
t.Fatal(err)
}
fallback := &stubDocReader{result: &types.ReadResult{MarkdownContent: "Both pages including OCR"}}
req := &types.ReadRequest{FileName: "mixed.pdf", FileType: "pdf", FileContent: data}
result, err := NewAnydocReader(nil, fallback).Read(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if fallback.got == nil ||
!bytes.Equal(fallback.got.FileContent, req.FileContent) ||
fallback.got.ParserEngine != BuiltinEngineName ||
result.MarkdownContent != "Both pages including OCR" ||
result.Metadata["anydoc_fallback"] != "scanned_pdf" {
t.Fatalf("mixed PDF did not reach fallback intact: %+v", result)
}
if result, err := NewAnydocReader(nil, nil).Read(context.Background(), req); err == nil || result != nil {
t.Fatalf("mixed PDF without OCR returned partial success: result=%+v err=%v", result, err)
}
}
@@ -0,0 +1,144 @@
package docparser
import (
"context"
"errors"
"strings"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
)
func TestAnydocReaderRejectsUnsupportedFileType(t *testing.T) {
_, err := NewAnydocReader(nil, nil).Read(context.Background(), &types.ReadRequest{
FileName: "photo.png",
FileType: "png",
FileContent: []byte("not really a png"),
})
if err == nil {
t.Fatal("Read succeeded for an unsupported file type, want an error")
}
if !strings.Contains(err.Error(), "png") {
t.Errorf("error does not name the file type: %v", err)
}
}
func TestAnydocReaderRejectsURLs(t *testing.T) {
_, err := NewAnydocReader(nil, nil).Read(context.Background(), &types.ReadRequest{
URL: "https://example.com/report.docx",
FileType: "docx",
})
if err == nil {
t.Fatal("Read succeeded for a URL request, want an error")
}
}
func TestNewAnydocReaderHonoursImageExtractionOverride(t *testing.T) {
if !NewAnydocReader(nil, nil).extractImages {
t.Error("image extraction is off by default, want on")
}
if NewAnydocReader(map[string]string{"anydoc_extract_images": "false"}, nil).extractImages {
t.Error("image extraction stayed on after the override turned it off")
}
}
func TestImageRefsFromAssetsMatchInPlaceMarkdownPaths(t *testing.T) {
refs := imageRefsFromAssets([]anydoc.Asset{
{Name: "image-1.png", MediaType: "image/png", Data: []byte("first")},
{Name: "image-2.jpg", MediaType: "image/jpeg", Data: []byte("second")},
})
if len(refs) != 2 {
t.Fatalf("got %d image refs, want 2", len(refs))
}
if refs[0].OriginalRef != "images/image-1.png" {
t.Errorf("first OriginalRef = %q, want images/image-1.png", refs[0].OriginalRef)
}
if refs[1].MimeType != "image/jpeg" {
t.Errorf("second mime type = %q, want image/jpeg", refs[1].MimeType)
}
if len(refs[0].ImageData) == 0 {
t.Error("image ref carries no bytes")
}
}
func TestImageRefsFromAssetsEmpty(t *testing.T) {
if refs := imageRefsFromAssets(nil); refs != nil {
t.Errorf("got %d image refs, want none", len(refs))
}
}
func TestAnydocReaderFallsBackForScannedPDF(t *testing.T) {
fallback := &stubDocReader{result: &types.ReadResult{
MarkdownContent: "![page](images/page_1.jpg)",
ImageRefs: []types.ImageRef{{
Filename: "page_1.jpg",
OriginalRef: "images/page_1.jpg",
ImageData: []byte("jpeg"),
}},
Metadata: map[string]string{"image_source_type": "scanned_pdf"},
}}
result, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
FileType: "pdf",
}, errors.New("PDF has no extractable text (Scanned, 5 pages): OCR is required"))
if err != nil {
t.Fatalf("readScannedPDF: %v", err)
}
if !strings.Contains(result.MarkdownContent, "images/page_1.jpg") {
t.Errorf("fallback markdown missing page image:\n%s", result.MarkdownContent)
}
if result.Metadata["anydoc_fallback"] != "scanned_pdf" {
t.Errorf("anydoc_fallback = %q, want scanned_pdf", result.Metadata["anydoc_fallback"])
}
if result.Metadata["image_source_type"] != "scanned_pdf" {
t.Errorf("image_source_type = %q, want scanned_pdf", result.Metadata["image_source_type"])
}
if fallback.got == nil || fallback.got.ParserEngine != BuiltinEngineName {
t.Errorf("fallback request engine = %v, want builtin", fallback.got)
}
}
func TestAnydocReaderScannedPDFWithoutFallbackKeepsError(t *testing.T) {
_, err := NewAnydocReader(nil, nil).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
}, errors.New("PDF has no extractable text: OCR is required"))
if err == nil {
t.Fatal("readScannedPDF succeeded without a fallback, want an error")
}
if !strings.Contains(err.Error(), "OCR is required") {
t.Errorf("error does not mention OCR: %v", err)
}
}
func TestAnydocReaderDisconnectedFallbackKeepsError(t *testing.T) {
fallback := &disconnectedDocReader{}
_, err := NewAnydocReader(nil, fallback).readScannedPDF(context.Background(), &types.ReadRequest{
FileName: "exam.pdf",
}, errors.New("PDF has no extractable text: OCR is required"))
if err == nil {
t.Fatal("readScannedPDF succeeded with a disconnected fallback, want an error")
}
if !strings.Contains(err.Error(), "OCR is required") {
t.Errorf("error does not mention OCR: %v", err)
}
}
type stubDocReader struct {
got *types.ReadRequest
result *types.ReadResult
err error
}
func (s *stubDocReader) Read(_ context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
s.got = req
return s.result, s.err
}
type disconnectedDocReader struct{}
func (disconnectedDocReader) Read(context.Context, *types.ReadRequest) (*types.ReadResult, error) {
return nil, errors.New("should not be called")
}
func (disconnectedDocReader) IsConnected() bool { return false }
@@ -0,0 +1,228 @@
//go:build anydoc && cgo
package docparser
import (
"archive/zip"
"bytes"
"encoding/binary"
"path"
"sort"
"strconv"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
)
// TestEmbeddedVectorImageLinksResolve guards the string contract between
// anydoc's Rust serializer and this package's image resolver.
//
// anydoc renders an embedded image in place as `![alt](images/image-N<ext>)`,
// where `<ext>` comes from `asset_links.rs::extension_for(asset.media_type)`.
// ImageResolver looks that exact string up in a map keyed by
// `anydoc.ImageDir + Asset.Name`, and `Asset.Name` is built from
// `backend_cgo.go::extensionFor(asset.MediaType)`. Nothing normalises the two,
// so any disagreement about the extension makes the lookup miss and the image
// bytes are never stored, silently.
//
// EMF and WMF are what Word, Excel and PowerPoint use for pasted charts,
// equations and Visio drawings. The two sides used to disagree about them: the
// Rust table fell through to ".bin" while the Go side asked the platform MIME
// registry and got ".emf"/".wmf". This test converts a document carrying one of
// each and requires every Markdown image reference to resolve.
func TestEmbeddedVectorImageLinksResolve(t *testing.T) {
result, err := anydoc.Convert(vectorDocx(t), anydoc.Options{Format: "docx", WithAssets: true})
if err != nil {
t.Fatalf("Convert: %v", err)
}
if result.AssetsError != nil {
t.Fatalf("image extraction failed: %v", result.AssetsError)
}
var mediaTypes []string
for _, asset := range result.Assets {
mediaTypes = append(mediaTypes, asset.MediaType)
}
sort.Strings(mediaTypes)
if want := []string{"image/emf", "image/wmf"}; !equalStrings(mediaTypes, want) {
t.Fatalf("extracted media types = %v, want %v", mediaTypes, want)
}
// Exactly what ImageResolver.ResolveAndStore builds before looking up the
// Markdown reference.
refMap := map[string]types.ImageRef{}
for _, ref := range imageRefsFromAssets(result.Assets) {
refMap[ref.OriginalRef] = ref
}
references := scanMarkdownImageTargets(result.Markdown)
if len(references) != len(result.Assets) {
t.Fatalf("markdown carries %d image references, want %d:\n%s",
len(references), len(result.Assets), result.Markdown)
}
for _, reference := range references {
raw := result.Markdown[reference.TargetStart:reference.TargetEnd]
if _, _, _, ok := splitMarkdownImageTarget(raw, refMap); !ok {
t.Errorf("markdown reference %q matches no ImageRef, so the image would never be stored (lookup keys: %v)",
raw, sortedRefKeys(refMap))
}
}
// Agreeing on ".bin" for everything would satisfy the loop above while
// still discarding the format, so pin the extensions too. Asset order
// follows the archive rather than the document, so compare the set.
var extensions []string
for key := range refMap {
extensions = append(extensions, path.Ext(key))
}
sort.Strings(extensions)
if want := []string{".emf", ".wmf"}; !equalStrings(extensions, want) {
t.Errorf("image reference extensions = %v, want %v (lookup keys: %v)",
extensions, want, sortedRefKeys(refMap))
}
}
func equalStrings(got, want []string) bool {
if len(got) != len(want) {
return false
}
for i := range got {
if got[i] != want[i] {
return false
}
}
return true
}
func sortedRefKeys(refMap map[string]types.ImageRef) []string {
keys := make([]string, 0, len(refMap))
for key := range refMap {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
// vectorDocx builds a minimal .docx holding one EMF and one WMF drawing. The
// payloads only need a recognisable header: anydoc addresses an embedded part
// through its relationship target and extension, not by decoding the image.
func vectorDocx(t *testing.T) []byte {
t.Helper()
const (
relsNS = "http://schemas.openxmlformats.org/package/2006/relationships"
wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
rNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
aNS = "http://schemas.openxmlformats.org/drawingml/2006/main"
wpNS = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
picNS = "http://schemas.openxmlformats.org/drawingml/2006/picture"
)
files := []struct {
name string
body string
}{
{"[Content_Types].xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="emf" ContentType="image/x-emf"/>
<Default Extension="wmf" ContentType="image/x-wmf"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>`},
{"_rels/.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + rNS + `/officeDocument" Target="word/document.xml"/></Relationships>`},
{"word/_rels/document.xml.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="` + relsNS + `">
<Relationship Id="rId1" Type="` + rNS + `/image" Target="media/image1.emf"/>
<Relationship Id="rId2" Type="` + rNS + `/image" Target="media/image2.wmf"/>
</Relationships>`},
{"word/document.xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="` + wNS + `" xmlns:r="` + rNS + `" xmlns:a="` + aNS + `" xmlns:wp="` + wpNS + `">
<w:body><w:p><w:r><w:t>vector images</w:t></w:r></w:p>` +
drawingParagraph(picNS, aNS, wpNS, rNS, "rId1", "chart.emf", 1) +
drawingParagraph(picNS, aNS, wpNS, rNS, "rId2", "equation.wmf", 2) +
`</w:body></w:document>`},
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, file := range files {
writer, err := zw.Create(file.name)
if err != nil {
t.Fatalf("zip create %s: %v", file.name, err)
}
if _, err := writer.Write([]byte(file.body)); err != nil {
t.Fatalf("zip write %s: %v", file.name, err)
}
}
for name, body := range map[string][]byte{
"word/media/image1.emf": emfHeader(),
"word/media/image2.wmf": wmfPlaceableHeader(),
} {
writer, err := zw.Create(name)
if err != nil {
t.Fatalf("zip create %s: %v", name, err)
}
if _, err := writer.Write(body); err != nil {
t.Fatalf("zip write %s: %v", name, err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("zip close: %v", err)
}
return buf.Bytes()
}
func drawingParagraph(picNS, aNS, wpNS, rNS, relID, name string, id int) string {
number := strconv.Itoa(id)
return `<w:p><w:r><w:drawing><wp:inline>
<wp:extent cx="914400" cy="914400"/>
<wp:docPr id="` + number + `" name="` + name + `" descr="` + name + `"/>
<a:graphic><a:graphicData uri="` + picNS + `">
<pic:pic xmlns:pic="` + picNS + `">
<pic:nvPicPr><pic:cNvPr id="` + number + `" name="` + name + `"/><pic:cNvPicPr/></pic:nvPicPr>
<pic:blipFill><a:blip r:embed="` + relID + `"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>
<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>
<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>
</pic:pic></a:graphicData></a:graphic>
</wp:inline></w:drawing></w:r></w:p>`
}
// emfHeader is a structurally valid EMR_HEADER record (MS-EMF 2.3.4.2).
func emfHeader() []byte {
buf := make([]byte, 0, 88)
buf = binary.LittleEndian.AppendUint32(buf, 1) // iType = EMR_HEADER
buf = binary.LittleEndian.AppendUint32(buf, 88)
for i := 0; i < 8; i++ { // rclBounds, rclFrame
buf = binary.LittleEndian.AppendUint32(buf, 914400)
}
buf = binary.LittleEndian.AppendUint32(buf, 0x464D4520) // dSignature = ' EMF'
buf = binary.LittleEndian.AppendUint32(buf, 0x00010000) // nVersion
buf = binary.LittleEndian.AppendUint32(buf, 88) // nBytes
buf = binary.LittleEndian.AppendUint32(buf, 16) // nRecords
buf = binary.LittleEndian.AppendUint16(buf, 0) // nHandles
buf = binary.LittleEndian.AppendUint16(buf, 0) // sReserved
for i := 0; i < 3; i++ { // nDescription, offDescription, nPalEntries
buf = binary.LittleEndian.AppendUint32(buf, 0)
}
for i := 0; i < 4; i++ { // szlDevice, szlMillimeters
buf = binary.LittleEndian.AppendUint32(buf, 0)
}
return append(buf, []byte("EMF-PAYLOAD")...)
}
// wmfPlaceableHeader is a placeable WMF header (MS-WMF 2.3.2.1).
func wmfPlaceableHeader() []byte {
buf := make([]byte, 0, 22)
buf = binary.LittleEndian.AppendUint32(buf, 0x9AC6CDD7) // key
buf = binary.LittleEndian.AppendUint16(buf, 0) // hmf
for i := 0; i < 4; i++ { // bbox
buf = binary.LittleEndian.AppendUint16(buf, 100)
}
buf = binary.LittleEndian.AppendUint16(buf, 96) // inch
buf = binary.LittleEndian.AppendUint32(buf, 0) // reserved
buf = binary.LittleEndian.AppendUint16(buf, 96) // checksum
return append(buf, []byte("WMF-PAYLOAD")...)
}
@@ -0,0 +1,240 @@
package docparser
import (
"bytes"
"context"
"encoding/csv"
"fmt"
"net/http"
"path/filepath"
"strings"
"academy/internal/types"
)
// simpleFormats lists file extensions that Go can handle without the Python service.
var simpleFormats = map[string]bool{
"md": true, "markdown": true,
"txt": true, "text": true,
"csv": true,
"json": true,
}
var imageFormats = map[string]bool{
"jpg": true, "jpeg": true, "png": true, "gif": true,
"bmp": true, "tiff": true, "webp": true,
}
var audioFormats = map[string]bool{
"mp3": true, "wav": true, "m4a": true, "flac": true, "ogg": true,
}
func init() {
for k := range imageFormats {
simpleFormats[k] = true
}
for k := range audioFormats {
simpleFormats[k] = true
}
}
// IsSimpleFormat returns true if the file type can be handled by the Go SimpleFormatReader.
func IsSimpleFormat(fileType string) bool {
return simpleFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// SimpleFormatReader handles simple file formats and images directly in Go,
// bypassing the Python docreader service.
type SimpleFormatReader struct{}
// Read reads simple format files and returns markdown.
func (b *SimpleFormatReader) Read(_ context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
switch {
case ft == "md" || ft == "markdown":
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
case ft == "txt" || ft == "text":
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
case ft == "csv":
md, err := csvToMarkdown(req.FileContent)
if err != nil {
return nil, fmt.Errorf("csv conversion failed: %w", err)
}
return &types.ReadResult{MarkdownContent: md}, nil
case ft == "json":
md, err := jsonToMarkdown(req.FileContent)
if err != nil {
return nil, fmt.Errorf("json conversion failed: %w", err)
}
return &types.ReadResult{MarkdownContent: md}, nil
case imageFormats[ft]:
return imageToResult(req.FileName, req.FileContent), nil
case audioFormats[ft]:
return audioToResult(req.FileName, req.FileContent), nil
default:
return nil, fmt.Errorf("unsupported simple format: %s", ft)
}
}
// imageToResult wraps a standalone image as a markdown image reference with
// the raw bytes in ImageRefs, matching Python ImageParser behaviour.
func imageToResult(fileName string, data []byte) *types.ReadResult {
if fileName == "" {
fileName = "image.png"
}
refPath := "images/" + fileName
// Encode spaces so the markdown URL is valid and matches the regex in ResolveAndStore.
safeRef := strings.ReplaceAll(refPath, " ", "%20")
mime := http.DetectContentType(data)
return &types.ReadResult{
MarkdownContent: fmt.Sprintf("![%s](%s)", fileName, safeRef),
ImageRefs: []types.ImageRef{
{
Filename: fileName,
OriginalRef: safeRef,
MimeType: mime,
ImageData: data,
IsOriginal: true,
},
},
}
}
// IsImageFormat returns true if the file type is a recognized image format.
func IsImageFormat(fileType string) bool {
return imageFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// IsAudioFormat returns true if the file type is a recognized audio format.
func IsAudioFormat(fileType string) bool {
return audioFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
}
// audioToResult wraps a standalone audio file. The actual transcription is
// handled by the ASR model in the knowledge service pipeline. Here we just
// return a placeholder markdown with the raw bytes preserved for upstream
// processing.
func audioToResult(fileName string, data []byte) *types.ReadResult {
if fileName == "" {
fileName = "audio.mp3"
}
// Return a placeholder; the knowledge service will replace this with
// the ASR transcription result.
return &types.ReadResult{
MarkdownContent: fmt.Sprintf("[Audio file: %s]", fileName),
IsAudio: true,
AudioData: data,
}
}
// ensureOriginalImageRef checks whether the input file is an image and, if the
// returned markdown does not already contain a markdown image reference for it,
// prepends one and appends the raw bytes to imageRefs. This guarantees that
// when MinerU OCRs a standalone image, the downstream chunks still carry the
// original image link for retrieval display.
func ensureOriginalImageRef(req *types.ReadRequest, mdContent string, imageRefs []types.ImageRef) (string, []types.ImageRef) {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
if !imageFormats[ft] {
return mdContent, imageRefs
}
if len(req.FileContent) == 0 {
return mdContent, imageRefs
}
fileName := req.FileName
if fileName == "" {
fileName = "image." + ft
}
refPath := "images/" + fileName
if strings.Contains(mdContent, refPath) {
return mdContent, imageRefs
}
imgLine := fmt.Sprintf("![%s](%s)", fileName, refPath)
if strings.TrimSpace(mdContent) == "" {
mdContent = imgLine
} else {
mdContent = imgLine + "\n\n" + mdContent
}
mime := http.DetectContentType(req.FileContent)
imageRefs = append(imageRefs, types.ImageRef{
Filename: fileName,
OriginalRef: refPath,
MimeType: mime,
ImageData: req.FileContent,
IsOriginal: true,
})
return mdContent, imageRefs
}
func csvToMarkdown(data []byte) (string, error) {
// Excel's "CSV UTF-8" export starts the file with a byte order mark.
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
reader := csv.NewReader(bytes.NewReader(data))
reader.LazyQuotes = true
reader.TrimLeadingSpace = true
// Rows may differ in length. The default, the first row's length, made
// one short or long row fail the whole file.
reader.FieldsPerRecord = -1
records, err := reader.ReadAll()
if err != nil {
return "", err
}
if len(records) == 0 {
return "", nil
}
// The table is as wide as the widest row, so no field is dropped, and
// shorter rows are padded with empty cells.
width := 0
for _, record := range records {
width = max(width, len(record))
}
var sb strings.Builder
writeRow := func(record []string) {
cells := make([]string, width)
for i, cell := range record {
cells[i] = csvCellReplacer.Replace(cell)
}
sb.WriteString("| ")
sb.WriteString(strings.Join(cells, " | "))
sb.WriteString(" |\n")
}
// Header row
writeRow(records[0])
// Separator
sb.WriteString("|")
for range width {
sb.WriteString(" --- |")
}
sb.WriteString("\n")
// Data rows
for _, row := range records[1:] {
writeRow(row)
}
return sb.String(), nil
}
// 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.
// Escape existing backslashes too, so a literal backslash before a pipe does
// not consume the pipe's escape and turn it back into a column separator.
var csvCellReplacer = strings.NewReplacer(`\`, `\\`, "|", `\|`, "\r\n", "<br />", "\n", "<br />", "\r", "<br />")
@@ -0,0 +1,162 @@
package docparser
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPaddleOCRVLCloudTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", paddleOCRVLCloudTimeout},
{"whitespace", " ", paddleOCRVLCloudTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 5400s ", 90 * time.Minute},
{"invalid", "invalid", paddleOCRVLCloudTimeout},
{"unitless", "5400", paddleOCRVLCloudTimeout},
{"zero", "0s", paddleOCRVLCloudTimeout},
{"negative", "-1s", paddleOCRVLCloudTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", tt.value)
assert.Equal(t, tt.want, NewPaddleOCRVLCloudReader(nil).timeout)
})
}
}
// The configured timeout, not the old hardcoded 600s, must end a job that the
// cloud keeps reporting as running.
func TestPaddleOCRVLCloudPollStopsAtConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
t.Setenv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", "200ms")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"code":0,"data":{"state":"running"}}`)
}))
defer server.Close()
reader := NewPaddleOCRVLCloudReader(nil)
reader.baseURL = server.URL
reader.pollInterval = 10 * time.Millisecond
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Watchdog: without the configured budget this loop keeps polling for the
// old hardcoded 600s, which must fail the test instead of hanging it.
done := make(chan error, 1)
start := time.Now()
go func() {
_, pollErr := reader.pollJob(ctx, "job-1")
done <- pollErr
}()
select {
case err := <-done:
require.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("timed out after %s", 200*time.Millisecond))
assert.Less(t, time.Since(start), 5*time.Second)
case <-time.After(5 * time.Second):
t.Fatalf("poll loop ignored ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT")
}
}
func TestAcademyCloudPollTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", defaultAcademyCloudPollTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 3600s ", time.Hour},
{"invalid", "invalid", defaultAcademyCloudPollTimeout},
{"zero", "0s", defaultAcademyCloudPollTimeout},
{"negative", "-1s", defaultAcademyCloudPollTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_ACADEMYCLOUD_TIMEOUT", tt.value)
reader, err := NewAcademyCloudSignedDocumentReader("app-id", "api-key")
require.NoError(t, err)
assert.Equal(t, tt.want, reader.pollTimeout)
})
}
}
// academyCloudPollTransport answers every poll with "still running" so the
// configured poll budget is the only thing that can end the loop.
type academyCloudPollTransport struct {
polls atomic.Int64
}
func (t *academyCloudPollTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.polls.Add(1)
body := `{"task_id":"task-1","status":"processing","progress":0.1}`
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
}
// The configured budget, not the old hardcoded 20m, must end the poll loop
// whether or not the caller has a deadline of its own. Ingestion always calls
// with a (much longer) DocReader deadline, so that case must not bypass it.
func TestAcademyCloudPollStopsAtConfiguredTimeout(t *testing.T) {
for _, tt := range []struct {
name string
parentCtx func() (context.Context, context.CancelFunc)
}{
{"no parent deadline", func() (context.Context, context.CancelFunc) {
return context.WithCancel(context.Background())
}},
{"longer parent deadline", func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Minute)
}},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_ACADEMYCLOUD_TIMEOUT", "300ms")
reader, err := NewAcademyCloudSignedDocumentReader("app-id", "api-key")
require.NoError(t, err)
transport := &academyCloudPollTransport{}
reader.client = &http.Client{Transport: transport}
reader.initialPollInterval = 5 * time.Millisecond
reader.maxPollInterval = 10 * time.Millisecond
ctx, cancel := tt.parentCtx()
defer cancel()
done := make(chan error, 1)
start := time.Now()
go func() {
_, pollErr := reader.pollTaskResult(ctx, "task-1")
done <- pollErr
}()
select {
case pollErr := <-done:
require.Error(t, pollErr)
assert.True(t, errors.Is(pollErr, context.DeadlineExceeded), "err = %v", pollErr)
assert.Less(t, time.Since(start), 5*time.Second)
assert.Greater(t, transport.polls.Load(), int64(1),
"the job must actually be polled before the budget ends it")
case <-time.After(5 * time.Second):
t.Fatalf("poll loop ignored ACADEMY_ACADEMYCLOUD_TIMEOUT after %d polls", transport.polls.Load())
}
})
}
}
@@ -0,0 +1,69 @@
package docparser
import "testing"
func TestCSVToMarkdown(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{
name: "rectangular",
in: "name,qty\npen,2\n",
want: "| name | qty |\n| --- | --- |\n| pen | 2 |\n",
},
{
// A short row failed the whole file with "wrong number of fields".
name: "short row is padded",
in: "name,qty,note\npen,2\nink,1,blue\n",
want: "| name | qty | note |\n| --- | --- | --- |\n| pen | 2 | |\n| ink | 1 | blue |\n",
},
{
name: "long row widens the table",
in: "name,qty\npen,2,spare\n",
want: "| name | qty | |\n| --- | --- | --- |\n| pen | 2 | spare |\n",
},
{
name: "pipe in a cell is escaped",
in: "expr,means\n\"a|b\",a or b\n",
want: "| expr | means |\n| --- | --- |\n| a\\|b | a or b |\n",
},
{
name: "backslash before pipe preserves both literal characters",
in: "expr,note\na\\|b,literal\n",
want: "| expr | note |\n| --- | --- |\n| " + `a\\\|b` + " | literal |\n",
},
{
name: "multiple and trailing backslashes stay inside the cell",
in: "expr,note\na\\\\|b\\,literal\n",
want: "| expr | note |\n| --- | --- |\n| " + `a\\\\\|b\\` + " | literal |\n",
},
{
name: "multi-line field stays in its row",
in: "name,address\nAnn,\"1 Main St\r\nSpringfield\"\n",
want: "| name | address |\n| --- | --- |\n| Ann | 1 Main St<br />Springfield |\n",
},
{
name: "byte order mark is not part of the first header",
in: "\xef\xbb\xbfname,qty\npen,2\n",
want: "| name | qty |\n| --- | --- |\n| pen | 2 |\n",
},
{
name: "empty file",
in: "",
want: "",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := csvToMarkdown([]byte(tc.in))
if err != nil {
t.Fatalf("csvToMarkdown(%q) error: %v", tc.in, err)
}
if got != tc.want {
t.Errorf("csvToMarkdown(%q)\n got: %q\nwant: %q", tc.in, got, tc.want)
}
})
}
}
+21
View File
@@ -0,0 +1,21 @@
// Package docparser turns uploaded files and URLs into Markdown plus the
// images they contain, which is the input the chunking and multimodal stages
// downstream expect.
//
// A parse request names a parser engine, and every engine is one entry in the
// registry:
//
// - engines.go declares the catalog — each engine's name, description,
// supported file types, availability probe, and the reader that does the
// work.
// - engine_registry.go turns an engine name into a reader (NewReader) and
// merges the local catalog with the engines the Python docreader reports
// over its ListEngines RPC (ListAllEngines).
//
// Readers differ in where the parsing happens: in this process
// (SimpleFormatReader, AnydocReader), in the docreader service over gRPC or
// HTTP (GRPCDocumentReader, HTTPDocumentReader), or in a remote API (MinerU,
// PaddleOCR-VL, Academy Cloud). They all return types.ReadResult, so the rest
// of the package — image resolution and storage, table normalization — is
// shared regardless of which engine ran.
package docparser
@@ -0,0 +1,151 @@
package docparser
import (
"context"
"fmt"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// EngineRegistration is what every locally registered parser engine provides:
// the metadata the engine list shows, and the reader that does the parsing.
// Remote-only engines (e.g. markitdown) live in the Python docreader, are
// discovered through its ListEngines RPC, and never register here — the
// registry routes them to the docreader client by default.
type EngineRegistration interface {
Name() string
Description() string
FileTypes(docreaderConnected bool) []string
CheckAvailable(docreaderConnected bool, overrides map[string]string) (available bool, reason string)
// NewReader builds the reader for one parse request. Returning an error
// means this engine cannot serve the request (missing credentials,
// unreachable service); the caller reports it rather than silently
// parsing with something else.
NewReader(ctx context.Context, deps ReaderDeps) (interfaces.DocReader, error)
}
// ReaderDeps carries everything an engine may need to build its reader but
// cannot construct itself: tenant configuration, tenant credentials, and the
// shared docreader connection.
type ReaderDeps struct {
// Overrides holds tenant-level engine configuration (service endpoints,
// API keys), as produced by ParserEngineConfig.ToOverridesMap.
Overrides map[string]string
// Remote is the docreader client. Nil when the service is not connected.
Remote interfaces.DocReader
// AcademyCloudCredentials resolves the tenant's Academy Cloud
// credentials. It is a function rather than a value because resolving
// them can hit the database, which most engines never need. Nil, or a
// nil return, means the tenant has not configured them.
AcademyCloudCredentials func(ctx context.Context) *types.AcademyCloudCredentials
}
// localEngines holds all locally registered parser engines, in registration
// order — which is also the order the engine list is shown in.
var localEngines []EngineRegistration
// RegisterEngine adds an engine to the local registry. Called from init().
func RegisterEngine(e EngineRegistration) {
localEngines = append(localEngines, e)
}
// lookupEngine returns the locally registered engine with this name.
func lookupEngine(name string) (EngineRegistration, bool) {
for _, engine := range localEngines {
if engine.Name() == name {
return engine, true
}
}
return nil, false
}
// NewReader builds the reader for an engine.
//
// An empty engine name means "no explicit choice": simple formats are handled
// in Go and everything else goes to the docreader service. An unknown name is
// routed to the docreader too, so engines that only exist in the Python
// service keep working without a Go-side registration.
func NewReader(
ctx context.Context, engine, fileType string, isURL bool, deps ReaderDeps,
) (interfaces.DocReader, error) {
if registration, ok := lookupEngine(engine); ok {
return registration.NewReader(ctx, deps)
}
if engine == "" && !isURL && IsSimpleFormat(fileType) {
return &SimpleFormatReader{}, nil
}
return remoteReader(deps)
}
// remoteReader returns the docreader client, or an error when the service is
// not connected — a nil interface value here would panic at the call site.
func remoteReader(deps ReaderDeps) (interfaces.DocReader, error) {
if deps.Remote == nil {
return nil, errNotConnected
}
return deps.Remote, nil
}
// ListAllEngines returns the merged engine list: locally registered engines
// plus engines discovered from the remote docreader via ListEngines RPC.
//
// Merge rules:
// - Local engines are always included, with Go-side availability checks.
// - For a remote engine whose name matches a local one, the remote's
// file_types and description take precedence (the remote service is
// authoritative for its own capabilities).
// - Remote engines not present locally are appended as-is, enabling
// auto-discovery of newly added docreader engines without Go changes.
func ListAllEngines(
docreaderConnected bool, overrides map[string]string, remoteEngines []types.ParserEngineInfo,
) []types.ParserEngineInfo {
remoteMap := make(map[string]types.ParserEngineInfo, len(remoteEngines))
for _, re := range remoteEngines {
remoteMap[re.Name] = re
}
seen := make(map[string]bool, len(localEngines))
result := make([]types.ParserEngineInfo, 0, len(localEngines)+len(remoteEngines))
for _, e := range localEngines {
name := e.Name()
seen[name] = true
fileTypes := e.FileTypes(docreaderConnected)
description := e.Description()
if re, ok := remoteMap[name]; ok {
if len(re.FileTypes) > 0 {
fileTypes = re.FileTypes
}
if re.Description != "" {
description = re.Description
}
}
available, reason := e.CheckAvailable(docreaderConnected, overrides)
result = append(result, types.ParserEngineInfo{
Name: name,
Description: description,
FileTypes: fileTypes,
Available: available,
UnavailableReason: reason,
})
}
for _, re := range remoteEngines {
if seen[re.Name] {
continue
}
result = append(result, re)
}
return result
}
// errEngineUnavailable reports an engine that is registered but cannot run for
// this tenant or this build.
func errEngineUnavailable(engine, reason string) error {
return fmt.Errorf("parser engine %q is unavailable: %s", engine, reason)
}
@@ -0,0 +1,112 @@
package docparser
import (
"context"
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubRemote stands in for the docreader client. NewReader only ever hands it
// back, so the embedded interface is never called — and would panic if routing
// ever sent a parse here by mistake.
type stubRemote struct{ interfaces.DocReader }
func TestNewReaderRoutesByEngine(t *testing.T) {
ctx := context.Background()
remote := &stubRemote{}
deps := ReaderDeps{Remote: remote}
cases := []struct {
name string
engine string
fileType string
isURL bool
want any
}{
{name: "simple engine", engine: SimpleEngineName, fileType: "md", want: &SimpleFormatReader{}},
{name: "builtin engine goes remote", engine: BuiltinEngineName, fileType: "md", want: remote},
{name: "unset engine handles simple formats in Go", fileType: "csv", want: &SimpleFormatReader{}},
{name: "unset engine sends complex formats to docreader", fileType: "docx", want: remote},
{name: "default pptx engine is remote markitdown", engine: "markitdown", fileType: "pptx", want: remote},
{name: "URLs always go to docreader", fileType: "md", isURL: true, want: remote},
{name: "docreader-only engines fall through", engine: "markitdown", fileType: "docx", want: remote},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
reader, err := NewReader(ctx, tc.engine, tc.fileType, tc.isURL, deps)
if err != nil {
t.Fatalf("NewReader: %v", err)
}
if _, isSimple := tc.want.(*SimpleFormatReader); isSimple {
if _, ok := reader.(*SimpleFormatReader); !ok {
t.Fatalf("reader = %T, want *SimpleFormatReader", reader)
}
return
}
if reader != tc.want {
t.Fatalf("reader = %T, want the docreader client", reader)
}
})
}
}
// A disconnected docreader has to surface as an error, not as a nil reader the
// caller would dereference.
func TestNewReaderReportsDisconnectedDocReader(t *testing.T) {
if _, err := NewReader(context.Background(), BuiltinEngineName, "docx", false, ReaderDeps{}); err == nil {
t.Fatal("NewReader succeeded without a docreader connection, want an error")
}
}
func TestNewReaderRequiresAcademyCloudCredentials(t *testing.T) {
_, err := NewReader(context.Background(), AcademyCloudEngineName, "docx", false, ReaderDeps{
AcademyCloudCredentials: func(context.Context) *types.AcademyCloudCredentials { return nil },
})
if err == nil {
t.Fatal("NewReader succeeded without credentials, want an error")
}
}
// The anydoc engine is only linked into builds tagged `anydoc`; everywhere
// else it must be listed as unavailable and refuse to build a reader, so a
// knowledge base configured for it fails loudly instead of parsing with
// something else.
func TestAnydocEngineFollowsBuildAvailability(t *testing.T) {
reader, err := NewReader(context.Background(), AnydocEngineName, "docx", false, ReaderDeps{})
if anydoc.Available() {
if err != nil {
t.Fatalf("NewReader: %v", err)
}
if _, ok := reader.(*AnydocReader); !ok {
t.Fatalf("reader = %T, want *AnydocReader", reader)
}
return
}
if err == nil {
t.Fatal("NewReader succeeded without the converter linked in, want an error")
}
}
func TestListAllEnginesIncludesAnydoc(t *testing.T) {
for _, engine := range ListAllEngines(true, nil, nil) {
if engine.Name != AnydocEngineName {
continue
}
if engine.Available != anydoc.Available() {
t.Errorf("anydoc availability = %v, want %v", engine.Available, anydoc.Available())
}
if !engine.Available && engine.UnavailableReason == "" {
t.Error("anydoc is unavailable without a reason to show")
}
if len(engine.FileTypes) == 0 {
t.Error("anydoc lists no file types")
}
return
}
t.Fatal("anydoc engine not found in the engine list")
}
@@ -0,0 +1,91 @@
package docparser
import (
"testing"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/utils"
)
// Locally advertised parser formats must pass the shared import gate used by
// direct uploads, URL imports, workers and datasource connectors (#4598).
// Check metadata even when a converter is not linked into this test build.
func TestLocalParserFormatsPassImportValidation(t *testing.T) {
for _, engine := range ListAllEngines(true, nil, nil) {
t.Run(engine.Name, func(t *testing.T) {
for _, ext := range engine.FileTypes {
if !utils.IsSupportedImportExtension(ext) {
t.Errorf("engine advertises %q but the shared import gate rejects it", ext)
}
}
})
}
}
func TestListAllEnginesBuiltinIncludesDocumentFormats(t *testing.T) {
engines := ListAllEngines(true, nil, nil)
for _, engine := range engines {
if engine.Name != "builtin" {
continue
}
if !engine.Available {
t.Fatalf("builtin engine is unavailable: %s", engine.UnavailableReason)
}
fileTypes := make(map[string]bool, len(engine.FileTypes))
for _, fileType := range engine.FileTypes {
fileTypes[fileType] = true
}
for _, want := range []string{"html", "htm", "xmind", "ppt", "pptx"} {
if !fileTypes[want] {
t.Errorf("builtin engine file types do not include %q: %v", want, engine.FileTypes)
}
}
return
}
t.Fatal("builtin engine not found")
}
func TestDefaultParserEnginePrefersAnydocWhenLinked(t *testing.T) {
cases := []string{"pptx", "ppt", "docx"}
if anydoc.Available() {
for _, ft := range cases {
if got := types.DefaultParserEngine(ft); got != AnydocEngineName {
t.Errorf("DefaultParserEngine(%s) = %q, want anydoc when the binding is linked", ft, got)
}
}
if got := types.DefaultParserEngine("csv"); got != "" {
t.Errorf("DefaultParserEngine(csv) = %q, want empty so the Go simple reader stays default", got)
}
// anydoc claims pdf but cannot model one, so linking the binding must
// not move PDFs off builtin. This branch is where that is observable.
for _, ft := range []string{"pdf", ".PDF"} {
if got := types.DefaultParserEngine(ft); got != "" {
t.Errorf("DefaultParserEngine(%q) = %q, want empty so PDFs stay on builtin", ft, got)
}
}
return
}
if got := types.DefaultParserEngine("pptx"); got != "markitdown" {
t.Fatalf("DefaultParserEngine(pptx) = %q, want markitdown when anydoc is unavailable", got)
}
if got := types.DefaultParserEngine("docx"); got != "" {
t.Fatalf("DefaultParserEngine(docx) = %q, want empty when anydoc is unavailable", got)
}
}
// The PDF exclusion only matters because anydoc still claims the type. If a
// future anydoc drops pdf, the exclusion becomes dead code and should go with
// it — this guard runs in every build, tagged or not.
func TestPreferAnydocSkipsPDF(t *testing.T) {
if !anydoc.Supports("pdf", "") {
t.Fatal("anydoc no longer claims pdf; drop the explicit exclusion in preferAnydocWhenAvailable")
}
for _, ft := range []string{"pdf", ".PDF", " Pdf "} {
if got := preferAnydocWhenAvailable(ft); got != "" {
t.Errorf("preferAnydocWhenAvailable(%q) = %q, want empty so PDFs stay on builtin", ft, got)
}
}
}
@@ -0,0 +1,296 @@
package docparser
import (
"context"
"strings"
"academy/internal/infrastructure/docparser/anydoc"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// Engine names, as stored in knowledge base parser rules and shown in the UI.
const (
// BuiltinEngineName is the DocReader (Python) parser suite.
BuiltinEngineName = "builtin"
// SimpleEngineName is Go-native handling of text formats and images.
SimpleEngineName = "simple"
// AnydocEngineName is the in-process anydoc office-document converter.
AnydocEngineName = "anydoc"
// AcademyCloudEngineName is the hosted Academy Cloud document reader.
AcademyCloudEngineName = "academycloud"
// MinerUEngineName is a self-hosted MinerU service.
MinerUEngineName = "mineru"
// MinerUCloudEngineName is the MinerU Cloud API.
MinerUCloudEngineName = "mineru_cloud"
// PaddleOCRVLEngineName is a self-hosted PaddleOCR-VL pipeline.
PaddleOCRVLEngineName = "paddleocr_vl"
// PaddleOCRVLCloudEngineName is the PaddleOCR-VL AI Studio cloud API.
PaddleOCRVLCloudEngineName = "paddleocr_vl_cloud"
)
func init() {
types.SetPreferParserEngine(preferAnydocWhenAvailable)
RegisterEngine(&builtinEngine{})
RegisterEngine(&simpleEngine{})
RegisterEngine(&anydocEngine{})
RegisterEngine(&academyCloudEngine{})
RegisterEngine(&mineruEngine{})
RegisterEngine(&mineruCloudEngine{})
RegisterEngine(&paddleOCRVLEngine{})
RegisterEngine(&paddleOCRVLCloudEngine{})
}
// preferAnydocWhenAvailable is the type-level default override: when the
// anydoc binding is linked and converts this file type, use it instead of
// builtin or the markitdown fallback. Simple formats stay on the Go reader.
//
// PDF is excluded. anydoc has no document model for it, so Convert force-
// disables asset extraction, and AnydocReader only falls back to builtin
// when the whole file yields no text at all. A born-digital PDF that yields
// a few characters is therefore reported as parsed while its figures,
// tables and layout are gone. The builtin parser classifies pages
// individually and routes scanned ones through OCR/VLM, so it is the better
// default for the one type anydoc cannot model.
func preferAnydocWhenAvailable(fileType string) string {
ft := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(fileType), "."))
if IsSimpleFormat(ft) || ft == "pdf" {
return ""
}
if anydoc.Available() && anydoc.Supports(ft, "") {
return AnydocEngineName
}
return ""
}
// ---------------------------------------------------------------------------
// builtin — DocReader-backed parser for complex document formats.
// ---------------------------------------------------------------------------
type builtinEngine struct{}
func (e *builtinEngine) Name() string { return BuiltinEngineName }
func (e *builtinEngine) Description() string { return "DocReader built-in parser engine" }
func (e *builtinEngine) FileTypes(_ bool) []string {
return []string{
"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls",
"pptx", "ppt", "epub",
"html", "htm", "mhtml", "xmind",
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
"mp3", "wav", "m4a", "flac", "ogg",
}
}
func (e *builtinEngine) CheckAvailable(docreaderConnected bool, _ map[string]string) (bool, string) {
if docreaderConnected {
return true, ""
}
return false, "DocReader service not connected"
}
// NewReader returns the docreader client. Selecting "builtin" explicitly means
// the docreader is wanted even for formats the simple reader could handle.
func (e *builtinEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return remoteReader(deps)
}
// ---------------------------------------------------------------------------
// simple — Go handles md/txt/csv/json natively, no external service needed.
// Distinct from docreader's "builtin", which uses Python libraries for complex
// formats (docx, pdf, ...).
// ---------------------------------------------------------------------------
type simpleEngine struct{}
func (e *simpleEngine) Name() string { return SimpleEngineName }
func (e *simpleEngine) Description() string {
return "Simple format & image parsing (no external service required)"
}
func (e *simpleEngine) FileTypes(_ bool) []string {
return []string{
"md", "markdown", "txt", "csv", "json",
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
"mp3", "wav", "m4a", "flac", "ogg",
}
}
func (e *simpleEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
return true, ""
}
func (e *simpleEngine) NewReader(_ context.Context, _ ReaderDeps) (interfaces.DocReader, error) {
return &SimpleFormatReader{}, nil
}
// ---------------------------------------------------------------------------
// anydoc — office documents converted in this process, no external service.
// Only present in builds that link the converter (see the anydoc package).
// ---------------------------------------------------------------------------
type anydocEngine struct{}
func (e *anydocEngine) Name() string { return AnydocEngineName }
func (e *anydocEngine) Description() string {
return "anydoc in-process office document converter (no external service required)"
}
func (e *anydocEngine) FileTypes(_ bool) []string { return anydoc.SupportedFileTypes() }
func (e *anydocEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
if anydoc.Available() {
return true, ""
}
return false, anydoc.UnavailableReason()
}
func (e *anydocEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
if !anydoc.Available() {
return nil, errEngineUnavailable(AnydocEngineName, anydoc.UnavailableReason())
}
return NewAnydocReader(deps.Overrides, deps.Remote), nil
}
// ---------------------------------------------------------------------------
// academycloud — Tenant-scoped AcademyCloud docreader with signed requests.
// ---------------------------------------------------------------------------
type academyCloudEngine struct{}
func (e *academyCloudEngine) Name() string { return AcademyCloudEngineName }
func (e *academyCloudEngine) Description() string { return "AcademyCloud document reader" }
func (e *academyCloudEngine) FileTypes(_ bool) []string {
return []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "pptx", "ppt"}
}
func (e *academyCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
if overrides["academycloud_app_id"] != "" {
return true, ""
}
return false, "Academy Cloud credentials not configured. Go to Settings → Academy Cloud to set up."
}
func (e *academyCloudEngine) NewReader(
ctx context.Context, deps ReaderDeps,
) (interfaces.DocReader, error) {
if deps.AcademyCloudCredentials == nil {
return nil, errEngineUnavailable(AcademyCloudEngineName, "no credential resolver configured")
}
creds := deps.AcademyCloudCredentials(ctx)
if creds == nil {
return nil, errEngineUnavailable(AcademyCloudEngineName, "tenant credentials not configured")
}
return NewAcademyCloudSignedDocumentReader(creds.AppID, creds.AppSecret)
}
// ---------------------------------------------------------------------------
// mineru — Go-native, calls self-hosted MinerU API directly
// ---------------------------------------------------------------------------
type mineruEngine struct{}
func (e *mineruEngine) Name() string { return MinerUEngineName }
func (e *mineruEngine) Description() string { return "MinerU self-hosted service" }
func (e *mineruEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
}
func (e *mineruEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
endpoint := strings.TrimSpace(overrides["mineru_endpoint"])
if endpoint == "" {
return false, "MinerU service not configured"
}
return PingMinerU(endpoint, overrides["mineru_server_api_key"])
}
func (e *mineruEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewMinerUReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// mineru_cloud — Go-native, calls MinerU Cloud API directly
// ---------------------------------------------------------------------------
type mineruCloudEngine struct{}
func (e *mineruCloudEngine) Name() string { return MinerUCloudEngineName }
func (e *mineruCloudEngine) Description() string { return "MinerU Cloud API" }
func (e *mineruCloudEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
}
func (e *mineruCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
apiKey := strings.TrimSpace(overrides["mineru_api_key"])
if apiKey == "" {
return false, "MinerU API Key not configured"
}
return PingMinerUCloud(apiKey)
}
func (e *mineruCloudEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewMinerUCloudReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// paddleocr_vl — Go-native, calls a self-hosted PaddleOCR-VL pipeline service
// ---------------------------------------------------------------------------
type paddleOCRVLEngine struct{}
func (e *paddleOCRVLEngine) Name() string { return PaddleOCRVLEngineName }
func (e *paddleOCRVLEngine) Description() string { return "PaddleOCR-VL self-hosted service" }
func (e *paddleOCRVLEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff"}
}
func (e *paddleOCRVLEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
endpoint := strings.TrimSpace(overrides["paddleocr_vl_endpoint"])
if endpoint == "" {
return false, "PaddleOCR-VL service not configured"
}
return PingPaddleOCRVL(endpoint)
}
func (e *paddleOCRVLEngine) NewReader(_ context.Context, deps ReaderDeps) (interfaces.DocReader, error) {
return NewPaddleOCRVLReader(deps.Overrides), nil
}
// ---------------------------------------------------------------------------
// paddleocr_vl_cloud — Go-native, calls the PaddleOCR-VL AI Studio cloud API
// ---------------------------------------------------------------------------
type paddleOCRVLCloudEngine struct{}
func (e *paddleOCRVLCloudEngine) Name() string { return PaddleOCRVLCloudEngineName }
func (e *paddleOCRVLCloudEngine) Description() string { return "PaddleOCR-VL Cloud API" }
func (e *paddleOCRVLCloudEngine) FileTypes(_ bool) []string {
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff"}
}
func (e *paddleOCRVLCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
token := strings.TrimSpace(overrides["paddleocr_vl_cloud_token"])
if token == "" {
return false, "PaddleOCR-VL Cloud Token not configured"
}
return PingPaddleOCRVLCloud(token)
}
func (e *paddleOCRVLCloudEngine) NewReader(
_ context.Context, deps ReaderDeps,
) (interfaces.DocReader, error) {
return NewPaddleOCRVLCloudReader(deps.Overrides), nil
}
@@ -0,0 +1,275 @@
package docparser
import (
"context"
"fmt"
"io"
"os"
"strconv"
"sync"
"time"
docclient "academy/docreader/client"
"academy/docreader/proto"
"academy/internal/logger"
"academy/internal/types"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func getMaxMessageSize() int {
if sizeStr := os.Getenv("MAX_FILE_SIZE_MB"); sizeStr != "" {
if size, err := strconv.Atoi(sizeStr); err == nil && size > 0 {
return size * 1024 * 1024
}
}
return 50 * 1024 * 1024
}
// GRPCDocumentReader implements DocumentReader over gRPC.
type GRPCDocumentReader struct {
mu sync.RWMutex
conn *grpc.ClientConn
client proto.DocReaderClient
addr string
}
func NewGRPCDocumentReader(addr string) (*GRPCDocumentReader, error) {
p := &GRPCDocumentReader{}
if addr != "" {
if err := p.connect(addr); err != nil {
return nil, err
}
}
return p, nil
}
func (p *GRPCDocumentReader) connect(addr string) error {
authConfig := docclient.LoadAuthConfigFromEnv()
opts, err := authConfig.BuildDialOptions(getMaxMessageSize())
if err != nil {
return fmt.Errorf("failed to build docreader dial options: %w", err)
}
if authConfig.TLSEnabled {
logger.Infof(context.Background(), "TLS enabled for docreader gRPC client")
}
if authConfig.AuthToken != "" {
logger.Infof(context.Background(),
"Token authentication enabled for docreader gRPC client (TLS=%v)",
authConfig.TLSEnabled,
)
}
start := time.Now()
conn, err := grpc.Dial("dns:///"+addr, opts...)
if err != nil {
return fmt.Errorf("failed to connect to docreader: %w", err)
}
logger.Infof(context.Background(), "Connected to docreader in %v", time.Since(start))
p.conn = conn
p.client = proto.NewDocReaderClient(conn)
p.addr = addr
return nil
}
func (p *GRPCDocumentReader) Reconnect(addr string) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn != nil {
_ = p.conn.Close()
p.conn = nil
p.client = nil
p.addr = ""
}
return p.connect(addr)
}
func (p *GRPCDocumentReader) IsConnected() bool {
p.mu.RLock()
defer p.mu.RUnlock()
return p.conn != nil
}
func (p *GRPCDocumentReader) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn != nil {
return p.conn.Close()
}
return nil
}
var errNotConnected = status.Error(codes.Unavailable, "docreader service not connected")
func (p *GRPCDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, errNotConnected
}
protoReq := &proto.ReadRequest{
FileContent: req.FileContent,
FileName: req.FileName,
FileType: req.FileType,
Url: req.URL,
Title: req.Title,
RequestId: req.RequestID,
Config: &proto.ReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
// Use the streaming RPC so documents with many page images (large scanned
// PDFs) are not capped by the unary message-size limit. The meta frame
// arrives first, followed by one frame per image.
result, err := p.readStream(ctx, client, protoReq)
if err != nil {
// An older docreader build may not implement ReadStream. Fall back to
// the unary Read RPC so a version-skewed deployment still parses
// documents (small/medium docs only — the unary path remains capped by
// the gRPC message-size limit, which is exactly what streaming avoids).
if status.Code(err) == codes.Unimplemented {
logger.Warnf(ctx, "docreader ReadStream unimplemented, falling back to unary Read: %v", err)
return p.readUnary(ctx, client, protoReq)
}
return nil, err
}
return result, nil
}
// readStream consumes the server-streaming ReadStream RPC: one meta frame
// followed by one frame per image. Errors are returned verbatim so the caller
// can inspect the gRPC status code (e.g. Unimplemented) for fallback.
func (p *GRPCDocumentReader) readStream(
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
) (*types.ReadResult, error) {
stream, err := client.ReadStream(ctx, protoReq)
if err != nil {
return nil, fmt.Errorf("gRPC ReadStream failed: %w", err)
}
result := &types.ReadResult{}
gotMeta := false
for {
frame, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
return nil, fmt.Errorf("gRPC ReadStream recv failed: %w", recvErr)
}
if meta := frame.GetMeta(); meta != nil {
gotMeta = true
result.MarkdownContent = meta.GetMarkdownContent()
result.ImageDirPath = meta.GetImageDirPath()
result.Metadata = meta.GetMetadata()
result.Error = meta.GetError()
result.SourceBlocks = sourceBlocksFromProto(meta.GetSourceBlocks())
if n := meta.GetImageCount(); n > 0 {
result.ImageRefs = make([]types.ImageRef, 0, n)
}
continue
}
if img := frame.GetImage(); img != nil {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: img.GetFilename(),
OriginalRef: img.GetOriginalRef(),
MimeType: img.GetMimeType(),
StorageKey: img.GetStorageKey(),
ImageData: img.GetImageData(),
})
}
}
if !gotMeta {
return nil, fmt.Errorf("gRPC ReadStream returned no metadata frame")
}
return result, nil
}
// readUnary calls the legacy unary Read RPC. Used only as a compatibility
// fallback when the connected docreader does not implement ReadStream.
func (p *GRPCDocumentReader) readUnary(
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
) (*types.ReadResult, error) {
resp, err := client.Read(ctx, protoReq)
if err != nil {
return nil, fmt.Errorf("gRPC Read failed: %w", err)
}
result := &types.ReadResult{
MarkdownContent: resp.GetMarkdownContent(),
ImageDirPath: resp.GetImageDirPath(),
Metadata: resp.GetMetadata(),
Error: resp.GetError(),
SourceBlocks: sourceBlocksFromProto(resp.GetSourceBlocks()),
}
if refs := resp.GetImageRefs(); len(refs) > 0 {
result.ImageRefs = make([]types.ImageRef, 0, len(refs))
for _, img := range refs {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: img.GetFilename(),
OriginalRef: img.GetOriginalRef(),
MimeType: img.GetMimeType(),
StorageKey: img.GetStorageKey(),
ImageData: img.GetImageData(),
})
}
}
return result, nil
}
func (p *GRPCDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, errNotConnected
}
resp, err := client.ListEngines(ctx, &proto.ListEnginesRequest{ConfigOverrides: overrides})
if err != nil {
return nil, fmt.Errorf("gRPC ListEngines failed: %w", err)
}
result := make([]types.ParserEngineInfo, 0, len(resp.GetEngines()))
for _, e := range resp.GetEngines() {
result = append(result, types.ParserEngineInfo{
Name: e.GetName(),
Description: e.GetDescription(),
FileTypes: e.GetFileTypes(),
Available: e.GetAvailable(),
UnavailableReason: e.GetUnavailableReason(),
})
}
return result, nil
}
// PreprocessImage straightens and crops a photographed page before OCR runs.
// The docreader does the work; a page it declines to improve comes back as
// fallback=true with no bytes, which the caller reads as "use the original".
func (p *GRPCDocumentReader) PreprocessImage(ctx context.Context, image []byte) ([]byte, bool, error) {
p.mu.RLock()
client := p.client
p.mu.RUnlock()
if client == nil {
return nil, true, errNotConnected
}
resp, err := client.PreprocessImage(ctx, &proto.PreprocessImageRequest{Image: image})
if err != nil {
return nil, true, fmt.Errorf("gRPC PreprocessImage failed: %w", err)
}
if resp.GetFallbackNeeded() || len(resp.GetImage()) == 0 {
return nil, true, nil
}
return resp.GetImage(), false, nil
}
@@ -0,0 +1,22 @@
package docparser
import (
"testing"
"google.golang.org/grpc/resolver"
)
func TestGRPCDocumentReaderDoesNotChangeGlobalResolver(t *testing.T) {
previous := resolver.GetDefaultScheme()
resolver.SetDefaultScheme("passthrough")
t.Cleanup(func() { resolver.SetDefaultScheme(previous) })
reader, err := NewGRPCDocumentReader("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = reader.Close() })
if got := resolver.GetDefaultScheme(); got != "passthrough" {
t.Fatalf("DocReader changed global gRPC resolver to %q", got)
}
}
@@ -0,0 +1,130 @@
package docparser
import (
"context"
"fmt"
"os"
"sort"
"strings"
"time"
"academy/internal/logger"
)
// stringOr returns val (trimmed) if non-empty, otherwise fallback.
func stringOr(val, fallback string) string {
val = strings.TrimSpace(val)
if val == "" {
return fallback
}
return val
}
// parseBoolOr parses a truthy string ("true","1","yes"), returning fallback on empty.
func parseBoolOr(val string, fallback bool) bool {
val = strings.ToLower(strings.TrimSpace(val))
if val == "" {
return fallback
}
return val == "true" || val == "1" || val == "yes"
}
// requestTimeoutFromEnv reads a positive Go duration from env, falling back to
// fallback when the variable is unset, invalid or not positive. It bounds a
// self-hosted engine's request; the caller's context may impose an earlier
// deadline.
func requestTimeoutFromEnv(env string, fallback time.Duration) time.Duration {
value := strings.TrimSpace(os.Getenv(env))
if value == "" {
return fallback
}
timeout, err := time.ParseDuration(value)
if err != nil || timeout <= 0 {
logger.Warnf(context.Background(), "Invalid %s %q; using %s", env, value, fallback)
return fallback
}
return timeout
}
// firstNonEmpty returns the first non-empty string, or "" if all are empty.
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
// sleepCtx sleeps for d but returns early if ctx is cancelled.
func sleepCtx(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
case <-t.C:
}
}
// logResponseStructure recursively logs the structure of an API response,
// truncating large string values. label identifies the subsystem (e.g. "MinerU").
func logResponseStructure(label string, obj interface{}, prefix string) {
switch v := obj.(type) {
case map[string]interface{}:
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
logger.Infof(context.Background(), "[%s] %s = {object with %d keys: %s}", label, prefix, len(v), strings.Join(keys, ", "))
for _, key := range keys {
val := v[key]
path := prefix + "." + key
switch inner := val.(type) {
case map[string]interface{}:
logResponseStructure(label, inner, path)
case []interface{}:
logger.Infof(context.Background(), "[%s] %s = [array with %d items]", label, path, len(inner))
if len(inner) > 0 {
logger.Infof(context.Background(), "[%s] %s[0] type=%T", label, path, inner[0])
if len(inner) <= 3 {
for i, item := range inner {
logResponseStructure(label, item, fmt.Sprintf("%s[%d]", path, i))
}
} else {
logResponseStructure(label, inner[0], path+"[0]")
logger.Infof(context.Background(), "[%s] ... and %d more items in %s", label, len(inner)-1, path)
}
}
case string:
if len(inner) > 200 {
logger.Infof(context.Background(), "[%s] %s = string(%d chars): %.200s...", label, path, len(inner), inner)
} else {
logger.Infof(context.Background(), "[%s] %s = %q", label, path, inner)
}
case float64:
logger.Infof(context.Background(), "[%s] %s = %v (number)", label, path, inner)
case bool:
logger.Infof(context.Background(), "[%s] %s = %v (bool)", label, path, inner)
case nil:
logger.Infof(context.Background(), "[%s] %s = null", label, path)
default:
logger.Infof(context.Background(), "[%s] %s = %v (%T)", label, path, val, val)
}
}
case []interface{}:
logger.Infof(context.Background(), "[%s] %s = [array with %d items]", label, prefix, len(v))
if len(v) > 0 {
if len(v) <= 3 {
for i, item := range v {
logResponseStructure(label, item, fmt.Sprintf("%s[%d]", prefix, i))
}
} else {
logResponseStructure(label, v[0], prefix+"[0]")
logger.Infof(context.Background(), "[%s] ... and %d more items in %s", label, len(v)-1, prefix)
}
}
default:
logger.Infof(context.Background(), "[%s] %s = %v (%T)", label, prefix, v, v)
}
}
@@ -0,0 +1,159 @@
package docparser
import (
"regexp"
"strings"
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
)
var (
// htmlTableBlockPattern matches a single (non-nested) <table>...</table>
// block, the form OCR/layout engines such as PaddleOCR-VL emit tables in.
htmlTableBlockPattern = regexp.MustCompile(`(?is)<table\b[^>]*>.*?</table>`)
// fencedCodeBlockPattern matches CommonMark fenced code blocks so HTML
// <table> examples inside them are left untouched.
fencedCodeBlockPattern = regexp.MustCompile("(?s)(?:```|~~~)[^\\n]*\\n.*?(?:```|~~~)")
// htmlLayoutAttrPattern matches presentational HTML attributes that carry
// no semantic value (text-align styles, CSS classes, sizing). Structural
// attributes like rowspan/colspan are intentionally excluded.
htmlLayoutAttrPattern = regexp.MustCompile(
`(?is)\s+(?:style|class|align|valign|width|height|bgcolor)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)`,
)
// htmlSpanAttrPattern detects rowspan/colspan values greater than 1, which
// Markdown tables cannot represent; such tables keep their HTML form
// (attributes stripped) instead. Span values of 1 (and the invalid 0) do
// not merge anything and must stay convertible.
htmlSpanAttrPattern = regexp.MustCompile(`(?i)\b(?:row|col)span\s*=\s*["']?(?:[2-9]|\d{2,})`)
// htmlTableRowPattern matches the opening <tr> tag of each table row, used
// to put every row on its own line so the chunker can split degraded HTML
// tables at "\n" boundaries.
htmlTableRowPattern = regexp.MustCompile(`(?i)<tr\b`)
// markdownTableSeparatorPattern matches the |---| delimiter row that a
// valid GFM table must contain. The repeating column group is optional so
// single-column tables (|---|) are accepted; requiring two or more columns
// discarded successful conversions of MinerU figure/TOC tables.
markdownTableSeparatorPattern = regexp.MustCompile(`(?m)^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$`)
)
// NormalizeHTMLTables rewrites inline HTML <table> blocks embedded in OCR
// markdown output. PaddleOCR-VL emits tables as HTML with per-cell text-align
// styles, which (1) waste tokens on layout markup and (2) are not recognized
// by the chunker's table-protection logic, so large tables get split mid-row.
//
// Each table block is converted to a GFM Markdown table when possible. Tables
// that use rowspan/colspan (which Markdown cannot express), or that the
// converter cannot turn into a valid GFM table (cell <br>, nested lists, …),
// fall back to presentational-attribute stripping plus one row per line so
// the chunker can still split on "\n". Tables inside fenced code blocks are
// left unchanged.
func NormalizeHTMLTables(md string) string {
if !strings.Contains(strings.ToLower(md), "<table") {
return md
}
locs := htmlTableBlockPattern.FindAllStringIndex(md, -1)
if len(locs) == 0 {
return md
}
conv := converter.NewConverter(
converter.WithPlugins(
base.NewBasePlugin(),
commonmark.NewCommonmarkPlugin(),
table.NewTablePlugin(),
),
)
fences := fencedCodeBlockPattern.FindAllStringIndex(md, -1)
var b strings.Builder
last := 0
for _, loc := range locs {
b.WriteString(md[last:loc[0]])
block := md[loc[0]:loc[1]]
if indexInsideSpans(loc[0], fences) {
b.WriteString(block)
last = loc[1]
continue
}
// Isolate the rewritten table with blank lines without stacking pads
// on repeated NormalizeHTMLTables calls.
out := strings.TrimRight(b.String(), "\n")
b.Reset()
b.WriteString(out)
b.WriteString("\n\n")
b.WriteString(normalizeOneHTMLTable(conv, block))
last = loc[1]
for last < len(md) && md[last] == '\n' {
last++
}
b.WriteString("\n\n")
}
b.WriteString(md[last:])
return b.String()
}
func normalizeOneHTMLTable(conv *converter.Converter, block string) string {
fallback := func() string {
return splitHTMLTableRows(stripHTMLLayoutAttrs(block))
}
if htmlSpanAttrPattern.MatchString(block) {
return fallback()
}
converted, err := conv.ConvertString(block)
if err != nil {
return fallback()
}
converted = unescapeMarkdownImageSyntax(strings.TrimSpace(converted))
if converted == "" || !markdownTableSeparatorPattern.MatchString(converted) {
return fallback()
}
return converted
}
func indexInsideSpans(pos int, spans [][]int) bool {
for _, s := range spans {
if pos >= s[0] && pos < s[1] {
return true
}
}
return false
}
// stripHTMLLayoutAttrs removes presentational attributes from an HTML fragment
// while preserving structural attributes (rowspan/colspan) and text content.
func stripHTMLLayoutAttrs(html string) string {
return htmlLayoutAttrPattern.ReplaceAllString(html, "")
}
// splitHTMLTableRows puts each table row on its own line. The chunker splits
// on "\n", so a single-line HTML table would otherwise be unsplittable and get
// force-cut at the absolute max size. Whitespace between tags is insignificant
// in HTML, and newlines are only inserted before <tr> (never inside a tag).
// A <tr> that already starts on its own line is left alone.
func splitHTMLTableRows(block string) string {
locs := htmlTableRowPattern.FindAllStringIndex(block, -1)
if len(locs) == 0 {
return strings.TrimSpace(block)
}
var b strings.Builder
last := 0
for _, loc := range locs {
b.WriteString(block[last:loc[0]])
if loc[0] == 0 || block[loc[0]-1] != '\n' {
b.WriteByte('\n')
}
b.WriteString(block[loc[0]:loc[1]])
last = loc[1]
}
b.WriteString(block[last:])
return strings.TrimSpace(b.String())
}
@@ -0,0 +1,233 @@
package docparser
import (
"strings"
"testing"
)
func TestNormalizeHTMLTables_ConvertsStyledTableToMarkdown(t *testing.T) {
// Mirrors PaddleOCR-VL output: a data table where every cell carries a
// text-align style that wastes tokens.
input := `# 报告
<table><tr><td style="text-align:center;">指标</td><td style="text-align:center;">数值</td></tr>` +
`<tr><td style="text-align:center;">营收</td><td style="text-align:right;">10亿</td></tr>` +
`<tr><td style="text-align:center;">利润</td><td style="text-align:right;">2.3亿</td></tr></table>
结尾。`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected HTML table to be converted away, got:\n%s", got)
}
if strings.Contains(got, "text-align") {
t.Fatalf("expected style attributes removed, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"指标", "数值", "营收", "10亿", "利润", "2.3亿"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
if !strings.Contains(got, "# 报告") || !strings.Contains(got, "结尾。") {
t.Fatalf("expected surrounding markdown to be preserved, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_NoTableUnchanged(t *testing.T) {
input := "# 标题\n\n普通段落,没有表格。\n\n| a | b |\n| --- | --- |\n| 1 | 2 |"
if got := NormalizeHTMLTables(input); got != input {
t.Fatalf("expected content without HTML tables to be unchanged, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_SpanValueOneIsConvertible(t *testing.T) {
// rowspan=1 / colspan=1 merge nothing, so the table must still become GFM.
// Covers quoted, unquoted and space-padded attribute forms.
input := `<table><tr>` +
`<td rowspan="1" colspan="1" style="text-align:center;">指标</td>` +
`<td rowspan=1 colspan=1>数值</td></tr>` +
`<tr><td rowspan="1" colspan='1'>营收</td>` +
`<td rowspan = 1 colspan = 1>10亿</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected span=1 table to be converted away, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"指标", "数值", "营收", "10亿"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_RealSpanKeepsHTMLWithRowNewlines(t *testing.T) {
// Genuine merges (colspan>1 / rowspan>1) cannot be GFM, so the table stays
// HTML — but each row must start on its own line so the chunker can split it.
input := `<table><tr><td colspan="6" style="text-align:center;">合计</td></tr>` +
`<tr><td rowspan="3">A</td><td>1</td></tr>` +
`<tr><td rowspan = 2>B</td><td>2</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected real span table to remain HTML, got:\n%s", got)
}
if !strings.Contains(got, `colspan="6"`) || !strings.Contains(got, `rowspan="3"`) {
t.Fatalf("expected structural span attrs preserved, got:\n%s", got)
}
if !strings.Contains(got, "\n<tr") {
t.Fatalf("expected each <tr> to start on a new line, got:\n%q", got)
}
if !strings.Contains(got, "\n\n<table") {
t.Fatalf("expected block to be padded at the head with blank lines, got:\n%q", got)
}
if !strings.HasSuffix(got, "</table>\n\n") {
t.Fatalf("expected block to be padded at the tail with blank lines, got:\n%q", got)
}
if n := strings.Count(got, "\n<tr"); n != 3 {
t.Fatalf("expected 3 rows each preceded by a newline, got %d in:\n%q", n, got)
}
}
func assertHTMLRowsSplittable(t *testing.T, got string) {
t.Helper()
if !strings.Contains(got, "<tr") {
t.Fatalf("expected remaining HTML table rows, got:\n%s", got)
}
for i := 0; ; {
idx := strings.Index(got[i:], "<tr")
if idx < 0 {
return
}
abs := i + idx
if abs == 0 || got[abs-1] != '\n' {
t.Fatalf("remaining <tr> at offset %d is not preceded by a newline:\n%s", abs, got)
}
i = abs + 1
}
}
func TestNormalizeHTMLTables_StripsAttrsOnSpanTables(t *testing.T) {
// rowspan/colspan cannot be expressed in Markdown, so the table stays HTML
// but its presentational attributes are stripped and rows become splittable.
input := `<table><tr>` +
`<td colspan="2" style="text-align:center;" class="hdr">合计</td></tr>` +
`<tr><td style="text-align:left;">A</td><td width="80">B</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected span table to remain HTML, got:\n%s", got)
}
if !strings.Contains(got, `colspan="2"`) {
t.Fatalf("expected colspan to be preserved, got:\n%s", got)
}
for _, banned := range []string{"text-align", "class=", "width="} {
if strings.Contains(got, banned) {
t.Fatalf("expected %q to be stripped, got:\n%s", banned, got)
}
}
assertHTMLRowsSplittable(t, got)
}
func TestNormalizeHTMLTables_BRCellsStaySplittableHTML(t *testing.T) {
// <br> inside a cell makes the table plugin give up (it emits a newline).
// The HTML fallback must still put each <tr> on its own line.
input := `<table><tr><td>指标<br/>名称</td><td>数值<br/>单位</td></tr>` +
`<tr><td>拉伸强度<br/>MPa</td><td>合格<br/>A级</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected <br> table to remain HTML rather than flattened text, got:\n%s", got)
}
assertHTMLRowsSplittable(t, got)
for _, want := range []string{"指标", "名称", "拉伸强度", "合格"} {
if !strings.Contains(got, want) {
t.Fatalf("expected fallback HTML to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_ListInCellFallsBackToSplittableHTML(t *testing.T) {
input := `<table><tr><td><ul><li>a</li><li>b</li></ul></td><td>x</td></tr>` +
`<tr><td>c</td><td>d</td></tr></table>`
got := NormalizeHTMLTables(input)
if !strings.Contains(got, "<table") {
t.Fatalf("expected list-in-cell table to remain HTML, got:\n%s", got)
}
assertHTMLRowsSplittable(t, got)
}
func TestNormalizeHTMLTables_SingleColumnConvertsToGFM(t *testing.T) {
input := `<table><tr><td>目录</td></tr><tr><td>第一章</td></tr><tr><td>第二章</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected single-column table to convert to GFM, got:\n%s", got)
}
if !markdownTableSeparatorPattern.MatchString(got) {
t.Fatalf("expected a Markdown table separator row, got:\n%s", got)
}
for _, want := range []string{"目录", "第一章", "第二章"} {
if !strings.Contains(got, want) {
t.Fatalf("expected converted table to retain %q, got:\n%s", want, got)
}
}
}
func TestNormalizeHTMLTables_ImgInSingleColumnBecomesGFM(t *testing.T) {
input := `<table><tr><td><img src="local://images/profile.png" alt="profile"/></td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, "<table") {
t.Fatalf("expected single-column image table to convert to GFM, got:\n%s", got)
}
if !strings.Contains(got, "![profile](local://images/profile.png)") {
t.Fatalf("expected markdown image to be preserved, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_MarkdownImageInCellNotEscaped(t *testing.T) {
input := `<table><tr><td>![cover](local://images/cover.png)</td><td>说明</td></tr></table>`
got := NormalizeHTMLTables(input)
if strings.Contains(got, `!\[`) {
t.Fatalf("markdown image syntax escaped:\n%s", got)
}
if !strings.Contains(got, "![cover](local://images/cover.png)") {
t.Fatalf("expected markdown image to survive conversion, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_CodeFenceTableLeftAlone(t *testing.T) {
input := "示例:\n\n```html\n<table><tr><td>a</td><td>b</td></tr></table>\n```\n"
got := NormalizeHTMLTables(input)
if got != input {
t.Fatalf("expected fenced HTML table to be unchanged, got:\n%s", got)
}
}
func TestNormalizeHTMLTables_SpanTableIdempotent(t *testing.T) {
input := `<table><tr><td colspan="6">汇总</td></tr><tr><td colspan="6">备注</td></tr></table>`
once := NormalizeHTMLTables(input)
twice := NormalizeHTMLTables(once)
if once != twice {
t.Fatalf("NormalizeHTMLTables is not idempotent for span tables:\n1=%q\n2=%q", once, twice)
}
}
@@ -0,0 +1,256 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
)
const (
PathRead = "/read"
PathListEngines = "/list-engines"
)
// --- JSON DTOs ---
type httpReadConfig struct {
ParserEngine string `json:"parser_engine,omitempty"`
ParserEngineOverrides map[string]string `json:"parser_engine_overrides,omitempty"`
}
type httpReadRequest struct {
FileContent string `json:"file_content,omitempty"` // base64
FileName string `json:"file_name,omitempty"`
FileType string `json:"file_type,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Config *httpReadConfig `json:"config,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
type httpImageRef struct {
Filename string `json:"filename"`
OriginalRef string `json:"original_ref"`
MimeType string `json:"mime_type"`
StorageKey string `json:"storage_key,omitempty"`
ImageData []byte `json:"image_data,omitempty"`
}
type httpReadResponse struct {
MarkdownContent string `json:"markdown_content"`
ImageRefs []httpImageRef `json:"image_refs,omitempty"`
ImageDirPath string `json:"image_dir_path,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Error string `json:"error,omitempty"`
SourceBlocks []wireSourceBlock `json:"source_blocks,omitempty"`
}
// HTTPDocumentReader implements DocumentReader over HTTP/JSON.
type HTTPDocumentReader struct {
mu sync.RWMutex
baseURL string
client *http.Client
}
func NewHTTPDocumentReader(baseURL string) (*HTTPDocumentReader, error) {
baseURL = strings.TrimSuffix(strings.TrimSpace(baseURL), "/")
if baseURL != "" {
if err := secutils.ValidateURLForSSRF(baseURL); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
}
clientCfg := secutils.DefaultSSRFSafeHTTPClientConfig()
clientCfg.Timeout = 5 * time.Minute
p := &HTTPDocumentReader{
baseURL: baseURL,
client: secutils.NewSSRFSafeHTTPClient(clientCfg),
}
if p.baseURL != "" {
logger.Infof(context.Background(), "INFO: HTTP docreader base URL: %s", p.baseURL)
}
return p, nil
}
func (p *HTTPDocumentReader) base() string {
p.mu.RLock()
defer p.mu.RUnlock()
return p.baseURL
}
func (p *HTTPDocumentReader) Reconnect(addr string) error {
addr = strings.TrimSuffix(strings.TrimSpace(addr), "/")
if addr != "" {
if err := secutils.ValidateURLForSSRF(addr); err != nil {
return fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
}
p.mu.Lock()
defer p.mu.Unlock()
p.baseURL = addr
logger.Infof(context.Background(), "INFO: HTTP docreader base URL set to %s", p.baseURL)
return nil
}
func (p *HTTPDocumentReader) IsConnected() bool {
p.mu.RLock()
defer p.mu.RUnlock()
return p.baseURL != ""
}
func (p *HTTPDocumentReader) Close() error { return nil }
type httpListEnginesRequest struct {
ConfigOverrides map[string]string `json:"config_overrides,omitempty"`
}
type httpParserEngineInfo struct {
Name string `json:"name"`
Description string `json:"description"`
FileTypes []string `json:"file_types"`
Available bool `json:"available"`
UnavailableReason string `json:"unavailable_reason,omitempty"`
}
type httpListEnginesResponse struct {
Engines []httpParserEngineInfo `json:"engines"`
}
func (p *HTTPDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
base := p.base()
if base == "" {
return nil, errNotConnected
}
if err := secutils.ValidateURLForSSRF(base); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
body := httpListEnginesRequest{ConfigOverrides: overrides}
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("http marshal list-engines request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathListEngines, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("http list-engines failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("http list-engines status %d: %s", resp.StatusCode, string(respBytes))
}
var out httpListEnginesResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("http decode list-engines response: %w", err)
}
result := make([]types.ParserEngineInfo, 0, len(out.Engines))
for _, e := range out.Engines {
result = append(result, types.ParserEngineInfo{
Name: e.Name,
Description: e.Description,
FileTypes: e.FileTypes,
Available: e.Available,
UnavailableReason: e.UnavailableReason,
})
}
return result, nil
}
func fromHTTPReadResponse(resp *httpReadResponse) *types.ReadResult {
result := &types.ReadResult{
MarkdownContent: resp.MarkdownContent,
ImageDirPath: resp.ImageDirPath,
Metadata: resp.Metadata,
Error: resp.Error,
SourceBlocks: sourceBlocksFromWire(resp.SourceBlocks),
}
for _, ref := range resp.ImageRefs {
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
Filename: ref.Filename,
OriginalRef: ref.OriginalRef,
MimeType: ref.MimeType,
StorageKey: ref.StorageKey,
ImageData: ref.ImageData,
})
}
return result
}
func (p *HTTPDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
base := p.base()
if base == "" {
return nil, errNotConnected
}
if err := secutils.ValidateURLForSSRF(base); err != nil {
return nil, fmt.Errorf("docreader address failed SSRF validation: %w", err)
}
body := httpReadRequest{
FileName: req.FileName,
FileType: req.FileType,
URL: req.URL,
Title: req.Title,
RequestID: req.RequestID,
Config: &httpReadConfig{
ParserEngine: req.ParserEngine,
ParserEngineOverrides: req.ParserEngineOverrides,
},
}
if len(req.FileContent) > 0 {
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
}
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("http marshal read request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathRead, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("http new request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.ContentLength = int64(len(jsonBody))
resp, err := p.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("http read failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
}
var out httpReadResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("http decode read response: %w", err)
}
return fromHTTPReadResponse(&out), nil
}
// PreprocessImage is not offered over the HTTP transport: page straightening
// lives in the docreader service, and this reader speaks to a different
// surface. It reports that as a verdict — fallback=true, no error — so the
// caller's single fallback (OCR the original bytes) is the only outcome, with
// nothing logged that looks like a failure.
func (p *HTTPDocumentReader) PreprocessImage(_ context.Context, _ []byte) ([]byte, bool, error) {
return nil, true, nil
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,80 @@
package docparser
import (
"context"
"strings"
"testing"
"academy/internal/types"
)
func TestResolveAndStoreRelativeHTMLImages(t *testing.T) {
png := createTestPNG(200, 150)
result := &types.ReadResult{
MarkdownContent: `<table><tr><td><img src="images/profile.jpg" alt="profile"/></td></tr></table>`,
ImageRefs: []types.ImageRef{
{
Filename: "profile.jpg",
OriginalRef: "images/profile.jpg",
MimeType: "image/png",
ImageData: png,
},
},
}
svc := &captureSaveBytes{}
r := NewImageResolver()
out, imgs, err := r.ResolveAndStore(context.Background(), result, svc, 1)
if err != nil {
t.Fatal(err)
}
if len(imgs) != 1 {
t.Fatalf("expected 1 stored image but got %d", len(imgs))
}
if len(svc.saved) != 1 {
t.Fatalf("expected SaveBytes to be called once but got %d", len(svc.saved))
}
if strings.Contains(out, `src="images/profile.jpg"`) {
t.Fatalf("expected relative html img src to be replaced, got: %s", out)
}
if !strings.Contains(out, `src="local://test/`) {
t.Fatalf("expected stored file url in html img src, got: %s", out)
}
}
// TestResolveAndStoreDedupsSameImageRefVariants ensures that when the same
// MinerU image is referenced under multiple path forms (e.g. "images/foo.png"
// and "./images/foo.png"), the bytes are uploaded to object storage only once.
func TestResolveAndStoreDedupsSameImageRefVariants(t *testing.T) {
png := createTestPNG(200, 150)
result := &types.ReadResult{
MarkdownContent: strings.Join([]string{
"![](images/foo.png)",
`<img src="./images/foo.png"/>`,
}, "\n"),
ImageRefs: []types.ImageRef{
{
Filename: "foo.png",
OriginalRef: "images/foo.png",
MimeType: "image/png",
ImageData: png,
},
{
Filename: "foo.png",
OriginalRef: "./images/foo.png",
MimeType: "image/png",
ImageData: png,
},
},
}
svc := &captureSaveBytes{}
r := NewImageResolver()
_, _, err := r.ResolveAndStore(context.Background(), result, svc, 1)
if err != nil {
t.Fatal(err)
}
if len(svc.saved) != 1 {
t.Fatalf("expected SaveBytes to be called once for duplicate refs, got %d", len(svc.saved))
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,301 @@
package docparser
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
// defaultJSONChunkSize is the target chunk size in bytes for JSON semantic
// splitting. Approximates 512 tokens (1 token ≈ 3-4 bytes for mixed content).
const defaultJSONChunkSize = 1536
// minJSONChunkSize is the minimum chunk size. A new chunk is only started
// when the current chunk has reached at least this size.
var minJSONChunkSize = defaultJSONChunkSize - 200
// Errors returned by ValidateJSONContent.
var (
ErrEmptyJSONContent = errors.New("empty JSON content")
ErrInvalidJSONContent = errors.New("invalid JSON content")
)
// ValidateJSONContent reports whether data is well-formed JSON after stripping
// a leading UTF-8 BOM. Upload paths call this before enqueueing parse work so
// JSONC / truncated payloads fail immediately instead of after async retries.
func ValidateJSONContent(data []byte) error {
data = trimBOM(data)
if len(data) == 0 {
return ErrEmptyJSONContent
}
if !json.Valid(data) {
return ErrInvalidJSONContent
}
return nil
}
// jsonToMarkdown converts raw JSON bytes into markdown text
//
// Key properties:
// - Every output chunk is a **valid JSON object** (not a fragment).
// - Nested paths from root to leaf are **fully preserved** in each chunk.
// - Arrays are converted to index-keyed dicts so the algorithm is uniform.
// - Small objects that fit within maxChunkSize are kept intact (not split).
// - The output is a series of fenced ```json code blocks separated by \n\n,
// which the downstream text chunker can split at block boundaries.
func jsonToMarkdown(data []byte) (string, error) {
if err := ValidateJSONContent(data); err != nil {
return "", err
}
data = trimBOM(data)
// UseNumber keeps each number as written. Decoded into a float64, an id
// above 2^53 changed digits: 12345678901234567890 came out as
// 12345678901234567000. ValidateJSONContent above has already rejected
// anything after the value.
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var parsed interface{}
if err := decoder.Decode(&parsed); err != nil {
return "", fmt.Errorf("failed to parse JSON: %w", err)
}
// Normalize: convert top-level arrays to index-keyed dicts
normalized := listToDictPreprocess(parsed)
// If the whole thing fits in one chunk, just format it
wholeSize := jsonSize(normalized)
if wholeSize <= defaultJSONChunkSize {
formatted := formatValue(normalized)
return wrapCodeBlock(formatted), nil
}
// Recursive split
chunks := recursiveJSONSplit(normalized, nil, nil)
// Convert each chunk dict to a fenced code block
blocks := make([]string, 0, len(chunks))
for _, chunk := range chunks {
if len(chunk) == 0 {
continue
}
blocks = append(blocks, wrapCodeBlock(formatValue(chunk)))
}
if len(blocks) == 0 {
return wrapCodeBlock(formatValue(normalized)), nil
}
return strings.Join(blocks, "\n\n"), nil
}
// ---------------------------------------------------------------------------
// RecursiveJsonSplitter core algorithm
// ---------------------------------------------------------------------------
// recursiveJSONSplit splits a JSON dict into a list of JSON dicts,
// each fitting within defaultJSONChunkSize. It preserves the full nested
// path from root to each leaf by using setNestedDict.
//
// This is a Go port of LangChain's RecursiveJsonSplitter._json_split.
func recursiveJSONSplit(
data interface{},
currentPath []string,
chunks []map[string]interface{},
) []map[string]interface{} {
if chunks == nil {
chunks = []map[string]interface{}{{}}
}
dict, ok := data.(map[string]interface{})
if !ok {
// Scalar or already-processed value: place it at the current path
if len(currentPath) > 0 && len(chunks) > 0 {
setNestedDict(chunks[len(chunks)-1], currentPath, data)
}
return chunks
}
// Sort keys for deterministic output
keys := sortedKeys(dict)
for _, key := range keys {
value := dict[key]
newPath := append(append([]string{}, currentPath...), key)
// Measure sizes
chunkSize := jsonSize(chunks[len(chunks)-1])
itemSize := jsonSize(map[string]interface{}{key: value})
remaining := defaultJSONChunkSize - chunkSize
if itemSize <= remaining {
// Item fits in the current chunk — add it preserving the path
setNestedDict(chunks[len(chunks)-1], newPath, value)
} else {
// Item doesn't fit
if chunkSize >= minJSONChunkSize {
// Current chunk is big enough, start a new one
chunks = append(chunks, map[string]interface{}{})
}
// Check if the value itself is a dict/list that can be recursed into
normalized := listToDictPreprocess(value)
if subDict, isDict := normalized.(map[string]interface{}); isDict && canSplitDict(subDict) {
// Recurse into the sub-object
chunks = recursiveJSONSplit(subDict, newPath, chunks)
} else {
// Cannot split further (scalar or single-key dict) — place as-is
setNestedDict(chunks[len(chunks)-1], newPath, value)
}
}
}
return chunks
}
// setNestedDict sets a value in a nested dict structure, creating
// intermediate dicts as needed. This preserves the full JSON path.
//
// Example: setNestedDict(d, ["config","db","host"], "localhost")
// produces: {"config": {"db": {"host": "localhost"}}}
func setNestedDict(d map[string]interface{}, path []string, value interface{}) {
if len(path) == 0 {
return
}
current := d
for _, key := range path[:len(path)-1] {
next, ok := current[key]
if !ok {
next = map[string]interface{}{}
current[key] = next
}
if nextDict, ok := next.(map[string]interface{}); ok {
current = nextDict
} else {
// Path conflict (existing value is not a dict) — overwrite
newDict := map[string]interface{}{}
current[key] = newDict
current = newDict
}
}
current[path[len(path)-1]] = value
}
// listToDictPreprocess recursively converts JSON arrays to index-keyed
// dicts so the splitter can treat everything uniformly.
//
// Example: ["a","b","c"] → {"0":"a", "1":"b", "2":"c"}
func listToDictPreprocess(data interface{}) interface{} {
switch v := data.(type) {
case map[string]interface{}:
result := make(map[string]interface{}, len(v))
for k, val := range v {
result[k] = listToDictPreprocess(val)
}
return result
case []interface{}:
result := make(map[string]interface{}, len(v))
for i, item := range v {
result[fmt.Sprintf("%d", i)] = listToDictPreprocess(item)
}
return result
default:
return data
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// jsonSize returns the serialized JSON byte length of a value.
func jsonSize(v interface{}) int {
b, err := marshalJSON(v, "")
if err != nil {
return 0
}
return len(b)
}
// formatValue formats a JSON value with indentation.
func formatValue(v interface{}) string {
b, err := marshalJSON(v, " ")
if err != nil {
b, _ = marshalJSON(v, "")
}
return string(b)
}
// marshalJSON encodes v like json.Marshal, indented when indent is set, but
// leaves <, > and & as they are. json.Marshal writes them as \u003c, \u003e
// and \u0026, which is meant for embedding in HTML and only garbles the text
// a chunk is read and searched as.
func marshalJSON(v interface{}, indent string) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", indent)
if err := encoder.Encode(v); err != nil {
return nil, err
}
return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil
}
// wrapCodeBlock wraps content in a fenced JSON code block.
func wrapCodeBlock(content string) string {
return "```json\n" + content + "\n```"
}
// trimBOM removes a UTF-8 BOM prefix if present.
func trimBOM(data []byte) []byte {
if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
return data[3:]
}
return data
}
// canSplitDict returns true if a dict can be meaningfully split.
// A dict with multiple keys can be split by distributing keys across chunks.
// A dict with a single key can still be split if its value is a splittable dict.
func canSplitDict(d map[string]interface{}) bool {
if len(d) > 1 {
return true
}
if len(d) == 1 {
for _, v := range d {
if sub, ok := v.(map[string]interface{}); ok && len(sub) > 1 {
return true
}
}
}
return false
}
// sortedKeys returns the keys of a map in sorted order.
// When all keys are numeric strings (from array-to-dict conversion),
// sorts numerically so "2" comes before "10".
func sortedKeys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
allNumeric := true
for k := range m {
keys = append(keys, k)
if allNumeric {
if _, err := strconv.Atoi(k); err != nil {
allNumeric = false
}
}
}
if allNumeric {
sort.Slice(keys, func(i, j int) bool {
ni, _ := strconv.Atoi(keys[i])
nj, _ := strconv.Atoi(keys[j])
return ni < nj
})
} else {
sort.Strings(keys)
}
return keys
}
@@ -0,0 +1,778 @@
package docparser
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"academy/internal/types"
)
// ═══════════════════════════════════════════════════════════════════════════
// Helper: visual test reporter
// ═══════════════════════════════════════════════════════════════════════════
func visualReport(t *testing.T, label string, input string, result string, err error, checks []checkResult) {
t.Helper()
const width = 72
bar := strings.Repeat("─", width)
thickBar := strings.Repeat("━", width)
t.Logf("\n%s", thickBar)
t.Logf("📋 TEST: %s", label)
t.Logf("%s", bar)
// ── Input ──
inputPreview := input
if len(inputPreview) > 200 {
inputPreview = inputPreview[:200] + fmt.Sprintf("... (%d bytes total)", len(input))
}
t.Logf("📥 INPUT (%d bytes):", len(input))
for _, line := range strings.Split(inputPreview, "\n") {
t.Logf(" %s", line)
}
t.Logf("%s", bar)
// ── Output / Error ──
if err != nil {
t.Logf("❌ ERROR: %v", err)
} else {
blockCount := strings.Count(result, "```json")
totalLen := len(result)
t.Logf("📤 OUTPUT: %d code block(s), %d bytes total", blockCount, totalLen)
t.Logf("%s", bar)
blocks := splitBlocks(result)
for i, blk := range blocks {
preview := blk
lines := strings.Split(preview, "\n")
if len(lines) > 10 {
preview = strings.Join(lines[:4], "\n") +
fmt.Sprintf("\n ... (%d lines omitted) ...\n", len(lines)-8) +
strings.Join(lines[len(lines)-4:], "\n")
}
t.Logf(" 📦 Block #%d (%d bytes):", i+1, len(blk))
for _, line := range strings.Split(preview, "\n") {
t.Logf(" │ %s", line)
}
}
}
t.Logf("%s", bar)
// ── Checks ──
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
}
t.Logf("%s %s", icon, c.desc)
if !c.pass {
t.Errorf("FAIL: %s", c.desc)
}
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("%s\n", thickBar)
}
// splitBlocks extracts the content between ```json and ``` fences.
func splitBlocks(result string) []string {
var blocks []string
rest := result
for {
start := strings.Index(rest, "```json\n")
if start < 0 {
break
}
rest = rest[start+len("```json\n"):]
end := strings.Index(rest, "\n```")
if end < 0 {
blocks = append(blocks, rest)
break
}
blocks = append(blocks, rest[:end])
rest = rest[end+len("\n```"):]
}
return blocks
}
type checkResult struct {
desc string
pass bool
}
func check(desc string, pass bool) checkResult { return checkResult{desc, pass} }
// blockIsValidJSON checks that each code block inside the result is valid JSON.
func allBlocksValidJSON(result string) bool {
for _, blk := range splitBlocks(result) {
if !json.Valid([]byte(blk)) {
return false
}
}
return true
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 1: Small inputs — kept intact, NOT split
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_SmallObject(t *testing.T) {
input := `{"name": "test", "version": "1.0"}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Small Object → single block, kept intact", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains key 'name'", strings.Contains(result, `"name"`)),
check("contains key 'version'", strings.Contains(result, `"version"`)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
check("both keys in SAME block (not split apart)",
strings.Contains(result, `"name"`) && strings.Contains(result, `"version"`) && blocks == 1),
})
}
func TestJsonToMarkdown_SmallArray(t *testing.T) {
input := `[{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Small Array → single block, kept intact", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_EmptyObject(t *testing.T) {
input := `{}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Object {}", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '{}'", strings.Contains(result, "{}")),
})
}
func TestJsonToMarkdown_EmptyArray(t *testing.T) {
input := `[]`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Array []", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '{}'", strings.Contains(result, "{}")), // [] → {} after list-to-dict
})
}
func TestJsonToMarkdown_PrimitiveString(t *testing.T) {
input := `"hello world"`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive String", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'hello world'", strings.Contains(result, "hello world")),
})
}
func TestJsonToMarkdown_PrimitiveNumber(t *testing.T) {
input := `42`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Number", input, result, err, []checkResult{
check("no error", err == nil),
check("contains '42'", strings.Contains(result, "42")),
})
}
func TestJsonToMarkdown_PrimitiveBoolean(t *testing.T) {
input := `true`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Boolean", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'true'", strings.Contains(result, "true")),
})
}
func TestJsonToMarkdown_PrimitiveNull(t *testing.T) {
input := `null`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Primitive Null", input, result, err, []checkResult{
check("no error", err == nil),
check("contains 'null'", strings.Contains(result, "null")),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 2: Large data — smart recursive splitting
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_LargeObject(t *testing.T) {
obj := make(map[string]interface{})
for i := 0; i < 50; i++ {
obj[fmt.Sprintf("key_%02d", i)] = strings.Repeat("value", 50)
}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Large Object (50 keys) → multiple blocks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_LargeArray(t *testing.T) {
arr := make([]interface{}, 100)
for i := range arr {
arr[i] = map[string]interface{}{
"id": i,
"name": strings.Repeat("name", 20),
"description": strings.Repeat("desc", 30),
}
}
data, _ := json.Marshal(arr)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Large Array (100 elements) → multiple blocks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_RecursiveSplitLargeKey(t *testing.T) {
inner := make(map[string]interface{})
for i := 0; i < 30; i++ {
inner[fmt.Sprintf("sub_%02d", i)] = strings.Repeat("val", 50)
}
obj := map[string]interface{}{"bigkey": inner}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Recursive Split: 1 big key with 30 sub-keys", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
check("path preserved: chunks contain 'bigkey'", strings.Contains(result, "bigkey")),
})
}
func TestJsonToMarkdown_PathPreservation(t *testing.T) {
// Core test: verify that nested paths are preserved in each chunk
inner := make(map[string]interface{})
for i := 0; i < 40; i++ {
inner[fmt.Sprintf("field_%02d", i)] = strings.Repeat("data", 60)
}
obj := map[string]interface{}{
"config": map[string]interface{}{
"database": inner,
},
}
data, _ := json.Marshal(obj)
result, err := jsonToMarkdown(data)
blocks := splitBlocks(result)
// Every block should contain the full path "config" → "database"
allHavePath := true
for _, blk := range blocks {
if !strings.Contains(blk, `"config"`) || !strings.Contains(blk, `"database"`) {
allHavePath = false
break
}
}
visualReport(t, "Path Preservation: config.database.* across chunks", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks (got %d)", len(blocks)), len(blocks) >= 2),
check("ALL blocks preserve path: config → database", allHavePath),
})
}
func TestJsonToMarkdown_MixedArrayElements(t *testing.T) {
arr := []interface{}{
map[string]interface{}{"id": 1},
map[string]interface{}{"id": 2},
map[string]interface{}{"id": 3, "data": strings.Repeat("x", 2000)},
map[string]interface{}{"id": 4},
}
data, _ := json.Marshal(arr)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Mixed Array: 3 small + 1 large element", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("at least 2 blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_DeepNested(t *testing.T) {
input := `{"l1": {"l2": {"l3": {"data": "` + strings.Repeat("x", 2000) + `"}}}}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Deep Nested (3 levels, large leaf)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("block count ≥ 1 (got %d)", blocks), blocks >= 1),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 3: Error Handling
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_InvalidJSON(t *testing.T) {
input := `{invalid json}`
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Invalid JSON → error", input, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'invalid JSON'",
err != nil && strings.Contains(err.Error(), "invalid JSON")),
})
}
func TestJsonToMarkdown_EmptyInput(t *testing.T) {
input := ""
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Empty Input → error", input, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'empty'",
err != nil && strings.Contains(err.Error(), "empty")),
})
}
func TestJsonToMarkdown_WhitespaceOnly(t *testing.T) {
input := " \n\t "
_, err := jsonToMarkdown([]byte(input))
visualReport(t, "Whitespace-Only Input → error", input, "", err, []checkResult{
check("returns error", err != nil),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 4: Edge Cases & Encoding
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_BOM(t *testing.T) {
raw := append([]byte{0xEF, 0xBB, 0xBF}, []byte(`{"key": "value"}`)...)
result, err := jsonToMarkdown(raw)
visualReport(t, "UTF-8 BOM prefix → stripped", string(raw), result, err, []checkResult{
check("no error", err == nil),
check("contains key after BOM removal", strings.Contains(result, `"key"`)),
})
}
func TestJsonToMarkdown_UnicodeContent(t *testing.T) {
input := `{"名称": "Academy 知识库", "描述": "支持中文 JSON 🎉", "emoji": "🚀"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Unicode / Chinese / Emoji", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains Chinese", strings.Contains(result, "知识库")),
check("contains emoji", strings.Contains(result, "🚀")),
})
}
func TestJsonToMarkdown_SpecialCharsInStrings(t *testing.T) {
input := `{"html": "<div class=\"test\">hello</div>", "path": "C:\\Users\\test", "newline": "line1\nline2"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Special characters (HTML, backslash, newline)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
})
}
func TestJsonToMarkdown_KeepsNumbersAsWritten(t *testing.T) {
// Decoded into a float64, an id above 2^53 changed digits.
input := `{"order_id": 12345678901234567890, "big": 9007199254740993, "price": 1.50, "ratio": 1e5}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Numbers keep the digits they were written with", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("order_id keeps all 20 digits", strings.Contains(result, `"order_id": 12345678901234567890`)),
check("2^53+1 is not rounded to 2^53", strings.Contains(result, `"big": 9007199254740993`)),
check("1.50 keeps its trailing zero", strings.Contains(result, `"price": 1.50`)),
check("1e5 keeps its exponent", strings.Contains(result, `"ratio": 1e5`)),
})
}
func TestJsonToMarkdown_KeepsNumbersAsWrittenAcrossChunks(t *testing.T) {
// Large enough to take the recursive split path.
items := make([]string, 0, 60)
for i := 0; i < 60; i++ {
item := fmt.Sprintf(`"item_%02d": {"id": 1234567890123456789%d, "label": "entry %d"}`, i, i%10, i)
items = append(items, item)
}
input := "{" + strings.Join(items, ", ") + "}"
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Numbers keep their digits in a split document", input, result, err, []checkResult{
check("no error", err == nil),
check("split into several blocks", len(splitBlocks(result)) > 1),
check("first id kept", strings.Contains(result, `"id": 12345678901234567890`)),
check("last id kept", strings.Contains(result, `"id": 12345678901234567899`)),
})
}
func TestJsonToMarkdown_KeepsAngleBracketsAndAmpersands(t *testing.T) {
// json.Marshal writes <, > and & as \u003c, \u003e and \u0026.
input := `{"note": "a < b && c > d", "html": "<b>bold</b>"}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "<, > and & stay readable", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("comparison text kept", strings.Contains(result, `"note": "a < b && c > d"`)),
check("markup kept", strings.Contains(result, `"html": "<b>bold</b>"`)),
check("no \\u003c escapes", !strings.Contains(result, `\u003c`)),
})
}
func TestJsonToMarkdown_NullValues(t *testing.T) {
input := `{"name": "test", "value": null, "list": [null, 1, null]}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Object with null values", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains 'null'", strings.Contains(result, "null")),
})
}
func TestJsonToMarkdown_MixedValueTypes(t *testing.T) {
input := `{"str": "hello", "num": 42, "float": 3.14, "bool": true, "null_val": null, "arr": [1,2], "obj": {"a":1}}`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Mixed value types in one object", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains string", strings.Contains(result, "hello")),
check("contains number", strings.Contains(result, "42")),
check("contains float", strings.Contains(result, "3.14")),
})
}
func TestJsonToMarkdown_NestedArrayOfArrays(t *testing.T) {
input := `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Nested Array of Arrays (matrix)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
})
}
func TestJsonToMarkdown_LargePrimitiveString(t *testing.T) {
bigStr := strings.Repeat("abcdefghij", 300)
input := fmt.Sprintf(`"%s"`, bigStr)
result, err := jsonToMarkdown([]byte(input))
visualReport(t, "Large Primitive String (3000 chars) → fallback", input, result, err, []checkResult{
check("no error", err == nil),
check("content preserved", strings.Contains(result, "abcdefghij")),
})
}
func TestJsonToMarkdown_SingleKeyObject(t *testing.T) {
input := `{"only_key": "only_value"}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Single-Key Object", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_SingleElementArray(t *testing.T) {
input := `[{"id": 1, "name": "solo"}]`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Single-Element Array", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("exactly 1 block (got %d)", blocks), blocks == 1),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 5: Realistic Scenarios
// ═══════════════════════════════════════════════════════════════════════════
func TestJsonToMarkdown_RealisticConfig(t *testing.T) {
input := `{
"app": {"name": "Academy", "version": "2.0.0", "debug": false},
"database": {"host": "localhost", "port": 5432, "name": "academy_db", "pool_size": 10},
"redis": {"host": "localhost", "port": 6379},
"features": {"json_upload": true, "multimodel": true, "graph_extraction": false}
}`
result, err := jsonToMarkdown([]byte(input))
blocks := strings.Count(result, "```json")
visualReport(t, "Realistic: App Config (fits in 1 block)", input, result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains 'Academy'", strings.Contains(result, "Academy")),
check("contains 'database'", strings.Contains(result, "database")),
check(fmt.Sprintf("single block (fits, got %d)", blocks), blocks == 1),
})
}
func TestJsonToMarkdown_RealisticAPIResponse(t *testing.T) {
users := make([]interface{}, 40)
for i := range users {
users[i] = map[string]interface{}{
"id": i + 1,
"username": fmt.Sprintf("user_%03d", i+1),
"email": fmt.Sprintf("user%03d@example.com", i+1),
"role": "editor",
"active": i%3 != 0,
}
}
apiResp := map[string]interface{}{
"status": "ok",
"total": 40,
"page": 1,
"data": users,
}
data, _ := json.Marshal(apiResp)
result, err := jsonToMarkdown(data)
blocks := strings.Count(result, "```json")
visualReport(t, "Realistic: API Response (40 user records)", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check("contains user data", strings.Contains(result, "user_001")),
check(fmt.Sprintf("multiple blocks (got %d)", blocks), blocks >= 2),
})
}
func TestJsonToMarkdown_RealisticLargeNestedConfig(t *testing.T) {
// A config where one section is huge and must be recursively split,
// while other sections are small
rules := make(map[string]interface{})
for i := 0; i < 30; i++ {
rules[fmt.Sprintf("rule_%02d", i)] = map[string]interface{}{
"pattern": strings.Repeat("pattern", 10),
"action": "allow",
"priority": i,
}
}
config := map[string]interface{}{
"version": "3.0",
"metadata": map[string]interface{}{"author": "admin", "updated": "2026-03-24"},
"firewall": map[string]interface{}{
"enabled": true,
"rules": rules,
},
}
data, _ := json.Marshal(config)
result, err := jsonToMarkdown(data)
blocks := splitBlocks(result)
// Each block should still have the path "firewall" → "rules" where applicable
visualReport(t, "Realistic: Nested config with 30 firewall rules", string(data), result, err, []checkResult{
check("no error", err == nil),
check("all blocks are valid JSON", allBlocksValidJSON(result)),
check(fmt.Sprintf("multiple blocks needed (got %d)", len(blocks)), len(blocks) >= 2),
check("contains 'firewall'", strings.Contains(result, "firewall")),
check("contains 'version'", strings.Contains(result, "version")),
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 6: Integration — SimpleFormatReader
// ═══════════════════════════════════════════════════════════════════════════
func TestSimpleFormatReader_JSON(t *testing.T) {
reader := &SimpleFormatReader{}
input := `{"test": "integration", "count": 42}`
req := &types.ReadRequest{
FileName: "config.json",
FileType: "json",
FileContent: []byte(input),
}
result, err := reader.Read(context.Background(), req)
var resultStr string
if result != nil {
resultStr = result.MarkdownContent
}
visualReport(t, "SimpleFormatReader.Read() with .json file", input, resultStr, err, []checkResult{
check("no error", err == nil),
check("result not nil", result != nil),
check("markdown contains 'test'",
result != nil && strings.Contains(result.MarkdownContent, "test")),
check("markdown has code block",
result != nil && strings.Contains(result.MarkdownContent, "```json")),
check("output is valid JSON inside block",
result != nil && allBlocksValidJSON(result.MarkdownContent)),
})
}
func TestSimpleFormatReader_JSON_Invalid(t *testing.T) {
reader := &SimpleFormatReader{}
req := &types.ReadRequest{
FileName: "bad.json",
FileType: "json",
FileContent: []byte(`{not valid json}`),
}
_, err := reader.Read(context.Background(), req)
visualReport(t, "SimpleFormatReader with invalid JSON → error", `{not valid json}`, "", err, []checkResult{
check("returns error", err != nil),
check("error mentions 'json'",
err != nil && strings.Contains(strings.ToLower(err.Error()), "json")),
})
}
func TestValidateJSONContent(t *testing.T) {
tests := []struct {
name string
data string
wantErr string
}{
{name: "object", data: `{"a":1}`},
{name: "array", data: `[1,2]`},
{name: "bom object", data: "\ufeff{\"a\":1}"},
{name: "empty", data: "", wantErr: "empty JSON content"},
{name: "jsonc", data: "{\n// x\n}", wantErr: "invalid JSON content"},
{name: "truncated", data: `{"a":`, wantErr: "invalid JSON content"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateJSONContent([]byte(tt.data))
if tt.wantErr == "" {
if err != nil {
t.Fatalf("ValidateJSONContent() err = %v", err)
}
return
}
if err == nil || err.Error() != tt.wantErr {
t.Fatalf("ValidateJSONContent() err = %v, want %q", err, tt.wantErr)
}
})
}
}
func TestIsSimpleFormat_JSON(t *testing.T) {
cases := []struct {
input string
want bool
}{
{"json", true}, {"JSON", true}, {".json", true}, {"Json", true},
{"txt", true}, {"csv", true},
{"pdf", false}, {"docx", false},
}
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: IsSimpleFormat() recognizes JSON")
t.Logf("─────────────────────────────────────────────────────────")
allPass := true
for _, tc := range cases {
got := IsSimpleFormat(tc.input)
icon := "✅"
if got != tc.want {
icon = "💥"
allPass = false
t.Errorf("IsSimpleFormat(%q) = %v, want %v", tc.input, got, tc.want)
}
t.Logf("%s IsSimpleFormat(%q) = %v (want %v)", icon, tc.input, got, tc.want)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
// ═══════════════════════════════════════════════════════════════════════════
// Group 7: list-to-dict preprocessing
// ═══════════════════════════════════════════════════════════════════════════
func TestListToDictPreprocess(t *testing.T) {
// Simulate what json.Unmarshal produces: numbers become float64
input := []interface{}{"a", "b", map[string]interface{}{"nested": []interface{}{float64(1), float64(2)}}}
result := listToDictPreprocess(input)
dict, ok := result.(map[string]interface{})
if !ok {
t.Fatalf("expected map, got %T", result)
}
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: listToDictPreprocess")
t.Logf("─────────────────────────────────────────────────────────")
t.Logf("📥 INPUT: [\"a\", \"b\", {\"nested\": [1, 2]}]")
t.Logf("📤 OUTPUT: %s", formatValue(dict))
t.Logf("─────────────────────────────────────────────────────────")
checks := []checkResult{
check("top level is dict", ok),
check(`key "0" = "a"`, dict["0"] == "a"),
check(`key "1" = "b"`, dict["1"] == "b"),
}
// Check nested array also converted
if nested, ok2 := dict["2"].(map[string]interface{}); ok2 {
if innerNested, ok3 := nested["nested"].(map[string]interface{}); ok3 {
checks = append(checks, check(`nested array converted to dict`, innerNested["0"] == float64(1)))
} else {
checks = append(checks, check(`nested array converted to dict`, false))
}
}
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
t.Errorf("FAIL: %s", c.desc)
}
t.Logf("%s %s", icon, c.desc)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
func TestSetNestedDict(t *testing.T) {
d := map[string]interface{}{}
setNestedDict(d, []string{"config", "database", "host"}, "localhost")
t.Logf("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
t.Logf("📋 TEST: setNestedDict path preservation")
t.Logf("─────────────────────────────────────────────────────────")
t.Logf("📥 path: [\"config\", \"database\", \"host\"]")
t.Logf("📥 value: \"localhost\"")
t.Logf("📤 result: %s", formatValue(d))
t.Logf("─────────────────────────────────────────────────────────")
// Verify the structure
config, ok1 := d["config"].(map[string]interface{})
db, ok2 := map[string]interface{}{}, false
host := ""
if ok1 {
db, ok2 = config["database"].(map[string]interface{})
}
if ok2 {
host, _ = db["host"].(string)
}
checks := []checkResult{
check(`d["config"] is dict`, ok1),
check(`d["config"]["database"] is dict`, ok2),
check(`d["config"]["database"]["host"] = "localhost"`, host == "localhost"),
}
allPass := true
for _, c := range checks {
icon := "✅"
if !c.pass {
icon = "💥"
allPass = false
t.Errorf("FAIL: %s", c.desc)
}
t.Logf("%s %s", icon, c.desc)
}
if allPass {
t.Logf("🎉 ALL CHECKS PASSED")
}
t.Logf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")
}
@@ -0,0 +1,290 @@
package docparser
import (
"strings"
"academy/internal/types"
)
type markdownImageTargetSpan struct {
ImageStart int
TargetStart int
TargetEnd int
}
func scanMarkdownImageTargets(markdown string) []markdownImageTargetSpan {
var spans []markdownImageTargetSpan
for i := 0; i+1 < len(markdown); i++ {
if markdown[i] != '!' || markdown[i+1] != '[' || isEscaped(markdown, i) {
continue
}
altEnd := findMarkdownImageAltEnd(markdown, i+2)
if altEnd == -1 {
continue
}
targetStart := altEnd + 2
targetEnd, ok := findMarkdownImageTargetEnd(markdown, targetStart)
if !ok {
i = altEnd
continue
}
spans = append(spans, markdownImageTargetSpan{
ImageStart: i,
TargetStart: targetStart,
TargetEnd: targetEnd,
})
i = targetEnd
}
return spans
}
// StripMarkdownImages removes complete ![alt](destination) constructs,
// including destinations and titles that contain parentheses. Leftover
// prose is preserved so callers can tell whether a chunk still has
// extractable text after image placeholders are gone.
func StripMarkdownImages(markdown string) string {
spans := scanMarkdownImageTargets(markdown)
if len(spans) == 0 {
return markdown
}
var b strings.Builder
b.Grow(len(markdown))
last := 0
for _, span := range spans {
if span.ImageStart < last {
continue
}
b.WriteString(markdown[last:span.ImageStart])
last = span.TargetEnd + 1
if last > len(markdown) {
last = len(markdown)
}
}
b.WriteString(markdown[last:])
return b.String()
}
func findMarkdownImageAltEnd(markdown string, start int) int {
for i := start; i+1 < len(markdown); i++ {
if markdown[i] == ']' && markdown[i+1] == '(' && !isEscaped(markdown, i) {
return i
}
}
return -1
}
func findMarkdownImageTargetEnd(markdown string, start int) (int, bool) {
parenDepth := 1
inAngleDestination := false
seenNonSpace := false
var inQuote byte
for i := start; i < len(markdown); i++ {
ch := markdown[i]
if ch == '\\' {
i++
continue
}
if !seenNonSpace && !isMarkdownSpace(ch) {
seenNonSpace = true
if ch == '<' {
inAngleDestination = true
continue
}
}
if inAngleDestination {
if ch == '>' {
inAngleDestination = false
}
continue
}
if inQuote != 0 {
if ch == inQuote {
inQuote = 0
}
continue
}
if (ch == '"' || ch == '\'') && i > start && isMarkdownSpace(markdown[i-1]) {
inQuote = ch
continue
}
switch ch {
case '(':
parenDepth++
case ')':
parenDepth--
if parenDepth == 0 {
return i, true
}
}
}
return 0, false
}
func splitMarkdownImageTarget(
raw string,
refMap map[string]types.ImageRef,
) (path string, pathStart int, pathEnd int, ok bool) {
start, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if start >= end {
return "", 0, 0, false
}
trimmed := raw[start:end]
if _, found := refMap[trimmed]; found {
return trimmed, start, end, true
}
if raw[start] == '<' {
return splitAngleMarkdownImageTarget(raw, start, end, refMap)
}
titleStart, found := parseMarkdownImageTitleSuffix(trimmed)
if !found {
return "", 0, 0, false
}
pathEnd = start + titleStart
for pathEnd > start && isMarkdownSpace(raw[pathEnd-1]) {
pathEnd--
}
if pathEnd == start {
return "", 0, 0, false
}
path = raw[start:pathEnd]
if _, found := refMap[path]; !found {
return "", 0, 0, false
}
return path, start, pathEnd, true
}
func splitAngleMarkdownImageTarget(
raw string,
start int,
end int,
refMap map[string]types.ImageRef,
) (path string, pathStart int, pathEnd int, ok bool) {
closeIdx := -1
for i := start + 1; i < end; i++ {
if raw[i] == '>' && !isEscaped(raw, i) {
closeIdx = i
break
}
}
if closeIdx == -1 {
return "", 0, 0, false
}
path = raw[start+1 : closeIdx]
if _, found := refMap[path]; !found {
return "", 0, 0, false
}
if !isEmptyOrMarkdownImageTitleSuffix(raw[closeIdx+1 : end]) {
return "", 0, 0, false
}
return path, start + 1, closeIdx, true
}
func parseMarkdownImageTitleSuffix(raw string) (titleStart int, ok bool) {
_, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if end == 0 {
return 0, false
}
switch raw[end-1] {
case '"', '\'':
quote := raw[end-1]
for i := end - 2; i >= 0; i-- {
if raw[i] != quote || isEscaped(raw, i) {
continue
}
if i == 0 || !isMarkdownSpace(raw[i-1]) {
return 0, false
}
if markdownTitleHasBlankLine(raw[i+1 : end-1]) {
return 0, false
}
return i, true
}
case ')':
depth := 0
for i := end - 2; i >= 0; i-- {
if isEscaped(raw, i) {
continue
}
switch raw[i] {
case ')':
depth++
case '(':
if depth == 0 {
if i == 0 || !isMarkdownSpace(raw[i-1]) {
return 0, false
}
if markdownTitleHasBlankLine(raw[i+1 : end-1]) {
return 0, false
}
return i, true
}
depth--
}
}
}
return 0, false
}
func isEmptyOrMarkdownImageTitleSuffix(raw string) bool {
start, end := trimMarkdownSpaceBounds(raw, 0, len(raw))
if start == end {
return true
}
titleStart, ok := parseMarkdownImageTitleSuffix(raw[:end])
return ok && isAllMarkdownSpace(raw[:titleStart])
}
func markdownTitleHasBlankLine(title string) bool {
for _, line := range strings.Split(title, "\n") {
if strings.Trim(line, " \t") == "" {
return true
}
}
return false
}
func isAllMarkdownSpace(raw string) bool {
for i := 0; i < len(raw); i++ {
if !isMarkdownSpace(raw[i]) {
return false
}
}
return true
}
func trimMarkdownSpaceBounds(raw string, start int, end int) (int, int) {
for start < end && isMarkdownSpace(raw[start]) {
start++
}
for end > start && isMarkdownSpace(raw[end-1]) {
end--
}
return start, end
}
func isMarkdownSpace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
func isEscaped(s string, pos int) bool {
backslashes := 0
for i := pos - 1; i >= 0 && s[i] == '\\'; i-- {
backslashes++
}
return backslashes%2 == 1
}
@@ -0,0 +1,239 @@
package docparser
import (
"strings"
"testing"
"academy/internal/types"
)
func TestScanMarkdownImageTargets(t *testing.T) {
tests := []struct {
name string
input string
targets []string
}{
{
name: "without title",
input: `before ![a](images/a.png) after`,
targets: []string{`images/a.png`},
},
{
name: "double quoted title",
input: `![a](images/a.png "图")`,
targets: []string{`images/a.png "图"`},
},
{
name: "single quoted title",
input: `![a](images/a.png '图')`,
targets: []string{`images/a.png '图'`},
},
{
name: "parenthesized title",
input: `![a](images/a.png (图))`,
targets: []string{`images/a.png (图)`},
},
{
name: "title containing right paren",
input: `![a](images/a.png "阶段 1) 结果")`,
targets: []string{`images/a.png "阶段 1) 结果"`},
},
{
name: "title containing both parens",
input: `![a](images/a.png '阶段 (1) 结果')`,
targets: []string{`images/a.png '阶段 (1) 结果'`},
},
{
name: "escaped quote in title",
input: `![a](images/a.png "阶段 \"1\"")`,
targets: []string{`images/a.png "阶段 \"1\""`},
},
{
name: "multiline title",
input: "![a](images/a.png\n \"多行 title\")",
targets: []string{"images/a.png\n \"多行 title\""},
},
{
name: "spaced path",
input: `![a](images/第 1 页.png)`,
targets: []string{`images/第 1 页.png`},
},
{
name: "path containing balanced parens",
input: `![a](images/a_(1).png "title")`,
targets: []string{`images/a_(1).png "title"`},
},
{
name: "angle destination",
input: `![a](<images/a b.png> "title")`,
targets: []string{`<images/a b.png> "title"`},
},
{
name: "malformed image is skipped",
input: `![a](images/a.png "unterminated title) after ![b](images/b.png)`,
targets: []string{`images/b.png`},
},
{
name: "escaped image marker is skipped",
input: `\![a](images/a.png) ![b](images/b.png)`,
targets: []string{`images/b.png`},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spans := scanMarkdownImageTargets(tt.input)
if len(spans) != len(tt.targets) {
t.Fatalf("got %d spans, want %d: %#v", len(spans), len(tt.targets), spans)
}
for i, span := range spans {
got := tt.input[span.TargetStart:span.TargetEnd]
if got != tt.targets[i] {
t.Fatalf("target %d = %q, want %q", i, got, tt.targets[i])
}
}
})
}
}
func TestSplitMarkdownImageTarget(t *testing.T) {
refMap := map[string]types.ImageRef{
"images/a.png": {OriginalRef: "images/a.png"},
"images/第 1 页.png": {OriginalRef: "images/第 1 页.png"},
"images/a_(1).png": {OriginalRef: "images/a_(1).png"},
"images/第 1 页 (测试).gif": {OriginalRef: "images/第 1 页 (测试).gif"},
}
tests := []struct {
name string
raw string
wantPath string
wantText string
wantOK bool
}{
{
name: "without title",
raw: `images/a.png`,
wantPath: `images/a.png`,
wantText: `local://stored`,
wantOK: true,
},
{
name: "double quoted title",
raw: `images/a.png "图"`,
wantPath: `images/a.png`,
wantText: `local://stored "图"`,
wantOK: true,
},
{
name: "single quoted title",
raw: `images/a.png '图'`,
wantPath: `images/a.png`,
wantText: `local://stored '图'`,
wantOK: true,
},
{
name: "parenthesized title",
raw: `images/a.png (阶段 (1) 结果)`,
wantPath: `images/a.png`,
wantText: `local://stored (阶段 (1) 结果)`,
wantOK: true,
},
{
name: "multiline title",
raw: "images/a.png\n \"多行 title\"",
wantPath: `images/a.png`,
wantText: "local://stored\n \"多行 title\"",
wantOK: true,
},
{
name: "path with spaces wins without title",
raw: `images/第 1 页.png`,
wantPath: `images/第 1 页.png`,
wantText: `local://stored`,
wantOK: true,
},
{
name: "path with balanced parens",
raw: `images/a_(1).png "title"`,
wantPath: `images/a_(1).png`,
wantText: `local://stored "title"`,
wantOK: true,
},
{
name: "angle destination replaces only inner path",
raw: `<images/第 1 页 (测试).gif> "阶段 1) 图片"`,
wantPath: `images/第 1 页 (测试).gif`,
wantText: `<local://stored> "阶段 1) 图片"`,
wantOK: true,
},
{
name: "unknown reference",
raw: `images/missing.png "title"`,
wantOK: false,
},
{
name: "blank line in title is invalid",
raw: "images/a.png \"line1\n\nline2\"",
wantOK: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path, pathStart, pathEnd, ok := splitMarkdownImageTarget(tt.raw, refMap)
if ok != tt.wantOK {
t.Fatalf("ok = %v, want %v", ok, tt.wantOK)
}
if !ok {
return
}
if path != tt.wantPath {
t.Fatalf("path = %q, want %q", path, tt.wantPath)
}
replaced := tt.raw[:pathStart] + "local://stored" + tt.raw[pathEnd:]
if replaced != tt.wantText {
t.Fatalf("replacement = %q, want %q", replaced, tt.wantText)
}
if strings.Contains(replaced, tt.wantPath) {
t.Fatalf("replacement still contains original path: %q", replaced)
}
})
}
}
func TestStripMarkdownImages(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "simple image",
input: "before ![a](images/a.png) after",
want: "before after",
},
{
name: "title containing right paren",
input: `![a](images/a.png "阶段 1) 结果")`,
want: "",
},
{
name: "prose around image",
input: "See figure: ![fig](resource://x) below.",
want: "See figure: below.",
},
{
name: "escaped image marker is kept",
input: `\![a](images/a.png) kept`,
want: `\![a](images/a.png) kept`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StripMarkdownImages(tt.input); got != tt.want {
t.Fatalf("StripMarkdownImages(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
@@ -0,0 +1,549 @@
package docparser
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"sort"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
"github.com/google/uuid"
)
const (
defaultPollInterval = 3 * time.Second
// defaultCloudTimeout bounds how long one batch is polled;
// ACADEMY_MINERU_CLOUD_TIMEOUT overrides it for documents that take longer.
defaultCloudTimeout = 600 * time.Second
defaultBaseURL = "https://mineru.net/api/v4"
)
// MinerUCloudReader calls the MinerU Cloud API (mineru.net) to read/convert documents.
// Flow: POST /file-urls/batch → PUT file → poll GET /extract-results/batch/{batch_id}.
type MinerUCloudReader struct {
apiKey string
baseURL string
timeout time.Duration
pollInterval time.Duration
model string
formulaEnable bool
tableEnable bool
ocrEnable bool
language string
}
// NewMinerUCloudReader creates a reader from ParserEngineOverrides.
func NewMinerUCloudReader(overrides map[string]string) *MinerUCloudReader {
return &MinerUCloudReader{
apiKey: strings.TrimSpace(overrides["mineru_api_key"]),
baseURL: defaultBaseURL,
timeout: requestTimeoutFromEnv("ACADEMY_MINERU_CLOUD_TIMEOUT", defaultCloudTimeout),
pollInterval: defaultPollInterval,
model: stringOr(overrides["mineru_cloud_model"], "pipeline"),
formulaEnable: parseBoolOr(overrides["mineru_cloud_enable_formula"], true),
tableEnable: parseBoolOr(overrides["mineru_cloud_enable_table"], true),
ocrEnable: parseBoolOr(overrides["mineru_cloud_enable_ocr"], true),
language: stringOr(overrides["mineru_cloud_language"], "ch"),
}
}
func (c *MinerUCloudReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.apiKey == "" {
return &types.ReadResult{Error: "MinerU Cloud API key is not configured"}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[MinerUCloud] Parsing file=%s size=%d via %s", req.FileName, len(content), c.baseURL)
ext := filepath.Ext(req.FileName)
if ext == "" && req.FileType != "" {
ext = "." + req.FileType
}
if ext == "" {
ext = ".pdf"
}
fileName := strings.TrimSuffix(req.FileName, ext) + ext
if fileName == ext {
fileName = "document" + ext
}
batchID, uploadURL, err := c.applyUploadURLs(ctx, fileName, ext)
if err != nil {
return nil, fmt.Errorf("MinerU Cloud apply upload URLs: %w", err)
}
if err := c.uploadFile(ctx, uploadURL, content); err != nil {
return nil, fmt.Errorf("MinerU Cloud file upload: %w", err)
}
mdContent, imageRefs, contentList, err := c.pollBatchResult(ctx, batchID)
if err != nil {
return nil, fmt.Errorf("MinerU Cloud poll: %w", err)
}
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
// --- batch upload API ---
type batchApplyResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
BatchID string `json:"batch_id"`
FileURLs []string `json:"file_urls"`
} `json:"data"`
}
func (c *MinerUCloudReader) applyUploadURLs(ctx context.Context, fileName, ext string) (string, string, error) {
modelVersion := c.model
if strings.ToLower(ext) == ".html" {
modelVersion = "MinerU-HTML"
}
payload := map[string]interface{}{
"files": []map[string]string{{"name": fileName, "data_id": uuid.New().String()}},
"model_version": modelVersion,
"is_ocr": c.ocrEnable,
"enable_formula": c.formulaEnable,
"enable_table": c.tableEnable,
"language": c.language,
}
body, err := json.Marshal(payload)
if err != nil {
return "", "", fmt.Errorf("marshal payload: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/file-urls/batch", bytes.NewReader(body))
if err != nil {
return "", "", fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
httpReq.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return "", "", fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return "", "", fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody))
}
var result batchApplyResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", "", fmt.Errorf("decode response: %w", err)
}
if result.Code != 0 {
return "", "", fmt.Errorf("API error: %s", result.Msg)
}
if len(result.Data.FileURLs) == 0 {
return "", "", fmt.Errorf("API returned no file_urls")
}
logger.Infof(context.Background(), "[MinerUCloud] batch apply ok: batch_id=%s, urls=%d", result.Data.BatchID, len(result.Data.FileURLs))
return result.Data.BatchID, result.Data.FileURLs[0], nil
}
func (c *MinerUCloudReader) uploadFile(ctx context.Context, uploadURL string, content []byte) error {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(content))
if err != nil {
return fmt.Errorf("create PUT request: %w", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return fmt.Errorf("PUT upload: %w", err)
}
resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("PUT upload status %d", resp.StatusCode)
}
logger.Infof(context.Background(), "[MinerUCloud] file uploaded, status=%d", resp.StatusCode)
return nil
}
// --- polling ---
type batchPollResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
ExtractResult json.RawMessage `json:"extract_result"` // can be object or array
} `json:"data"`
}
type extractResultItem struct {
State string `json:"state"`
FileName string `json:"file_name"`
Markdown string `json:"markdown"`
Content string `json:"content"`
Text string `json:"text"`
ErrMsg string `json:"err_msg"`
Progress struct {
ExtractedPages int `json:"extracted_pages"`
TotalPages int `json:"total_pages"`
} `json:"extract_progress"`
FullZipURL string `json:"full_zip_url"`
}
func (c *MinerUCloudReader) pollBatchResult(
ctx context.Context, batchID string,
) (string, []types.ImageRef, []byte, error) {
deadline := time.Now().Add(c.timeout)
pollCount := 0
headers := map[string]string{
"Authorization": "Bearer " + c.apiKey,
}
for time.Now().Before(deadline) {
// Bail out promptly on caller cancellation instead of spinning:
// fetchBatchStatus fails immediately and sleepCtx returns at once on a
// cancelled ctx, so without this guard the loop busy-hammers the cloud
// API and floods logs until the deadline.
if err := ctx.Err(); err != nil {
return "", nil, nil, err
}
pollCount++
items, err := c.fetchBatchStatus(ctx, batchID, headers)
if err != nil {
logger.Errorf(context.Background(), "[MinerUCloud] poll #%d failed: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
if len(items) == 0 {
if pollCount <= 3 || pollCount%10 == 0 {
logger.Infof(context.Background(), "[MinerUCloud] poll #%d: extract_result empty, retrying", pollCount)
}
sleepCtx(ctx, c.pollInterval)
continue
}
item := items[0]
state := strings.ToLower(item.State)
if pollCount == 1 || pollCount%10 == 0 || state == "done" || state == "failed" {
logger.Infof(context.Background(), "[MinerUCloud] poll #%d: file=%s state=%s pages=%d/%d",
pollCount, item.FileName, state, item.Progress.ExtractedPages, item.Progress.TotalPages)
}
if state == "failed" {
return "", nil, nil, fmt.Errorf("MinerU Cloud task failed: %s", item.ErrMsg)
}
if state == "done" {
return c.extractDoneResult(ctx, &item)
}
sleepCtx(ctx, c.pollInterval)
}
return "", nil, nil, fmt.Errorf("MinerU Cloud task timed out after %s (%d polls)", c.timeout, pollCount)
}
func (c *MinerUCloudReader) fetchBatchStatus(ctx context.Context, batchID string, headers map[string]string) ([]extractResultItem, error) {
url := fmt.Sprintf("%s/extract-results/batch/%s", c.baseURL, batchID)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
httpReq.Header.Set(k, v)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read poll response body: %w", err)
}
var pollResp batchPollResponse
if err := json.Unmarshal(respBody, &pollResp); err != nil {
return nil, fmt.Errorf("decode poll response: %w", err)
}
if pollResp.Code != 0 {
return nil, fmt.Errorf("poll error code=%d msg=%s", pollResp.Code, pollResp.Msg)
}
if len(pollResp.Data.ExtractResult) == 0 {
return nil, nil
}
// Dump the raw extract_result JSON for debugging
rawExtract := string(pollResp.Data.ExtractResult)
if len(rawExtract) > 4000 {
logger.Infof(context.Background(), "[MinerUCloud] Raw extract_result (truncated to 4000 chars): %s ...", rawExtract[:4000])
} else {
logger.Infof(context.Background(), "[MinerUCloud] Raw extract_result: %s", rawExtract)
}
// Pretty-print the structure to reveal all available fields
var rawObj interface{}
if err := json.Unmarshal(pollResp.Data.ExtractResult, &rawObj); err == nil {
logResponseStructure("MinerUCloud", rawObj, "extract_result")
}
// The extract_result can be either a single object or an array
var items []extractResultItem
if pollResp.Data.ExtractResult[0] == '[' {
if err := json.Unmarshal(pollResp.Data.ExtractResult, &items); err != nil {
return nil, fmt.Errorf("decode extract_result array: %w", err)
}
} else {
var single extractResultItem
if err := json.Unmarshal(pollResp.Data.ExtractResult, &single); err != nil {
return nil, fmt.Errorf("decode extract_result object: %w", err)
}
items = []extractResultItem{single}
}
return items, nil
}
// extractDoneResult extracts markdown and images from a completed batch item.
// Prefers inline markdown/content fields; falls back to downloading full_zip_url.
func (c *MinerUCloudReader) extractDoneResult(
_ context.Context, item *extractResultItem,
) (string, []types.ImageRef, []byte, error) {
text := firstNonEmpty(item.Markdown, item.Content, item.Text)
if text != "" {
logger.Infof(context.Background(), "[MinerUCloud] parsed (inline), length=%d", len(text))
return text, nil, nil, nil
}
if item.FullZipURL == "" {
return "", nil, nil, fmt.Errorf("MinerU Cloud state=done but no markdown/content or full_zip_url")
}
md, imageRefs, contentList, err := downloadAndExtractZip(item.FullZipURL)
if err != nil {
return "", nil, nil, fmt.Errorf("extract zip: %w", err)
}
logger.Infof(context.Background(), "[MinerUCloud] parsed (zip), markdown=%d chars, images=%d", len(md), len(imageRefs))
return md, imageRefs, contentList, nil
}
// --- ZIP handling ---
// downloadAndExtractZip also returns the content_list of the package, if any.
func downloadAndExtractZip(zipURL string) (string, []types.ImageRef, []byte, error) {
if err := utils.ValidateURLForSSRF(zipURL); err != nil {
return "", nil, nil, fmt.Errorf("zip URL blocked by SSRF check: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Get(zipURL)
if err != nil {
return "", nil, nil, fmt.Errorf("download zip: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("download zip status %d", resp.StatusCode)
}
zipData, err := readResultPackage(resp.Body, maxResultPackageBytes)
if err != nil {
return "", nil, nil, fmt.Errorf("read zip body: %w", err)
}
md, imageRefs, err := extractMarkdownZip(zipData, "MinerUCloud")
if err != nil {
return "", nil, nil, err
}
return md, imageRefs, minerUContentListFromZip(zipData), nil
}
// extractMarkdownZip reads the shallowest .md file of a MinerU result package
// and the images it references, via markdown or inline HTML <img> syntax.
func extractMarkdownZip(zipData []byte, logLabel string) (string, []types.ImageRef, error) {
return extractMarkdownZipBounded(zipData, logLabel, maxZipImagesTotalBytes)
}
// extractMarkdownZipBounded is extractMarkdownZip with the accumulated-image
// budget as a parameter, so a test can exercise the limit without materialising
// the production figure.
func extractMarkdownZipBounded(zipData []byte, logLabel string, maxImages int64) (string, []types.ImageRef, error) {
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err != nil {
return "", nil, fmt.Errorf("open zip: %w", err)
}
// Find .md files
var mdFiles []string
entries := make(map[string]*zip.File)
for _, f := range zr.File {
entries[f.Name] = f
if strings.HasSuffix(f.Name, ".md") {
mdFiles = append(mdFiles, f.Name)
}
}
if len(mdFiles) == 0 {
return "", nil, fmt.Errorf("no .md file found in zip")
}
sort.Slice(mdFiles, func(i, j int) bool {
di, dj := strings.Count(mdFiles[i], "/"), strings.Count(mdFiles[j], "/")
if di != dj {
return di < dj
}
return mdFiles[i] < mdFiles[j]
})
mdText, err := readZipEntry(entries[mdFiles[0]])
if err != nil {
return "", nil, fmt.Errorf("read md file: %w", err)
}
mdDir := filepath.Dir(mdFiles[0])
// Extract referenced images
var imageRefs []types.ImageRef
// Every image below is kept in memory until the caller hands the slice on,
// so the package needs a total budget as well as a per-entry cap: a package
// of thousands of small entries expands without ever tripping the latter.
var imageBytes int64
seen := map[string]bool{}
for _, imgPath := range extractImageRefsFromContent(mdText) {
if strings.HasPrefix(imgPath, "http://") || strings.HasPrefix(imgPath, "https://") || strings.HasPrefix(imgPath, "data:") {
continue
}
if seen[imgPath] {
continue
}
seen[imgPath] = true
resolved := resolveInZip(imgPath, mdDir, entries)
if resolved == nil {
logger.Errorf(context.Background(), "[%s] image not found in zip: %s", logLabel, imgPath)
continue
}
imgData, err := readZipEntryBytes(resolved)
if err != nil {
logger.Errorf(context.Background(), "[%s] failed to read zip image %s: %v", logLabel, imgPath, err)
continue
}
if imageBytes+int64(len(imgData)) > maxImages {
return "", nil, fmt.Errorf("%w: images in %q exceed %d bytes",
errResultPackageTooLarge, logLabel, maxImages)
}
imageBytes += int64(len(imgData))
ext := strings.ToLower(filepath.Ext(resolved.Name))
if ext == "" {
ext = ".png"
}
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
mimeType = "image/png"
}
imageRefs = append(imageRefs, types.ImageRef{
Filename: filepath.Base(resolved.Name),
OriginalRef: imgPath,
MimeType: mimeType,
ImageData: imgData,
})
}
return mdText, imageRefs, nil
}
func resolveInZip(imgPath, mdDir string, entries map[string]*zip.File) *zip.File {
candidates := []string{strings.ReplaceAll(imgPath, "\\", "/")}
if decoded, err := url.PathUnescape(candidates[0]); err == nil && decoded != candidates[0] {
candidates = append(candidates, decoded)
}
for _, c := range candidates {
c = strings.TrimPrefix(c, "./")
if f, ok := entries[c]; ok {
return f
}
if mdDir != "" && mdDir != "." {
if f, ok := entries[mdDir+"/"+c]; ok {
return f
}
}
}
return nil
}
// readZipEntry reads a text entry (the package markdown) under the per-entry cap.
func readZipEntry(f *zip.File) (string, error) {
data, err := readZipEntryCapped(f, maxZipEntryBytes)
if err != nil {
return "", err
}
return string(data), nil
}
// readZipEntryBytes reads a binary entry (an extracted image) under the
// per-entry cap.
func readZipEntryBytes(f *zip.File) ([]byte, error) {
return readZipEntryCapped(f, maxZipEntryBytes)
}
// PingMinerUCloud checks if the MinerU Cloud API is reachable with the given API key.
func PingMinerUCloud(apiKey string) (bool, string) {
apiKey = strings.TrimSpace(apiKey)
if apiKey == "" {
return false, "未配置 MinerU Cloud API Key"
}
targetURL := defaultBaseURL + "/file-urls/batch"
payload := []byte(`{"files":[],"model_version":"pipeline"}`)
req, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewReader(payload))
if err != nil {
return false, fmt.Sprintf("构建请求失败: %v", err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 10 * time.Second,
MaxRedirects: 5,
})
resp, err := client.Do(req)
if err != nil {
return false, fmt.Sprintf("MinerU Cloud 不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return false, "MinerU Cloud API Key 无效"
}
return true, ""
}
@@ -0,0 +1,582 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
)
// defaultMinerUTimeout bounds one self-hosted parse; ACADEMY_MINERU_TIMEOUT
// overrides it for documents that take longer.
const defaultMinerUTimeout = 1000 * time.Second // large docs can take a while
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.
// MinerU >= 4.0 is driven through the V1 API; older servers through the
// legacy /file_parse endpoint. The protocol is detected per request, so an
// in-place MinerU upgrade needs no configuration change.
type MinerUReader struct {
endpoint string
timeout time.Duration
apiKey string // V1 only: the server's --api-key
tier string // V1 only: flash, basic, standard, advanced; "" = server default
// Legacy (<= 3.x) only; MinerU 4.0 dropped these request parameters.
backend string // "pipeline", "vlm-*", "hybrid-*"
vlmServerURL string // vLLM server URL for vlm-http-client / hybrid-http-client
formulaEnable bool
tableEnable bool
language string
// Shared: legacy parse_method / V1 ocr_mode take the same values.
parseMethod string
}
// NewMinerUReader creates a reader from ParserEngineOverrides.
func NewMinerUReader(overrides map[string]string) *MinerUReader {
var legacyOCREnabled *bool
if raw, ok := overrides["mineru_enable_ocr"]; ok {
value := parseBoolOr(raw, true)
legacyOCREnabled = &value
}
c := &MinerUReader{
endpoint: strings.TrimRight(overrides["mineru_endpoint"], "/"),
timeout: requestTimeoutFromEnv("ACADEMY_MINERU_TIMEOUT", defaultMinerUTimeout),
apiKey: strings.TrimSpace(overrides["mineru_server_api_key"]),
tier: resolveMinerUTier(overrides["mineru_tier"]),
backend: stringOr(overrides["mineru_model"], "pipeline"),
vlmServerURL: overrides["mineru_vlm_server_url"],
formulaEnable: parseBoolOr(overrides["mineru_enable_formula"], true),
tableEnable: parseBoolOr(overrides["mineru_enable_table"], true),
parseMethod: types.ResolveMinerUParseMethod(overrides["mineru_parse_method"], legacyOCREnabled),
language: stringOr(overrides["mineru_language"], "ch"),
}
return c
}
// resolveMinerUTier keeps only tiers MinerU 4.0 understands; anything else
// falls back to the server's default selection.
func resolveMinerUTier(raw string) string {
tier := strings.ToLower(strings.TrimSpace(raw))
if _, ok := mineruV1Tiers[tier]; ok {
return tier
}
return ""
}
func (c *MinerUReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.endpoint == "" {
return &types.ReadResult{Error: "MinerU endpoint is not configured"}, nil
}
if err := validateMinerUOutboundURL(c.endpoint); err != nil {
return &types.ReadResult{Error: err.Error()}, nil
}
if c.vlmServerURL != "" {
if err := validateMinerUOutboundURL(c.vlmServerURL); err != nil {
return &types.ReadResult{Error: err.Error()}, nil
}
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
protocol, err := detectMinerUProtocol(ctx, utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: mineruV1APITimeout,
MaxRedirects: 5,
}), c.endpoint)
if err != nil {
return nil, fmt.Errorf("MinerU protocol detection: %w", err)
}
if protocol == minerUProtocolV1 {
logger.Infof(ctx, "[MinerU] Parsing file=%s size=%d via %s (V1 API)", req.FileName, len(content), c.endpoint)
return c.readV1(ctx, req)
}
logger.Infof(ctx, "[MinerU] Parsing file=%s size=%d via %s (legacy /file_parse)",
req.FileName, len(content), c.endpoint)
mdContent, imagesB64, contentList, err := c.callFileParse(ctx, content, req.FileName, req.FileType)
if err != nil {
return nil, fmt.Errorf("MinerU file_parse: %w", err)
}
// MinerU already returns markdown with embedded HTML blocks (e.g. <table>, <details>).
// Re-running the whole document through html-to-markdown corrupts valid markdown
// by escaping headings and image syntax. Only apply narrow compatibility fixes.
mdContent = normalizeMinerUMarkdown(mdContent)
// Process images: decode base64, build ImageRef list, replace refs in markdown
imageRefs, mdContent := c.processImages(mdContent, imagesB64)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[MinerU] Parsed successfully, markdown=%d chars, images=%d", len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
func (c *MinerUReader) readV1(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
client := newMinerUV1Client(c.endpoint, c.apiKey, c.timeout)
mdContent, imageRefs, contentList, err := client.ParseWithLayout(ctx, req.FileContent,
minerUUploadFileName(req.FileName, req.FileType),
minerUV1ParseOptions{Tier: c.tier, OCRMode: c.parseMethod})
if err != nil {
return nil, fmt.Errorf("MinerU V1: %w", err)
}
mdContent = normalizeMinerUMarkdown(mdContent)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(ctx, "[MinerU] Parsed successfully (V1), markdown=%d chars, images=%d", len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: minerUSourceBlocks(mdContent, contentList, req.FileType),
}, nil
}
type mineruFileEntry struct {
MDContent string `json:"md_content"`
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
// ContentList is the layout block list (page and box per block), as a
// JSON array or a string holding one depending on the MinerU version.
ContentList json.RawMessage `json:"content_list"`
}
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 {
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 != "/" {
if filepath.Ext(cleanName) == "" {
if cleanType := minerUCleanFileType(fileType); cleanType != "" {
return cleanName + "." + cleanType
}
}
return cleanName
}
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
}
// minerUFileParseContentList returns the content_list of the result entry
// that supplied the markdown.
func minerUFileParseContentList(respBody []byte, resultKey string) json.RawMessage {
var envelope struct {
Results map[string]mineruFileEntry `json:"results"`
}
if json.Unmarshal(respBody, &envelope) != nil {
return nil
}
return envelope.Results[resultKey].ContentList
}
func (c *MinerUReader) callFileParse(
ctx context.Context,
content []byte,
fileName string,
fileType string,
) (string, map[string]string, json.RawMessage, error) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// Form fields
fields := map[string]string{
"return_md": "true",
"return_images": "true",
"table_enable": fmt.Sprintf("%v", c.tableEnable),
"formula_enable": fmt.Sprintf("%v", c.formulaEnable),
"parse_method": c.parseMethod,
"start_page_id": "0",
"end_page_id": "99999",
"backend": c.backend,
"response_format_zip": "false",
"return_middle_json": "false",
"return_model_output": "false",
"return_content_list": "true",
}
if c.language != "" {
fields["lang_list"] = c.language
}
if c.vlmServerURL != "" && (strings.HasPrefix(c.backend, "vlm-http-client") || strings.HasPrefix(c.backend, "hybrid-http-client")) {
fields["server_url"] = c.vlmServerURL
}
for k, v := range fields {
_ = writer.WriteField(k, v)
}
uploadFileName := minerUUploadFileName(fileName, fileType)
// File part
part, err := writer.CreateFormFile("files", uploadFileName)
if err != nil {
return "", nil, nil, fmt.Errorf("create form file: %w", err)
}
if _, err := part.Write(content); err != nil {
return "", nil, nil, fmt.Errorf("write file content: %w", err)
}
writer.Close()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint+"/file_parse", &body)
if err != nil {
return "", nil, nil, fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: c.timeout,
MaxRedirects: 5,
})
resp, err := client.Do(httpReq)
if err != nil {
return "", nil, nil, fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return "", nil, nil, fmt.Errorf("MinerU API status %d: %s", resp.StatusCode, string(respBody))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read response body: %w", err)
}
// Dump raw response for debugging (truncate if too large)
rawStr := string(respBody)
if len(rawStr) > 4000 {
logger.Infof(context.Background(), "[MinerU] Raw response (truncated to 4000 chars): %s ...", rawStr[:4000])
} else {
logger.Infof(context.Background(), "[MinerU] Raw response: %s", rawStr)
}
// Also pretty-print the top-level structure (without large base64 blobs)
var rawMap map[string]interface{}
if err := json.Unmarshal(respBody, &rawMap); err == nil {
c.logMinerUResponseStructure(rawMap, "")
}
mdContent, imagesB64, resultKey, err := parseMinerUFileParseResponse(respBody, uploadFileName)
if err != nil {
return "", nil, nil, err
}
if resultKey != "" {
logger.Infof(context.Background(), "[MinerU] Using response path: results.%s", resultKey)
return mdContent, imagesB64, minerUFileParseContentList(respBody, resultKey), nil
}
logger.Errorf(context.Background(), "[MinerU] Response has no markdown/images under results")
return "", nil, nil, nil
}
// processImages decodes base64 images from MinerU response and returns ImageRef list.
// It also replaces image references in the markdown content.
func (c *MinerUReader) processImages(mdContent string, imagesB64 map[string]string) ([]types.ImageRef, string) {
var refs []types.ImageRef
for ipath, b64Str := range imagesB64 {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
var imgBytes []byte
var ext string
if m := b64DataURIPattern.FindStringSubmatch(b64Str); len(m) == 3 {
ext = m[1]
decoded, err := base64.StdEncoding.DecodeString(m[2])
if err != nil {
logger.Errorf(context.Background(), "[MinerU] Failed to decode base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
} else {
// raw base64 without data URI prefix
decoded, err := base64.StdEncoding.DecodeString(b64Str)
if err != nil {
logger.Errorf(context.Background(), "[MinerU] Failed to decode raw base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
ext = strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs, mdContent
}
// logMinerUResponseStructure logs the structure of the MinerU API response.
func (c *MinerUReader) logMinerUResponseStructure(obj interface{}, prefix string) {
logResponseStructure("MinerU", obj, prefix)
}
// validateMinerUOutboundURL rejects MinerU endpoints that would reach private
// or otherwise restricted hosts when parsed or probed from the app server.
func validateMinerUOutboundURL(rawURL string) error {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
return nil
}
if err := utils.ValidateURLForSSRF(rawURL); err != nil {
return fmt.Errorf("MinerU URL blocked by SSRF check: %v", err)
}
return nil
}
// PingMinerU checks if the self-hosted MinerU service is reachable. For
// MinerU 4.0 it also verifies the configured API key, since /v1/health itself
// is served without authentication.
func PingMinerU(endpoint, apiKey string) (bool, string) {
endpoint = strings.TrimRight(endpoint, "/")
if endpoint == "" {
return false, "未配置 MinerU 端点"
}
if err := validateMinerUOutboundURL(endpoint); err != nil {
return false, err.Error()
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 5 * time.Second,
MaxRedirects: 5,
})
ctx := context.Background()
protocol, err := detectMinerUProtocol(ctx, client, endpoint)
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可用: %v", err)
}
if protocol == minerUProtocolV1 {
return pingMinerUV1Auth(ctx, client, endpoint, apiKey)
}
resp, err := client.Get(endpoint + "/docs")
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode >= 400 {
return false, fmt.Sprintf("MinerU 服务返回状态 %d", resp.StatusCode)
}
return true, ""
}
// pingMinerUV1Auth hits an authenticated V1 endpoint: a server started with
// --api-key answers 401 when the key is missing or wrong.
func pingMinerUV1Auth(ctx context.Context, client *http.Client, endpoint, apiKey string) (bool, string) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint+"/v1/parse/jobs?limit=1", nil)
if err != nil {
return false, fmt.Sprintf("构建请求失败: %v", err)
}
if apiKey = strings.TrimSpace(apiKey); apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
resp, err := client.Do(req)
if err != nil {
return false, fmt.Sprintf("MinerU 服务不可达: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
if apiKey == "" {
return false, "MinerU 服务已启用鉴权,请配置 API Key"
}
return false, "MinerU API Key 无效"
}
return true, ""
}
// escapedImageSyntaxPattern matches markdown image references whose `[` was
// over-escaped to `\[` by html-to-markdown. The URL group mirrors the
// downstream image-extraction regex so escapes are only stripped for actual
// image references.
var escapedImageSyntaxPattern = regexp.MustCompile(`!\\\[(.*?)\\?\]\(([^()\n]*(?:\([^)]*\)[^()\n]*)*)\)`)
// escapedHeadingPattern restores markdown headings that were over-escaped to
// \# Heading. We only touch line-leading heading markers to avoid rewriting
// body text that intentionally contains escaped # characters.
var escapedHeadingPattern = regexp.MustCompile(`(?m)^\\(#{1,6})(\s+)`)
// unescapeMarkdownImageSyntax restores `![alt](url)` from html-to-markdown's
// over-escaped `!\[alt\](url)` form. Without this, the downstream image regex
// in ImageResolver fails to match and images are never persisted.
func unescapeMarkdownImageSyntax(content string) string {
return escapedImageSyntaxPattern.ReplaceAllString(content, "![$1]($2)")
}
func normalizeEscapedMarkdownHeadings(content string) string {
return escapedHeadingPattern.ReplaceAllString(content, `$1$2`)
}
func normalizeMinerUMarkdown(content string) string {
content = unescapeMarkdownImageSyntax(content)
content = normalizeEscapedMarkdownHeadings(content)
return content
}
func mineruImageOriginalRefs(mdContent, imagePath string) []string {
normalizedTarget := normalizeMinerUImagePath(imagePath)
if normalizedTarget == "" {
return nil
}
referenced := extractImageRefsFromContent(mdContent)
seen := make(map[string]struct{}, len(referenced))
var matched []string
for _, refPath := range referenced {
if normalizeMinerUImagePath(refPath) != normalizedTarget {
continue
}
if _, ok := seen[refPath]; ok {
continue
}
matched = append(matched, refPath)
seen[refPath] = struct{}{}
}
return matched
}
// imgMarkdownPatternAllowSpaces matches markdown image syntax while allowing
// spaces in the URL group, so that paths like "images/第 1 页.jpg" produced by
// MinerU on Chinese documents are still detected as image references.
var imgMarkdownPatternAllowSpaces = regexp.MustCompile(
`!\[(.*?)\]\(([^()\n]*(?:\([^)]*\)[^()\n]*)*)\)`,
)
func extractImageRefsFromContent(content string) []string {
var refs []string
for _, match := range imgMarkdownPatternAllowSpaces.FindAllStringSubmatch(content, -1) {
if len(match) >= 3 {
refs = append(refs, strings.TrimSpace(match[2]))
}
}
for _, match := range imgHTMLSrc.FindAllStringSubmatch(content, -1) {
if len(match) >= 3 {
refs = append(refs, match[2])
}
}
return refs
}
func normalizeMinerUImagePath(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
if decoded, err := url.PathUnescape(p); err == nil && decoded != "" {
p = decoded
}
p = strings.TrimPrefix(p, "./")
p = strings.TrimPrefix(p, "/")
p = strings.TrimPrefix(p, "images/")
return p
}
@@ -0,0 +1,20 @@
package docparser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateMinerUOutboundURL_RejectsLoopback(t *testing.T) {
err := validateMinerUOutboundURL("http://127.0.0.1:8080")
require.Error(t, err)
assert.Contains(t, err.Error(), "SSRF")
}
func TestPingMinerU_RejectsPrivateEndpoint(t *testing.T) {
ok, msg := PingMinerU("http://127.0.0.1:8080", "")
assert.False(t, ok)
assert.Contains(t, msg, "SSRF")
}
@@ -0,0 +1,321 @@
package docparser
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/types"
"academy/internal/utils"
)
func TestNewMinerUReaderResolvesParseMethod(t *testing.T) {
tests := []struct {
name string
overrides map[string]string
want string
}{
{name: "default is auto", overrides: map[string]string{}, want: "auto"},
{name: "legacy enabled becomes auto", overrides: map[string]string{"mineru_enable_ocr": "true"}, want: "auto"},
{name: "legacy disabled becomes text", overrides: map[string]string{"mineru_enable_ocr": "false"}, want: "txt"},
{name: "explicit method wins", overrides: map[string]string{"mineru_parse_method": "ocr", "mineru_enable_ocr": "false"}, want: "ocr"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reader := NewMinerUReader(tt.overrides)
if reader.parseMethod != tt.want {
t.Fatalf("parseMethod = %q, want %q", reader.parseMethod, tt.want)
}
})
}
}
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() {
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)
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) {
if r.URL.Path == "/v1/health" {
// MinerU <= 3.x has no V1 API.
http.NotFound(w, r)
return
}
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")
_, _ = w.Write(responseBody)
}))
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",
"",
"![](images/cover.jpg)",
"",
`<details><summary>text_image</summary>caption</details>`,
"",
`<table><tr><td><img src="images/profile.jpg"/></td></tr></table>`,
}, "\n")
got := normalizeMinerUMarkdown(input)
if !strings.Contains(got, "# Heading") {
t.Fatalf("expected heading to stay intact, got: %q", got)
}
if strings.Contains(got, `\# Heading`) {
t.Fatalf("expected heading to avoid escaped form, got: %q", got)
}
if !strings.Contains(got, "![](images/cover.jpg)") {
t.Fatalf("expected markdown image syntax to stay intact, got: %q", got)
}
if strings.Contains(got, `!\[](images/cover.jpg)`) {
t.Fatalf("expected markdown image syntax to avoid escaped form, got: %q", got)
}
if !strings.Contains(got, `<details><summary>text_image</summary>caption</details>`) {
t.Fatalf("expected details/summary block to be preserved, got: %q", got)
}
if !strings.Contains(got, `<img src="images/profile.jpg"/>`) {
t.Fatalf("expected html img tag to be preserved, got: %q", got)
}
}
func TestProcessImagesKeepsReferencedVariants(t *testing.T) {
reader := &MinerUReader{}
mdContent := strings.Join([]string{
"![](images/cover.jpg)",
`<img src="./images/profile.jpg"/>`,
`![](plain.jpg)`,
}, "\n")
png := createTestPNG(200, 150)
b64 := base64.StdEncoding.EncodeToString(png)
images := map[string]string{
"cover.jpg": "data:image/png;base64," + b64,
"profile.jpg": "data:image/png;base64," + b64,
"plain.jpg": "data:image/png;base64," + b64,
}
refs, gotMarkdown := reader.processImages(mdContent, images)
if gotMarkdown != mdContent {
t.Fatalf("processImages should not rewrite markdown content")
}
if len(refs) != 3 {
t.Fatalf("expected 3 image refs, got %d", len(refs))
}
}
// TestProcessImagesMatchesPathsWithSpaces guards against a regression where
// MinerU image filenames containing spaces (common on Chinese documents,
// e.g. "images/第 1 页.jpg") would be silently dropped because the markdown
// regex used to extract refs disallowed whitespace inside the URL group.
func TestProcessImagesMatchesPathsWithSpaces(t *testing.T) {
reader := &MinerUReader{}
mdContent := "![](images/第 1 页.jpg)"
png := createTestPNG(200, 150)
b64 := base64.StdEncoding.EncodeToString(png)
images := map[string]string{
"第 1 页.jpg": "data:image/png;base64," + b64,
}
refs, _ := reader.processImages(mdContent, images)
if len(refs) != 1 {
t.Fatalf("expected 1 image ref for path with spaces, got %d", len(refs))
}
if refs[0].OriginalRef != "images/第 1 页.jpg" {
t.Fatalf("unexpected OriginalRef: %q", refs[0].OriginalRef)
}
}
@@ -0,0 +1,298 @@
package docparser
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"html"
"math"
"regexp"
"sort"
"strings"
"academy/internal/sourceloc"
"academy/internal/types"
)
// minerUBBoxScale is the coordinate range of content_list bounding boxes:
// MinerU normalizes them to 0-1000 of the page, origin at the top-left.
const minerUBBoxScale = 1000.0
// minerUContentItem is one layout block of MinerU's content_list output.
type minerUContentItem struct {
Type string `json:"type"`
Text string `json:"text"`
PageIdx *int `json:"page_idx"`
BBox []float64 `json:"bbox"`
TableBody string `json:"table_body"`
TableCaption json.RawMessage `json:"table_caption"`
ImageCaption json.RawMessage `json:"image_caption"`
ListItems json.RawMessage `json:"list_items"`
CodeBody string `json:"code_body"`
}
var minerUHTMLTagRe = regexp.MustCompile(`<[^>]+>`)
// text is the block's searchable text, in the order MinerU renders it to
// markdown: captions above tables and figures, then the body.
func (it minerUContentItem) text() string {
parts := []string{it.Text}
parts = append(parts, rawStrings(it.TableCaption)...)
parts = append(parts, rawStrings(it.ImageCaption)...)
if it.TableBody != "" {
parts = append(parts, minerUHTMLTagRe.ReplaceAllString(it.TableBody, " "))
}
parts = append(parts, it.CodeBody)
parts = append(parts, rawStrings(it.ListItems)...)
return strings.TrimSpace(strings.Join(parts, " "))
}
// rawStrings reads a JSON string or array of strings.
func rawStrings(raw json.RawMessage) []string {
if len(raw) == 0 {
return nil
}
var list []string
if json.Unmarshal(raw, &list) == nil {
return list
}
var one string
if json.Unmarshal(raw, &one) == nil {
return []string{one}
}
return nil
}
// decodeMinerUContentList accepts the list itself or the list serialized as
// a JSON string, which is how some MinerU API versions return it.
func decodeMinerUContentList(raw []byte) []minerUContentItem {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
return nil
}
if raw[0] == '"' {
var inner string
if json.Unmarshal(raw, &inner) != nil {
return nil
}
raw = []byte(inner)
}
var items []minerUContentItem
if json.Unmarshal(raw, &items) != nil {
return nil
}
return items
}
// minerUContentListFromZip prefers supported MiddleJson 2.0 geometry and
// falls back to legacy content_list.json for older MinerU packages.
func minerUContentListFromZip(zipData []byte) []byte {
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err != nil {
return nil
}
var candidates []*zip.File
for _, f := range zr.File {
name := strings.ToLower(f.Name)
if strings.HasSuffix(name, "middle_json.json") || strings.HasSuffix(name, "content_list.json") {
candidates = append(candidates, f)
}
}
if len(candidates) == 0 {
return nil
}
sort.Slice(candidates, func(i, j int) bool {
mi,
mj := strings.HasSuffix(strings.ToLower(candidates[i].Name),
"middle_json.json"),
strings.HasSuffix(strings.ToLower(candidates[j].Name),
"middle_json.json")
if mi != mj {
return mi
}
di, dj := strings.Count(candidates[i].Name, "/"), strings.Count(candidates[j].Name, "/")
if di != dj {
return di < dj
}
return candidates[i].Name < candidates[j].Name
})
for _, candidate := range candidates {
data, err := readZipEntryCapped(candidate, maxZipEntryBytes)
if err != nil {
continue
}
if strings.HasSuffix(strings.ToLower(candidate.Name), "middle_json.json") {
var doc minerUMiddle
if json.Unmarshal(data, &doc) != nil || doc.Schema != "docvortex.middle" || doc.Version != "2.0" {
continue
}
}
return data
}
return nil
}
// minerUSourceBlocks aligns MinerU's layout blocks against its markdown so
// each paragraph, table and figure points back at its page and region. Only
// PDFs and images have pages a viewer can show; for office files MinerU's
// pages belong to an intermediate PDF, so those are left to the structure
// aligner.
func minerUSourceBlocks(markdown string, contentList []byte, fileType string) []types.SourceBlock {
ft := strings.ToLower(strings.TrimPrefix(fileType, "."))
if ft != "pdf" && !IsImageFormat(ft) {
return nil
}
raw := bytes.TrimSpace(contentList)
if len(raw) > 0 && raw[0] == '{' {
return minerUMiddleSourceBlocks(markdown, raw)
}
items := decodeMinerUContentList(contentList)
if len(items) == 0 {
return nil
}
units := make([]sourceloc.Unit, 0, len(items))
for i, it := range items {
if it.PageIdx == nil || *it.PageIdx < 0 {
continue
}
loc := types.SourceLocator{
Type: types.SourceLocatorPDF,
Page: *it.PageIdx + 1,
SourceID: fmt.Sprintf("mineru:legacy:%d:%d",
*it.PageIdx,
i),
}
if bbox, ok := minerUBBox(it.BBox); ok {
loc.BBox = bbox
}
units = append(units, sourceloc.Unit{Text: it.text(), Locator: loc})
}
return sourceloc.Align(markdown, units)
}
// minerUBBox converts a 0-1000 content_list box to page fractions. Boxes
// outside that range come from MinerU versions that report other units and
// are dropped rather than drawn in the wrong place.
func minerUBBox(b []float64) ([]float64, bool) {
if len(b) != 4 || b[2] <= b[0] || b[3] <= b[1] {
return nil, false
}
for _, v := range b {
if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > minerUBBoxScale {
return nil, false
}
}
out := make([]float64, 4)
for i, v := range b {
out[i] = v / minerUBBoxScale
}
return out, true
}
// MiddleJson 2.0 uses [0,1] normalized boxes (NOT legacy 0..1000).
// Child annotations keep their own geometry. Inline spans have no geometry.
type minerUMiddleBlock struct {
Type string `json:"type"`
Index *int `json:"index"`
BBox []float64 `json:"bbox"`
Content json.RawMessage `json:"content"`
}
type minerUMiddle struct {
Schema string `json:"schema"`
Version string `json:"schema_version"`
Pages []struct {
PageIdx *int `json:"page_idx"`
Blocks []minerUMiddleBlock `json:"blocks"`
} `json:"pages"`
}
func minerUMiddleSourceBlocks(markdown string, raw []byte) []types.SourceBlock {
var doc minerUMiddle
if json.Unmarshal(raw, &doc) != nil || doc.Schema != "docvortex.middle" || doc.Version != "2.0" {
return nil
}
var units []sourceloc.Unit
previousPage := -1
for _, page := range doc.Pages {
if page.PageIdx == nil || *page.PageIdx <= previousPage {
return nil
}
previousPage = *page.PageIdx
previousBlock := -1
for _, block := range page.Blocks {
if block.Index == nil || *block.Index <= previousBlock {
return nil
}
previousBlock = *block.Index
ref := fmt.Sprintf("mineru:2:%d:%d", *page.PageIdx, *block.Index)
units = append(units, minerUMiddleUnits(block, *page.PageIdx+1, ref, nil)...)
}
}
return sourceloc.Align(markdown, units)
}
func minerUMiddleUnits(block minerUMiddleBlock, page int, ref string, parentBox []float64) []sourceloc.Unit {
box := block.BBox
if len(box) == 0 {
box = parentBox
}
loc := types.SourceLocator{Type: types.SourceLocatorPDF, Page: page, SourceID: ref}
if normalizedMinerUBox(box) {
loc.BBox = append([]float64(nil), box...)
}
// These containers contain blocks; text and hyperlinks contain inline spans.
switch block.Type {
case "list", "index", "table", "image", "chart", "code":
var children []minerUMiddleBlock
if json.Unmarshal(block.Content, &children) != nil {
return nil
}
var out []sourceloc.Unit
for i, child := range children {
out = append(out, minerUMiddleUnits(child, page, fmt.Sprintf("%s/%d", ref, i), box)...)
}
return out
default:
text := minerUMiddleText(block.Content)
if block.Type == "table_body" || block.Type == "chart_body" {
text = html.UnescapeString(minerUHTMLTagRe.ReplaceAllString(text, " "))
}
if strings.TrimSpace(text) == "" {
return nil
}
return []sourceloc.Unit{{Text: text, Locator: loc}}
}
}
func minerUMiddleText(raw json.RawMessage) string {
var text string
if json.Unmarshal(raw, &text) == nil {
return text
}
var spans []struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(raw, &spans) != nil {
return ""
}
var out strings.Builder
for _, span := range spans {
out.WriteString(minerUMiddleText(span.Content))
}
return out.String()
}
func normalizedMinerUBox(box []float64) bool {
if len(box) != 4 || box[0] >= box[2] || box[1] >= box[3] {
return false
}
for _, v := range box {
if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 1 {
return false
}
}
return true
}
@@ -0,0 +1,172 @@
package docparser
import (
"archive/zip"
"bytes"
"encoding/json"
"math"
"testing"
"github.com/stretchr/testify/require"
)
// Contract fixture for DocVortex MiddleJson 2.0. Bboxes are normalized
// fractions, page indices are original source indices, and captions are
// child blocks. This is deliberately not a legacy content_list payload.
const middleFixture = `{
"schema": "docvortex.middle",
"schema_version": "2.0",
"is_full_document": true,
"metadata": {
"file_suffix": "pdf",
"producer": {
"name": "mineru",
"version": "4.0.0"
}
},
"pages": [
{
"page_idx": 4,
"blocks": [
{
"type": "text",
"index": 0,
"bbox": [
0.1,
0.2,
0.9,
0.3
],
"content": [
{
"type": "text",
"content": "设备"
},
{
"type": "hyperlink",
"url": "https://example.org",
"content": [
{
"type": "text",
"content": "验收合格"
}
]
}
]
},
{
"type": "table",
"index": 1,
"bbox": [
0.1,
0.4,
0.9,
0.8
],
"content": [
{
"type": "table_caption",
"bbox": [
0.1,
0.4,
0.9,
0.45
],
"content": [
{
"type": "text",
"content": "设备参数表"
}
]
},
{
"type": "table_body",
"bbox": [
0.1,
0.46,
0.9,
0.8
],
"content": "<table><tr><td>限值</td><td>1.5毫米</td></tr></table>"
}
]
}
]
}
]
}`
func TestMinerUMiddleNormalizedGeometryAndNestedBlocks(t *testing.T) {
blocks := minerUSourceBlocks("设备验收合格\n\n设备参数表\n\n|限值|1.5毫米|", []byte(middleFixture), "pdf")
require.Len(t, blocks, 3)
require.Equal(t, 5, blocks[0].Locator.Page)
require.Equal(t, []float64{0.1, 0.2, 0.9, 0.3}, blocks[0].Locator.BBox)
require.Equal(t, "mineru:2:4:0", blocks[0].Locator.SourceID)
require.Equal(t, "exact", blocks[0].Locator.Mapping)
require.Equal(t, []float64{0.1, 0.46, 0.9, 0.8}, blocks[2].Locator.BBox)
}
func TestMinerUMiddleZIPPreferredToLegacy(t *testing.T) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
for name, body := range map[string]string{
"markdown.md": "设备验收合格",
"middle_json.json": middleFixture,
"doc_content_list.json": "[]",
} {
w, err := z.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(body))
require.NoError(t, err)
}
require.NoError(t, z.Close())
require.JSONEq(t, middleFixture, string(minerUContentListFromZip(buf.Bytes())))
}
func TestMinerUMiddleRejectsUnknownSchemaAndInvalidIndices(t *testing.T) {
for _, mutate := range []func(map[string]any){
func(d map[string]any) { d["schema"] = "docvortex.model" },
func(d map[string]any) { d["schema_version"] = "9.0" },
func(d map[string]any) { delete(d["pages"].([]any)[0].(map[string]any), "page_idx") },
func(d map[string]any) { d["pages"].([]any)[0].(map[string]any)["page_idx"] = -1 },
} {
var d map[string]any
require.NoError(t, json.Unmarshal([]byte(middleFixture), &d))
mutate(d)
raw, err := json.Marshal(d)
require.NoError(t, err)
require.Empty(t, minerUSourceBlocks("设备验收合格", raw, "pdf"))
}
}
func TestMinerULegacyMissingPageIsNotPageOne(t *testing.T) {
require.Empty(t, minerUSourceBlocks("设备验收合格", []byte(`[{"type":"text","text":"设备验收合格"}]`), "pdf"))
}
func TestMinerUBoxesRejectNonFiniteAndWrongUnits(t *testing.T) {
for _, box := range [][]float64{{0, 0, math.NaN(), 1}, {0, 0, math.Inf(1), 1}, {0, 0, 900, 600}, {.9, 0, .1, 1}} {
require.False(t, normalizedMinerUBox(box))
}
_, ok := minerUBBox([]float64{0, 0, math.NaN(), 100})
require.False(t, ok)
}
func TestMinerULegacyZIPWithUnsupportedMiddleKeepsContentList(t *testing.T) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
legacy := `[{"type":"text","text":"设备验收合格","page_idx":1,"bbox":[100,200,900,300]}]`
for name, body := range map[string]string{
"doc_middle_json.json": `{"pdf_info":[]}`,
"doc_content_list.json": legacy,
} {
w, err := z.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(body))
require.NoError(t, err)
}
require.NoError(t, z.Close())
blocks := minerUSourceBlocks("设备验收合格", minerUContentListFromZip(buf.Bytes()), "pdf")
require.Len(t, blocks, 1)
require.Equal(t, 2, blocks[0].Locator.Page)
require.Equal(t, []float64{.1, .2, .9, .3}, blocks[0].Locator.BBox)
}
@@ -0,0 +1,117 @@
package docparser
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
func TestMinerUTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"empty", "", defaultMinerUTimeout},
{"whitespace", " ", defaultMinerUTimeout},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 5400s ", 90 * time.Minute},
{"invalid", "invalid", defaultMinerUTimeout},
{"unitless", "5400", defaultMinerUTimeout},
{"zero", "0s", defaultMinerUTimeout},
{"negative", "-1s", defaultMinerUTimeout},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", tt.value)
assert.Equal(t, tt.want, NewMinerUReader(nil).timeout)
})
}
}
// The configured timeout, not the old hardcoded 1000s, must end a parse on
// both protocols, and it must fire before the caller's own deadline.
func TestMinerUReaderHonorsConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
req := &types.ReadRequest{FileContent: []byte("%PDF"), FileName: "a.pdf", FileType: "pdf"}
t.Run("v1", func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", "200ms")
statuses := make([]string, 1000)
for i := range statuses {
statuses[i] = "running"
}
fake := &fakeMinerUV1{t: t, pollStatuses: statuses}
server := httptest.NewServer(fake.handler())
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewMinerUReader(map[string]string{"mineru_endpoint": server.URL}).Read(ctx, req)
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.NoError(t, ctx.Err(), "the configured timeout, not the caller's deadline, should stop the parse")
assert.True(t, fake.canceled, "abandoned job should be canceled on the server")
})
t.Run("legacy", func(t *testing.T) {
t.Setenv("ACADEMY_MINERU_TIMEOUT", "100ms")
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/health" {
http.NotFound(w, r)
return
}
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-r.Context().Done():
case <-release:
}
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := NewMinerUReader(map[string]string{"mineru_endpoint": server.URL}).Read(ctx, req)
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.NoError(t, ctx.Err(), "the configured timeout, not the caller's deadline, should stop the parse")
})
}
func TestMinerUCloudTimeoutConfig(t *testing.T) {
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "")
assert.Equal(t, defaultCloudTimeout, NewMinerUCloudReader(nil).timeout)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "45m")
assert.Equal(t, 45*time.Minute, NewMinerUCloudReader(nil).timeout)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "0s")
assert.Equal(t, defaultCloudTimeout, NewMinerUCloudReader(nil).timeout)
}
func TestMinerUCloudPollStopsAtConfiguredTimeout(t *testing.T) {
allowLoopbackSSRF(t)
t.Setenv("ACADEMY_MINERU_CLOUD_TIMEOUT", "200ms")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"code":0,"data":{"extract_result":[{"state":"running"}]}}`)
}))
defer server.Close()
reader := NewMinerUCloudReader(nil)
reader.baseURL = server.URL
reader.pollInterval = 10 * time.Millisecond
start := time.Now()
_, _, _, err := reader.pollBatchResult(context.Background(), "batch-1")
require.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("timed out after %s", 200*time.Millisecond))
assert.Less(t, time.Since(start), 5*time.Second)
}
@@ -0,0 +1,606 @@
package docparser
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/utils"
)
// MinerU 4.0 replaced the synchronous /file_parse endpoint with the V1 API:
// upload → parse job → poll → download artifacts. See
// https://opendatalab.github.io/MinerU/usage/http_api/.
const (
mineruV1PollInitial = 2 * time.Second
mineruV1PollMax = 30 * time.Second
mineruV1APITimeout = 30 * time.Second
mineruV1MaxZipBytes = 1 << 30
mineruV1CancelBudget = 10 * time.Second
)
// MinerU V1 tiers accepted by POST /v1/parse/jobs. An empty tier means the
// server's default selection policy (standard → basic for PDF/image).
var mineruV1Tiers = map[string]struct{}{
"flash": {},
"basic": {},
"standard": {},
"advanced": {},
}
type minerUProtocol int
const (
minerUProtocolLegacy minerUProtocol = iota // MinerU <= 3.x: POST /file_parse
minerUProtocolV1 // MinerU >= 4.0: /v1/*
)
// minerUV1Client talks to any MinerU V1 deployment (self-hosted api-server or
// the official mineru.net/api).
type minerUV1Client struct {
baseURL string // without the /v1 suffix
apiKey string
apiClient *http.Client // small JSON calls
bulkClient *http.Client // byte upload and artifact download
pollInitial time.Duration
pollMax time.Duration
jobTimeout time.Duration
maxZipBytes int64
logLabel string
cancelBudget time.Duration
}
type minerUV1ParseOptions struct {
Tier string // "" → server default
OCRMode string // auto, txt, ocr
}
func newMinerUV1Client(baseURL, apiKey string, jobTimeout time.Duration) *minerUV1Client {
return &minerUV1Client{
baseURL: strings.TrimRight(baseURL, "/"),
apiKey: strings.TrimSpace(apiKey),
apiClient: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: mineruV1APITimeout,
MaxRedirects: 5,
}),
bulkClient: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: jobTimeout,
MaxRedirects: 5,
}),
pollInitial: mineruV1PollInitial,
pollMax: mineruV1PollMax,
jobTimeout: jobTimeout,
maxZipBytes: mineruV1MaxZipBytes,
logLabel: "MinerU",
cancelBudget: mineruV1CancelBudget,
}
}
// --- wire types ---
type minerUV1ErrorEnvelope struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code"`
} `json:"error"`
}
type minerUV1File struct {
ID string `json:"id"`
}
type minerUV1Upload struct {
ID string `json:"id"`
Status string `json:"status"`
UploadURL string `json:"upload_url"`
UploadMethod string `json:"upload_method"`
UploadHeaders map[string]string `json:"upload_headers"`
File *minerUV1File `json:"file"`
}
type minerUV1FileRef struct {
FileID string `json:"file_id"`
Bytes int64 `json:"bytes"`
}
type minerUV1JobFile struct {
Name string `json:"name"`
Status string `json:"status"`
OutputFiles map[string]minerUV1FileRef `json:"output_files"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
Parse *struct {
ModelUsed string `json:"model_used"`
DurationMS int64 `json:"duration_ms"`
ParserVersion string `json:"parser_version"`
} `json:"parse"`
}
type minerUV1Job struct {
JobID string `json:"job_id"`
Status string `json:"status"`
Tier string `json:"tier"`
Files []minerUV1JobFile `json:"files"`
}
func minerUV1JobTerminal(status string) bool {
switch status {
case "completed", "partial", "failed", "canceled":
return true
}
return false
}
// --- protocol detection ---
// detectMinerUProtocol probes GET /v1/health. MinerU 4.0 answers 200 (or 503
// while models are still preloading); older servers have no such route and
// answer 404/405.
func detectMinerUProtocol(ctx context.Context, client *http.Client, endpoint string) (minerUProtocol, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint+"/v1/health", nil)
if err != nil {
return minerUProtocolLegacy, fmt.Errorf("create health request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return minerUProtocolLegacy, fmt.Errorf("MinerU service unreachable: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
switch resp.StatusCode {
case http.StatusOK:
var health struct {
Status string `json:"status"`
}
if err := json.Unmarshal(body, &health); err != nil || health.Status != "ok" {
return minerUProtocolLegacy, fmt.Errorf("unexpected /v1/health response: %s",
truncateForLog(string(body), 300))
}
return minerUProtocolV1, nil
case http.StatusNotFound, http.StatusMethodNotAllowed:
return minerUProtocolLegacy, nil
default:
if msg := minerUV1ErrorMessage(body); msg != "" {
return minerUProtocolV1, fmt.Errorf("MinerU service not ready (status %d): %s", resp.StatusCode, msg)
}
return minerUProtocolLegacy, fmt.Errorf("MinerU /v1/health status %d: %s",
resp.StatusCode, truncateForLog(string(body), 300))
}
}
func minerUV1ErrorMessage(body []byte) string {
var env minerUV1ErrorEnvelope
if err := json.Unmarshal(body, &env); err != nil {
return ""
}
if env.Error.Code != "" && env.Error.Message != "" {
return env.Error.Code + ": " + env.Error.Message
}
return firstNonEmpty(env.Error.Message, env.Error.Code)
}
func truncateForLog(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
// --- parse flow ---
// Parse uploads content, runs a parse job and returns the markdown and
// images extracted from the job's zip artifact.
func (c *minerUV1Client) Parse(
ctx context.Context,
content []byte,
fileName string,
opts minerUV1ParseOptions,
) (string, []types.ImageRef, error) {
md, refs, _, err := c.ParseWithLayout(ctx, content, fileName, opts)
return md, refs, err
}
// ParseWithLayout is Parse plus the package's content_list, the per-block
// page and box layout (nil when the package carried none).
func (c *minerUV1Client) ParseWithLayout(
ctx context.Context,
content []byte,
fileName string,
opts minerUV1ParseOptions,
) (string, []types.ImageRef, []byte, error) {
ctx, cancel := context.WithTimeout(ctx, c.jobTimeout)
defer cancel()
fileID, err := c.upload(ctx, content, fileName)
if err != nil {
return "", nil, nil, fmt.Errorf("upload: %w", err)
}
jobID, err := c.createJob(ctx, fileID, opts)
if err != nil {
return "", nil, nil, fmt.Errorf("create parse job: %w", err)
}
logger.Infof(ctx, "[%s] parse job created: job_id=%s file_id=%s tier=%q ocr_mode=%s",
c.logLabel, jobID, fileID, opts.Tier, opts.OCRMode)
job, err := c.waitJob(ctx, jobID)
if err != nil {
c.cancelJob(jobID)
return "", nil, nil, err
}
zipRef, err := minerUV1ZipOutput(job)
if err != nil {
return "", nil, nil, err
}
zipData, err := c.downloadFile(ctx, zipRef.FileID)
if err != nil {
return "", nil, nil, fmt.Errorf("download zip artifact: %w", err)
}
md, imageRefs, err := extractMarkdownZip(zipData, c.logLabel)
if err != nil {
return "", nil, nil, fmt.Errorf("extract zip artifact: %w", err)
}
return md, imageRefs, minerUContentListFromZip(zipData), nil
}
func (c *minerUV1Client) upload(ctx context.Context, content []byte, fileName string) (string, error) {
sum := sha256.Sum256(content)
sha := hex.EncodeToString(sum[:])
var created minerUV1Upload
err := c.doJSON(ctx, http.MethodPost, "/v1/uploads", map[string]interface{}{
"filename": fileName,
"bytes": len(content),
"mime_type": minerUV1MimeType(fileName),
"purpose": "parse",
"sha256sum": sha,
}, &created)
if err != nil {
return "", err
}
switch created.Status {
case "completed":
// Same bytes already stored on the server: no transfer needed.
if created.File == nil || created.File.ID == "" {
return "", fmt.Errorf("upload completed without file id")
}
return created.File.ID, nil
case "pending":
default:
return "", fmt.Errorf("unexpected upload status %q", created.Status)
}
if created.ID == "" || created.UploadURL == "" {
return "", fmt.Errorf("pending upload missing id or upload_url")
}
if err := c.putBytes(ctx, &created, content); err != nil {
return "", err
}
var completed minerUV1Upload
err = c.doJSON(ctx, http.MethodPost, "/v1/uploads/"+url.PathEscape(created.ID)+"/complete",
map[string]string{"sha256sum": sha}, &completed)
if err != nil {
return "", fmt.Errorf("complete upload: %w", err)
}
if completed.File == nil || completed.File.ID == "" {
return "", fmt.Errorf("complete upload returned no file id (status %q)", completed.Status)
}
return completed.File.ID, nil
}
// putBytes sends the file to the URL returned by POST /v1/uploads. The MinerU
// API key is attached only when that URL is same-origin with the configured
// endpoint: the official API hands out pre-signed object-storage URLs that
// carry their own authorization and must never receive our key.
func (c *minerUV1Client) putBytes(ctx context.Context, up *minerUV1Upload, content []byte) error {
target, err := c.resolveURL(up.UploadURL)
if err != nil {
return fmt.Errorf("invalid upload_url: %w", err)
}
method := strings.ToUpper(stringOr(up.UploadMethod, http.MethodPut))
req, err := http.NewRequestWithContext(ctx, method, target.String(), bytes.NewReader(content))
if err != nil {
return fmt.Errorf("create upload request: %w", err)
}
for k, v := range up.UploadHeaders {
req.Header.Set(k, v)
}
if c.sameOrigin(target) {
c.setAuth(req)
}
resp, err := c.bulkClient.Do(req)
if err != nil {
return fmt.Errorf("upload bytes: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
return fmt.Errorf("upload bytes status %d: %s", resp.StatusCode, truncateForLog(string(body), 300))
}
return nil
}
func (c *minerUV1Client) createJob(ctx context.Context, fileID string, opts minerUV1ParseOptions) (string, error) {
payload := map[string]interface{}{
"files": []map[string]interface{}{
{"source": map[string]string{"type": "file_id", "file_id": fileID}},
},
"output_formats": []string{"zip"},
}
if opts.Tier != "" {
payload["tier"] = opts.Tier
}
if opts.OCRMode != "" {
payload["ocr_mode"] = opts.OCRMode
}
var job minerUV1Job
if err := c.doJSON(ctx, http.MethodPost, "/v1/parse/jobs", payload, &job); err != nil {
return "", err
}
if job.JobID == "" {
return "", fmt.Errorf("response has no job_id")
}
return job.JobID, nil
}
func (c *minerUV1Client) waitJob(ctx context.Context, jobID string) (*minerUV1Job, error) {
interval := c.pollInitial
for poll := 1; ; poll++ {
var job minerUV1Job
err := c.doJSON(ctx, http.MethodGet, "/v1/parse/jobs/"+url.PathEscape(jobID), nil, &job)
if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("parse job %s: %w", jobID, ctxErr)
}
var apiErr *minerUV1APIError
if errors.As(err, &apiErr) && apiErr.status == http.StatusNotFound {
// Job state lives in process memory; a restarted server forgets it.
return nil, fmt.Errorf("parse job %s no longer exists (MinerU restarted?): %w", jobID, err)
}
logger.Warnf(ctx, "[%s] poll #%d for job %s failed: %v", c.logLabel, poll, jobID, err)
} else {
if poll == 1 || poll%10 == 0 || minerUV1JobTerminal(job.Status) {
logger.Infof(ctx, "[%s] poll #%d: job=%s status=%s", c.logLabel, poll, jobID, job.Status)
}
if minerUV1JobTerminal(job.Status) {
return &job, nil
}
}
sleepCtx(ctx, interval)
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("parse job %s: %w", jobID, ctxErr)
}
interval *= 2
if interval > c.pollMax {
interval = c.pollMax
}
}
}
// cancelJob best-effort cancels a job we stopped waiting for so the server
// does not keep burning GPU time on it. It runs on a fresh context because the
// caller's context is usually already done.
func (c *minerUV1Client) cancelJob(jobID string) {
ctx, cancel := context.WithTimeout(context.Background(), c.cancelBudget)
defer cancel()
if err := c.doJSON(ctx, http.MethodDelete, "/v1/parse/jobs/"+url.PathEscape(jobID), nil, nil); err != nil {
logger.Warnf(ctx, "[%s] cancel job %s: %v", c.logLabel, jobID, err)
}
}
// minerUV1ZipOutput returns the zip artifact of the single submitted file, or
// the per-file error when parsing did not succeed.
func minerUV1ZipOutput(job *minerUV1Job) (minerUV1FileRef, error) {
if len(job.Files) == 0 {
return minerUV1FileRef{}, fmt.Errorf("parse job %s ended %s without file results", job.JobID, job.Status)
}
f := job.Files[0]
if f.Status != "completed" {
reason := job.Status
if f.Error != nil {
reason = firstNonEmpty(strings.TrimSpace(f.Error.Code+": "+f.Error.Message), job.Status)
}
return minerUV1FileRef{}, fmt.Errorf("parse job %s %s: %s", job.JobID, job.Status, reason)
}
ref, ok := f.OutputFiles["zip"]
if !ok || ref.FileID == "" {
return minerUV1FileRef{}, fmt.Errorf("parse job %s completed without zip output", job.JobID)
}
return ref, nil
}
func (c *minerUV1Client) downloadFile(ctx context.Context, fileID string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
c.baseURL+"/v1/files/"+url.PathEscape(fileID)+"/content", nil)
if err != nil {
return nil, err
}
// Go drops Authorization when following a redirect to another host, so a
// 302 to a CDN (official API) does not leak the key.
c.setAuth(req)
resp, err := c.bulkClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
return nil, newMinerUV1APIError(resp.StatusCode, body)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, c.maxZipBytes+1))
if err != nil {
return nil, err
}
if int64(len(data)) > c.maxZipBytes {
return nil, fmt.Errorf("artifact exceeds %d bytes", c.maxZipBytes)
}
return data, nil
}
// --- HTTP helpers ---
type minerUV1APIError struct {
status int
msg string
}
func (e *minerUV1APIError) Error() string {
return fmt.Sprintf("MinerU API status %d: %s", e.status, e.msg)
}
func newMinerUV1APIError(status int, body []byte) *minerUV1APIError {
msg := minerUV1ErrorMessage(body)
if msg == "" {
msg = truncateForLog(string(body), 500)
}
return &minerUV1APIError{status: status, msg: msg}
}
func (c *minerUV1Client) doJSON(ctx context.Context, method, path string, in, out interface{}) error {
var body io.Reader
if in != nil {
raw, err := json.Marshal(in)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
c.setAuth(req)
resp, err := c.apiClient.Do(req)
if err != nil {
return fmt.Errorf("%s %s: %w", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return fmt.Errorf("read response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return newMinerUV1APIError(resp.StatusCode, respBody)
}
if out == nil {
return nil
}
if err := json.Unmarshal(respBody, out); err != nil {
return fmt.Errorf("decode %s %s response: %w", method, path, err)
}
return nil
}
func (c *minerUV1Client) setAuth(req *http.Request) {
if c.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
}
}
func (c *minerUV1Client) resolveURL(raw string) (*url.URL, error) {
base, err := url.Parse(c.baseURL + "/")
if err != nil {
return nil, err
}
ref, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return nil, err
}
resolved := base.ResolveReference(ref)
if resolved.Scheme != "http" && resolved.Scheme != "https" {
return nil, fmt.Errorf("unsupported scheme %q", resolved.Scheme)
}
return resolved, nil
}
// sameOrigin compares scheme, host and effective port with the base URL.
func (c *minerUV1Client) sameOrigin(u *url.URL) bool {
base, err := url.Parse(c.baseURL)
if err != nil {
return false
}
return strings.EqualFold(base.Scheme, u.Scheme) &&
strings.EqualFold(base.Hostname(), u.Hostname()) &&
effectivePort(base) == effectivePort(u)
}
func effectivePort(u *url.URL) string {
if p := u.Port(); p != "" {
return p
}
switch strings.ToLower(u.Scheme) {
case "https":
return "443"
case "http":
return "80"
}
return ""
}
// Slim container images often ship without /etc/mime.types, where Go only
// knows a handful of extensions; cover the formats MinerU accepts explicitly.
var minerUV1MimeTypes = map[string]string{
".pdf": "application/pdf",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".ppt": "application/vnd.ms-powerpoint",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".bmp": "image/bmp",
".tif": "image/tiff",
".tiff": "image/tiff",
".html": "text/html",
".htm": "text/html",
}
func minerUV1MimeType(fileName string) string {
ext := strings.ToLower(filepath.Ext(fileName))
if t, ok := minerUV1MimeTypes[ext]; ok {
return t
}
if ext != "" {
if t := mime.TypeByExtension(ext); t != "" {
if mediaType, _, err := mime.ParseMediaType(t); err == nil {
return mediaType
}
return t
}
}
return "application/octet-stream"
}
@@ -0,0 +1,433 @@
package docparser
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"academy/internal/types"
"academy/internal/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeMinerUV1 is a minimal in-memory MinerU 4.0 api-server.
type fakeMinerUV1 struct {
t *testing.T
apiKey string
mu sync.Mutex
uploadURL string // absolute or relative; defaults to same-origin relative path
dedupHit bool // POST /v1/uploads answers "completed" directly
uploaded []byte
putAuth string
uploadMime string
jobPayload map[string]any
pollStatuses []string // statuses returned by successive GET job calls
polls int
fileError *map[string]string
canceled bool
zipData []byte
downloadCalls int
}
func (f *fakeMinerUV1) handler() http.Handler {
mux := http.NewServeMux()
writeJSON := func(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
authed := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if f.apiKey != "" && r.Header.Get("Authorization") != "Bearer "+f.apiKey {
writeJSON(w, http.StatusUnauthorized, map[string]any{
"error": map[string]string{"message": "bad key", "type": "auth_error", "code": "invalid_api_key"},
})
return
}
next(w, r)
}
}
mux.HandleFunc("GET /v1/health", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "version": "1.0.0"})
})
mux.HandleFunc("POST /v1/uploads", authed(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(f.t, json.NewDecoder(r.Body).Decode(&body))
f.mu.Lock()
defer f.mu.Unlock()
f.uploadMime, _ = body["mime_type"].(string)
if f.dedupHit {
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "completed", "file": map[string]any{"id": "file-src"},
})
return
}
uploadURL := f.uploadURL
if uploadURL == "" {
uploadURL = "/v1/uploads/upload_1/content"
}
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "pending", "upload_url": uploadURL, "upload_method": "PUT",
"upload_headers": map[string]string{"Content-Type": f.uploadMime},
})
}))
mux.HandleFunc("PUT /v1/uploads/upload_1/content", f.handlePut)
mux.HandleFunc("POST /v1/uploads/upload_1/complete", authed(func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"id": "upload_1", "status": "completed", "file": map[string]any{"id": "file-src"},
})
}))
mux.HandleFunc("POST /v1/parse/jobs", authed(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(f.t, json.NewDecoder(r.Body).Decode(&body))
f.mu.Lock()
f.jobPayload = body
f.mu.Unlock()
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": "job_1", "status": "queued"})
}))
mux.HandleFunc("GET /v1/parse/jobs/job_1", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
status := "completed"
if f.polls < len(f.pollStatuses) {
status = f.pollStatuses[f.polls]
}
f.polls++
file := map[string]any{"name": "report.pdf", "status": status}
switch status {
case "completed":
file["output_files"] = map[string]any{"zip": map[string]any{"file_id": "file-zip", "bytes": len(f.zipData)}}
case "failed":
file["error"] = *f.fileError
}
writeJSON(w, http.StatusOK, map[string]any{"job_id": "job_1", "status": status, "files": []any{file}})
}))
mux.HandleFunc("DELETE /v1/parse/jobs/job_1", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
f.canceled = true
f.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"job_id": "job_1", "status": "canceled"})
}))
mux.HandleFunc("GET /v1/parse/jobs", authed(func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": []any{}})
}))
mux.HandleFunc("GET /v1/files/file-zip/content", authed(func(w http.ResponseWriter, _ *http.Request) {
f.mu.Lock()
f.downloadCalls++
f.mu.Unlock()
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(f.zipData)
}))
return mux
}
func (f *fakeMinerUV1) handlePut(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
require.NoError(f.t, err)
f.mu.Lock()
f.uploaded = data
f.putAuth = r.Header.Get("Authorization")
f.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func buildMinerUZip(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range files {
w, err := zw.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, zw.Close())
return buf.Bytes()
}
func allowLoopbackSSRF(t *testing.T) {
t.Helper()
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
}
func fastV1Client(baseURL, apiKey string) *minerUV1Client {
c := newMinerUV1Client(baseURL, apiKey, 10*time.Second)
c.pollInitial = time.Millisecond
c.pollMax = 5 * time.Millisecond
return c
}
const v1TestMarkdown = "# Report\n\n![](images/page_0_image_1.png)\n\n" +
"<table><tr><td><img src=\"images/page_0_table_image_2_1.png\"></td></tr></table>\n"
func v1TestZip(t *testing.T) []byte {
return buildMinerUZip(t, map[string]string{
"markdown.md": v1TestMarkdown,
"middle_json.json": "{}",
"images/page_0_image_1.png": "png-bytes-1",
"images/page_0_table_image_2_1.png": "png-bytes-2",
"images/page_1_image_unreferenced.png": "unused",
})
}
func TestMinerUV1ClientParseFullFlow(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{
t: t,
apiKey: "server-key",
pollStatuses: []string{"queued", "running", "completed"},
zipData: v1TestZip(t),
}
server := httptest.NewServer(fake.handler())
defer server.Close()
client := fastV1Client(server.URL, "server-key")
md, refs, err := client.Parse(context.Background(), []byte("%PDF-1.7 body"), "report.pdf",
minerUV1ParseOptions{Tier: "advanced", OCRMode: "txt"})
require.NoError(t, err)
assert.Equal(t, v1TestMarkdown, md)
require.Len(t, refs, 2)
byRef := map[string]types.ImageRef{}
for _, ref := range refs {
byRef[ref.OriginalRef] = ref
}
assert.Equal(t, []byte("png-bytes-1"), byRef["images/page_0_image_1.png"].ImageData)
assert.Equal(t, []byte("png-bytes-2"), byRef["images/page_0_table_image_2_1.png"].ImageData)
assert.Equal(t, "image/png", byRef["images/page_0_image_1.png"].MimeType)
assert.Equal(t, []byte("%PDF-1.7 body"), fake.uploaded)
assert.Equal(t, "Bearer server-key", fake.putAuth, "same-origin upload must carry the API key")
assert.Equal(t, "application/pdf", fake.uploadMime)
assert.Equal(t, 3, fake.polls)
assert.False(t, fake.canceled)
assert.Equal(t, "advanced", fake.jobPayload["tier"])
assert.Equal(t, "txt", fake.jobPayload["ocr_mode"])
assert.Equal(t, []any{"zip"}, fake.jobPayload["output_formats"])
files := fake.jobPayload["files"].([]any)
source := files[0].(map[string]any)["source"].(map[string]any)
assert.Equal(t, map[string]any{"type": "file_id", "file_id": "file-src"}, source)
}
func TestMinerUV1ClientOmitsTierForServerDefault(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{OCRMode: "auto"})
require.NoError(t, err)
_, hasTier := fake.jobPayload["tier"]
assert.False(t, hasTier)
}
func TestMinerUV1ClientCrossOriginUploadOmitsAPIKey(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key", zipData: v1TestZip(t)}
// A different port on the same host is a different origin, like a
// pre-signed object-storage URL handed out by the official API.
storage := httptest.NewServer(http.HandlerFunc(fake.handlePut))
defer storage.Close()
fake.uploadURL = storage.URL + "/v1/uploads/upload_1/content?Signature=abc"
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "server-key").Parse(context.Background(), []byte("bytes"), "a.pdf",
minerUV1ParseOptions{})
require.NoError(t, err)
assert.Equal(t, []byte("bytes"), fake.uploaded)
assert.Empty(t, fake.putAuth, "API key must not leak to a cross-origin upload URL")
}
func TestMinerUV1ClientDedupSkipsByteUpload(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, dedupHit: true, zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("bytes"), "a.pdf",
minerUV1ParseOptions{})
require.NoError(t, err)
assert.Nil(t, fake.uploaded)
}
func TestMinerUV1ClientFailedJobReportsFileError(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{
t: t,
pollStatuses: []string{"failed"},
fileError: &map[string]string{"code": "parse_failed", "message": "corrupt pdf"},
}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "parse_failed: corrupt pdf")
assert.Zero(t, fake.downloadCalls)
}
func TestMinerUV1ClientCancelsJobOnTimeout(t *testing.T) {
allowLoopbackSSRF(t)
statuses := make([]string, 1000)
for i := range statuses {
statuses[i] = "running"
}
fake := &fakeMinerUV1{t: t, pollStatuses: statuses}
server := httptest.NewServer(fake.handler())
defer server.Close()
client := fastV1Client(server.URL, "")
client.jobTimeout = 100 * time.Millisecond
_, _, err := client.Parse(context.Background(), []byte("x"), "a.pdf", minerUV1ParseOptions{})
require.Error(t, err)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.True(t, fake.canceled, "abandoned job should be canceled on the server")
}
func TestMinerUV1ClientAPIErrorMessage(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key"}
server := httptest.NewServer(fake.handler())
defer server.Close()
_, _, err := fastV1Client(server.URL, "wrong").Parse(context.Background(), []byte("x"), "a.pdf",
minerUV1ParseOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "401")
assert.Contains(t, err.Error(), "invalid_api_key: bad key")
}
func TestDetectMinerUProtocol(t *testing.T) {
allowLoopbackSSRF(t)
tests := []struct {
name string
status int
body string
want minerUProtocol
wantErr string
}{
{name: "v1 healthy", status: 200, body: `{"status":"ok","version":"1.0.0"}`, want: minerUProtocolV1},
{name: "legacy 404", status: 404, body: `{"detail":"Not Found"}`, want: minerUProtocolLegacy},
{name: "legacy 405", status: 405, body: ``, want: minerUProtocolLegacy},
{
name: "v1 preloading models",
status: 503,
body: `{"error":{"message":"weights missing","type":"engine_error",` +
`"code":"model_preload_files_missing"}}`,
want: minerUProtocolV1,
wantErr: "model_preload_files_missing: weights missing",
},
{name: "proxy error", status: 502, body: `bad gateway`, wantErr: "status 502"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/v1/health", r.URL.Path)
w.WriteHeader(tt.status)
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
got, err := detectMinerUProtocol(context.Background(), http.DefaultClient, server.URL)
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
func TestMinerUReaderUsesV1WhenAvailable(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key", zipData: v1TestZip(t)}
server := httptest.NewServer(fake.handler())
defer server.Close()
reader := NewMinerUReader(map[string]string{
"mineru_endpoint": server.URL,
"mineru_server_api_key": "server-key",
"mineru_tier": "Standard",
"mineru_parse_method": "ocr",
// Legacy-only knobs are ignored by the V1 path.
"mineru_model": "pipeline",
"mineru_enable_formula": "false",
})
result, err := reader.Read(context.Background(), &types.ReadRequest{
FileContent: []byte("%PDF"),
FileName: "dir/report.pdf",
FileType: "pdf",
})
require.NoError(t, err)
require.Empty(t, result.Error)
assert.True(t, strings.HasPrefix(result.MarkdownContent, "# Report"))
assert.Len(t, result.ImageRefs, 2)
assert.Equal(t, "standard", fake.jobPayload["tier"])
assert.Equal(t, "ocr", fake.jobPayload["ocr_mode"])
}
func TestResolveMinerUTier(t *testing.T) {
assert.Equal(t, "", resolveMinerUTier(""))
assert.Equal(t, "flash", resolveMinerUTier(" Flash "))
assert.Equal(t, "advanced", resolveMinerUTier("advanced"))
assert.Equal(t, "", resolveMinerUTier("pipeline"), "legacy backend names are not tiers")
assert.Equal(t, "", resolveMinerUTier("auto"))
}
func TestPingMinerUV1(t *testing.T) {
allowLoopbackSSRF(t)
fake := &fakeMinerUV1{t: t, apiKey: "server-key"}
server := httptest.NewServer(fake.handler())
defer server.Close()
ok, msg := PingMinerU(server.URL, "server-key")
assert.True(t, ok, msg)
ok, msg = PingMinerU(server.URL, "wrong")
assert.False(t, ok)
assert.Contains(t, msg, "API Key 无效")
ok, msg = PingMinerU(server.URL, "")
assert.False(t, ok)
assert.Contains(t, msg, "配置 API Key")
open := &fakeMinerUV1{t: t}
openServer := httptest.NewServer(open.handler())
defer openServer.Close()
ok, msg = PingMinerU(openServer.URL, "")
assert.True(t, ok, msg)
}
func TestExtractMarkdownZipResolvesEncodedAndNestedPaths(t *testing.T) {
data := buildMinerUZip(t, map[string]string{
"report/report.md": "![](images/%E7%AC%AC%201%20%E9%A1%B5.png)\n![](./images/b.jpg)",
"report/images/第 1 页.png": "p1",
"report/images/b.jpg": "p2",
})
md, refs, err := extractMarkdownZip(data, "test")
require.NoError(t, err)
assert.Contains(t, md, "images/")
require.Len(t, refs, 2)
assert.Equal(t, []byte("p1"), refs[0].ImageData)
assert.Equal(t, "image/jpeg", refs[1].MimeType)
}
@@ -0,0 +1,375 @@
package docparser
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/sourceloc"
"academy/internal/types"
"academy/internal/utils"
)
const (
paddleOCRVLCloudDefaultBaseURL = "https://paddleocr.aistudio-app.com/api/v2/ocr/jobs"
paddleOCRVLCloudDefaultModel = "PaddleOCR-VL-1.6"
paddleOCRVLCloudPollInterval = 5 * time.Second
// paddleOCRVLCloudTimeout bounds how long one job is polled;
// ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT overrides it for documents that take
// longer, mirroring ACADEMY_MINERU_CLOUD_TIMEOUT on the MinerU cloud reader.
paddleOCRVLCloudTimeout = 600 * time.Second
)
// PaddleOCRVLCloudReader calls the PaddleOCR-VL AI Studio cloud API.
// Flow: POST /jobs (multipart) → poll GET /jobs/{id} → download result JSONL,
// then fetch each referenced image URL.
type PaddleOCRVLCloudReader struct {
token string
baseURL string
model string
useSeal bool
useChart bool
timeout time.Duration
pollInterval time.Duration
}
// NewPaddleOCRVLCloudReader creates a reader from ParserEngineOverrides.
func NewPaddleOCRVLCloudReader(overrides map[string]string) *PaddleOCRVLCloudReader {
return &PaddleOCRVLCloudReader{
token: strings.TrimSpace(overrides["paddleocr_vl_cloud_token"]),
baseURL: strings.TrimRight(stringOr(
overrides["paddleocr_vl_cloud_base_url"], paddleOCRVLCloudDefaultBaseURL,
), "/"),
model: stringOr(overrides["paddleocr_vl_cloud_model"], paddleOCRVLCloudDefaultModel),
useSeal: parseBoolOr(overrides["paddleocr_vl_cloud_use_seal_recognition"], true),
useChart: parseBoolOr(overrides["paddleocr_vl_cloud_use_chart_recognition"], false),
timeout: requestTimeoutFromEnv("ACADEMY_PADDLEOCR_VL_CLOUD_TIMEOUT", paddleOCRVLCloudTimeout),
pollInterval: paddleOCRVLCloudPollInterval,
}
}
func (c *PaddleOCRVLCloudReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.token == "" {
return &types.ReadResult{Error: "PaddleOCR-VL Cloud token is not configured"}, nil
}
if err := utils.ValidateURLForSSRF(c.baseURL); err != nil {
return &types.ReadResult{Error: fmt.Sprintf("PaddleOCR-VL Cloud base URL blocked by SSRF policy: %v", err)}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] Parsing file=%s size=%d model=%s",
req.FileName, len(content), c.model)
jobID, err := c.submitJob(ctx, req, content)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud submit: %w", err)
}
jsonlURL, err := c.pollJob(ctx, jobID)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud poll: %w", err)
}
mdContent, imagesURL, layoutUnits, err := c.fetchResults(jsonlURL)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL Cloud fetch results: %w", err)
}
mdContent = NormalizeHTMLTables(mdContent)
imageRefs := c.downloadImages(mdContent, imagesURL)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] Parsed successfully, markdown=%d chars, images=%d",
len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: paddleOCRVLSourceBlocks(mdContent, layoutUnits, req.FileType),
}, nil
}
func (c *PaddleOCRVLCloudReader) optionalPayload() map[string]interface{} {
// Shared with the self-hosted engine so both produce identical output.
return paddleOCRVLRecognitionParams(c.useSeal, c.useChart)
}
// --- job submit ---
type paddleOCRVLCloudSubmitResponse struct {
Data struct {
JobID string `json:"jobId"`
} `json:"data"`
ErrorCode int `json:"errorCode"`
ErrorMsg string `json:"errorMsg"`
}
func (c *PaddleOCRVLCloudReader) submitJob(ctx context.Context, req *types.ReadRequest, content []byte) (string, error) {
optional, err := json.Marshal(c.optionalPayload())
if err != nil {
return "", fmt.Errorf("marshal optionalPayload: %w", err)
}
fileName := req.FileName
if fileName == "" {
ext := strings.TrimPrefix(req.FileType, ".")
if ext == "" {
ext = "pdf"
}
fileName = "document." + ext
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
_ = writer.WriteField("model", c.model)
_ = writer.WriteField("optionalPayload", string(optional))
part, err := writer.CreateFormFile("file", filepath.Base(fileName))
if err != nil {
return "", fmt.Errorf("create form file: %w", err)
}
if _, err := part.Write(content); err != nil {
return "", fmt.Errorf("write file content: %w", err)
}
writer.Close()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL, &body)
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Authorization", "bearer "+c.token)
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 60 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
return "", fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody))
}
var result paddleOCRVLCloudSubmitResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", fmt.Errorf("decode response: %w", err)
}
if result.Data.JobID == "" {
return "", fmt.Errorf("API returned no jobId: %s", string(respBody))
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] job submitted: jobId=%s", result.Data.JobID)
return result.Data.JobID, nil
}
// --- polling ---
type paddleOCRVLCloudPollResponse struct {
Data struct {
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
ExtractProgress struct {
TotalPages int `json:"totalPages"`
ExtractedPages int `json:"extractedPages"`
} `json:"extractProgress"`
ResultURL struct {
JSONURL string `json:"jsonUrl"`
} `json:"resultUrl"`
} `json:"data"`
}
func (c *PaddleOCRVLCloudReader) pollJob(ctx context.Context, jobID string) (string, error) {
deadline := time.Now().Add(c.timeout)
pollCount := 0
url := c.baseURL + "/" + jobID
for time.Now().Before(deadline) {
// Bail out promptly when the caller cancels (task cancelled / timed
// out) instead of spinning: client.Do would fail immediately and
// sleepCtx returns at once on a cancelled ctx, so without this guard
// the loop busy-hammers the cloud API and floods logs until deadline.
if err := ctx.Err(); err != nil {
return "", err
}
pollCount++
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("create poll request: %w", err)
}
httpReq.Header.Set("Authorization", "bearer "+c.token)
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 30 * time.Second, MaxRedirects: 5})
resp, err := client.Do(httpReq)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d failed: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
respBody, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d status %d: %s", pollCount, resp.StatusCode, string(respBody))
sleepCtx(ctx, c.pollInterval)
continue
}
var pollResp paddleOCRVLCloudPollResponse
if err := json.Unmarshal(respBody, &pollResp); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] poll #%d decode error: %v", pollCount, err)
sleepCtx(ctx, c.pollInterval)
continue
}
state := strings.ToLower(pollResp.Data.State)
if pollCount == 1 || pollCount%6 == 0 || state == "done" || state == "failed" {
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] poll #%d: state=%s pages=%d/%d",
pollCount, state, pollResp.Data.ExtractProgress.ExtractedPages, pollResp.Data.ExtractProgress.TotalPages)
}
switch state {
case "done":
if pollResp.Data.ResultURL.JSONURL == "" {
return "", fmt.Errorf("state=done but no jsonUrl")
}
return pollResp.Data.ResultURL.JSONURL, nil
case "failed":
return "", fmt.Errorf("task failed: %s", pollResp.Data.ErrorMsg)
}
sleepCtx(ctx, c.pollInterval)
}
return "", fmt.Errorf("PaddleOCR-VL Cloud task timed out after %s (%d polls)", c.timeout, pollCount)
}
// --- result parsing ---
type paddleOCRVLCloudResultLine struct {
Result struct {
LayoutParsingResults []paddleOCRVLPage `json:"layoutParsingResults"`
} `json:"result"`
}
func (c *PaddleOCRVLCloudReader) fetchResults(jsonlURL string) (string, map[string]string, []sourceloc.Unit, error) {
if err := utils.ValidateURLForSSRF(jsonlURL); err != nil {
return "", nil, nil, fmt.Errorf("jsonl URL blocked by SSRF check: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 120 * time.Second, MaxRedirects: 5})
resp, err := client.Get(jsonlURL)
if err != nil {
return "", nil, nil, fmt.Errorf("download jsonl: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("download jsonl status %d", resp.StatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read jsonl body: %w", err)
}
texts := make([]string, 0)
images := make(map[string]string)
var units []sourceloc.Unit
pageNumber := 0
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
var parsed paddleOCRVLCloudResultLine
if err := json.Unmarshal([]byte(line), &parsed); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] skip malformed jsonl line: %v", err)
continue
}
for _, p := range parsed.Result.LayoutParsingResults {
pageNumber++
units = append(units, paddleOCRVLPageUnits(pageNumber, p)...)
if t := strings.TrimSpace(p.Markdown.Text); t != "" {
texts = append(texts, p.Markdown.Text)
}
for path, u := range p.Markdown.Images {
if _, ok := images[path]; !ok {
images[path] = u
}
}
}
}
logger.Infof(context.Background(), "[PaddleOCR-VL Cloud] fetched %d page(s), images=%d", len(texts), len(images))
return strings.Join(texts, "\n\n"), images, units, nil
}
// downloadImages fetches each referenced image URL and builds ImageRef entries.
func (c *PaddleOCRVLCloudReader) downloadImages(mdContent string, imagesURL map[string]string) []types.ImageRef {
var refs []types.ImageRef
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{Timeout: 60 * time.Second, MaxRedirects: 5})
for ipath, u := range imagesURL {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
if err := utils.ValidateURLForSSRF(u); err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] image URL blocked %s: %v", ipath, err)
continue
}
resp, err := client.Get(u)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] download image %s: %v", ipath, err)
continue
}
imgBytes, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || resp.StatusCode != http.StatusOK {
logger.Errorf(context.Background(), "[PaddleOCR-VL Cloud] read image %s status=%d err=%v", ipath, resp.StatusCode, err)
continue
}
ext := strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs
}
// PingPaddleOCRVLCloud checks whether the cloud token is present (the API has
// no lightweight health endpoint, so we only validate configuration here).
func PingPaddleOCRVLCloud(token string) (bool, string) {
if strings.TrimSpace(token) == "" {
return false, "未配置 PaddleOCR-VL Cloud Token"
}
return true, ""
}
@@ -0,0 +1,293 @@
package docparser
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strings"
"time"
"academy/internal/logger"
"academy/internal/sourceloc"
"academy/internal/types"
"academy/internal/utils"
)
const defaultPaddleOCRVLTimeout = 1000 * time.Second // large scanned PDFs can take a while
// PaddleOCRVLReader calls a self-hosted PaddleOCR-VL pipeline service
// (the full document-parsing API, not the bare VLM inference server).
//
// Flow: POST {endpoint}/layout-parsing with base64 file → synchronous JSON
// response containing per-page markdown + inline base64 images.
type PaddleOCRVLReader struct {
endpoint string
timeout time.Duration
useSeal bool
useChart bool
}
// NewPaddleOCRVLReader creates a reader from ParserEngineOverrides.
func NewPaddleOCRVLReader(overrides map[string]string) *PaddleOCRVLReader {
return &PaddleOCRVLReader{
timeout: requestTimeoutFromEnv("ACADEMY_PADDLEOCR_VL_TIMEOUT", defaultPaddleOCRVLTimeout),
endpoint: strings.TrimRight(overrides["paddleocr_vl_endpoint"], "/"),
useSeal: parseBoolOr(overrides["paddleocr_vl_use_seal_recognition"], true),
useChart: parseBoolOr(overrides["paddleocr_vl_use_chart_recognition"], false),
}
}
func (c *PaddleOCRVLReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
if c.endpoint == "" {
return &types.ReadResult{Error: "PaddleOCR-VL endpoint is not configured"}, nil
}
if err := utils.ValidateURLForSSRF(c.endpoint); err != nil {
return &types.ReadResult{Error: fmt.Sprintf("PaddleOCR-VL endpoint blocked by SSRF policy: %v", err)}, nil
}
content := req.FileContent
if len(content) == 0 {
return &types.ReadResult{Error: "no file content provided"}, nil
}
logger.Infof(context.Background(), "[PaddleOCR-VL] Parsing file=%s size=%d via %s",
req.FileName, len(content), c.endpoint)
mdContent, imagesB64, layoutUnits, err := c.callLayoutParsing(ctx, req, content)
if err != nil {
return nil, fmt.Errorf("PaddleOCR-VL layout-parsing: %w", err)
}
// PaddleOCR-VL renders tables as styled HTML (per-cell text-align), which
// wastes tokens and defeats the chunker's table-protection logic. Convert
// them to Markdown tables (or strip layout attributes when conversion is
// not possible) before downstream processing.
mdContent = NormalizeHTMLTables(mdContent)
imageRefs, mdContent := c.processImages(mdContent, imagesB64)
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
logger.Infof(context.Background(), "[PaddleOCR-VL] Parsed successfully, markdown=%d chars, images=%d",
len(mdContent), len(imageRefs))
return &types.ReadResult{
MarkdownContent: mdContent,
ImageRefs: imageRefs,
SourceBlocks: paddleOCRVLSourceBlocks(mdContent, layoutUnits, req.FileType),
}, nil
}
// paddleOCRVLRecognitionParams returns the recognition / page-restructuring
// parameters shared by the self-hosted (/layout-parsing, top-level body) and
// cloud (optionalPayload) request bodies. Keeping both identical ensures the
// self-hosted engine reproduces the cloud output: cross-page table merging,
// multi-level heading reconstruction, header/footer stripping, and the same
// sampling / resolution settings used by the AI Studio service.
func paddleOCRVLRecognitionParams(useSeal, useChart bool) map[string]interface{} {
return map[string]interface{}{
"markdownIgnoreLabels": []string{
"header", "header_image", "footer", "footer_image",
"number", "footnote", "aside_text",
},
"useDocOrientationClassify": false,
"useDocUnwarping": false,
"useLayoutDetection": true,
"useChartRecognition": useChart,
"useSealRecognition": useSeal,
"useOcrForImageBlock": false,
"mergeTables": true,
"relevelTitles": true,
"restructurePages": true,
"layoutShapeMode": "auto",
"promptLabel": "ocr",
"layoutNms": true,
"repetitionPenalty": 1,
"temperature": 0,
"topP": 1,
"minPixels": 147384,
"maxPixels": 2822400,
}
}
// fileTypeCode maps a request to the PaddleOCR-VL fileType field:
// 0 = PDF, 1 = image (including TIFF).
func fileTypeCode(req *types.ReadRequest) int {
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
if ft == "" {
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
}
if ft == "pdf" {
return 0
}
return 1
}
// paddleOCRVLResponse mirrors the relevant fields of the PaddleX serving
// /layout-parsing response. The service returns one entry per page.
type paddleOCRVLResponse struct {
ErrorCode int `json:"errorCode"`
ErrorMsg string `json:"errorMsg"`
Result struct {
LayoutParsingResults []paddleOCRVLPage `json:"layoutParsingResults"`
} `json:"result"`
}
func (c *PaddleOCRVLReader) callLayoutParsing(
ctx context.Context, req *types.ReadRequest, content []byte,
) (string, map[string]string, []sourceloc.Unit, error) {
payload := paddleOCRVLRecognitionParams(c.useSeal, c.useChart)
payload["file"] = base64.StdEncoding.EncodeToString(content)
payload["fileType"] = fileTypeCode(req)
payload["visualize"] = false
body, err := json.Marshal(payload)
if err != nil {
return "", nil, nil, fmt.Errorf("marshal payload: %w", err)
}
httpReq, err := http.NewRequestWithContext(
ctx, http.MethodPost, c.endpoint+"/layout-parsing", bytes.NewReader(body),
)
if err != nil {
return "", nil, nil, fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: c.timeout,
MaxRedirects: 5,
})
resp, err := client.Do(httpReq)
if err != nil {
return "", nil, nil, fmt.Errorf("HTTP request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, nil, fmt.Errorf("read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", nil, nil, fmt.Errorf("PaddleOCR-VL API status %d: %s", resp.StatusCode, string(respBody))
}
var result paddleOCRVLResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", nil, nil, fmt.Errorf("decode response: %w", err)
}
if result.ErrorCode != 0 {
return "", nil, nil, fmt.Errorf("PaddleOCR-VL error %d: %s", result.ErrorCode, result.ErrorMsg)
}
pages := result.Result.LayoutParsingResults
if len(pages) == 0 {
logger.Errorf(context.Background(), "[PaddleOCR-VL] response has no layoutParsingResults")
return "", nil, nil, nil
}
// Merge per-page markdown and image dicts into one document.
texts := make([]string, 0, len(pages))
images := make(map[string]string)
var units []sourceloc.Unit
for i, p := range pages {
units = append(units, paddleOCRVLPageUnits(i+1, p)...)
if t := strings.TrimSpace(p.Markdown.Text); t != "" {
texts = append(texts, p.Markdown.Text)
}
for path, data := range p.Markdown.Images {
if _, ok := images[path]; !ok {
images[path] = data
}
}
}
logger.Infof(context.Background(), "[PaddleOCR-VL] parsed %d page(s), images=%d", len(pages), len(images))
return strings.Join(texts, "\n\n"), images, units, nil
}
// processImages decodes the inline base64 images returned by PaddleOCR-VL and
// builds ImageRef entries, matching them against references in the markdown.
func (c *PaddleOCRVLReader) processImages(
mdContent string, imagesB64 map[string]string,
) ([]types.ImageRef, string) {
var refs []types.ImageRef
for ipath, b64Str := range imagesB64 {
matchedRefs := mineruImageOriginalRefs(mdContent, ipath)
if len(matchedRefs) == 0 {
continue
}
var imgBytes []byte
var ext string
if m := b64DataURIPattern.FindStringSubmatch(b64Str); len(m) == 3 {
ext = m[1]
decoded, err := base64.StdEncoding.DecodeString(m[2])
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL] decode base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
} else {
decoded, err := base64.StdEncoding.DecodeString(b64Str)
if err != nil {
logger.Errorf(context.Background(), "[PaddleOCR-VL] decode raw base64 image %s: %v", ipath, err)
continue
}
imgBytes = decoded
ext = strings.TrimPrefix(filepath.Ext(ipath), ".")
if ext == "" {
ext = "png"
}
}
mimeType := mime.TypeByExtension("." + ext)
if mimeType == "" {
mimeType = "image/png"
}
for _, originalRef := range matchedRefs {
refs = append(refs, types.ImageRef{
Filename: ipath,
OriginalRef: originalRef,
MimeType: mimeType,
ImageData: imgBytes,
})
}
}
return refs, mdContent
}
// PingPaddleOCRVL checks whether a self-hosted PaddleOCR-VL service is reachable.
func PingPaddleOCRVL(endpoint string) (bool, string) {
endpoint = strings.TrimRight(endpoint, "/")
if endpoint == "" {
return false, "未配置 PaddleOCR-VL 端点"
}
if err := utils.ValidateURLForSSRF(endpoint); err != nil {
return false, fmt.Sprintf("PaddleOCR-VL 端点未通过 SSRF 校验: %v", err)
}
client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
Timeout: 5 * time.Second,
MaxRedirects: 5,
})
// The pipeline only exposes POST /layout-parsing; an empty GET should still
// produce a routed HTTP response (e.g. 404/405) when the service is up.
resp, err := client.Get(endpoint + "/layout-parsing")
if err != nil {
return false, fmt.Sprintf("PaddleOCR-VL 服务不可达: %v", err)
}
resp.Body.Close()
if resp.StatusCode >= 500 {
return false, fmt.Sprintf("PaddleOCR-VL 服务返回状态 %d", resp.StatusCode)
}
return true, ""
}
@@ -0,0 +1,119 @@
package docparser
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"academy/internal/types"
"academy/internal/utils"
)
func TestPaddleOCRVLTimeoutConfig(t *testing.T) {
for _, tt := range []struct {
name, value string
want time.Duration
}{
{"unset", "", 1000 * time.Second},
{"empty", "", 1000 * time.Second},
{"whitespace", " ", 1000 * time.Second},
{"seconds", "5400s", 90 * time.Minute},
{"minutes", "90m", 90 * time.Minute},
{"trimmed", " 90m ", 90 * time.Minute},
{"invalid", "invalid", 1000 * time.Second},
{"unitless", "5400", 1000 * time.Second},
{"zero", "0s", 1000 * time.Second},
{"negative", "-1s", 1000 * time.Second},
{"overflow", "999999999999999999999h", 1000 * time.Second},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", tt.value)
if tt.name == "unset" {
if err := os.Unsetenv("ACADEMY_PADDLEOCR_VL_TIMEOUT"); err != nil {
t.Fatal(err)
}
}
reader := NewPaddleOCRVLReader(nil)
if reader.timeout != tt.want {
t.Fatalf("timeout = %s, want %s", reader.timeout, tt.want)
}
})
}
}
func TestPaddleOCRVLReadTimeout(t *testing.T) {
// Earlier parser tests may have initialized the runtime whitelist.
utils.SetSSRFWhitelistFromRaw("127.0.0.1,localhost")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
for _, mode := range []string{"success", "http timeout", "parent deadline", "parent cancellation"} {
t.Run(mode, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", "10s")
if mode == "http timeout" {
t.Setenv("ACADEMY_PADDLEOCR_VL_TIMEOUT", "100ms")
}
arrived := make(chan struct{})
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
close(arrived)
if mode == "success" {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"errorCode":0,"result":{"layoutParsingResults":[
{"markdown":{"text":"parsed document","images":{}}}]}}`)
return
}
select {
case <-r.Context().Done():
case <-release:
}
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if mode == "parent deadline" {
var stop context.CancelFunc
ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond)
defer stop()
}
if mode == "parent cancellation" {
go func() {
select {
case <-arrived:
cancel()
case <-ctx.Done():
}
}()
}
reader := NewPaddleOCRVLReader(map[string]string{"paddleocr_vl_endpoint": server.URL})
result, err := reader.Read(ctx, &types.ReadRequest{
FileName: "test.pdf", FileType: "pdf", FileContent: []byte("test"),
})
if mode == "success" {
if err != nil {
t.Fatal(err)
}
if result.MarkdownContent != "parsed document" {
t.Fatalf("unexpected result: %+v", result)
}
return
}
want := context.DeadlineExceeded
if mode == "parent cancellation" {
want = context.Canceled
}
if !errors.Is(err, want) {
t.Fatalf("error = %v, want %v", err, want)
}
if mode == "http timeout" && ctx.Err() != nil {
t.Fatalf("request only stopped at parent deadline: %v", ctx.Err())
}
})
}
}
@@ -0,0 +1,82 @@
package docparser
import (
"encoding/json"
"strings"
"academy/internal/sourceloc"
"academy/internal/types"
)
// paddleOCRVLPage is one page of a PaddleOCR-VL layout-parsing result.
type paddleOCRVLPage struct {
Markdown struct {
Text string `json:"text"`
Images map[string]string `json:"images"`
} `json:"markdown"`
// PrunedResult carries the page's layout blocks; decoded lazily and
// only for the fields source locators need.
PrunedResult json.RawMessage `json:"prunedResult"`
}
type paddleOCRVLLayout struct {
Width float64 `json:"width"`
Height float64 `json:"height"`
ParsingResList []struct {
BlockContent string `json:"block_content"`
BlockBBox []float64 `json:"block_bbox"`
} `json:"parsing_res_list"`
}
// paddleOCRVLPageUnits lists a page's layout blocks, each boxed in page
// fractions, for aligning against the merged markdown. Without layout
// blocks the page's markdown paragraphs are listed with the page alone.
func paddleOCRVLPageUnits(pageNumber int, page paddleOCRVLPage) []sourceloc.Unit {
pageOnly := types.SourceLocator{Type: types.SourceLocatorPDF, Page: pageNumber}
var layout paddleOCRVLLayout
if len(page.PrunedResult) > 0 && json.Unmarshal(page.PrunedResult, &layout) == nil &&
layout.Width > 0 && layout.Height > 0 && len(layout.ParsingResList) > 0 {
units := make([]sourceloc.Unit, 0, len(layout.ParsingResList))
for _, b := range layout.ParsingResList {
loc := pageOnly
if len(b.BlockBBox) == 4 && b.BlockBBox[2] > b.BlockBBox[0] && b.BlockBBox[3] > b.BlockBBox[1] {
loc.BBox = []float64{
clampUnit(b.BlockBBox[0] / layout.Width), clampUnit(b.BlockBBox[1] / layout.Height),
clampUnit(b.BlockBBox[2] / layout.Width), clampUnit(b.BlockBBox[3] / layout.Height),
}
}
units = append(units, sourceloc.Unit{
Text: minerUHTMLTagRe.ReplaceAllString(b.BlockContent, " "),
Locator: loc,
})
}
return units
}
var units []sourceloc.Unit
for _, para := range strings.Split(page.Markdown.Text, "\n\n") {
if strings.TrimSpace(para) != "" {
units = append(units, sourceloc.Unit{Text: para, Locator: pageOnly})
}
}
return units
}
// paddleOCRVLSourceBlocks aligns layout units against the final markdown
// for file types a viewer shows page by page.
func paddleOCRVLSourceBlocks(markdown string, units []sourceloc.Unit, fileType string) []types.SourceBlock {
ft := strings.ToLower(strings.TrimPrefix(fileType, "."))
if ft != "pdf" && !IsImageFormat(ft) {
return nil
}
return sourceloc.Align(markdown, units)
}
func clampUnit(v float64) float64 {
if v < 0 {
return 0
}
if v > 1 {
return 1
}
return v
}
@@ -0,0 +1,406 @@
package docparser
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"academy/internal/types"
secutils "academy/internal/utils"
)
// remoteImageServer serves a valid PNG for every request and counts the hits so
// that budget and dedup behaviour can be asserted directly.
func remoteImageServer(t *testing.T) (*httptest.Server, *int64) {
t.Helper()
var hits int64
png := createTestPNG(200, 200)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&hits, 1)
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(png)
}))
t.Cleanup(ts.Close)
return ts, &hits
}
func allowLocalhost(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
secutils.ResetSSRFWhitelistForTest()
}
func resolve(t *testing.T, markdown string) (string, []StoredImage, *mockFileService) {
t.Helper()
fSvc := &mockFileService{}
updated, images, err := NewImageResolver().ResolveRemoteImages(
context.Background(), markdown, fSvc, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return updated, images, fSvc
}
func TestResolveRemoteImages_HTMLTagRewritesSrcAndKeepsTag(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
markdown := fmt.Sprintf(
`<p><img class="screenshot" src="%s/a.png" alt="login screen" width="600"></p>`, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("original URL still present: %s", updated)
}
if !strings.Contains(updated, images[0].ServingURL) {
t.Errorf("serving URL missing from output: %s", updated)
}
// The surrounding markup is the reason these documents use HTML at all.
for _, want := range []string{`<img`, `class="screenshot"`, `alt="login screen"`, `width="600"`, `</p>`} {
if !strings.Contains(updated, want) {
t.Errorf("tag structure lost, %q missing from: %s", want, updated)
}
}
if strings.Contains(updated, "![") {
t.Errorf("tag was converted to markdown syntax: %s", updated)
}
}
func TestResolveRemoteImages_MarkdownAndHTMLBothResolved(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
markdown := fmt.Sprintf("![md](%s/md.png)\n\n<img src=\"%s/html.png\">", ts.URL, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 2 {
t.Fatalf("expected 2 stored images, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("a remote URL survived: %s", updated)
}
}
func TestResolveRemoteImages_IndependentBudgetPerSyntax(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Adding HTML support must not reduce how many Markdown images a document
// already gets resolved: each syntax carries its own budget.
var b strings.Builder
for i := 0; i < maxRemoteImages; i++ {
fmt.Fprintf(&b, "![md%d](%s/md%d.png)\n\n", i, ts.URL, i)
}
for i := 0; i < 5; i++ {
fmt.Fprintf(&b, "<img src=\"%s/html%d.png\">\n\n", ts.URL, i)
}
updated, images, _ := resolve(t, b.String())
if len(images) != maxRemoteImages+5 {
t.Fatalf("expected %d stored images, got %d", maxRemoteImages+5, len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("a remote URL survived: %s", updated)
}
}
func TestResolveRemoteImages_HTMLSrcNormalization(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
t.Run("uppercase scheme", func(t *testing.T) {
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
updated, images, _ := resolve(t, fmt.Sprintf(`<img SRC="%s/up.png">`, upper))
if len(images) != 1 {
t.Fatalf("expected uppercase scheme to be fetched, got %d", len(images))
}
// The scheme is normalized because every fetcher downstream compares it
// byte-for-byte; an image counted as resolved but unfetchable is worse
// than one left alone.
if strings.Contains(images[0].OriginalRef, "HTTP://") {
t.Errorf("scheme was not normalized: %q", images[0].OriginalRef)
}
if strings.Contains(updated, "HTTP://") {
t.Errorf("document still carries the uppercase scheme: %s", updated)
}
})
t.Run("markdown uppercase scheme is left alone", func(t *testing.T) {
// Markdown targets are handed through unchanged, so a document that
// upstream leaves untouched stays untouched.
upper := strings.Replace(ts.URL, "http://", "HTTP://", 1)
markdown := fmt.Sprintf("![x](%s/md-up.png)", upper)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no markdown behaviour change, got %d image(s)", len(images))
}
if updated != markdown {
t.Errorf("markdown content changed:\n got %q\nwant %q", updated, markdown)
}
})
t.Run("padded src", func(t *testing.T) {
_, images, _ := resolve(t, fmt.Sprintf(`<img src=" %s/pad.png ">`, ts.URL))
if len(images) != 1 {
t.Fatalf("expected padded src to be fetched, got %d", len(images))
}
})
t.Run("entity encoded query", func(t *testing.T) {
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.URL.RawQuery
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(createTestPNG(200, 200))
}))
defer srv.Close()
_, images, _ := resolve(t, fmt.Sprintf(`<img src="%s/q.png?a=1&amp;b=2">`, srv.URL))
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if got != "a=1&b=2" {
t.Errorf("entities were not decoded before the request: raw query %q", got)
}
})
}
func TestResolveRemoteImages_HTMLSrcFormsOutOfScope(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
cases := map[string]string{
"unquoted src": fmt.Sprintf(`<img src=%s/unquoted.png>`, ts.URL),
"srcset only": fmt.Sprintf(`<img srcset="%s/set.png 2x">`, ts.URL),
"relative src": `<img src="./images/local.png">`,
"data uri src": `<img src="data:image/png;base64,AAAA">`,
"provider src": `<img src="local://images/x.png">`,
"non-img tag": fmt.Sprintf(`<video src="%s/v.mp4">`, ts.URL),
}
for name, markdown := range cases {
t.Run(name, func(t *testing.T) {
before := atomic.LoadInt64(hits)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no stored images, got %d", len(images))
}
if updated != markdown {
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
}
if got := atomic.LoadInt64(hits) - before; got != 0 {
t.Errorf("expected no fetch, got %d", got)
}
})
}
}
func TestResolveRemoteImages_HyphenatedAttributeIsNotSrc(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// A lazy-loading tag carries a placeholder in src and the real image in
// data-src. Treating data-src as src would capture whichever came first and
// leave the other unvisited, so only src counts.
markdown := fmt.Sprintf(`<img data-src="/placeholder.svg" src="%s/real.png">`, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected the src image to be resolved, got %d", len(images))
}
if images[0].OriginalRef != ts.URL+"/real.png" {
t.Errorf("expected src to be the fetched reference, got %s", images[0].OriginalRef)
}
if !strings.Contains(updated, `data-src="/placeholder.svg"`) {
t.Errorf("data-src must be left alone: %s", updated)
}
if strings.Contains(updated, ts.URL) {
t.Errorf("src was not rewritten: %s", updated)
}
}
func TestResolveRemoteImages_HyphenatedAttributeOnlyIsNotResolved(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
// The other half of the same trade-off, pinned deliberately. Requiring
// whitespace before src means a tag carrying only a hyphenated *-src is no
// longer treated as an image at all — the previous boundary did resolve it.
// Recovering that needs an attribute parser rather than a regex; capturing a
// lazy-loading placeholder while the real src goes unvisited is the worse of
// the two failures.
for _, attr := range []string{"data-src", "ng-src", "data-original-src"} {
t.Run(attr, func(t *testing.T) {
before := atomic.LoadInt64(hits)
markdown := fmt.Sprintf(`<img %s="%s/only.png">`, attr, ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 0 {
t.Errorf("expected no stored images, got %d", len(images))
}
if updated != markdown {
t.Errorf("content changed:\n got %q\nwant %q", updated, markdown)
}
if got := atomic.LoadInt64(hits) - before; got != 0 {
t.Errorf("expected no fetch, got %d", got)
}
})
}
}
func TestResolveRemoteImages_WhitelistedHostAgreesWithDocument(t *testing.T) {
var hits int64
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&hits, 1)
if got := r.URL.RawQuery; got != "a=1&b=2" {
t.Errorf("expected entities decoded for the request, got raw query %q", got)
}
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(createTestPNG(200, 200))
}))
defer ts.Close()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
t.Setenv("IMAGE_HOST_KEEP_URL", strings.TrimPrefix(ts.URL, "http://"))
secutils.ResetSSRFWhitelistForTest()
markdown := fmt.Sprintf(`<img src=" %s/q.png?a=1&amp;b=2 " alt="kept">`, ts.URL)
updated, images, fSvc := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
if atomic.LoadInt64(&hits) != 1 {
t.Fatalf("expected the image to be downloaded once, got %d", hits)
}
if len(fSvc.saved) != 0 {
t.Errorf("a whitelisted image must not be uploaded, got %d uploads", len(fSvc.saved))
}
serving := images[0].ServingURL
// ServingURL carries two obligations that have to agree: later stages locate
// the image by searching the document for it, and the multimodal stage fetches
// that same string.
if !strings.Contains(updated, serving) {
t.Errorf("ServingURL %q is not present in the document %q", serving, updated)
}
if serving != ts.URL+"/q.png?a=1&b=2" {
t.Errorf("ServingURL must be the normalized fetchable URL, got %q", serving)
}
if strings.TrimSpace(serving) != serving {
t.Errorf("ServingURL must not carry padding: %q", serving)
}
if strings.Contains(serving, "&amp;") {
t.Errorf("ServingURL must not carry HTML entities: %q", serving)
}
if !strings.Contains(updated, `alt="kept"`) {
t.Errorf("the rest of the tag must survive: %s", updated)
}
}
func TestResolveRemoteImages_CodeExampleIsRewritten(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Accepted limitation: this resolver does not parse Markdown structure, so a
// tag shown as a documentation example inside a fence is rewritten like any
// other. Recognising code spans reliably needs a Markdown parser; a
// hand-rolled scanner risks the opposite and far worse failure of treating a
// document's real screenshots as examples.
markdown := fmt.Sprintf("```html\n<img src=\"%s/example.png\">\n```", ts.URL)
updated, images, _ := resolve(t, markdown)
if len(images) != 1 {
t.Fatalf("expected the example to be resolved, got %d", len(images))
}
if strings.Contains(updated, ts.URL) {
t.Errorf("expected the example to be rewritten: %s", updated)
}
}
func TestResolveRemoteImages_CancelledContextStops(t *testing.T) {
allowLocalhost(t)
ts, hits := remoteImageServer(t)
var b strings.Builder
for i := 0; i < 5; i++ {
fmt.Fprintf(&b, "<img src=\"%s/c%d.png\">\n\n", ts.URL, i)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, images, err := NewImageResolver().ResolveRemoteImages(ctx, b.String(), &mockFileService{}, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected no images after cancellation, got %d", len(images))
}
if got := atomic.LoadInt64(hits); got != 0 {
t.Errorf("expected no fetch after cancellation, got %d", got)
}
}
func TestResolveAndStoreThenResolveRemoteImages(t *testing.T) {
allowLocalhost(t)
ts, _ := remoteImageServer(t)
// Mirrors the real ingest order, where ResolveAndStore runs first and
// ResolveRemoteImages then works on its output. This is the only place the
// two HTML resolvers can interfere with each other.
markdown := fmt.Sprintf(
"<img src=\"images/relative.png\">\n\n<img src=\"%s/remote.png\">", ts.URL)
fSvc := &mockFileService{}
resolver := NewImageResolver()
afterStore, storeImages, err := resolver.ResolveAndStore(context.Background(), &types.ReadResult{
MarkdownContent: markdown,
ImageRefs: []types.ImageRef{{
OriginalRef: "images/relative.png",
Filename: "relative.png",
MimeType: "image/png",
ImageData: createTestPNG(200, 200),
}},
}, fSvc, 42)
if err != nil {
t.Fatalf("ResolveAndStore: %v", err)
}
if len(storeImages) != 1 {
t.Fatalf("expected the relative image stored, got %d", len(storeImages))
}
afterRemote, remoteImages, err := resolver.ResolveRemoteImages(
context.Background(), afterStore, fSvc, 42)
if err != nil {
t.Fatalf("ResolveRemoteImages: %v", err)
}
if len(remoteImages) != 1 {
t.Fatalf("expected the remote image stored, got %d", len(remoteImages))
}
if strings.Contains(afterRemote, ts.URL) {
t.Errorf("remote URL survived: %s", afterRemote)
}
if strings.Contains(afterRemote, "images/relative.png") {
t.Errorf("relative reference was not rewritten by the earlier pass: %s", afterRemote)
}
if n := strings.Count(afterRemote, "<img"); n != 2 {
t.Errorf("expected both tags preserved, found %d", n)
}
}
@@ -0,0 +1,264 @@
package docparser
import (
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// mockFileService is a minimal FileService implementation for testing.
type mockFileService struct {
saved []savedEntry
}
type savedEntry struct {
Data []byte
TenantID uint64
FileName string
}
func (m *mockFileService) CheckConnectivity(ctx context.Context) error { return nil }
func (m *mockFileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
return "", nil
}
func (m *mockFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
m.saved = append(m.saved, savedEntry{Data: data, TenantID: tenantID, FileName: fileName})
return fmt.Sprintf("local://images/%s", fileName), nil
}
func (m *mockFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
return nil, nil
}
func (m *mockFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
return filePath, nil
}
func (m *mockFileService) DeleteFile(ctx context.Context, filePath string) error { return nil }
func (m *mockFileService) CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string) (string, error) {
return "", nil
}
func TestResolveRemoteImages_NormalDownload(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
// Create a test HTTP server that serves a real PNG image.
pngData := createTestPNG(200, 200)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
w.Write(pngData)
}))
defer ts.Close()
markdown := fmt.Sprintf("# Hello\n\n![photo](%s/image.png)\n\nSome text", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 42)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 1 {
t.Fatalf("expected 1 stored image, got %d", len(images))
}
// URL should have been replaced.
if strings.Contains(updated, ts.URL) {
t.Errorf("original URL should have been replaced in markdown, got: %s", updated)
}
if !strings.Contains(updated, "local://images/") {
t.Errorf("expected local:// URL in markdown, got: %s", updated)
}
// Verify saved data.
if len(fSvc.saved) != 1 {
t.Fatalf("expected 1 saved entry, got %d", len(fSvc.saved))
}
if fSvc.saved[0].TenantID != 42 {
t.Errorf("expected tenantID 42, got %d", fSvc.saved[0].TenantID)
}
}
func TestResolveRemoteImages_SSRFBlocked(t *testing.T) {
// URLs pointing to private IPs should be blocked by SSRF check.
markdown := "![evil](http://127.0.0.1:8080/secret.png)\n\n![also-evil](http://169.254.169.254/metadata)"
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Both images should be left unchanged (SSRF blocked).
if len(images) != 0 {
t.Errorf("expected 0 stored images (SSRF blocked), got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged when SSRF blocked")
}
}
func TestResolveRemoteImages_NonImageContentType(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write([]byte("<html>not an image</html>"))
}))
defer ts.Close()
markdown := fmt.Sprintf("![bad](%s/page.html)", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for non-image content type, got %d", len(images))
}
// Original URL should be preserved.
if !strings.Contains(updated, ts.URL) {
t.Errorf("original URL should be preserved for non-image content")
}
}
func TestResolveRemoteImages_ProviderSchemeSkipped(t *testing.T) {
markdown := "![already](local://images/abc.png)\n![also](minio://bucket/key.jpg)"
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for provider:// URLs, got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged for provider:// URLs")
}
}
func TestResolveRemoteImages_MultipleImages(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
pngData := createTestPNG(256, 256)
callCount := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
w.Write(pngData)
}))
defer ts.Close()
markdown := fmt.Sprintf("![img1](%s/a.png)\n\ntext\n\n![img2](%s/b.png)\n\n![img3](%s/c.png)",
ts.URL, ts.URL, ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 10)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 3 {
t.Fatalf("expected 3 stored images, got %d", len(images))
}
if callCount != 3 {
t.Errorf("expected 3 HTTP requests, got %d", callCount)
}
if strings.Contains(updated, ts.URL) {
t.Errorf("all original URLs should have been replaced")
}
}
func TestResolveRemoteImages_NoImages(t *testing.T) {
markdown := "# Just text\n\nNo images here."
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images, got %d", len(images))
}
if updated != markdown {
t.Errorf("markdown should be unchanged")
}
}
func TestResolveRemoteImages_Server404(t *testing.T) {
// Whitelist localhost for this test so the test server is reachable
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer ts.Close()
markdown := fmt.Sprintf("![missing](%s/nope.png)", ts.URL)
resolver := NewImageResolver()
fSvc := &mockFileService{}
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(images) != 0 {
t.Errorf("expected 0 images for 404, got %d", len(images))
}
// Original URL preserved on failure.
if !strings.Contains(updated, ts.URL) {
t.Errorf("original URL should be preserved on download failure")
}
}
func TestExtFromURLPath(t *testing.T) {
tests := []struct {
url string
expect string
}{
{"https://example.com/photo.jpg", ".jpg"},
{"https://example.com/photo.JPEG", ".jpeg"},
{"https://example.com/photo.png?v=2", ""}, // query param — path.Ext won't catch it cleanly but that's ok
{"https://example.com/photo.gif", ".gif"},
{"https://example.com/photo.webp", ".webp"},
{"https://example.com/photo.bmp", ".bmp"},
{"https://example.com/photo.svg", ".svg"},
{"https://example.com/photo.pdf", ""},
{"https://example.com/noext", ""},
}
for _, tt := range tests {
t.Run(tt.url, func(t *testing.T) {
got := extFromURLPath(tt.url)
if got != tt.expect {
t.Errorf("extFromURLPath(%q) = %q, want %q", tt.url, got, tt.expect)
}
})
}
}
@@ -0,0 +1,57 @@
package docparser
import (
"encoding/json"
"academy/docreader/proto"
"academy/internal/types"
)
// wireSourceBlock is the transport shape of a source block: a markdown range
// plus the JSON-encoded locator, shared by the gRPC and HTTP docreaders.
type wireSourceBlock struct {
Start uint32 `json:"start"`
End uint32 `json:"end"`
LocatorJSON string `json:"locator_json"`
}
// decodeSourceBlock converts one transported block, dropping it when the
// range is empty or the locator cannot be decoded.
func decodeSourceBlock(b wireSourceBlock) (types.SourceBlock, bool) {
if b.End <= b.Start || b.LocatorJSON == "" {
return types.SourceBlock{}, false
}
var loc types.SourceLocator
if err := json.Unmarshal([]byte(b.LocatorJSON), &loc); err != nil || loc.Type == "" {
return types.SourceBlock{}, false
}
return types.SourceBlock{Start: int(b.Start), End: int(b.End), Locator: loc}, true
}
func sourceBlocksFromProto(pbs []*proto.SourceBlock) []types.SourceBlock {
if len(pbs) == 0 {
return nil
}
out := make([]types.SourceBlock, 0, len(pbs))
for _, pb := range pbs {
if b, ok := decodeSourceBlock(wireSourceBlock{
Start: pb.GetStart(), End: pb.GetEnd(), LocatorJSON: pb.GetLocatorJson(),
}); ok {
out = append(out, b)
}
}
return out
}
func sourceBlocksFromWire(wire []wireSourceBlock) []types.SourceBlock {
if len(wire) == 0 {
return nil
}
out := make([]types.SourceBlock, 0, len(wire))
for _, w := range wire {
if b, ok := decodeSourceBlock(w); ok {
out = append(out, b)
}
}
return out
}
@@ -0,0 +1,92 @@
package docparser
import (
"archive/zip"
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/docreader/proto"
"academy/internal/types"
)
const minerUContentListJSON = `[
{"type":"text","text":"8.14.11 索夹与吊索施工应符合下列规定:","text_level":2,"page_idx":56,"bbox":[80,100,900,120]},
{"type":"text","text":"1 在满足施工需要的前提下,应减小猫道面层开孔面积。","page_idx":56,"bbox":[80,130,920,170]},
{"type":"table","table_body":"<table><tr><td>高度</td><td>12m</td></tr></table>",
"table_caption":["表 1"],"page_idx":57,"bbox":[50,10,950,2000]}
]`
func TestMinerUSourceBlocks(t *testing.T) {
md := "## 8.14.11 索夹与吊索施工应符合下列规定:\n\n1 在满足施工需要的前提下,应减小猫道面层开孔面积。\n\n表 1\n\n| 高度 | 12m |\n| --- | --- |\n"
for name, raw := range map[string][]byte{
"array": []byte(minerUContentListJSON),
"string": mustJSON(t, minerUContentListJSON),
} {
t.Run(name, func(t *testing.T) {
blocks := minerUSourceBlocks(md, raw, "pdf")
require.Len(t, blocks, 3)
assert.Equal(t, 57, blocks[0].Locator.Page)
assert.InDeltaSlice(t, []float64{0.08, 0.1, 0.9, 0.12}, blocks[0].Locator.BBox, 1e-9)
assert.Equal(t, 58, blocks[2].Locator.Page)
assert.Nil(t, blocks[2].Locator.BBox, "out-of-range boxes are dropped")
})
}
assert.Nil(t, minerUSourceBlocks(md, []byte(minerUContentListJSON), "docx"))
}
func TestMinerUContentListFromZip(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, body := range map[string]string{
"doc/doc.md": "x",
"doc/doc_content_list.json": "[1]",
"doc/auto/doc_content_list.json": "[2]",
} {
w, err := zw.Create(name)
require.NoError(t, err)
_, _ = w.Write([]byte(body))
}
require.NoError(t, zw.Close())
assert.Equal(t, "[1]", string(minerUContentListFromZip(buf.Bytes())))
}
func TestPaddleOCRVLPageUnits(t *testing.T) {
var page paddleOCRVLPage
require.NoError(t, json.Unmarshal([]byte(`{
"markdown":{"text":"第一段\n\n第二段"},
"prunedResult":{"width":1000,"height":2000,"parsing_res_list":[
{"block_label":"text","block_content":"第一段","block_bbox":[100,200,900,400]}]}
}`), &page))
units := paddleOCRVLPageUnits(3, page)
require.Len(t, units, 1)
assert.Equal(t, []float64{0.1, 0.1, 0.9, 0.2}, units[0].Locator.BBox)
assert.Equal(t, 3, units[0].Locator.Page)
page.PrunedResult = nil
units = paddleOCRVLPageUnits(4, page)
require.Len(t, units, 2)
assert.Nil(t, units[1].Locator.BBox)
assert.True(t, strings.Contains(units[1].Text, "第二段"))
}
func TestSourceBlocksFromProto(t *testing.T) {
blocks := sourceBlocksFromProto([]*proto.SourceBlock{
{Start: 0, End: 5, LocatorJson: `{"type":"pdf","page":2,"bbox":[0.1,0.2,0.3,0.4]}`},
{Start: 5, End: 5, LocatorJson: `{"type":"pdf","page":2}`},
{Start: 5, End: 9, LocatorJson: `not json`},
})
require.Len(t, blocks, 1)
assert.Equal(t, types.SourceLocator{Type: "pdf", Page: 2, BBox: []float64{0.1, 0.2, 0.3, 0.4}}, blocks[0].Locator)
}
func mustJSON(t *testing.T, s string) []byte {
t.Helper()
b, err := json.Marshal(s)
require.NoError(t, err)
return b
}
@@ -0,0 +1,81 @@
package docparser
import (
"archive/zip"
"errors"
"fmt"
"io"
)
// A MinerU result package arrives over the network from a third-party parse API
// and is buffered before anything about it is validated, so both the download
// and what the archive expands to need a ceiling. The V1 client already caps the
// download (mineruV1MaxZipBytes); the Cloud converter did not, and neither path
// capped decompression.
const (
// maxResultPackageBytes caps a downloaded result package. Same ceiling the
// V1 client applies to the same artifact.
maxResultPackageBytes = mineruV1MaxZipBytes
// maxZipEntryBytes caps one decompressed entry. A markdown page or a single
// extracted image is far below this; an entry that reaches it is a
// compression bomb rather than document content.
maxZipEntryBytes = 64 << 20
// maxZipImagesTotalBytes caps the images extracted from one package. Every
// image is held in memory at once, so the total is what actually decides the
// footprint - bounding each entry alone does not bound a package holding
// thousands of small ones.
maxZipImagesTotalBytes = 512 << 20
)
// errResultPackageTooLarge marks a result package over one of the caps above.
var errResultPackageTooLarge = errors.New("result package exceeds maximum size")
// readResultPackage reads a downloaded result package, refusing anything larger
// than limit instead of buffering it. A non-positive limit falls back to
// maxResultPackageBytes.
//
// Mirrors readCapped in the datasource connectors and internal/infrastructure
// /web_search: read one byte past the cap so an oversized body is distinguishable
// from one that merely failed to read.
func readResultPackage(body io.Reader, limit int64) ([]byte, error) {
if limit <= 0 {
limit = maxResultPackageBytes
}
data, err := io.ReadAll(io.LimitReader(body, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, fmt.Errorf("%w (%d bytes)", errResultPackageTooLarge, limit)
}
return data, nil
}
// readZipEntryCapped reads one archive entry under limit.
//
// It checks UncompressedSize64 first so an obviously oversized entry is never
// decompressed at all, then caps the read anyway: the declared size is attacker
// or vendor controlled and is allowed to understate what the entry expands to.
func readZipEntryCapped(f *zip.File, limit int64) ([]byte, error) {
if limit <= 0 {
limit = maxZipEntryBytes
}
if f.UncompressedSize64 > uint64(limit) {
return nil, fmt.Errorf("%w: entry %q declares %d bytes", errResultPackageTooLarge, f.Name, f.UncompressedSize64)
}
rc, err := f.Open()
if err != nil {
return nil, err
}
defer func() { _ = rc.Close() }()
data, err := io.ReadAll(io.LimitReader(rc, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, fmt.Errorf("%w: entry %q expands past %d bytes", errResultPackageTooLarge, f.Name, limit)
}
return data, nil
}
@@ -0,0 +1,158 @@
package docparser
import (
"archive/zip"
"bytes"
"errors"
"strings"
"testing"
)
// buildZip returns an in-memory archive holding the given name -> content pairs.
func buildZip(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range files {
w, err := zw.Create(name)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if _, err := w.Write([]byte(content)); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("close zip: %v", err)
}
return buf.Bytes()
}
// openEntry returns the first archive entry matching name.
func openEntry(t *testing.T, zipData []byte, name string) *zip.File {
t.Helper()
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err != nil {
t.Fatalf("open zip: %v", err)
}
for _, f := range zr.File {
if f.Name == name {
return f
}
}
t.Fatalf("entry %q not found", name)
return nil
}
func TestReadResultPackage(t *testing.T) {
t.Run("rejects over the cap", func(t *testing.T) {
const limit = 1 << 10
_, err := readResultPackage(strings.NewReader(strings.Repeat("a", limit+1)), limit)
if !errors.Is(err, errResultPackageTooLarge) {
t.Fatalf("err = %v, want errResultPackageTooLarge", err)
}
})
t.Run("accepts exactly the cap", func(t *testing.T) {
const limit = 1 << 10
got, err := readResultPackage(strings.NewReader(strings.Repeat("a", limit)), limit)
if err != nil {
t.Fatalf("readResultPackage() = %v, want nil at exactly the cap", err)
}
if len(got) != limit {
t.Errorf("len = %d, want %d", len(got), limit)
}
})
t.Run("non-positive limit falls back to the production cap", func(t *testing.T) {
if _, err := readResultPackage(strings.NewReader("zip"), 0); err != nil {
t.Fatalf("readResultPackage(_, 0) = %v, want nil", err)
}
})
}
// The declared UncompressedSize64 comes from the archive and is allowed to
// understate the expansion, so the read has to be capped as well as the header
// checked. A header that understates it is the actual bomb.
func TestReadZipEntryCappedRejectsBombs(t *testing.T) {
t.Run("declares over the cap", func(t *testing.T) {
data := buildZip(t, map[string]string{"big.txt": strings.Repeat("a", 4096)})
entry := openEntry(t, data, "big.txt")
_, err := readZipEntryCapped(entry, 1024)
if !errors.Is(err, errResultPackageTooLarge) {
t.Fatalf("err = %v, want errResultPackageTooLarge", err)
}
if !strings.Contains(err.Error(), "declares") {
t.Errorf("error = %q, want it to name the declared size", err)
}
})
t.Run("expands past the cap even with an honest header", func(t *testing.T) {
// 64 KiB of zeroes deflates to well under 1 KiB, so the declared size is
// truthful and passes the header check; only the capped read catches it.
data := buildZip(t, map[string]string{"bomb.txt": strings.Repeat("\x00", 64<<10)})
entry := openEntry(t, data, "bomb.txt")
if entry.UncompressedSize64 > 1024 {
t.Skipf("fixture is not compressed enough to exercise the read cap")
}
got, err := readZipEntryCapped(entry, 1024)
if !errors.Is(err, errResultPackageTooLarge) {
t.Fatalf("err = %v, want errResultPackageTooLarge (read %d bytes)", err, len(got))
}
if !strings.Contains(err.Error(), "expands past") {
t.Errorf("error = %q, want it to name the expansion", err)
}
})
t.Run("accepts an entry at the cap", func(t *testing.T) {
data := buildZip(t, map[string]string{"ok.txt": strings.Repeat("a", 2048)})
entry := openEntry(t, data, "ok.txt")
got, err := readZipEntryCapped(entry, 2048)
if err != nil {
t.Fatalf("readZipEntryCapped() = %v, want nil at exactly the cap", err)
}
if len(got) != 2048 {
t.Errorf("len = %d, want 2048", len(got))
}
})
}
// Every extracted image is held in memory at once, so a package of many small
// entries expands without ever tripping a per-entry cap.
func TestExtractMarkdownZipEnforcesTotalImageBudget(t *testing.T) {
files := map[string]string{
"doc.md": "![a](img/a.png)\n![b](img/b.png)\n![c](img/c.png)\n![d](img/d.png)",
}
for _, name := range []string{"img/a.png", "img/b.png", "img/c.png", "img/d.png"} {
files[name] = strings.Repeat("i", 1024)
}
data := buildZip(t, files)
t.Run("refuses a package over the budget", func(t *testing.T) {
_, _, err := extractMarkdownZipBounded(data, "Test", 3*1024)
if !errors.Is(err, errResultPackageTooLarge) {
t.Fatalf("err = %v, want errResultPackageTooLarge", err)
}
})
t.Run("still extracts a package within budget", func(t *testing.T) {
md, refs, err := extractMarkdownZipBounded(data, "Test", 8*1024)
if err != nil {
t.Fatalf("extractMarkdownZipBounded() = %v, want nil", err)
}
if len(refs) != 4 {
t.Errorf("extracted %d images, want 4", len(refs))
}
for _, r := range refs {
if len(r.ImageData) != 1024 {
t.Errorf("%s: %d bytes, want 1024", r.Filename, len(r.ImageData))
}
}
if !strings.Contains(md, "img/a.png") {
t.Errorf("markdown = %q, want the image references preserved", md)
}
})
}