Skip to content

Go: implement provider: MinerU_Local - #15051

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 20, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. Add model types when add model

RAGFlow(user)> add model 'pipeline' to provider 'mineru_local' instance 'test' with tokens 131072 doc_parse;
SUCCESS
  1. implement provider: MinerU_Local

Verified from CLI

RAGFlow(user)> parse with 'pipeline@test@mineru_local' file './internal/test.pdf'
+--------------------------------------+
| task_id                              |
+--------------------------------------+
| c7260e31-b6e2-4b36-955d-e9c60510c669 |
+--------------------------------------+
RAGFlow(user)> show 'test@mineru_local' task 'c7260e31-b6e2-4b36-955d-e9c60510c669'
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| content                                                                                                                                                                                                                                                          | index |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| # Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation

Bingxin Ke Anton Obukhov Shengyu Huang Nando Metzger Rodrigo Caye Daudt Konrad Schindler Photogrammetry and Remote Sensing, ETH Zurich ¨

![](images/ae256101419715b544d13722...  | 1     |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 20, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 20, 2026
@Haruko386
Haruko386 marked this pull request as draft May 20, 2026 09:04
@Haruko386
Haruko386 marked this pull request as ready for review May 20, 2026 09:04
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a new mineru_local model driver for handling document parsing and task result retrieval. The changes enable users to add models with doc_parse capability via the CLI, and provide the backend implementation for uploading documents to local MinerU endpoints and retrieving parsed results.

Changes

MinerU Local Model Driver Implementation

Layer / File(s) Summary
CLI support for doc_parse model type
internal/cli/types.go, internal/cli/lexer.go, internal/cli/user_parser.go, conf/models/mineru_local.json
New TokenDocParse lexer token recognizes the DOC_PARSE keyword. The parser handles this token in parseAddModel to append "doc_parse" to model types. Configuration file defines the mineru_local model with url mappings for doc_parse and task endpoints.
MinerU local model driver and factory routing
internal/entity/models/factory.go, internal/entity/models/mineru_local.go
CreateModelDriver routes the "mineru_local" provider to instantiate MinerULocalModel. The driver implements ParseFile (multipart upload with optional bearer auth) and ShowTask (retrieve markdown content from results), with stub methods returning "no such method" errors for unsupported operations.

Sequence Diagram

sequenceDiagram
  participant User
  participant ParseFile
  participant HTTPClient
  participant MinerUServer
  participant ShowTask as ShowTask
  
  User->>ParseFile: Call ParseFile with content, modelName, apiConfig
  ParseFile->>ParseFile: Validate content, select region
  ParseFile->>HTTPClient: Multipart POST to parse endpoint with PDF + backend field
  alt Has ApiKey
    ParseFile->>HTTPClient: Set Authorization Bearer header
  end
  HTTPClient->>MinerUServer: POST upload
  MinerUServer-->>HTTPClient: Return task_id
  HTTPClient-->>ParseFile: Unmarshall response (200/202)
  ParseFile-->>User: Return ParseFileResponse with task_id
  
  User->>ShowTask: Call ShowTask with taskID, apiConfig
  ShowTask->>ShowTask: Validate taskID, select region
  ShowTask->>HTTPClient: GET task result endpoint
  alt Has ApiKey
    ShowTask->>HTTPClient: Set Authorization Bearer header
  end
  HTTPClient->>MinerUServer: GET retrieve results
  MinerUServer-->>HTTPClient: Return results with md_content
  HTTPClient-->>ShowTask: Unmarshall response (200/202)
  ShowTask->>ShowTask: Locate first md_content in results
  ShowTask-->>User: Return TaskResponse with TaskSegment
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • infiniflow/ragflow#14990: Parallel implementation adding a mineru model driver with the same ParseFile/ShowTask flow and task ID extraction logic for remote MinerU endpoints.

Poem

🐰 A local miner arrives with PDF in hand,
Parse files and tasks, our region-aware brand,
DOC_PARSE tokens sing through the CLI cascade,
Task IDs and markdown in multipart parade! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly describes the main change: implementing a new provider called MinerU_Local, which is the primary objective of the changeset.
Description check ✅ Passed The description includes the required template sections with problem statement, type of change, and CLI verification demonstrating the feature works as intended.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/entity/models/mineru_local.go`:
- Around line 113-114: Check that the region-specific base URL exists and is
non-empty before building endpoint URLs: validate m.BaseURL[region] (used when
constructing apiURL with m.URLSuffix.DocumentParse and the other usage at the
section noted around lines 200-201), and if missing return a clear error (or
handle via fallback) instead of proceeding to fmt.Sprintf; update the methods
that construct apiURL to early-return an error when the base URL is absent and
include the region in the error message so callers can handle configuration
problems.
- Around line 221-257: The ShowTask handler in mineru_local.go currently treats
HTTP 202 like a finished response and proceeds to parse results, causing
misleading "missing results field"/"md_content not found" errors; update the
response handling so that if resp.StatusCode == 202 you short-circuit and return
a clear in-progress result (e.g., a dedicated error or status value like "task
in progress" with the response body/detail) instead of attempting JSON parse,
and only parse the body for status OK (200); adjust the logic around the
results/md_content checks (results variable and md_content lookup) to assume a
200-only code path so pending jobs produce a clear in-progress response from
ShowTask.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e00af4ad-6056-473d-96ca-dd25e17b0510

📥 Commits

Reviewing files that changed from the base of the PR and between b28e134 and 2295e20.

📒 Files selected for processing (6)
  • conf/models/mineru_local.json
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_parser.go
  • internal/entity/models/factory.go
  • internal/entity/models/mineru_local.go

Comment on lines +113 to +114
apiURL := fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.DocumentParse)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validate region base URL before constructing endpoint URLs.

Both methods read m.BaseURL[region] without checking existence/emptiness, which can degrade into malformed URL errors when region config is missing.

Suggested fix
-	apiURL := fmt.Sprintf("%s/%s", m.BaseURL[region], m.URLSuffix.DocumentParse)
+	baseURL, ok := m.BaseURL[region]
+	if !ok || baseURL == "" {
+		return nil, fmt.Errorf("no base URL configured for region %q", region)
+	}
+	apiURL := fmt.Sprintf("%s/%s", baseURL, m.URLSuffix.DocumentParse)
-	url := fmt.Sprintf("%s/%s/%s/result", m.BaseURL[region], m.URLSuffix.Task, taskID)
+	baseURL, ok := m.BaseURL[region]
+	if !ok || baseURL == "" {
+		return nil, fmt.Errorf("no base URL configured for region %q", region)
+	}
+	url := fmt.Sprintf("%s/%s/%s/result", baseURL, m.URLSuffix.Task, taskID)

Also applies to: 200-201

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/mineru_local.go` around lines 113 - 114, Check that
the region-specific base URL exists and is non-empty before building endpoint
URLs: validate m.BaseURL[region] (used when constructing apiURL with
m.URLSuffix.DocumentParse and the other usage at the section noted around lines
200-201), and if missing return a clear error (or handle via fallback) instead
of proceeding to fmt.Sprintf; update the methods that construct apiURL to
early-return an error when the base URL is absent and include the region in the
error message so callers can handle configuration problems.

Comment on lines +221 to +257
if resp.StatusCode != http.StatusOK && resp.StatusCode != 202 {
return nil, fmt.Errorf("MinerU local status API failed with status %d: %s", resp.StatusCode, string(body))
}

// parse JSON
var result map[string]interface{}

if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %w", err)
}

content := ""

// results
results, ok := result["results"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("missing results field")
}

// Get markdown
for _, fileObj := range results {

fileMap, ok := fileObj.(map[string]interface{})
if !ok {
continue
}

md, ok := fileMap["md_content"].(string)
if ok {
content = md
break
}
}

if content == "" {
return nil, fmt.Errorf("md_content not found")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle 202 Accepted as an in-progress task, not a parse failure.

ShowTask allows 202 but immediately enforces results.md_content; pending jobs will be reported as "missing results field" / "md_content not found" instead of a clear “still processing” status.

Suggested fix
-	if resp.StatusCode != http.StatusOK && resp.StatusCode != 202 {
+	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
 		return nil, fmt.Errorf("MinerU local status API failed with status %d: %s", resp.StatusCode, string(body))
 	}
+
+	if resp.StatusCode == http.StatusAccepted {
+		return nil, fmt.Errorf("task %s is still processing", taskID)
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/mineru_local.go` around lines 221 - 257, The ShowTask
handler in mineru_local.go currently treats HTTP 202 like a finished response
and proceeds to parse results, causing misleading "missing results
field"/"md_content not found" errors; update the response handling so that if
resp.StatusCode == 202 you short-circuit and return a clear in-progress result
(e.g., a dedicated error or status value like "task in progress" with the
response body/detail) instead of attempting JSON parse, and only parse the body
for status OK (200); adjust the logic around the results/md_content checks
(results variable and md_content lookup) to assume a 200-only code path so
pending jobs produce a clear in-progress response from ShowTask.

@codecov

codecov Bot commented May 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (6499bce) to head (2295e20).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15051   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 4a91ca5 into infiniflow:main May 20, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 22, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants