Skip to content

fix: improve CSV encoding detection for non-UTF-8 files - #293

Open
li5435945-ship-it wants to merge 2 commits into
danny-avila:mainfrom
li5435945-ship-it:fix/csv-encoding-detection
Open

fix: improve CSV encoding detection for non-UTF-8 files#293
li5435945-ship-it wants to merge 2 commits into
danny-avila:mainfrom
li5435945-ship-it:fix/csv-encoding-detection

Conversation

@li5435945-ship-it

Copy link
Copy Markdown

Problem

CSVLoader fails with UnicodeDecodeError for non-UTF-8 CSV files (e.g., Shift-JIS / CP932 from Japanese Excel) when the file has a mostly-ASCII header. The chardet detection only inspects the first 4096 bytes, which contains too few non-ASCII characters to detect Shift-JIS reliably.

Fixes #291

Root Cause

detect_file_encoding() reads only 4096 bytes. For CSV files with English column headers and Japanese data rows, chardet returns "utf-8" because the sample is mostly ASCII.

Solution

Three-layer approach:

  1. Larger detection sample: Increase chardet sample from 4KB to 64KB for better accuracy
  2. Encoding validation: After chardet detects encoding, verify it can actually decode the sample
  3. Fallback mechanism: If detected encoding fails, try common non-UTF-8 encodings (cp932, shift_jis, gb18030, latin-1)

Changes

  • app/utils/document_loader.py: 81 insertions, 4 deletions

Testing

Tested with a Shift-JIS CSV file (English headers, Japanese data) that was previously misdetected as UTF-8.

SL added 2 commits June 2, 2026 14:25
Fix UnicodeDecodeError when chardet misdetects Shift-JIS/CP932 files
as UTF-8 due to ASCII-heavy headers.

Changes:
- Increase chardet sample size from 4KB to 64KB for better accuracy
- Add encoding validation: verify detected encoding can decode the sample
- Add fallback mechanism: try common encodings (cp932, shift_jis, gb18030, latin-1)
- Add _retry_csv_with_fallback_encodings() for runtime retry on UnicodeDecodeError

Fixes danny-avila#291
Add comprehensive tests for detect_file_encoding() to verify:
- UTF-8 and UTF-8 BOM detection
- UTF-16 LE detection
- Shift-JIS detection with ASCII headers (issue danny-avila#291 scenario)
- GB18030 detection with ASCII headers
- Latin-1 fallback detection
- CSVLoader integration test with Shift-JIS file

These tests ensure the encoding detection fix works correctly for
non-UTF-8 CSV files with ASCII-heavy headers.
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.

CSV upload fails with UnicodeDecodeError when chardet misdetects Shift-JIS file as utf-8

1 participant