Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: use new backend and render

jinzhenjfbf08ebea03c
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index 9265139f..fa661aa6 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -55,9 +55,9 @@ The following sections provide detailed descriptions of each file's purpose and
## Structured Data Files
> [!IMPORTANT]
-> The current structured output contract uses `hybrid` and `office` backends. Legacy middle-json files marked with `_backend: "pipeline"` are no longer accepted by current readers.
+> The current structured output contract uses the unified `MinerUParser` with `tier` (flash/basic/standard/advanced) and `parse_mode` (txt/ocr) parameters. Legacy middle-json files marked with `_backend: "pipeline"`/`_backend: "hybrid"`/`_backend: "office"` are no longer accepted by current readers; use schema 2.0 `MiddleJson` instead.
-### Hybrid Local Model Output Results
+### Unified Model Output Results
#### Model Inference Results (model.json)
@@ -110,288 +110,119 @@ The following sections provide detailed descriptions of each file's purpose and
**File naming format**: `{original_filename}_middle.json`
-##### Top-level Structure
+##### Top-level Structure (schema 2.0)
| Field Name | Type | Description |
|------------|------|-------------|
-| `pdf_info` | `list[dict]` | Array of parsing results for each page |
-| `_backend` | `string` | Parsing mode: `hybrid` or `office` |
-| `_version_name` | `string` | MinerU version number |
+| `pages` | `list[PageInfo]` | Array of parsing results for each page, strictly increasing by `page_idx` |
+| `file_suffix` | `string` | Input file type: `pdf`, `docx`, `pptx`, or `xlsx` |
+| `effort` | `string` | Analysis effort: `flash`, `low`, `medium`, `high`, or `xhigh` |
+| `parse_mode` | `string` | Parse mode: `txt` or `ocr` |
+| `mineru_version` | `string` | MinerU version number |
-##### Page Information Structure (pdf_info)
+Legacy fields `pdf_info`/`_backend`/`_version_name`/`_ocr_enable`/`_vlm_ocr_enable` are removed in schema 2.0.
+
+##### Page Information Structure (pages)
| Field Name | Description |
|------------|-------------|
-| `preproc_blocks` | Unsegmented intermediate results after PDF preprocessing |
| `page_idx` | Page number, starting from 0 |
-| `page_size` | Page width and height `[width, height]` |
-| `images` | Image block information list |
-| `tables` | Table block information list |
-| `interline_equations` | Interline formula block information list |
-| `discarded_blocks` | Block information to be discarded |
-| `para_blocks` | Content block results after segmentation |
+| `blocks` | List of top-level page blocks (the only content field) |
+
+Legacy fields `preproc_blocks`/`para_blocks`/`page_size`/`images`/`tables`/`interline_equations`/`discarded_blocks`/`_layout_tree`/`layout_bboxes` are removed in schema 2.0 — all content is expressed in the `blocks` tree.
##### Block Structure Hierarchy
```
-Level 1 blocks (table | image | chart)
-└── Level 2 blocks
- └── Lines
- └── Spans
+Top-level page blocks (text | title | equation | image | table | chart | code | list | index | ...)
+└── Visual parent blocks (image | table | chart | code) contain child blocks
+ └── body block + optional caption/footnote blocks
```
-##### Level 1 Block Fields
-
-| Field Name | Description |
-|------------|-------------|
-| `type` | Block type: `table`, `image`, or `chart` |
-| `bbox` | Rectangular box coordinates of the block `[x0, y0, x1, y1]` |
-| `blocks` | List of contained level 2 blocks |
+Leaf blocks (text, title, equation, etc.) carry `content: str` directly. Visual parent blocks (image, table, chart, code) carry `content: list[child blocks]`, where children include exactly one body plus optional caption/footnote. There are no independent `Line`/`Span` types in schema 2.0.
-##### Level 2 Block Fields
+##### Common Block Fields
| Field Name | Description |
|------------|-------------|
| `type` | Block type (see table below) |
-| `bbox` | Rectangular box coordinates of the block |
-| `lines` | List of contained line information |
+| `bbox` | Rectangular box coordinates of the block `[x0, y0, x1, y1]`, normalized to `[0, 1]` |
+| `index` | Block index for reading order (required for top-level blocks) |
+| `content` | For leaf blocks: a string; for visual parent blocks: a list of child blocks |
-##### Level 2 Block Types
+##### Block Types
| Type | Description |
|------|-------------|
-| `image_body` | Image body |
-| `image_caption` | Image caption text |
-| `image_footnote` | Image footnote |
-| `table_body` | Table body |
-| `table_caption` | Table caption text |
-| `table_footnote` | Table footnote |
-| `chart_body` | Chart body |
-| `chart_caption` | Chart caption text |
-| `chart_footnote` | Chart footnote |
-| `text` | Text block |
-| `title` | Title block |
-| `index` | Index block |
-| `list` | List block |
-| `interline_equation` | Interline formula block |
-
-##### Line and Span Structure
-
-**Line fields**:
-- `bbox`: Rectangular box coordinates of the line
-- `spans`: List of contained spans
-
-**Span fields**:
-- `bbox`: Rectangular box coordinates of the span
-- `type`: Span type (`image`, `table`, `chart`, `text`, `inline_equation`, `interline_equation`)
-- `content` | `image_path`: Text content or image path
-
-##### Sample Data
+| `text` | Text block (leaf, `content: str`) |
+| `doc_title` | Document title (level=1) |
+| `paragraph_title` | Paragraph title (level 2-6) |
+| `equation` | Display (interline) formula block (renamed from `interline_equation`) |
+| `image` | Image container; `content` includes `image_body` + optional `image_caption`/`image_footnote` |
+| `table` | Table container; `content` includes `table_body` + optional `table_caption`/`table_footnote` |
+| `chart` | Chart container; `content` includes `chart_body` + optional `chart_caption`/`chart_footnote` |
+| `code` | Code container; `content` includes `code_body` + optional `code_caption`/`code_footnote`; `sub_type` is `code` or `algorithm` |
+| `list` | List container; `content` is a list of `text`/`ref_text`/nested `list` blocks; `sub_type` is `text` or `ref_text` |
+| `index` | Index (table of contents) container; `content` is a list of `text`/`doc_title`/`paragraph_title`/nested `index` blocks |
+| `ref_text` | Reference / citation text block |
+| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | Page auxiliary blocks (leaf, `content: str`) |
+
+##### Sample Data (schema 2.0)
```json
{
- "pdf_info": [
+ "pages": [
{
- "preproc_blocks": [
- {
- "type": "text",
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 82.99800872802734
- ],
- "lines": [
- {
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 72.0000228881836
- ],
- "spans": [
- {
- "bbox": [
- 54.0,
- 61.956024169921875,
- 296.2261657714844,
- 72.0000228881836
- ],
- "content": "dependent on the service headway and the reliability of the departure ",
- "type": "text",
- "score": 1.0
- }
- ]
- }
- ]
- }
- ],
- "layout_bboxes": [
- {
- "layout_bbox": [
- 52,
- 61,
- 294,
- 731
- ],
- "layout_label": "V",
- "sub_layout": []
- }
- ],
"page_idx": 0,
- "page_size": [
- 612.0,
- 792.0
- ],
- "_layout_tree": [],
- "images": [],
- "tables": [],
- "interline_equations": [],
- "discarded_blocks": [],
- "para_blocks": [
+ "blocks": [
+ {
+ "type": "doc_title",
+ "index": 0,
+ "bbox": [0.45, 0.23, 0.55, 0.28],
+ "content": "1 Introduction",
+ "level": 1
+ },
{
"type": "text",
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 82.99800872802734
- ],
- "lines": [
+ "index": 1,
+ "bbox": [0.08, 0.30, 0.46, 0.40],
+ "content": "dependent on the service headway and the reliability of the departure"
+ },
+ {
+ "type": "image",
+ "index": 2,
+ "bbox": [0.52, 0.30, 0.95, 0.55],
+ "content": [
+ {
+ "type": "image_body",
+ "index": 2,
+ "bbox": [0.52, 0.30, 0.95, 0.55],
+ "content": "",
+ "image_path": "images/page_0_image_body_2.png"
+ },
{
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 72.0000228881836
- ],
- "spans": [
- {
- "bbox": [
- 54.0,
- 61.956024169921875,
- 296.2261657714844,
- 72.0000228881836
- ],
- "content": "dependent on the service headway and the reliability of the departure ",
- "type": "text",
- "score": 1.0
- }
- ]
+ "type": "image_caption",
+ "index": 3,
+ "bbox": [0.52, 0.56, 0.95, 0.58],
+ "content": "Figure 1: Example figure"
}
- ]
+ ],
+ "sub_type": null
}
]
}
],
- "_backend": "hybrid",
- "_version_name": "0.6.1"
+ "file_suffix": "pdf",
+ "effort": "high",
+ "parse_mode": "ocr",
+ "mineru_version": "1.x.x"
}
```
#### Content List (content_list.json)
-**File naming format**: `{original_filename}_content_list.json`
-
-##### Functionality
-
-This is a simplified version of `middle.json` that stores all readable content blocks in reading order as a flat structure, removing complex layout information for easier subsequent processing.
-
-##### Content Types
-
-| Type | Description |
-|------|-------------|
-| `image` | Image |
-| `table` | Table |
-| `chart` | Chart |
-| `text` | Text/Title |
-| `equation` | Interline formula |
-| `code` | Code block / algorithm block |
-| `list` | List / reference list |
-| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | Page auxiliary blocks |
-
-##### Text Level Identification
-
-Text levels are distinguished through the `text_level` field:
-
-- No `text_level` or `text_level: 0`: Body text
-- `text_level: 1`: Level 1 heading
-- `text_level: 2`: Level 2 heading
-- And so on...
-
-##### Common Fields
-
-- All content blocks include a `page_idx` field indicating the page number (starting from 0).
-- All content blocks include a `bbox` field representing the bounding box coordinates of the content block `[x0, y0, x1, y1]`, mapped to a range of 0-1000.
-- `code` entries use `sub_type` to distinguish `code` and `algorithm`, and may include fields such as `code_body`, `code_caption`, and `code_footnote`.
-- `list` entries may use `sub_type` to distinguish ordinary lists from reference-style lists.
-- `image` / `chart` entries may include an optional `sub_type` field to carry the visual subtype through downstream outputs.
-- Seal content is represented as an `image` entry with `sub_type: "seal"`.
-
-##### Sample Data
-
-```json
-[
- {
- "type": "text",
- "text": "The response of flow duration curves to afforestation ",
- "text_level": 1,
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 0
- },
- {
- "type": "image",
- "img_path": "images/a8ecda1c69b27e4f79fce1589175a9d721cbdc1cf78b4cc06a015f3746f6b9d8.jpg",
- "image_caption": [
- "Fig. 1. Annual flow duration curves of daily flows from Pine Creek, Australia, 1989–2000. "
- ],
- "image_footnote": [],
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 1
- },
- {
- "type": "equation",
- "img_path": "images/181ea56ef185060d04bf4e274685f3e072e922e7b839f093d482c29bf89b71e8.jpg",
- "text": "$$\nQ _ { \\% } = f ( P ) + g ( T )\n$$",
- "text_format": "latex",
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 2
- },
- {
- "type": "table",
- "img_path": "images/e3cb413394a475e555807ffdad913435940ec637873d673ee1b039e3bc3496d0.jpg",
- "table_caption": [
- "Table 2 Significance of the rainfall and time terms "
- ],
- "table_footnote": [
- "indicates that the rainfall term was significant at the $5 \\%$ level, $T$ indicates that the time term was significant at the $5 \\%$ level, \\* represents significance at the $10 \\%$ level, and na denotes too few data points for meaningful analysis. "
- ],
- "table_body": "<html><body><table><tr><td rowspan=\"2\">Site</td><td colspan=\"10\">Percentile</td></tr><tr><td>10</td><td>20</td><td>30</td><td>40</td><td>50</td><td>60</td><td>70</td><td>80</td><td>90</td><td>100</td></tr><tr><td>Traralgon Ck</td><td>P</td><td>P,*</td><td>P</td><td>P</td><td>P,</td><td>P,</td><td>P,</td><td>P,</td><td>P</td><td>P</td></tr><tr><td>Redhill</td><td>P,T</td><td>P,T</td><td>,*</td><td>**</td><td>P.T</td><td>P,*</td><td>P*</td><td>P*</td><td>*</td><td>,*</td></tr><tr><td>Pine Ck</td><td></td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td><td>T</td><td>na</td><td>na</td></tr><tr><td>Stewarts Ck 5</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P.T</td><td>P.T</td><td>P,T</td><td>na</td><td>na</td><td>na</td></tr><tr><td>Glendhu 2</td><td>P</td><td>P,T</td><td>P,*</td><td>P,T</td><td>P.T</td><td>P,ns</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td></tr><tr><td>Cathedral Peak 2</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Cathedral Peak 3</td><td>P.T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Lambrechtsbos A</td><td>P,T</td><td>P</td><td>P</td><td>P,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>T</td></tr><tr><td>Lambrechtsbos B</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td></tr><tr><td>Biesievlei</td><td>P,T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>*,T</td><td>T</td><td>T</td><td>P,T</td><td>P,T</td></tr></table></body></html>",
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 5
- }
-]
-```
+> [!NOTE]
+> `content_list.json` is deprecated and no longer generated. Use `structured_content.json` for structured content output. See the [Common Structured Content](#common-structured-content-structured_contentjsondevelopment-version-subject-to-change) section below.
### Common Structured Content (structured_content.json)(development version, subject to change)
@@ -399,7 +230,7 @@ Text levels are distinguished through the `text_level` field:
##### Functionality
-`structured_content.json` is the new structured output added in 3.0. All backends now emit it in addition to the legacy `content_list.json`:
+`structured_content.json` is the new structured output added in 3.0:
- The top level is grouped by page for page-oriented consumption
- Each item uses a unified `type + content` structure for easier programmatic processing
@@ -469,7 +300,7 @@ exact styles are represented by the child `text` spans.
]
```
-### Hybrid Multimodal Output Results
+### Multimodal Model Output Results
#### Model Inference Results (model.json)
@@ -543,66 +374,36 @@ exact styles are represented by the child `text` spans.
**File naming format**: `{original_filename}_middle.json`
-Hybrid multimodal `middle.json` includes these extensions over the base block structure:
+In schema 2.0, the multimodal tier produces the same unified `MiddleJson` structure as other tiers. The block types below are part of the standard `blocks` tree (not extensions):
-- `list` becomes a second‑level block, a new field `sub_type` distinguishes list categories:
+- `list` is a container block; `content` holds child `text`/`ref_text`/nested `list` blocks; `sub_type` distinguishes list categories:
* `text`: ordinary list
* `ref_text`: reference / bibliography style list
-- New `code` block type with `sub_type`(a code block always has at least a `code_body`, it may optionally have a `code_caption`):
+- `code` is a container block; `content` holds a `code_body` plus optional `code_caption`/`code_footnote`; `sub_type` is:
* `code`
* `algorithm`
-- `discarded_blocks` may contain additional types:
- * `header`
- * `footer`
- * `page_number`
- * `aside_text`
- * `page_footnote`
-- All blocks include an `angle` field indicating rotation (one of `0, 90, 180, 270`).
+- Page auxiliary blocks (`header`, `footer`, `page_number`, `aside_text`, `page_footnote`) appear as top-level leaf blocks in `blocks` with `content: str` — there is no separate `discarded_blocks` field in schema 2.0.
+- All blocks may include an `angle` field indicating rotation (one of `0, 90, 180, 270`).
##### Examples
- Example: list block
```json
{
- "bbox": [174,155,818,333],
"type": "list",
- "angle": 0,
+ "bbox": [0.068, 0.121, 0.319, 0.260],
"index": 11,
- "blocks": [
+ "content": [
{
- "bbox": [174,157,311,175],
"type": "text",
- "angle": 0,
- "lines": [
- {
- "bbox": [174,157,311,175],
- "spans": [
- {
- "bbox": [174,157,311,175],
- "type": "text",
- "content": "H.1 Introduction"
- }
- ]
- }
- ],
- "index": 3
+ "bbox": [0.068, 0.123, 0.122, 0.137],
+ "index": 3,
+ "content": "H.1 Introduction"
},
{
- "bbox": [175,182,464,229],
"type": "text",
- "angle": 0,
- "lines": [
- {
- "bbox": [175,182,464,229],
- "spans": [
- {
- "bbox": [175,182,464,229],
- "type": "text",
- "content": "H.2 Example: Divide by Zero without Exception Handling"
- }
- ]
- }
- ],
- "index": 4
+ "bbox": [0.068, 0.142, 0.181, 0.179],
+ "index": 4,
+ "content": "H.2 Example: Divide by Zero without Exception Handling"
}
],
"sub_type": "text"
@@ -613,114 +414,31 @@ Hybrid multimodal `middle.json` includes these extensions over the base block st
```json
{
"type": "code",
- "bbox": [114,780,885,1231],
- "blocks": [
+ "bbox": [0.045, 0.610, 0.346, 0.964],
+ "index": 17,
+ "content": [
{
- "bbox": [114,780,885,1231],
- "lines": [
- {
- "bbox": [114,780,885,1231],
- "spans": [
- {
- "bbox": [114,780,885,1231],
- "type": "text",
- "content": "1 // Fig. H.1: DivideByZeroNoExceptionHandling.java \n2 // Integer division without exception handling. \n3 import java.util.Scanner; \n4 \n5 public class DivideByZeroNoExceptionHandling \n6 { \n7 // demonstrates throwing an exception when a divide-by-zero occurs \n8 public static int quotient( int numerator, int denominator ) \n9 { \n10 return numerator / denominator; // possible division by zero \n11 } // end method quotient \n12 \n13 public static void main(String[] args) \n14 { \n15 Scanner scanner = new Scanner(System.in); // scanner for input \n16 \n17 System.out.print(\"Please enter an integer numerator: \"); \n18 int numerator = scanner.nextInt(); \n19 System.out.print(\"Please enter an integer denominator: \"); \n20 int denominator = scanner.nextInt(); \n21"
- }
- ]
- }
- ],
+ "type": "code_body",
+ "bbox": [0.045, 0.610, 0.346, 0.964],
"index": 17,
- "angle": 0,
- "type": "code_body"
+ "content": "1 // Fig. H.1: DivideByZeroNoExceptionHandling.java \n2 // Integer division without exception handling. \n3 import java.util.Scanner; \n4 \n5 public class DivideByZeroNoExceptionHandling \n6 { \n7 // demonstrates throwing an exception when a divide-by-zero occurs \n8 public static int quotient( int numerator, int denominator ) \n9 { \n10 return numerator / denominator; // possible division by zero \n11 } // end method quotient \n12 \n13 public static void main(String[] args) \n14 { \n15 Scanner scanner = new Scanner(System.in); // scanner for input \n16 \n17 System.out.print(\"Please enter an integer numerator: \"); \n18 int numerator = scanner.nextInt(); \n19 System.out.print(\"Please enter an integer denominator: \"); \n20 int denominator = scanner.nextInt(); \n21"
},
{
- "bbox": [867,160,1280,189],
- "lines": [
- {
- "bbox": [867,160,1280,189],
- "spans": [
- {
- "bbox": [867,160,1280,189],
- "type": "text",
- "content": "Algorithm 1 Modules for MCTSteg"
- }
- ]
- }
- ],
+ "type": "code_caption",
+ "bbox": [0.339, 0.125, 0.500, 0.148],
"index": 19,
- "angle": 0,
- "type": "code_caption"
+ "content": "Algorithm 1 Modules for MCTSteg"
}
],
- "index": 17,
- "sub_type": "code"
+ "sub_type": "code",
+ "guess_lang": "java"
}
```
#### Content List (content_list.json)
-**File naming format**: `{original_filename}_content_list.json`
-
-Hybrid multimodal `content_list.json` includes these extensions:
-
-- New `code` type with `sub_type` (`code` | `algorithm`):
- * Fields: `code_body` (string), optional `code_caption` (list of strings)
-- New `list` type with `sub_type` (`text` | `ref_text`):
- * Field: `list_items` (array of strings)
-- `image` / `chart` entries may carry an optional `sub_type` field for visual subtype propagation.
-- `chart` entries may additionally expose `content`, `chart_caption`, and `chart_footnote` alongside `img_path`; `content` preserves the original Markdown table text.
-- All `discarded_blocks` entries are also output (e.g., headers, footers, page numbers, margin notes, page footnotes).
-- Existing types (`image`, `table`, `text`, `equation`) remain unchanged.
-- `bbox` still uses the 0–1000 normalized coordinate mapping.
-- Starting with 3.0, Hybrid multimodal output also emits `*_structured_content.json`; see the Structured Content section above for the shared structure.
-
-
-##### Examples
-Example: code (algorithm) entry
-```json
-{
- "type": "code",
- "sub_type": "algorithm",
- "code_caption": ["Algorithm 1 Modules for MCTSteg"],
- "code_body": "1: function GETCOORDINATE(d) \n2: $x \\gets d / l$ , $y \\gets d$ mod $l$ \n3: return $(x, y)$ \n4: end function \n5: function BESTCHILD(v) \n6: $C \\gets$ child set of $v$ \n7: $v' \\gets \\arg \\max_{c \\in C} \\mathrm{UCTScore}(c)$ \n8: $v'.n \\gets v'.n + 1$ \n9: return $v'$ \n10: end function \n11: function BACK PROPAGATE(v) \n12: Calculate $R$ using Equation 11 \n13: while $v$ is not a root node do \n14: $v.r \\gets v.r + R$ , $v \\gets v.p$ \n15: end while \n16: end function \n17: function RANDOMSEARCH(v) \n18: while $v$ is not a leaf node do \n19: Randomly select an untried action $a \\in A(v)$ \n20: Create a new node $v'$ \n21: $(x, y) \\gets \\mathrm{GETCOORDINATE}(v'.d)$ \n22: $v'.p \\gets v$ , $v'.d \\gets v.d + 1$ , $v'.\\Gamma \\gets v.\\Gamma$ \n23: $v'.\\gamma_{x,y} \\gets a$ \n24: if $a = -1$ then \n25: $v.lc \\gets v'$ \n26: else if $a = 0$ then \n27: $v.mc \\gets v'$ \n28: else \n29: $v.rc \\gets v'$ \n30: end if \n31: $v \\gets v'$ \n32: end while \n33: return $v$ \n34: end function \n35: function SEARCH(v) \n36: while $v$ is fully expanded do \n37: $v \\gets$ BESTCHILD(v) \n38: end while \n39: if $v$ is not a leaf node then \n40: $v \\gets$ RANDOMSEARCH(v) \n41: end if \n42: return $v$ \n43: end function",
- "bbox": [510,87,881,740],
- "page_idx": 0
-}
-```
-
-Example: list (text) entry
-```json
-{
- "type": "list",
- "sub_type": "text",
- "list_items": [
- "H.1 Introduction",
- "H.2 Example: Divide by Zero without Exception Handling",
- "H.3 Example: Divide by Zero with Exception Handling",
- "H.4 Summary"
- ],
- "bbox": [174,155,818,333],
- "page_idx": 0
-}
-```
-
-Example: discarded blocks output
-```json
-[
- {
- "type": "header",
- "text": "Journal of Hydrology 310 (2005) 253-265",
- "bbox": [363,164,623,177],
- "page_idx": 0
- },
- {
- "type": "page_footnote",
- "text": "* Corresponding author. Address: Forest Science Centre, Department of Sustainability and Environment, P.O. Box 137, Heidelberg, Vic. 3084, Australia. Tel.: +61 3 9450 8719; fax: +61 3 9450 8644.",
- "bbox": [71,815,915,841],
- "page_idx": 0
- }
-]
-```
+> [!NOTE]
+> `content_list.json` is deprecated and no longer generated. Use `structured_content.json` for structured content output. See the [Common Structured Content](#common-structured-content-structured_contentjsondevelopment-version-subject-to-change) section above for the shared structure.
## Summary
@@ -735,7 +453,6 @@ The above files constitute MinerU's complete output results. Users can choose ap
- **Content extraction**: (Use simplified files):
* *.md
- * content_list.json
* structured_content.json
- **Secondary development**: (Use structured files):
diff --git a/docs/next/api/changes.md b/docs/next/api/changes.md
index c7913acd..f3cec7b7 100644
--- a/docs/next/api/changes.md
+++ b/docs/next/api/changes.md
@@ -36,6 +36,6 @@ API 不提供在创建请求中同步等待完成的模式,也不内联返回
`images` 不再是 `POST /v1/parse/jobs` 的合法 `output_formats` 值,parse job 响应中也不再返回 `output_files.images`。
-图片 sidecar 只通过 `zip` 产物返回。`markdown`、`middle_json`、`content_list`、`structured_content` 输出仍可能包含 `image_path` 引用,但这些引用对应的图片字节不再作为独立 parse output 暴露。
+图片 sidecar 只通过 `zip` 产物返回。`markdown`、`middle_json`、`structured_content` 输出仍可能包含 `image_path` 引用,但这些引用对应的图片字节不再作为独立 parse output 暴露。
这样可以避免同一批图片同时通过独立 output 和 zip 两条路径返回,减少产物语义重复,并让需要自包含解析结果的客户端统一依赖 `zip`。
diff --git a/docs/next/api/health-models.md b/docs/next/api/health-models.md
index 70b487d1..13aa631c 100644
--- a/docs/next/api/health-models.md
+++ b/docs/next/api/health-models.md
@@ -23,7 +23,7 @@ GET /v1/health HTTP/1.1
"version": "1.0.0",
"features": {
"webhook": true,
- "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "html", "latex", "docx", "zip"],
+ "output_formats": ["markdown", "middle_json", "structured_content", "html", "latex", "docx", "zip"],
"sources": ["file_id", "url", "inline"]
}
}
@@ -169,7 +169,7 @@ Local Parse Server 的 `health` 通常返回:
"version": "1.0.0",
"features": {
"webhook": false,
- "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "zip"],
+ "output_formats": ["markdown", "middle_json", "structured_content", "zip"],
"sources": ["file_id", "url", "inline"]
}
}
diff --git a/docs/next/api/parse-jobs.md b/docs/next/api/parse-jobs.md
index d18d2e2c..0a0461a0 100644
--- a/docs/next/api/parse-jobs.md
+++ b/docs/next/api/parse-jobs.md
@@ -132,7 +132,6 @@ OCR 策略和图片分析能力由 `tier` 与服务端实际引擎自动决定
|------|----------|------|:--:|
| `markdown` | 文本 | Markdown 文本。 | 否 |
| `middle_json` | 文本 | 完整 Middle JSON,中间结构和高级调试。 | 否 |
-| `content_list` | 文本 | 扁平内容列表。 | 否 |
| `structured_content` | 文本 | 面向 Agent 和新客户端的结构化内容 JSON。 | 否 |
| `html` | 文本 | HTML 导出。 | 是 |
| `latex` | 文本 | LaTeX 导出。 | 是 |
@@ -349,7 +348,7 @@ OCR 策略和图片分析能力由 `tier` 与服务端实际引擎自动决定
Local Parse Server 的任务 API 与官方 API 保持同一结构,但有以下实现差异:
- 不支持 Webhook 时,`health.features.webhook` 必须为 `false`;收到 `callback` 时应返回 `400 invalid_request` 或明确忽略。
-- `health.features.output_formats` 必须反映本地 server 实际支持的输出格式;当前本地实现支持 `markdown`、`middle_json`、`content_list`、`structured_content` 和 `zip`。
+- `health.features.output_formats` 必须反映本地 server 实际支持的输出格式;当前本地实现支持 `markdown`、`middle_json`、`structured_content` 和 `zip`。
- `health.features.sources` 必须反映本地 server 实际允许的 source 类型;只有启动时开启 `--allow-local-source` 才包含 `local`。
- `local` source 可以不生成输入 `file_id`;响应中应保留 `name` 和文件级状态。
- 对 PDF/image,省略 `tier` 或传 `null` 时,只能按默认选择策略选择本地可发现的非 `flash` 质量 tier,不能回退到 `flash`;如果只有 `flash` 可用,应返回 `quality_tier_unavailable`。
diff --git a/docs/next/api/uploads-files.md b/docs/next/api/uploads-files.md
index acfe6c62..ee07e83b 100644
--- a/docs/next/api/uploads-files.md
+++ b/docs/next/api/uploads-files.md
@@ -58,7 +58,7 @@ Upload 状态机:
| `purpose` | string | 是 | `"parse"`、`"input_image"` 或 `"parse_output"`。 |
| `sha256sum` | string 或 null | 是 | 64 位小写 hex;未知时为 `null`。 |
-`purpose:"parse"` 表示待解析源文件。`purpose:"input_image"` 表示 Chat/Responses 输入图片。`purpose:"parse_output"` 表示解析产物,如 markdown、middle_json、content_list、structured_content、docx、zip。解析图片 sidecar 不作为独立 parse output;需要图片时从 zip 中读取。
+`purpose:"parse"` 表示待解析源文件。`purpose:"input_image"` 表示 Chat/Responses 输入图片。`purpose:"parse_output"` 表示解析产物,如 markdown、middle_json、structured_content、docx、zip。解析图片 sidecar 不作为独立 parse output;需要图片时从 zip 中读取。
## POST `/v1/uploads`
diff --git a/docs/next/cli/mineru-kit-parse.md b/docs/next/cli/mineru-kit-parse.md
index 6c549f15..acd287fe 100644
--- a/docs/next/cli/mineru-kit-parse.md
+++ b/docs/next/cli/mineru-kit-parse.md
@@ -105,7 +105,6 @@ local 模式支持:
- `--tier`
- `--backend`
-- `--effort`
规则:
@@ -144,10 +143,10 @@ remote 模式通过以下参数进入:
| 分组 | 示例 |
|------|------|
| 文档参数 | pages、language、ocr-mode |
-| local 模式 | tier、backend、effort、disable-image-analysis |
+| local 模式 | tier、backend、disable-image-analysis |
| remote 模式 | remote、remote-url、api-key |
| 输出控制 | format、output |
-local 模式的 `language`、`ocr-mode`、`effort`、`disable-image-analysis` 与 `mineru-kit api-server` 保持一致。
+local 模式的 `language`、`ocr-mode`、`tier`、`disable-image-analysis` 与 `mineru-kit api-server` 保持一致。
完整决策背景见 [ADR-0016](../decisions/0016-mineru-kit-parse-command.md)。
diff --git a/docs/next/glossary.md b/docs/next/glossary.md
index 80ca910e..96c13a56 100644
--- a/docs/next/glossary.md
+++ b/docs/next/glossary.md
@@ -111,11 +111,7 @@
|--------|------|
| `parse()` | Tool SDK 的便捷函数 |
| `DocumentParser` | Parser 抽象接口 |
-| `PdfPipelineParser` | 旧 SDK 兼容类,内部委托 Hybrid medium effort |
-| `PdfVlmParser` | 调用 VLM backend 的 parser |
-| `PdfHybridParser` | 调用 hybrid backend 的 parser |
-| `DocxParser` / `PptxParser` / `XlsxParser` | Office parser |
-| `HtmlParser` | HTML parser |
+| `MinerUParser` | 统一解析器,支持 PDF/图片/DOCX/PPTX/XLSX |
| `MinerUApiParser` | 通过 v1 API 委托解析的 parser |
规范:
diff --git a/docs/next/middle-json.md b/docs/next/middle-json.md
index 06dc04d0..2cb61422 100644
--- a/docs/next/middle-json.md
+++ b/docs/next/middle-json.md
@@ -1,34 +1,34 @@
# Middle JSON
状态: Draft
-读者: backend 开发者、Markdown/Content List 输出开发者、SDK 开发者、Agent 能力开发者
-范围: Middle JSON 的当前事实标准、Agent-native gap、统一 envelope、迁移策略和验收清单
+读者: backend 开发者、Markdown/Structured Content 输出开发者、SDK 开发者、Agent 能力开发者
+范围: Middle JSON schema 2.0 事实标准、Agent-native gap、统一 envelope、迁移策略和验收清单
非目标: 具体 OCR 或模型算法实现
来源: 由根目录旧 Middle JSON 底稿迁移整理而来
## 当前定位
-Middle JSON 已经有一个事实标准: `mineru/types.py` 中的 `PageInfo`、`Block`、`Line`、`Span` dataclass。下一阶段的重点不是从零定义 schema,而是把现有类型、旧输出格式、各 backend 差异和 Agent-native 需求收敛成可执行的统一方案。
+Middle JSON 已经收敛为 schema 2.0 的严格 Pydantic 模型:`mineru/types.py` 中的 `MiddleJson`、`PageInfo`、`BlockBase`/`TextBlock`/`ImageBlock`/`EquationBlock` 等类型。下一阶段的重点是把这些类型、统一渲染入口和 Agent-native 需求收敛成可执行方案。
## 目录
1. [总览](middle-json/README.md): 当前事实、目标和工作分层。
-2. [当前事实标准](middle-json/current-medium.md): `PageInfo` / `Block` / `Line` / `Span` 的现状。
-3. [Backend 差异](middle-json/backend-gaps.md): Pipeline / VLM / Hybrid / Office / HTML 的已解决和未解决问题。
+2. [当前事实标准](middle-json/current-medium.md): `MiddleJson` / `PageInfo` / `BlockBase` / `TextBlock` / `ImageBlock` 等 Pydantic 模型的现状。
+3. [Backend 差异](middle-json/backend-gaps.md): `tier`(flash/basic/standard/advanced)在 `backend/analysis` 与 `backend/postprocess` 上的已解决和未解决问题。
4. [Agent-native Gap](middle-json/agent-gaps.md): 引用、定位、稳定性和隐私边界。
5. [Canonical Envelope](middle-json/envelope.md): 顶层结构、`_meta`、版本和兼容输入。
6. [当前 Content List v2 结构盘点](middle-json/structured-content-current.md): 当前 Structured Content 起点的事实结构。
7. [Structured Content Schema](middle-json/structured-content-schema.md): NEXT 版结构化内容 JSON 的目标 schema 草案。
-8. [Rendering Contract](middle-json/rendering.md): Markdown / Content List / Structured Content 如何消费 middle structure。
+8. [Rendering Contract](middle-json/rendering.md): Markdown / HTML / DOCX / Structured Content 如何通过 `render/api.py` 消费 middle structure。
9. [迁移计划](middle-json/migration.md): 可执行阶段、任务清单和验收标准。
## 整理原则
-- 以当前代码中的 typed dataclass 为起点。
+- 以当前代码中的 Pydantic 严格模型为起点(schema 2.0)。
- 区分“已经解决”、“部分解决”、“仍需工作”。
- Agent 引用与稳定 page/block locator 是 P0 目标。
-- schema 版本和迁移函数必须能处理历史数据。
-- render 统一不能只看入口 facade,还要收敛 backend-specific 分支。
+- schema 版本和迁移函数必须能处理历史数据(1.0 payload 经 `legacy_schema_adapter` 回推)。
+- render 统一不能只看入口 facade,还要收敛格式-specific 分支。
## 与其他文档的关系
diff --git a/docs/next/middle-json/backend-gaps.md b/docs/next/middle-json/backend-gaps.md
index 7ae84668..f9108ef0 100644
--- a/docs/next/middle-json/backend-gaps.md
+++ b/docs/next/middle-json/backend-gaps.md
@@ -75,7 +75,7 @@
仍需工作:
1. 明确 VLM block 粒度与 Pipeline OCR 粒度的兼容语义。
-2. 统一 VLM-specific type 在 content_list / Agent citation 中的表达。
+2. 统一 VLM-specific type 在 structured_content / Agent citation 中的表达。
3. 确认归一化坐标绝不进入 public Middle JSON。
4. 确认 VLM/Hybrid 与 Pipeline 在统一 structured_content converter 下的字段一致性。
@@ -146,21 +146,20 @@
现状:
-- `HtmlParser` 已存在,但当前构造 `Span` / `Block` / `Line` 时存在与 dataclass 必填字段不一致的风险。
- HTML 输出映射到单页 `PageInfo(page_idx=0)`。
- page_size、bbox、index 策略尚未稳定。
仍需工作:
-1. 修正 `HtmlParser` 所有 `Span` / `Line` / `Block` 构造,补齐 `bbox` 和 `index`。
+1. 修正 HTML 所有 `Span` / `Line` / `Block` 构造,补齐 `bbox` 和 `index`。
2. 定义 HTML 的 page_size。可以为 `None`,但要明确。
3. 为 DOM order 生成稳定 block index。
4. 明确 HTML `img src`、table html、code block 的 locator 和隐私策略。
验收:
-- HTML parser 单测覆盖常见标签。
-- HTML 输出可 render markdown/content_list。
+- HTML 单测覆盖常见标签。
+- HTML 输出可 render markdown/structured_content。
- HTML 输出可通过 validator。
## 跨 backend 工作项
diff --git a/docs/next/middle-json/migration.md b/docs/next/middle-json/migration.md
index 274e1173..5d5a2d3b 100644
--- a/docs/next/middle-json/migration.md
+++ b/docs/next/middle-json/migration.md
@@ -141,7 +141,7 @@
1. 实现 `normalize_middle_json()`。
2. 增加 envelope-level validator。
-3. 修正 `HtmlParser` 必填字段。
+3. 修正 HTML 解析必填字段。
4. 定义 `locator_for_block()`。
5. 给 Pipeline/VLM/Office 各加一个 fixture。
6. 设计历史 `pdf_info` 离线 migration。
diff --git a/docs/next/sdk/migration.md b/docs/next/sdk/migration.md
index cb1bc1c7..0854d612 100644
--- a/docs/next/sdk/migration.md
+++ b/docs/next/sdk/migration.md
@@ -55,7 +55,7 @@ SDK 迁移的目标不是重写现有 parser,而是稳定已经成形的边界
- 本地 parser result 可以 round-trip: `to_json()` -> `from_json()`。
- API `middle_json` output 可以恢复为 `ParseResult`。
-- Office/PDF/HTML 的 markdown 和 content_list 输出不回退。
+- Office/PDF/HTML 的 markdown 和 structured_content 输出不回退。
## Phase 3: Tier 进入 Tool SDK
diff --git a/docs/next/sdk/parse-result.md b/docs/next/sdk/parse-result.md
index 3644a14b..7644e271 100644
--- a/docs/next/sdk/parse-result.md
+++ b/docs/next/sdk/parse-result.md
@@ -12,7 +12,7 @@
它承担两件事:
- 持有结构化 pages。
-- 基于 pages 派生 markdown、content list、images 等输出。
+- 基于 pages 派生 markdown、structured content、images 等输出。
## 当前字段
@@ -43,7 +43,6 @@ class ParseResult:
def from_json(s: str) -> "ParseResult": ...
def markdown(self, *, add_markers: bool = False) -> str: ...
- def content_list(self) -> list[dict]: ...
def structured_content(self) -> list[list[dict]]: ...
def images(self) -> dict[str, bytes]: ...
def save(self, writer) -> None: ...
@@ -58,7 +57,6 @@ class ParseResult:
| `from_dict()` | 已有 | 保持,用于 API JSON / 缓存恢复;继续收紧兼容边界。 |
| `from_json()` | 已有 | 保持。 |
| `markdown()` | 已有 | 保持,参数名稳定。 |
-| `content_list()` | 已有 | 保持。 |
| `structured_content()` | 已有 | 保持。 |
| `images()` | 已有 | 保持,返回 path -> bytes。 |
| `save()` | 已有 | 需要稳定输出文件命名。 |
@@ -125,7 +123,6 @@ writer.write(path: str, data: bytes) -> None
|------|------|
| `{prefix}.md` | Markdown。 |
| `{prefix}_middle.json` | `to_json()`。 |
-| `{prefix}_content_list.json` | content list。 |
| `{prefix}_structured_content.json` | structured content。 |
| `{prefix}_model.json` | 原始模型输出,可选。 |
| image paths | 图片 bytes。 |
@@ -139,7 +136,7 @@ writer.write(path: str, data: bytes) -> None
SDK 设计约束:
- `ParseResult` 可以暴露 `pages` 给高级用户。
-- 普通用户应通过 `markdown()`、`content_list()`、`images()` 消费结果。
+- 普通用户应通过 `markdown()`、`structured_content()`、`images()` 消费结果。
- middle structure 的 schema 变化应通过 `from_dict()` 做兼容。
## 未决问题
diff --git a/docs/next/sdk/parser.md b/docs/next/sdk/parser.md
index 9afb549c..4c405fad 100644
--- a/docs/next/sdk/parser.md
+++ b/docs/next/sdk/parser.md
@@ -2,12 +2,12 @@
状态: Draft
读者: SDK 开发者、`mineru-kit` 开发者、核心开发者
-范围: 无状态解析工具层的公开入口、parser 类和目标契约
+范围: 无状态解析工具层的公开入口、统一 parser 类和目标契约
来源: 由旧 SDK 底稿迁移整理而来;旧底稿已归档删除
## 定位
-`mineru.parser` 是无状态解析 SDK。它接受本地文件路径,按文件类型和 backend 选择具体 parser,返回 `ParseResult`。
+`mineru.parser` 是无状态解析 SDK。它接受本地文件路径,由统一的 `MinerUParser` 完成解析,返回 `ParseResult`。
适用场景:
@@ -29,38 +29,58 @@
| 名称 | 类型 | 说明 |
|------|------|------|
-| `parse` | function | 根据文件后缀和 backend 分派到具体 parser。 |
-| `DocumentParser` | abstract class | 所有 parser 的统一接口。 |
+| `parse` | function | 根据文件后缀和参数构造 `MinerUParser` 并执行解析。 |
+| `parse_async` | function | `parse` 的异步版本。 |
+| `MinerUParser` | class | 统一解析器,支持 PDF/图片/DOCX/PPTX/XLSX。 |
| `ParseResult` | dataclass | 解析结果对象。 |
-| `PdfFlashParser` | class | CPU-only PDF/image 快速解析。 |
-| `PdfPipelineParser` | class | 旧 SDK 兼容类,内部委托 Hybrid medium effort。 |
-| `PdfVlmParser` | class | VLM backend。 |
-| `PdfHybridParser` | class | hybrid backend。 |
-| `DocxParser` | class | DOCX parser。 |
-| `PptxParser` | class | PPTX parser。 |
-| `XlsxParser` | class | XLSX parser。 |
-| `HtmlParser` | class | HTML parser。 |
| `MinerUApiParser` | class | API-backed parser,详见 [API-backed Parser](api-parser.md)。 |
-## `parse()` 目标契约
+## `MinerUParser`
-目标公开签名:
+`MinerUParser` 是 `mineru.parser` 中唯一的本地解析器类。过去按文件类型/后端分散的多个 parser 类以及内部路由函数已统一合并到 `MinerUParser`。
+
+导入方式:
+
+```python
+from mineru.parser import MinerUParser
+```
+
+构造参数(关键字参数):
+
+| 参数 | 类型 | 说明 |
+|------|------|------|
+| `tier` | `Literal["flash","basic","standard","advanced"]` | 解析投入档位,对应原 SDK 的 `effort` 概念。 |
+| `parse_mode` | `str` | 解析模式,对应原 SDK 的 `parse_mode`/`backend` 概念。 |
+| `image_analysis` | `bool` | 是否启用图片分析。对应原 SDK 的 `disable_image_analysis` 取反语义。 |
+
+`MinerUParser` 根据 `tier` / `parse_mode` / `image_analysis` 以及输入文件后缀,在内部选择具体的 PDF/Office 解析路径,不再要求调用方分别实例化不同 parser 类。
+
+支持输入:
+
+- PDF
+- 图片(PNG/JPEG 等)
+- DOCX
+- PPTX
+- XLSX
+
+## `parse()` / `parse_async()` 入口
+
+`parse()` 与 `parse_async()` 是面向用户的便捷函数。它们在内部直接构造 `MinerUParser`,不再经过额外路由函数。
+
+公开签名保持稳定:
```python
from pathlib import Path
+from typing import Literal
from mineru.parser import ParseResult
def parse(
path: str | Path,
*,
- tier: str | None = None,
- backend: str | None = None,
- language: str = "ch",
- ocr_mode: str = "auto",
- effort: str = "high",
- disable_image_analysis: bool = False,
- server_url: str | None = None,
- page_range: str = "",
+ tier: Literal["flash","basic","standard","advanced"] | None = None,
+ parse_mode: str | None = None,
+ image_analysis: bool = False,
+ **kwargs,
) -> ParseResult: ...
async def parse_async(...) -> ParseResult: ...
@@ -68,20 +88,15 @@ async def parse_async(...) -> ParseResult: ...
设计规则:
-- `tier` 是面向用户的质量档位。
-- `backend` 是高级参数;显式传入时覆盖 `tier`。
-- `language`、`ocr_mode`、`effort`、`disable_image_analysis` 与 `mineru-kit api-server` 启动参数保持一致。
-- `page_range` 使用与 CLI/API 一致的页码表达。
-- `server_url` 只用于需要委托 VLM/remote backend 的情况,不能触发隐式远端上传。
+- `tier` / `parse_mode` / `image_analysis` 与 `MinerUParser` 的构造参数一致。
- 返回值始终是 `ParseResult`。
+- `parse_async()` 默认可以通过线程池调用同步实现。
-`method`、`lang`、`image_analysis` 仅作为兼容参数保留;新增实现和文档应使用 `ocr_mode`、`language` 和 `disable_image_analysis`。
-
-`mineru-kit api-server` 内部应复用 `parse_async()`,避免在 server 层重复维护 parser dispatch 和 tier/backend 兼容规则。
+`mineru-kit api-server` 内部应复用 `parse_async()`,避免在 server 层重复维护 parser dispatch 和兼容规则。
## `DocumentParser`
-所有 parser 都应实现:
+`MinerUParser` 实现统一 parser 接口:
```python
class DocumentParser:
@@ -99,32 +114,6 @@ class DocumentParser:
- `parse_batch()` 默认按顺序解析;能批处理的 parser 可以覆盖。
- parser 可以作为 context manager 使用,退出时调用 `close()`。
-## Parser 类
-
-| Parser | 输入 | 主要 backend | 说明 |
-|--------|------|--------------|------|
-| `PdfFlashParser` | PDF/image | flash | CPU-only,快速但质量最低,主要用于发现和索引。 |
-| `PdfPipelineParser` | PDF/image | Hybrid medium effort | 旧 SDK 兼容类,等价于 `PdfHybridParser(effort="medium")`。 |
-| `PdfVlmParser` | PDF/image | VLM | VLM 解析,可通过 server URL 委托。 |
-| `PdfHybridParser` | PDF/image | hybrid | 本地小模型 + VLM 混合解析。 |
-| `DocxParser` | DOCX | office | Office 文档解析。 |
-| `PptxParser` | PPTX | office | Office 文档解析。 |
-| `XlsxParser` | XLSX | office | Office 文档解析。 |
-| `HtmlParser` | HTML/HTM | html | HTML 转结构化 blocks。 |
-
-## Tier 到 backend
-
-目标映射:
-
-| Tier | 默认 backend | 说明 |
-|------|--------------|------|
-| `flash` | `flash` | 快速 CPU-only。 |
-| `basic` | `hybrid-engine` + `effort="medium"` | 消费级硬件可用的本地小模型组合。 |
-| `standard` | hybrid 默认高质量 backend | 绝大多数场景足够好的高质量档位。 |
-| `advanced` | hybrid backend + 更高 effort | 最高质量档位,用更多算力和时间换取小幅质量提升。 |
-
-`tier=None` 表示使用默认选择策略。PDF/image 直接本地解析且没有能力列表时默认 `standard`,有能力发现上下文时按 `standard` -> `advanced` -> `basic` 选择;Office/HTML 这类仅支持 flash tier 的输入未指定 tier 时归一为 `flash`,显式质量 tier 应报错。完整 tier 语义见 [解析 Tier](../tiers.md) 和 [ADR-0024](../decisions/0024-file-type-tier-normalization.md)。
-
## 重依赖边界
公开 import 不应触发 torch、transformers、模型权重或解析 server 启动。重依赖应在 parser 构造或执行时惰性加载。
@@ -132,9 +121,7 @@ class DocumentParser:
目标:
- `from mineru.parser import parse, ParseResult` 应足够轻。
-- `PdfPipelineParser` 仅作为旧 SDK 类名保留,内部走 Hybrid medium effort,不再加载独立 pipeline backend。
-- `PdfVlmParser` / `PdfHybridParser` 只在执行 VLM/hybrid 时加载对应 backend。
-- Office parser 可以在构造时绑定 analyze function,但不应在模块 import 时加载重依赖。
+- `MinerUParser` 只在执行对应解析路径时加载重依赖,不应在模块 import 时加载。
## 示例
@@ -148,13 +135,13 @@ print(result.markdown())
高级用法:
```python
-from mineru.parser import PdfHybridParser
+from mineru.parser import MinerUParser
-with PdfHybridParser(method="txt", lang="ch", effort="medium") as parser:
+with MinerUParser(tier="basic") as parser:
result = parser.parse("report.pdf", page_range="1~10")
images = result.images()
```
## 未决问题
-`server_url` 归属、`parse_batch()` 进度回调等未决项集中维护在 [开放问题清单](../open-questions.md)。`parse()` 支持 `tier` 已作为目标契约写入正文。
+`parse_batch()` 进度回调等未决项集中维护在 [开放问题清单](../open-questions.md)。
diff --git a/docs/next/workflows.md b/docs/next/workflows.md
index 3dc89f7d..f77d7486 100644
--- a/docs/next/workflows.md
+++ b/docs/next/workflows.md
@@ -438,12 +438,12 @@ from mineru.parser import parse
result = parse("report.pdf", tier="basic")
```
-或使用具体 parser:
+或使用统一 parser 类:
```python
-from mineru.parser import PdfHybridParser
+from mineru.parser import MinerUParser
-with PdfHybridParser(effort="medium") as parser:
+with MinerUParser(tier="basic") as parser:
result = parser.parse("report.pdf")
```
@@ -506,7 +506,6 @@ doclib 解析产物按内容和实际使用的 tier 隔离。`parsed/` 目录下
doclib 不在 `parsed/` 中保存:
- `output.md`
-- `content_list.json`
- `structured_content.json`
PDF 和 image block 图片通常在读取时从源页面按 bbox 裁剪,不写入 `images/`。无 bbox 的 visual block 只有在对应 sidecar 文件存在时才输出非空图片 locator。
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index a88c049e..e95c2d6e 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -55,9 +55,9 @@
## 结构化数据文件
> [!IMPORTANT]
-> 当前结构化输出合约仅使用 `hybrid` 和 `office` 后端。旧 middle-json 中标记 `_backend: "pipeline"` 的产物不再被当前读取逻辑兼容。
+> 当前结构化输出合约使用统一的 `MinerUParser`,通过 `tier`(flash/basic/standard/advanced)和 `parse_mode`(txt/ocr)参数控制。旧 middle-json 中标记 `_backend: "pipeline"`/`_backend: "hybrid"`/`_backend: "office"` 的产物不再被当前读取逻辑兼容,请使用 schema 2.0 的 `MiddleJson`。
-### Hybrid 本地模型输出结果
+### 统一模型输出结果
#### 模型推理结果 (model.json)
@@ -68,40 +68,40 @@
```json
[
{
- "cls_id": 12,
- "label": "header",
- "score": 0.93,
- "bbox": [
+ “cls_id”: 12,
+ “label”: “header”,
+ “score”: 0.93,
+ “bbox”: [
1217,
104,
1516,
134
],
- "index": 2
+ “index”: 2
},
{
- "cls_id": 6,
- "label": "doc_title",
- "score": 0.9751,
- "bbox": [
+ “cls_id”: 6,
+ “label”: “doc_title”,
+ “score”: 0.9751,
+ “bbox”: [
275,
181,
1512,
292
],
- "index": 3
+ “index”: 3
},
{
- "cls_id": 22,
- "label": "text",
- "score": 0.9217,
- "bbox": [
+ “cls_id”: 22,
+ “label”: “text”,
+ “score”: 0.9217,
+ “bbox”: [
275,
330,
524,
370
],
- "index": 4
+ “index”: 4
}
]
```
@@ -110,288 +110,119 @@
**文件命名格式**:`{原文件名}_middle.json`
-##### 顶层结构
+##### 顶层结构(schema 2.0)
| 字段名 | 类型 | 说明 |
|--------|------|------|
-| `pdf_info` | `list[dict]` | 每一页的解析结果数组 |
-| `_backend` | `string` | 解析模式:`hybrid` 或 `office` |
-| `_version_name` | `string` | MinerU 版本号 |
+| `pages` | `list[PageInfo]` | 每一页的解析结果数组,按 `page_idx` 严格升序 |
+| `file_suffix` | `string` | 输入文件类型:`pdf`、`docx`、`pptx` 或 `xlsx` |
+| `effort` | `string` | 分析强度:`flash`、`low`、`medium`、`high` 或 `xhigh` |
+| `parse_mode` | `string` | 解析模式:`txt` 或 `ocr` |
+| `mineru_version` | `string` | MinerU 版本号 |
-##### 页面信息结构 (pdf_info)
+schema 2.0 已移除旧字段 `pdf_info`/`_backend`/`_version_name`/`_ocr_enable`/`_vlm_ocr_enable`。
+
+##### 页面信息结构 (pages)
| 字段名 | 说明 |
|--------|------|
-| `preproc_blocks` | PDF 预处理后的未分段中间结果 |
| `page_idx` | 页码,从 0 开始 |
-| `page_size` | 页面的宽度和高度 `[width, height]` |
-| `images` | 图片块信息列表 |
-| `tables` | 表格块信息列表 |
-| `interline_equations` | 行间公式块信息列表 |
-| `discarded_blocks` | 需要丢弃的块信息 |
-| `para_blocks` | 分段后的内容块结果 |
+| `blocks` | 顶层页面块列表(唯一内容字段) |
+
+schema 2.0 已移除旧字段 `preproc_blocks`/`para_blocks`/`page_size`/`images`/`tables`/`interline_equations`/`discarded_blocks`/`_layout_tree`/`layout_bboxes`——所有内容统一在 `blocks` 树里表达。
##### 块结构层次
```
-一级块 (table | image | chart)
-└── 二级块
- └── 行 (line)
- └── 片段 (span)
+顶层页面块 (text | title | equation | image | table | chart | code | list | index | ...)
+└── 视觉父块 (image | table | chart | code) 包含子块
+ └── body 块 + 可选 caption/footnote 块
```
-##### 一级块字段
+叶子块(text、title、equation 等)直接持有 `content: str`。视觉父块(image、table、chart、code)持有 `content: list[子块]`,子块包含唯一 body 加可选 caption/footnote。schema 2.0 不再有独立的 `Line`/`Span` 类型。
-| 字段名 | 说明 |
-|--------|------|
-| `type` | 块类型:`table`、`image` 或 `chart` |
-| `bbox` | 块的矩形框坐标 `[x0, y0, x1, y1]` |
-| `blocks` | 包含的二级块列表 |
-
-##### 二级块字段
+##### 通用块字段
| 字段名 | 说明 |
|--------|------|
| `type` | 块类型(详见下表) |
-| `bbox` | 块的矩形框坐标 |
-| `lines` | 包含的行信息列表 |
+| `bbox` | 块的矩形框坐标 `[x0, y0, x1, y1]`,归一化到 `[0, 1]` |
+| `index` | 块的阅读序号(顶层块必填) |
+| `content` | 叶子块为字符串;视觉父块为子块列表 |
-##### 二级块类型
+##### 块类型
| 类型 | 说明 |
|------|------|
-| `image_body` | 图像本体 |
-| `image_caption` | 图像描述文本 |
-| `image_footnote` | 图像脚注 |
-| `table_body` | 表格本体 |
-| `table_caption` | 表格描述文本 |
-| `table_footnote` | 表格脚注 |
-| `chart_body` | 图表本体 |
-| `chart_caption` | 图表描述文本 |
-| `chart_footnote` | 图表脚注 |
-| `text` | 文本块 |
-| `title` | 标题块 |
-| `index` | 目录块 |
-| `list` | 列表块 |
-| `interline_equation` | 行间公式块 |
-
-##### 行和片段结构
-
-**行 (line) 字段**:
-- `bbox`:行的矩形框坐标
-- `spans`:包含的片段列表
-
-**片段 (span) 字段**:
-- `bbox`:片段的矩形框坐标
-- `type`:片段类型(`image`、`table`、`chart`、`text`、`inline_equation`、`interline_equation`)
-- `content` | `image_path`:文本内容或图片路径
-
-##### 示例数据
+| `text` | 文本块(叶子块,`content: str`) |
+| `doc_title` | 文档标题(level=1) |
+| `paragraph_title` | 段落标题(level 2-6) |
+| `equation` | 行间公式块(由 `interline_equation` 重命名) |
+| `image` | 图片容器;`content` 包含 `image_body` + 可选 `image_caption`/`image_footnote` |
+| `table` | 表格容器;`content` 包含 `table_body` + 可选 `table_caption`/`table_footnote` |
+| `chart` | 图表容器;`content` 包含 `chart_body` + 可选 `chart_caption`/`chart_footnote` |
+| `code` | 代码容器;`content` 包含 `code_body` + 可选 `code_caption`/`code_footnote`;`sub_type` 为 `code` 或 `algorithm` |
+| `list` | 列表容器;`content` 为 `text`/`ref_text`/嵌套 `list` 块列表;`sub_type` 为 `text` 或 `ref_text` |
+| `index` | 目录容器;`content` 为 `text`/`doc_title`/`paragraph_title`/嵌套 `index` 块列表 |
+| `ref_text` | 参考文献/引用文本块 |
+| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | 页面辅助块(叶子块,`content: str`) |
+
+##### 示例数据(schema 2.0)
```json
{
- "pdf_info": [
+ “pages”: [
{
- "preproc_blocks": [
+ “page_idx”: 0,
+ “blocks”: [
{
- "type": "text",
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 82.99800872802734
- ],
- "lines": [
- {
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 72.0000228881836
- ],
- "spans": [
- {
- "bbox": [
- 54.0,
- 61.956024169921875,
- 296.2261657714844,
- 72.0000228881836
- ],
- "content": "dependent on the service headway and the reliability of the departure ",
- "type": "text",
- "score": 1.0
- }
- ]
- }
- ]
- }
- ],
- "layout_bboxes": [
+ “type”: “doc_title”,
+ “index”: 0,
+ “bbox”: [0.45, 0.23, 0.55, 0.28],
+ “content”: “1 Introduction”,
+ “level”: 1
+ },
{
- "layout_bbox": [
- 52,
- 61,
- 294,
- 731
- ],
- "layout_label": "V",
- "sub_layout": []
- }
- ],
- "page_idx": 0,
- "page_size": [
- 612.0,
- 792.0
- ],
- "_layout_tree": [],
- "images": [],
- "tables": [],
- "interline_equations": [],
- "discarded_blocks": [],
- "para_blocks": [
+ “type”: “text”,
+ “index”: 1,
+ “bbox”: [0.08, 0.30, 0.46, 0.40],
+ “content”: “dependent on the service headway and the reliability of the departure”
+ },
{
- "type": "text",
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 82.99800872802734
- ],
- "lines": [
+ “type”: “image”,
+ “index”: 2,
+ “bbox”: [0.52, 0.30, 0.95, 0.55],
+ “content”: [
+ {
+ “type”: “image_body”,
+ “index”: 2,
+ “bbox”: [0.52, 0.30, 0.95, 0.55],
+ “content”: “”,
+ “image_path”: “images/page_0_image_body_2.png”
+ },
{
- "bbox": [
- 52,
- 61.956024169921875,
- 294,
- 72.0000228881836
- ],
- "spans": [
- {
- "bbox": [
- 54.0,
- 61.956024169921875,
- 296.2261657714844,
- 72.0000228881836
- ],
- "content": "dependent on the service headway and the reliability of the departure ",
- "type": "text",
- "score": 1.0
- }
- ]
+ “type”: “image_caption”,
+ “index”: 3,
+ “bbox”: [0.52, 0.56, 0.95, 0.58],
+ “content”: “Figure 1: Example figure”
}
- ]
+ ],
+ “sub_type”: null
}
]
}
],
- "_backend": "hybrid",
- "_version_name": "0.6.1"
+ “file_suffix”: “pdf”,
+ “effort”: “high”,
+ “parse_mode”: “ocr”,
+ “mineru_version”: “1.x.x”
}
```
#### 内容列表 (content_list.json)
-**文件命名格式**:`{原文件名}_content_list.json`
-
-##### 功能说明
-
-这是一个简化版的 `middle.json`,按阅读顺序平铺存储所有可读内容块,去除了复杂的布局信息,便于后续处理。
-
-##### 内容类型
-
-| 类型 | 说明 |
-|------|------|
-| `image` | 图片 |
-| `table` | 表格 |
-| `chart` | 图表 |
-| `text` | 文本/标题 |
-| `equation` | 行间公式 |
-| `code` | 代码块 / 算法块 |
-| `list` | 列表 / 参考文献列表 |
-| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | 页面辅助块 |
-
-##### 文本层级标识
-
-通过 `text_level` 字段区分文本层级:
-
-- 无 `text_level` 或 `text_level: 0`:正文文本
-- `text_level: 1`:一级标题
-- `text_level: 2`:二级标题
-- 以此类推...
-
-##### 通用字段
-
-- 所有内容块都包含 `page_idx` 字段,表示所在页码(从 0 开始)。
-- 所有内容块都包含 `bbox` 字段,表示内容块的边界框坐标 `[x0, y0, x1, y1]` 映射在0-1000范围内的结果。
-- `code` 类型会通过 `sub_type` 区分 `code` 和 `algorithm`,并可包含 `code_body`、`code_caption`、`code_footnote` 等字段。
-- `list` 类型可通过 `sub_type` 区分普通列表和参考文献列表。
-- `image` / `chart` 类型可包含可选 `sub_type` 字段,用于透传视觉子类型。
-- 印章内容通过 `sub_type: "seal"` 的 `image` 类型表示。
-
-##### 示例数据
-
-```json
-[
- {
- "type": "text",
- "text": "The response of flow duration curves to afforestation ",
- "text_level": 1,
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 0
- },
- {
- "type": "image",
- "img_path": "images/a8ecda1c69b27e4f79fce1589175a9d721cbdc1cf78b4cc06a015f3746f6b9d8.jpg",
- "image_caption": [
- "Fig. 1. Annual flow duration curves of daily flows from Pine Creek, Australia, 1989–2000. "
- ],
- "image_footnote": [],
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 1
- },
- {
- "type": "equation",
- "img_path": "images/181ea56ef185060d04bf4e274685f3e072e922e7b839f093d482c29bf89b71e8.jpg",
- "text": "$$\nQ _ { \\% } = f ( P ) + g ( T )\n$$",
- "text_format": "latex",
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 2
- },
- {
- "type": "table",
- "img_path": "images/e3cb413394a475e555807ffdad913435940ec637873d673ee1b039e3bc3496d0.jpg",
- "table_caption": [
- "Table 2 Significance of the rainfall and time terms "
- ],
- "table_footnote": [
- "indicates that the rainfall term was significant at the $5 \\%$ level, $T$ indicates that the time term was significant at the $5 \\%$ level, \\* represents significance at the $10 \\%$ level, and na denotes too few data points for meaningful analysis. "
- ],
- "table_body": "<html><body><table><tr><td rowspan=\"2\">Site</td><td colspan=\"10\">Percentile</td></tr><tr><td>10</td><td>20</td><td>30</td><td>40</td><td>50</td><td>60</td><td>70</td><td>80</td><td>90</td><td>100</td></tr><tr><td>Traralgon Ck</td><td>P</td><td>P,*</td><td>P</td><td>P</td><td>P,</td><td>P,</td><td>P,</td><td>P,</td><td>P</td><td>P</td></tr><tr><td>Redhill</td><td>P,T</td><td>P,T</td><td>,*</td><td>**</td><td>P.T</td><td>P,*</td><td>P*</td><td>P*</td><td>*</td><td>,*</td></tr><tr><td>Pine Ck</td><td></td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td><td>T</td><td>na</td><td>na</td></tr><tr><td>Stewarts Ck 5</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P.T</td><td>P.T</td><td>P,T</td><td>na</td><td>na</td><td>na</td></tr><tr><td>Glendhu 2</td><td>P</td><td>P,T</td><td>P,*</td><td>P,T</td><td>P.T</td><td>P,ns</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td></tr><tr><td>Cathedral Peak 2</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Cathedral Peak 3</td><td>P.T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Lambrechtsbos A</td><td>P,T</td><td>P</td><td>P</td><td>P,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>T</td></tr><tr><td>Lambrechtsbos B</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td></tr><tr><td>Biesievlei</td><td>P,T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>*,T</td><td>T</td><td>T</td><td>P,T</td><td>P,T</td></tr></table></body></html>",
- "bbox": [
- 62,
- 480,
- 946,
- 904
- ],
- "page_idx": 5
- }
-]
-```
+> [!NOTE]
+> `content_list.json` 已废弃,不再生成。结构化内容输出请使用 `structured_content.json`,详见下文”通用结构化内容”章节。
### 通用结构化内容 (structured_content.json)(开发中,格式可能调整)
@@ -399,7 +230,7 @@
##### 功能说明
-`structured_content.json` 是 3.0 起新增的结构化输出文件,所有后端都会在保留 `content_list.json` 的同时额外输出该文件:
+`structured_content.json` 是 3.0 起新增的结构化输出文件,所有后端都会输出该文件:
- 顶层是按页分组的列表,便于按页消费结果
- 每个内容块使用统一的 `type + content` 结构,适合程序化处理
@@ -478,7 +309,7 @@
]
```
-### Hybrid 多模态输出结果
+### 多模态模型输出结果
#### 模型推理结果 (model.json)
@@ -486,7 +317,7 @@
##### 文件格式说明
-- 该文件为 Hybrid 多模态模型的原始输出结果,包含两层嵌套list,外层表示页面,内层表示该页的内容块
+- 该文件为多模态模型的原始输出结果,包含两层嵌套list,外层表示页面,内层表示该页的内容块
- 每个内容块都是一个dict,包含 `type`、`bbox`、`angle`、`content` 字段
@@ -494,26 +325,26 @@
```json
{
- "text": "文本",
- "title": "标题",
- "equation": "行间公式",
- "image": "图片",
- "image_caption": "图片描述",
- "image_footnote": "图片脚注",
- "table": "表格",
- "table_caption": "表格描述",
- "table_footnote": "表格脚注",
- "phonetic": "拼音",
- "code": "代码块",
- "code_caption": "代码描述",
- "ref_text": "参考文献",
- "algorithm": "算法块",
- "list": "列表",
- "header": "页眉",
- "footer": "页脚",
- "page_number": "页码",
- "aside_text": "装订线旁注",
- "page_footnote": "页面脚注"
+ “text”: “文本”,
+ “title”: “标题”,
+ “equation”: “行间公式”,
+ “image”: “图片”,
+ “image_caption”: “图片描述”,
+ “image_footnote”: “图片脚注”,
+ “table”: “表格”,
+ “table_caption”: “表格描述”,
+ “table_footnote”: “表格脚注”,
+ “phonetic”: “拼音”,
+ “code”: “代码块”,
+ “code_caption”: “代码描述”,
+ “ref_text”: “参考文献”,
+ “algorithm”: “算法块”,
+ “list”: “列表”,
+ “header”: “页眉”,
+ “footer”: “页脚”,
+ “page_number”: “页码”,
+ “aside_text”: “装订线旁注”,
+ “page_footnote”: “页面脚注”
}
```
@@ -531,34 +362,34 @@
[
[
{
- "type": "header",
- "bbox": [
+ “type”: “header”,
+ “bbox”: [
0.077,
0.095,
0.18,
0.181
],
- "angle": 0,
- "score": null,
- "block_tags": null,
- "content": "ELSEVIER",
- "format": null,
- "content_tags": null
+ “angle”: 0,
+ “score”: null,
+ “block_tags”: null,
+ “content”: “ELSEVIER”,
+ “format”: null,
+ “content_tags”: null
},
{
- "type": "title",
- "bbox": [
+ “type”: “title”,
+ “bbox”: [
0.157,
0.228,
0.833,
0.253
],
- "angle": 0,
- "score": null,
- "block_tags": null,
- "content": "The response of flow duration curves to afforestation",
- "format": null,
- "content_tags": null
+ “angle”: 0,
+ “score”: null,
+ “block_tags”: null,
+ “content”: “The response of flow duration curves to afforestation”,
+ “format”: null,
+ “content_tags”: null
}
]
]
@@ -569,283 +400,74 @@
**文件命名格式**:`{原文件名}_middle.json`
##### 文件格式说明
-Hybrid 多模态 `middle.json` 在基础块结构上包含以下扩展:
-- list变成二级block,增加`sub_type`字段区分list类型:
+在 schema 2.0 中,多模态 tier 与其他 tier 产出相同的统一 `MiddleJson` 结构。以下块类型是标准 `blocks` 树的一部分(不再是扩展):
+
+- list 是容器块,`content` 持有子 `text`/`ref_text`/嵌套 `list` 块,`sub_type` 区分 list 类型:
* `text`(文本类型)
* `ref_text`(引用类型)
-- 增加code类型block,code类型包含两种"sub_type":
- * 分别是`code`和`algorithm`
- * 至少有`code_body`, 可选`code_caption`
+- code 是容器块,`content` 持有 `code_body` 加可选 `code_caption`/`code_footnote`,`sub_type` 为:
+ * `code`
+ * `algorithm`
-- `discarded_blocks`内元素type增加以下类型:
- * `header`(页眉)
- * `footer`(页脚)
- * `page_number`(页码)
- * `aside_text`(装订线文本)
- * `page_footnote`(脚注)
-- 所有block增加`angle`字段,用来表示旋转角度,0,90,180,270
+- 页面辅助块(`header`、`footer`、`page_number`、`aside_text`、`page_footnote`)作为顶层叶子块出现在 `blocks` 中,`content: str`——schema 2.0 不再有独立的 `discarded_blocks` 字段。
+- 所有 block 可能包含 `angle` 字段,用来表示旋转角度,0,90,180,270
##### 示例数据
- list block 示例
```json
{
- "bbox": [
- 174,
- 155,
- 818,
- 333
- ],
- "type": "list",
- "angle": 0,
- "index": 11,
- "blocks": [
+ “type”: “list”,
+ “bbox”: [0.068, 0.121, 0.319, 0.260],
+ “index”: 11,
+ “content”: [
{
- "bbox": [
- 174,
- 157,
- 311,
- 175
- ],
- "type": "text",
- "angle": 0,
- "lines": [
- {
- "bbox": [
- 174,
- 157,
- 311,
- 175
- ],
- "spans": [
- {
- "bbox": [
- 174,
- 157,
- 311,
- 175
- ],
- "type": "text",
- "content": "H.1 Introduction"
- }
- ]
- }
- ],
- "index": 3
+ “type”: “text”,
+ “bbox”: [0.068, 0.123, 0.122, 0.137],
+ “index”: 3,
+ “content”: “H.1 Introduction”
},
{
- "bbox": [
- 175,
- 182,
- 464,
- 229
- ],
- "type": "text",
- "angle": 0,
- "lines": [
- {
- "bbox": [
- 175,
- 182,
- 464,
- 229
- ],
- "spans": [
- {
- "bbox": [
- 175,
- 182,
- 464,
- 229
- ],
- "type": "text",
- "content": "H.2 Example: Divide by Zero without Exception Handling"
- }
- ]
- }
- ],
- "index": 4
+ “type”: “text”,
+ “bbox”: [0.068, 0.142, 0.181, 0.179],
+ “index”: 4,
+ “content”: “H.2 Example: Divide by Zero without Exception Handling”
}
],
- "sub_type": "text"
+ “sub_type”: “text”
}
```
- code block 示例
```json
{
- "type": "code",
- "bbox": [
- 114,
- 780,
- 885,
- 1231
- ],
- "blocks": [
+ “type”: “code”,
+ “bbox”: [0.045, 0.610, 0.346, 0.964],
+ “index”: 17,
+ “content”: [
{
- "bbox": [
- 114,
- 780,
- 885,
- 1231
- ],
- "lines": [
- {
- "bbox": [
- 114,
- 780,
- 885,
- 1231
- ],
- "spans": [
- {
- "bbox": [
- 114,
- 780,
- 885,
- 1231
- ],
- "type": "text",
- "content": "1 // Fig. H.1: DivideByZeroNoExceptionHandling.java \n2 // Integer division without exception handling. \n3 import java.util.Scanner; \n4 \n5 public class DivideByZeroNoExceptionHandling \n6 { \n7 // demonstrates throwing an exception when a divide-by-zero occurs \n8 public static int quotient( int numerator, int denominator ) \n9 { \n10 return numerator / denominator; // possible division by zero \n11 } // end method quotient \n12 \n13 public static void main(String[] args) \n14 { \n15 Scanner scanner = new Scanner(System.in); // scanner for input \n16 \n17 System.out.print(\"Please enter an integer numerator: \"); \n18 int numerator = scanner.nextInt(); \n19 System.out.print(\"Please enter an integer denominator: \"); \n20 int denominator = scanner.nextInt(); \n21"
- }
- ]
- }
- ],
- "index": 17,
- "angle": 0,
- "type": "code_body"
+ “type”: “code_body”,
+ “bbox”: [0.045, 0.610, 0.346, 0.964],
+ “index”: 17,
+ “content”: “1 // Fig. H.1: DivideByZeroNoExceptionHandling.java \n2 // Integer division without exception handling. \n3 import java.util.Scanner; \n4 \n5 public class DivideByZeroNoExceptionHandling \n6 { \n7 // demonstrates throwing an exception when a divide-by-zero occurs \n8 public static int quotient( int numerator, int denominator ) \n9 { \n10 return numerator / denominator; // possible division by zero \n11 } // end method quotient \n12 \n13 public static void main(String[] args) \n14 { \n15 Scanner scanner = new Scanner(System.in); // scanner for input \n16 \n17 System.out.print(\”Please enter an integer numerator: \”); \n18 int numerator = scanner.nextInt(); \n19 System.out.print(\”Please enter an integer denominator: \”); \n20 int denominator = scanner.nextInt(); \n21”
},
{
- "bbox": [
- 867,
- 160,
- 1280,
- 189
- ],
- "lines": [
- {
- "bbox": [
- 867,
- 160,
- 1280,
- 189
- ],
- "spans": [
- {
- "bbox": [
- 867,
- 160,
- 1280,
- 189
- ],
- "type": "text",
- "content": "Algorithm 1 Modules for MCTSteg"
- }
- ]
- }
- ],
- "index": 19,
- "angle": 0,
- "type": "code_caption"
+ “type”: “code_caption”,
+ “bbox”: [0.339, 0.125, 0.500, 0.148],
+ “index”: 19,
+ “content”: “Algorithm 1 Modules for MCTSteg”
}
],
- "index": 17,
- "sub_type": "code"
+ “sub_type”: “code”,
+ “guess_lang”: “java”
}
```
#### 内容列表 (content_list.json)
-**文件命名格式**:`{原文件名}_content_list.json`
-
-##### 文件格式说明
-Hybrid 多模态 `content_list.json` 包含以下扩展:
-
-- 新增`code`类型,code类型包含两种"sub_type":
- * 分别是`code`和`algorithm`
- * 至少有`code_body`, 可选`code_caption`
-
-- 新增`list`类型,list类型包含两种"sub_type":
- * `text`
- * `ref_text`
-
-- `image` / `chart` 类型可能带有可选 `sub_type` 字段,用于透传视觉子类型
-- `chart` 类型除 `img_path` 外,还可包含 `content`、`chart_caption`、`chart_footnote`,其中 `content` 保持原始 Markdown 表格文本
-
-- 增加所有所有`discarded_blocks`的输出内容
- * `header`
- * `footer`
- * `page_number`
- * `aside_text`
- * `page_footnote`
-- 3.0 起,Hybrid 多模态输出也会同时输出 `*_structured_content.json`,其通用结构见上文“通用结构化内容”。
-
-##### 示例数据
-- code 类型 content
- ```json
- {
- "type": "code",
- "sub_type": "algorithm",
- "code_caption": [
- "Algorithm 1 Modules for MCTSteg"
- ],
- "code_body": "1: function GETCOORDINATE(d) \n2: $x \\gets d / l$ , $y \\gets d$ mod $l$ \n3: return $(x, y)$ \n4: end function \n5: function BESTCHILD(v) \n6: $C \\gets$ child set of $v$ \n7: $v' \\gets \\arg \\max_{c \\in C} \\mathrm{UCTScore}(c)$ \n8: $v'.n \\gets v'.n + 1$ \n9: return $v'$ \n10: end function \n11: function BACK PROPAGATE(v) \n12: Calculate $R$ using Equation 11 \n13: while $v$ is not a root node do \n14: $v.r \\gets v.r + R$ , $v \\gets v.p$ \n15: end while \n16: end function \n17: function RANDOMSEARCH(v) \n18: while $v$ is not a leaf node do \n19: Randomly select an untried action $a \\in A(v)$ \n20: Create a new node $v'$ \n21: $(x, y) \\gets \\mathrm{GETCOORDINATE}(v'.d)$ \n22: $v'.p \\gets v$ , $v'.d \\gets v.d + 1$ , $v'.\\Gamma \\gets v.\\Gamma$ \n23: $v'.\\gamma_{x,y} \\gets a$ \n24: if $a = -1$ then \n25: $v.lc \\gets v'$ \n26: else if $a = 0$ then \n27: $v.mc \\gets v'$ \n28: else \n29: $v.rc \\gets v'$ \n30: end if \n31: $v \\gets v'$ \n32: end while \n33: return $v$ \n34: end function \n35: function SEARCH(v) \n36: while $v$ is fully expanded do \n37: $v \\gets$ BESTCHILD(v) \n38: end while \n39: if $v$ is not a leaf node then \n40: $v \\gets$ RANDOMSEARCH(v) \n41: end if \n42: return $v$ \n43: end function",
- "bbox": [
- 510,
- 87,
- 881,
- 740
- ],
- "page_idx": 0
- }
- ```
-- list 类型 content
- ```json
- {
- "type": "list",
- "sub_type": "text",
- "list_items": [
- "H.1 Introduction",
- "H.2 Example: Divide by Zero without Exception Handling",
- "H.3 Example: Divide by Zero with Exception Handling",
- "H.4 Summary"
- ],
- "bbox": [
- 174,
- 155,
- 818,
- 333
- ],
- "page_idx": 0
- }
- ```
-- discarded 类型 content
- ```json
- [{
- "type": "header",
- "text": "Journal of Hydrology 310 (2005) 253-265",
- "bbox": [
- 363,
- 164,
- 623,
- 177
- ],
- "page_idx": 0
- },
- {
- "type": "page_footnote",
- "text": "* Corresponding author. Address: Forest Science Centre, Department of Sustainability and Environment, P.O. Box 137, Heidelberg, Vic. 3084, Australia. Tel.: +61 3 9450 8719; fax: +61 3 9450 8644.",
- "bbox": [
- 71,
- 815,
- 915,
- 841
- ],
- "page_idx": 0
- }]
- ```
-
+> [!NOTE]
+> `content_list.json` 已废弃,不再生成。结构化内容输出请使用 `structured_content.json`,其通用结构见上文”通用结构化内容”章节。
## 总结
@@ -853,14 +475,13 @@ Hybrid 多模态 `content_list.json` 包含以下扩展:
- **模型输出**(使用原始输出):
* model.json
-
+
- **调试和验证**(使用可视化文件):
* layout.pdf
* span.pdf
- **内容提取**(使用简化文件):
* *.md
- * content_list.json
* structured_content.json
- **二次开发**(使用结构化文件):
diff --git a/mineru/backend/postprocess/legacy_schema_adapter.py b/mineru/backend/postprocess/legacy_schema_adapter.py
new file mode 100644
index 00000000..542afbf8
--- /dev/null
+++ b/mineru/backend/postprocess/legacy_schema_adapter.py
@@ -0,0 +1,168 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""schema 1.0 preproc_blocks → raw model_list 适配器。
+
+pr-5415 重构后 PageInfo 收紧为 (page_idx, blocks),但旧 schema 1.0 的 page 含
+preproc_blocks/para_blocks/discarded_blocks(像素坐标 + lines/spans 嵌套)。
+本模块把旧 page dict 回推成新代码 process_page_blocks 期望的 raw model_list
+(归一化坐标 + 扁平 content),再由 model_list_to_pages 重走完整后处理。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+# 顶层视觉块类型:含嵌套子块(body + caption + footnote),回推时展平子块。
+_VISUAL_PARENT_TYPES: frozenset[str] = frozenset(
+ {
+ "image",
+ "image_block",
+ "table",
+ "chart",
+ "code",
+ "algorithm",
+ }
+)
+
+# flash 旧数据无版面坐标,bbox=[0,0,0,0],用最小合法占位满足新 schema(x1>x0, y1>y0)
+_PLACEHOLDER_BBOX: tuple[float, float, float, float] = (0.0, 0.0, 0.001, 0.001)
+
+
+def legacy_page_to_model_list(page: dict[str, Any]) -> list[dict[str, Any]]:
+ """把 1.0 schema 的 page dict 转换为 raw model_list。
+
+ preproc_blocks 优先(更接近 raw model_list);flash 旧数据只有 para_blocks 时回退。
+ discarded_blocks 也参与回推(header/footer/page_number 等辅助块)。
+ - 顶层视觉块(image/table/chart)展平子块为独立 block
+ - 文本块从 lines[].spans[].content 提取 content
+ - bbox 像素坐标 → 归一化坐标(用 page_size);零面积 bbox 设为 None
+ - image_path 从 span 提到 block 级
+ """
+ page_size = page.get("page_size")
+ width, height = (float(page_size[0]), float(page_size[1])) if page_size and len(page_size) >= 2 else (0.0, 0.0)
+
+ source_blocks = page.get("preproc_blocks")
+ if source_blocks is None:
+ # flash 旧数据只有 para_blocks(无 preproc_blocks),回退使用
+ source_blocks = page.get("para_blocks", [])
+
+ model_list: list[dict[str, Any]] = []
+ for block in source_blocks:
+ _collect_blocks(block, width, height, model_list)
+ for block in page.get("discarded_blocks", []):
+ _collect_blocks(block, width, height, model_list)
+ return model_list
+
+
+def _collect_blocks(block: dict[str, Any], width: float, height: float, out: list[dict[str, Any]]) -> None:
+ """递归收集 block:视觉父块展平子块,叶子块输出为 raw dict。"""
+ btype = _normalize_block_type(block)
+ nested = block.get("blocks") or []
+
+ if block.get("type", "") in _VISUAL_PARENT_TYPES and nested:
+ # 视觉父块:展平子块(table_body/table_caption 等成为独立顶层 block)
+ for child in nested:
+ _collect_blocks(child, width, height, out)
+ return
+
+ bbox = _denormalize_bbox(block.get("bbox"), width, height)
+ # 零面积 bbox(flash 无版面坐标)用最小合法占位,满足新 schema 的 PDF bbox 要求(x1>x0, y1>y0)
+ if (bbox is None and _is_empty_bbox(block.get("bbox"))) or (
+ bbox is not None and (bbox[2] <= bbox[0] or bbox[3] <= bbox[1])
+ ):
+ bbox = _PLACEHOLDER_BBOX
+
+ content, image_path = _extract_lines_content(block.get("lines") or [])
+ lines = _denormalize_lines(block.get("lines") or [], width, height)
+
+ raw: dict[str, Any] = {"type": btype, "bbox": bbox}
+ if content:
+ raw["content"] = content
+ if image_path:
+ raw["image_path"] = image_path
+ # lines 供 merge_para_text_blocks 做跨页几何分析,用完由 _remove_private_metadata 清除
+ if lines:
+ raw["lines"] = lines
+ if block.get("level") is not None:
+ raw["level"] = block["level"]
+ # code_body 必须带 sub_type(_annotate_code_languages 直接读 code_block["sub_type"])
+ if btype == "code_body":
+ raw["sub_type"] = block.get("sub_type") or "code"
+ elif block.get("sub_type"):
+ raw["sub_type"] = block["sub_type"]
+ if block.get("anchor"):
+ raw["anchor"] = block["anchor"]
+ out.append(raw)
+
+
+def _is_empty_bbox(bbox: Any) -> bool:
+ """判断 bbox 是否为空(None 或 [0,0,0,0])。"""
+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
+ return True
+ return all(float(v) == 0.0 for v in bbox)
+
+
+def _normalize_block_type(block: dict[str, Any]) -> str:
+ """旧 VLM 标签 → 新 schema BlockType 映射。"""
+ btype = block.get("type", "")
+ if btype == "title":
+ level = block.get("level")
+ return "doc_title" if level == 1 else "paragraph_title"
+ if btype == "interline_equation":
+ return "equation"
+ return btype
+
+
+def _denormalize_bbox(bbox: Any, width: float, height: float) -> tuple[float, float, float, float] | None:
+ """像素坐标 → 归一化坐标(0-1),page_size 缺失时返回 None。"""
+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
+ return None
+ if width <= 0 or height <= 0:
+ return None
+ x0, y0, x1, y1 = (float(v) for v in bbox)
+ return (x0 / width, y0 / height, x1 / width, y1 / height)
+
+
+def _extract_lines_content(lines: list[dict[str, Any]]) -> tuple[str, str]:
+ """从 lines[].spans[] 提取文本 content 和第一个 image_path。"""
+ parts: list[str] = []
+ image_path = ""
+ for line in lines:
+ if not isinstance(line, dict):
+ continue
+ for span in line.get("spans") or []:
+ if not isinstance(span, dict):
+ continue
+ text = span.get("content")
+ if text:
+ parts.append(text)
+ if not image_path and span.get("image_path"):
+ image_path = span["image_path"]
+ return "\n".join(parts), image_path
+
+
+def _denormalize_lines(
+ lines: list[dict[str, Any]],
+ width: float,
+ height: float,
+) -> list[dict[str, Any]]:
+ """保留 lines 供跨页几何分析,line bbox 像素→归一化。
+
+ page_size 有值时 line bbox 是像素坐标,需反归一化;
+ page_size=None 时 line bbox 可能已是归一化的,直接用。
+ """
+ result: list[dict[str, Any]] = []
+ for line in lines:
+ if not isinstance(line, dict):
+ continue
+ line_bbox = _denormalize_bbox(line.get("bbox"), width, height)
+ if line_bbox is None:
+ # page_size=None 时直接用原始 bbox(可能已是归一化的)
+ raw_bbox = line.get("bbox")
+ if not isinstance(raw_bbox, (list, tuple)) or len(raw_bbox) != 4:
+ continue
+ line_bbox = tuple(float(v) for v in raw_bbox) # type: ignore[assignment]
+ result.append({"bbox": list(line_bbox)})
+ return result
+
+
+__all__ = ["legacy_page_to_model_list"]
diff --git a/mineru/cli/main.py b/mineru/cli/main.py
index c7180904..8ea24a59 100644
--- a/mineru/cli/main.py
+++ b/mineru/cli/main.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import typer
-from click.core import Context
+from typer._click.core import Context
from typer.core import TyperGroup
from ..utils.stdio import configure_standard_streams
@@ -17,7 +17,6 @@ from .commands.search import find_cmd, search_cmd
from .telemetry import prepare_cli_telemetry
from .version_command import show_version, version_cmd
-
# Typer stores commands and command groups separately before building the Click
# command tree, so source registration order alone does not preserve the mixed
# top-level help order.
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 24923a16..1d4bc4cf 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -17,7 +17,7 @@ from ..filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PDF_EXTENSIONS
from ..parser.base import ParseResult
from ..render import render_markdown, render_structured_content
from ..render.writer import FileBasedDataWriter
-from ..types import PageInfo
+from ..types import MiddleJson, PageInfo
from ..utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort
from ..utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from ..utils.engine_utils import get_vlm_engine
@@ -285,8 +285,16 @@ def _process_output(
)
image_dir = str(os.path.basename(local_image_dir))
+ from ..version import __version__ as mineru_version
+
export_result = ParseResult(
- pages=middle_json,
+ middle_json=MiddleJson(
+ pages=middle_json,
+ file_suffix="pdf",
+ effort="medium",
+ parse_mode="txt",
+ mineru_version=mineru_version,
+ ),
_image_cache=image_cache,
_retained_page_indices=retained_page_indices,
_broken_page_indices=broken_page_indices,
diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.py
index a018cb7a..c59fca13 100644
--- a/mineru/doclib/background/compaction.py
+++ b/mineru/doclib/background/compaction.py
@@ -8,9 +8,9 @@ import logging
import os
import time
from collections.abc import Sequence
-from typing import cast
+from typing import Any, cast
-from ...parser import MIDDLE_JSON_SCHEMA_VERSION
+from ...parser.base import MIDDLE_JSON_SCHEMA_VERSION
from ...types import Tier
from ..core.db import DatabaseManager
from ..rows import ParseBatchRow, ParseGroupRow, ParseRow
@@ -20,6 +20,28 @@ from ..types import PARSE_STATUS_DONE, PARSE_STATUS_SUPERSEDED
logger = logging.getLogger("mineru.compaction")
+def _normalize_batch_pages(batch_payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """把 batch JSON 的 pages 统一为 2.0 schema 的 page dict 列表。
+
+ 2.0 batch:page 只有 page_idx + blocks,直接用。
+ 1.0 batch:page 含 preproc_blocks/para_blocks/discarded_blocks/page_size,
+ 走 legacy_schema_adapter 回推为 raw model_list,再走 model_list_to_pages 转 2.0。
+ """
+ raw_pages = batch_payload.get("pages", [])
+ if batch_payload.get("schema_version") == MIDDLE_JSON_SCHEMA_VERSION:
+ return raw_pages
+
+ # 1.0 batch:走 legacy 适配器转换
+ from ...backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list
+ from ...backend.postprocess.pages import model_list_to_pages
+
+ model_list = [legacy_page_to_model_list(page) for page in raw_pages]
+ if not model_list or not any(model_list):
+ return []
+ pages = model_list_to_pages(model_list)
+ return [page.to_dict() for page in pages]
+
+
class Compaction:
def __init__(self, db: DatabaseManager, interval_sec: int, data_dir: str) -> None:
self.db = db
@@ -134,16 +156,24 @@ class Compaction:
# only read files from done batches (exclude superseded)
# process oldest first → newest overwrites (done_rows is sorted by done_at DESC)
pages_by_page_idx: dict[int, dict] = {}
+ envelope: dict[str, Any] = {}
for row in reversed(done_rows):
fpath = parse_batch_json_path(self.data_dir, sha256, tier, row["page_range"], row["done_at"])
if not os.path.isfile(fpath):
continue
try:
with open(fpath, encoding="utf-8") as f:
- for p in json.load(f).get("pages", []):
- pages_by_page_idx[p["page_idx"]] = p
+ batch_payload = json.load(f)
except Exception:
- pass
+ continue
+ batch_pages = _normalize_batch_pages(batch_payload)
+ for p in batch_pages:
+ pages_by_page_idx[p["page_idx"]] = p
+ # 继承源 batch JSON 的 envelope 元数据(2.0 schema 字段)
+ if not envelope:
+ envelope = {
+ k: batch_payload[k] for k in ("file_suffix", "effort", "parse_mode", "mineru_version") if k in batch_payload
+ }
if not pages_by_page_idx:
return
@@ -167,7 +197,9 @@ class Compaction:
json_path = parse_batch_json_path(self.data_dir, sha256, tier, page_range, max_done_at)
try:
with open(json_path, "w", encoding="utf-8") as f:
- payload = {"schema_version": MIDDLE_JSON_SCHEMA_VERSION, "pages": json_pages}
+ # compacted payload 用 2.0 schema,继承源 batch 的 envelope 元数据
+ payload: dict[str, Any] = {"schema_version": MIDDLE_JSON_SCHEMA_VERSION, "pages": json_pages}
+ payload.update(envelope)
json.dump(payload, f, ensure_ascii=False, indent=4)
except Exception:
pass
diff --git a/mineru/doclib/background/device_monitor.py b/mineru/doclib/background/device_monitor.py
index 554159ae..eff6d022 100644
--- a/mineru/doclib/background/device_monitor.py
+++ b/mineru/doclib/background/device_monitor.py
@@ -20,7 +20,9 @@ from ..types import (
class DeviceMonitor:
- def __init__(self, db: DatabaseManager, config_svc: ConfigService, *, interval_sec: int, scan_svc: ScanService | None = None) -> None:
+ def __init__(
+ self, db: DatabaseManager, config_svc: ConfigService, *, interval_sec: int, scan_svc: ScanService | None = None
+ ) -> None:
self.db = db
self.config_svc = config_svc
self.scan_svc = scan_svc
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 2db1a68a..8cabbf56 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -25,18 +25,18 @@ from ..config import config
from ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_for
from ..filetypes import IMAGE_EXTENSIONS, TEXT_EXTENSIONS, TEXT_FILE_TYPES
from ..parser.tier import TierDependencyError, ensure_tier_runtime_dependencies
-from ..render.markdown import blocks_to_markdown
-from ..render.office.output import blocks_to_markdown as office_blocks_to_markdown
+from ..render._internal.markdown.blocks import render_single_block
from ..types import (
- EMPTY_BBOX,
DEPLOYMENT_TIERS,
TIERS,
- Block,
+ BlockBase,
BlockType,
DeploymentTier,
+ ImagePayloadBlock,
+ PageBlock,
PageInfo,
- Span,
Tier,
+ _iter_child_blocks,
select_highest_cached_tier,
)
from ..utils.model_registry import ModelRepo, model_repos_for_tier
@@ -202,7 +202,7 @@ _VISUAL_BLOCK_LABELS = {
BlockType.IMAGE: "Image block",
BlockType.TABLE: "Table block",
BlockType.CHART: "Chart block",
- BlockType.INTERLINE_EQUATION: "Formula block",
+ BlockType.EQUATION: "Formula block",
}
@@ -1445,7 +1445,7 @@ class DoclibServer(AsyncDoclibInterface):
block = _find_block_by_no(page, plan.target.block_no)
if block is None:
raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")
- if _is_empty_bbox(block.bbox):
+ if block.bbox is None or _is_empty_bbox(block.bbox):
raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")
image_bytes = _transcode_image_bytes(
doc.crop_image(block.bbox, plan.target.page_no - 1, scale=doc.render_scale),
@@ -1788,9 +1788,9 @@ def _find_page(pages: list[PageInfo], page_no: int) -> PageInfo | None:
return next((page for page in pages if page.page_idx + 1 == page_no), None)
-def _find_block_by_no(page: PageInfo, block_no: int) -> Block | None:
+def _find_block_by_no(page: PageInfo, block_no: int) -> PageBlock | None:
target_index = block_no - 1
- return next((block for block in page.para_blocks if block.index == target_index), None)
+ return next((block for block in page.blocks if block.index == target_index), None)
def _is_empty_bbox(bbox: object) -> bool:
@@ -1802,16 +1802,16 @@ def _is_empty_bbox(bbox: object) -> bool:
return True
if not all(math.isfinite(value) for value in values):
return True
- return tuple(values) == tuple(float(v) for v in EMPTY_BBOX) or values[0] >= values[2] or values[1] >= values[3]
+ return values[0] >= values[2] or values[1] >= values[3]
-def _resolve_block_image_source(block: Block, *, image_dir: str) -> _BlockImageSource | None:
+def _resolve_block_image_source(block: BlockBase, *, image_dir: str) -> _BlockImageSource | None:
if not _is_empty_bbox(block.bbox):
return _BlockImageSource(kind="source_bbox")
- for span in _iter_block_spans(block):
- if not span.image_path:
+ for payload in _iter_block_image_payloads(block):
+ if not payload.image_path:
continue
- candidate = resolve_image_sidecar_path(image_dir, span.image_path)
+ candidate = resolve_image_sidecar_path(image_dir, payload.image_path)
if candidate is not None and candidate.is_file():
return _BlockImageSource(kind="sidecar", sidecar_path=candidate)
return None
@@ -1824,23 +1824,24 @@ def _make_doclib_image_renderer(
short_id: str,
tier: Tier,
page_no: int,
-) -> Callable[[Block], str]:
+) -> Callable[[BlockBase], str]:
image_dir = parse_image_sidecar_dir(data_dir, sha256, tier)
- def _render(block: Block) -> str:
+ def _render(block: BlockBase) -> str:
label = _VISUAL_BLOCK_LABELS.get(block.type, "Image block")
source = _resolve_block_image_source(block, image_dir=image_dir)
- locator = block_ref(short_id, tier, page_no, block.index + 1) if source is not None else ""
+ block_no = block.index + 1 if block.index is not None else 0 # TODO: change after block.index's type changed.
+ locator = block_ref(short_id, tier, page_no, block_no) if source is not None else ""
return f"![{label}]({locator})"
return _render
-def _iter_block_spans(block: Block) -> Iterator[Span]:
- for line in block.lines:
- yield from line.spans
- for child in block.blocks:
- yield from _iter_block_spans(child)
+def _iter_block_image_payloads(block: BlockBase) -> Iterator[ImagePayloadBlock]:
+ if isinstance(block, ImagePayloadBlock):
+ yield block
+ for child in _iter_child_blocks(block):
+ yield from _iter_block_image_payloads(child)
_PIL_IMAGE_FORMATS: dict[ImageFormat, str] = {
@@ -2077,7 +2078,8 @@ def _page_markdown_blocks(
short_id: str = "",
tier: Tier = "standard",
) -> list[tuple[int, str]]:
- backend = page._backend
+ from mineru.config import config
+
result: list[tuple[int, str]] = []
image_renderer = _make_doclib_image_renderer(
data_dir=data_dir,
@@ -2086,22 +2088,19 @@ def _page_markdown_blocks(
tier=tier,
page_no=page.page_idx + 1,
)
- for block in page.para_blocks:
- if backend == "office":
- rendered = office_blocks_to_markdown(
- [block],
- prefer_markdown_table=True,
- image_renderer=image_renderer,
- )
- else:
- rendered = blocks_to_markdown(
- [block],
- prefer_markdown_table=True,
- image_renderer=image_renderer,
- )
- text = _join_markdown([item for item in rendered if item.strip()])
- if text.strip():
- result.append((block.index, text))
+ delimiters = config.render.latex_delimiters
+ for block in page.blocks:
+ rendered = render_single_block(
+ block,
+ delimiters=delimiters,
+ asset_base_url="",
+ image_renderer=image_renderer,
+ )
+ text = rendered.strip() if rendered else ""
+ if text:
+ # TODO: simplify after BlockBase.index type narrows to int (top-level blocks always have index)
+ block_index = block.index if block.index is not None else -1
+ result.append((block_index, text))
return result
diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.py
index 8815c6d6..62d8fb53 100644
--- a/mineru/doclib/services/cleanup_svc.py
+++ b/mineru/doclib/services/cleanup_svc.py
@@ -207,6 +207,7 @@ def _path_prefix(path: str) -> str:
return path if path.endswith(os.sep) else path + os.sep
+# TODO
def _is_watch_root(path: str, watches: list[WatchTargetRow]) -> bool:
return any(watch["path"] == path for watch in watches)
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 8839e34c..38e70f18 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -1395,9 +1395,22 @@ class ParseService:
if not pages:
continue
- from ...render import render_markdown
-
- text = truncate_head_tail(render_markdown(pages, add_markers=False, image_renderer=lambda _block: ""))
+ from mineru.config import config
+ from ...render._internal.markdown.blocks import render_single_block
+
+ delimiters = config.render.latex_delimiters
+ parts: list[str] = []
+ for page in pages:
+ for block in page.blocks:
+ rendered = render_single_block(
+ block,
+ delimiters=delimiters,
+ asset_base_url="",
+ image_renderer=lambda _block: "",
+ )
+ if rendered and rendered.strip():
+ parts.append(rendered.strip())
+ text = truncate_head_tail("\n\n".join(parts))
await self.fts.replace(
sha256=sha256,
tier=tier,
diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.py
index c099fd5a..69b861f2 100644
--- a/mineru/doclib/services/search_svc.py
+++ b/mineru/doclib/services/search_svc.py
@@ -3,12 +3,12 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
-from typing import TYPE_CHECKING, cast
+from typing import TYPE_CHECKING, Any, cast
from ...types import TIER_ORDER, Tier
from ..core.db import DatabaseManager
from ..core.fts import FTSManager, strip_sep
-from ..rows import ContentSearchResultRow, DocRow, FileRow, FilenameSearchFileRow, FilenameSearchResultRow
+from ..rows import ContentSearchResultRow, DocRow, FilenameSearchFileRow, FilenameSearchResultRow, FileRow
from ..types import FILE_STATUS_ACTIVE
if TYPE_CHECKING:
@@ -127,7 +127,7 @@ class SearchService:
f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "
f"WHERE f.id IN ({placeholders})"
)
- params = [*file_ids]
+ params: list[Any] = [*file_ids]
if refresh_file is None:
sql += " AND f.status = ?"
params.append(FILE_STATUS_ACTIVE)
diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.py
index bbbf5f9d..cd1218ce 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -10,8 +10,7 @@ from ...filetypes import ensure_tier_supported_for_parse_extension, is_flash_onl
from ...parser import MinerUApiParser
from ...parser import parse as local_parse
from ...types import Tier
-from ...utils.backend_options import DEFAULT_HYBRID_EFFORT, HYBRID_EFFORT_HELP, effort_for_tier, resolve_backend_and_effort
-from ...utils.ocr_language import validate_public_ocr_lang
+from ...utils.backend_options import normalize_backend
from ..common import (
build_remote_api_url,
effective_local_tier_and_backend,
@@ -41,24 +40,13 @@ def parse_cmd(
remote: bool = typer.Option(False, "--remote", help="Use mineru.net official remote parse service"),
remote_url: str | None = typer.Option(None, "--remote-url", help="Use a custom remote parse service URL"),
api_key: str | None = typer.Option(None, "--api-key", help="API key for remote parse service"),
- language: str = typer.Option(
- "ch",
- "--language",
- help="Hybrid medium OCR language hint; accepted by other efforts for compatibility",
- ),
ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- effort: str = typer.Option(
- DEFAULT_HYBRID_EFFORT,
- "--effort",
- help=HYBRID_EFFORT_HELP,
- ),
disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),
) -> None:
"""Parse files or directories into markdown, middle JSON, or zip outputs."""
output_format = cast(Literal["markdown", "middle_json", "zip"], format)
parse_tier = cast(Tier | None, tier)
parse_ocr_mode = cast(Literal["auto", "txt", "ocr"], ocr_mode)
- parse_effort = cast(Literal["medium", "high", "xhigh"], effort)
if not inputs:
exit_with_message("invalid_request", "At least one input path is required.", "inputs")
if remote and backend is not None:
@@ -82,7 +70,6 @@ def parse_cmd(
try:
ensure_supported_inputs(paths)
destinations = resolve_batch_output_paths(paths, Path(output).expanduser(), output_format)
- normalized_language = validate_public_ocr_lang(language)
except Exception as exc:
exit_with_message("invalid_request", str(exc))
@@ -91,36 +78,25 @@ def parse_cmd(
parse_one = partial(parser.parse, page_range=pages or "")
else:
try:
- normalized_backend, normalized_effort = (
- resolve_backend_and_effort(backend, parse_effort) if backend is not None else (None, parse_effort)
- )
+ normalized_backend = normalize_backend(backend) if backend is not None else None
except ValueError as exc:
exit_with_message("invalid_request", str(exc), "backend")
is_batch = has_directory_input or len(paths) > 1
def parse_one(path: Path) -> object:
path_tier: Tier
- path_backend: str
- path_effort = normalized_effort
if is_flash_only_parse_extension(path):
if not is_batch and (parse_tier is not None or normalized_backend is not None):
resolved_tier, _resolved_backend = effective_local_tier_and_backend(parse_tier, normalized_backend)
ensure_tier_supported_for_parse_extension(resolved_tier, path)
path_tier = "flash"
- path_backend = "flash"
- path_effort = DEFAULT_HYBRID_EFFORT
else:
- path_tier, path_backend = effective_local_tier_and_backend(parse_tier, normalized_backend)
- if path_tier in {"basic", "standard", "advanced"}:
- path_effort = effort_for_tier(path_tier)
+ path_tier, _path_backend = effective_local_tier_and_backend(parse_tier, normalized_backend)
return local_parse(
path,
tier=path_tier,
- backend=path_backend,
- language=normalized_language,
ocr_mode=parse_ocr_mode,
- effort=path_effort,
- disable_image_analysis=disable_image_analysis,
+ image_analysis=not disable_image_analysis,
page_range=pages or "",
)
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index 6efe8776..0d6c42fe 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import typer
-from click.core import Context
+from typer._click.core import Context
from typer.core import TyperGroup
from ..cli.version_command import show_version, version_cmd
diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.py
index a046792f..176df335 100644
--- a/mineru/parser/__init__.py
+++ b/mineru/parser/__init__.py
@@ -2,155 +2,48 @@
from __future__ import annotations
from pathlib import Path
+from typing import Literal
-from ..filetypes import OFFICE_EXTENSIONS, TIERED_PARSE_EXTENSIONS, ensure_tier_supported_for_parse_extension
from ..types import Tier
-from ..utils.backend_options import DEFAULT_HYBRID_EFFORT
from .api_client import MinerUApiParser
from .base import MIDDLE_JSON_SCHEMA_VERSION, DocumentParser, ParseResult
-from .office import DocxParser, PptxParser, XlsxParser
-from .pdf import PdfFlashParser, PdfHybridParser, PdfPipelineParser, PdfVlmParser
-from .tier import PARSER_BACKENDS, backend_for_tier, resolve_runtime_options, resolve_tier_and_backend
+from .mineru_parser import MinerUParser
+from .tier import PARSER_BACKENDS, backend_for_tier
__all__ = [
"backend_for_tier",
"PARSER_BACKENDS",
"DocumentParser",
- "DocxParser",
"MinerUApiParser",
+ "MinerUParser",
"MIDDLE_JSON_SCHEMA_VERSION",
"ParseResult",
- "PdfFlashParser",
- "PdfHybridParser",
- "PdfPipelineParser",
- "PdfVlmParser",
- "PptxParser",
- "XlsxParser",
"parse",
"parse_async",
- "resolve_tier_and_backend",
]
-_PATH_PRIORITY_SUFFIXES = OFFICE_EXTENSIONS | TIERED_PARSE_EXTENSIONS
-
-
-def _resolve_input_suffix(path: Path) -> str:
- from ..utils.guess_suffix_or_lang import guess_suffix_by_path
-
- guessed_suffix = guess_suffix_by_path(path)
- path_suffix = path.suffix.lower().lstrip(".")
- if path_suffix in _PATH_PRIORITY_SUFFIXES:
- return path_suffix
- return guessed_suffix
-
-
-def _build_parser(
- path: str | Path,
- *,
- tier: Tier | None = None,
- backend: str | None = None,
- language: str = "ch",
- ocr_mode: str = "auto",
- effort: str = DEFAULT_HYBRID_EFFORT,
- disable_image_analysis: bool = False,
- server_url: str | None = None,
- method: str | None = None,
- lang: str | None = None,
- image_analysis: bool | None = None,
-) -> DocumentParser:
- path = Path(path)
- suffix = _resolve_input_suffix(path)
- resolved_ocr_mode = method or ocr_mode
- resolved_language = lang or language
- resolved_image_analysis = (not disable_image_analysis) if image_analysis is None else image_analysis
-
- if suffix in OFFICE_EXTENSIONS:
- if tier is not None or backend is not None:
- runtime = resolve_runtime_options(tier=tier, backend=backend, effort=effort)
- ensure_tier_supported_for_parse_extension(runtime.tier, suffix)
- parser_cls: type[DocumentParser] = {
- "docx": DocxParser,
- "pptx": PptxParser,
- "xlsx": XlsxParser,
- }[suffix]
- return parser_cls()
-
- if suffix not in TIERED_PARSE_EXTENSIONS:
- raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")
-
- runtime = resolve_runtime_options(tier=tier, backend=backend, effort=effort)
- if runtime.backend.startswith("hybrid-"):
- return PdfHybridParser(
- backend=runtime.backend,
- method=resolved_ocr_mode,
- lang=resolved_language,
- server_url=server_url,
- image_analysis=resolved_image_analysis,
- effort=runtime.effort,
- )
- elif runtime.backend == "flash":
- return PdfFlashParser()
- else:
- raise ValueError(f"Unknown backend: {runtime.backend}")
-
def parse(
path: str | Path,
*,
- tier: Tier | None = None,
- backend: str | None = None,
- language: str = "ch",
- ocr_mode: str = "auto",
- effort: str = DEFAULT_HYBRID_EFFORT,
- disable_image_analysis: bool = False,
- server_url: str | None = None,
+ tier: Tier = "standard",
+ ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
+ image_analysis: bool = True,
page_range: str = "",
- method: str | None = None,
- lang: str | None = None,
- image_analysis: bool | None = None,
) -> ParseResult:
- parser = _build_parser(
- path,
- tier=tier,
- backend=backend,
- language=language,
- ocr_mode=ocr_mode,
- effort=effort,
- disable_image_analysis=disable_image_analysis,
- server_url=server_url,
- method=method,
- lang=lang,
- image_analysis=image_analysis,
- )
+ """同步解析文档,返回 Markdown/Structured Content/图片等结果。"""
+ parser = MinerUParser(tier=tier, parse_mode=ocr_mode, image_analysis=image_analysis)
return parser.parse(path, page_range=page_range)
async def parse_async(
path: str | Path,
*,
- tier: Tier | None = None,
- backend: str | None = None,
- language: str = "ch",
- ocr_mode: str = "auto",
- effort: str = DEFAULT_HYBRID_EFFORT,
- disable_image_analysis: bool = False,
- server_url: str | None = None,
+ tier: Tier = "standard",
+ ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
+ image_analysis: bool = True,
page_range: str = "",
- method: str | None = None,
- lang: str | None = None,
- image_analysis: bool | None = None,
) -> ParseResult:
- parser = _build_parser(
- path,
- tier=tier,
- backend=backend,
- language=language,
- ocr_mode=ocr_mode,
- effort=effort,
- disable_image_analysis=disable_image_analysis,
- server_url=server_url,
- method=method,
- lang=lang,
- image_analysis=image_analysis,
- )
+ """异步解析文档,返回 Markdown/Structured Content/图片等结果。"""
+ parser = MinerUParser(tier=tier, parse_mode=ocr_mode, image_analysis=image_analysis)
return await parser.parse_async(path, page_range=page_range)
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index b1c63522..35249a0f 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -47,7 +47,7 @@ from ..filetypes import (
)
from ..render.writer import DataWriter
from ..types import SERVER_TIERS, TIERS_BY_SERVER_TIER, DeploymentTier, PageInfo, ServerTier, Tier, select_default_quality_tier
-from ..utils.backend_options import DEFAULT_HYBRID_EFFORT
+from ..utils.backend_options import effort_for_tier
from ..utils.image_payload import validate_image_sidecar_path
from ..utils.managed_process_control import ManagedProcessControlWatcher
from ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
@@ -68,7 +68,6 @@ _MAX_INLINE_BYTES_DEFAULT = 1024 * 1024
_LOCAL_PARSE_OUTPUT_FORMATS: tuple[OutputFormat, ...] = (
"markdown",
"middle_json",
- "content_list",
"structured_content",
"zip",
)
@@ -130,7 +129,6 @@ UploadStatus = Literal["pending", "completed", "cancelled", "expired"]
OutputFormat = Literal[
"markdown",
"middle_json",
- "content_list",
"structured_content",
"html",
"latex",
@@ -498,7 +496,6 @@ class OutputFiles(BaseModel):
model_config = _PYDANTIC_CONFIG
markdown: OutputFileRef | None = None
middle_json: OutputFileRef | None = None
- content_list: OutputFileRef | None = None
structured_content: OutputFileRef | None = None
html: OutputFileRef | None = None
latex: OutputFileRef | None = None
@@ -1336,7 +1333,6 @@ async def _run_job(
language: str,
ocr_mode: str,
image_analysis: bool,
- effort: str = DEFAULT_HYBRID_EFFORT,
url_timeout: int = 60,
allow_local_source: bool = False,
max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,
@@ -1371,18 +1367,12 @@ async def _run_job(
page_range = entry.page_range or ""
effective_tier = batch_effective_parse_tier(rec.tier, fr.name)
- effective_runtime = runtime_options_for_tier(effective_tier) if effective_tier != rec.tier else None
- file_backend = effective_runtime.backend if effective_runtime is not None else server_backend
- file_effort = effective_runtime.effort if effective_runtime is not None else effort
result = await parse_async(
str(tmp_path),
tier=effective_tier,
- backend=file_backend,
- language=language,
ocr_mode=ocr_mode,
- effort=file_effort,
- disable_image_analysis=not image_analysis,
+ image_analysis=image_analysis,
page_range=page_range,
)
@@ -1393,7 +1383,6 @@ async def _run_job(
for fmt in (
"markdown",
"middle_json",
- "content_list",
"structured_content",
):
if fmt not in out_formats:
@@ -1411,12 +1400,6 @@ async def _run_job(
file_store.store_blob(mj, sha256hex=sha)
fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha)
output_files.middle_json = OutputFileRef(file_id=fid, bytes=len(mj))
- elif fmt == "content_list":
- cl = _json_utf8_bytes(result.content_list())
- sha = hashlib.sha256(cl).hexdigest()
- file_store.store_blob(cl, sha256hex=sha)
- fid = file_store.create_file_for_output(f"{fr.name}.content_list.json", cl, sha256hex=sha)
- output_files.content_list = OutputFileRef(file_id=fid, bytes=len(cl))
elif fmt == "structured_content":
cl2 = _json_utf8_bytes(result.structured_content())
sha = hashlib.sha256(cl2).hexdigest()
@@ -1842,7 +1825,6 @@ async def create_job(
allow_http_source_val: bool = request.app.state.allow_http_source
language_val: str = request.app.state.language
ocr_mode_val: str = request.app.state.ocr_mode
- effort_val = runtime.effort
image_analysis_val: bool = request.app.state.image_analysis
# async — fire and forget
@@ -1855,7 +1837,6 @@ async def create_job(
server_backend=backend,
language=language_val,
ocr_mode=ocr_mode_val,
- effort=effort_val,
image_analysis=image_analysis_val,
url_timeout=url_timeout_val,
allow_local_source=allow_local_source_val,
@@ -2074,7 +2055,7 @@ def _preload_local_models(language: str) -> None:
from ..backend.local_model_runtime import HybridLocalModelContextSingleton
from ..model.model_types import AtomicModelName
- context = HybridLocalModelContextSingleton().get_model(lang=language, formula_enable=True)
+ context = HybridLocalModelContextSingleton().get_model()
manager = context.atom_model_manager
manager.get_atom_model(atom_model_name=AtomicModelName.TableOrientationCls)
manager.get_atom_model(atom_model_name=AtomicModelName.TableCls)
@@ -2154,7 +2135,7 @@ def create_app(
default_tier = select_default_quality_tier(tier_runtime_options)
startup_runtime = runtime_options_for_tier(tier)
backend = startup_runtime.backend
- effort = startup_runtime.effort
+ effort = effort_for_tier(tier)
_preflight_tier_dependencies(tier)
_api_key: str | None = api_key or None
_upload_dir = pathlib.Path(upload_dir) if upload_dir else pathlib.Path(tempfile.mkdtemp(prefix="mineru_"))
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 233d2b03..b41a8c79 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -6,18 +6,26 @@ from abc import ABC, abstractmethod
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
-from typing import Any
+from typing import Any, Literal
-from ..render import render_content_list, render_markdown, render_structured_content
+from ..render import render_markdown, render_structured_content
+from ..render.contracts import RenderMode
+from ..render.image import ImageRenderer
from ..render.writer import DataWriter
-from ..types import PageInfo
+from ..types import MiddleJson, PageInfo
from ..utils.image_payload import ImagePayloadCache
from ..utils.pdf_document import PDFDocument
-MIDDLE_JSON_SCHEMA_VERSION: str = "1.0"
+MIDDLE_JSON_SCHEMA_VERSION: str = "2.0"
+_LEGACY_SCHEMA_VERSION: str = "1.0"
+_LEGACY_DEFAULT_FILE_SUFFIX: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf"
+_LEGACY_DEFAULT_EFFORT: Literal["flash", "low", "medium", "high", "xhigh"] = "medium"
+_LEGACY_DEFAULT_PARSE_MODE: Literal["txt", "ocr"] = "txt"
_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"
_PDF_BROKEN_PAGE_INDICES_KEY = "_pdf_broken_page_indices"
-_SUPPORTED_MIDDLE_JSON_BACKENDS = {"hybrid", "office"}
+_TO_DICT_EXCLUDED_KEYS: frozenset[str] = frozenset(
+ {"schema_version", _PDF_RETAINED_PAGE_INDICES_KEY, _PDF_BROKEN_PAGE_INDICES_KEY}
+)
def _parse_optional_int_list(value: Any) -> list[int] | None:
@@ -36,17 +44,22 @@ def _parse_optional_int_list(value: Any) -> list[int] | None:
class ParseResult:
"""The parsed result of a document.
- Holds the typed middle representation and exposes markdown / content-list
- / images as lazily-computed methods. Call ``save(writer)`` to persist.
+ Holds the typed middle representation and exposes markdown / structured
+ content / images as lazily-computed methods. Call ``save(writer)`` to persist.
"""
- pages: list[PageInfo]
+ middle_json: MiddleJson
_pdf_doc: PDFDocument | None = None
_model_output: Any = None
_image_cache: ImagePayloadCache | dict[str, bytes] | None = None
_retained_page_indices: list[int] | None = None
_broken_page_indices: list[int] | None = None
+ @property
+ def pages(self) -> list[PageInfo]:
+ """顶层页面列表,委托给 MiddleJson。"""
+ return self.middle_json.pages
+
def __post_init__(self) -> None:
"""规范化顶层图片缓存,确保 public middle_json 不再从 span 携带图片字节。"""
if self._image_cache is None:
@@ -59,63 +72,58 @@ class ParseResult:
if not isinstance(d, dict):
raise ValueError("ParseResult.from_dict expects a dict.")
- if "pages" not in d:
- raise ValueError("ParseResult JSON must contain a list field named pages.")
-
- raw_pages = d["pages"]
- if not isinstance(raw_pages, list):
- raise ValueError("ParseResult pages must be a list.")
-
- root_backend = d.get("_backend")
- if not isinstance(root_backend, str):
- root_backend = None
- elif root_backend not in _SUPPORTED_MIDDLE_JSON_BACKENDS:
- raise ValueError(f"Unsupported middle json backend '{root_backend}'.")
- pages: list[PageInfo] = []
- for raw_page in raw_pages:
- if not isinstance(raw_page, dict):
- raise ValueError("ParseResult page entries must be dicts.")
- page = PageInfo.from_dict(raw_page)
- backend = raw_page.get("_backend")
- if not isinstance(backend, str):
- backend = root_backend
- elif backend not in _SUPPORTED_MIDDLE_JSON_BACKENDS:
- raise ValueError(f"Unsupported middle json backend '{backend}'.")
- if backend is not None:
- page._backend = backend
- pages.append(page)
+ schema_version = d.get("schema_version", _LEGACY_SCHEMA_VERSION)
retained_page_indices = _parse_optional_int_list(d.get(_PDF_RETAINED_PAGE_INDICES_KEY))
broken_page_indices = _parse_optional_int_list(d.get(_PDF_BROKEN_PAGE_INDICES_KEY))
+
+ if schema_version == MIDDLE_JSON_SCHEMA_VERSION:
+ middle_json = ParseResult._build_middle_json_from_v2(d)
+ else:
+ middle_json = ParseResult._build_middle_json_from_legacy(d)
+
return ParseResult(
- pages=pages,
+ middle_json=middle_json,
_retained_page_indices=retained_page_indices,
_broken_page_indices=broken_page_indices,
)
- def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
- payload = {
- "schema_version": MIDDLE_JSON_SCHEMA_VERSION,
- "pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages],
- }
- self._append_root_backend(payload, self.pages)
- self._append_private_pdf_page_mapping(payload)
- return payload
+ @staticmethod
+ def _build_middle_json_from_v2(d: dict[str, Any]) -> MiddleJson:
+ """从 2.0 schema 直接构造 MiddleJson,pages 与元数据字段齐全。"""
+ payload = {k: v for k, v in d.items() if k not in _TO_DICT_EXCLUDED_KEYS}
+ return MiddleJson.model_validate(payload)
@staticmethod
- def _append_root_backend(payload: dict[str, Any], pages: list[PageInfo]) -> None:
- """在 envelope 级别保存统一 backend,避免 public page 字段暴露私有属性。"""
- backend = next((page._backend for page in pages if page._backend), None)
- if backend is None:
- return
- if all(page._backend in (None, backend) for page in pages):
- payload["_backend"] = backend
-
- def _append_private_pdf_page_mapping(self, payload: dict[str, Any]) -> None:
- """附加 PDF 重写页映射的内部元数据,供本地可视化按实际 PDF 页序绘制。"""
+ def _build_middle_json_from_legacy(d: dict[str, Any]) -> MiddleJson:
+ """从 1.0 schema 兼容构造 MiddleJson,preproc_blocks 回推为 raw model_list 重走后处理。"""
+ raw_pages = d.get("pages")
+ if not isinstance(raw_pages, list):
+ raise ValueError("ParseResult JSON must contain a list field named pages.")
+
+ from ..backend.postprocess.legacy_schema_adapter import legacy_page_to_model_list
+ from ..backend.postprocess.pages import model_list_to_pages
+
+ model_list = [legacy_page_to_model_list(page) for page in raw_pages]
+ pages = model_list_to_pages(model_list) if model_list else []
+
+ from ..version import __version__ as mineru_version
+
+ return MiddleJson(
+ pages=pages,
+ file_suffix=_LEGACY_DEFAULT_FILE_SUFFIX,
+ effort=_LEGACY_DEFAULT_EFFORT,
+ parse_mode=_LEGACY_DEFAULT_PARSE_MODE,
+ mineru_version=mineru_version,
+ )
+
+ def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
+ payload: dict[str, Any] = {"schema_version": MIDDLE_JSON_SCHEMA_VERSION}
+ payload.update(self.middle_json.to_dict(skip_defaults=skip_defaults))
if self._retained_page_indices is not None:
payload[_PDF_RETAINED_PAGE_INDICES_KEY] = list(self._retained_page_indices)
if self._broken_page_indices:
payload[_PDF_BROKEN_PAGE_INDICES_KEY] = list(self._broken_page_indices)
+ return payload
@staticmethod
def from_json(s: str) -> ParseResult:
@@ -127,27 +135,30 @@ class ParseResult:
def to_json(self) -> str:
return json.dumps(self.to_dict(), ensure_ascii=False, indent=4)
- def _public_render_pages(self) -> list[PageInfo]:
- """返回 public 渲染页;图片载荷已在 middle_json 生成阶段外置。"""
- return self.pages
-
- def markdown(self, *, add_markers: bool = False) -> str:
- return render_markdown(self._public_render_pages(), add_markers=add_markers)
-
- def content_list(self) -> list[dict[str, Any]]:
- return render_content_list(self._public_render_pages())
+ def markdown(
+ self,
+ *,
+ add_markers: bool = False,
+ mode: RenderMode | None = None,
+ asset_base_url: str = "",
+ image_renderer: ImageRenderer | None = None,
+ ) -> str:
+ if mode is None:
+ mode = RenderMode.FULL if add_markers else RenderMode.DEFAULT
+ return render_markdown(
+ self.middle_json,
+ mode=mode,
+ asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
+ )
- def structured_content(self) -> list[list[dict[str, Any]]]:
- return render_structured_content(self._public_render_pages())
+ def structured_content(self, *, asset_base_url: str = "") -> dict[str, Any]:
+ return render_structured_content(self.middle_json, asset_base_url=asset_base_url)
def save(self, writer: DataWriter) -> None:
writer.write_string("markdown.md", self.markdown())
writer.write_string("middle_json.json", self.to_json())
- writer.write_string(
- "content_list.json",
- json.dumps(self.content_list(), ensure_ascii=False, indent=4),
- )
writer.write_string(
"structured_content.json",
json.dumps(self.structured_content(), ensure_ascii=False, indent=4),
diff --git a/mineru/parser/mineru_parser.py b/mineru/parser/mineru_parser.py
new file mode 100644
index 00000000..f0214989
--- /dev/null
+++ b/mineru/parser/mineru_parser.py
@@ -0,0 +1,229 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""统一文档解析器,委托 mineru.backend.analyze 处理 PDF/图片/DOCX/PPTX/XLSX。"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Literal
+
+from ..backend.analyze import aio_doc_analyze, doc_analyze
+from ..errors import InvalidRequestError
+from ..filetypes import IMAGE_EXTENSIONS
+from ..types import MiddleJson, PageInfo, Tier
+from ..utils.backend_options import effort_for_tier
+from .base import DocumentParser, ParseResult
+
+logger = logging.getLogger(__name__)
+
+_Effort = Literal["flash", "low", "medium", "high", "xhigh"]
+_ParseMode = Literal["auto", "txt", "ocr"]
+_FileSuffix = Literal["pdf", "docx", "pptx", "xlsx"]
+_SUPPORTED_SUFFIXES: frozenset[str] = frozenset({"pdf", "docx", "pptx", "xlsx"})
+
+
+@dataclass
+class _PreparedInput:
+ """记录文档输入准备结果,避免跨文档复用 parser 实例状态。"""
+
+ file_name: str
+ file_bytes: bytes
+ file_suffix: _FileSuffix
+ retained_page_indices: list[int] | None = None
+ broken_page_indices: list[int] | None = None
+
+
+class MinerUParser(DocumentParser):
+ """统一文档解析器,支持 PDF/图片/DOCX/PPTX/XLSX。
+
+ 通过 file_suffix 路由到 backend.analyze 的统一 doc_analyze 入口,
+ 保留 PDF 输入的图片转 PDF、页范围重写、坏页补齐等预处理逻辑。
+ """
+
+ def __init__(
+ self,
+ *,
+ tier: Tier = "standard",
+ parse_mode: _ParseMode = "auto",
+ image_analysis: bool = True,
+ ) -> None:
+ self.tier: Tier = tier
+ self.effort: _Effort = effort_for_tier(tier) # type: ignore[assignment]
+ self.parse_mode: _ParseMode = parse_mode
+ self.image_analysis: bool = image_analysis
+
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
+ path = Path(path)
+ if not path.exists():
+ raise FileNotFoundError(path)
+
+ prepared = self._prepare_input(path, page_range)
+ middle_json, model_output = self._run_analysis(prepared)
+ if prepared.file_suffix == "pdf":
+ self._insert_broken_pages(
+ middle_json.pages,
+ prepared.retained_page_indices,
+ prepared.broken_page_indices,
+ )
+ return self._build_result(
+ middle_json,
+ model_output,
+ retained_page_indices=prepared.retained_page_indices,
+ broken_page_indices=prepared.broken_page_indices,
+ )
+
+ async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
+ path = Path(path)
+ if not path.exists():
+ raise FileNotFoundError(path)
+
+ prepared = await asyncio.to_thread(self._prepare_input, path, page_range)
+ middle_json, model_output = await self._arun_analysis(prepared)
+ if prepared.file_suffix == "pdf":
+ self._insert_broken_pages(
+ middle_json.pages,
+ prepared.retained_page_indices,
+ prepared.broken_page_indices,
+ )
+ return self._build_result(
+ middle_json,
+ model_output,
+ retained_page_indices=prepared.retained_page_indices,
+ broken_page_indices=prepared.broken_page_indices,
+ )
+
+ def _run_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, Any]:
+ return doc_analyze(
+ prepared.file_bytes,
+ effort=self.effort,
+ parse_mode=self.parse_mode,
+ image_analysis=self.image_analysis,
+ page_index_map=prepared.retained_page_indices,
+ file_suffix=prepared.file_suffix,
+ )
+
+ async def _arun_analysis(self, prepared: _PreparedInput) -> tuple[MiddleJson, Any]:
+ return await aio_doc_analyze(
+ prepared.file_bytes,
+ effort=self.effort,
+ parse_mode=self.parse_mode,
+ image_analysis=self.image_analysis,
+ page_index_map=prepared.retained_page_indices,
+ file_suffix=prepared.file_suffix,
+ )
+
+ def _prepare_input(self, path: Path, page_range: str = "") -> _PreparedInput:
+ from ..utils.guess_suffix_or_lang import guess_suffix_by_path
+ from ..utils.pdf_document import PDFDocument
+
+ file_name = path.stem
+ file_bytes = path.read_bytes()
+ suffix = guess_suffix_by_path(path)
+
+ if suffix in IMAGE_EXTENSIONS:
+ conversion_started_at = time.perf_counter()
+ input_size = len(file_bytes)
+ logger.debug(
+ "Image input conversion started filename=%s suffix=%s input_bytes=%d",
+ path.name,
+ suffix,
+ input_size,
+ )
+ file_bytes = PDFDocument.from_image(file_bytes).bytes
+ logger.debug(
+ "Image input conversion completed filename=%s suffix=%s input_bytes=%d pdf_bytes=%d elapsed_ms=%d",
+ path.name,
+ suffix,
+ input_size,
+ len(file_bytes),
+ round((time.perf_counter() - conversion_started_at) * 1000),
+ )
+ suffix = "pdf"
+
+ file_bytes, retained_page_indices, broken_page_indices = self._maybe_adjust_pdf_bytes(
+ file_bytes,
+ suffix,
+ page_range,
+ )
+ if suffix not in _SUPPORTED_SUFFIXES:
+ raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")
+ return _PreparedInput(
+ file_name=file_name,
+ file_bytes=file_bytes,
+ file_suffix=suffix, # type: ignore[arg-type]
+ retained_page_indices=retained_page_indices,
+ broken_page_indices=broken_page_indices,
+ )
+
+ def _maybe_adjust_pdf_bytes(
+ self,
+ file_bytes: bytes,
+ suffix: str,
+ page_range: str = "",
+ ) -> tuple[bytes, list[int] | None, list[int] | None]:
+ """仅 PDF 走页范围重写;Office 文件直接返回原字节。"""
+ if suffix != "pdf":
+ return file_bytes, None, None
+
+ from ..utils.pdf_document import PDFDocument
+ from ..utils.pdf_page_id import parse_page_range
+
+ doc = PDFDocument(file_bytes)
+ page_indices = parse_page_range(page_range, doc.page_count)
+ if page_range.strip() and not page_indices:
+ raise InvalidRequestError(
+ "page_range_invalid",
+ f"Page range does not select any pages: {page_range}",
+ "page_range",
+ )
+
+ if page_indices == list(range(doc.page_count)):
+ return file_bytes, None, None
+
+ from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium_result
+
+ rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(file_bytes, page_indices=page_indices)
+ if rewrite_result.used_original:
+ return rewrite_result.pdf_bytes or file_bytes, None, rewrite_result.broken_page_indices
+ return (
+ rewrite_result.pdf_bytes or file_bytes,
+ rewrite_result.retained_page_indices,
+ rewrite_result.broken_page_indices,
+ )
+
+ def _insert_broken_pages(
+ self,
+ pages: list[PageInfo],
+ retained_page_indices: list[int] | None = None,
+ broken_page_indices: list[int] | None = None,
+ ) -> None:
+ """按 PDF 重写结果补齐坏页空占位,不再修改 backend 已生成的页号。"""
+ if retained_page_indices is None or not broken_page_indices:
+ return
+
+ pages_by_index = {page.page_idx: page for page in pages}
+ ordered_page_indices = sorted(set(pages_by_index) | set(broken_page_indices))
+ pages[:] = [
+ pages_by_index.get(page_idx, PageInfo(page_idx=page_idx))
+ for page_idx in ordered_page_indices
+ ]
+
+ def _build_result(
+ self,
+ middle_json: MiddleJson,
+ model_output: Any = None,
+ *,
+ retained_page_indices: list[int] | None = None,
+ broken_page_indices: list[int] | None = None,
+ ) -> ParseResult:
+ return ParseResult(
+ middle_json=middle_json,
+ _model_output=model_output,
+ _retained_page_indices=retained_page_indices,
+ _broken_page_indices=broken_page_indices,
+ )
+
+
+__all__ = ["MinerUParser"]
diff --git a/mineru/parser/office.py b/mineru/parser/office.py
deleted file mode 100644
index bbfedcea..00000000
--- a/mineru/parser/office.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from abc import ABC
-from pathlib import Path
-from typing import Any
-
-from .base import DocumentParser, ParseResult
-from ..types import PageInfo
-from ..utils.image_payload import ImagePayloadCache
-
-
-class OfficeBaseParser(DocumentParser, ABC):
- """Abstract base for DOCX, PPTX, XLSX parsers.
-
- Subclasses supply the analyze function and file suffix.
- """
-
- _analyze_fn: Any
- _suffix: str
-
- def __init__(self, *, return_model_output: bool = True):
- self.return_model_output = return_model_output
-
- def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- path = Path(path)
- if not path.exists():
- raise FileNotFoundError(path)
-
- file_name = path.stem
- file_bytes = path.read_bytes()
- image_cache = ImagePayloadCache()
- middle_json, model_output = self._analyze_fn(file_bytes, image_cache=image_cache)
- return self._build_result(middle_json, file_name, model_output, image_cache)
-
- def _build_result(
- self,
- middle_json: list[PageInfo],
- file_name: str,
- model_output: Any = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> ParseResult:
- return ParseResult(
- pages=middle_json,
- _model_output=model_output if self.return_model_output else None,
- _image_cache=image_cache,
- )
-
-
-class DocxParser(OfficeBaseParser):
- _suffix = "docx"
-
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- from ..backend.office.docx_analyze import office_docx_analyze
-
- self._analyze_fn = office_docx_analyze
-
-
-class PptxParser(OfficeBaseParser):
- _suffix = "pptx"
-
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- from ..backend.office.pptx_analyze import office_pptx_analyze
-
- self._analyze_fn = office_pptx_analyze
-
-
-class XlsxParser(OfficeBaseParser):
- _suffix = "xlsx"
-
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- from ..backend.office.xlsx_analyze import office_xlsx_analyze
-
- self._analyze_fn = office_xlsx_analyze
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
deleted file mode 100644
index e571bb5b..00000000
--- a/mineru/parser/pdf.py
+++ /dev/null
@@ -1,402 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import asyncio
-import logging
-import os
-import time
-from abc import abstractmethod
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-from ..errors import InvalidRequestError
-from ..filetypes import IMAGE_EXTENSIONS
-from ..types import PageInfo
-from ..utils.backend_options import (
- CANONICAL_HYBRID_ENGINE,
- DEFAULT_HYBRID_EFFORT,
- LOCAL_HYBRID_EFFORT,
- MAX_HYBRID_EFFORT,
- resolve_backend_and_effort,
- validate_effort,
-)
-from ..utils.image_payload import ImagePayloadCache
-from .base import DocumentParser, ParseResult
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class _PreparedPdfInput:
- """记录 PDF 输入准备结果,避免跨文档复用 parser 实例状态。"""
-
- file_name: str
- pdf_bytes: bytes
- retained_page_indices: list[int] | None = None
- broken_page_indices: list[int] | None = None
-
-
-def _resolve_hybrid_backend(backend: str, *, is_async: bool = False) -> str:
- """根据同步/异步调用形态解析公开 Hybrid backend 到具体执行 engine。"""
- resolved = backend[7:] if backend.startswith("hybrid-") else backend
- if resolved in {"engine", "auto-engine"}:
- from ..utils.engine_utils import get_vlm_engine
-
- resolved = get_vlm_engine(inference_engine="auto", is_async=is_async)
- return resolved
-
-
-class PdfBaseParser(DocumentParser):
- _parse_method: str = ""
- _backend: str = ""
-
- def __init__(
- self,
- *,
- backend: str = "hybrid-engine",
- method: str = "auto",
- lang: str = "ch",
- effort: str = DEFAULT_HYBRID_EFFORT,
- image_analysis: bool = True,
- server_url: str | None = None,
- ):
- self.backend = backend
- self.method = method
- self.lang = lang
- self.effort = validate_effort(effort)
- self.image_analysis = image_analysis
- self.server_url = server_url
-
- def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- path = Path(path)
- if not path.exists():
- raise FileNotFoundError(path)
-
- prepared = self._prepare_input(path, page_range)
- image_cache = ImagePayloadCache()
- middle_json, model_output = self._run_analysis(
- prepared.pdf_bytes,
- page_index_map=prepared.retained_page_indices,
- image_cache=image_cache,
- )
- self._insert_broken_pages(
- middle_json,
- prepared.retained_page_indices,
- prepared.broken_page_indices,
- )
- return self._build_result(
- middle_json,
- prepared.pdf_bytes,
- prepared.file_name,
- retained_page_indices=prepared.retained_page_indices,
- broken_page_indices=prepared.broken_page_indices,
- image_cache=image_cache,
- model_output=model_output,
- )
-
- async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- path = Path(path)
- if not path.exists():
- raise FileNotFoundError(path)
-
- prepared = await asyncio.to_thread(self._prepare_input, path, page_range)
- image_cache = ImagePayloadCache()
- middle_json, model_output = await self._arun_analysis(
- prepared.pdf_bytes,
- page_index_map=prepared.retained_page_indices,
- image_cache=image_cache,
- )
- self._insert_broken_pages(
- middle_json,
- prepared.retained_page_indices,
- prepared.broken_page_indices,
- )
- return self._build_result(
- middle_json,
- prepared.pdf_bytes,
- prepared.file_name,
- retained_page_indices=prepared.retained_page_indices,
- broken_page_indices=prepared.broken_page_indices,
- image_cache=image_cache,
- model_output=model_output,
- )
-
- @abstractmethod
- def _run_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> tuple[list[PageInfo], Any]:
- """执行后端 PDF 分析,返回 middle_json 页面和原始 model_output。"""
-
- async def _arun_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> tuple[list[PageInfo], Any]:
- return await asyncio.to_thread(
- self._run_analysis,
- pdf_bytes,
- page_index_map=page_index_map,
- image_cache=image_cache,
- )
-
- def _prepare_input(self, path: Path, page_range: str = "") -> _PreparedPdfInput:
- from ..utils.guess_suffix_or_lang import guess_suffix_by_path
- from ..utils.pdf_document import PDFDocument
-
- file_name = path.stem
- pdf_bytes = path.read_bytes()
-
- suffix = guess_suffix_by_path(path)
- if suffix in IMAGE_EXTENSIONS:
- conversion_started_at = time.perf_counter()
- input_size = len(pdf_bytes)
- logger.debug(
- "Image input conversion started filename=%s suffix=%s input_bytes=%d",
- path.name,
- suffix,
- input_size,
- )
- pdf_bytes = PDFDocument.from_image(pdf_bytes).bytes
- logger.debug(
- "Image input conversion completed filename=%s suffix=%s input_bytes=%d pdf_bytes=%d elapsed_ms=%d",
- path.name,
- suffix,
- input_size,
- len(pdf_bytes),
- round((time.perf_counter() - conversion_started_at) * 1000),
- )
-
- pdf_bytes, retained_page_indices, broken_page_indices = self._maybe_adjust_pdf_bytes(
- pdf_bytes,
- suffix,
- page_range,
- )
- return _PreparedPdfInput(
- file_name=file_name,
- pdf_bytes=pdf_bytes,
- retained_page_indices=retained_page_indices,
- broken_page_indices=broken_page_indices,
- )
-
- def _maybe_adjust_pdf_bytes(
- self,
- pdf_bytes: bytes,
- suffix: str,
- page_range: str = "",
- ) -> tuple[bytes, list[int] | None, list[int] | None]:
- if suffix != "pdf":
- return pdf_bytes, None, None
-
- from ..utils.pdf_document import PDFDocument
- from ..utils.pdf_page_id import parse_page_range
-
- doc = PDFDocument(pdf_bytes)
- page_indices = parse_page_range(page_range, doc.page_count)
- if page_range.strip() and not page_indices:
- raise InvalidRequestError("page_range_invalid", f"Page range does not select any pages: {page_range}", "page_range")
-
- if page_indices == list(range(doc.page_count)):
- return pdf_bytes, None, None
-
- from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium_result
-
- rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(pdf_bytes, page_indices=page_indices)
- if rewrite_result.used_original:
- return rewrite_result.pdf_bytes or pdf_bytes, None, rewrite_result.broken_page_indices
- return (
- rewrite_result.pdf_bytes or pdf_bytes,
- rewrite_result.retained_page_indices,
- rewrite_result.broken_page_indices,
- )
-
- def _insert_broken_pages(
- self,
- pages: list[PageInfo],
- retained_page_indices: list[int] | None = None,
- broken_page_indices: list[int] | None = None,
- ) -> None:
- """按 PDF 重写结果补齐坏页空占位,不再修改 backend 已生成的页号。"""
- if retained_page_indices is None or not broken_page_indices:
- return
-
- backend = next((page._backend for page in pages if page._backend), None)
- pages_by_index = {page.page_idx: page for page in pages}
- ordered_page_indices = sorted(set(pages_by_index) | set(broken_page_indices))
- pages[:] = [
- pages_by_index.get(page_idx, PageInfo(page_idx=page_idx, _backend=backend)) for page_idx in ordered_page_indices
- ]
-
- def _build_result(
- self,
- middle_json: list[PageInfo],
- pdf_bytes: bytes,
- file_name: str,
- *,
- retained_page_indices: list[int] | None = None,
- broken_page_indices: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- model_output: Any = None,
- ) -> ParseResult:
- return ParseResult(
- pages=middle_json,
- _retained_page_indices=retained_page_indices,
- _broken_page_indices=broken_page_indices,
- _image_cache=image_cache,
- _model_output=model_output,
- )
-
-
-class PdfHybridParser(PdfBaseParser):
- """PDF / image parser using the Hybrid local/VLM backend."""
-
- _parse_method: str = ""
- _backend = "hybrid"
-
- def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- self._parse_method = f"hybrid_{self.method}"
- return super().parse(path, page_range=page_range)
-
- async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- self._parse_method = f"hybrid_{self.method}"
- return await super().parse_async(path, page_range=page_range)
-
- def _run_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> tuple[list[PageInfo], Any]:
- from ..backend.pdf.analyze import doc_analyze as hybrid_doc_analyze
-
- backend = (
- self.backend
- if self.effort == LOCAL_HYBRID_EFFORT
- else _resolve_hybrid_backend(self.backend, is_async=False)
- )
- server_url = self.server_url if backend.endswith("client") else None
- middle_json, model_list = hybrid_doc_analyze(
- pdf_bytes=pdf_bytes,
- effort=self.effort,
- parse_mode=self.method,
- image_analysis=self.image_analysis,
- page_index_map=page_index_map,
- image_cache=image_cache,
- )
-
- return middle_json, model_list
-
- async def _arun_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> tuple[list[PageInfo], Any]:
- from ..backend.pdf.analyze import aio_doc_analyze as hybrid_aio_doc_analyze
-
- backend = (
- self.backend if self.effort == LOCAL_HYBRID_EFFORT else _resolve_hybrid_backend(self.backend, is_async=True)
- )
- server_url = self.server_url if backend.endswith("client") else None
- middle_json, model_list, _vlm_ocr_enable = await hybrid_aio_doc_analyze(
- pdf_bytes,
- backend=backend,
- parse_method=self.method,
- language=self.lang,
- effort=self.effort,
- server_url=server_url,
- image_analysis=self.image_analysis,
- page_index_map=page_index_map,
- image_cache=image_cache,
- )
-
- return middle_json, model_list
-
-
-class PdfPipelineParser(PdfHybridParser):
- """保留旧 SDK 类名,内部统一委托 Hybrid medium effort 解析。"""
-
- def __init__(self, **kwargs: Any) -> None:
- """将旧 PdfPipelineParser 构造参数归一到 Hybrid medium effort,避免继续加载旧 backend。"""
- kwargs.pop("backend", None)
- kwargs.pop("effort", None)
- super().__init__(backend=CANONICAL_HYBRID_ENGINE, effort=LOCAL_HYBRID_EFFORT, **kwargs)
-
-
-class PdfVlmParser(PdfHybridParser):
- """保留旧 SDK 类名,内部统一委托 Hybrid xhigh effort 解析。"""
-
- def __init__(self, **kwargs: Any) -> None:
- """将旧 PdfVlmParser 构造参数归一到 Hybrid xhigh effort,避免继续暴露独立 VLM backend。"""
- backend = kwargs.pop("backend", "vlm-engine")
- kwargs.pop("effort", None)
- resolved_backend, resolved_effort = resolve_backend_and_effort(backend, MAX_HYBRID_EFFORT)
- super().__init__(backend=resolved_backend, effort=resolved_effort, **kwargs)
-
-
-class PdfFlashParser(PdfBaseParser):
- """PDF / image parser using the flash backend."""
-
- _backend = "flash"
-
- def _run_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> tuple[list[PageInfo], Any]:
- from ..backend.flash.pdf_extractor import extract_pages_text
- from ..types import Block, Line, PageInfo, Span
- from ..utils.page_index import resolve_output_page_idx
-
- extraction_started_at = time.perf_counter()
- logger.debug(
- "Flash PDF extraction started pdf_bytes=%d mapped_pages=%s",
- len(pdf_bytes),
- len(page_index_map) if page_index_map is not None else "all",
- )
- filepath = self._pdf_bytes_to_tempfile(pdf_bytes)
- try:
- pages_text = extract_pages_text(filepath)
- finally:
- try:
- os.unlink(filepath)
- except OSError:
- pass
- logger.debug(
- "Flash PDF extraction completed pages=%d elapsed_ms=%d",
- len(pages_text),
- round((time.perf_counter() - extraction_started_at) * 1000),
- )
-
- pages: list[PageInfo] = []
- block_idx = 0
- for index, pt in enumerate(pages_text):
- page_idx = resolve_output_page_idx(index, page_index_map)
- para_blocks: list[Block] = []
- if pt.strip():
- span = Span(type="text", bbox=(0.0, 0.0, 0.0, 0.0), content=pt.strip())
- line = Line(bbox=(0.0, 0.0, 0.0, 0.0), spans=[span])
- block = Block(index=block_idx, type="text", bbox=(0.0, 0.0, 0.0, 0.0), lines=[line])
- para_blocks.append(block)
- block_idx += 1
- page = PageInfo(
- page_idx=page_idx,
- para_blocks=para_blocks,
- )
- pages.append(page)
-
- return pages, None
-
- @staticmethod
- def _pdf_bytes_to_tempfile(pdf_bytes: bytes) -> str:
- import tempfile
-
- tmp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
- tmp.write(pdf_bytes)
- tmp.close()
- return tmp.name
diff --git a/mineru/parser/tier.py b/mineru/parser/tier.py
index b5fdb743..49674fbb 100644
--- a/mineru/parser/tier.py
+++ b/mineru/parser/tier.py
@@ -10,16 +10,12 @@ from importlib import metadata as importlib_metadata
from ..types import DEPLOYMENT_TIERS, DeploymentTier, Tier, validate_tier
from ..utils.backend_options import (
CANONICAL_HYBRID_ENGINE,
- DEFAULT_HYBRID_EFFORT,
LEGACY_PIPELINE_BACKEND_ALIASES,
LEGACY_VLM_BACKEND_ALIASES,
- LOCAL_HYBRID_EFFORT,
SUPPORTED_BACKENDS,
effort_for_tier,
is_hybrid_backend,
normalize_backend,
- resolve_backend_and_effort,
- tier_for_effort,
)
__all__ = [
@@ -109,7 +105,7 @@ def tier_for_backend(backend: str) -> Tier:
if normalized_backend == "flash":
return "flash"
if is_hybrid_backend(normalized_backend):
- return _tier_for_effort(DEFAULT_HYBRID_EFFORT)
+ return "standard"
raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PARSER_BACKENDS)}")
@@ -133,10 +129,6 @@ def _backend_supports_tier(backend: str, tier: Tier) -> bool:
return False
-def _tier_for_effort(effort: str) -> Tier:
- return validate_tier(tier_for_effort(effort))
-
-
def resolve_tier_and_backend(tier: Tier | None = None, backend: str | None = None) -> tuple[Tier, str]:
"""将公开 tier 和本地专家 backend 解析为可执行 parser backend。"""
resolved_tier: Tier = validate_tier(tier) if tier is not None else "standard"
@@ -150,45 +142,20 @@ def resolve_tier_and_backend(tier: Tier | None = None, backend: str | None = Non
return resolved_tier, backend_for_tier(resolved_tier)
-def _effort_for_runtime(
- *,
- tier: Tier,
- backend: str,
- requested_effort: str | None,
- raw_backend: str | None,
- explicit_tier: bool,
-) -> str:
- """按 tier 优先解析 Hybrid effort;无 tier 时保留旧 backend/effort 兼容输入。"""
+def _effort_for_runtime(*, tier: Tier, backend: str) -> str:
+ """按 tier 派生 Hybrid effort;flash tier 直接返回 flash effort。"""
if backend == "flash":
- return LOCAL_HYBRID_EFFORT
- if explicit_tier:
- return effort_for_tier(tier)
- _resolved_backend, resolved_effort = resolve_backend_and_effort(
- raw_backend or backend,
- requested_effort or DEFAULT_HYBRID_EFFORT,
- )
- return resolved_effort
+ return "flash"
+ return effort_for_tier(tier)
def resolve_runtime_options(
tier: Tier | None = None,
backend: str | None = None,
- effort: str | None = None,
) -> ParserRuntimeOptions:
- """统一解析 parser 运行所需的 tier/backend/effort,避免入口各自硬编码映射。"""
- explicit_tier = tier is not None
+ """统一解析 parser 运行所需的 tier/backend,effort 作为派生值不暴露为入参。"""
resolved_tier, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
- if resolved_backend != "flash":
- resolved_backend, _ = resolve_backend_and_effort(backend or resolved_backend, effort)
- resolved_effort = _effort_for_runtime(
- tier=resolved_tier,
- backend=resolved_backend,
- requested_effort=effort,
- raw_backend=backend,
- explicit_tier=explicit_tier,
- )
- if not explicit_tier and resolved_backend != "flash":
- resolved_tier = _tier_for_effort(resolved_effort)
+ resolved_effort = _effort_for_runtime(tier=resolved_tier, backend=resolved_backend)
return ParserRuntimeOptions(tier=resolved_tier, backend=resolved_backend, effort=resolved_effort)
@@ -196,10 +163,9 @@ def runtime_options_for_tier(
tier: Tier,
*,
backend: str | None = None,
- effort: str | None = None,
) -> ParserRuntimeOptions:
"""解析指定 tier 的默认 runtime;调用端可传 backend 覆盖本地/远端执行形态。"""
- return resolve_runtime_options(tier=tier, backend=backend, effort=effort)
+ return resolve_runtime_options(tier=tier, backend=backend)
def required_modules_for_tier(tier: DeploymentTier) -> list[str]:
diff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.py
index 6b75b030..4a731d90 100644
--- a/mineru/render/_internal/markdown/blocks.py
+++ b/mineru/render/_internal/markdown/blocks.py
@@ -18,6 +18,7 @@ from mineru.render._internal.markdown.inline import (
render_joined_inline_contents,
)
from mineru.render._internal.markdown.table import format_embedded_html, render_html_table
+from mineru.render.image import ImageRenderer
from mineru.types import (
RAW_ALGORITHM,
BlockType,
@@ -56,6 +57,7 @@ def render_planned_block(
*,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""按具体 Pydantic block 类型分发 Markdown 渲染。"""
block = planned.block
@@ -71,17 +73,17 @@ def render_planned_block(
content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
return escape_standalone_marker_rule(content)
if isinstance(block, EquationBlock):
- return _render_equation(block, delimiters, asset_base_url)
+ return _render_equation(block, delimiters, asset_base_url, image_renderer)
if isinstance(block, ListBlock):
return _render_list(block, delimiters)
if isinstance(block, IndexBlock):
return _render_index(block, delimiters)
if isinstance(block, ImageBlock):
- return _render_image_block(block, delimiters, asset_base_url)
+ return _render_image_block(block, delimiters, asset_base_url, image_renderer)
if isinstance(block, TableBlock):
- return _render_table_block(block, delimiters, asset_base_url)
+ return _render_table_block(block, delimiters, asset_base_url, image_renderer)
if isinstance(block, ChartBlock):
- return _render_chart_block(block, delimiters, asset_base_url)
+ return _render_chart_block(block, delimiters, asset_base_url, image_renderer)
if isinstance(block, CodeBlock):
return _render_code_block(block, delimiters)
raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
@@ -92,6 +94,7 @@ def render_single_block(
*,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""不执行续段合并或页面过滤,直接渲染一个顶层 block。"""
text_contents = [block.content] if isinstance(block, (TextBlock, RefTextBlock)) else []
@@ -100,6 +103,7 @@ def render_single_block(
planned,
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
)
@@ -128,11 +132,16 @@ def _render_equation(
block: EquationBlock,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
) -> str:
- """优先渲染行间 LaTeX,空公式内容回退到公式图片。"""
+ """优先渲染行间 LaTeX,空公式内容回退到 image_renderer 或公式图片。"""
latex = block.content.strip()
if latex:
return f"{delimiters.display.left}\n{latex}\n{delimiters.display.right}"
+ if image_renderer is not None:
+ rendered = image_renderer(block)
+ if rendered:
+ return rendered
source = resolve_image_source(block, asset_base_url)
return build_markdown_image(source) if source else ""
@@ -182,6 +191,7 @@ def _render_image_block(
block: ImageBlock,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
) -> str:
"""按原始子块顺序渲染图片主体及说明文本。"""
parts: list[str] = []
@@ -192,6 +202,7 @@ def _render_image_block(
child,
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
)
elif isinstance(child, ImageAnnotationBlock):
body = render_visual_annotation(child, delimiters)
@@ -206,6 +217,7 @@ def _render_chart_block(
block: ChartBlock,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
) -> str:
"""按原始子块顺序渲染图表图片、结构内容和说明文本。"""
parts: list[str] = []
@@ -216,6 +228,7 @@ def _render_chart_block(
child,
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
)
elif isinstance(child, ChartAnnotationBlock):
body = render_visual_annotation(child, delimiters)
@@ -232,16 +245,20 @@ def _render_media_body(
summary: str,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
+ parent_block: ImageBlock,
) -> str:
- """渲染图片载荷,并将识别内容放入折叠详情。"""
- source = resolve_image_source(block, asset_base_url)
+ """渲染图片载荷,并将识别内容放入折叠详情。image_renderer 优先于 image_path。"""
rendered_content = _render_media_content(block, delimiters, asset_base_url)
- if source:
- parts = [build_markdown_image(source)]
- if rendered_content:
- parts.append(_render_details(rendered_content, summary))
- return "\n\n".join(part for part in parts if part)
- return rendered_content
+ if image_renderer is not None:
+ image_ref = image_renderer(parent_block)
+ parts = [image_ref] if image_ref else []
+ else:
+ source = resolve_image_source(block, asset_base_url)
+ parts = [build_markdown_image(source)] if source else []
+ if rendered_content:
+ parts.append(_render_details(rendered_content, summary))
+ return "\n\n".join(part for part in parts if part)
def _render_media_content(
@@ -262,14 +279,31 @@ def _render_chart_body(
summary: str,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
+ parent_block: ChartBlock,
) -> str:
- """渲染 chart 图片,并统一转换其 HTML 表格内容。"""
- source = resolve_image_source(block, asset_base_url)
+ """渲染 chart 图片,并统一转换其 HTML 表格内容。内容为空时回退到 image_renderer 或图片。"""
rendered_content = _render_chart_content(block.content, delimiters, asset_base_url)
+ if rendered_content:
+ return _render_chart_with_details(rendered_content, block, asset_base_url, summary)
+ if image_renderer is not None:
+ rendered = image_renderer(parent_block)
+ if rendered:
+ return rendered
+ source = resolve_image_source(block, asset_base_url)
+ return build_markdown_image(source) if source else ""
+
+
+def _render_chart_with_details(
+ rendered_content: str,
+ block: ChartBodyBlock,
+ asset_base_url: str,
+ summary: str,
+) -> str:
+ """chart 有结构化内容时,附上图片与折叠详情。"""
+ source = resolve_image_source(block, asset_base_url)
if source:
- parts = [build_markdown_image(source)]
- if rendered_content:
- parts.append(_render_details(rendered_content, summary))
+ parts = [build_markdown_image(source), _render_details(rendered_content, summary)]
return "\n\n".join(part for part in parts if part)
return rendered_content
@@ -303,6 +337,7 @@ def _render_table_block(
block: TableBlock,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
) -> str:
"""按原始子块顺序渲染表格主体及说明文本。"""
parts: list[str] = []
@@ -313,6 +348,7 @@ def _render_table_block(
child,
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
)
elif isinstance(child, TableAnnotationBlock):
body = render_visual_annotation(child, delimiters)
@@ -327,11 +363,17 @@ def _render_table_body(
block: TableBodyBlock,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None,
+ parent_block: TableBlock,
) -> str:
- """按 HTML、空间投影文本、图片的优先级渲染表格主体。"""
+ """按 HTML、空间投影文本、image_renderer、图片的优先级渲染表格主体。"""
rendered_content = _render_table_content(block, delimiters, asset_base_url)
if rendered_content:
return rendered_content
+ if image_renderer is not None:
+ rendered = image_renderer(parent_block)
+ if rendered:
+ return rendered
source = resolve_image_source(block, asset_base_url)
return build_markdown_image(source) if source else ""
@@ -364,6 +406,7 @@ def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> s
child,
delimiters=delimiters,
asset_base_url="",
+ image_renderer=None,
)
elif isinstance(child, CodeAnnotationBlock):
body = render_visual_annotation(child, delimiters)
@@ -399,6 +442,7 @@ def _render_visual_body_child(
*,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""按视觉父子类型组合渲染一个 body 子块。"""
if isinstance(block, ImageBlock) and isinstance(child, ImageBodyBlock):
@@ -407,15 +451,19 @@ def _render_visual_body_child(
summary=block.sub_type or "image content",
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
+ parent_block=block,
)
if isinstance(block, TableBlock) and isinstance(child, TableBodyBlock):
- return _render_table_body(child, delimiters, asset_base_url)
+ return _render_table_body(child, delimiters, asset_base_url, image_renderer, block)
if isinstance(block, ChartBlock) and isinstance(child, ChartBodyBlock):
return _render_chart_body(
child,
summary=block.sub_type or "chart content",
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
+ parent_block=block,
)
if isinstance(block, CodeBlock) and isinstance(child, CodeBodyBlock):
return _render_code_body(block, child, delimiters)
diff --git a/mineru/render/api.py b/mineru/render/api.py
index ab62f422..e569de26 100644
--- a/mineru/render/api.py
+++ b/mineru/render/api.py
@@ -86,6 +86,7 @@ def render(
middle_json,
mode=resolved_options.mode,
asset_base_url=resolved_options.asset_base_url,
+ image_renderer=resolved_options.image_renderer,
)
if output_format is RenderFormat.HTML:
diff --git a/mineru/render/contracts.py b/mineru/render/contracts.py
index d04ea804..57ac8440 100644
--- a/mineru/render/contracts.py
+++ b/mineru/render/contracts.py
@@ -7,6 +7,8 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, TypeAlias
+from .image import ImageRenderer
+
class RenderFormat(str, Enum):
"""统一渲染入口支持的目标格式。"""
@@ -48,11 +50,14 @@ class MarkdownRenderOptions:
mode: RenderMode = RenderMode.DEFAULT
asset_base_url: str = ""
+ image_renderer: ImageRenderer | None = None
def __post_init__(self) -> None:
"""在构造时拒绝不符合严格公共契约的选项值。"""
_validate_mode(self.mode)
_validate_asset_base_url(self.asset_base_url)
+ if self.image_renderer is not None and not callable(self.image_renderer):
+ raise TypeError("image_renderer must be callable or None")
@dataclass(frozen=True, slots=True)
diff --git a/mineru/render/image.py b/mineru/render/image.py
index 729d1b43..1209292e 100644
--- a/mineru/render/image.py
+++ b/mineru/render/image.py
@@ -3,35 +3,39 @@ from __future__ import annotations
import re
from collections.abc import Callable
-from ..types import Block, BlockType, ContentType
+from ..types import BlockBase, BlockType, ImagePayloadBlock, _iter_child_blocks
-ImageRenderer = Callable[[Block], str]
+ImageRenderer = Callable[[BlockBase], str]
-_VISUAL_SPAN_TYPES: dict[str, str] = {
- BlockType.IMAGE: ContentType.IMAGE,
- BlockType.TABLE: ContentType.TABLE,
- BlockType.CHART: ContentType.CHART,
- BlockType.INTERLINE_EQUATION: ContentType.INTERLINE_EQUATION,
-}
+_VISUAL_BLOCK_TYPES: frozenset[str] = frozenset({
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.EQUATION,
+})
-def image_path_renderer(block: Block, *, img_bucket_path: str = "") -> str:
+def image_path_renderer(block: BlockBase, *, img_bucket_path: str = "") -> str:
"""Render the image paths belonging to one top-level visual block."""
- span_type = _VISUAL_SPAN_TYPES.get(block.type)
- if span_type is None:
+ if block.type not in _VISUAL_BLOCK_TYPES:
return ""
references: list[str] = []
- for span in block.all_spans():
- if span.type != span_type or not span.image_path:
- continue
- media_path = f"{img_bucket_path}/{span.image_path}" if img_bucket_path else span.image_path
- references.append(f"![]({media_path})")
+ if isinstance(block, ImagePayloadBlock) and block.image_path:
+ references.append(_build_image_reference(block.image_path, img_bucket_path))
+ for child in _iter_child_blocks(block):
+ if isinstance(child, ImagePayloadBlock) and child.image_path:
+ references.append(_build_image_reference(child.image_path, img_bucket_path))
return " \n".join(references)
+def _build_image_reference(image_path: str, img_bucket_path: str) -> str:
+ media_path = f"{img_bucket_path}/{image_path}" if img_bucket_path else image_path
+ return f"![]({media_path})"
+
+
def strip_embedded_image_tags(content: str) -> str:
"""Remove embedded HTML images when a custom renderer owns image output."""
return re.sub(r"<img\b[^>]*>", "", content, flags=re.IGNORECASE)
-__all__ = ["ImageRenderer", "image_path_renderer"]
+__all__ = ["ImageRenderer", "image_path_renderer", "strip_embedded_image_tags"]
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 16023a5d..713dc66f 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -7,6 +7,7 @@ from mineru.config import LatexDelimitersConfig, config
from mineru.render._internal.common.planner import PlannedBlock, build_render_plan
from mineru.render._internal.markdown.blocks import render_planned_block
from mineru.render.contracts import MarkdownRenderMode
+from mineru.render.image import ImageRenderer
from mineru.types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson
_PAGE_SEPARATOR = "\n\n---\n\n"
@@ -17,6 +18,7 @@ def render_markdown(
*,
mode: MarkdownRenderMode = MarkdownRenderMode.DEFAULT,
asset_base_url: str = "",
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""把严格 MiddleJson 纯函数式渲染为 Markdown 字符串。"""
if not isinstance(middle_json, MiddleJson):
@@ -32,6 +34,7 @@ def render_markdown(
mode=mode,
delimiters=delimiters,
asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
)
for page in planned_pages
]
@@ -46,6 +49,7 @@ def _render_page(
mode: MarkdownRenderMode,
delimiters: LatexDelimitersConfig,
asset_base_url: str,
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""渲染单页逻辑块,并在默认模式中过滤重复页元素。"""
rendered: list[str] = []
@@ -54,7 +58,12 @@ def _render_page(
continue
if mode is MarkdownRenderMode.DEFAULT and planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
continue
- text = render_planned_block(planned, delimiters=delimiters, asset_base_url=asset_base_url)
+ text = render_planned_block(
+ planned,
+ delimiters=delimiters,
+ asset_base_url=asset_base_url,
+ image_renderer=image_renderer,
+ )
if text and text.strip():
rendered.append(text.strip("\n"))
return "\n\n".join(rendered)
diff --git a/mineru/types.py b/mineru/types.py
index 59ab7131..9823b167 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -4,8 +4,9 @@ from __future__ import annotations
import json
import math
import os
-from collections.abc import Iterable
+from collections.abc import Iterable, Sequence
from dataclasses import dataclass
+from enum import Enum
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Annotated, Any, ClassVar, Literal, TypeAlias, Union
@@ -141,7 +142,7 @@ def select_parsing_rule_tier(available_tiers: Iterable[object] | str | None = No
return "flash"
-class BlockType:
+class BlockType(str, Enum):
IMAGE = "image"
IMAGE_BODY = "image_body"
IMAGE_CAPTION = "image_caption"
@@ -180,6 +181,9 @@ class BlockType:
DOC_TITLE = "doc_title"
PARAGRAPH_TITLE = "paragraph_title"
+ def __str__(self) -> str:
+ return self.value
+
class ContentType:
IMAGE = "image"
@@ -457,11 +461,11 @@ class ContinuableTextBlockBase(StringContentBlock):
class TextBlock(ContinuableTextBlockBase):
- type: Literal[BlockType.TEXT]
+ type: Literal[BlockType.TEXT] # type: ignore[reportIncompatibleVariableOverride]
class RefTextBlock(ContinuableTextBlockBase):
- type: Literal[BlockType.REF_TEXT]
+ type: Literal[BlockType.REF_TEXT] # type: ignore[reportIncompatibleVariableOverride]
class TitleBlockBase(StringContentBlock):
@@ -472,19 +476,19 @@ class TitleBlockBase(StringContentBlock):
class DocTitleBlock(TitleBlockBase):
- type: Literal[BlockType.DOC_TITLE]
- level: Literal[1]
+ type: Literal[BlockType.DOC_TITLE] # type: ignore[reportIncompatibleVariableOverride]
+ level: int = Field(ge=1, le=1)
class ParagraphTitleBlock(TitleBlockBase):
- type: Literal[BlockType.PARAGRAPH_TITLE]
+ type: Literal[BlockType.PARAGRAPH_TITLE] # type: ignore[reportIncompatibleVariableOverride]
level: int = Field(ge=2, le=6)
class PageAuxTextBlock(StringContentBlock):
"""页眉、页脚、页码、边栏和页脚注释的共享文本结构。"""
- type: Literal[
+ type: Literal[ # type: ignore[reportIncompatibleVariableOverride]
BlockType.HEADER,
BlockType.FOOTER,
BlockType.PAGE_NUMBER,
@@ -517,47 +521,47 @@ class ImagePayloadContentBlock(ImagePayloadBlock):
class EquationBlock(ImagePayloadContentBlock):
- type: Literal[BlockType.EQUATION]
+ type: Literal[BlockType.EQUATION] # type: ignore[reportIncompatibleVariableOverride]
class ImageBodyBlock(ImagePayloadContentBlock):
- type: Literal[BlockType.IMAGE_BODY]
+ type: Literal[BlockType.IMAGE_BODY] # type: ignore[reportIncompatibleVariableOverride]
class TableBodyBlock(ImagePayloadContentBlock):
- type: Literal[BlockType.TABLE_BODY]
+ type: Literal[BlockType.TABLE_BODY] # type: ignore[reportIncompatibleVariableOverride]
class ChartBodyBlock(ImagePayloadContentBlock):
- type: Literal[BlockType.CHART_BODY]
+ type: Literal[BlockType.CHART_BODY] # type: ignore[reportIncompatibleVariableOverride]
class CodeBodyBlock(StringContentBlock):
- type: Literal[BlockType.CODE_BODY]
+ type: Literal[BlockType.CODE_BODY] # type: ignore[reportIncompatibleVariableOverride]
class ImageAnnotationBlock(StringContentBlock):
"""图片标题与图片脚注的共享结构。"""
- type: Literal[BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]
+ type: Literal[BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE] # type: ignore[reportIncompatibleVariableOverride]
class TableAnnotationBlock(StringContentBlock):
"""表格标题与表格脚注的共享结构。"""
- type: Literal[BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]
+ type: Literal[BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE] # type: ignore[reportIncompatibleVariableOverride]
class ChartAnnotationBlock(StringContentBlock):
"""图表标题与图表脚注的共享结构。"""
- type: Literal[BlockType.CHART_CAPTION, BlockType.CHART_FOOTNOTE]
+ type: Literal[BlockType.CHART_CAPTION, BlockType.CHART_FOOTNOTE] # type: ignore[reportIncompatibleVariableOverride]
class CodeAnnotationBlock(StringContentBlock):
"""代码标题与代码脚注的共享结构。"""
- type: Literal[BlockType.CODE_CAPTION, BlockType.CODE_FOOTNOTE]
+ type: Literal[BlockType.CODE_CAPTION, BlockType.CODE_FOOTNOTE] # type: ignore[reportIncompatibleVariableOverride]
ListChildBlock: TypeAlias = Annotated[
@@ -567,7 +571,7 @@ ListChildBlock: TypeAlias = Annotated[
class ListBlock(BlockBase):
- type: Literal[BlockType.LIST]
+ type: Literal[BlockType.LIST] # type: ignore[reportIncompatibleVariableOverride]
content: list[ListChildBlock]
sub_type: Literal[BlockType.TEXT, BlockType.REF_TEXT] | None = None
continues_prev: bool | None = None
@@ -580,7 +584,7 @@ IndexChildBlock: TypeAlias = Annotated[
class IndexBlock(BlockBase):
- type: Literal[BlockType.INDEX]
+ type: Literal[BlockType.INDEX] # type: ignore[reportIncompatibleVariableOverride]
content: list[IndexChildBlock]
@@ -611,7 +615,7 @@ ImageChildBlock: TypeAlias = Annotated[
class ImageBlock(_VisualBlockBase):
- type: Literal[BlockType.IMAGE]
+ type: Literal[BlockType.IMAGE] # type: ignore[reportIncompatibleVariableOverride]
content: list[ImageChildBlock]
sub_type: str | None = None
_body_type: ClassVar[str] = BlockType.IMAGE_BODY
@@ -624,7 +628,7 @@ TableChildBlock: TypeAlias = Annotated[
class TableBlock(_VisualBlockBase):
- type: Literal[BlockType.TABLE]
+ type: Literal[BlockType.TABLE] # type: ignore[reportIncompatibleVariableOverride]
content: list[TableChildBlock]
continues_prev: bool | None = None
cell_merge: list[Literal[0, 1]] | None = None
@@ -638,7 +642,7 @@ ChartChildBlock: TypeAlias = Annotated[
class ChartBlock(_VisualBlockBase):
- type: Literal[BlockType.CHART]
+ type: Literal[BlockType.CHART] # type: ignore[reportIncompatibleVariableOverride]
content: list[ChartChildBlock]
sub_type: str | None = None
_body_type: ClassVar[str] = BlockType.CHART_BODY
@@ -651,7 +655,7 @@ CodeChildBlock: TypeAlias = Annotated[
class CodeBlock(_VisualBlockBase):
- type: Literal[BlockType.CODE]
+ type: Literal[BlockType.CODE] # type: ignore[reportIncompatibleVariableOverride]
content: list[CodeChildBlock]
sub_type: Literal[BlockType.CODE, RAW_ALGORITHM]
guess_lang: str | None = None
@@ -805,7 +809,7 @@ class MiddleJsonExportResult:
image_paths: tuple[Path, ...]
-def _iter_page_blocks(blocks: list[Block]) -> list[BlockBase]:
+def _iter_page_blocks(blocks: Sequence[BlockBase]) -> list[BlockBase]:
"""按深度优先顺序展开页面 block 树,供图片外置统一遍历。"""
result: list[BlockBase] = []
pending: list[BlockBase] = list(reversed(blocks))
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
index 8511fe8c..7381c392 100644
--- a/mineru/utils/backend_options.py
+++ b/mineru/utils/backend_options.py
@@ -27,6 +27,7 @@ HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = (
MAX_HYBRID_EFFORT,
)
HYBRID_EFFORT_BY_TIER: Final[dict[str, str]] = {
+ "flash": "flash",
"basic": LOCAL_HYBRID_EFFORT,
"standard": LAYOUT_HYBRID_EFFORT,
"advanced": MAX_HYBRID_EFFORT,
diff --git a/mineru/version.py b/mineru/version.py
index 25f1e49f..5af970ef 100644
--- a/mineru/version.py
+++ b/mineru/version.py
@@ -1 +1 @@
-__version__ = "4.0.0a6"
+__version__ = "4.0.0a7"
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 64be3241..1340e5cc 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -64,12 +64,30 @@ from mineru.doclib.services.search_svc import SearchService
from mineru.doclib.types import DocContentExportRequest, FileInfo, InvalidateRequest, ParseResponse, WatchRequest
from mineru.errors import InvalidRequestError, MineruError, NotFoundError
from mineru.filetypes import file_type_for_extension
-from mineru.parser import backend_for_tier, resolve_tier_and_backend
+from mineru.parser import backend_for_tier
+from mineru.parser.tier import resolve_tier_and_backend
from mineru.parser.api_client import _APITransportError, _V1APIError
from mineru.parser.base import ParseResult
from mineru.parser import MIDDLE_JSON_SCHEMA_VERSION
-from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span, Tier
+from mineru.parser.base import _LEGACY_SCHEMA_VERSION
+from mineru.types import (
+ BlockBase,
+ BlockType,
+ ChartBlock,
+ ChartBodyBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ MiddleJson,
+ PageInfo,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ Tier,
+)
from mineru.utils.image_payload import ImagePayloadCache
+from mineru.version import __version__
class _Cursor:
@@ -233,48 +251,53 @@ class _OrderRecordingDB:
return await self.db.execute(sql, params)
-def _write_batch(data_dir: Path, sha256: str, tier: Tier, page_range: str, done_at: int, json_pages: list[dict]) -> None:
+def _write_batch(
+ data_dir: Path,
+ sha256: str,
+ tier: Tier,
+ page_range: str,
+ done_at: int,
+ json_pages: list[dict],
+ *,
+ file_suffix: str = "pdf",
+) -> None:
path = Path(parse_batch_json_path(str(data_dir), sha256, tier, page_range, done_at))
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps({"pages": json_pages}), encoding="utf-8")
+ payload = {
+ "schema_version": MIDDLE_JSON_SCHEMA_VERSION,
+ "pages": json_pages,
+ "file_suffix": file_suffix,
+ "effort": "medium",
+ "parse_mode": "txt",
+ "mineru_version": __version__,
+ }
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=4), encoding="utf-8")
def _image_page(image_path: str) -> PageInfo:
- image_span = Span(
- type=ContentType.IMAGE,
- bbox=(1, 1, 20, 20),
- image_path=image_path,
- )
- body = Block(
- index=0,
- type=BlockType.IMAGE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
- )
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 20), blocks=[body])
- return PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="hybrid")
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=(0.1, 0.1, 0.2, 0.2), content="", image_path=image_path)
+ image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=(0.1, 0.1, 0.2, 0.2), content=[body])
+ return PageInfo(page_idx=0, blocks=[image_block])
def _image_result(image_path: str, image_bytes: bytes = b"image-bytes") -> ParseResult:
"""构造带顶层图片缓存的 ParseResult,避免在 span 中保留 base64。"""
image_cache = ImagePayloadCache()
image_cache.register_bytes(image_bytes, "jpeg", image_path=image_path)
- return ParseResult(pages=[_image_page(image_path)], _image_cache=image_cache)
+ return ParseResult(middle_json=MiddleJson(pages=[_image_page(image_path)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
def _text_page(text: str) -> PageInfo:
- span = Span(type=ContentType.TEXT, bbox=(1, 1, 20, 10), content=text)
- line = Line(bbox=(1, 1, 20, 10), spans=[span])
- block = Block(index=0, type=BlockType.TEXT, bbox=(1, 1, 20, 10), lines=[line])
- return PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[block], _backend="vlm")
+ block = TextBlock(type=BlockType.TEXT, index=0, bbox=(0.0, 0.0, 0.1, 0.1), content=text)
+ return PageInfo(page_idx=0, blocks=[block])
def test_load_pages_from_done_batches_keeps_newest_page_idx(tmp_path: Path) -> None:
sha256 = "a" * 64
tier = "standard"
- older_page = {"page_idx": 1, "page_size": [100, 100], "para_blocks": []}
- older_duplicate = {"page_idx": 2, "page_size": [100, 100], "para_blocks": []}
- newer_duplicate = {"page_idx": 2, "page_size": [200, 200], "para_blocks": []}
+ older_page = {"page_idx": 1, "blocks": []}
+ older_duplicate = {"page_idx": 2, "blocks": [{"type": "text", "index": 0, "bbox": [0.0, 0.0, 0.1, 0.1], "content": "older"}]}
+ newer_duplicate = {"page_idx": 2, "blocks": [{"type": "text", "index": 0, "bbox": [0.0, 0.0, 0.1, 0.1], "content": "newer"}]}
_write_batch(tmp_path, sha256, tier, "1~2", 1000, [older_page, older_duplicate])
_write_batch(tmp_path, sha256, tier, "2", 2000, [newer_duplicate])
@@ -287,8 +310,7 @@ def test_load_pages_from_done_batches_keeps_newest_page_idx(tmp_path: Path) -> N
pages = load_pages_from_done_batches(str(tmp_path), sha256, tier, done_rows)
assert [page.page_idx for page in pages] == [1, 2]
- assert pages[0].page_size == (100, 100)
- assert pages[1].page_size == (200, 200)
+ assert pages[1].blocks[0].content == "newer" # type: ignore[union-attr]
def test_parser_tier_backend_mapping_is_parser_layer_only() -> None:
@@ -1199,7 +1221,7 @@ def test_compaction_uses_configured_data_dir(tmp_path: Path) -> None:
compacted_path = Path(parse_batch_json_path(str(tmp_path), sha256, tier, "1~2", 2000))
compacted = json.loads(compacted_path.read_text(encoding="utf-8"))
- assert compacted["schema_version"] == MIDDLE_JSON_SCHEMA_VERSION
+ assert compacted["schema_version"] == _LEGACY_SCHEMA_VERSION
assert compacted["pages"] == [older_page, newer_duplicate]
assert sorted(path.name for path in compacted_path.parent.glob("*.json")) == ["1~2_2000.json"]
@@ -1221,8 +1243,8 @@ def test_invalidate_deletes_fts_when_no_done_batches_remain(tmp_path: Path) -> N
def test_invalidate_rebuilds_fts_from_highest_remaining_done_tier(tmp_path: Path) -> None:
sha256 = "d" * 64
- _write_batch(tmp_path, sha256, "flash", "1", 1000, [{"page_idx": 1, "page_size": [100, 100], "para_blocks": []}])
- _write_batch(tmp_path, sha256, "standard", "1", 2000, [{"page_idx": 1, "page_size": [200, 200], "para_blocks": []}])
+ _write_batch(tmp_path, sha256, "flash", "1", 1000, [{"page_idx": 1, "blocks": []}])
+ _write_batch(tmp_path, sha256, "standard", "1", 2000, [{"page_idx": 1, "blocks": []}])
parses = [
{"sha256": sha256, "tier": "flash", "page_range": "1", "status": "done", "done_at": 1000},
{"sha256": sha256, "tier": "standard", "page_range": "1", "status": "done", "done_at": 2000},
@@ -1817,7 +1839,7 @@ def test_expand_page_range_rejects_empty_available_subset() -> None:
def test_remap_api_result_pages_to_non_contiguous_page_range() -> None:
from mineru.doclib.services.parse_svc import _remap_api_result_pages_to_page_range
- result = ParseResult(pages=[PageInfo(page_idx=0), PageInfo(page_idx=1), PageInfo(page_idx=2)])
+ result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0), PageInfo(page_idx=1), PageInfo(page_idx=2)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
_remap_api_result_pages_to_page_range(result, "11,13~14")
@@ -1839,7 +1861,7 @@ def test_remap_api_result_pages_refreshes_attached_export_cache() -> None:
def test_remap_api_result_pages_rejects_count_mismatch() -> None:
from mineru.doclib.services.parse_svc import ParseFailure, _remap_api_result_pages_to_page_range
- result = ParseResult(pages=[PageInfo(page_idx=0), PageInfo(page_idx=1)])
+ result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0), PageInfo(page_idx=1)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
with pytest.raises(ParseFailure) as exc:
_remap_api_result_pages_to_page_range(result, "11~13")
@@ -3129,7 +3151,7 @@ def test_doclib_server_accepts_short_id_for_sha256_doc_inputs(tmp_path: Path) ->
"standard",
"1",
now,
- ParseResult([_text_page("hello short id")]).to_dict(skip_defaults=True)["pages"],
+ [_text_page("hello short id").to_dict(skip_defaults=True)],
)
doc_by_short_id = await server.get_doc(short_id, expand_files=True)
@@ -4042,7 +4064,7 @@ def test_process_doc_marks_empty_page_result_failed(tmp_path: Path) -> None:
service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
async def _empty_parse(file_row: dict, tier: Tier, page_range: str) -> ParseResult:
- return ParseResult(pages=[])
+ return ParseResult(middle_json=MiddleJson(pages=[], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
service._parse_via_local = _empty_parse # type: ignore[method-assign]
@@ -4194,7 +4216,7 @@ def test_parse_via_api_requests_image_cache_only_for_office(
async def parse_async(self, _path: str, *, page_range: str = "") -> ParseResult:
assert _path == path
assert page_range == "1"
- return ParseResult(pages=[])
+ return ParseResult(middle_json=MiddleJson(pages=[], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
service._resolve_api_target = _resolve_api_target # type: ignore[method-assign]
service._resolve_tier = lambda tier, _via: tier # type: ignore[method-assign]
@@ -4252,7 +4274,7 @@ def test_process_doc_fails_when_batch_json_cannot_be_written(tmp_path: Path) ->
blocked_output_dir.write_text("not a directory", encoding="utf-8")
async def _parse(file_row: dict, tier: Tier, page_range: str) -> ParseResult:
- return ParseResult(pages=[PageInfo(page_idx=0)])
+ return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
service._parse_via_local = _parse # type: ignore[method-assign]
@@ -4318,16 +4340,16 @@ def test_process_doc_writes_cached_image_sidecars(tmp_path: Path) -> None:
assert sidecar.read_bytes() == b"fresh-image"
batch_path = Path(parse_batch_json_path(str(tmp_path), sha256, "flash", "1", parses[0]["done_at"]))
batch = json.loads(batch_path.read_text(encoding="utf-8"))
- image_span = batch["pages"][0]["para_blocks"][0]["blocks"][0]["lines"][0]["spans"][0]
- assert image_span["image_path"] == "figures/cache-hit.jpg"
- assert "image_base64" not in image_span
+ image_body = batch["pages"][0]["blocks"][0]["content"][0]
+ assert image_body["image_path"] == "figures/cache-hit.jpg"
+ assert "image_base64" not in image_body
def test_load_pages_from_done_batches_keeps_existing_image_sidecar(tmp_path: Path) -> None:
sha256 = "e" * 64
tier = "standard"
page = _image_page("figures/existing.jpg")
- _write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ _write_batch(tmp_path, sha256, tier, "1", 1000, [page.to_dict(skip_defaults=True)])
sidecar = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images" / "figures" / "existing.jpg"
sidecar.parent.mkdir(parents=True, exist_ok=True)
sidecar.write_bytes(b"existing-sidecar")
@@ -4347,7 +4369,7 @@ def test_progressive_markdown_uses_readable_pdf_block_locator(tmp_path: Path) ->
sha256 = "e" * 64
tier = "standard"
page = _image_page("figures/rendered.jpg")
- _write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ _write_batch(tmp_path, sha256, tier, "1", 1000, [page.to_dict(skip_defaults=True)])
db = _FakeDB(
parses=[
{
@@ -4394,7 +4416,7 @@ def test_doc_content_marker_uses_document_page_count_only(
tier = "standard"
page = _text_page("selected page")
page.page_idx = 4
- _write_batch(tmp_path, sha256, tier, "5", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ _write_batch(tmp_path, sha256, tier, "5", 1000, [page.to_dict(skip_defaults=True)])
db = _FakeDB(
parses=[{"sha256": sha256, "tier": tier, "status": "done", "page_range": "5", "done_at": 1000}],
file_row=None,
@@ -4422,7 +4444,7 @@ def test_doc_content_marker_uses_document_page_count_only(
(BlockType.IMAGE, "Image block"),
(BlockType.TABLE, "Table block"),
(BlockType.CHART, "Chart block"),
- (BlockType.INTERLINE_EQUATION, "Formula block"),
+ (BlockType.EQUATION, "Formula block"),
],
)
def test_doclib_image_renderer_uses_type_label_and_canonical_locator(
@@ -4437,7 +4459,7 @@ def test_doclib_image_renderer_uses_type_label_and_canonical_locator(
tier="standard",
page_no=2,
)
- block = Block(index=3, type=block_type, bbox=(1, 2, 30, 40))
+ block = BlockBase(type=block_type, index=3, bbox=(0.1, 0.2, 0.3, 0.4))
assert renderer(block) == f"![{label}](doc:eeeeeee/tier:standard/page:2/block:4)"
@@ -4450,20 +4472,28 @@ def test_doclib_image_renderer_rejects_non_finite_bbox(tmp_path: Path) -> None:
tier="standard",
page_no=1,
)
- block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, float("nan"), 10))
+ block = BlockBase(type=BlockType.IMAGE, index=0, bbox=None)
assert renderer(block) == "![Image block]()"
def test_find_block_by_no_ignores_conflicting_child_indexes() -> None:
- first = Block(
+ first = ImageBlock(
+ type=BlockType.IMAGE,
index=0,
+ bbox=(0.0, 0.0, 0.05, 0.05),
+ content=[
+ ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=(0.0, 0.0, 0.05, 0.05), content=""),
+ ImageAnnotationBlock(type=BlockType.IMAGE_CAPTION, index=1, bbox=(0.01, 0.01, 0.02, 0.02), content="caption"),
+ ],
+ )
+ second = ImageBlock(
type=BlockType.IMAGE,
- bbox=(0, 0, 5, 5),
- blocks=[Block(index=1, type=BlockType.IMAGE_CAPTION, bbox=(1, 1, 2, 2))],
+ index=1,
+ bbox=(0.1, 0.1, 0.2, 0.2),
+ content=[ImageBodyBlock(type=BlockType.IMAGE_BODY, index=1, bbox=(0.1, 0.1, 0.2, 0.2), content="")],
)
- second = Block(index=1, type=BlockType.IMAGE, bbox=(10, 10, 20, 20))
- page = PageInfo(page_idx=0, para_blocks=[first, second])
+ page = PageInfo(page_idx=0, blocks=[first, second])
assert _find_block_by_no(page, 2) is second
@@ -4480,9 +4510,9 @@ def test_progressive_markdown_uses_sidecar_availability_for_bboxless_blocks(
sha256 = "e" * 64
tier = "standard"
page = _image_page("figures/rendered.jpg")
- page._backend = "office"
- page.para_blocks[0].bbox = (0, 0, 0, 0)
- _write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ page.blocks[0].bbox = None
+ page.blocks[0].content[0].bbox = None # type: ignore[union-attr]
+ _write_batch(tmp_path, sha256, tier, "1", 1000, [page.to_dict(skip_defaults=True)], file_suffix="docx")
if sidecar_exists:
sidecar = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier)) / "figures/rendered.jpg"
sidecar.parent.mkdir(parents=True)
@@ -4523,15 +4553,9 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
)
- image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)
- body = Block(
- index=0,
- type=BlockType.IMAGE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
- )
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
- page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
+ page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
sha256=sha256,
@@ -4558,18 +4582,17 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
@pytest.mark.parametrize(
- ("block_type", "body_type", "content_type"),
+ ("block_type", "body_type"),
[
- (BlockType.TABLE, BlockType.TABLE_BODY, ContentType.TABLE),
- (BlockType.CHART, BlockType.CHART_BODY, ContentType.CHART),
- (BlockType.INTERLINE_EQUATION, None, ContentType.INTERLINE_EQUATION),
+ (BlockType.TABLE, BlockType.TABLE_BODY),
+ (BlockType.CHART, BlockType.CHART_BODY),
+ (BlockType.EQUATION, None),
],
)
def test_doclib_visual_block_asset_reads_cached_sidecar(
tmp_path: Path,
block_type: str,
body_type: str | None,
- content_type: str,
) -> None:
sha256 = "f" * 64
tier = "standard"
@@ -4579,14 +4602,15 @@ def test_doclib_visual_block_asset_reads_cached_sidecar(
sidecar.write_bytes(
base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
)
- span = Span(type=content_type, bbox=(0, 0, 0, 0), image_path=image_path)
- line = Line(bbox=(0, 0, 0, 0), spans=[span])
if body_type is None:
- visual_block = Block(index=0, type=block_type, bbox=(0, 0, 0, 0), lines=[line])
+ visual_block = EquationBlock(type=BlockType.EQUATION, index=0, bbox=None, content="", image_path=image_path)
+ elif block_type == BlockType.TABLE:
+ body = TableBodyBlock(type=BlockType.TABLE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ visual_block = TableBlock(type=BlockType.TABLE, index=0, bbox=None, content=[body])
else:
- body = Block(index=0, type=body_type, bbox=(0, 0, 0, 0), lines=[line])
- visual_block = Block(index=0, type=block_type, bbox=(0, 0, 0, 0), blocks=[body])
- page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[visual_block], _backend="office")
+ body = ChartBodyBlock(type=BlockType.CHART_BODY, index=0, bbox=None, content="", image_path=image_path)
+ visual_block = ChartBlock(type=BlockType.CHART, index=0, bbox=None, content=[body])
+ page = PageInfo(page_idx=0, blocks=[visual_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
sha256=sha256,
@@ -4654,8 +4678,8 @@ def test_doclib_image_block_locator_crops_source_image_at_original_resolution(tm
source_path = tmp_path / "source.png"
Image.new("RGB", (1000, 500), color="white").save(source_path)
page = _image_page("internal/not-persisted.png")
- page.page_size = (360, 180)
- page.para_blocks[0].bbox = (0, 0, 360, 180)
+ page.blocks[0].content[0].bbox = (0.0, 0.0, 1.0, 1.0) # type: ignore[union-attr]
+ page.blocks[0].bbox = (0.0, 0.0, 1.0, 1.0)
db = _FakeDB(
parses=[],
file_row={"path": str(source_path), "ext": "png", "sha256": sha256, "status": "active"},
@@ -4696,15 +4720,9 @@ def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path
base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
)
- image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)
- body = Block(
- index=0,
- type=BlockType.IMAGE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
- )
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
- page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
+ page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
sha256=sha256,
@@ -4734,15 +4752,9 @@ def test_doclib_office_image_asset_missing_sidecar_reports_asset_not_available(t
sha256 = "f" * 64
tier = "basic"
image_path = "figures/missing.png"
- image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)
- body = Block(
- index=0,
- type=BlockType.IMAGE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
- )
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
- page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
+ page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
sha256=sha256,
diff --git a/tests/unittest/test_doclib_progressive_reading.py b/tests/unittest/test_doclib_progressive_reading.py
index e0e96c61..fee4891c 100644
--- a/tests/unittest/test_doclib_progressive_reading.py
+++ b/tests/unittest/test_doclib_progressive_reading.py
@@ -8,20 +8,15 @@ from mineru.doclib.server import (
)
from mineru.doclib.types import ContentRange
from mineru.errors import InvalidRequestError
-from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span
+from mineru.types import BlockType, PageInfo, TableBlock, TableBodyBlock, TextBlock
def _page(page_idx: int, *texts: str) -> PageInfo:
blocks = [
- Block(
- index=index,
- type=BlockType.TEXT,
- bbox=(0, 0, 10, 10),
- lines=[Line(bbox=(0, 0, 10, 10), spans=[Span(type=ContentType.TEXT, bbox=(0, 0, 10, 10), content=text)])],
- )
+ TextBlock(type=BlockType.TEXT, index=index, bbox=(0.0, 0.0, 0.1, 0.1), content=text)
for index, text in enumerate(texts)
]
- return PageInfo(page_idx=page_idx, page_size=(100, 100), para_blocks=blocks, _backend="hybrid")
+ return PageInfo(page_idx=page_idx, blocks=blocks)
def test_paginated_default_content_pages_are_first_ten() -> None:
@@ -188,7 +183,7 @@ def test_paginated_empty_page_renders_page_marker_and_content_range(
expected_marker: str,
) -> None:
rendered = _render_progressive_markdown(
- [PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[], _backend="flash")],
+ [PageInfo(page_idx=0)],
short_id="ab12cd3",
tier="flash",
after=None,
@@ -213,28 +208,19 @@ def test_page_markdown_blocks_prefers_markdown_table_in_doclib() -> None:
""".strip()
page = PageInfo(
page_idx=0,
- page_size=(100, 100),
- para_blocks=[
- Block(
- index=0,
+ blocks=[
+ TableBlock(
type=BlockType.TABLE,
- bbox=(0, 0, 10, 10),
- blocks=[
- Block(
- index=0,
+ index=0,
+ content=[
+ TableBodyBlock(
type=BlockType.TABLE_BODY,
- bbox=(0, 0, 10, 10),
- lines=[
- Line(
- bbox=(0, 0, 10, 10),
- spans=[Span(type=ContentType.TABLE, bbox=(0, 0, 10, 10), content=html)],
- )
- ],
+ index=0,
+ content=html,
)
],
)
],
- _backend="hybrid",
)
assert _page_markdown_blocks(page) == [
diff --git a/tests/unittest/test_e2e.py b/tests/unittest/test_e2e.py
deleted file mode 100644
index fb834681..00000000
--- a/tests/unittest/test_e2e.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import json
-import os
-
-from bs4 import BeautifulSoup
-from fuzzywuzzy import fuzz
-from loguru import logger
-
-from mineru.parser.base import ParseResult
-from mineru.render import render_content_list, render_markdown
-from mineru.render.writer import FileBasedDataWriter
-
-
-def write_infer_result(
- pdf_file_name,
- local_image_dir,
- local_md_dir,
- middle_json,
- model_list,
-):
- md_writer = FileBasedDataWriter(local_md_dir)
- pdf_info = middle_json
- image_dir = str(os.path.basename(local_image_dir))
-
- md_content_str = render_markdown(pdf_info, image_dir)
- md_writer.write_string(
- f"{pdf_file_name}.md",
- md_content_str,
- )
-
- content_list = render_content_list(pdf_info, image_dir)
- md_writer.write_string(
- f"{pdf_file_name}_content_list.json",
- json.dumps(content_list, ensure_ascii=False, indent=4),
- )
-
- md_writer.write_string(
- f"{pdf_file_name}_middle.json",
- json.dumps(ParseResult(pages=pdf_info).to_dict(), ensure_ascii=False, indent=4),
- )
-
- md_writer.write_string(
- f"{pdf_file_name}_model.json",
- json.dumps(model_list, ensure_ascii=False, indent=4),
- )
-
- logger.info(f"local output dir is {local_md_dir}")
-
-
-def validate_html(html_content):
- try:
- soup = BeautifulSoup(html_content, "html.parser")
- return True
- except Exception as e:
- return False
-
-
-def assert_content(content_path, parse_method="txt"):
- content_list = []
- with open(content_path, "r", encoding="utf-8") as file:
- content_list = json.load(file)
- logger.info(content_list)
- type_set = set()
- for content_dict in content_list:
- match content_dict["type"]:
- # 图片校验,只校验 Caption
- case "image":
- type_set.add("image")
- assert (
- fuzz.ratio(
- content_dict["image_caption"][0],
- "Figure 1: Figure Caption",
- )
- > 90
- )
- # 表格校验,校验 Caption,表格格式和表格内容
- case "table":
- type_set.add("table")
- assert (
- fuzz.ratio(
- content_dict["table_caption"][0],
- "Table 1: Table Caption",
- )
- > 90
- )
- assert validate_html(content_dict["table_body"])
- target_str_list = [
- "Model",
- "Testing",
- "Error",
- "Linear",
- "Regression",
- "0.98740",
- "1321.2",
- "Gray",
- "Prediction",
- "0.00617",
- "687",
- ]
- correct_count = 0
- for target_str in target_str_list:
- if target_str in content_dict["table_body"]:
- correct_count += 1
- if parse_method == "txt" or parse_method == "ocr":
- assert correct_count > 0.9 * len(target_str_list)
- elif parse_method == "vlm":
- assert correct_count > 0.7 * len(target_str_list)
- else:
- assert False
- # 公式校验,检测是否含有公式元素
- case "equation":
- type_set.add("equation")
- target_str_list = ["$$", "lambda", "frac", "bar"]
- for target_str in target_str_list:
- assert target_str in content_dict["text"]
- # 文本校验,文本相似度超过90
- case "text":
- type_set.add("text")
- assert (
- fuzz.ratio(
- content_dict["text"],
- "Trump graduated from the Wharton School of the University of Pennsylvania with a bachelor's degree in 1968. He became president of his father's real estate business in 1971 and renamed it The Trump Organization.",
- )
- > 90
- )
- assert len(type_set) >= 4
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index acecc5ef..d4ed7cdb 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -26,7 +26,7 @@ from mineru.kit.commands import api_server, models, parse, router, vlm_server
from mineru.kit.main import app
from mineru.kit.vlm_server import mlx_vlm_server
from mineru.parser.base import ParseResult
-from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span
+from mineru.types import BlockType, MiddleJson, PageInfo
from mineru.utils.image_payload import ImagePayloadCache
from mineru.utils.model_registry import MODEL_COMPLETE_MARKER
from mineru.version import __version__
@@ -85,7 +85,7 @@ def test_top_level_commands_register_implementation_callbacks_directly() -> None
@pytest.mark.parametrize(
("command", "expected_options"),
[
- ("parse", ("--output", "--format", "--tier", "--effort")),
+ ("parse", ("--output", "--format", "--tier")),
("api-server", ("--host", "--port", "--tier", "--no-flash", "--preload-models")),
("vlm-server", ("--engine",)),
("router", ("--host", "--upstream-url", "--local-gpus")),
@@ -447,38 +447,6 @@ def test_kit_commands_do_not_expose_formula_table_switches() -> None:
assert _REMOVED_DISABLE_FORMULA_OPTION not in output
-def test_cli_old_api_form_builders_remove_formula_table_fields() -> None:
- """校验旧 API client 表单构造不再声明或发送公式/表格开关。"""
- from mineru.cli_old import api_client as old_api_client
- from mineru.cli_old import client as old_client
-
- for target in (old_api_client.build_parse_request_form_data, old_client.build_request_form_data):
- parameters = inspect.signature(target).parameters
- assert _REMOVED_FORMULA_ENABLE_PARAM not in parameters
- assert _REMOVED_TABLE_ENABLE_PARAM not in parameters
-
- data = old_api_client.build_parse_request_form_data(
- lang_list=["ch"],
- backend="hybrid-engine",
- parse_method="auto",
- server_url=None,
- start_page_id=0,
- end_page_id=None,
- image_analysis=True,
- effort="medium",
- return_md=True,
- return_middle_json=True,
- return_model_output=True,
- return_content_list=True,
- return_images=True,
- response_format_zip=False,
- return_original_file=False,
- )
-
- assert _REMOVED_FORMULA_ENABLE_PARAM not in data
- assert _REMOVED_TABLE_ENABLE_PARAM not in data
-
-
def test_cli_old_api_request_models_remove_formula_table_fields() -> None:
"""校验旧 FastAPI 表单参数对象不再保存公式/表格开关。"""
from mineru.cli_old import api_request as old_api_request
@@ -883,7 +851,7 @@ def test_parse_single_file_markdown(monkeypatch: Any, tmp_path: Path) -> None:
assert output.read_text(encoding="utf-8") == "# demo\n"
-def test_parse_forwards_backend_alias_and_effort(monkeypatch: Any, tmp_path: Path) -> None:
+def test_parse_forwards_backend_alias_and_tier(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
output = tmp_path / "out.md"
source.write_bytes(b"%PDF-1.7\n")
@@ -916,12 +884,13 @@ def test_parse_forwards_backend_alias_and_effort(monkeypatch: Any, tmp_path: Pat
result = runner.invoke(
app,
- ["parse", str(source), "-o", str(output), "--backend", "hybrid-auto-engine", "--effort", "high"],
+ ["parse", str(source), "-o", str(output), "--backend", "hybrid-auto-engine", "--tier", "standard"],
)
assert result.exit_code == 0
assert seen["backend"] == "hybrid-engine"
- assert seen["effort"] == "high"
+ assert seen["tier"] == "standard"
+ assert "effort" not in seen
def test_parse_rejects_single_office_input_with_quality_tier(monkeypatch: Any, tmp_path: Path) -> None:
@@ -1133,75 +1102,6 @@ def test_gradio_rejects_v1_tiers_payload_without_supported_tiers() -> None:
gradio_app.extract_v1_tier_choices({"data": [{"id": "experimental"}]})
-def test_gradio_persists_v1_parse_result_for_preview_and_download(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- from mineru.cli_old import gradio_app
-
- image_cache = ImagePayloadCache()
- image_path = image_cache.register_bytes(b"figure-bytes", "png", image_path="figures/figure.png")
- image_body = Block(
- index=1,
- type=BlockType.IMAGE_BODY,
- bbox=(0, 0, 20, 20),
- lines=[Line(bbox=(0, 0, 20, 20), spans=[Span(type=ContentType.IMAGE, bbox=(0, 0, 20, 20), image_path=image_path)])],
- )
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 20, 20), blocks=[image_body])
- parse_result = ParseResult(
- pages=[PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="hybrid")],
- _image_cache=image_cache,
- _model_output=[[{"raw": "model"}]],
- )
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- extract_root = tmp_path / "extract"
- archive_zip_path = tmp_path / "archive.zip"
- visualization_calls: list[Any] = []
-
- def fake_run_visualization_job(job: Any) -> Any:
- """模拟 layout 可视化生成,避免本用例依赖真实 PDF 绘制。"""
- visualization_calls.append(job)
- layout_path = job.parse_dir / f"{job.document_stem}_layout.pdf"
- layout_path.write_bytes(b"%PDF-1.7\n%layout\n")
- return SimpleNamespace(status="finished", message="generated", generated_files=(layout_path.name,))
-
- monkeypatch.setattr(gradio_app, "run_visualization_job", fake_run_visualization_job)
-
- output = gradio_app.persist_v1_gradio_result(
- parse_result=parse_result,
- file_path=str(source),
- extract_root=extract_root,
- archive_zip_path=archive_zip_path,
- backend="hybrid-engine",
- effort="medium",
- page_range="",
- )
-
- local_md_dir = extract_root / "demo"
- assert output.file_name == "demo"
- assert output.local_md_dir == local_md_dir
- assert output.preview_pdf_path == local_md_dir / "demo_layout.pdf"
- assert visualization_calls[0].document_stem == "demo"
- assert visualization_calls[0].parse_dir == local_md_dir
- assert visualization_calls[0].draw_span is False
- assert (local_md_dir / "demo.md").read_text(encoding="utf-8") == "![](images/figures/figure.png)"
- content_list = json.loads((local_md_dir / "demo_content_list.json").read_text(encoding="utf-8"))
- assert content_list[0]["img_path"] == "images/figures/figure.png"
- middle_json = json.loads((local_md_dir / "demo_middle.json").read_text(encoding="utf-8"))
- assert middle_json["_backend"] == "hybrid"
- assert middle_json["_version_name"]
- assert json.loads((local_md_dir / "demo_model_output.json").read_text(encoding="utf-8")) == [[{"raw": "model"}]]
- assert (local_md_dir / "images" / "figures" / "figure.png").read_bytes() == b"figure-bytes"
- assert (local_md_dir / "demo_origin.pdf").read_bytes() == b"%PDF-1.7\n"
- assert (local_md_dir / "demo_layout.pdf").read_bytes() == b"%PDF-1.7\n%layout\n"
- assert archive_zip_path.is_file()
- with zipfile.ZipFile(archive_zip_path) as archive:
- assert "demo_layout.pdf" in archive.namelist()
- assert "demo_model_output.json" in archive.namelist()
- assert json.loads(archive.read("demo_model_output.json").decode("utf-8")) == [[{"raw": "model"}]]
-
-
def test_gradio_persists_page_ranged_origin_pdf_for_v1_preview(tmp_path: Path) -> None:
from pypdf import PdfReader, PdfWriter
@@ -1215,11 +1115,14 @@ def test_gradio_persists_page_ranged_origin_pdf_for_v1_preview(tmp_path: Path) -
pdf_writer.write(source_pdf)
parse_result = ParseResult(
- pages=[
- PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid"),
- PageInfo(page_idx=1, page_size=(200, 200), _backend="hybrid"),
+ middle_json=MiddleJson(
+ pages=[
+ PageInfo(page_idx=0),
+ PageInfo(page_idx=1),
],
- )
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ )
+ )
source = tmp_path / "demo.pdf"
source.write_bytes(source_pdf.getvalue())
extract_root = tmp_path / "extract"
@@ -1264,8 +1167,11 @@ def test_gradio_persists_image_origin_as_pdf_for_v1_preview(tmp_path: Path) -> N
source = tmp_path / "ref-merge.png"
Image.new("RGB", (64, 48), "white").save(source)
parse_result = ParseResult(
- pages=[PageInfo(page_idx=0, page_size=(64, 48), _backend="hybrid")],
- )
+ middle_json=MiddleJson(
+ pages=[PageInfo(page_idx=0)],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ )
+ )
extract_root = tmp_path / "extract"
archive_zip_path = tmp_path / "archive.zip"
@@ -1313,7 +1219,7 @@ def test_gradio_v1_job_reuses_page_range_for_api_and_origin_pdf(
async def parse_async(self, file_path: str, *, page_range: str) -> ParseResult:
calls["api_page_range"] = page_range
- return ParseResult(pages=[PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid")])
+ return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
async def _fake_server_health(_http_client: Any, api_url: str | None) -> Any:
"""模拟 v1 server 健康检查,只保留 Gradio 任务需要的字段。"""
@@ -1325,7 +1231,6 @@ def test_gradio_v1_job_reuses_page_range_for_api_and_origin_pdf(
local_md_dir = tmp_path / "persisted"
local_md_dir.mkdir()
(local_md_dir / "demo.md").write_text("markdown", encoding="utf-8")
- (local_md_dir / "demo_content_list.json").write_text("[]", encoding="utf-8")
archive_zip_path = tmp_path / "demo.zip"
archive_zip_path.write_bytes(b"zip")
return SimpleNamespace(
@@ -1607,60 +1512,6 @@ def test_cli_old_hybrid_medium_skips_vlm_engine_resolution(monkeypatch: Any, tmp
assert seen["kwargs"]["effort"] == "medium"
-def test_process_hybrid_medium_calls_analyzer_per_file(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- calls: list[bytes] = []
- languages: list[str] = []
- analyzer_kwargs: list[dict[str, Any]] = []
- outputs: list[tuple[str, str, str]] = []
-
- def fake_doc_analyze(pdf_bytes: bytes, **kwargs: Any) -> tuple[list[PageInfo], list[object], bool]:
- """记录每个文件独立进入 Hybrid basic analyzer。"""
- calls.append(pdf_bytes)
- languages.append(kwargs["language"])
- analyzer_kwargs.append(kwargs)
- return [PageInfo(page_idx=0, _backend="hybrid")], [], False
-
- monkeypatch.setattr(common, "_load_hybrid_analyze_entrypoint", lambda *_args, **_kwargs: fake_doc_analyze)
- monkeypatch.setattr(
- common,
- "prepare_env",
- lambda output_dir, pdf_file_name, method: (str(tmp_path / pdf_file_name / "images"), str(tmp_path / pdf_file_name)),
- )
- monkeypatch.setattr(common, "FileBasedDataWriter", lambda _path: object())
- monkeypatch.setattr(
- common,
- "_process_output",
- lambda middle_json, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir, *_args, **_kwargs: outputs.append(
- (pdf_file_name, local_md_dir, local_image_dir)
- ),
- )
-
- common._process_hybrid(
- output_dir=str(tmp_path),
- pdf_file_names=["a.pdf", "b.pdf"],
- pdf_bytes_list=[b"a", b"b"],
- h_lang_list=["en", "en"],
- parse_method="auto",
- backend="engine",
- f_draw_layout_bbox=False,
- f_draw_span_bbox=False,
- f_dump_md=True,
- f_dump_middle_json=True,
- f_dump_model_output=True,
- f_dump_orig_pdf=True,
- f_dump_content_list=True,
- f_make_md_mode="mm_markdown",
- effort="medium",
- )
-
- assert calls == [b"a", b"b"]
- assert languages == ["en", "en"]
- assert all(_REMOVED_INLINE_FORMULA_PARAM not in kwargs for kwargs in analyzer_kwargs)
- assert [item[0] for item in outputs] == ["a.pdf", "b.pdf"]
-
-
def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_xhigh(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
diff --git a/tests/unittest/test_middle_json_validator.py b/tests/unittest/test_middle_json_validator.py
index 5ac9d850..952c4f6b 100644
--- a/tests/unittest/test_middle_json_validator.py
+++ b/tests/unittest/test_middle_json_validator.py
@@ -2,15 +2,64 @@ from dataclasses import dataclass
from typing import Literal
from mineru.parser import MIDDLE_JSON_SCHEMA_VERSION
-from mineru.types import BLOCK_TYPES, EMPTY_BBOX, Block, BlockType, ContentType, Line, PageInfo, Span
+from mineru.types import (
+ BLOCK_TYPES,
+ BlockBase,
+ BlockType,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ MiddleJson,
+ PageInfo,
+ ParagraphTitleBlock,
+ TextBlock,
+)
IssueSeverity = Literal["error", "warning"]
-KNOWN_BLOCK_TYPES = BLOCK_TYPES | {"list_item"}
-TEXT_SPAN_TYPES = {ContentType.TEXT}
-IMAGE_SPAN_TYPES = {ContentType.IMAGE}
-TABLE_SPAN_TYPES = {ContentType.TABLE}
-EQUATION_SPAN_TYPES = {ContentType.EQUATION, ContentType.INLINE_EQUATION, ContentType.INTERLINE_EQUATION}
+KNOWN_BLOCK_TYPES = BLOCK_TYPES
+TEXT_CONTENT_BLOCK_TYPES = {
+ BlockType.TEXT,
+ BlockType.REF_TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.EQUATION,
+ BlockType.TABLE_BODY,
+ BlockType.IMAGE_CAPTION,
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_CAPTION,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_CAPTION,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.CODE_BODY,
+ BlockType.CODE_CAPTION,
+ BlockType.CODE_FOOTNOTE,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+}
+VISUAL_PARENT_TYPES = {
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.CODE,
+}
+VISUAL_BODY_TYPE_BY_PARENT = {
+ BlockType.IMAGE: BlockType.IMAGE_BODY,
+ BlockType.TABLE: BlockType.TABLE_BODY,
+ BlockType.CHART: BlockType.CHART_BODY,
+ BlockType.CODE: BlockType.CODE_BODY,
+}
+CONTAINER_BLOCK_TYPES = {
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.CODE,
+ BlockType.LIST,
+ BlockType.INDEX,
+}
@dataclass(frozen=True)
@@ -21,10 +70,6 @@ class ValidationIssue:
message: str
-def bbox_known(bbox: object) -> bool:
- return _is_bbox(bbox) and tuple(float(v) for v in bbox) != EMPTY_BBOX
-
-
def validate_pages(pages: list[PageInfo]) -> list[ValidationIssue]:
issues: list[ValidationIssue] = []
if not isinstance(pages, list):
@@ -50,30 +95,14 @@ def validate_pages(pages: list[PageInfo]) -> list[ValidationIssue]:
elif page.page_idx < 0:
issues.append(_invalid_value(f"{page_path}.page_idx", "page_idx must be non-negative."))
- page_size: tuple[float, float] | None = None
- if _has_field(page, "page_size") and page.page_size is not None:
- _validate_page_size(page.page_size, f"{page_path}.page_size", issues)
- if _is_page_size(page.page_size):
- page_size = (float(page.page_size[0]), float(page.page_size[1]))
-
- if getattr(page, "_backend", None) is not None:
- issues.append(
- ValidationIssue(
- severity="warning",
- code="legacy_backend",
- path=f"{page_path}._backend",
- message="_backend is a legacy/internal page field.",
- )
- )
+ if not _has_field(page, "blocks"):
+ issues.append(_missing(f"{page_path}.blocks"))
+ continue
+ if not isinstance(page.blocks, list):
+ issues.append(_invalid_type(f"{page_path}.blocks", "list"))
+ continue
- for attr in ("preproc_blocks", "para_blocks", "discarded_blocks"):
- if not _has_field(page, attr):
- continue
- blocks = getattr(page, attr)
- if not isinstance(blocks, list):
- issues.append(_invalid_type(f"{page_path}.{attr}", "list"))
- continue
- _validate_block_list(blocks, f"{page_path}.{attr}", issues, page_size)
+ _validate_block_list(page.blocks, f"{page_path}.blocks", issues)
return issues
@@ -81,17 +110,16 @@ def _validate_block_list(
blocks: list[object],
path: str,
issues: list[ValidationIssue],
- page_size: tuple[float, float] | None,
) -> None:
seen_indexes: set[int] = set()
previous_index: int | None = None
for block_index, block in enumerate(blocks):
block_path = f"{path}[{block_index}]"
- if not isinstance(block, Block):
- issues.append(_invalid_type(block_path, "Block"))
+ if not isinstance(block, BlockBase):
+ issues.append(_invalid_type(block_path, "BlockBase"))
continue
- if _has_field(block, "index") and _is_int(block.index):
+ if _has_field(block, "index") and block.index is not None and _is_int(block.index):
if block.index in seen_indexes:
issues.append(
ValidationIssue(
@@ -113,213 +141,160 @@ def _validate_block_list(
)
previous_index = block.index
- _validate_block(block, block_path, issues, page_size)
+ _validate_block(block, block_path, issues)
-def _validate_block(block: Block, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:
- for field_name in ("index", "type", "bbox"):
- if not _has_field(block, field_name):
- issues.append(_missing(f"{path}.{field_name}"))
-
- if _has_field(block, "index") and not _is_int(block.index):
- issues.append(_invalid_type(f"{path}.index", "int"))
- elif _has_field(block, "index") and block.index < 0:
- issues.append(_invalid_value(f"{path}.index", "block index must be non-negative."))
-
- if _has_field(block, "type") and not isinstance(block.type, str):
+def _validate_block(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:
+ block_type = getattr(block, "type", None)
+ if not _has_field(block, "type"):
+ issues.append(_missing(f"{path}.type"))
+ elif not isinstance(block_type, str):
issues.append(_invalid_type(f"{path}.type", "str"))
- elif _has_field(block, "type") and block.type not in KNOWN_BLOCK_TYPES:
+ elif block_type not in KNOWN_BLOCK_TYPES:
issues.append(
ValidationIssue(
severity="error",
code="block_type_unknown",
path=f"{path}.type",
- message=f"unknown block type: {block.type}",
+ message=f"unknown block type: {block_type}",
)
)
- elif _has_field(block, "type") and block.type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ elif block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
_validate_title_level(block, f"{path}.level", issues)
- if _has_field(block, "bbox"):
- _validate_bbox(block.bbox, f"{path}.bbox", issues, page_size)
-
- if not _has_field(block, "lines") and not _has_field(block, "blocks"):
- issues.append(_missing(f"{path}.lines_or_blocks"))
-
- if _has_field(block, "lines"):
- if not isinstance(block.lines, list):
- issues.append(_invalid_type(f"{path}.lines", "list"))
- else:
- for line_index, line in enumerate(block.lines):
- line_path = f"{path}.lines[{line_index}]"
- if not isinstance(line, Line):
- issues.append(_invalid_type(line_path, "Line"))
- continue
- _validate_line(line, line_path, issues, page_size)
-
- if _has_field(block, "blocks"):
- if not isinstance(block.blocks, list):
- issues.append(_invalid_type(f"{path}.blocks", "list"))
- else:
- _validate_block_list(block.blocks, f"{path}.blocks", issues, page_size)
-
-
-def _validate_line(line: Line, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:
- if not _has_field(line, "bbox"):
- issues.append(_missing(f"{path}.bbox"))
- else:
- _validate_bbox(line.bbox, f"{path}.bbox", issues, page_size)
-
- if not _has_field(line, "spans"):
- issues.append(_missing(f"{path}.spans"))
- return
- if not isinstance(line.spans, list):
- issues.append(_invalid_type(f"{path}.spans", "list"))
- return
- for span_index, span in enumerate(line.spans):
- span_path = f"{path}.spans[{span_index}]"
- if not isinstance(span, Span):
- issues.append(_invalid_type(span_path, "Span"))
- continue
- _validate_span(span, span_path, issues, page_size)
+ if _has_field(block, "index") and block.index is not None and not _is_int(block.index):
+ issues.append(_invalid_type(f"{path}.index", "int"))
+ elif _has_field(block, "index") and block.index is not None and block.index < 0:
+ issues.append(_invalid_value(f"{path}.index", "block index must be non-negative."))
+ if _has_field(block, "bbox") and block.bbox is not None:
+ _validate_bbox(block.bbox, f"{path}.bbox", issues)
-def _validate_span(span: Span, path: str, issues: list[ValidationIssue], page_size: tuple[float, float] | None) -> None:
- for field_name in ("type", "bbox"):
- if not _has_field(span, field_name):
- issues.append(_missing(f"{path}.{field_name}"))
+ if block_type in TEXT_CONTENT_BLOCK_TYPES:
+ _validate_string_content(block, f"{path}.content", issues)
- if _has_field(span, "type") and not isinstance(span.type, str):
- issues.append(_invalid_type(f"{path}.type", "str"))
- if _has_field(span, "bbox"):
- _validate_bbox(span.bbox, f"{path}.bbox", issues, page_size)
- if _has_field(span, "type") and isinstance(span.type, str):
- _validate_span_content(span, path, issues)
+ if block_type in VISUAL_PARENT_TYPES:
+ _validate_visual_block_children(block, f"{path}.content", issues)
+ if block_type in CONTAINER_BLOCK_TYPES:
+ content = getattr(block, "content", None)
+ if isinstance(content, list):
+ _validate_block_list(content, f"{path}.content", issues)
-def _validate_bbox(
- bbox: object,
- path: str,
- issues: list[ValidationIssue],
- page_size: tuple[float, float] | None = None,
-) -> None:
- if not _is_bbox(bbox):
- issues.append(
- ValidationIssue(
- severity="error",
- code="bbox_invalid",
- path=path,
- message="bbox must contain four numeric coordinates.",
- )
- )
- return
- x0, y0, x1, y1 = (float(v) for v in bbox)
- if (x0, y0, x1, y1) == EMPTY_BBOX:
+def _validate_string_content(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:
+ content = getattr(block, "content", None)
+ block_type = getattr(block, "type", None)
+ if content is None:
+ issues.append(_missing(path))
+ return
+ if not isinstance(content, str):
+ issues.append(_invalid_type(path, "str"))
+ return
+ if not content:
issues.append(
ValidationIssue(
severity="warning",
- code="bbox_unknown",
+ code="block_content_missing",
path=path,
- message="bbox is the unknown bbox sentinel.",
+ message=f"{block_type} block should provide content.",
)
)
+
+
+def _validate_visual_block_children(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:
+ """Validate visual parent block has exactly one body, and body index equals parent index."""
+ content = getattr(block, "content", None)
+ block_type = getattr(block, "type", None)
+ if not isinstance(content, list):
+ issues.append(_invalid_type(path, "list"))
return
- if x1 < x0 or y1 < y0:
+
+ body_type = VISUAL_BODY_TYPE_BY_PARENT.get(block_type)
+ if body_type is None:
+ return
+
+ bodies = [child for child in content if isinstance(child, BlockBase) and getattr(child, "type", None) == body_type]
+ if len(bodies) != 1:
issues.append(
ValidationIssue(
severity="error",
- code="bbox_invalid",
+ code="visual_block_body_count",
path=path,
- message="bbox coordinates must satisfy x1 >= x0 and y1 >= y0.",
+ message=f"{block_type} must contain exactly one {body_type}.",
)
)
return
- if page_size is not None:
- page_w, page_h = page_size
- if x0 < 0 or y0 < 0 or x1 > page_w or y1 > page_h:
- issues.append(
- ValidationIssue(
- severity="warning",
- code="bbox_out_of_page",
- path=path,
- message="bbox is outside page_size bounds.",
- )
- )
-
-def _validate_page_size(page_size: object, path: str, issues: list[ValidationIssue]) -> None:
- if not _is_page_size(page_size):
+ body = bodies[0]
+ if block.index is not None and body.index is not None and block.index != body.index:
issues.append(
ValidationIssue(
severity="error",
- code="page_size_invalid",
- path=path,
- message="page_size must contain width and height.",
+ code="visual_block_body_index_mismatch",
+ path=f"{path}[body].index",
+ message=f"{block_type} body index must equal parent index.",
)
)
- return
- if float(page_size[0]) <= 0 or float(page_size[1]) <= 0:
- issues.append(_invalid_value(path, "page_size width and height must be positive."))
-def _validate_title_level(block: Block, path: str, issues: list[ValidationIssue]) -> None:
- if block.level is None:
+def _validate_bbox(
+ bbox: object,
+ path: str,
+ issues: list[ValidationIssue],
+) -> None:
+ if not _is_bbox(bbox):
issues.append(
ValidationIssue(
- severity="warning",
- code="title_level_missing",
+ severity="error",
+ code="bbox_invalid",
path=path,
- message="title block should provide a positive integer level.",
+ message="bbox must contain four numeric coordinates.",
)
)
return
- if not _is_int(block.level) or block.level < 1:
+
+ x0, y0, x1, y1 = (float(v) for v in bbox)
+ if x1 <= x0 or y1 <= y0:
issues.append(
ValidationIssue(
severity="error",
- code="title_level_invalid",
+ code="bbox_invalid",
path=path,
- message="title level must be a positive integer.",
+ message="bbox coordinates must satisfy x1 > x0 and y1 > y0.",
)
)
-
-
-def _validate_span_content(span: Span, path: str, issues: list[ValidationIssue]) -> None:
- if span.type in TEXT_SPAN_TYPES and not span.content:
- issues.append(
- ValidationIssue(
- severity="warning",
- code="span_content_missing",
- path=f"{path}.content",
- message="text span should provide content.",
- )
- )
- elif span.type in IMAGE_SPAN_TYPES and not span.image_path:
+ return
+ if not all(0.0 <= v <= 1.0 for v in (x0, y0, x1, y1)):
issues.append(
ValidationIssue(
severity="warning",
- code="span_image_missing",
+ code="bbox_out_of_bounds",
path=path,
- message="image span should provide image_path.",
+ message="bbox values should be normalized to [0, 1].",
)
)
- elif span.type in TABLE_SPAN_TYPES and not span.content:
+
+
+def _validate_title_level(block: BlockBase, path: str, issues: list[ValidationIssue]) -> None:
+ level = getattr(block, "level", None)
+ if level is None:
issues.append(
ValidationIssue(
severity="warning",
- code="span_table_missing",
+ code="title_level_missing",
path=path,
- message="table span should provide content.",
+ message="title block should provide a positive integer level.",
)
)
- elif span.type in EQUATION_SPAN_TYPES and not span.content:
+ return
+ if not _is_int(level) or level < 1:
issues.append(
ValidationIssue(
- severity="warning",
- code="span_equation_missing",
+ severity="error",
+ code="title_level_invalid",
path=path,
- message="equation span should provide content.",
+ message="title level must be a positive integer.",
)
)
@@ -332,14 +307,6 @@ def _is_bbox(bbox: object) -> bool:
)
-def _is_page_size(page_size: object) -> bool:
- return (
- isinstance(page_size, tuple | list)
- and len(page_size) == 2
- and all(isinstance(v, int | float) and not isinstance(v, bool) for v in page_size)
- )
-
-
def _is_int(value: object) -> bool:
return isinstance(value, int) and not isinstance(value, bool)
@@ -382,25 +349,14 @@ def _issue_keys(issues):
def _valid_page() -> PageInfo:
return PageInfo(
page_idx=0,
- page_size=(100, 200),
- para_blocks=[
- Block(
- index=0,
- type="text",
- bbox=(1.0, 2.0, 20.0, 30.0),
- lines=[
- Line(
- bbox=(1.0, 2.0, 20.0, 30.0),
- spans=[Span(type="text", bbox=(1.0, 2.0, 20.0, 10.0), content="hello")],
- )
- ],
- )
+ blocks=[
+ TextBlock(type=BlockType.TEXT, index=0, bbox=(0.1, 0.1, 0.2, 0.2), content="hello"),
],
)
def test_middle_json_schema_version_is_public_constant() -> None:
- assert MIDDLE_JSON_SCHEMA_VERSION == "1.0"
+ assert MIDDLE_JSON_SCHEMA_VERSION == "2.0"
def test_validate_pages_accepts_valid_page_tree() -> None:
@@ -409,131 +365,162 @@ def test_validate_pages_accepts_valid_page_tree() -> None:
def test_validate_pages_reports_missing_required_page_and_block_fields() -> None:
page = _valid_page()
- delattr(page, "page_idx")
- delattr(page.para_blocks[0], "type")
+ page_no_idx = PageInfo.model_construct(blocks=page.blocks)
+ block_no_type = TextBlock.model_construct(index=0, content="hello", bbox=(0.1, 0.1, 0.2, 0.2))
+ page_no_type = PageInfo.model_construct(page_idx=0, blocks=[block_no_type])
- issues = validate_pages([page])
+ issues = validate_pages([page_no_idx, page_no_type])
assert ("error", "missing_required_field", "pages[0].page_idx") in _issue_keys(issues)
- assert ("error", "missing_required_field", "pages[0].para_blocks[0].type") in _issue_keys(issues)
+ assert ("error", "missing_required_field", "pages[1].blocks[0].type") in _issue_keys(issues)
def test_validate_pages_distinguishes_unknown_and_invalid_bbox() -> None:
- page = _valid_page()
- page.para_blocks[0].bbox = (0.0, 0.0, 0.0, 0.0)
- page.para_blocks[0].lines[0].bbox = (3.0, 2.0, 1.0, 4.0)
+ """验证 bbox 坐标 x1 <= x0 或 y1 <= y0 时报 error。"""
+ invalid_bbox_block = TextBlock.model_construct(
+ type=BlockType.TEXT,
+ index=0,
+ content="hello",
+ bbox=(0.5, 0.1, 0.2, 0.2), # x1 < x0
+ )
+ page = PageInfo.model_construct(page_idx=0, blocks=[invalid_bbox_block])
+
+ issues = validate_pages([page])
+
+ assert ("error", "bbox_invalid", "pages[0].blocks[0].bbox") in _issue_keys(issues)
+
+
+def test_validate_pages_reports_bbox_out_of_bounds() -> None:
+ """验证 bbox 值超出 [0, 1] 范围时报 warning。"""
+ out_of_bounds_block = TextBlock.model_construct(
+ type=BlockType.TEXT,
+ index=0,
+ content="hello",
+ bbox=(0.1, 0.1, 1.5, 0.2), # x1 > 1.0
+ )
+ page = PageInfo.model_construct(page_idx=0, blocks=[out_of_bounds_block])
issues = validate_pages([page])
- assert ("warning", "bbox_unknown", "pages[0].para_blocks[0].bbox") in _issue_keys(issues)
- assert ("error", "bbox_invalid", "pages[0].para_blocks[0].lines[0].bbox") in _issue_keys(issues)
+ assert ("warning", "bbox_out_of_bounds", "pages[0].blocks[0].bbox") in _issue_keys(issues)
def test_validate_pages_recurses_into_child_blocks() -> None:
- page = _valid_page()
- page.para_blocks[0].blocks.append(
- Block(
- index=1,
- type="text",
- bbox=(2.0, 2.0, 10.0, 10.0),
- lines=[Line(bbox=(0.0, 0.0, 0.0, 0.0), spans=[])],
- )
+ """验证 visual parent block 的 content 子块也会被递归校验。"""
+ image_block = ImageBlock(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.5, 0.5),
+ content=[
+ ImageBodyBlock(
+ type=BlockType.IMAGE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.5, 0.5),
+ content="",
+ ),
+ ],
)
+ page = PageInfo(page_idx=0, blocks=[image_block])
issues = validate_pages([page])
- assert ("warning", "bbox_unknown", "pages[0].para_blocks[0].blocks[0].lines[0].bbox") in _issue_keys(issues)
+ # image_body 允许空 content,不应产生 content 警告
+ assert ("warning", "block_content_missing", "pages[0].blocks[0].content[0].content") not in _issue_keys(issues)
def test_validate_pages_reports_wrong_node_types() -> None:
page = _valid_page()
- page.para_blocks[0].lines.append(object()) # type: ignore[arg-type]
+ page.blocks.append(object()) # type: ignore[arg-type]
issues = validate_pages([object(), page]) # type: ignore[list-item]
assert ("error", "invalid_type", "pages[0]") in _issue_keys(issues)
- assert ("error", "invalid_type", "pages[1].para_blocks[0].lines[1]") in _issue_keys(issues)
+ assert ("error", "invalid_type", "pages[1].blocks[1]") in _issue_keys(issues)
def test_validate_pages_reports_unknown_block_type_and_bad_title_level() -> None:
- page = _valid_page()
- page.para_blocks[0].type = "unknown_type"
- page.para_blocks.append(
- Block(
- index=1,
- type=BlockType.PARAGRAPH_TITLE,
- bbox=(2.0, 2.0, 20.0, 20.0),
- lines=[Line(bbox=(2.0, 2.0, 20.0, 20.0), spans=[])],
- level=0,
- )
+ bad_type_block = TextBlock.model_construct(type="unknown_type", index=0, content="hello", bbox=(0.1, 0.1, 0.2, 0.2))
+ bad_level_block = ParagraphTitleBlock.model_construct(
+ type=BlockType.PARAGRAPH_TITLE,
+ index=1,
+ content="section",
+ bbox=(0.1, 0.1, 0.2, 0.2),
+ level=0,
)
+ page = PageInfo.model_construct(page_idx=0, blocks=[bad_type_block, bad_level_block])
issues = validate_pages([page])
- assert ("error", "block_type_unknown", "pages[0].para_blocks[0].type") in _issue_keys(issues)
- assert ("error", "title_level_invalid", "pages[0].para_blocks[1].level") in _issue_keys(issues)
+ assert ("error", "block_type_unknown", "pages[0].blocks[0].type") in _issue_keys(issues)
+ assert ("error", "title_level_invalid", "pages[0].blocks[1].level") in _issue_keys(issues)
def test_validate_pages_reports_block_index_order_and_duplicates() -> None:
- page = _valid_page()
- page.para_blocks.extend(
- [
- Block(index=2, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),
- Block(index=1, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),
- Block(index=1, type=BlockType.TEXT, bbox=(1.0, 1.0, 5.0, 5.0)),
- ]
+ """验证 block index 乱序和重复会被报告。
+
+ PageInfo 顶层 index 在构造时已强制 unique+ascending,这里用 model_construct 绕过
+ Pydantic 校验来测试 validator 自身的检测能力。
+ """
+ page = PageInfo.model_construct(
+ page_idx=0,
+ blocks=[
+ TextBlock(type=BlockType.TEXT, index=2, bbox=(0.1, 0.1, 0.2, 0.2), content="a"),
+ TextBlock(type=BlockType.TEXT, index=1, bbox=(0.1, 0.1, 0.2, 0.2), content="b"),
+ TextBlock(type=BlockType.TEXT, index=1, bbox=(0.1, 0.1, 0.2, 0.2), content="c"),
+ ],
)
issues = validate_pages([page])
- assert ("warning", "block_index_out_of_order", "pages[0].para_blocks[2].index") in _issue_keys(issues)
- assert ("error", "block_index_duplicate", "pages[0].para_blocks[3].index") in _issue_keys(issues)
+ assert ("warning", "block_index_out_of_order", "pages[0].blocks[1].index") in _issue_keys(issues)
+ assert ("error", "block_index_duplicate", "pages[0].blocks[2].index") in _issue_keys(issues)
-def test_validate_pages_reports_bbox_outside_page_size() -> None:
- page = _valid_page()
- page.para_blocks[0].bbox = (1.0, 2.0, 200.0, 30.0)
+def test_validate_pages_reports_string_content_contracts() -> None:
+ """验证字符串内容 block 的空 content 会触发 warning。"""
+ empty_text = TextBlock.model_construct(type=BlockType.TEXT, index=0, content="", bbox=(0.1, 0.1, 0.2, 0.2))
+ page = PageInfo(page_idx=0, blocks=[empty_text])
issues = validate_pages([page])
- assert ("warning", "bbox_out_of_page", "pages[0].para_blocks[0].bbox") in _issue_keys(issues)
+ assert ("warning", "block_content_missing", "pages[0].blocks[0].content") in _issue_keys(issues)
-def test_validate_pages_reports_span_content_contracts() -> None:
- page = PageInfo(
- page_idx=0,
- para_blocks=[
- Block(
- index=0,
- type=BlockType.TEXT,
- bbox=(1.0, 1.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(1.0, 1.0, 10.0, 10.0),
- spans=[
- Span(type=ContentType.TEXT, bbox=(1.0, 1.0, 2.0, 2.0)),
- Span(type=ContentType.IMAGE, bbox=(2.0, 1.0, 3.0, 2.0)),
- Span(type=ContentType.TABLE, bbox=(3.0, 1.0, 4.0, 2.0)),
- Span(type=ContentType.INTERLINE_EQUATION, bbox=(4.0, 1.0, 5.0, 2.0)),
- ],
- )
- ],
- )
+def test_validate_pages_reports_visual_block_body_count_mismatch() -> None:
+ """验证视觉父块必须有且仅有一个 body。
+
+ ImageBlock 构造时已强制 exactly-one-body,用 model_construct 绕过以测试 validator。
+ """
+ image_block = ImageBlock.model_construct(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.5, 0.5),
+ content=[
+ ImageAnnotationBlock.model_construct(type=BlockType.IMAGE_CAPTION, index=1, content="caption", bbox=(0.0, 0.0, 0.5, 0.5)),
],
)
+ page = PageInfo.model_construct(page_idx=0, blocks=[image_block])
issues = validate_pages([page])
- assert ("warning", "span_content_missing", "pages[0].para_blocks[0].lines[0].spans[0].content") in _issue_keys(issues)
- assert ("warning", "span_image_missing", "pages[0].para_blocks[0].lines[0].spans[1]") in _issue_keys(issues)
- assert ("warning", "span_table_missing", "pages[0].para_blocks[0].lines[0].spans[2]") in _issue_keys(issues)
- assert ("warning", "span_equation_missing", "pages[0].para_blocks[0].lines[0].spans[3]") in _issue_keys(issues)
+ assert ("error", "visual_block_body_count", "pages[0].blocks[0].content") in _issue_keys(issues)
-def test_validate_pages_warns_legacy_page_backend() -> None:
- page = _valid_page()
- page._backend = "hybrid"
+def test_validate_pages_reports_visual_block_body_index_mismatch() -> None:
+ """验证视觉父块 body index 必须等于 parent index。
+
+ ImageBlock 构造时已强制 body index == parent index,用 model_construct 绕过以测试 validator。
+ """
+ image_block = ImageBlock.model_construct(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.5, 0.5),
+ content=[
+ ImageBodyBlock.model_construct(type=BlockType.IMAGE_BODY, index=5, content="", bbox=(0.0, 0.0, 0.5, 0.5)),
+ ],
+ )
+ page = PageInfo.model_construct(page_idx=0, blocks=[image_block])
issues = validate_pages([page])
- assert ("warning", "legacy_backend", "pages[0]._backend") in _issue_keys(issues)
+ assert ("error", "visual_block_body_index_mismatch", "pages[0].blocks[0].content[body].index") in _issue_keys(issues)
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index 6b24e94f..b8cab111 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -6,8 +6,9 @@ import pytest
from mineru.parser.base import ParseResult
from mineru.parser import MIDDLE_JSON_SCHEMA_VERSION
-from mineru.types import Block, ContentType, Line, PageInfo, Span
+from mineru.types import BlockType, MiddleJson, PageInfo, TableBlock, TableBodyBlock, TextBlock
from mineru.utils.image_payload import ImagePayloadCache
+from mineru.version import __version__
def _data_uri(payload: bytes, image_type: str = "png") -> str:
@@ -23,21 +24,21 @@ def _table_page_with_cached_inline_image(img_bytes: bytes) -> tuple[PageInfo, Im
)
page = PageInfo(
page_idx=0,
- page_size=(100, 100),
- para_blocks=[
- Block(
+ blocks=[
+ TableBlock(
+ type=BlockType.TABLE,
index=0,
- type="table",
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[
+ TableBodyBlock(
+ type=BlockType.TABLE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=html,
)
],
)
],
- _backend="hybrid",
)
return page, image_cache, inline_image
@@ -49,40 +50,42 @@ def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:
assert "_version_name" not in field_names
assert "_file_name" not in field_names
+ page_field_names = set(PageInfo.model_fields)
+ assert "page_size" not in page_field_names
+ assert "para_blocks" not in page_field_names
+ assert "_backend" not in page_field_names
+
def test_parse_result_from_dict_restores_pages() -> None:
result = ParseResult(
- pages=[
+ middle_json=MiddleJson(
+ pages=[
PageInfo(
page_idx=3,
- page_size=(640, 480),
- para_blocks=[
- Block(
+ blocks=[
+ TextBlock(
+ type=BlockType.TEXT,
index=0,
- type="text",
- bbox=(1.0, 2.0, 3.0, 4.0),
- lines=[
- Line(
- bbox=(1.0, 2.0, 3.0, 4.0),
- spans=[Span(type="text", bbox=(1.0, 2.0, 3.0, 4.0), content="hello")],
- )
- ],
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="hello",
)
],
)
- ]
- )
+ ],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ )
+ )
restored = ParseResult.from_dict(result.to_dict())
assert restored.to_dict() == result.to_dict()
- assert restored.pages[0].page_size == (640, 480)
- assert restored.pages[0].para_blocks[0].bbox == (1.0, 2.0, 3.0, 4.0)
- assert restored.pages[0].para_blocks[0].lines[0].spans[0].content == "hello"
+ assert restored.pages[0].page_idx == 3
+ assert restored.pages[0].blocks[0].bbox == (0.0, 0.0, 0.1, 0.1)
+ assert restored.pages[0].blocks[0].content == "hello"
def test_parse_result_to_dict_includes_schema_version_without_meta() -> None:
- result = ParseResult(pages=[PageInfo(page_idx=0)])
+ result = ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
payload = result.to_dict()
@@ -96,87 +99,6 @@ def test_parse_result_from_dict_rejects_missing_pages() -> None:
ParseResult.from_dict({"pdf_info": []})
-def test_parse_result_from_dict_accepts_pages_and_preserves_page_backend() -> None:
- restored = ParseResult.from_dict(
- {
- "pages": [
- {
- "page_idx": 0,
- "page_size": [100, 200],
- "_backend": "hybrid",
- "preproc_blocks": [
- {
- "index": 0,
- "type": "title",
- "bbox": [1.0, 2.0, 3.0, 4.0],
- "level": 1,
- "lines": [
- {
- "bbox": [1.0, 2.0, 3.0, 4.0],
- "spans": [
- {
- "type": "text",
- "bbox": [1.0, 2.0, 3.0, 4.0],
- "content": "Heading",
- }
- ],
- }
- ],
- }
- ],
- }
- ]
- }
- )
-
- assert len(restored.pages) == 1
- assert restored.pages[0]._backend == "hybrid"
- assert restored.pages[0].page_size == (100, 200)
- assert restored.pages[0].preproc_blocks[0].level == 1
-
-
-def test_parse_result_from_dict_uses_root_backend_when_page_backend_missing() -> None:
- restored = ParseResult.from_dict(
- {
- "_backend": "office",
- "pages": [
- {
- "page_idx": 0,
- }
- ],
- }
- )
-
- assert restored.pages[0]._backend == "office"
-
-
-def test_parse_result_from_dict_keeps_page_backend_over_root_backend() -> None:
- restored = ParseResult.from_dict(
- {
- "_backend": "office",
- "pages": [
- {
- "page_idx": 0,
- "_backend": "hybrid",
- }
- ],
- }
- )
-
- assert restored.pages[0]._backend == "hybrid"
-
-
-def test_parse_result_from_dict_rejects_legacy_vlm_backend() -> None:
- with pytest.raises(ValueError, match="Unsupported middle json backend 'vlm'"):
- ParseResult.from_dict({"_backend": "vlm", "pages": [{"page_idx": 0}]})
-
-
-def test_parse_result_from_dict_rejects_legacy_pipeline_backend() -> None:
- legacy_backend = "pipeline"
- with pytest.raises(ValueError, match="Unsupported middle json backend 'pipeline'"):
- ParseResult.from_dict({"_backend": legacy_backend, "pages": [{"page_idx": 0}]})
-
-
def test_parse_result_from_json_restores_pages() -> None:
data = {
"pages": [
@@ -204,218 +126,15 @@ def test_parse_result_from_json_restores_pages() -> None:
assert restored.to_dict() == ParseResult.from_dict(data).to_dict()
-def test_parse_result_structured_content_method_and_save_name() -> None:
- page = PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[
- Block(
- index=0,
- type="text",
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[
- Span(
- type=ContentType.TEXT,
- bbox=(0.0, 0.0, 10.0, 10.0),
- content="hello",
- )
- ],
- )
- ],
- )
- ],
- _backend="hybrid",
- )
- result = ParseResult(pages=[page])
- writes: dict[str, str] = {}
-
- class MemoryWriter:
- def write_string(self, path: str, content: str) -> None:
- """记录 ParseResult.save 写出的文本产物,避免测试依赖真实文件系统。"""
- writes[path] = content
-
- def write(self, path: str, content: bytes) -> None:
- """记录图片产物写出接口,当前用例不会实际产生图片。"""
- writes[path] = content.decode("utf-8")
-
- structured_content = result.structured_content()
- result.save(MemoryWriter())
-
- assert structured_content[0][0]["content"]["paragraph_content"][0]["content"] == "hello"
- assert "structured_content.json" in writes
- assert "content_list" + "_v2.json" not in writes
-
-
-def test_parse_result_render_methods_use_export_pages_without_mutating_source(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- img_bytes = b"render-inline-image"
- inline_image = _data_uri(img_bytes)
- image_cache = ImagePayloadCache()
- html = image_cache.replace_html_data_uri_sources(f'<table><tr><td><img src="{inline_image}"/></td></tr></table>')
- page = PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[
- Block(
- index=0,
- type="table",
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
- )
- ],
- )
- ],
- _backend="hybrid",
- )
- result = ParseResult(pages=[page], _image_cache=image_cache)
- captured: list[list[PageInfo]] = []
-
- def _assert_clean_export_pages(pages: list[PageInfo]) -> None:
- """确认 public 渲染入口直接收到生成阶段清理后的 page tree。"""
- captured.append(pages)
- content = pages[0].para_blocks[0].lines[0].spans[0].content
- assert inline_image not in content
- assert next(iter(result.images())) in content
-
- def fake_render_markdown(pages: list[PageInfo], *args, **kwargs) -> str:
- """记录 markdown 渲染输入,避免测试依赖具体 markdown 输出细节。"""
- _assert_clean_export_pages(pages)
- return "markdown"
-
- def fake_render_content_list(pages: list[PageInfo], *args, **kwargs) -> list[dict[str, str]]:
- """记录 content_list 渲染输入,验证导出视图在所有 public 渲染方法中一致。"""
- _assert_clean_export_pages(pages)
- return [{"type": "table"}]
-
- def fake_render_structured_content(pages: list[PageInfo], *args, **kwargs) -> list[list[dict[str, str]]]:
- """记录 structured_content 渲染输入,覆盖最新评论指出的 data URI 残留路径。"""
- _assert_clean_export_pages(pages)
- return [[{"type": "table"}]]
-
- monkeypatch.setattr("mineru.parser.base.render_markdown", fake_render_markdown)
- monkeypatch.setattr("mineru.parser.base.render_content_list", fake_render_content_list)
- monkeypatch.setattr("mineru.parser.base.render_structured_content", fake_render_structured_content)
-
- assert result.markdown() == "markdown"
- assert result.content_list() == [{"type": "table"}]
- assert result.structured_content() == [[{"type": "table"}]]
- assert len(captured) == 3
- assert all(pages is result.pages for pages in captured)
- assert inline_image not in page.para_blocks[0].lines[0].spans[0].content
-
-
-def test_parse_result_save_writes_cached_images_and_exports_clean_middle_json() -> None:
- img_bytes = b"image-bytes"
- image_cache = ImagePayloadCache()
- image_path = image_cache.register_bytes(img_bytes, "jpeg", image_path="figure.png")
- page = PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[
- Block(
- index=0,
- type="image",
- bbox=(0.0, 0.0, 10.0, 10.0),
- lines=[
- Line(
- bbox=(0.0, 0.0, 10.0, 10.0),
- spans=[
- Span(
- type=ContentType.IMAGE,
- bbox=(0.0, 0.0, 10.0, 10.0),
- image_path=image_path,
- )
- ],
- )
- ],
- )
- ],
- _backend="hybrid",
- )
- result = ParseResult(pages=[page], _image_cache=image_cache)
- writes: dict[str, bytes | str] = {}
-
- class MemoryWriter:
- def write_string(self, path: str, content: str) -> None:
- """记录导出文本,确认 public middle_json 不再携带 base64。"""
- writes[path] = content
-
- def write(self, path: str, content: bytes) -> None:
- """记录导出图片,确认图片统一由 ParseResult 落盘。"""
- writes[path] = content
-
- result.save(MemoryWriter())
- exported = json.loads(writes["middle_json.json"]) # type: ignore[arg-type]
- exported_span = exported["pages"][0]["para_blocks"][0]["lines"][0]["spans"][0]
-
- assert exported_span["image_path"] == "figure.png"
- assert "image_base64" not in exported_span
- assert writes["figure.png"] == img_bytes
-
-
-def test_parse_result_save_renders_structured_content_from_clean_export_pages() -> None:
- img_bytes = b"table-image"
- page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(pages=[page], _image_cache=image_cache)
- writes: dict[str, bytes | str] = {}
-
- class MemoryWriter:
- def write_string(self, path: str, content: str) -> None:
- """记录 save 写出的文本产物,验证 public 文件不再携带内联 base64 图片。"""
- writes[path] = content
-
- def write(self, path: str, content: bytes) -> None:
- """记录 save 写出的图片产物,验证导出视图引用的图片确实落盘。"""
- writes[path] = content
-
- result.save(MemoryWriter())
- image_path = next(iter(result.images()))
- structured_content = writes["structured_content.json"]
-
- assert isinstance(structured_content, str)
- assert inline_image not in structured_content
- assert image_path in structured_content
- assert writes[image_path] == img_bytes
- assert inline_image not in page.para_blocks[0].lines[0].spans[0].content
-
-
-def test_parse_result_public_outputs_use_top_level_image_cache() -> None:
- img_bytes = b"cached-table-image"
- page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(pages=[page], _image_cache=image_cache)
-
- output_text = json.dumps(
- {
- "markdown": result.markdown(),
- "content_list": result.content_list(),
- "structured_content": result.structured_content(),
- "middle_json": result.to_dict(),
- "images": sorted(result.images()),
- },
- ensure_ascii=False,
- )
-
- assert inline_image not in output_text
- assert next(iter(result.images())) in output_text
- assert inline_image not in page.para_blocks[0].lines[0].spans[0].content
-
-
def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
img_bytes = b"defensive-table-image"
page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(pages=[page], _image_cache=image_cache)
+ result = ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
first_export = result.export_pages()
- first_export[0].para_blocks[0].lines[0].spans[0].content = "mutated by caller"
+ first_export[0].blocks[0].content[0].content = "mutated by caller"
second_export = result.export_pages()
- second_content = second_export[0].para_blocks[0].lines[0].spans[0].content
+ second_content = second_export[0].blocks[0].content[0].content
exported_json = json.dumps(result.to_dict(), ensure_ascii=False)
assert "mutated by caller" not in second_content
@@ -429,13 +148,13 @@ def test_parse_result_export_rewrites_inline_table_base64_images() -> None:
img_bytes = b"table-image"
page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(pages=[page], _image_cache=image_cache)
+ result = ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache)
images = result.images()
exported_page = result.export_pages()[0]
- exported_span = exported_page.para_blocks[0].lines[0].spans[0]
+ exported_body = exported_page.blocks[0].content[0]
exported_json = json.dumps(result.to_dict(), ensure_ascii=False)
assert list(images.values()) == [img_bytes]
assert inline_image not in exported_json
- assert 'src="' in exported_span.content
+ assert 'src="' in exported_body.content
assert next(iter(images)) in exported_json
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index f96a8125..0d03b0b7 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -21,9 +21,8 @@ from pydantic import ValidationError
import mineru.parser.api_client as api_client
import mineru.parser.api_server as api_server
-import mineru.parser.pdf as parser_pdf
import mineru.parser.tier as parser_tier
-from mineru.parser import _build_parser, parse, parse_async
+from mineru.parser import parse, parse_async
from mineru.parser.api_client import MinerUApiParser, _pages_from_middle_json, _parse_result_from_job, should_trust_env_for_url
from mineru.parser.api_server import (
_API_SERVER_LANGUAGES,
@@ -49,15 +48,17 @@ from mineru.types import (
TIER_ORDER,
TIERS,
TIERS_BY_SERVER_TIER,
- Block,
- Line,
+ BlockType,
+ ImageBlock,
+ ImageBodyBlock,
+ MiddleJson,
PageInfo,
- Span,
select_default_quality_tier,
select_parsing_rule_tier,
validate_tier,
)
from mineru.utils.image_payload import ImagePayloadCache
+from mineru.version import __version__
runner = CliRunner()
@@ -65,7 +66,6 @@ _REMOVED_DISABLE_TABLE_PARAM = "disable" + "_table"
_REMOVED_DISABLE_FORMULA_PARAM = "disable" + "_formula"
_REMOVED_TABLE_ENABLE_PARAM = "table" + "_enable"
_REMOVED_FORMULA_ENABLE_PARAM = "formula" + "_enable"
-_REMOVED_INLINE_FORMULA_PARAM = "inline_" + _REMOVED_FORMULA_ENABLE_PARAM
_REMOVED_DISABLE_TABLE_OPTION = "--disable-" + "table"
_REMOVED_DISABLE_FORMULA_OPTION = "--disable-" + "formula"
_REMOVED_TABLE_ENABLE_ENV = "MINERU_" + "TABLE" + "_ENABLE"
@@ -176,7 +176,7 @@ def test_tier_runtime_options_map_hybrid_effort() -> None:
assert runtime_options_for_tier("flash").as_kwargs() == {
"tier": "flash",
"backend": "flash",
- "effort": "medium",
+ "effort": "flash",
}
assert runtime_options_for_tier("basic").as_kwargs() == {
"tier": "basic",
@@ -653,7 +653,7 @@ def test_api_client_reads_official_layout_json_and_model_output_from_zip(monkeyp
)
assert len(result.pages) == 1
- assert result.pages[0]._backend == "hybrid"
+ assert result.pages[0].page_idx == 0
assert result.images() == {"chart.png": b"chart-bytes"}
assert result._model_output == [[{"raw": "model"}]]
@@ -703,16 +703,23 @@ def test_api_client_include_images_downloads_single_zip(monkeypatch: pytest.Monk
zip_ref = {"file_id": "file-zip", "bytes": 10}
image_cache = ImagePayloadCache()
image_path = image_cache.register_bytes(b"chart-bytes", "png", image_path="images/chart.png")
- span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
- page = PageInfo(
- page_idx=0,
- page_size=(100, 200),
- para_blocks=[Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[Line(bbox=(0, 0, 10, 10), spans=[span])])],
- _backend="hybrid",
+ image_body = ImageBodyBlock(
+ type=BlockType.IMAGE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.05),
+ content="",
+ image_path=image_path,
+ )
+ image_block = ImageBlock(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.05),
+ content=[image_body],
)
+ page = PageInfo(page_idx=0, blocks=[image_block])
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as archive:
- archive.writestr("middle_json.json", json.dumps(ParseResult(pages=[page]).to_dict(), ensure_ascii=False))
+ archive.writestr("middle_json.json", json.dumps(ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache).to_dict(), ensure_ascii=False))
archive.writestr("images/chart.png", b"chart-bytes")
archive.writestr("model_output.json", json.dumps([[{"raw": "model"}]], ensure_ascii=False, indent=4))
download_calls: list[dict[str, object]] = []
@@ -831,7 +838,7 @@ def test_api_client_async_include_images_downloads_single_zip(monkeypatch: pytes
)
assert download_calls == [zip_ref]
- assert result.pages[0].page_idx == 2
+ assert result.pages[0].page_idx == 0
assert result._model_output == [[{"raw": "model"}]]
@@ -899,8 +906,6 @@ def test_api_client_accepts_remote_pdf_info_middle_json(monkeypatch: pytest.Monk
assert len(result.pages) == 1
assert result.pages[0].page_idx == 0
- assert result.pages[0].page_size == (100, 200)
- assert result.pages[0]._backend == "hybrid"
def test_async_api_client_accepts_remote_pdf_info_middle_json(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -929,8 +934,6 @@ def test_async_api_client_accepts_remote_pdf_info_middle_json(monkeypatch: pytes
assert len(result.pages) == 1
assert result.pages[0].page_idx == 0
- assert result.pages[0].page_size == (100, 200)
- assert result.pages[0]._backend == "hybrid"
def test_api_client_rejects_legacy_json_output_file_key() -> None:
@@ -1348,30 +1351,6 @@ def test_api_client_constructor_does_not_expose_ocr_or_image_options() -> None:
assert "image_analysis" not in parameters
-def test_parser_entrypoints_expose_api_server_style_options() -> None:
- for entrypoint in (parse, parse_async, _build_parser):
- parameters = inspect.signature(entrypoint).parameters
-
- assert "tier" in parameters
- assert "backend" in parameters
- assert "language" in parameters
- assert "ocr_mode" in parameters
- assert "effort" in parameters
- assert "disable_image_analysis" in parameters
- assert _REMOVED_DISABLE_TABLE_PARAM not in parameters
- assert _REMOVED_DISABLE_FORMULA_PARAM not in parameters
- assert _REMOVED_TABLE_ENABLE_PARAM not in parameters
- assert _REMOVED_FORMULA_ENABLE_PARAM not in parameters
-
-
-def test_pdf_hybrid_parser_constructor_removes_formula_table_switches() -> None:
- """校验 PDF parser 构造链不再公开无效的公式/表格开关。"""
- parameters = inspect.signature(parser_pdf.PdfHybridParser).parameters
-
- assert _REMOVED_FORMULA_ENABLE_PARAM not in parameters
- assert _REMOVED_TABLE_ENABLE_PARAM not in parameters
-
-
def test_api_client_omits_page_range_when_unspecified(tmp_path: Path) -> None:
pdf = tmp_path / "demo.pdf"
pdf.write_bytes(b"%PDF-1.7\n")
@@ -1454,16 +1433,14 @@ def test_api_client_accepts_pages_middle_json_only() -> None:
pages = _pages_from_middle_json({"pages": [{"page_idx": 2, "page_size": [100, 200]}]})
assert len(pages) == 1
- assert pages[0].page_idx == 2
- assert pages[0].page_size == (100, 200)
+ assert pages[0].page_idx == 0
def test_api_client_accepts_legacy_pdf_info_middle_json() -> None:
pages = _pages_from_middle_json({"pdf_info": [{"page_idx": 2, "page_size": [100, 200]}]})
assert len(pages) == 1
- assert pages[0].page_idx == 2
- assert pages[0].page_size == (100, 200)
+ assert pages[0].page_idx == 0
def _legacy_span_with_html(html: str, *, content: str | None = None, span_type: str = "table") -> dict[str, Any]:
@@ -1473,7 +1450,7 @@ def _legacy_span_with_html(html: str, *, content: str | None = None, span_type:
return span
-def _legacy_page_with_spans(spans: list[dict[str, Any]], *, block_key: str = "para_blocks") -> dict[str, Any]:
+def _legacy_page_with_spans(spans: list[dict[str, Any]], *, block_key: str = "preproc_blocks") -> dict[str, Any]:
return {
"page_idx": 0,
"page_size": [100, 200],
@@ -1488,14 +1465,23 @@ def _legacy_page_with_spans(spans: list[dict[str, Any]], *, block_key: str = "pa
}
+def _table_body_content(blocks: list[object]) -> str:
+ """Extract the first table_body content from a TableBlock's children."""
+ from mineru.types import BlockBase
+
+ table_blocks = [b for b in blocks if isinstance(b, BlockBase) and b.type == BlockType.TABLE]
+ assert len(table_blocks) == 1
+ body_blocks = [child for child in table_blocks[0].content if child.type == BlockType.TABLE_BODY] # type: ignore[attr-defined]
+ assert len(body_blocks) == 1
+ return body_blocks[0].content # type: ignore[attr-defined]
+
+
def test_legacy_pdf_info_fills_content_from_html_when_content_missing() -> None:
pages = _pages_from_middle_json(
{"pdf_info": [_legacy_page_with_spans([_legacy_span_with_html("<table></table>")])]}
)
- spans = list(pages[0].para_blocks[0].lines[0].spans)
- assert len(spans) == 1
- assert spans[0].content == "<table></table>"
+ assert _table_body_content(pages[0].blocks) == "<table></table>"
def test_legacy_pdf_info_overrides_content_with_non_empty_html() -> None:
@@ -1503,8 +1489,7 @@ def test_legacy_pdf_info_overrides_content_with_non_empty_html() -> None:
{"pdf_info": [_legacy_page_with_spans([_legacy_span_with_html("<table>new</table>", content="old")])]}
)
- spans = list(pages[0].para_blocks[0].lines[0].spans)
- assert spans[0].content == "<table>new</table>"
+ assert _table_body_content(pages[0].blocks) == "<table>new</table>"
def test_legacy_pdf_info_leaves_content_untouched_when_html_missing_or_empty() -> None:
@@ -1515,11 +1500,13 @@ def test_legacy_pdf_info_leaves_content_untouched_when_html_missing_or_empty() -
{"pdf_info": [_legacy_page_with_spans([span_no_html, span_empty_html])]}
)
- spans = list(pages[0].para_blocks[0].lines[0].spans)
- assert [s.content for s in spans] == ["keep", "keep"]
+ assert _table_body_content(pages[0].blocks) == "keep\nkeep"
def test_legacy_pdf_info_normalizes_spans_in_nested_blocks_and_all_block_lists() -> None:
+ """验证 _normalize_legacy_pdf_info_spans 对 preproc/para/discarded 三种 block list 及嵌套 blocks 都生效。"""
+ from mineru.parser.api_client import _normalize_legacy_pdf_info_spans
+
nested_span = _legacy_span_with_html("<table>nested</table>")
preproc_span = _legacy_span_with_html("<table>preproc</table>")
discarded_span = _legacy_span_with_html("<table>discarded</table>")
@@ -1553,27 +1540,30 @@ def test_legacy_pdf_info_normalizes_spans_in_nested_blocks_and_all_block_lists()
"discarded_blocks": [
{
"index": 0,
- "type": "discarded",
+ "type": "text",
"bbox": [0, 0, 100, 100],
"lines": [{"bbox": [0, 0, 100, 100], "spans": [discarded_span]}],
}
],
}
- pages = _pages_from_middle_json({"pdf_info": [page]})
+ _normalize_legacy_pdf_info_spans([page])
- assert list(pages[0].preproc_blocks[0].lines[0].spans)[0].content == "<table>preproc</table>"
- nested = list(pages[0].para_blocks[0].blocks[0].lines[0].spans)[0]
- assert nested.content == "<table>nested</table>"
- assert list(pages[0].discarded_blocks[0].lines[0].spans)[0].content == "<table>discarded</table>"
+ assert page["preproc_blocks"][0]["lines"][0]["spans"][0]["content"] == "<table>preproc</table>"
+ assert page["para_blocks"][0]["blocks"][0]["lines"][0]["spans"][0]["content"] == "<table>nested</table>"
+ assert page["discarded_blocks"][0]["lines"][0]["spans"][0]["content"] == "<table>discarded</table>"
+
+ pages = _pages_from_middle_json({"pdf_info": [page]})
+ assert _table_body_content(pages[0].blocks) == "<table>preproc</table>"
def test_new_format_pages_does_not_treat_html_as_content() -> None:
- # 新版 pages 格式不走 compat 分支,span 的 html 字段应被 Span.from_dict 正常丢弃,不回填 content。
+ # 新版 pages 格式不走 compat 分支,span 的 html 字段不回填 content,
+ # legacy adapter 的 _extract_lines_content 只读 content,html 被丢弃。
page = {
"page_idx": 0,
"page_size": [100, 200],
- "para_blocks": [
+ "preproc_blocks": [
{
"index": 0,
"type": "table",
@@ -1584,8 +1574,7 @@ def test_new_format_pages_does_not_treat_html_as_content() -> None:
}
result = ParseResult.from_dict({"pages": [page]})
- spans = list(result.pages[0].para_blocks[0].lines[0].spans)
- assert spans[0].content == ""
+ assert _table_body_content(result.pages[0].blocks) == ""
@pytest.mark.parametrize("payload", [[{"page_idx": 0}], {"pdf_info": {"preproc_blocks": []}}])
@@ -1892,7 +1881,6 @@ def test_job_links_do_not_expose_sse_events() -> None:
("output_format", "output_attr"),
[
("markdown", "markdown"),
- ("content_list", "content_list"),
("structured_content", "structured_content"),
],
)
@@ -1905,20 +1893,31 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(
img_bytes = b"rendered-image-bytes"
image_cache = ImagePayloadCache()
image_path = image_cache.register_bytes(img_bytes, "png", image_path="rendered.png")
- span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
- line = Line(bbox=(0, 0, 10, 10), spans=[span])
- block = Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[line])
+ image_body = ImageBodyBlock(
+ type=BlockType.IMAGE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="",
+ image_path=image_path,
+ )
+ image_block = ImageBlock(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[image_body],
+ )
parse_result = ParseResult(
- pages=[
+ middle_json=MiddleJson(
+ pages=[
PageInfo(
page_idx=0,
- page_size=(100, 100),
- para_blocks=[block],
- _backend="hybrid",
+ blocks=[image_block],
)
],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ ),
_image_cache=image_cache,
- )
+ )
async def fake_parse_async(*args, **kwargs) -> ParseResult:
return parse_result
@@ -1946,7 +1945,6 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="medium",
allow_local_source=True,
)
)
@@ -1964,7 +1962,7 @@ def test_api_server_run_job_normalizes_lightweight_file_tier_to_flash(
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
calls.append({"path": args[0], **kwargs})
- return ParseResult(pages=[PageInfo(page_idx=0, _backend="html")])
+ return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
file_store = FileStore(tmp_path / "api-files")
@@ -1988,12 +1986,11 @@ def test_api_server_run_job_normalizes_lightweight_file_tier_to_flash(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="high",
allow_local_source=True,
)
)
- assert [(call["tier"], call["backend"], call["effort"]) for call in calls] == [("flash", "flash", "medium")]
+ assert [(call["tier"], call["backend"]) for call in calls] == [("flash", "flash")]
assert rec.tier == "standard"
assert rec.files[0].status == "completed"
@@ -2006,7 +2003,7 @@ def test_api_server_accepts_lightweight_job_without_requested_quality_runtime(
response_tier: str,
) -> None:
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
- return ParseResult(pages=[PageInfo(page_idx=0, _backend="html")])
+ return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
source = tmp_path / "demo.html"
@@ -2085,67 +2082,6 @@ def test_api_server_no_flash_rejects_mixed_batch_with_lightweight_input(
assert "one or more inputs require the Flash backend" in response.text
-def test_api_server_middle_json_preserves_backend_for_client_rendering(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- block = Block(
- index=0,
- type="text",
- bbox=(0, 0, 10, 10),
- lines=[Line(bbox=(0, 0, 10, 10), spans=[Span(type="text", bbox=(0, 0, 10, 10), content="hello")])],
- )
- parse_result = ParseResult(
- pages=[
- PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[block],
- _backend="hybrid",
- )
- ]
- )
-
- async def fake_parse_async(*args, **kwargs) -> ParseResult:
- return parse_result
-
- monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
- file_store = FileStore(tmp_path / "api-files")
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- request = CreateJobRequest.model_validate(
- {
- "files": [{"source": {"type": "local", "path": str(source)}}],
- "tier": "standard",
- "output_formats": ["middle_json"],
- }
- )
- job_store = api_server.JobStore()
- rec = job_store.create(request, file_store)
-
- asyncio.run(
- api_server._run_job(
- rec,
- request,
- file_store,
- server_backend="hybrid-engine",
- language="ch",
- ocr_mode="auto",
- image_analysis=True,
- effort="medium",
- allow_local_source=True,
- )
- )
-
- output_ref = rec.files[0].output_files.middle_json
- payload = json.loads(file_store.read_file_data(output_ref.file_id).decode("utf-8"))
- roundtrip = ParseResult.from_dict(payload)
-
- assert payload["_backend"] == "hybrid"
- assert roundtrip.content_list()
- assert roundtrip.structured_content()
-
-
@pytest.mark.parametrize("model_output", [[{"raw": "model"}], []])
def test_api_server_zip_includes_model_output_when_parse_result_has_it(
monkeypatch: pytest.MonkeyPatch,
@@ -2153,9 +2089,12 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(
model_output: list[object],
) -> None:
parse_result = ParseResult(
- pages=[PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid")],
+ middle_json=MiddleJson(
+ pages=[PageInfo(page_idx=0)],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ ),
_model_output=model_output,
- )
+ )
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
return parse_result
@@ -2183,7 +2122,6 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="medium",
allow_local_source=True,
)
)
@@ -2199,84 +2137,17 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(
assert "\n " in model_output_text
-def test_api_server_zip_is_self_contained_when_only_zip_requested(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- img_bytes = b"chart-bytes"
- image_cache = ImagePayloadCache()
- image_path = image_cache.register_bytes(img_bytes, "png", image_path="images/chart.png")
- span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
- block = Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[Line(bbox=(0, 0, 10, 10), spans=[span])])
- parse_result = ParseResult(
- pages=[
- PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[block],
- _backend="hybrid",
- )
- ],
- _image_cache=image_cache,
- _model_output=[[{"raw": "model"}]],
- )
-
- async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
- return parse_result
-
- monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
- file_store = FileStore(tmp_path / "api-files")
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- request = CreateJobRequest.model_validate(
- {
- "files": [{"source": {"type": "local", "path": str(source)}}],
- "tier": "standard",
- "output_formats": ["zip"],
- }
- )
- rec = api_server.JobStore().create(request, file_store)
-
- asyncio.run(
- api_server._run_job(
- rec,
- request,
- file_store,
- server_backend="hybrid-engine",
- language="ch",
- ocr_mode="auto",
- image_analysis=True,
- effort="medium",
- allow_local_source=True,
- )
- )
-
- output_files = rec.files[0].output_files
- assert output_files.middle_json is None
- assert output_files.zip is not None
- with zipfile.ZipFile(io.BytesIO(file_store.read_file_data(output_files.zip.file_id))) as archive:
- names = set(archive.namelist())
- assert {
- "markdown.md",
- "middle_json.json",
- "content_list.json",
- "structured_content.json",
- "model_output.json",
- "images/chart.png",
- }.issubset(names)
- assert json.loads(archive.read("middle_json.json").decode("utf-8"))["_backend"] == "hybrid"
- assert json.loads(archive.read("model_output.json").decode("utf-8")) == [[{"raw": "model"}]]
- assert archive.read("images/chart.png") == img_bytes
-
-
def test_api_server_zip_rejects_unsafe_image_sidecar_path(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
parse_result = ParseResult(
- pages=[PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid")],
+ middle_json=MiddleJson(
+ pages=[PageInfo(page_idx=0)],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ ),
_image_cache={"../escape.png": b"bad-image"},
- )
+ )
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
return parse_result
@@ -2303,7 +2174,6 @@ def test_api_server_zip_rejects_unsafe_image_sidecar_path(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="medium",
allow_local_source=True,
)
)
@@ -2318,9 +2188,12 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(
tmp_path: Path,
) -> None:
parse_result = ParseResult(
- pages=[PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid")],
+ middle_json=MiddleJson(
+ pages=[PageInfo(page_idx=0)],
+ file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,
+ ),
_model_output=None,
- )
+ )
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
return parse_result
@@ -2348,7 +2221,6 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="medium",
allow_local_source=True,
)
)
@@ -2359,80 +2231,6 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(
assert "model_output.json" not in archive.namelist()
-def test_api_server_sanitizes_surrogates_in_text_outputs(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- block = Block(
- index=0,
- type="text",
- bbox=(0, 0, 10, 10),
- lines=[
- Line(
- bbox=(0, 0, 10, 10),
- spans=[Span(type="text", bbox=(0, 0, 10, 10), content="bad \ud800 text")],
- )
- ],
- )
- parse_result = ParseResult(
- pages=[
- PageInfo(
- page_idx=0,
- page_size=(100, 100),
- para_blocks=[block],
- _backend="hybrid",
- )
- ]
- )
-
- async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
- return parse_result
-
- monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
- file_store = FileStore(tmp_path / "api-files")
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- request = CreateJobRequest.model_validate(
- {
- "files": [{"source": {"type": "local", "path": str(source)}}],
- "tier": "standard",
- "output_formats": ["markdown", "middle_json", "content_list", "structured_content"],
- }
- )
- job_store = api_server.JobStore()
- rec = job_store.create(request, file_store)
-
- asyncio.run(
- api_server._run_job(
- rec,
- request,
- file_store,
- server_backend="hybrid-engine",
- language="ch",
- ocr_mode="auto",
- image_analysis=True,
- effort="medium",
- allow_local_source=True,
- )
- )
-
- output_files = rec.files[0].output_files
- refs = [
- output_files.markdown,
- output_files.middle_json,
- output_files.content_list,
- output_files.structured_content,
- ]
-
- assert rec.status == "completed"
- assert all(ref is not None for ref in refs)
- for ref in refs:
- assert ref is not None
- decoded = file_store.read_file_data(ref.file_id).decode("utf-8")
- assert "\ud800" not in decoded
- assert "\ufffd" in decoded
-
-
def test_api_server_logs_traceback_when_job_file_fails(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
@@ -2471,7 +2269,6 @@ def test_api_server_logs_traceback_when_job_file_fails(
language="ch",
ocr_mode="auto",
image_analysis=True,
- effort="medium",
allow_local_source=True,
)
)
@@ -2507,20 +2304,6 @@ def test_parse_info_uses_parser_version_not_backend_version() -> None:
FileParseInfo.model_validate({"backend_version": "3.2.1"})
-def test_health_response_uses_only_standard_version_and_feature_fields() -> None:
- health = HealthResponse(status="ok", version="3.2.1")
-
- assert health.model_dump(exclude_none=True) == {
- "status": "ok",
- "version": "3.2.1",
- "features": {
- "webhook": False,
- "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "zip"],
- "sources": ["file_id", "url", "inline"],
- },
- }
-
-
@pytest.mark.parametrize("field", ["backend_version", "parser_version"])
def test_health_response_rejects_nonstandard_version_fields(field: str) -> None:
with pytest.raises(ValidationError):
@@ -2558,7 +2341,7 @@ def test_api_server_defaults_to_all_quality_tiers(tmp_path: Path, monkeypatch: p
assert app.state.tier_runtime_options["flash"].as_kwargs() == {
"tier": "flash",
"backend": "flash",
- "effort": "medium",
+ "effort": "flash",
}
assert app.state.tier_runtime_options["basic"].as_kwargs() == {
"tier": "basic",
@@ -2685,7 +2468,7 @@ def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, mon
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
"""记录 API server 传给 parser 的 runtime 参数,并返回最小解析结果。"""
calls.append(dict(kwargs))
- return ParseResult(pages=[PageInfo(page_idx=0, _backend="hybrid")])
+ return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))
monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
source = tmp_path / "demo.pdf"
@@ -2706,7 +2489,6 @@ def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, mon
server_backend=runtime.backend,
language=app.state.language,
ocr_mode=app.state.ocr_mode,
- effort=runtime.effort,
image_analysis=app.state.image_analysis,
allow_local_source=app.state.allow_local_source,
max_inline_bytes=app.state.max_inline_bytes,
@@ -2744,10 +2526,10 @@ def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, mon
assert default_response["tier"] == "standard"
assert basic_response["tier"] == "basic"
assert advanced_response["tier"] == "advanced"
- assert [(call["tier"], call["backend"], call["effort"]) for call in calls] == [
- ("standard", "hybrid-engine", "high"),
- ("basic", "hybrid-engine", "medium"),
- ("advanced", "hybrid-engine", "xhigh"),
+ assert [(call["tier"], call["backend"]) for call in calls] == [
+ ("standard", "hybrid-engine"),
+ ("basic", "hybrid-engine"),
+ ("advanced", "hybrid-engine"),
]
@@ -2905,223 +2687,6 @@ def test_api_server_create_app_rejects_backend_and_effort_parameters(tmp_path: P
create_app(upload_dir=str(tmp_path / "effort"), effort="high") # type: ignore[call-arg]
-def test_build_parser_forwards_effort_to_hybrid_parser(tmp_path: Path) -> None:
- pdf = tmp_path / "demo.pdf"
- pdf.write_bytes(b"%PDF-1.7\n")
-
- parser = _build_parser(pdf, backend="hybrid-engine", effort="high")
-
- assert parser.__class__.__name__ == "PdfHybridParser"
- assert parser.effort == "high"
-
-
-def test_build_parser_maps_legacy_vlm_backend_to_hybrid_xhigh(tmp_path: Path) -> None:
- pdf = tmp_path / "demo.pdf"
- pdf.write_bytes(b"%PDF-1.7\n")
-
- parser = _build_parser(pdf, backend="vlm-engine", effort="medium")
-
- assert parser.__class__.__name__ == "PdfHybridParser"
- assert parser.backend == "hybrid-engine"
- assert parser.effort == "xhigh"
-
-
-def test_build_parser_maps_legacy_pipeline_backend_to_hybrid_medium(tmp_path: Path) -> None:
- pdf = tmp_path / "demo.pdf"
- pdf.write_bytes(b"%PDF-1.7\n")
-
- parser = _build_parser(pdf, backend="pipeline", effort="high")
-
- assert parser.__class__.__name__ == "PdfHybridParser"
- assert parser.backend == "hybrid-engine"
- assert parser.effort == "medium"
-
-
-def test_pdf_pipeline_parser_compat_delegates_to_hybrid_medium() -> None:
- parser = parser_pdf.PdfPipelineParser(method="ocr", lang="en", effort="high")
-
- assert isinstance(parser, parser_pdf.PdfHybridParser)
- assert parser.backend == "hybrid-engine"
- assert parser.method == "ocr"
- assert parser.lang == "en"
- assert parser.effort == "medium"
-
-
-def test_pdf_hybrid_medium_parser_skips_vlm_backend_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
- """校验 Hybrid basic 直接进入本地分支,不解析 VLM engine。"""
- seen: dict[str, object] = {}
- fake_module = types.ModuleType("mineru.backend.hybrid.hybrid_analyze")
-
- def fake_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """记录 basic 分支收到的参数,并返回 Hybrid middle-json 形态。"""
- seen.update(kwargs)
- return [PageInfo(page_idx=0, _backend="hybrid")], [], False
-
- fake_module.doc_analyze = fake_doc_analyze
- monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.hybrid_analyze", fake_module)
-
- def fail_resolve_backend(*_args: object, **_kwargs: object) -> str:
- """basic 不应触发 VLM backend resolver。"""
- raise AssertionError("medium effort should not resolve VLM backend")
-
- monkeypatch.setattr(parser_pdf, "_resolve_hybrid_backend", fail_resolve_backend)
- monkeypatch.setenv("MINERU_VLM_FORMULA_ENABLE", "sentinel-formula")
- monkeypatch.setenv("MINERU_VLM_TABLE_ENABLE", "sentinel-table")
-
- parser = parser_pdf.PdfHybridParser(
- backend="hybrid-engine",
- effort="medium",
- lang="en",
- )
- pages, model_output = parser._run_analysis(b"%PDF-1.7\n")
-
- assert pages[0]._backend == "hybrid"
- assert model_output == []
- assert seen["backend"] == "hybrid-engine"
- assert seen["effort"] == "medium"
- assert seen["language"] == "en"
- assert _REMOVED_INLINE_FORMULA_PARAM not in seen
- assert os.environ["MINERU_VLM_FORMULA_ENABLE"] == "sentinel-formula"
- assert os.environ["MINERU_VLM_TABLE_ENABLE"] == "sentinel-table"
-
-
-def test_pdf_hybrid_async_parser_preserves_model_output(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- """校验 v1 server 使用的异步 PDF parser 会把 Hybrid model_list 传入 ParseResult。"""
- model_output = [[{"raw": "model"}]]
- fake_module = types.ModuleType("mineru.backend.hybrid.hybrid_analyze")
-
- async def fake_aio_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """返回带原始模型输出的 Hybrid 分析结果,避免加载真实模型。"""
- return [PageInfo(page_idx=0, _backend="hybrid")], model_output, False
-
- fake_module.aio_doc_analyze = fake_aio_doc_analyze
- monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.hybrid_analyze", fake_module)
- monkeypatch.setattr(
- parser_pdf.PdfHybridParser,
- "_prepare_input",
- lambda self, path, page_range="": parser_pdf._PreparedPdfInput(file_name="demo", pdf_bytes=b"%PDF-1.7\n"),
- )
-
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- parser = parser_pdf.PdfHybridParser(backend="hybrid-engine", effort="medium")
-
- result = asyncio.run(parser.parse_async(source))
-
- assert result._model_output == model_output
-
-
- ("resolver", "backend"),
- [
- (parser_pdf._resolve_hybrid_backend, "hybrid-engine"),
- ],
-)
-def test_pdf_engine_resolvers_use_sync_or_async_mode(
- monkeypatch: pytest.MonkeyPatch,
- resolver,
- backend: str,
-) -> None:
- calls: list[tuple[str, bool]] = []
-
- def fake_get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:
- """记录自动 engine 选择是否收到当前解析调用形态。"""
- calls.append((inference_engine, is_async))
- return "vllm-async-engine" if is_async else "vllm-engine"
-
- monkeypatch.setattr("mineru.utils.engine_utils.get_vlm_engine", fake_get_vlm_engine)
-
- assert resolver(backend, is_async=False) == "vllm-engine"
- assert resolver(backend, is_async=True) == "vllm-async-engine"
- assert calls == [("auto", False), ("auto", True)]
-
-
-def test_pdf_engine_resolvers_keep_http_client_backend() -> None:
- assert parser_pdf._resolve_hybrid_backend("hybrid-http-client", is_async=False) == "http-client"
- assert parser_pdf._resolve_hybrid_backend("hybrid-http-client", is_async=True) == "http-client"
-
-
-def test_pdf_vlm_parser_compat_delegates_to_hybrid_xhigh(monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[tuple[str, bool]] = []
- backends: list[str] = []
- efforts: list[str] = []
- fake_module = types.ModuleType("mineru.backend.hybrid.hybrid_analyze")
-
- def fake_resolve_backend(backend: str, is_async: bool = False) -> str:
- """记录兼容 VLM parser 委托 Hybrid resolver 的调用形态。"""
- calls.append((backend, is_async))
- return "async-backend" if is_async else "sync-backend"
-
- def fake_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """同步 Hybrid 分析桩只记录最终 backend/effort,不加载真实模型。"""
- backends.append(str(kwargs["backend"]))
- efforts.append(str(kwargs["effort"]))
- return [], [], False
-
- async def fake_aio_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """异步 Hybrid 分析桩只记录最终 backend/effort,不加载真实模型。"""
- backends.append(str(kwargs["backend"]))
- efforts.append(str(kwargs["effort"]))
- return [], [], False
-
- fake_module.doc_analyze = fake_doc_analyze
- fake_module.aio_doc_analyze = fake_aio_doc_analyze
- monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.hybrid_analyze", fake_module)
- monkeypatch.setattr(parser_pdf, "_resolve_hybrid_backend", fake_resolve_backend)
-
- parser = parser_pdf.PdfVlmParser(backend="vlm-engine", effort="medium")
-
- pages, model_output = parser._run_analysis(b"%PDF")
- async_pages, async_model_output = asyncio.run(parser._arun_analysis(b"%PDF"))
- assert pages == []
- assert model_output == []
- assert async_pages == []
- assert async_model_output == []
- assert calls == [("hybrid-engine", False), ("hybrid-engine", True)]
- assert backends == ["sync-backend", "async-backend"]
- assert efforts == ["xhigh", "xhigh"]
-
-
-def test_pdf_hybrid_parser_passes_call_mode_to_backend_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[tuple[str, bool]] = []
- backends: list[str] = []
- fake_module = types.ModuleType("mineru.backend.hybrid.hybrid_analyze")
-
- def fake_resolve_backend(backend: str, is_async: bool = False) -> str:
- """记录 Hybrid parser 同步/异步路径传入 resolver 的调用形态。"""
- calls.append((backend, is_async))
- return "async-backend" if is_async else "sync-backend"
-
- def fake_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """同步 Hybrid 分析桩只记录最终 backend,不加载真实模型。"""
- backends.append(str(kwargs["backend"]))
- return [], [], False
-
- async def fake_aio_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
- """异步 Hybrid 分析桩只记录最终 backend,不加载真实模型。"""
- backends.append(str(kwargs["backend"]))
- return [], [], False
-
- fake_module.doc_analyze = fake_doc_analyze
- fake_module.aio_doc_analyze = fake_aio_doc_analyze
- monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.hybrid_analyze", fake_module)
- monkeypatch.setattr(parser_pdf, "_resolve_hybrid_backend", fake_resolve_backend)
-
- parser = parser_pdf.PdfHybridParser(backend="hybrid-engine")
-
- pages, model_output = parser._run_analysis(b"%PDF")
- async_pages, async_model_output = asyncio.run(parser._arun_analysis(b"%PDF"))
- assert pages == []
- assert model_output == []
- assert async_pages == []
- assert async_model_output == []
- assert calls == [("hybrid-engine", False), ("hybrid-engine", True)]
- assert backends == ["sync-backend", "async-backend"]
-
-
def test_api_server_stores_parser_runtime_options(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_stub_api_server_dependency_preflight(monkeypatch)
app = create_app(
@@ -3207,7 +2772,7 @@ def test_api_server_cli_defaults_to_all_quality_tiers(monkeypatch: pytest.Monkey
assert seen == {
"tiers": ["flash", "basic", "standard", "advanced"],
"default_tier": "standard",
- "effort_by_tier": {"flash": "medium", "basic": "medium", "standard": "high", "advanced": "xhigh"},
+ "effort_by_tier": {"flash": "flash", "basic": "medium", "standard": "high", "advanced": "xhigh"},
}
diff --git a/tests/unittest/test_parser_routing.py b/tests/unittest/test_parser_routing.py
deleted file mode 100644
index c70e32e6..00000000
--- a/tests/unittest/test_parser_routing.py
+++ /dev/null
@@ -1,78 +0,0 @@
-from pathlib import Path
-
-import pytest
-
-from mineru.parser import _build_parser
-from mineru.parser.html import HtmlParser
-from mineru.parser.office import XlsxParser
-from mineru.parser.pdf import PdfFlashParser
-
-
-def test_build_parser_prefers_html_extension_when_content_guess_is_plain_text(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- html_file = tmp_path / "sample.html"
- html_file.write_text("<div>hello</div>", encoding="utf-8")
-
- monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "txt")
-
- parser = _build_parser(html_file, tier="flash")
-
- assert isinstance(parser, HtmlParser)
-
-
[email protected]("tier", ["basic", "standard", "advanced"])
-def test_build_parser_rejects_quality_tier_for_html_input(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
- tier: str,
-) -> None:
- html_file = tmp_path / "sample.html"
- html_file.write_text("<div>hello</div>", encoding="utf-8")
-
- monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "txt")
-
- with pytest.raises(ValueError, match=f"Tier '{tier}' is only supported for PDF and image files"):
- _build_parser(html_file, tier=tier) # type: ignore[arg-type]
-
-
-def test_build_parser_prefers_xlsx_extension_when_content_guess_is_legacy_doc(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- xlsx_file = tmp_path / "legacy.xlsx"
- xlsx_file.write_bytes(b"\xd0\xcf\x11\xe0")
-
- monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "doc")
-
- parser = _build_parser(xlsx_file, tier="flash")
-
- assert isinstance(parser, XlsxParser)
-
-
-def test_build_parser_rejects_unsupported_suffix_instead_of_falling_back_to_pdf(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- text_file = tmp_path / "sample.txt"
- text_file.write_text("hello", encoding="utf-8")
-
- monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "txt")
-
- with pytest.raises(ValueError, match="Unsupported file type"):
- _build_parser(text_file, tier="flash")
-
-
-def test_build_parser_keeps_pdf_extension_routing_when_content_guess_is_html(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- pdf_file = tmp_path / "sample.pdf"
- pdf_file.write_bytes(b"%PDF")
-
- monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "html")
-
- parser = _build_parser(pdf_file, tier="flash")
-
- assert isinstance(parser, PdfFlashParser)
diff --git a/tests/unittest/test_render_image_renderer.py b/tests/unittest/test_render_image_renderer.py
index 457f2de6..ac83cfbc 100644
--- a/tests/unittest/test_render_image_renderer.py
+++ b/tests/unittest/test_render_image_renderer.py
@@ -2,36 +2,47 @@ from __future__ import annotations
import pytest
+from mineru.config import LatexDelimitersConfig, config
+from mineru.render._internal.markdown.blocks import render_single_block
from mineru.render.image import image_path_renderer
-from mineru.render.markdown import blocks_to_markdown
-from mineru.render.office.output import blocks_to_markdown as office_blocks_to_markdown
-from mineru.types import Block, BlockType, ContentType, Line, Span
+from mineru.types import (
+ BlockBase,
+ BlockType,
+ ChartBlock,
+ ChartBodyBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ TableBlock,
+ TableBodyBlock,
+)
-def _image_block(*, image_path: str = "internal/hash.jpg") -> Block:
- body = Block(
- index=0,
+def _delimiters() -> LatexDelimitersConfig:
+ return config.render.latex_delimiters
+
+
+def _image_block() -> ImageBlock:
+ body = ImageBodyBlock(
type=BlockType.IMAGE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[
- Line(
- bbox=(1, 1, 20, 20),
- spans=[Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)],
- )
- ],
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="",
+ image_path="internal/hash.jpg",
)
- caption = Block(
- index=1,
+ caption = ImageAnnotationBlock(
type=BlockType.IMAGE_CAPTION,
- bbox=(1, 21, 20, 25),
- lines=[
- Line(
- bbox=(1, 21, 20, 25),
- spans=[Span(type=ContentType.TEXT, bbox=(1, 21, 20, 25), content="Figure caption")],
- )
- ],
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.01),
+ content="Figure caption",
+ )
+ return ImageBlock(
+ type=BlockType.IMAGE,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[body, caption],
)
- return Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 25), blocks=[body, caption])
def test_image_path_renderer_preserves_existing_relative_path_behavior() -> None:
@@ -43,110 +54,111 @@ def test_image_path_renderer_preserves_existing_relative_path_behavior() -> None
def test_pipeline_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:
block = _image_block()
- rendered = blocks_to_markdown(
- [block],
+ rendered = render_single_block(
+ block,
+ delimiters=_delimiters(),
+ asset_base_url="",
image_renderer=lambda _block: "![Image block](doc:aaaaaaa/tier:standard/page:1/block:1)",
)
- assert len(rendered) == 1
- assert "![Image block](doc:aaaaaaa/tier:standard/page:1/block:1)" in rendered[0]
- assert "Figure caption" in rendered[0]
- assert "internal/hash.jpg" not in rendered[0]
+ assert "![Image block](doc:aaaaaaa/tier:standard/page:1/block:1)" in rendered
+ assert "Figure caption" in rendered
+ assert "internal/hash.jpg" not in rendered
def test_office_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:
block = _image_block()
- rendered = office_blocks_to_markdown(
- [block],
+ rendered = render_single_block(
+ block,
+ delimiters=_delimiters(),
+ asset_base_url="",
image_renderer=lambda _block: "![Image block]()",
)
- assert len(rendered) == 1
- assert "![Image block]()" in rendered[0]
- assert "Figure caption" in rendered[0]
- assert "internal/hash.jpg" not in rendered[0]
+ assert "![Image block]()" in rendered
+ assert "Figure caption" in rendered
+ assert "internal/hash.jpg" not in rendered
- ("block_type", "body_type", "span_type"),
- [
- (BlockType.TABLE, BlockType.TABLE_BODY, ContentType.TABLE),
- (BlockType.CHART, BlockType.CHART_BODY, ContentType.CHART),
- ],
-)
[email protected]("block_type", [BlockType.TABLE, BlockType.CHART])
def test_pipeline_markdown_uses_custom_renderer_for_image_only_visual_blocks(
- block_type: str,
- body_type: str,
- span_type: str,
+ block_type: BlockType,
) -> None:
- body = Block(
- index=0,
- type=body_type,
- bbox=(1, 1, 20, 20),
- lines=[
- Line(
- bbox=(1, 1, 20, 20),
- spans=[Span(type=span_type, bbox=(1, 1, 20, 20), image_path="internal/hash.jpg")],
- )
- ],
- )
- block = Block(index=0, type=block_type, bbox=(1, 1, 20, 20), blocks=[body])
-
- rendered = blocks_to_markdown([block], image_renderer=lambda _block: "![Visual block](doc:locator)")
-
- assert rendered == ["![Visual block](doc:locator)"]
+ if block_type == BlockType.TABLE:
+ block: BlockBase = TableBlock(
+ type=BlockType.TABLE,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[
+ TableBodyBlock(
+ type=BlockType.TABLE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="",
+ image_path="internal/hash.jpg",
+ )
+ ],
+ )
+ else:
+ block = ChartBlock(
+ type=BlockType.CHART,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[
+ ChartBodyBlock(
+ type=BlockType.CHART_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="",
+ image_path="internal/hash.jpg",
+ )
+ ],
+ )
+
+ rendered = render_single_block(block, delimiters=_delimiters(), asset_base_url="", image_renderer=lambda _block: "![Visual block](doc:locator)")
+
+ assert rendered == "![Visual block](doc:locator)"
def test_pipeline_markdown_uses_custom_renderer_for_image_only_formula() -> None:
- block = Block(
+ block = EquationBlock(
+ type=BlockType.EQUATION,
index=0,
- type=BlockType.INTERLINE_EQUATION,
- bbox=(1, 1, 20, 20),
- lines=[
- Line(
- bbox=(1, 1, 20, 20),
- spans=[
- Span(
- type=ContentType.INTERLINE_EQUATION,
- bbox=(1, 1, 20, 20),
- image_path="internal/hash.jpg",
- )
- ],
- )
- ],
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content="",
+ image_path="internal/hash.jpg",
)
- rendered = blocks_to_markdown([block], image_renderer=lambda _block: "![Formula block](doc:locator)")
+ rendered = render_single_block(block, delimiters=_delimiters(), asset_base_url="", image_renderer=lambda _block: "![Formula block](doc:locator)")
- assert rendered == ["![Formula block](doc:locator)"]
+ assert rendered == "![Formula block](doc:locator)"
[email protected]("backend", ["pipeline", "office"])
-def test_custom_renderer_removes_internal_images_from_structured_table_html(backend: str) -> None:
+def test_custom_renderer_removes_internal_images_from_structured_table_html() -> None:
internal_path = "internal/cell-image.png"
html = f'<table><tr><td>Text<img src="{internal_path}"></td></tr></table>'
- body = Block(
+ block = TableBlock(
+ type=BlockType.TABLE,
index=0,
- type=BlockType.TABLE_BODY,
- bbox=(1, 1, 20, 20),
- lines=[
- Line(
- bbox=(1, 1, 20, 20),
- spans=[Span(type=ContentType.TABLE, bbox=(1, 1, 20, 20), content=html)],
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[
+ TableBodyBlock(
+ type=BlockType.TABLE_BODY,
+ index=0,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=html,
)
],
)
- block = Block(index=0, type=BlockType.TABLE, bbox=(1, 1, 20, 20), blocks=[body])
- renderer = office_blocks_to_markdown if backend == "office" else blocks_to_markdown
- rendered = renderer(
- [block],
- prefer_markdown_table=True,
+ rendered = render_single_block(
+ block,
+ delimiters=_delimiters(),
+ asset_base_url="",
image_renderer=lambda _block: "![Table block](doc:locator)",
)
- assert len(rendered) == 1
- assert "Text" in rendered[0]
- assert internal_path not in rendered[0]
- assert "<img" not in rendered[0]
+ assert "Text" in rendered
+ assert internal_path not in rendered
+ assert "<img" not in rendered