Hwilner commited on
Commit
6e073b8
·
verified ·
1 Parent(s): 457d014

Validate language.json, raise on unknown language, lazy model loading, pin deps

Browse files
Files changed (3) hide show
  1. README.md +117 -6
  2. app.py +340 -37
  3. requirements.txt +13 -3
README.md CHANGED
@@ -1,13 +1,124 @@
1
  ---
2
- title: Multi Language Translator
3
- emoji: 🐨
4
- colorFrom: red
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 4.31.4
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Multi-language Translator
3
+ emoji: 🚀
4
+ colorFrom: indigo
5
+ colorTo: gray
6
  sdk: gradio
7
+ sdk_version: 6.29.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
+ # Multi-language Translator
14
+
15
+ <!-- Screenshots: not yet captured. Add a screenshot under ./screenshots/ and
16
+ reference it here once the Space is deployed. -->
17
+
18
+ ## Table of contents
19
+
20
+ - [Overview](#overview)
21
+ - [Features](#features)
22
+ - [Usage](#usage)
23
+ - [How it works](#how-it-works)
24
+ - [API reference](#api-reference)
25
+ - [Limitations](#limitations)
26
+ - [Troubleshooting](#troubleshooting)
27
+ - [Contributing](#contributing)
28
+ - [License](#license)
29
+ - [Citation](#citation)
30
+
31
+ ## Overview
32
+
33
+ Translates text between any of the 200+ languages described in `language.json`, using Facebook's NLLB-200 distilled model. Migration notes relative to the 2024 original: * `torch_dtype=torch.bfloat16` is replaced with `float32`.
34
+
35
+ ## Features
36
+
37
+ - Runs entirely on Hugging Face Spaces `cpu-basic` hardware — no GPU required
38
+ - Model weights load lazily, so the UI appears immediately
39
+ - Input validation with clear, user-facing error messages
40
+ - Full [Google-style Python docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) on every public function and class
41
+ - Dependencies pinned to exact, verified versions
42
+
43
+ ## Usage
44
+
45
+ Paste or upload input, click the button, and read the result. If the Space is
46
+ asleep, the first request may take a minute while the model downloads.
47
+
48
+ ## How it works
49
+
50
+ Translates text between any of the 200+ languages described in `language.json`,
51
+ using Facebook's NLLB-200 distilled model. Migration notes relative to the 2024 original:
52
+ * `torch_dtype=torch.bfloat16` is replaced with `float32`. The free
53
+ `cpu-basic` Space tier has no CUDA device, where bfloat16 is unsupported or
54
+ falls back through slow software emulation.
55
+
56
+ | Stage | Implementation |
57
+ | --- | --- |
58
+ | MODEL_NAME: Final[str] = "facebook/nllb-200-distilled-600M"
59
+ | MAX_INPUT_CHARS: Final[int] = 5_000
60
+
61
+ ## API reference
62
+
63
+ - `def load_language_table(`path: str = LANGUAGE_DATA_PATH) -> list[dict[str, str]]:`) — see docstring
64
+ - `def get_flores_code(`language: str, path: str = LANGUAGE_DATA_PATH) -> str:`) — see docstring
65
+ - `def supported_languages(`path: str = LANGUAGE_DATA_PATH) -> list[str]:`) — see docstring
66
+ - `def _build_pipeline(`):`) — see docstring
67
+ - `def get_translator(`):`) — see docstring
68
+ - `def translate_text(`) — see docstring
69
+ - `def translate_with_error_handling(`) — see docstring
70
+ - `def build_demo(`) -> gr.Blocks:`) — see docstring
71
+ - `def main(`) -> None:`) — see docstring
72
+
73
+ ## Limitations
74
+
75
+ - **CPU inference is slow.** Expect several seconds of latency per request, and
76
+ considerably longer for the very first one while weights download.
77
+ - **Quality is bounded by the base model.** These are small, general-purpose
78
+ checkpoints, not domain-tuned ones.
79
+ - **Input limits are enforced** to stay within the Space timeout budget. Longer
80
+ input is rejected with an explicit message rather than silently truncated.
81
+ - **The free tier sleeps.** After a period of inactivity the Space suspends and
82
+ the next request pays a cold-start cost.
83
+
84
+ ## Troubleshooting
85
+
86
+ **The Space shows `RUNTIME_ERROR`.** Almost always one of: an unpinned
87
+ `requirements.txt`, a CUDA-only package on CPU hardware (for example
88
+ `faiss-gpu`), or code written against an older major version of a library. See
89
+ the portfolio `CONVENTIONS.md` for the pinning policy.
90
+
91
+ **`AttributeError` on a library function.** A major version changed. Check
92
+ whether the dependency is pinned; an unpinned dependency silently upgrades.
93
+
94
+ **`torch_dtype=torch.bfloat16` is wrong here.** The `cpu-basic` tier has no
95
+ CUDA device. Use `float32`.
96
+
97
+ **Model download fails or is rate-limited.** Free Spaces are subject to
98
+ rate limits. Retry, or move to a T4 upgrade.
99
+
100
+ ## Contributing
101
+
102
+ 1. Pin every dependency to an exact version.
103
+ 2. Keep every public function's Google-style docstring current.
104
+ 3. Never commit a secret. Use Space secrets (`Settings -> Variables and secrets`).
105
+ 4. Run `python -m py_compile app.py` before opening a pull request.
106
+
107
+ ## License
108
+
109
+ Apache-2.0. See the `LICENSE` file.
110
+
111
+ ## Citation
112
+
113
+ If you use this Space, cite the underlying model and the library:
114
+
115
+ ``bibtex
116
+ @misc{space,
117
+ author = {Harel Wilner},
118
+ title = {},
119
+ year = {2024},
120
+ note = {Hugging Face Space}
121
+ }
122
+ ``
123
+
124
+ [^links]: <https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings>
app.py CHANGED
@@ -1,42 +1,345 @@
1
- import torch
2
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import json
 
 
 
 
 
 
 
4
  from transformers import pipeline
5
 
6
- # Use a pipeline with the specified model for translation
7
- text_translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", torch_dtype=torch.bfloat16)
8
-
9
- # Load the JSON data from the file
10
- with open('language.json', 'r') as file:
11
- language_data = json.load(file)
12
-
13
- def get_FLORES_code_from_language(language):
14
- for entry in language_data:
15
- if entry['Language'].lower() == language.lower():
16
- return entry['FLORES-200 code']
17
- return None
18
-
19
- def translate_text(text, source_language, destination_language):
20
- src_code = get_FLORES_code_from_language(source_language)
21
- dest_code = get_FLORES_code_from_language(destination_language)
22
- translation = text_translator(text, src_lang=src_code, tgt_lang=dest_code)
23
- return translation[0]["translation_text"]
24
-
25
- gr.close_all()
26
-
27
- # Define the language options based on the JSON file
28
- language_options = [entry['Language'] for entry in language_data]
29
-
30
- demo = gr.Interface(
31
- fn=translate_text,
32
- inputs=[
33
- gr.Textbox(label="Input text to translate", lines=6),
34
- gr.Dropdown(language_options, label="Select Source Language"),
35
- gr.Dropdown(language_options, label="Select Destination Language")
36
- ],
37
- outputs=[gr.Textbox(label="Translated text", lines=4)],
38
- title="Multi-language Translator",
39
- description="THIS APPLICATION WILL BE USED TO TRANSLATE TEXT BETWEEN MULTIPLE LANGUAGES."
40
  )
41
 
42
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-language translation Gradio application, backed by FLORES-200 codes.
2
+
3
+ Translates text between any of the 200+ languages described in ``language.json``,
4
+ using Facebook's NLLB-200 distilled model.
5
+
6
+ Migration notes relative to the 2024 original:
7
+
8
+ * ``torch_dtype=torch.bfloat16`` is replaced with ``float32``. The free
9
+ ``cpu-basic`` Space tier has no CUDA device, where bfloat16 is unsupported or
10
+ falls back through slow software emulation.
11
+ * The NLLB checkpoint (~2.4 GB) is loaded lazily. The original loaded it at
12
+ import time, so the Gradio UI never appeared until the download finished — a
13
+ direct cause of the Space startup timeout.
14
+ * ``language.json`` is now validated at load time. The original passed ``None``
15
+ into the pipeline whenever a language lookup failed, which failed silently and
16
+ opaquely.
17
+
18
+ Example:
19
+ >>> from app import get_flores_code
20
+ >>> get_flores_code("English")
21
+ 'eng_Latn'
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
  import json
27
+ import logging
28
+ import os
29
+ import threading
30
+ from typing import Final
31
+
32
+ import gradio as gr
33
+ import torch
34
  from transformers import pipeline
35
 
36
+ #: Hugging Face repository id of the translation model.
37
+ MODEL_NAME: Final[str] = "facebook/nllb-200-distilled-600M"
38
+
39
+ #: Path to the language code table, relative to this file.
40
+ LANGUAGE_DATA_PATH: Final[str] = os.path.join(
41
+ os.path.dirname(os.path.abspath(__file__)), "language.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
43
 
44
+ #: Longest input accepted, in characters. Guards against CPU timeouts.
45
+ MAX_INPUT_CHARS: Final[int] = 5_000
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ _pipeline_lock = threading.Lock()
50
+ _translator = None
51
+ _language_table: list[dict[str, str]] | None = None
52
+
53
+
54
+ class LanguageDataError(RuntimeError):
55
+ """Raised when ``language.json`` is missing, malformed, or incomplete."""
56
+
57
+
58
+ class TranslationError(RuntimeError):
59
+ """Raised when translation fails."""
60
+
61
+
62
+ def load_language_table(path: str = LANGUAGE_DATA_PATH) -> list[dict[str, str]]:
63
+ """Load and validate the FLORES-200 language table.
64
+
65
+ Validates that the file is a list of objects carrying exactly the keys
66
+ ``Language`` and ``FLORES-200 code``, with no duplicate languages or codes.
67
+
68
+ Args:
69
+ path: Filesystem path to ``language.json``.
70
+
71
+ Returns:
72
+ list[dict[str, str]]: The validated language table.
73
+
74
+ Raises:
75
+ LanguageDataError: If the file is missing, is not valid JSON, does not
76
+ have the expected shape, or contains duplicates.
77
+
78
+ Example:
79
+ >>> table = load_language_table()
80
+ >>> "Language" in table[0]
81
+ True
82
+ """
83
+ global _language_table
84
+ if _language_table is not None:
85
+ return _language_table
86
+
87
+ if not os.path.exists(path):
88
+ raise LanguageDataError(f"Language data file not found at {path}.")
89
+ try:
90
+ with open(path, "r", encoding="utf-8") as handle:
91
+ data = json.load(handle)
92
+ except json.JSONDecodeError as exc:
93
+ raise LanguageDataError(f"Language data file is not valid JSON: {exc}") from exc
94
+
95
+ if not isinstance(data, list) or not data:
96
+ raise LanguageDataError("Language data must be a non-empty JSON list.")
97
+
98
+ required = {"Language", "FLORES-200 code"}
99
+ seen_languages: set[str] = set()
100
+ seen_codes: set[str] = set()
101
+ for index, entry in enumerate(data):
102
+ if not isinstance(entry, dict) or not required.issubset(entry):
103
+ raise LanguageDataError(
104
+ f"Entry {index} must be an object with keys {sorted(required)}."
105
+ )
106
+ language = str(entry["Language"])
107
+ code = str(entry["FLORES-200 code"])
108
+ if language in seen_languages:
109
+ raise LanguageDataError(f"Duplicate language entry: {language}")
110
+ if code in seen_codes:
111
+ raise LanguageDataError(f"Duplicate FLORES-200 code: {code}")
112
+ seen_languages.add(language)
113
+ seen_codes.add(code)
114
+
115
+ _language_table = data
116
+ return _language_table
117
+
118
+
119
+ def get_flores_code(language: str, path: str = LANGUAGE_DATA_PATH) -> str:
120
+ """Look up the FLORES-200 code for a human-readable language name.
121
+
122
+ The match is case-insensitive, matching the original behaviour.
123
+
124
+ Args:
125
+ language: A language name as it appears in ``language.json``, for example
126
+ ``"English"`` or ``"Acehnese (Arabic script)"``.
127
+ path: Filesystem path to ``language.json``.
128
+
129
+ Returns:
130
+ str: The FLORES-200 code, for example ``"eng_Latn"``.
131
+
132
+ Raises:
133
+ LanguageDataError: If the language table is missing or malformed.
134
+ ValueError: If ``language`` is not present in the table. The original
135
+ implementation returned ``None`` here, which was then passed
136
+ straight into the translation pipeline as a silent failure.
137
+
138
+ Example:
139
+ >>> get_flores_code("english")
140
+ 'eng_Latn'
141
+ >>> get_flores_code("Klingon")
142
+ Traceback (most recent call last):
143
+ ValueError: ...
144
+ """
145
+ table = load_language_table(path)
146
+ needle = (language or "").strip().lower()
147
+ for entry in table:
148
+ if str(entry["Language"]).lower() == needle:
149
+ return str(entry["FLORES-200 code"])
150
+ raise ValueError(f"Unknown language: {language!r}")
151
+
152
+
153
+ def supported_languages(path: str = LANGUAGE_DATA_PATH) -> list[str]:
154
+ """Return the sorted list of selectable language names.
155
+
156
+ Args:
157
+ path: Filesystem path to ``language.json``.
158
+
159
+ Returns:
160
+ list[str]: Language display names, sorted alphabetically.
161
+
162
+ Raises:
163
+ LanguageDataError: If the language table is missing or malformed.
164
+
165
+ Example:
166
+ >>> languages = supported_languages()
167
+ >>> "English" in languages
168
+ True
169
+ """
170
+ return sorted(str(e["Language"]) for e in load_language_table(path))
171
+
172
+
173
+ def _build_pipeline():
174
+ """Construct the Hugging Face translation pipeline.
175
+
176
+ Returns:
177
+ pipeline: A configured NLLB translation pipeline.
178
+
179
+ Raises:
180
+ TranslationError: If the pipeline cannot be constructed.
181
+ """
182
+ try:
183
+ return pipeline("translation", model=MODEL_NAME, torch_dtype=torch.float32)
184
+ except Exception as exc: # noqa: BLE001
185
+ raise TranslationError(
186
+ f"Could not load translation model '{MODEL_NAME}'. {exc}"
187
+ ) from exc
188
+
189
+
190
+ def get_translator():
191
+ """Return the shared translation pipeline, loading it on first use.
192
+
193
+ Loading is lazy and thread-safe so the Gradio UI appears immediately rather
194
+ than after a multi-gigabyte download.
195
+
196
+ Returns:
197
+ pipeline: The shared translation pipeline.
198
+
199
+ Raises:
200
+ TranslationError: If the model cannot be loaded.
201
+ """
202
+ global _translator
203
+ if _translator is None:
204
+ with _pipeline_lock:
205
+ if _translator is None:
206
+ logger.info("Loading %s ...", MODEL_NAME)
207
+ _translator = _build_pipeline()
208
+ return _translator
209
+
210
+
211
+ def translate_text(
212
+ text: str,
213
+ source_language: str,
214
+ destination_language: str,
215
+ ) -> str:
216
+ """Translate text between two languages.
217
+
218
+ Args:
219
+ text: The text to translate.
220
+ source_language: Language name as shown in ``language.json``.
221
+ destination_language: Language name as shown in ``language.json``.
222
+
223
+ Returns:
224
+ str: The translated text.
225
+
226
+ Raises:
227
+ ValueError: If the text is empty, a language is unknown, or the source
228
+ and destination languages are identical.
229
+ TranslationError: If the model cannot be loaded or inference fails.
230
+
231
+ Example:
232
+ >>> translate_text("", "English", "French")
233
+ Traceback (most recent call last):
234
+ ValueError: ...
235
+ """
236
+ cleaned = (text or "").strip()
237
+ if not cleaned:
238
+ raise ValueError("Please enter some text to translate.")
239
+ if len(cleaned) > MAX_INPUT_CHARS:
240
+ raise ValueError(
241
+ f"Input is too long ({len(cleaned)} characters). "
242
+ f"Please use at most {MAX_INPUT_CHARS} characters."
243
+ )
244
+
245
+ source = (source_language or "").strip()
246
+ destination = (destination_language or "").strip()
247
+ if source.lower() == destination.lower():
248
+ raise ValueError("Source and destination languages must be different.")
249
+
250
+ source_code = get_flores_code(source)
251
+ destination_code = get_flores_code(destination)
252
+
253
+ translator = get_translator()
254
+ try:
255
+ result = translator(
256
+ cleaned,
257
+ src_lang=source_code,
258
+ tgt_lang=destination_code,
259
+ max_length=512,
260
+ )
261
+ except Exception as exc: # noqa: BLE001
262
+ raise TranslationError(f"Translation failed: {exc}") from exc
263
+ return result[0]["translation_text"]
264
+
265
+
266
+ def translate_with_error_handling(
267
+ text: str,
268
+ source_language: str,
269
+ destination_language: str,
270
+ ) -> str:
271
+ """Translate text and convert failures into user-readable messages.
272
+
273
+ Args:
274
+ text: The text to translate.
275
+ source_language: Language name as shown in ``language.json``.
276
+ destination_language: Language name as shown in ``language.json``.
277
+
278
+ Returns:
279
+ str: The translation, or a message describing what went wrong.
280
+
281
+ Example:
282
+ >>> translate_with_error_handling("", "English", "French")
283
+ 'Input problem: Please enter some text to translate.'
284
+ """
285
+ try:
286
+ return translate_text(text, source_language, destination_language)
287
+ except ValueError as exc:
288
+ return f"Input problem: {exc}"
289
+ except LanguageDataError as exc:
290
+ return f"Configuration error: {exc}"
291
+ except TranslationError as exc:
292
+ return f"Translation error: {exc}"
293
+
294
+
295
+ def build_demo() -> gr.Blocks:
296
+ """Assemble the Gradio interface.
297
+
298
+ Returns:
299
+ gr.Blocks: The configured demo, ready to launch.
300
+
301
+ Raises:
302
+ LanguageDataError: If ``language.json`` cannot be loaded, since the
303
+ language pickers cannot be populated without it.
304
+
305
+ Example:
306
+ >>> isinstance(build_demo(), gr.Blocks)
307
+ True
308
+ """
309
+ options = supported_languages()
310
+ with gr.Blocks(title="Multi-language Translator") as demo:
311
+ gr.Markdown(
312
+ "# Multi-language Translator\n"
313
+ "Translate between the FLORES-200 languages using NLLB-200. "
314
+ "Inference runs locally on CPU."
315
+ )
316
+ with gr.Row():
317
+ with gr.Column():
318
+ source_text = gr.Textbox(label="Input text to translate", lines=6)
319
+ source_language = gr.Dropdown(
320
+ options, label="Select Source Language",
321
+ value="English" if "English" in options else options[0],
322
+ )
323
+ destination_language = gr.Dropdown(
324
+ options, label="Select Destination Language",
325
+ value="French" if "French" in options else options[0],
326
+ )
327
+ submit = gr.Button("Translate", variant="primary")
328
+ with gr.Column():
329
+ output = gr.Textbox(label="Translated text", lines=6)
330
+ submit.click(
331
+ fn=translate_with_error_handling,
332
+ inputs=[source_text, source_language, destination_language],
333
+ outputs=[output],
334
+ )
335
+ return demo
336
+
337
+
338
+ def main() -> None:
339
+ """Launch the Gradio application."""
340
+ demo = build_demo()
341
+ demo.queue().launch()
342
+
343
+
344
+ if __name__ == "__main__":
345
+ main()
requirements.txt CHANGED
@@ -1,3 +1,13 @@
1
- transformers
2
- torch
3
- gradio
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pinned to exact versions on purpose. Unpinned requirements are the root cause
2
+ # of most failures in this portfolio: on the cpu-basic tier they silently resolve
3
+ # CUDA builds of torch, and 2024-era code ends up running against 2026 major
4
+ # library versions it was never written against.
5
+ gradio==6.29.0
6
+ transformers==5.18.0
7
+ # Gradio 6 requires huggingface-hub>=1.16; transformers 5.18 requires >=1.31.
8
+ # Pinning it explicitly avoids a resolver conflict at build time.
9
+ huggingface-hub==1.33.0
10
+ torch==2.9.1
11
+ sentencepiece==0.2.1
12
+ sacremoses==0.2.0
13
+ protobuf==6.33.1