Skip to content

feat: add Mistral OCR (/v1/ocr) as a document parser; fix "Can't find model" mis-tag (#5782, #7075) - #17057

Merged
yingfeng merged 28 commits into
infiniflow:mainfrom
Xavierando:feat/mistral-ocr-parser
Jul 24, 2026
Merged

yingfeng merged 28 commits into
infiniflow:mainfrom
Xavierando:feat/mistral-ocr-parser

Conversation

@Xavierando

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Adds first-class support for Mistral OCR (POST /v1/ocr) as a document parser, and fixes the long-standing bug where selecting mistral-ocr-latest fails with Can't find model for <tenant>/image2text/mistral-ocr-latest.

mistral-ocr-latest is Mistral's dedicated document-OCR endpoint, not a vision-chat (image2text) model, but the catalog tagged it image2text — so it resolved to the CvModel registry, which has no Mistral entry, and there was no OcrModel entry either. This PR registers it correctly and wires it end to end.

Closes #17056
Closes #5782
Closes #7075

What it does

  1. MistralParser + MistralOcrModel (deepdoc/parser/mistral_parser.py, rag/llm/ocr_model.py) — a proper OcrModel factory Mistral OCR, mirroring the SoMark cloud-OCR template. Tables stay inline as HTML; the page range maps to Mistral's native pages selector (absolute page indices, billed per selected page, so multi-task documents do not re-OCR the whole file); documents over the inline limit go through the /v1/files signed-URL flow with cleanup.
  2. Removes the image2text mis-tag for mistral-ocr-latest from the Mistral factory in conf/llm_factories.json (it now lives only in the Mistral OCR factory, typed ocr). This is what closes the Can't find model path.
  3. MistralCV (rag/llm/cv_model.py) — a thin GptV4 subclass over Mistral's OpenAI-compatible endpoint, registering a Mistral entry in the CvModel registry so Mistral vision models (pixtral-*) become usable as image2text at all.
  4. Figure description — Mistral-OCR-extracted figures are captioned using the tenant's configured image2text model (any provider), matching MinerU/deepdoc behaviour.
  5. Wires the parser into every chunking method (naive, paper, book, laws, manual, one, presentation) and the rag/flow DAG path. This also fixes a related latent gap where those chunkers forwarded only mineru_llm_name, so any model-based OCR provider selected on a non-naive method silently fell through.

Notes on the API contract (verified against the live Mistral API): pages is a selector (returns absolute index, bills only the requested pages); include_blocks: true returns per-block bounding boxes usable for chunk highlighting and figure cropping; large files use POST /v1/files → signed URL → OCR → DELETE.

Testing: new unit tests cover the response→sections contract (both the 2-tuple naive path and the typed 3-tuple DAG path), the position-tag rescale, the HTTP client incl. upload failure/cleanup paths, parse_pdf page-range threading, registry registration, env config, the suffix normalization, the factory catalog entry, MistralCV registration, and figure-description injection. Verified end to end against the live Mistral API on real PDFs (table extraction, page-selector cost avoidance, figure captioning).

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Xavierando and others added 20 commits July 15, 2026 08:45
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…alized bytes

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove unused `import os` and `_KNOWN_INTERNAL_TYPES` from mistral_parser.py;
run `ruff format` (repo line-length=200) across the feature files. No behavior
change; feature suite 41/41 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ighten annotations

Final-review polish: crop() logged a stray [SoMark] prefix (copy-paste from the
cloned method); MistralOcrModel now logs its resolved config (redacted) for
parity with SoMarkOcrModel; parse_pdf return/filepath annotations tightened.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…actory

mistral-ocr-latest is the /v1/ocr endpoint, not a vision (image2text) or chat
model. The stock Mistral factory declared it as ["image2text","chat"], which
is the root of infiniflow#5782/infiniflow#7075 ("Can't find model for .../image2text/mistral-ocr-latest"):
selecting it as a layout recognizer resolved to CvModel["Mistral"], which does
not exist. It is now correctly represented by the separate "Mistral OCR" factory
(model_type ocr). Removing the redundant, non-functional entry completes the fix
and de-duplicates it from the parser dropdown. Pixtral vision models are left as-is
(a separate 'no Mistral CvModel' gap, out of scope here).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
RAGFlow's CvModel registry had no Mistral entry, so pixtral vision models
advertised by the Mistral factory failed with 'Can't find model' when used as
image2text. Mistral exposes an OpenAI-compatible endpoint, so MistralCV is a
thin GptV4 subclass pointing at https://api.mistral.ai/v1 (default pixtral-12b-2409).
This enables Mistral vision models for figure description and any image2text use.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…model

Mistral OCR extracts figures (image blocks with bboxes). When the tenant has a
vision model configured, by_mistral_ocr now passes it to the parser, which crops
each figure from the locally rendered page and captions it via vision_llm_chunk
(same helper MinerU/deepdoc use). The caption replaces the bare 'image N' label,
so figures become searchable/embeddable content. Best-effort: any failure or a
missing vision model silently degrades to the caption/seq label. Pairs with the
new MistralCV so pixtral can serve as that vision model.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
_describe_image serialized the crop to PNG bytes and passed those to
vision_llm_chunk, but that helper expects a PIL Image (it calls img.size and
img.save). The bytes path silently returned '' so figures were never described.
Pass the crop directly; add a regression test asserting a PIL Image reaches
vision_llm_chunk.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
book/laws/manual/one/paper/presentation dispatch to naive's PARSERS but only
forwarded mineru_llm_name (paper: only that), so selecting Mistral OCR as the
layout recognizer on a doc using any of these chunking methods left
mistral_ocr_llm_name=None -> by_mistral_ocr fell through to 'Mistral OCR not
found' and crashed. Forward mistral_ocr_llm_name=parser_model_name like naive.py
does. (SoMark has the same latent gap in paper.py; out of scope here.)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 17, 2026
@coderabbitai

ghost commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Mistral OCR as a dedicated PDF parsing provider with environment configuration, OCR API integration, model registration, parser routing, page-range support, figure enrichment, and unit tests across configuration and ingestion paths.

Changes

Mistral OCR support

Layer / File(s) Summary
Provider and configuration contracts
common/constants.py, conf/llm_factories.json, api/db/joint_services/tenant_model_service.py, common/parser_config_utils.py, api/apps/services/provider_api_service.py, test/unit_test/common/*
Defines Mistral OCR defaults and environment keys, registers a dedicated OCR factory, provisions tenant models, normalizes OCR model names, exposes OCR provider types, and tests these contracts.
OCR parser and model implementations
deepdoc/parser/mistral_parser.py, rag/llm/ocr_model.py, rag/llm/cv_model.py, test/unit_test/deepdoc/parser/*, test/unit_test/llm/*
Adds PDF rendering, Mistral OCR requests, inline and uploaded-file workflows, response normalization, cropping, optional vision captions, OCR model wrapping, Mistral CV registration, and unit coverage.
PDF pipeline routing
rag/flow/parser/parser.py, rag/app/{naive,book,laws,manual,one,paper,presentation}.py
Accepts Mistral OCR parse methods, resolves configured or environment-backed models, routes PDF chunking paths, forwards the model name, and converts parser output into standardized records.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PDFChunker
  participant ParserRouter
  participant TenantModelService
  participant MistralOcrModel
  participant MistralOCRAPI
  PDFChunker->>ParserRouter: select Mistral OCR and pass PDF
  ParserRouter->>TenantModelService: resolve configured or environment-backed model
  TenantModelService-->>ParserRouter: return OCR model configuration
  ParserRouter->>MistralOcrModel: parse PDF with page bounds
  MistralOcrModel->>MistralOCRAPI: submit inline PDF or uploaded file
  MistralOCRAPI-->>MistralOcrModel: return OCR pages and blocks
  MistralOcrModel-->>ParserRouter: return normalized sections
  ParserRouter-->>PDFChunker: return standardized records
Loading

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: lynn-inf, 6ba3i

Poem

I’m a rabbit with OCR in my ear,
PDFs hop through the Mistral frontier.
Pages align and figures shine,
Tests dance softly, all is fine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly captures the main change: adding Mistral OCR parser support and fixing the mis-tagged model lookup.
Description check ✅ Passed The description gives strong context, scope, motivation, and testing details, exceeding the repository's brief summary template.
Linked Issues check ✅ Passed The changes address the linked issues by adding Mistral OCR, correcting its catalog type, adding MistralCV, and wiring support through chunking paths.
Out of Scope Changes check ✅ Passed The added code and tests are all aligned with the Mistral OCR objectives, with no clear unrelated changes introduced.

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

❤️ Share

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

@coderabbitai

ghost commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/app/book.py (1)

121-122: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Bypass further chunking for Mistral OCR's structured output.

Like MinerU, Docling, and PaddleOCR, Mistral OCR returns structured semantic sections that should not be blindly merged by the subsequent text chunker. While "mistral ocr" was correctly added to the chunk_token_num bypass list in naive.py (Line 1076), it was omitted in the other chunking flows, meaning Mistral OCR blocks may be inappropriately concatenated here.

  • rag/app/book.py#L121-L122: add "mistral ocr" to the name in [...] list.
  • rag/app/laws.py#L213-L214: add "mistral ocr" to the name in [...] list.
  • rag/app/manual.py#L202-L203: add "mistral ocr" to the name in [...] list.
  • rag/app/one.py#L117-L118: add "mistral ocr" to the name in [...] list.
  • rag/app/presentation.py#L225-L226: add "mistral ocr" to the name in [...] list.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/app/book.py` around lines 121 - 122, Bypass subsequent chunking for
Mistral OCR structured output by adding "mistral ocr" to each name list in
rag/app/book.py lines 121-122, rag/app/laws.py lines 213-214, rag/app/manual.py
lines 202-203, rag/app/one.py lines 117-118, and rag/app/presentation.py lines
225-226, alongside the existing parser names and preserving the chunk_token_num
assignment.
🧹 Nitpick comments (2)
rag/flow/parser/parser.py (1)

338-360: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the shared parser-name normalizer.

This duplicates normalize_layout_recognizer and already differs from it, requiring every provider suffix to be maintained twice.

Proposed refactor
-        raw_parse_method = conf.get("parse_method", "")
-        parser_model_name = None
-        parse_method = raw_parse_method
-        parse_method = parse_method or ""
-        if isinstance(raw_parse_method, str):
-            lowered = raw_parse_method.lower()
-            ...
-            elif lowered.endswith("`@mistral` ocr"):
-                parser_model_name = raw_parse_method
-                parse_method = "Mistral OCR"
+        parse_method, parser_model_name = normalize_layout_recognizer(
+            conf.get("parse_method", "")
+        )
+        parse_method = parse_method or ""

As per coding guidelines, “converge coexisting implementations to one path unless an external contract requires compatibility.”

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

In `@rag/flow/parser/parser.py` around lines 338 - 360, Replace the local
parser-selection and provider-suffix normalization logic in the configuration
parsing flow with the shared normalize_layout_recognizer implementation. Reuse
its returned parser method and model name so provider suffix handling has one
source of truth, while preserving the existing downstream behavior for
parse_method and parser_model_name.

Source: Coding guidelines

rag/llm/cv_model.py (1)

331-337: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log activation of the Mistral vision flow.

Emit a structured initialization log containing the model and resolved base URL, but never the API key.

As per coding guidelines, “Add logging for new flows.”

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

In `@rag/llm/cv_model.py` around lines 331 - 337, Add a structured initialization
log in MistralCV.__init__ after resolving base_url and before or after the
superclass call, including model_name and the resolved base URL. Ensure the log
context identifies the Mistral vision flow and excludes key from both structured
fields and message content.

Source: Coding guidelines

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

Inline comments:
In `@deepdoc/parser/mistral_parser.py`:
- Around line 58-75: Update the Mistral parser’s base URL handling and the
outbound request flow around the document upload and response-reading logic to
enforce the server’s existing outbound-request policy. Validate resolved
destinations, including every redirect target, before issuing requests, and
reject private, loopback, link-local, and metadata endpoints; apply the same
centralized validation to the request paths referenced near the later
upload/response handling block.
- Around line 462-473: Update the page-rendering flow around __images__ and
page_images so restricted from_page/to_page requests rasterize only that range
while preserving the absolute-to-local mapping required by _line_tag and crop
logic. Determine the available page count safely before building pages, avoid
fallback ranges based on MAXIMUM_PAGE_NUMBER, and return empty results cleanly
when rendering or page-count detection fails.
- Around line 435-440: Update the file cleanup in the finally block to validate
the response returned by requests.delete, treating 4xx/5xx statuses as cleanup
failures and logging them alongside transport exceptions. Keep cleanup errors
non-fatal so the original OCR error remains unmasked, and include the existing
file_id context in the warning.

In `@rag/llm/ocr_model.py`:
- Around line 337-358: Update the configuration normalization around _resolve so
flat dictionaries with a string api_key retain the full raw_config; only unwrap
raw_config["api_key"] when that value is a configuration dictionary. Preserve
lower-case api_key and mistral_ocr_base_url resolution, and add a regression
test covering this flat configuration.

In `@test/unit_test/common/test_parser_config_utils_mistral.py`:
- Around line 11-15: Update test_mistral_ocr_suffix_case_insensitive to use
model_name explicitly by asserting it retains the original model reference
returned by normalize_layout_recognizer. Do not leave the value unused;
alternatively, rename the binding to _model_name if preservation is not part of
the test’s intended behavior.

In `@test/unit_test/deepdoc/parser/test_mistral_parser.py`:
- Around line 263-271: Replace the try/except and `assert False` exception
checks in the affected tests, including `test_call_ocr_raises_on_http_error` and
the four additional sites, with `pytest.raises` context managers. Preserve each
test’s expected exception type and message/status assertion within the
corresponding context.

---

Outside diff comments:
In `@rag/app/book.py`:
- Around line 121-122: Bypass subsequent chunking for Mistral OCR structured
output by adding "mistral ocr" to each name list in rag/app/book.py lines
121-122, rag/app/laws.py lines 213-214, rag/app/manual.py lines 202-203,
rag/app/one.py lines 117-118, and rag/app/presentation.py lines 225-226,
alongside the existing parser names and preserving the chunk_token_num
assignment.

---

Nitpick comments:
In `@rag/flow/parser/parser.py`:
- Around line 338-360: Replace the local parser-selection and provider-suffix
normalization logic in the configuration parsing flow with the shared
normalize_layout_recognizer implementation. Reuse its returned parser method and
model name so provider suffix handling has one source of truth, while preserving
the existing downstream behavior for parse_method and parser_model_name.

In `@rag/llm/cv_model.py`:
- Around line 331-337: Add a structured initialization log in MistralCV.__init__
after resolving base_url and before or after the superclass call, including
model_name and the resolved base URL. Ensure the log context identifies the
Mistral vision flow and excludes key from both structured fields and message
content.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c33ba534-7d7d-4d6f-8932-e039642e815a

📥 Commits

Reviewing files that changed from the base of the PR and between c420de0 and 009203b.

📒 Files selected for processing (22)
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • common/constants.py
  • common/parser_config_utils.py
  • conf/llm_factories.json
  • deepdoc/parser/mistral_parser.py
  • rag/app/book.py
  • rag/app/laws.py
  • rag/app/manual.py
  • rag/app/naive.py
  • rag/app/one.py
  • rag/app/paper.py
  • rag/app/presentation.py
  • rag/flow/parser/parser.py
  • rag/llm/cv_model.py
  • rag/llm/ocr_model.py
  • test/unit_test/common/test_mistral_ocr_env.py
  • test/unit_test/common/test_mistral_ocr_factory.py
  • test/unit_test/common/test_parser_config_utils_mistral.py
  • test/unit_test/deepdoc/parser/test_mistral_ocr_model.py
  • test/unit_test/deepdoc/parser/test_mistral_parser.py
  • test/unit_test/llm/test_mistral_cv.py

Comment on lines +58 to +75
def __init__(
self,
base_url: str,
api_key: str = "",
*,
model: str = "mistral-ocr-latest",
table_format: str = "html",
keep_header_footer: bool = False,
timeout: int = 600,
inline_max_bytes: int = 20 * 1024 * 1024,
):
self.base_url = (base_url or "https://api.mistral.ai/v1").strip().rstrip("/")
self.api_key = api_key
self.model = model
self.table_format = table_format.strip().lower() if table_format else "html"
self.keep_header_footer = bool(keep_header_footer)
self.timeout = int(timeout)
self.inline_max_bytes = int(inline_max_bytes)

ghost Jul 17, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Validate base_url with the server’s outbound-request policy.

The configurable URL is used to upload document contents and read response bodies without restricting private, loopback, link-local, or metadata endpoints. A crafted provider URL therefore creates an SSRF path. Validate resolved destinations and redirects centrally before issuing these requests.

Also applies to: 419-445

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

In `@deepdoc/parser/mistral_parser.py` around lines 58 - 75, Update the Mistral
parser’s base URL handling and the outbound request flow around the document
upload and response-reading logic to enforce the server’s existing
outbound-request policy. Validate resolved destinations, including every
redirect target, before issuing requests, and reject private, loopback,
link-local, and metadata endpoints; apply the same centralized validation to the
request paths referenced near the later upload/response handling block.

Source: Linters/SAST tools

Comment thread deepdoc/parser/mistral_parser.py Resolved
Comment thread deepdoc/parser/mistral_parser.py Resolved
Comment thread rag/llm/ocr_model.py Resolved
- MistralOcrModel: preserve a flat config whose api_key is a plain string
  (was discarded, leaving the parser with no key) + regression test.
- _call_ocr cleanup: treat a non-2xx DELETE response as a cleanup failure
  (was silently accepted, potentially retaining uploaded PDFs).
- parse_pdf page selector: bound by the real page count, never the
  MAXIMUM_PAGE_NUMBER sentinel, so a failed render can't build a ~100k list.
- tests: replace assert-False exception checks with pytest.raises (Ruff B011),
  assert the preserved model ref in the case-insensitive suffix test (RUF059).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@yingfeng yingfeng added the ci Continue Integration label Jul 17, 2026
@yingfeng
yingfeng marked this pull request as draft July 17, 2026 13:40
@yingfeng
yingfeng marked this pull request as ready for review July 17, 2026 13:40
@dosubot dosubot Bot added the 🌈 python Pull requests that update Python code label Jul 17, 2026
@yingfeng
yingfeng marked this pull request as draft July 17, 2026 13:41
@yingfeng
yingfeng marked this pull request as ready for review July 17, 2026 13:41
@yingfeng
yingfeng marked this pull request as draft July 17, 2026 13:41
@yingfeng
yingfeng marked this pull request as ready for review July 17, 2026 13:41
@yingfeng
yingfeng marked this pull request as draft July 17, 2026 13:42
@yingfeng
yingfeng marked this pull request as ready for review July 17, 2026 13:42
@codecov

ghost commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (cd9db94) to head (6c65599).
⚠️ Report is 25 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17057   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

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

Xavier Prot and others added 2 commits July 17, 2026 17:21
Address xhigh review findings on the Mistral OCR parser:

- _resolve_internal_type: accept Optional[str] so a block with a
  missing/null "type" falls back to text instead of raising
  BeartypeCallHintParamViolation in production.
- _normalize_pages: coerce a present-but-null "index" to 0 (dict.get's
  default only applies to an absent key), avoiding None + 1 TypeError in
  _line_tag.
- _line_tag: clamp rescaled coords to >= 0 so a bbox bleeding past the
  page origin is not silently dropped by extract_positions' regex.
- Remove dead code: the unused table_id block field and the permanently
  empty ALWAYS_DISCARDED set plus its guard.

Add regression tests for the three hardening fixes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@yingfeng
yingfeng requested a review from Lynn-Inf July 20, 2026 05:43

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Inline comments for specific changes. Rest LGTM.

Comment thread conf/llm_factories.json Outdated
"tags": "OCR",
"status": "1",
"rank": "930",
"llm": []

ghost Jul 20, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It would be better to add a default model (like MinerU-model above), in case users are unable to add a model through the model provider page.

ghost Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks — done in c644fa3b. I added a default model to the Mistral OCR factory, matching the MinerU-model / SoMark-model convention.

One deliberate difference: I used the real model id mistral-ocr-latest as the llm_name rather than a Mistral OCR-model placeholder.

The reason is that the other OCR providers and Mistral select the OCR engine differently. MinerU, SoMark and OpenDataLoader are dedicated OCR services — the engine is chosen by which endpoint the file is POSTed to (/file_parse, /submit, …), and no model id is sent in the request body, so their *-model llm_name is a purely internal label. Mistral, by contrast, is a multi-model API: api.mistral.ai/v1 serves chat, embeddings, vision and OCR behind one base URL, so the /v1/ocr call must carry a "model" field to say which model to run. The parser threads the selected name straight through as "model": self.model (deepdoc/parser/mistral_parser.py:398), so the llm_name is the API model id — a placeholder like Mistral OCR-model would come back as a model not found / 422 error.

Everything else (tags: OCR, max_tokens: 8192, model_type: ocr) follows the same shape as the other OCR factories.

Xavier Prot and others added 4 commits July 23, 2026 13:48
Per maintainer review: like the other OCR factories (MinerU-model,
SoMark-model, ...), the Mistral OCR factory must list a default model so
it is usable without manually adding one through the model provider page.

Use the real API id "mistral-ocr-latest" as the llm_name rather than a
"Mistral OCR-model" placeholder: the parser POSTs self.model verbatim to
Mistral's /v1/ocr endpoint, so a placeholder name would be rejected by
the API.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The factory now ships a default mistral-ocr-latest model, so the
assertion that its llm list is empty is stale. Assert the default model
is present and correctly shaped (ocr type, OCR tag) instead.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Xavierando

ghost commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

CI red checks are environmental network flakes, not code issues — a re-run should clear them.

The failing checks are all outbound-network failures on the runners, at test collection/setup time, in files unrelated to this PR:

  • ragflow_preflight (latest run) — 2 errors during collection, both external CDN fetches at import time:
    • test/unit_test/agent/component/test_akshare.py → requests.exceptions.SSLError: HTTPSConnectionPool(host='openaipublic.blob.core.windows.net') (tiktoken cl100k_base vocab download)
    • test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py → huggingface_hub.errors.LocalEntryNotFoundError (HuggingFace Hub download)
  • ragflow_tests_elasticsearch (python) (earlier run) — aborted in setup: _pytest.outcomes.Exit: Error in set_tenant_info: ('Connection aborted.', RemoteDisconnected(...))
  • An earlier run also hit a tiktoken CDN connection-reset and a failed codecov-action download (SSL).

None touch the files changed here. Where the network cooperated, everything this PR affects is green: on 477fd58, ragflow_preflight ran the full unit suite (incl. the Mistral OCR tests) green, and ragflow_tests_infinity (python) passed the entire integration/SDK suite (25m). The same ES SDK suite that flaked in setup passed on the Infinity backend.

Could a maintainer re-run the failed jobs when convenient? I don't have re-run permissions on the repo. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

3 participants