Skip to content

mem: load only 15 common langdetect profiles to reduce memory - #4297

Closed
KRRT7 wants to merge 3 commits into
Unstructured-IO:mainfrom
KRRT7:mem/langdetect-profile-subset
Closed

KRRT7 wants to merge 3 commits into
Unstructured-IO:mainfrom
KRRT7:mem/langdetect-profile-subset

Conversation

@KRRT7

@KRRT7 KRRT7 commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

Monkey-patch langdetect's init_factory() to load only 15 high-coverage language profiles instead of all 55. The full set creates large n-gram probability arrays (word_lang_prob_map) that persist for the lifetime of the process. The subset covers >95% of web content by language share.

What happens with unsupported languages?

langdetect always returns a result — it scores text against loaded profiles using n-gram frequency comparison and picks the best match. For a document in an excluded language (e.g., Thai, Polish), langdetect returns the closest loaded profile instead of the correct one. This is the same behavior as before for the downstream code path: detect_languages() maps the langdetect result to an ISO 639-3 code for element metadata. The language metadata is informational — it does not gate OCR model selection or partitioning logic.

In practice this means:

  • Included language (e.g., English, French, Japanese): correct detection, same as before
  • Excluded language (e.g., Thai): langdetect returns the closest loaded profile (e.g., id for Thai text) instead of th. No crash, no empty result — just a less precise language tag in metadata.

The 15 languages were chosen to cover the vast majority of real-world document processing: en, es, ar, fr, de, it, pt, ru, ja, ko, zh-cn, zh-tw, hi, bn, id. If a deployment needs accurate metadata for additional languages, the set can be extended by adding to LANGDETECT_LANGUAGES in lang.py.

Benchmark

Measured with memray (memray run + memray stats --json), 3 rounds × 5 texts (EN/DE/FR/JP + short ASCII) through the real detect_languages() code path, Python 3.12.

bench_langdetect

detect_languages() — langdetect profile subsetting benchmark
unstructured.partition.common.lang  |  3 rounds x 5 texts  |  Python 3.12.12

Configuration                     Peak MB      Saved      %
------------------------------------------------------------
All 55 profiles                    76.1MB      0.0MB   0.0%
15 common profiles                 31.7MB     44.4MB  58.3%

KRRT7 added 3 commits March 26, 2026 17:13
Monkey-patch langdetect's init_factory() to load 15 high-coverage
language profiles instead of all 55. Cuts n-gram probability map
memory by ~77% (58 MiB -> 14 MiB). Documents in excluded languages
still get a result from the closest loaded profile.
… global state

Replace the import-time `_ldf.init_factory = ...` override with a private
DetectorFactory instance that is lazily created and cached at module level.
This avoids mutating langdetect's global `_factory`, eliminating import-order
sensitivity, cross-library side effects, and fleet inconsistency in
multi-worker deployments.
@KRRT7
KRRT7 marked this pull request as draft March 27, 2026 18:33
@KRRT7

KRRT7 commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author

Closing per team discussion — the ~44MB memory save isn't worth the risk of silently misclassifying languages for international customers. langdetect always returns a result from loaded profiles, so there's no reliable way to detect or recover from excluded-language misses at runtime.

@KRRT7 KRRT7 closed this Mar 31, 2026
cragwolfe pushed a commit that referenced this pull request Oct 15, 2026
…4547)

## Summary

Partition language detection can now use
[`langdetect-rs`](https://github.com/SyntaxSpirits/langdetect-rs)
instead of `langdetect`. This is opt-in: it only happens when
`UNSTRUCTURED_USE_LANGDETECT_RS=true` is set before `unstructured` is
imported and `langdetect-rs` is installed. Without the variable,
`langdetect` is used as before, whether or not `langdetect-rs` is
installed. `langdetect-rs` is a Rust port of `langdetect` 1.0.9 with the
same API. It reproduces the random walk exactly: the same Mersenne
Twister, the same floating-point operations in the same order. With
`DetectorFactory.seed = 0`, as set in `detect_languages`, it returned
the same probabilities as `langdetect` on every input tested below.

Disclosure: I wrote `langdetect-rs`. It is Apache-2.0, has no Python
dependencies, and ships abi3 wheels for Linux (glibc and musl, x86_64
and aarch64), macOS and Windows.

Changes:
- `UNSTRUCTURED_USE_LANGDETECT_RS` (default off) in `ENVConfig`.
`partition/common/lang.py` reads it on first import. If it is set and
`langdetect-rs` is missing, a warning is logged and `langdetect` is
used; any other import error is raised. `langdetect` stays the required
dependency.
- `cleaners/translate.py` is unchanged.
- `langdetect-rs==0.1.0` is added to the `test` group. Default CI jobs
still run `langdetect`. `test_unit` on Python 3.12 gets one extra step,
`make test-langdetect-rs`, which asserts the Rust backend is selected
and reruns the language-metadata tests (lang, text, email, html, xml)
with the variable set.
- Tests: a parity test comparing languages and probabilities on three
example documents, subprocess tests for backend selection (unset,
enabled, enabled but missing), and a config parsing test.
- CHANGELOG entry and version bump to 0.27.27.

## Why

Timed on `example-docs`: best of 3 runs of the partitioner, macOS arm64,
CPython 3.12, default arguments.

| Document | Elements | `detect_language_per_element` | langdetect |
langdetect-rs |
|---|---|---|---|---|
| `fake-email.eml` | 4 | False | 5 ms | 2 ms |
| `example-10k-1p.html` | 23 | False | 9 ms | 4 ms |
| `README.md` | 10 | True | 20 ms | 2 ms |
| `language-docs/eng_spa_mult.html` | 5 | True | 16 ms | 2 ms |
| `language-docs/UDHR_first_article_all.txt` | 525 | False | 3.88 s |
2.37 s |
| `example-10k.html` | 314 | True | 2.16 s | 1.53 s |
| `book-war-and-peace-1225p.txt` | 11,724 | True | 95.6 s | 75.2 s |

`metadata.languages` was identical for every document in both modes. On
large documents without per-element detection, the gain is small because
detection is a small part of the total work.

There are also process-level savings:
- **First call:** the first `partition_text` call in a fresh process
takes 0.50–0.56 s with `langdetect` and 0.32–0.33 s with
`langdetect-rs`, because `langdetect` parses 55 JSON profiles on first
use.
- **Memory:** after loading the profiles, RSS grows by about 67 MB with
`langdetect` and about 19 MB with `langdetect-rs`. This is the memory
that #4297 tried to reduce by loading fewer profiles. That PR was closed
because it changed results; this change keeps all 55 profiles and the
same results.

How identity is checked in `langdetect-rs`: its test suite compares full
probability vectors against `langdetect` on CPython 3.9 to 3.15. Its CI
runs all 127,500 texts of the WiLI-2018 and papluca test sets on Linux,
macOS and Windows with no differences.

## Testing

```bash
uv sync --group test
uv run pytest test_unstructured/partition/common/test_lang.py test_unstructured/partition/utils/test_config.py
make test-langdetect-rs
```

To compare the two backends directly:

```python
import langdetect, langdetect_rs
for m in (langdetect, langdetect_rs):
    m.DetectorFactory.seed = 0
text = open("example-docs/language-docs/eng_spa_mult.txt").read()
assert [(x.lang, x.prob) for x in langdetect.detect_langs(text)] == \
       [(x.lang, x.prob) for x in langdetect_rs.detect_langs(text)]
```


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4547?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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