streamlit-gettext 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streamlit-gettext
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: A Streamlit extension for easy localization of your apps
5
5
  Author-email: insolor <insolor@gmail.com>
6
6
  Project-URL: repository, https://github.com/insolor/streamlit-gettext
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
19
20
  Classifier: Intended Audience :: Developers
20
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
22
  Requires-Python: >=3.11
@@ -35,10 +36,12 @@ Dynamic: license-file
35
36
 
36
37
  A Streamlit extension that makes it easy to localize your apps. It detects users' preferred languages from their browsers and displays the app in the appropriate language. It avoids a common issue when using gettext in Streamlit: if the browser language is detected only once at startup, all users may see the app in the same language.
37
38
 
38
- When a Streamlit app is deployed, reading the browser language only once at startup can cause every user to see the language detected for the first person who opened the app. `streamlit-gettext` avoids this by checking each user's browser language whenever it translates a message, so users sharing the same app can see it in different languages.
39
+ When browser detection is active, `streamlit-gettext` checks each user's browser language whenever it translates a message. This lets users sharing the same deployed app see different languages. Calling `set_preferred_languages()` overrides browser detection for that session; passing `None` or an empty iterable restores it.
39
40
 
40
41
  See a working app that uses `streamlit-gettext`: <https://github.com/dfint/package-build>
41
42
 
43
+ Get started with the [complete setup guide](https://insolor.github.io/streamlit-gettext/quick_start/).
44
+
42
45
  TODO:
43
46
 
44
47
  - [x] [example application](https://github.com/insolor/streamlit-gettext/blob/main/example)
@@ -46,7 +49,7 @@ TODO:
46
49
  - [x] tests
47
50
  - [x] documentation
48
51
  - [x] support for manually switching languages, with the browser's preferred language selected by default
49
- - [ ] examples of translations with context
52
+ - [x] examples of translations with context
50
53
  - [ ] ...
51
54
 
52
55
  Feedback and suggestions are welcome.
@@ -9,10 +9,12 @@
9
9
 
10
10
  A Streamlit extension that makes it easy to localize your apps. It detects users' preferred languages from their browsers and displays the app in the appropriate language. It avoids a common issue when using gettext in Streamlit: if the browser language is detected only once at startup, all users may see the app in the same language.
11
11
 
12
- When a Streamlit app is deployed, reading the browser language only once at startup can cause every user to see the language detected for the first person who opened the app. `streamlit-gettext` avoids this by checking each user's browser language whenever it translates a message, so users sharing the same app can see it in different languages.
12
+ When browser detection is active, `streamlit-gettext` checks each user's browser language whenever it translates a message. This lets users sharing the same deployed app see different languages. Calling `set_preferred_languages()` overrides browser detection for that session; passing `None` or an empty iterable restores it.
13
13
 
14
14
  See a working app that uses `streamlit-gettext`: <https://github.com/dfint/package-build>
15
15
 
16
+ Get started with the [complete setup guide](https://insolor.github.io/streamlit-gettext/quick_start/).
17
+
16
18
  TODO:
17
19
 
18
20
  - [x] [example application](https://github.com/insolor/streamlit-gettext/blob/main/example)
@@ -20,7 +22,7 @@ TODO:
20
22
  - [x] tests
21
23
  - [x] documentation
22
24
  - [x] support for manually switching languages, with the browser's preferred language selected by default
23
- - [ ] examples of translations with context
25
+ - [x] examples of translations with context
24
26
  - [ ] ...
25
27
 
26
28
  Feedback and suggestions are welcome.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "streamlit-gettext"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "A Streamlit extension for easy localization of your apps"
5
5
  authors = [{name = "insolor", email = "insolor@gmail.com"}]
6
6
  readme = "README.md"
@@ -16,6 +16,7 @@ classifiers = [
16
16
  "Programming Language :: Python :: 3.12",
17
17
  "Programming Language :: Python :: 3.13",
18
18
  "Programming Language :: Python :: 3.14",
19
+ "Programming Language :: Python :: 3.15",
19
20
  "Intended Audience :: Developers",
20
21
  "Topic :: Software Development :: Libraries :: Python Modules",
21
22
  ]
@@ -73,3 +74,9 @@ ignore = [
73
74
  "ANN201", # Ignore "Missing return type annotation for public function", tests don't return anything
74
75
  "D", # Don't warn about missing documentation in tests
75
76
  ]
77
+
78
+ "tests/*.py" = [
79
+ "S101", # Assertions are expected in tests
80
+ "ANN201", # Test functions do not return values
81
+ "INP001", # The standalone test project is not a Python package
82
+ ]
@@ -0,0 +1,161 @@
1
+ from __future__ import annotations
2
+
3
+ import gettext as _gettext_module
4
+ import re
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ import streamlit as st
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterable
12
+
13
+
14
+ class GettextWrapper:
15
+ """
16
+ A wrapper for the gettext module
17
+ """
18
+
19
+ locale_path: Path
20
+ domain: str
21
+
22
+ def __init__(self, locale_path: str | Path, domain: str = "messages") -> None:
23
+ self.locale_path = Path(locale_path)
24
+ self.domain = domain
25
+
26
+ def _get_session_state_key(self) -> str:
27
+ return f"streamlit_gettext.preferred_languages:{(str(self.locale_path.resolve()), self.domain)!r}"
28
+
29
+ def set_preferred_languages(self, languages: Iterable[str] | None) -> None:
30
+ """
31
+ Set preferred languages for this session. None or an empty iterable restores browser detection.
32
+ """
33
+ preferred_languages = list(languages) if languages is not None else []
34
+ session_state_key = self._get_session_state_key()
35
+ if preferred_languages:
36
+ st.session_state[session_state_key] = preferred_languages
37
+ else:
38
+ st.session_state.pop(session_state_key, None)
39
+
40
+ def get_preferred_languages(self) -> list[str]:
41
+ """
42
+ Get preferred languages from the browser if preferred languages are not set explicitly
43
+ """
44
+ preferred_languages = st.session_state.get(self._get_session_state_key())
45
+ if preferred_languages:
46
+ return list(preferred_languages)
47
+
48
+ return self.get_preferred_languages_from_browser()
49
+
50
+ @staticmethod
51
+ def _normalize_language(language: str) -> str:
52
+ """Normalize a language tag to gettext locale form."""
53
+ return language.replace("-", "_").casefold()
54
+
55
+ def get_preferred_languages_from_browser(self) -> list[str]:
56
+ """
57
+ Get concrete browser languages by descending quality, preserving order for ties.
58
+ """
59
+ accept_language = st.context.headers.get("Accept-Language") or ""
60
+ weighted_languages: list[tuple[str, float]] = []
61
+ for entry in accept_language.split(","):
62
+ parsed = self._parse_accept_language_entry(entry)
63
+ if parsed is not None:
64
+ weighted_languages.append(parsed)
65
+
66
+ weighted_languages.sort(key=lambda item: item[1], reverse=True)
67
+ languages: list[str] = []
68
+ seen: set[str] = set()
69
+ for language, _weight in weighted_languages:
70
+ normalized = self._normalize_language(language)
71
+ if normalized not in seen:
72
+ seen.add(normalized)
73
+ languages.append(language.replace("-", "_"))
74
+ return languages
75
+
76
+ @staticmethod
77
+ def _parse_accept_language_entry(entry: str) -> tuple[str, float] | None:
78
+ """Return a concrete language and weight, or None for unusable entries."""
79
+ match = re.fullmatch(
80
+ r"[ \t]*([a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*|\*)[ \t]*"
81
+ r"(?:;[ \t]*[qQ]=(0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)[ \t]*)?",
82
+ entry,
83
+ )
84
+ if match is None:
85
+ return None
86
+ language, quality = match.groups()
87
+ weight = float(quality) if quality is not None else 1.0
88
+ # A wildcard does not identify a concrete gettext catalog.
89
+ if language == "*" or weight == 0:
90
+ return None
91
+ return language, weight
92
+
93
+ def translation(self, languages: Iterable[str] | None = None) -> _gettext_module.NullTranslations:
94
+ if languages is not None:
95
+ languages = [language.replace("-", "_") for language in languages]
96
+ return _gettext_module.translation(
97
+ domain=self.domain,
98
+ localedir=self.locale_path,
99
+ languages=languages,
100
+ fallback=True,
101
+ )
102
+
103
+ def gettext(self, message: str) -> str:
104
+ """
105
+ Get the translation of a message
106
+ """
107
+ translation = self.translation(self.get_preferred_languages())
108
+ return translation.gettext(message)
109
+
110
+ def ngettext(self, singular: str, plural: str, n: int) -> str:
111
+ """
112
+ Get the plural form of a message
113
+ """
114
+ translation = self.translation(self.get_preferred_languages())
115
+ return translation.ngettext(singular, plural, n)
116
+
117
+ def pgettext(self, context: str, message: str) -> str:
118
+ """
119
+ Get the translation of a message with a context
120
+ """
121
+ translation = self.translation(self.get_preferred_languages())
122
+ return translation.pgettext(context, message)
123
+
124
+ def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:
125
+ """
126
+ Get the plural form of a message with a context
127
+ """
128
+ translation = self.translation(self.get_preferred_languages())
129
+ return translation.npgettext(context, singular, plural, n)
130
+
131
+ def get_available_languages(self) -> list[str]:
132
+ """
133
+ Get languages available in the locale directory
134
+ """
135
+ try:
136
+ locale_directories = list(self.locale_path.iterdir())
137
+ except FileNotFoundError:
138
+ locale_directories = []
139
+
140
+ language_codes = {
141
+ path.name
142
+ for path in locale_directories
143
+ if path.is_dir() and (path / "LC_MESSAGES" / f"{self.domain}.mo").is_file()
144
+ }
145
+ language_codes.add("en")
146
+
147
+ preferred_languages = [
148
+ self._normalize_language(language) for language in self.get_preferred_languages_from_browser()
149
+ ]
150
+
151
+ def sort_key(language: str) -> tuple[int, int, str]:
152
+ """Prefer exact locale matches, then compatible language fallbacks."""
153
+ normalized = self._normalize_language(language)
154
+ for index, preferred in enumerate(preferred_languages):
155
+ if normalized == preferred:
156
+ return index, 0, language.casefold()
157
+ if normalized == preferred.split("_")[0] or preferred == normalized.split("_")[0]:
158
+ return index, 1, language.casefold()
159
+ return len(preferred_languages), 0, language.casefold()
160
+
161
+ return sorted(language_codes, key=sort_key)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streamlit-gettext
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: A Streamlit extension for easy localization of your apps
5
5
  Author-email: insolor <insolor@gmail.com>
6
6
  Project-URL: repository, https://github.com/insolor/streamlit-gettext
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
19
20
  Classifier: Intended Audience :: Developers
20
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
22
  Requires-Python: >=3.11
@@ -35,10 +36,12 @@ Dynamic: license-file
35
36
 
36
37
  A Streamlit extension that makes it easy to localize your apps. It detects users' preferred languages from their browsers and displays the app in the appropriate language. It avoids a common issue when using gettext in Streamlit: if the browser language is detected only once at startup, all users may see the app in the same language.
37
38
 
38
- When a Streamlit app is deployed, reading the browser language only once at startup can cause every user to see the language detected for the first person who opened the app. `streamlit-gettext` avoids this by checking each user's browser language whenever it translates a message, so users sharing the same app can see it in different languages.
39
+ When browser detection is active, `streamlit-gettext` checks each user's browser language whenever it translates a message. This lets users sharing the same deployed app see different languages. Calling `set_preferred_languages()` overrides browser detection for that session; passing `None` or an empty iterable restores it.
39
40
 
40
41
  See a working app that uses `streamlit-gettext`: <https://github.com/dfint/package-build>
41
42
 
43
+ Get started with the [complete setup guide](https://insolor.github.io/streamlit-gettext/quick_start/).
44
+
42
45
  TODO:
43
46
 
44
47
  - [x] [example application](https://github.com/insolor/streamlit-gettext/blob/main/example)
@@ -46,7 +49,7 @@ TODO:
46
49
  - [x] tests
47
50
  - [x] documentation
48
51
  - [x] support for manually switching languages, with the browser's preferred language selected by default
49
- - [ ] examples of translations with context
52
+ - [x] examples of translations with context
50
53
  - [ ] ...
51
54
 
52
55
  Feedback and suggestions are welcome.
@@ -1,106 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import gettext as _gettext_module
4
- import re
5
- from pathlib import Path
6
- from typing import TYPE_CHECKING
7
-
8
- import streamlit as st
9
-
10
- if TYPE_CHECKING:
11
- from collections.abc import Iterable
12
-
13
-
14
- class GettextWrapper:
15
- """
16
- A wrapper for the gettext module
17
- """
18
-
19
- locale_path: Path
20
- domain: str
21
-
22
- preferred_languages: list[str] | None = None
23
-
24
- def __init__(self, locale_path: str | Path, domain: str = "messages") -> None:
25
- self.locale_path = Path(locale_path)
26
- self.domain = domain
27
-
28
- def set_preferred_languages(self, languages: Iterable[str] | None) -> None:
29
- """
30
- Manually set preferred languages. If not None then it overrides detected languages.
31
- """
32
- self.preferred_languages = list(languages) if languages else None
33
-
34
- def get_preferred_languages(self) -> list[str]:
35
- """
36
- Get preferred languages from the browser if preferred languages are not set explicitly
37
- """
38
- if self.preferred_languages is not None:
39
- return self.preferred_languages
40
-
41
- return self.get_preferred_languages_from_browser()
42
-
43
- def get_preferred_languages_from_browser(self) -> list[str]:
44
- """
45
- Get preferred languages from the browser
46
- """
47
- accept_language = st.context.headers.get("Accept-Language") or ""
48
- return re.findall(r"([a-zA-Z-]{2,})", accept_language) or []
49
-
50
- def translation(self, languages: Iterable[str] | None = None) -> _gettext_module.NullTranslations:
51
- return _gettext_module.translation(
52
- domain=self.domain,
53
- localedir=self.locale_path,
54
- languages=languages,
55
- fallback=True,
56
- )
57
-
58
- def gettext(self, message: str) -> str:
59
- """
60
- Get the translation of a message
61
- """
62
- translation = self.translation(self.get_preferred_languages())
63
- return translation.gettext(message)
64
-
65
- def ngettext(self, singular: str, plural: str, n: int) -> str:
66
- """
67
- Get the plural form of a message
68
- """
69
- translation = self.translation(self.get_preferred_languages())
70
- return translation.ngettext(singular, plural, n)
71
-
72
- def pgettext(self, context: str, message: str) -> str:
73
- """
74
- Get the translation of a message with a context
75
- """
76
- translation = self.translation(self.get_preferred_languages())
77
- return translation.pgettext(context, message)
78
-
79
- def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:
80
- """
81
- Get the plural form of a message with a context
82
- """
83
- translation = self.translation(self.get_preferred_languages())
84
- return translation.npgettext(context, singular, plural, n)
85
-
86
- def get_available_languages(self) -> list[str]:
87
- """
88
- Get languages available in the locale directory
89
- """
90
- language_codes = [
91
- path.name
92
- for path in self.locale_path.iterdir()
93
- if path.is_dir() and (path / "LC_MESSAGES" / "messages.mo").is_file()
94
- ]
95
- language_codes.insert(0, "en")
96
-
97
- preferred_languages = self.get_preferred_languages_from_browser()
98
- index_map = {language: i for i, language in enumerate(preferred_languages)}
99
-
100
- def sort_key(language: str) -> tuple[int, str]:
101
- """Prioritize browser-preferred languages, then sort alphabetically."""
102
- return index_map.get(language, len(index_map)), language.casefold()
103
-
104
- language_codes.sort(key=sort_key)
105
-
106
- return language_codes