Skip to content

Mitigate UnicodeDecodeError due to wrong ASCII charset guess for long files - #2360

Merged
Adam Fourney (afourney) merged 6 commits into
microsoft:mainfrom
fcatalan92:fix_json_conversion
Aug 31, 2026
Merged

Adam Fourney (afourney) merged 6 commits into
microsoft:mainfrom
fcatalan92:fix_json_conversion

Conversation

@fcatalan92

Copy link
Copy Markdown
Contributor

This PR mitigate UnicodeDecodeError issues encountered when a non-ASCII character appears late in the file, namely after the window used to guess the charset.

The changes are the following:

  • prevent IpynbConverter.accepts() from failing when a file cannot be decoded with the guessed charset. I implemented the same solution used in outlook_msg_converter
  • increase the charset-detection sample from 4 KB to 64 KB, making the issue unlikely to occur
  • add guidance to conversion errors caused by an incorrectly guessed charset

Another possibility is to force a retry if a UnicodeDecodeError is encountered in the converter using the same approach used when the detected charset is None. But I preferred to not change the current behavior of the converters.

if stream_info.charset:
text_content = file_stream.read().decode(stream_info.charset)
else:
text_content = str(from_bytes(file_stream.read()).best())

The PR fixes #2359. It could also address #1505, #1894 and #1949 (for which there are no working reproducers).

Adam Fourney (@afourney) I hope you could have a look at this human-generated contribution ;-)

@fcatalan92

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@afourney
Adam Fourney (afourney) merged commit 4243c26 into microsoft:main Aug 31, 2026
3 checks passed
@afourney

Copy link
Copy Markdown
Member

Thanks! Merged!

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.

Bug: UnicodeDecodeError in JSON conversion when non-ASCII character appears after 4 KB

2 participants