Repository navigation
Conversation
cragwolfe
approved these changes
Mar 25, 2026
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.
…ngdetect global state" This reverts commit 7318aba.
KRRT7
marked this pull request as draft
March 27, 2026 18:33
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. |
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. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
idfor Thai text) instead ofth. 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 toLANGDETECT_LANGUAGESinlang.py.Benchmark
Measured with memray (
memray run+memray stats --json), 3 rounds × 5 texts (EN/DE/FR/JP + short ASCII) through the realdetect_languages()code path, Python 3.12.