Skip to main content

Translation Finder

Website Translation status CII Best Practices PyPI package Documentation

Translation file discovery library used by Weblate to identify translation files and their configuration in source repositories.

Discovery can operate on file listings alone or inspect the filesystem when more accurate detection is needed, such as determining file encoding or distinguishing formats with similar syntax.

Weblate

Maintained by Weblate — a privacy-respecting localization platform built on open-source foundations.

Usage

It can be used from Python:

>>> from translation_finder import discover
>>> from pprint import pprint
>>> results = discover("translation_finder/test_data/")
>>> len(results)
40
>>> pprint(results[0].match)
{'file_format': 'aresource',
 'filemask': 'app/src/res/main/values-*/strings.xml',
 'name': 'android',
 'template': 'app/src/res/main/values/strings.xml'}
>>> pprint(results[1].match)
{'file_format': 'po',
 'filemask': 'locales/*.po',
 'name': 'translation',
 'new_base': 'locales/messages.pot'}

Additional information about discovery can be obtained from meta attribute:

>>> pprint(results[0].meta)
{'discovery': 'TransifexDiscovery', 'origin': 'Transifex', 'priority': 500}
>>> pprint(results[22].meta)
{'discovery': 'GettextDiscovery', 'origin': None, 'priority': 1000}

Or command line:

$ weblate-discovery translation_finder/test_data/
== Match 1 (Transifex) ==
file_format    : aresource
filemask       : app/src/res/main/values-*/strings.xml
name           : android
template       : app/src/res/main/values/strings.xml
...

== Match 7 ==
file_format    : po
filemask       : locales/*.po
new_base       : locales/messages.pot

Non-printable characters in command-line results are displayed as visible escapes (for example, \n and \x1b). The Python API returns the original values unchanged.

Discovery result fields

Each result describes a suggested configuration. Paths are relative to the discovery root, and filemask identifies the translation files belonging to that configuration. File masks, including discovery hints, use * as their only wildcard. Question marks and brackets match literal characters, so paths such as src/[locale]/*.json preserve their bracketed directory names. Custom discovery selectors needing multiple alternatives should provide a tuple of masks, for example ("resources.resx", "resources.resw").

Two optional fields describe files with different roles:

template

The source file containing string definitions for a monolingual configuration. This maps to Weblate’s Monolingual base language file. Translations are interpreted using the string definitions in this file.

new_base

The file used to create translation files for additional languages. This maps to Weblate’s Template for new translations. It can be an untranslated source file, a Gettext POT file, or an existing bilingual translation whose translations will be cleared when creating the new language file. Setting new_base alone does not make a configuration monolingual.

For example, the Gettext result in the usage example has only new_base: locales/messages.pot supplies the messages for new languages, while existing PO files contain their own source strings. Similarly, Qt’s translation repository can produce this bilingual configuration, using an existing Arabic translation to create new languages:

{
    "file_format": "ts",
    "filemask": "translations/designer_*.ts",
    "new_base": "translations/designer_ar.ts",
}

Both fields can refer to the same file. For example, the PHP and Laravel fixtures use their English source files both to define strings and to create new language files:

>>> pprint(sorted(
...     (r["file_format"], r["template"], r["new_base"])
...     for r in results if r["file_format"] in {"php", "laravel"}
... ))
[('laravel', 'laravel/en.php', 'laravel/en.php'),
 ('php', 'php/en.php', 'php/en.php')]

Either field can appear independently, both can appear, or both can be absent. An absent field means discovery did not provide that setting; it does not necessarily mean the format does not support it. Discovery backends may also read settings from repository configuration, such as Transifex configuration.

Filename-based discovery first looks for an exact name derived from the filemask for new_base. Otherwise, it prefers a discovered template when that file is eligible for creating translations. Formats using the same file extension for sources and translations then prefer a translation from the same discovered filemask. If those checks do not identify a file, discovery retains a deterministic fallback from the nearest directory containing an eligible file. These are heuristics: review suggestions when a directory contains unrelated catalogs or several possible templates.

Discovery limits

The threat model describes which inputs discovery treats as untrusted and which resource limits are the caller’s responsibility.

The high-level discover() API accepts a hint and a source language of at most 400 characters each. These limits bound the cost of compiling wildcard patterns and constructing candidate template paths. Longer values raise ValueError before discovery scans the repository. The CLI applies the same limits to --hint and --source-language and exits with status 2 for an overlong value. Both limits apply even with unlimited discovery budgets.

The CLI accepts nonnegative integer limits. Each value applies to the operation described below, including when you set it to zero.

  • --max-candidates: 4096 generated candidates across all backends. Transifex discovery also processes at most this many resource-section occurrences across its configuration files, including empty, repeated, and non-discoverable sections. [main] and [DEFAULT] do not count as resources. Section processing has separate accounting, so useful resources are not charged twice. Exceeding either allowance reports candidates truncation.

  • --max-results: 4096 returned matches.

  • --max-new-base-checks: 65536 probes in the shared new-base resolver. Gettext can also check up to five fallback filenames per candidate, even when this budget is zero.

  • --max-wildcard-checks: 1000000 language-code probes in the generic wildcard generator across the run. The Apple .strings and RESX backends also check locales in files selected under Finder’s match budget. Those locale checks use a separate code path and can still run at zero.

  • --max-masks-per-path: 32 alternative masks during one pass of the generic generator over the language-like components of a path. Masks derived from a hint, an eager filename, or a format-specific rule can still be returned at zero.

  • --sniff-max-bytes: 67108864 bytes (64 MiB) sampled across the run.

  • --sniff-max-files: 512 content-sniffing file attempts across the run.

  • --max-files: 100000 indexed files.

  • --max-dirs: 20000 indexed directories.

  • --max-depth: 64 directory levels below the root.

  • --max-entries: 150000 directory entries examined, including excluded entries and symlinks.

  • --max-path-length: 4096 characters in an indexed relative path.

  • --max-path-bytes: 67108864 bytes (64 MiB) across all collected file and directory paths. Each entry counts once, using its full path relative to the discovery root, encoded as UTF-8 with surrogatepass for undecodable names. For example, collecting po and po/fr.po uses 10 bytes (2 + 8). Collection stops before adding a path that would exceed the budget and reports path-bytes truncation. Process memory can exceed the budget because Python objects and lookup indexes also use memory.

  • --max-match-checks: 65536 regular expression and wildcard candidate evaluations.

For example, weblate-discover --max-results 10000 translations/ raises only the result limit. weblate-discover --unlimited translations/ disables all configurable discovery limits. Use it without individual limit options. Internal parser safeguards and per-result format and encoding sampling limits remain active.

Transifex configuration discovery follows the Transifex client’s INI syntax, including comments, quoted values, backslash continuations, repeated-section merging, dotted parent sections, and %(name)s value references. It does not inherit Python ConfigParser behavior such as indentation-only continuations or implicit [DEFAULT] option inheritance. Malformed headers and their following options are skipped until the next valid header, preserving preceding resource sections. Malformed assignments invalidate only their own section.

Discovery attempts up to 16 Transifex configuration files per run, samples up to 1 MiB per file, and admits up to 1 MiB in total for parsing. It skips a file if its sample is incomplete or its contents exceed the remaining parsing allowance. A later, smaller file can still fit. A physical line longer than 4096 UTF-8 bytes (excluding the line ending) skips the entire file. A resolved discovery value longer than 4096 UTF-8 bytes skips its section. These fixed safeguards apply even with --unlimited and can omit resources without setting a truncation flag.

Across all Transifex configuration files, each run also has 8,388,608 work units for resolving options. Each scan costs 64 units plus the character count of the current value. Substitution also charges for the replacement text and the expanded output. If the next operation exceeds the allowance, discovery keeps completed resources, stops processing Transifex configuration, and reports transifex-interpolation. This safeguard applies even with --unlimited.

The CLI prints collected matches to stdout, including partial results. Exit status 0 means discovery finished with no reported limit reason. Content sampling is best effort, so exhausting a sniff budget can affect detection without setting a truncation flag. When discovery reports truncation, the CLI prints one warning listing the reasons to stderr and exits with status 3. Invalid arguments produce exit status 2.

Python callers can import DiscoveryLimits from translation_finder.api and pass it as the keyword-only limits argument to discover(). Defaults match the CLI. Setting a field to None disables that limit. DiscoveryLimits.unlimited() disables all configurable discovery limits. Fixed safeguards such as the Transifex interpolation allowance still apply. Negative values raise ValueError. High-level discovery reports truncation through results.truncated and results.limit_reasons without emitting a Python warning for truncation. Format detection can issue its own warnings, for example when a JSON template cannot be parsed. max_results=0 returns before scanning the tree and conservatively reports truncation. Direct Finder use has the same scan and matching defaults and exposes limit_reasons; pass None for a limit to disable it. Direct backend discover() calls also use the default run-wide sniff limits.

Finder mask matching

Finder.filter_masks() accepts basename patterns such as *.po, using only * as a wildcard, and matches them against lowercased filenames in every directory. Question marks and brackets match literal characters. To select multiple alternatives, pass a tuple such as ("resources.resx", "resources.resw"). Patterns containing / raise ValueError when the generator is iterated, before any matches are yielded.

To restrict directories, pass a separate directory regular expression as dirglob, for example finder.filter_masks("*.po", dirglob="po"). Finder.filter_files() accepts regular expressions for both the basename and the optional directory filter. Both expressions are fullmatched against lowercased names. Supply application-controlled regular expressions that are safe to evaluate on repository-controlled names. The match budget counts evaluations and cannot interrupt a single expensive expression. For a user-supplied discovery hint, use the high-level discover(..., hint=...) API.

Finder.mask_matches() matches relative paths, for example po/*.po. Its * wildcard can span directory separators; ? and brackets are literal characters. It preserves case according to platform fnmatch rules, rather than lowercasing paths as the filtering methods do.

Custom discovery backends

Custom BaseDiscovery implementations return DiscoveryCandidate objects from get_masks(). Each candidate associates the result with the paths which actually generated it, allowing content detection to inspect the group without expanding its wildcard mask again.

Backend filter_files() and candidate paths use read-only path references. These can be compact file records or PurePath objects supplied through mock listings. Use their name, parent, parts, and as_posix() interfaces; do not require concrete Path instances or access filesystem methods on the references. Read file content through self.finder.open(path). If additional path operations are necessary, explicitly construct Path(path.as_posix()).

The public Finder.mask_matches(), filter_masks(), filter_files(), and get_lc_candidates() methods continue to return relative PurePath objects, including the original path objects for mock listings. Filesystem paths are materialized on demand, so callers should not depend on object identity across calls. Finder’s lookup indexes are private implementation details.

Direct calls to a backend’s get_masks() use Finder’s configured limits and any safeguards specific to that backend. The generic language-mask generator also applies its per-path allowance. Use the high-level discover() to share budgets across backends and receive a list-compatible DiscoveryResults with run-wide truncated and limit_reasons attributes.

from translation_finder.discovery.base import BaseDiscovery
from translation_finder.discovery.result import DiscoveryCandidate


class CustomDiscovery(BaseDiscovery):
    def get_masks(self, *, eager=False, hint=None):
        for path in self.filter_files():
            yield DiscoveryCandidate({"filemask": "locale/*.json"}, [path])

Metadata

Release files for translation-finder 3.11.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for translation-finder 3.11.0
File Size Uploaded Provenance Actions
translation_finder-3.11.0.tar.gz 167.1 kB With provenance Details for translation_finder-3.11.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for translation-finder 3.11.0
File Interpreter ABI Platform Actions
translation_finder-3.11.0-py3-none-any.whl Python 3 none any Details for translation_finder-3.11.0-py3-none-any.whl

Total release size: 335.4 kB

Release files / translation_finder-3.11.0.tar.gz

Download URL translation_finder-3.11.0.tar.gz
Size 167.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e495209af111d027759563bb7e24374f4aa581becdd0cc591b5aa0640c2521ae
BLAKE2b-256 checksum
How to use checksums
25e55e13706947cbf824dbba844f3f766fb3a908a333678c8a22b882a17f43f8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / translation_finder-3.11.0-py3-none-any.whl

Download URL translation_finder-3.11.0-py3-none-any.whl
Size 168.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fed8367d0b4c3bc31fbf87e376bb47f8bb4261d5c9961c1edaf24e415b06e024
BLAKE2b-256 checksum
How to use checksums
ba9cab7e4687c4880938590f4c61f5d4ee7fe018076c28d0f05a99691763db5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for translation-finder 3.11.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for translation_finder-3.11.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.11.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page