fix: strip leading UTF-8 BOM before JSON content-shape detection

Merged
CH
19d ago
+30-1

Problem

detect_filetype() decodes a file's text head as plain "utf-8". If the source has a leading UTF-8 byte-order-mark, that BOM survives the decode as a literal U+FEFF character at the start of the text.

_TextFileDifferentiator._is_json requires the first non-whitespace character to be [ or {:

if text_head.lstrip()[0] not in "[{":
    return False

str.lstrip() doesn't strip U+FEFF (it's not whitespace), so this check fails immediately for BOM-prefixed content — _is_json returns False without even attempting to parse it. When this happens for a payload with no .json/.ndjson extension and libmagic guesses a generic text/plain MIME type (which it does for BOM-prefixed content — confirmed BOM changes libmagic's own guess from application/json/application/x-ndjson to text/plain), the file falls all the way through to FileType.TXT instead of FileType.JSON.

Repro

import io, json
from unstructured.file_utils.filetype import detect_filetype

json_bytes = b"\xef\xbb\xbf" + json.dumps([{"example": "data"}]).encode("utf-8")
detect_filetype(file=io.BytesIO(json_bytes), metadata_file_path="filename.pdf")
# -> FileType.TXT  (before this fix)
# -> FileType.JSON (after this fix, matching the non-BOM case)

Fix

Strip a leading BOM once in _FileTypeDetectionContext.text_head (the property consumed by _is_json/_is_csv/_is_eml), rather than changing the .encoding property itself — an existing test (it_knows_the_encoding_asserted_by_the_caller_and_normalizes_it) asserts .encoding returns the literal string "utf-8", so I kept that contract untouched and fixed the actual text consumption point instead.

Only one BOM can come from decoding, so at most one U+FEFF is removed (removeprefix, not lstrip); a second one is content and stays.

Rebased onto current main; no CHANGELOG.md / __version__.py edits, per the updated contributing guide.

Testing

  • test_it_identifies_json_with_a_leading_utf8_bom_and_no_extension and it_strips_only_the_leading_utf8_bom_and_not_a_later_literal_ufeff_char fail on main and pass with the fix.
  • test_unstructured/file_utils/ (566 passed, test_file_conversion.py skipped: needs pypandoc) and test_json.py / test_ndjson.py / test_text.py (263 passed).
  • ruff check / ruff format --check clean.

AI disclosure

This PR was written and tested by an AI coding agent working autonomously; I review each change after it is opened and take responsibility for it. (An earlier version of this section said I had traced the bug and run the tests myself before opening; that was not accurate.)