Skip to content

Fix UnicodeDecodeError when guessed charset doesn't hold for the whole file - #2346

Open
Oscar A Garcia (alexandregfonseca) wants to merge 2 commits into
microsoft:mainfrom
alexandregfonseca:fix/plaintext-charset-fallback
Open

Fix UnicodeDecodeError when guessed charset doesn't hold for the whole file#2346
Oscar A Garcia (alexandregfonseca) wants to merge 2 commits into
microsoft:mainfrom
alexandregfonseca:fix/plaintext-charset-fallback

Conversation

@alexandregfonseca

Copy link
Copy Markdown

Summary

  • PlainTextConverter guesses the file's charset from only the first 4096 bytes of the stream (_markitdown.py). If that prefix happens to be pure ASCII but a multi-byte UTF-8 character appears later in the file, the charset is mis-detected as ascii, and the subsequent full-content .decode("ascii") raises UnicodeDecodeError, causing conversion to fail entirely.
  • This is easy to hit in practice: running markitdown README.md on this very repo's README fails, because the README is ASCII for its first 4096 bytes and contains an em dash () shortly after.
  • Fix: when decoding with the guessed charset fails, fall back to detecting the charset from the full file content instead of just the first 4096 bytes.

Test plan

  • Added a regression test (test_plain_text_charset_guessed_from_prefix) reproducing the exact scenario: 4096 bytes of ASCII followed by a UTF-8 multi-byte character.
  • pytest packages/markitdown/tests/test_module_misc.py passes (one unrelated pre-existing failure in test_speech_transcription due to ffprobe not being installed in my environment).
  • Manually verified markitdown README.md now succeeds instead of raising FileConversionException.

PlainTextConverter guesses the charset from only the first 4096 bytes of
the stream. For files that are pure ASCII in that window but contain
multi-byte UTF-8 characters later on (e.g. an em dash), the charset is
guessed as "ascii" and the subsequent full-content decode raises
UnicodeDecodeError, causing conversion to fail entirely.

Fall back to detecting the charset from the full content when decoding
with the guessed charset fails.
Covers the case where the guessed charset (based on the first 4096
bytes) is ASCII but the file contains multi-byte UTF-8 characters later
on.
@alexandregfonseca

Oscar A Garcia (alexandregfonseca) commented Aug 27, 2026 via email

Copy link
Copy Markdown
Author

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.

1 participant