Skip to content

Refactor Office OCR converters to reuse core conversion pipelines - #2506

Merged
Adam Fourney (afourney) merged 6 commits into
mainfrom
ocr_refactor
Sep 16, 2026
Merged

Adam Fourney (afourney) merged 6 commits into
mainfrom
ocr_refactor

Conversation

@afourney

@afourney Adam Fourney (afourney) commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Replace the OCR plugin’s duplicated DOCX, PPTX, and XLSX conversion pipelines with thin subclasses of the core converters. Native parsing and formatting fixes now benefit OCR-enabled conversion automatically, rather than requiring parallel fixes in the plugin.

Each core Office converter exposes the same semi-private _image_to_html(image_stream, stream_info, **kwargs) hook. Core handles image extraction and placement; the plugin supplies OCR text as escaped HTML for the shared HTML-to-Markdown renderer.

  • DOCX inserts image fragments before Markdown conversion, preserving table/list context and splitting enclosing paragraphs where needed.
  • PPTX inherits core slide traversal, tables, charts, notes, and image resolution while retaining caption-first behavior.
  • XLSX reads images from the repaired workbook, validates drawing/image relationship types, and preserves the existing images-after-table layout and image ordering.
  • OCR recognition is cached per conversion, with results reused at each image occurrence.
  • Image metadata reaches compatible OCR services, preserving MIME types such as image/svg+xml, while legacy one-argument services remain supported.

Compatibility and output

Public constructor and conversion signatures are unchanged. Hooks that return None or blank text retain native rendering.

OCR markers are preserved, but recognized text now follows shared Markdown escaping and line-break handling. PPTX also inherits core’s real newlines and empty-title/notes handling; XLSX heading spacing follows core.

Bump core to 0.1.8b3 and require markitdown>=0.1.8b3 in the OCR package so dependency resolution enforces hook availability.

PDF and legacy .xls conversion are unchanged. SVG rasterization and broader HTML-table formatting improvements remain outside this PR.

Copilot AI 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.

🟡 Changes recommended

The OCR package dependency permits older core versions that lack the newly required hook.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Adds a reusable DOCX image-to-HTML hook and refactors DOCX OCR to use the core conversion pipeline.

Changes:

  • Introduces image fragment replacement with native fallback.
  • Simplifies DOCX OCR through inheritance and per-document caching.
  • Adds comprehensive core and OCR integration tests.
File summaries
File Description
packages/markitdown/src/markitdown/converters/_docx_converter.py Adds the image-rendering hook.
packages/markitdown/src/markitdown/converter_utils/docx/_images.py Bridges image callbacks into generated HTML.
packages/markitdown/tests/test_docx_images.py Tests hook behavior and HTML placement.
packages/markitdown-ocr/src/markitdown_ocr/_docx_converter_with_ocr.py Refactors OCR onto the core converter.
packages/markitdown-ocr/tests/test_docx_inheritance.py Tests inherited OCR conversion behavior.
packages/markitdown-ocr/tests/test_docx_converter.py Updates OCR output expectations.
Review details
  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI 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.

🟢 Approval recommended

The hook, fallback behavior, error handling, compatibility constraint, and OCR integration are comprehensively tested.

Review details
  • Files reviewed: 9/9 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Copilot AI 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.

🟡 Changes recommended

XLSX relationship validation can expose non-image package parts to OCR, and whitespace-only PPTX captions incorrectly suppress OCR fallback.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 21/21 changed files
  • Comments generated: 2
  • Review effort level: Balanced

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

Copilot AI 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.

🟡 Changes recommended

Office OCR calls discard image MIME metadata, causing formats such as SVG to be submitted with an incorrect media type.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

packages/markitdown-ocr/src/markitdown_ocr/_docx_converter_with_ocr.py:54

  • Discarding the image StreamInfo forces the bundled OCR service to infer the MIME type from Pillow. DOCX can contain formats such as SVG that Pillow does not identify, causing valid SVG bytes to be submitted as data:image/png. Please pass metadata to services that support it while preserving the documented one-argument custom-service compatibility.
  • Files reviewed: 21/21 changed files
  • Comments generated: 2
  • Review effort level: Balanced

Copilot AI 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.

🔵 Needs a closer look

The broad Office conversion and plugin refactor warrants final human validation despite extensive automated coverage.

Review details
  • Files reviewed: 23/23 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@afourney Adam Fourney (afourney) changed the title Add _image_to_html helper for docx ocr conversion. Refactor Office OCR converters to reuse core conversion pipelines Sep 16, 2026
@afourney
Adam Fourney (afourney) merged commit 945314a into main Sep 16, 2026
24 checks passed
@afourney
Adam Fourney (afourney) deleted the ocr_refactor branch September 16, 2026 17:23
Lukas (L4XB) added a commit to L4XB/markitdown that referenced this pull request Sep 17, 2026
microsoft#2506 turned `_read_xlsx_sheets` into a context manager and made
`XlsxConverterWithOCR` a subclass of `XlsxConverter`. The fix now sits on
that structure: both `read_excel` calls in `_read_xlsx_sheets` pass
`dtype=object`, and the sheet loop in `XlsxConverter.convert` renders
through `sheet_to_html`.

`_xlsx_converter_with_ocr.py` is taken from main as is. It no longer reads
or renders a sheet itself, so the fix reaches it through the parent.
Guillermo Dols (gdols) added a commit to gdols/markitdown that referenced this pull request Sep 23, 2026
markitdown-ocr stopped carrying its own copy of the chart method in microsoft#2506,
so the fix in the core converter now reaches it by inheritance.
San-Hsien (SanHsien) pushed a commit to SanHsien/markitdown that referenced this pull request Oct 25, 2026
本 repo 已停用 issues,接續開發報告依規定寫在本 commit 訊息。

# 接續開發報告 2026-10-25

## 一、線索與處理
- open/draft PR:無。PR #1 已關閉未合併,內容已 squash 進 main(bebd625),
  head 分支 ci/job-names-20261024 已不在遠端。
- 非預設分支:只有 claude/gifted-dirac-r9vpm0(本 session 工作分支,內容已 fast-forward 進 main)。
- open issue:無(issues 已停用)。
- main 紅燈 Dependency freshness:ruff 0.17.2。對 E9+F gate 全綠,記入
  .github/dependency-deferrals.json(deferredLatest),未調高下限 → 已轉綠。
- main 紅燈 Upstream check:20 commit/153 PR/40 issue 未審 → 第三輪審查完成,已轉綠。
- HANDOFF.md/TODO.md:不存在。程式碼 TODO/FIXME 7 處皆為上游產品碼,不動。
- REVIEW.md:R-01~R-10 已修,無未修項。
- 2026-09-30 待辦 microsoft#2506:觸發條件成立(上游整併測試依賴它),已採用(4a377f9)。

## 二、做了什麼(bebd625..本 commit)
- 上游 commit:cherry-pick -x 本輪 20 筆中 19 筆(9a15f66..e211f83),microsoft#2731 部分採用(3e440d7),
  補採 microsoft#2506(4a377f9)。
- 例外移植上游 OPEN PR,皆先重現缺陷、附 PR 測試:
  - microsoft#2674(1029094):短 UTF-8 文字被誤判 UTF-16 亂碼。
  - microsoft#2742(9947ed1):UTF-8 BOM 殘留。
  - microsoft#2738(38a2ae6):Outlook MSG 尾端 NUL。
  - microsoft#2620(0d1140c):大寫副檔名音訊不轉譯。
- 依賴(c561006):
  - requirements 跟隨上游 magika/mammoth/certifi,補列 ocr 漏的 PyMuPDF、Pillow。
  - dependabot 補 ocr 與 sample-plugin 目錄。
  - ruff 延後。
- 文件(8f1db57、3382745、b618bc9、本 commit):
  - microsoft#1913 英文段落併入 README.en.md。
  - 繁中 README text_content → markdown。
  - DECISIONS/UPSTREAM/baseline 推進水位。
- CI(d4c2b7a):移除 microsoft#2586 帶進 tests.yml 的 Linux 專用 apt-get 步驟(R-09)。
- 驗證:
  - 每批推送前由全新審查員審 diff 並等 Windows CI 完成(一次 NO-SHIP,修正後重審 ship)。
  - 維護 gate 與 Windows CI py3.10–3.14 全綠。
  - 產品測試(Linux 雲端)1312 passed/12 skipped/2 failed,2 個失敗皆因沙箱無對外網路。

## 三、上游結論
- 水位:commit 7482c09、PR microsoft#2765、issue microsoft#2762。
- commit:採用 18、部分採用 1(microsoft#2731 ARM/pre-commit CI 不適用),microsoft#2733 版本 bump 不適用。
- PR:
  - MERGED 12,例外移植 4。
  - 其餘 OPEN 不 fork-ahead,等上游合併。
  - 無 merge ref 12 筆多為重複,不採。
- issue:已修 2(microsoft#2646、microsoft#2719),16 筆對應 OPEN PR,其餘為不適用、觸發條件或垃圾。
- 逐筆見 docs/DECISIONS.md 2026-10-25。

## 四、刻意不做(理由/觸發條件)
- microsoft#2756 ZIP 檔名:會把 Big5「臺灣報告.pdf」解成亂碼(誤判為 shift_jis_2004)。
  觸發:上游合併時先補 cp950 測試,或改為優先 metadata_encoding/locale。
- microsoft#2621/microsoft#2622 SSRF 政策:牽動 MCP/URI 擷取。
  觸發:上游合併,或本 fork 對外提供 MCP HTTP 服務。
- microsoft#2679/microsoft#2723 cp1252 偵測:可能影響 CJK 舊碼頁。觸發:上游合併後跑 CJK charset 測試。
- microsoft#2407 youtube-transcript-api ~=1.2.3:維持本 fork >=1.0.0+freshness-hold。
- microsoft#2740 Python 3.15:上游 CI 加 3.15 時同步 ci.yml。

## 五、需要維護者決定
1. 雲端 session 對 microsoft/markitdown 無 API 權限(只能匿名 git 讀取)。
   本輪 PR/issue 清單取自本 fork Upstream check log,狀態以 refs/pull/*/merge 判斷。
2. 產品程式變動只在 Linux 跑過;ci.yml 只跑維護 gate。請在 Windows 11 本機跑
   pwsh -NoProfile -File tools\test_product.ps1 -AllPackages。
3. 「不 fork-ahead」政策的 4 筆例外移植;若不同意可 revert 1029094、9947ed1、38a2ae6、0d1140c。

STATUS: NEEDS-MAINTAINER Windows 11 本機跑 test_product.ps1 -AllPackages;確認是否接受 4 筆上游 open PR 例外移植

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014CWBckUdMZcCAsc15iaJtm
San-Hsien (SanHsien) pushed a commit to SanHsien/markitdown that referenced this pull request Oct 25, 2026
本 repo 已停用 issues,接續開發報告依規定寫在本 commit 訊息。

# 接續開發報告 2026-10-25

## 一、線索與處理
- open/draft PR:無。PR #1 已關閉未合併,內容已 squash 進 main(bebd625),
  head 分支 ci/job-names-20261024 已不在遠端。
- 非預設分支:只有 claude/gifted-dirac-r9vpm0(本 session 工作分支,內容已 fast-forward 進 main)。
- open issue:無(issues 已停用)。
- main 紅燈 Dependency freshness:ruff 0.17.2。對 E9+F gate 全綠,記入
  .github/dependency-deferrals.json(deferredLatest),未調高下限 → 已轉綠。
- main 紅燈 Upstream check:20 commit/153 PR/40 issue 未審 → 第三輪審查完成,已轉綠。
- HANDOFF.md/TODO.md:不存在。程式碼 TODO/FIXME 7 處皆為上游產品碼,不動。
- REVIEW.md:R-01~R-10 已修,無未修項。
- 2026-09-30 待辦 microsoft#2506:觸發條件成立(上游整併測試依賴它),已採用(4a377f9)。

## 二、做了什麼(bebd625..本 commit)
- 上游 commit:cherry-pick -x 本輪 20 筆中 19 筆(9a15f66..e211f83),microsoft#2731 部分採用(3e440d7),
  補採 microsoft#2506(4a377f9)。
- 例外移植上游 OPEN PR,皆先重現缺陷、附 PR 測試:
  - microsoft#2674(1029094):短 UTF-8 文字被誤判 UTF-16 亂碼。
  - microsoft#2742(9947ed1):UTF-8 BOM 殘留。
  - microsoft#2738(38a2ae6):Outlook MSG 尾端 NUL。
  - microsoft#2620(0d1140c):大寫副檔名音訊不轉譯。
- 依賴(c561006):
  - requirements 跟隨上游 magika/mammoth/certifi,補列 ocr 漏的 PyMuPDF、Pillow。
  - dependabot 補 ocr 與 sample-plugin 目錄。
  - ruff 延後。
- 文件(8f1db57、3382745、b618bc9、本 commit):
  - microsoft#1913 英文段落併入 README.en.md。
  - 繁中 README text_content → markdown。
  - DECISIONS/UPSTREAM/baseline 推進水位。
- CI(d4c2b7a):移除 microsoft#2586 帶進 tests.yml 的 Linux 專用 apt-get 步驟(R-09)。
- 驗證:
  - 每批推送前由全新審查員審 diff 並等 Windows CI 完成(一次 NO-SHIP,修正後重審 ship)。
  - 維護 gate 與 Windows CI py3.10–3.14 全綠。
  - 產品測試(Linux 雲端)1312 passed/12 skipped/2 failed,2 個失敗皆因沙箱無對外網路。

## 三、上游結論
- 水位:commit 7482c09、PR microsoft#2765、issue microsoft#2762。
- commit:採用 18、部分採用 1(microsoft#2731 ARM/pre-commit CI 不適用),microsoft#2733 版本 bump 不適用。
- PR:
  - MERGED 12,例外移植 4。
  - 其餘 OPEN 不 fork-ahead,等上游合併。
  - 無 merge ref 12 筆多為重複,不採。
- issue:已修 2(microsoft#2646、microsoft#2719),16 筆對應 OPEN PR,其餘為不適用、觸發條件或垃圾。
- 逐筆見 docs/DECISIONS.md 2026-10-25。

## 四、刻意不做(理由/觸發條件)
- microsoft#2756 ZIP 檔名:會把 Big5「臺灣報告.pdf」解成亂碼(誤判為 shift_jis_2004)。
  觸發:上游合併時先補 cp950 測試,或改為優先 metadata_encoding/locale。
- microsoft#2621/microsoft#2622 SSRF 政策:牽動 MCP/URI 擷取。
  觸發:上游合併,或本 fork 對外提供 MCP HTTP 服務。
- microsoft#2679/microsoft#2723 cp1252 偵測:可能影響 CJK 舊碼頁。觸發:上游合併後跑 CJK charset 測試。
- microsoft#2407 youtube-transcript-api ~=1.2.3:維持本 fork >=1.0.0+freshness-hold。
- microsoft#2740 Python 3.15:上游 CI 加 3.15 時同步 ci.yml。

## 五、需要維護者決定
1. 雲端 session 對 microsoft/markitdown 無 API 權限(只能匿名 git 讀取)。
   本輪 PR/issue 清單取自本 fork Upstream check log,狀態以 refs/pull/*/merge 判斷。
2. 產品程式變動只在 Linux 跑過;ci.yml 只跑維護 gate。請在 Windows 11 本機跑
   pwsh -NoProfile -File tools\test_product.ps1 -AllPackages。
3. 「不 fork-ahead」政策的 4 筆例外移植;若不同意可 revert 1029094、9947ed1、38a2ae6、0d1140c。

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014CWBckUdMZcCAsc15iaJtm
STATUS: NEEDS-MAINTAINER Windows 11 本機跑 test_product.ps1 -AllPackages;確認是否接受 4 筆上游 open PR 例外移植
San-Hsien (SanHsien) added a commit to SanHsien/markitdown that referenced this pull request Nov 20, 2026
With the OCR plugin enabled but no LLM client, XlsxConverterWithOCR still
built _XlsxImages, so a drawing relationship pointing at a missing media
part raised KeyError and failed the converter, and every embedded image
was read into memory although the hook declines them all. Delegate to the
native XlsxConverter when neither the constructor nor the call supplies an
ocr_service. Core _XlsxImages keeps upstream microsoft#2506 behaviour (malformed
references fail loudly and the dispatcher falls back to the built-in
converter); upstream main ed17895 has no later change here.

Review findings F-1 and H-1 (2026-11-20).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
San-Hsien (SanHsien) added a commit to SanHsien/markitdown that referenced this pull request Nov 21, 2026
With an ocr_service configured, a drawing relationship pointing at a
missing media part (or a dangling relationship id) still raised KeyError
in _XlsxImages. With enable_builtins=False or a direct converter call
nothing could fall back, so the whole workbook failed; with builtins the
dispatcher fell back to native output and every other image's OCR was
lost.

Add an XlsxConverter._unreadable_image(reference, error) hook that
_XlsxImages calls on KeyError/BadZipFile/zlib.error while reading an
image. Converters that do not override it construct _XlsxImages exactly
as upstream microsoft#2506 does, so broken references still raise and the
upstream test test_malformed_image_reference_does_not_become_silent_native_fallback
is unchanged. XlsxConverterWithOCR overrides it to emit a RuntimeWarning
and skip only that image. Recorded as a fork divergence in
docs/DECISIONS.md and FORK.md; REVIEW.md F-1 updated (and its stale
ea28184 hash corrected to a88c8e4).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
San-Hsien (SanHsien) added a commit to SanHsien/markitdown that referenced this pull request Nov 21, 2026
Two gaps left by b6b2a3c, found by independent verification:

- A sheet relationship to a drawing part absent from the package still
  raised KeyError with enable_builtins=False or a direct converter call,
  losing the whole workbook. _XlsxImages now routes a missing drawing
  through the same _unreadable_image hook and skips that drawing.
- No size cap: a 200 MB embedded image was read fully into memory (peak
  about 449 MB) and sent to OCR. XlsxConverterWithOCR gains
  max_image_bytes (default 20 MiB, None disables); the declared
  uncompressed file_size is checked before reading and oversized images
  are skipped with a RuntimeWarning.

Both apply only on the _unreadable_image override path; the base
converter and plain _image_to_html subclasses keep upstream microsoft#2506
behaviour (XlsxConverter._max_image_bytes defaults to None). DECISIONS
and REVIEW updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants