From e9d427e7e79465da4b0234298058eb36338a463d Mon Sep 17 00:00:00 2001 From: "pascal.tremblin" Date: Sat, 28 Nov 2026 20:32:47 +0100 Subject: [PATCH] studio: interface in English or French (FR/EN switch) The texts of canoP studio are written in French in the code and wrapped in tr() (tools/canop_i18n.py); their English translations are in tools/canop_i18n_en.py (322 texts). The language is a setting of the studio, switched in the top bar: the texts of the state are recomputed (refresh_language() of the modules) and the interface is rebuilt once the update of the page is handled. New installations start in English; settings saved without a language keep French. - Values used by the logic stay as they are (run states, stored in signac documents and read by the MCP tools, are translated only when shown); files written by the studio (version lines of the inis) do not depend on the language. - tools/trame/check_i18n.py checks that every tr() text has a translation with the same placeholders and {{ }} expressions: ctest (label unit) and pre-commit. - The run view template and the analysis.py template of new campaigns are translated; existing runs and campaigns keep their copies. - VS Code extension: follows the language of VS Code (package.nls*.json, a dictionary in extension.js). - Docs and the studio README use the English labels; physics// in a help text now shows. Co-Authored-By: Claude Opus 5.5 --- .pre-commit-config.yaml | 9 + CHANGELOG.md | 3 + REUSE.toml | 2 +- docs/getting-started/running.md | 2 +- docs/user-guide/campaigns.md | 18 +- docs/user-guide/studio.md | 17 +- test/CMakeLists.txt | 7 +- tools/canop_core.py | 34 +- tools/canop_i18n.py | 52 +++ tools/canop_i18n_en.py | 342 ++++++++++++++++ tools/trame/README.md | 18 +- tools/trame/campaign_template/analysis.py | 10 +- tools/trame/canop_analysis.py | 44 ++- tools/trame/canop_app.py | 347 ++++++++++------- tools/trame/canop_campaign.py | 453 ++++++++++++---------- tools/trame/canop_journal.py | 55 ++- tools/trame/canop_view.py | 14 +- tools/trame/check_i18n.py | 122 ++++++ tools/trame/run_view/canoP_view.py | 30 +- tools/vscode/build_vsix.py | 4 +- tools/vscode/extension.js | 49 ++- tools/vscode/package.json | 10 +- tools/vscode/package.nls.fr.json | 7 + tools/vscode/package.nls.json | 7 + 24 files changed, 1205 insertions(+), 451 deletions(-) create mode 100644 tools/canop_i18n.py create mode 100644 tools/canop_i18n_en.py create mode 100644 tools/trame/check_i18n.py create mode 100644 tools/vscode/package.nls.fr.json create mode 100644 tools/vscode/package.nls.json diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5b081fa..a1b9343 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -36,6 +36,15 @@ repos: - id: pylint files: ^(physics|tools|test)/ additional_dependencies: [numpy] + # translations of canoP studio: every text of the studio has its English translation + - repo: local + hooks: + - id: check-i18n + name: translations of canoP studio + entry: python tools/trame/check_i18n.py + language: python + files: ^tools/ + pass_filenames: false # Fix typos - repo: https://github.com/crate-ci/typos rev: v1.23.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 18c9ad4..f824c12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver ## Unreleased +- canoP studio in English or in French: a FR/EN switch in the top bar, saved in the settings. New + installations start in English; studios set up before keep French. + ## 0.1.0 - 2026-11-27 First release of canoP with its physics written in Python. The numbering restarts at 0.1.0. diff --git a/REUSE.toml b/REUSE.toml index b2869e5..42e4c33 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -45,7 +45,7 @@ SPDX-License-Identifier = "Apache-2.0 WITH LLVM-exception" [[annotations]] path = [ - ".mcp.json", "tools/vscode/package.json" + ".mcp.json", "tools/vscode/package*.json" ] precedence = "aggregate" SPDX-FileCopyrightText = "canoP authors" diff --git a/docs/getting-started/running.md b/docs/getting-started/running.md index 1514f62..3433b66 100644 --- a/docs/getting-started/running.md +++ b/docs/getting-started/running.md @@ -48,7 +48,7 @@ A run restarts from an output with `io.restart_enabled = 1` and `io.restart_file ## Initial condition only `simulation.nstepmax = 0` runs no time step: canoP refines the initial condition level by level up -to `amr.max_refine` and writes it. The **Condition initiale** button of canoP studio does this +to `amr.max_refine` and writes it. The **Initial condition** button of canoP studio does this without touching the run ({doc}`../user-guide/studio`). ## Physics directory diff --git a/docs/user-guide/campaigns.md b/docs/user-guide/campaigns.md index ef1af7d..6e1572e 100644 --- a/docs/user-guide/campaigns.md +++ b/docs/user-guide/campaigns.md @@ -13,7 +13,7 @@ The runs of the **Run** tab belong to the campaign `hors-campagne`. ## Making and launching a campaign -In the **Campagne** tab, give a name, a base input file and one line per varied parameter: +In the **Campaign** tab, give a name, a base input file and one line per varied parameter: ```text simulation.cfl = 0.4, 0.6, 0.8 @@ -23,14 +23,14 @@ launch.nprocs = 4, 8 The campaign holds one run per combination (here 18). `launch.*` keys vary the execution of the run (`nprocs`, `omp_threads`, `nodes`, `time`, `partition`, `gpus_per_task`) instead of its input file. -Runs can be added later. **Lancer les runs préparés** submits the prepared runs as Slurm jobs +Runs can be added later. **Launch the prepared runs** submits the prepared runs as Slurm jobs (signac-flow, `project.py` of the campaign). Before submitting, the studio checks the limits set in its settings: runs per submission, runs per campaign, nodes, cores and GPUs per run, core-hours and GPU-hours per submission. -The table of the campaign shows the state of each run (préparé, en file, en cours, terminé, -interrompu, échoué), its parameters and its metrics; a run can be shown in the Visualisation or loaded -in the editor of the Run tab. `analysis.py` of the campaign defines the plots of the **Analyse** tab. +The table of the campaign shows the state of each run (prepared, queued, running, finished, +interrupted, failed), its parameters and its metrics; a run can be shown in the View tab or loaded in +the editor of the Run tab. `analysis.py` of the campaign defines the plots of the **Analysis** tab. ## Physics and versioning @@ -53,13 +53,13 @@ studio. The `README.md` of each campaign explains it: build canoP at the commit written in the input files, clone the repository of the campaign into `_campaigns/` of that canoP (switch to a branch -to start from an older commit), then **Préparer à nouveau** puts back the runs submitted in the -original campaign in the prepared state, and **Lancer les runs préparés** runs them again. +to start from an older commit), then **Prepare again** puts back the runs submitted in the +original campaign in the prepared state, and **Launch the prepared runs** runs them again. ## Initial condition only -The **Condition initiale** button of the Run tab runs the input file of the editor without any time -step (`simulation.nstepmax = 0`) and shows the refined initial condition in the Visualisation. The run +The **Initial condition** button of the Run tab runs the input file of the editor without any time +step (`simulation.nstepmax = 0`) and shows the refined initial condition in the View tab. The run is not launched and nothing is committed: the output goes to `/condition_initiale/` (ignored by the repository of the campaign), with the current physics of the campaign. **Revenir au run** shows the outputs of the run again. diff --git a/docs/user-guide/studio.md b/docs/user-guide/studio.md index 643223c..48e0cdd 100644 --- a/docs/user-guide/studio.md +++ b/docs/user-guide/studio.md @@ -8,20 +8,21 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception canoP studio is a web application, built with [trame](https://kitware.github.io/trame/), to prepare, build, run and look at canoP simulations from a browser. It runs on a login node: the meshes are drawn -by the browser (vtk.js), the server needs neither a GPU nor OpenGL. Its interface is in French. +by the browser (vtk.js), the server needs neither a GPU nor OpenGL. Its interface is in English or +French: the FR/EN switch of the top bar, saved in its settings (new installations start in English). - **Run**: load an example of `settings/` or the input file of a run, edit it key by key or as text. Each key shows, under the mouse, its role, its type, its default value and, for the options of the model, the valid values and the summary of the chosen file; keys that canoP never reads are flagged. Launch the run, or compute only its refined initial - condition (**Condition initiale**). -- **Campagne**: parameter studies, see {doc}`campaigns`. -- **Visualisation**: fields and colour maps, the AMR mesh, velocity arrows, streamlines, time + condition (**Initial condition**). +- **Campaign**: parameter studies, see {doc}`campaigns`. +- **View**: fields and colour maps, the AMR mesh, velocity arrows, streamlines, time slider, slices or outer surface in 3D, updated while the run writes its outputs. The view and the derived fields of each run are Python files of the run (`canoP_view.py`, `canoP_fields.py`), reloaded when they are saved. -- **Journal**: the logs of the build and of the run, while they are written. -- **Analyse**: the analysis of a campaign (`analysis.py` of the campaign). +- **Log**: the logs of the build and of the run, while they are written. +- **Analysis**: the analysis of a campaign (`analysis.py` of the campaign). The settings panel holds the build settings (sources, build directory, dimension, Kokkos backend and architectures, environment, CMake options, build on this node or as a Slurm job) and the run settings @@ -86,8 +87,8 @@ in `/.local/canop-studio/venv` when `.local/canop-studio` exists, else in The script prints the addresses to open, with a key: ```text -via code-server : http://127.0.0.1:8080/proxy/8090/index.html?secret=... -direct : http://localhost:8090/index.html?secret=... +via code-server: http://127.0.0.1:8080/proxy/8090/index.html?secret=... +direct: http://localhost:8090/index.html?secret=... ``` From code-server on the same node, open the first one. Otherwise open an ssh tunnel diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 83380e9..3ea2529 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,6 +1,7 @@ # Tests of canoP (ctest): # -# * unit tests of the limiters and the settings (label "unit"), see unit/; +# * unit tests of the limiters and the settings (label "unit"), see unit/, and the check of the +# translations of canoP studio (label "unit"), tools/trame/check_i18n.py; # * regression tests: short runs compared with stored reference outputs (label "regression", and # "3d" for the 3D cases), see regression/regression.py and regression/cases.py; # * physical properties without reference outputs (label "physics"), see physics/physics.py. @@ -15,6 +16,10 @@ if(NOT Python3_Interpreter_FOUND) return() endif() +# translations of canoP studio: every text of the studio has its English translation +add_test(NAME studio_i18n COMMAND ${Python3_EXECUTABLE} ${PROJECT_SOURCE_DIR}/tools/trame/check_i18n.py) +set_tests_properties(studio_i18n PROPERTIES LABELS unit) + # physical properties without reference outputs (label "physics"), with canoP_2d foreach(CHECK outflow mirror energy) add_test( diff --git a/tools/canop_core.py b/tools/canop_core.py index 22e98e3..3927626 100644 --- a/tools/canop_core.py +++ b/tools/canop_core.py @@ -20,6 +20,8 @@ import time from dataclasses import asdict, dataclass, field, fields +from canop_i18n import DEFAULT_LANGUAGE, LANGUAGES, tr + # this file lives in /tools DEFAULT_SOURCE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -704,9 +706,13 @@ class Settings: camp_max_core_hours: int = 100 # core-hours requested by a submission (cores x Slurm time) camp_max_gpus: int = 4 # GPUs of a run camp_max_gpu_hours: int = 50 # GPU-hours requested by a submission + # language of the studio, 'en' or 'fr' (canop_i18n); settings saved without it are in French + language: str = DEFAULT_LANGUAGE def __post_init__(self): """Replace invalid values by defaults and keep the profiles of the pykokkos backends only.""" + if self.language not in LANGUAGES: + self.language = DEFAULT_LANGUAGE try: self.dim = int(self.dim) except (TypeError, ValueError): @@ -1257,14 +1263,14 @@ def slurm_partitions_info(): def _duration(seconds): - """A time limit as shown to the user, in French: 30 min, 1 h, 1 j 12 h, sans limite.""" + """A time limit as shown to the user, in the language of the studio: 30 min, 1 h, 1 j 12 h, sans limite.""" if seconds == float("inf"): - return "sans limite" + return tr("sans limite") d, r = divmod(int(seconds), 86400) h, r = divmod(r, 3600) m = r // 60 - return " ".join(x for x in ("%d j" % d if d else "", "%d h" % h if h else "", "%d min" % m if m else "") if x) \ - or "0 min" + return " ".join(x for x in (tr("%d j") % d if d else "", "%d h" % h if h else "", "%d min" % m if m else "") + if x) or "0 min" def slurm_partitions(): @@ -1273,7 +1279,7 @@ def slurm_partitions(): def slurm_partitions_text(): - """One line per Slurm partition with its limits, or [] without Slurm. + """One line per Slurm partition with its limits, in the language of the studio, or [] without Slurm. E.g. 'gpua100 : 1 j max, 9 nœuds de 32 cœurs, 4 GPU par nœud'; the default partition is marked by *. """ @@ -1281,10 +1287,10 @@ def slurm_partitions_text(): for p in slurm_partitions_info(): words = ["%s max" % _duration(p["seconds"])] if p["nodes"] and p["cpus"]: - words.append("%s nœuds de %s cœurs" % (p["nodes"], p["cpus"])) + words.append(tr("%s nœuds de %s cœurs") % (p["nodes"], p["cpus"])) if p["gpus"]: - words.append("%d GPU par nœud" % p["gpus"]) - out.append("%s%s : %s" % (p["name"], " *" if p["default"] else "", ", ".join(words))) + words.append(tr("%d GPU par nœud") % p["gpus"]) + out.append(tr("%s%s : %s") % (p["name"], " *" if p["default"] else "", ", ".join(words))) return out @@ -1309,7 +1315,7 @@ def slurm_jobs_alive(root): def clear_directory(path, source): - """Delete everything inside `path`, keeping the directory itself; return (ok, message). + """Delete everything inside `path`, keeping the directory itself; return (ok, message in the studio's language). Refused for /, the home directory, a directory that holds the sources, and a directory with active Slurm jobs. @@ -1318,12 +1324,12 @@ def clear_directory(path, source): source = os.path.realpath(source) home = os.path.realpath(os.path.expanduser("~")) if not os.path.isdir(path): - return True, "%s n'existe pas, rien à supprimer" % path + return True, tr("%s n'existe pas, rien à supprimer") % path if path in ("/", home) or path == source or source.startswith(path + os.sep): - return False, "refusé : %s contient les sources ou est un répertoire système" % path + return False, tr("refusé : %s contient les sources ou est un répertoire système") % path jobs = slurm_jobs_alive(path) if jobs: - return False, "refusé : job(s) Slurm encore actif(s) dans %s : %s" % (path, ", ".join(jobs)) + return False, tr("refusé : job(s) Slurm encore actif(s) dans %s : %s") % (path, ", ".join(jobs)) errors = [] for name in os.listdir(path): entry = os.path.join(path, name) @@ -1335,8 +1341,8 @@ def clear_directory(path, source): except OSError as err: errors.append(str(err)) if errors: - return False, "suppression incomplète dans %s : %s" % (path, errors[0]) - return True, "%s vidé" % path + return False, tr("suppression incomplète dans %s : %s") % (path, errors[0]) + return True, tr("%s vidé") % path def xdmf_complete(path): diff --git a/tools/canop_i18n.py b/tools/canop_i18n.py new file mode 100644 index 0000000..cef4687 --- /dev/null +++ b/tools/canop_i18n.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Language of the texts of canoP studio: French or English. + +The texts are written in French in the code, wrapped in tr(); their English translations are in +canop_i18n_en.py (EN, French text -> English text). tr() returns the text in the current language, +chosen in the studio (setting `language`), so a text must be translated when it is shown, not when +a module is imported: module-level constants and state values set once are recomputed when the +language changes (refresh_language() of the modules of the studio). + +A translation keeps the placeholders of the text (%s, %d, %(name)s, {{ ... }}), and, for a text that +is part of a JavaScript expression, its quotes: tools/trame/check_i18n.py checks both, and that every +text wrapped in tr() has a translation. +""" +import json + +from canop_i18n_en import EN + +LANGUAGES = ("en", "fr") +DEFAULT_LANGUAGE = "en" # new installations; settings saved before the choice existed are in French + +_current = {"language": DEFAULT_LANGUAGE} + + +def set_language(language): + """Choose the language of the texts ('en' or 'fr'; anything else: the default).""" + _current["language"] = language if language in LANGUAGES else DEFAULT_LANGUAGE + + +def language(): + """Current language of the texts.""" + return _current["language"] + + +def tr(text): + """`text` (French, as written in the code) in the current language.""" + if _current["language"] == "en": + return EN.get(text, text) + return text + + +def tr_js(text): + """tr(text) as a single-quoted JavaScript string literal, for a text inside an expression of the page. + + Safe inside {{ }} and in a bound attribute (label=("... + %s" % tr_js(...),)), which trame writes + as :label="" without escaping: no double quote, no & nor < > in the literal. + """ + escaped = json.dumps(tr(text), ensure_ascii=False)[1:-1].replace('\\"', '"') # JSON escapes, unquoted + for char, code in (("'", "\\u0027"), ('"', "\\u0022"), ("&", "\\u0026"), ("<", "\\u003c"), (">", "\\u003e")): + escaped = escaped.replace(char, code) + return "'" + escaped + "'" diff --git a/tools/canop_i18n_en.py b/tools/canop_i18n_en.py new file mode 100644 index 0000000..5e3cfb4 --- /dev/null +++ b/tools/canop_i18n_en.py @@ -0,0 +1,342 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""English translations of the texts of canoP studio: French text, as written in tr(), -> English. + +Grouped by file of the studio. tools/trame/check_i18n.py checks that every text wrapped in tr() is +here, with the same placeholders (%s, %(name)s, {{ ... }}) and the same quotes. +""" +# pylint: disable=line-too-long + +EN = { + # canop_core.py + "sans limite": "no limit", + "%s vidé": "%s emptied", + "%s%s : %s": "%s%s: %s", + "%s n'existe pas, rien à supprimer": "%s does not exist, nothing to delete", + "refusé : %s contient les sources ou est un répertoire système": "refused: %s holds the sources or is a system directory", + "refusé : job(s) Slurm encore actif(s) dans %s : %s": "refused: Slurm job(s) still active in %s: %s", + "suppression incomplète dans %s : %s": "incomplete deletion in %s: %s", + "%s nœuds de %s cœurs": "%s nodes of %s cores", + "%d GPU par nœud": "%d GPU(s) per node", + "%d j": "%d d", + # trame/canop_analysis.py + "Choisissez une campagne.": "Choose a campaign.", + "%s : %d run(s), %d avec des métriques": "%s: %d run(s), %d with metrics", + "%s : %s en fonction de %s": "%s: %s versus %s", + "Analyse : {{ an_source }}": "Analysis: {{ an_source }}", + "Campagne %s : %s: %s": "Campaign %s: %s: %s", + "Erreur dans %s : %s: %s": "Error in %s: %s: %s", + "analysis.py, analyse : %s: %s": "analysis.py, analyse: %s: %s", + "analysis.py, draw : %s: %s": "analysis.py, draw: %s: %s", + "Campagne": "Campaign", + "aucune campagne": "no campaign", + "Paramètre (x)": "Parameter (x)", + "Métrique (y)": "Metric (y)", + "Rafraîchir": "Refresh", + "Pas encore de métriques à tracer (runs terminés de la campagne, calculées par « python project.py run -o metrics »).": "No metrics to plot yet (finished runs of the campaign, computed by \"python project.py run -o metrics\").", + "analysis.py, panel : %s: %s": "analysis.py, panel: %s: %s", + # trame/canop_app.py + "Mise à jour du studio, la page va se recharger…": "Updating the studio, the page will reload…", + "Chargez un fichier ini ou choisissez un exemple.": "Load an ini file or choose an example.", + "\n canoP studio, ouvrez dans votre navigateur :\n": "\n canoP studio, open in your browser:\n", + " Ctrl-C pour arrêter le serveur.\n": " Ctrl-C to stop the server.\n", + "%s / condition initiale": "%s / initial condition", + "Chargé : %s": "Loaded: %s", + "Indiquez un chemin pour le fichier ini": "Give a path for the ini file", + "Enregistré : %s": "Saved: %s", + "Section et clé requises": "Section and key required", + "aucune (défaut du compilateur)": "none (compiler default)", + "%d paramètres trouvés dans le code": "%d parameters found in the code", + "Une compilation ou un run est en cours : arrêtez-le d'abord.": "A build or a run is running: stop it first.", + "Ajouter un paramètre": "Add a parameter", + " (même adresse de base que celle où vous ouvrez code-server)\n": " (same base address as the one where you open code-server)\n", + " en direct : http://localhost:%d/%s": " direct: http://localhost:%d/%s", + " (tunnel ssh : ssh -L %d:localhost:%d %s)\n": " (ssh tunnel: ssh -L %d:localhost:%d %s)\n", + " La clé est gardée dans %s (supprimez-le pour en changer).": " The key is kept in %s (delete it to get a new one).", + " Claude Code ouvert sur le dépôt canoP le trouve tout seul (.mcp.json).": " Claude Code opened on the canoP repository finds it by itself (.mcp.json).", + " Ailleurs, une fois, sur ce nœud :\n": " Elsewhere, once, on this node:\n", + "Fichier introuvable : %s": "File not found: %s", + "Refusé : %s ne ressemble pas à un répertoire de build canoP.": "Refused: %s does not look like a canoP build directory.", + "Compilation : %s": "Build: %s", + "Simulation : %s": "Run: %s", + "champs dérivés": "derived fields", + "campagne": "campaign", + "visualisation": "view", + "journal": "log", + "analyse": "analysis", + "Erreur dans canop_fields.py : %s": "Error in canop_fields.py: %s", + "Rechargé : %s": "Reloaded: %s", + "ce nœud (direct)": "this node (direct)", + "un nœud de calcul (job Slurm, sbatch)": "a compute node (Slurm job, sbatch)", + "compilation : {{ build_state }}": "build: {{ build_state }}", + "run affiché : {{ view_run_name }}": "run shown: {{ view_run_name }}", + "canop-studio: aucun port libre entre 8090 et 8199, utilisez --port": "canop-studio: no free port between 8090 and 8199, use --port", + " via code-server : %s%s": " via code-server: %s%s", + " Serveur MCP : http://127.0.0.1:%d/mcp (jeton dans %s)": " MCP server: http://127.0.0.1:%d/mcp (token in %s)", + "Écriture impossible : %s": "Cannot write: %s", + "Rechargement impossible : %s: %s": "Cannot reload: %s: %s", + "Pas encore de sortie dans %s": "No output yet in %s", + "Code et compilation": "Code and build", + "Le modèle de la physique (physics/<modèle>/, en Python avec pykokkos) se choisit dans l'ini : simulation.model.": "The model of the physics (physics/<model>/, in Python with pykokkos) is chosen in the ini: simulation.model.", + "Kokkos (partagé) et pykokkos sont construits avec canoP pour ce backend et ces architectures (GPU : celle du GPU des runs, ex. AMPERE80 pour un A100). L'environnement, les options CMake et les options Slurm des runs sont propres à chaque backend : ils changent avec lui.": "Kokkos (shared) and pykokkos are built with canoP for this backend and these architectures (GPU: that of the GPU of the runs, e.g. AMPERE80 for an A100). The environment, the CMake options and the Slurm options of the runs belong to each backend: they change with it.", + "Build de cette variante : {{ build_dir_resolved }}": "Build of this variant: {{ build_dir_resolved }}", + "Le backend et les architectures de Kokkos viennent des menus ci-dessus : le studio retire -DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… et -DKALYPSSO_CORE_KOKKOS_BUILD de ces options.": "The backend and the architectures of Kokkos come from the menus above: the studio removes -DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… and -DKALYPSSO_CORE_KOKKOS_BUILD from these options.", + "Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda se compile sans GPU.": "A job of one task with “Build jobs” cores; Cuda builds without a GPU.", + "{{ executable ? 'Exécutable : ' + executable : 'Exécutable non compilé' }}": "{{ executable ? 'Executable: ' + executable : 'Executable not built' }}", + "Vider le répertoire de build": "Empty the build directory", + "Exécution": "Execution", + "Partitions de ce cluster (* : par défaut) :\n{{ slurm_partitions.join('\\n') }}": "Partitions of this cluster (*: default):\n{{ slurm_partitions.join('\\n') }}", + "Garde-fous des campagnes lancées par un agent": "Safeguards of the campaigns run by an agent", + "Au-delà, l'agent doit demander votre accord. Ces valeurs ne sont modifiables que par vous.": "Beyond them, the agent must ask for your go-ahead. Only you can change these values.", + "{{ ini_unknown }} clé(s) inconnue(s) du code": "{{ ini_unknown }} key(s) unknown to the code", + "Rescanner le code": "Rescan the code", + "{{ sec.keys.filter(k => k.set).length }} paramètre(s)": "{{ sec.keys.filter(k => k.set).length }} parameter(s)", + "Section": "Section", + "Clé": "Key", + "Valeur (défaut si vide)": "Value (default if empty)", + "{{ delete_kind === 'build' ? 'Vider le répertoire de build ?' : 'Supprimer tous les runs ?' }}": "{{ delete_kind === 'build' ? 'Empty the build directory?' : 'Delete all the runs?' }}", + "canop-studio: le port %d est déjà utilisé, choisissez-en un autre avec --port": "canop-studio: the port %d is already in use, choose another one with --port", + " (pas de code-server sur ce nœud, %s : pour passer par code-server,\n lancez canop-studio depuis un terminal de code-server, sur son nœud)\n": " (no code-server on this node, %s: to go through code-server,\n start canop-studio from a terminal of code-server, on its node)\n", + "Lecture impossible : %s": "Cannot read: %s", + "Sources canoP": "canoP sources", + "Répertoire de build": "Build directory", + "Dimension (exécutable)": "Dimension (executable)", + "Backend Kokkos": "Kokkos backend", + "Architecture CPU (Kokkos_ARCH)": "CPU architecture (Kokkos_ARCH)", + "Architecture GPU (Kokkos_ARCH)": "GPU architecture (Kokkos_ARCH)", + "Jobs de compilation": "Build jobs", + "sur un nœud de calcul : les cœurs demandés (--cpus-per-task)": "on a compute node: the cores requested (--cpus-per-task)", + "Compiler sur": "Build on", + "Options Slurm de la compilation (#SBATCH)": "Slurm options of the build (#SBATCH)", + "Configurer": "Configure", + "Compiler": "Build", + "Lanceur": "Launcher", + "Arguments supplémentaires": "Extra arguments", + "Heures-cœur par soumission": "Core-hours per submission", + "somme sur les runs soumis de cœurs x durée Slurm demandée": "sum over the submitted runs of cores x Slurm time requested", + "Filtrer les paramètres": "Filter the parameters", + "Afficher les défauts du code": "Show the defaults of the code", + "Texte du fichier ini": "Text of the ini file", + "Modifications prises en compte en quittant le champ": "Changes applied when leaving the field", + "Run": "Run", + "Journal": "Log", + "Visualisation": "View", + "Analyse": "Analysis", + "Tout le contenu de ce répertoire sera supprimé définitivement :": "All the content of this directory will be deleted for good:", + "Il faudra tout recompiler (configuration CMake comprise).": "Everything will have to be built again (CMake configuration included).", + "Annuler": "Cancel", + "Supprimer": "Delete", + "canop-studio: le port MCP %d est déjà utilisé": "canop-studio: the MCP port %d is already in use", + "Processus MPI": "MPI processes", + "Threads OpenMP": "OpenMP threads", + "0 : non défini": "0: not set", + "GPU par processus": "GPUs per process", + "avec --gres : GPU par nœud": "with --gres: GPUs per node", + "Demande Slurm": "Slurm request", + "Runs par soumission": "Runs per submission", + "Runs par campagne": "Runs per campaign", + "Nœuds par run": "Nodes per run", + "Cœurs par run": "Cores per run", + "processus MPI x threads OpenMP": "MPI processes x OpenMP threads", + "GPU par run": "GPUs per run", + "Heures-GPU par soumission": "GPU-hours per submission", + "Environnement %s (modules…)": "%s environment (modules…)", + "Options CMake %s": "%s CMake options", + "Options Slurm des runs %s (#SBATCH)": "Slurm options of the %s runs (#SBATCH)", + "{{ item.value || item.default }} : {{ item.value_doc }}": "{{ item.value || item.default }}: {{ item.value_doc }}", + "type : {{ item.type }}": "type: {{ item.type }}", + "défaut : {{ item.default }}": "default: {{ item.default }}", + "valeurs : {{ item.choices }}": "values: {{ item.choices }}", + # trame/canop_campaign.py + "nom": "name", + "créé le": "created", + "%d processus x %d threads = %d cœurs%s, %s nœud(s), %s, %s": "%d processes x %d threads = %d cores%s, %s node(s), %s, %s", + "aucun paramètre à faire varier": "no parameter to vary", + "%d run(s) — absents de l'ini de l'éditeur (seront ajoutés) : %s": "%d run(s) — not in the ini of the editor (will be added): %s", + "%d run(s)": "%d run(s)", + "nom de campagne : lettres, chiffres, - et _ uniquement": "campaign name: letters, digits, - and _ only", + "ini de base vide": "empty base ini", + "campagne %s créée : %d run(s) préparé(s), physique copiée de canoP dans %s": "campaign %s created: %d run(s) prepared, physics copied from canoP into %s", + "%d run(s) ajouté(s) à %s (%d déjà là)": "%d run(s) added to %s (%d already there)", + "les campagnes se lancent avec le lanceur sbatch (panneau Exécution)": "campaigns are launched with the sbatch launcher (Execution panel)", + "%d run(s) soumis avec signac-flow (python project.py submit), physique %s": "%d run(s) submitted with signac-flow (python project.py submit), physics %s", + "%d run(s) de %s à nouveau préparé(s)": "%d run(s) of %s prepared again", + "%d run(s) arrêté(s)": "%d run(s) stopped", + "Chargez d'abord cet ini dans une campagne (« Charger dans la campagne »).": "Load this ini into a campaign first (“Load into the campaign”).", + "Un run de l'onglet Run tourne déjà : arrêtez-le d'abord.": "A run of the Run tab is already running: stop it first.", + "L'éditeur est vide.": "The editor is empty.", + "Run %s créé dans %s : vous pouvez le lancer.": "Run %s created in %s: you can run it.", + "Run arrêté.": "Run stopped.", + "%s / %s / condition initiale": "%s / %s / initial condition", + "Condition initiale prête : onglet Visualisation (%s).": "Initial condition ready: View tab (%s).", + "Charger dans la campagne": "Load into the campaign", + "Éditeur vide : choisissez un exemple, ou « Charger dans l'éditeur » un run d'une campagne.": "Empty editor: choose an example, or load a run of a campaign into the editor.", + "Visualisation : la condition initiale seule (0 pas de temps, non versionnée), dans {{ view_run }}": "View: the initial condition alone (0 time steps, not versioned), in {{ view_run }}", + "Revenir au run": "Back to the run", + "Exécution de ce run (script de soumission, pas l'ini) — vide : valeur par défaut, en gris": "Execution of this run (submission script, not the ini) — empty: default value, in grey", + "Demandé à Slurm : {{ run_launch_effective }}": "Requested from Slurm: {{ run_launch_effective }}", + "Lancer": "Run", + "Condition initiale": "Initial condition", + "Arrêter": "Stop", + "run : {{ run_state }}": "run: {{ run_state }}", + "{{ camp_info.n }} run(s) : {{ camp_info.counts }} — {{ camp_info.path }}": "{{ camp_info.n }} run(s): {{ camp_info.counts }} — {{ camp_info.path }}", + "Pas de dépôt git pour cette campagne (créé au prochain lancement).": "No git repository for this campaign (made at the next launch).", + "Créez une campagne : l'ini de l'éditeur sert de base, et vous indiquez les paramètres à faire varier.": "Create a campaign: the ini of the editor is its base, and you give the parameters to vary.", + "préparé": "prepared", + "en file": "queued", + "en cours": "running", + "terminé": "finished", + "interrompu": "interrupted", + "échoué": "failed", + "%d runs à soumettre (limite %d)": "%d runs to submit (limit %d)", + "%.0f heures-GPU demandées (limite %d)": "%.0f GPU-hours requested (limit %d)", + "%.0f heures-cœur demandées (limite %d)": "%.0f core-hours requested (limit %d)", + "%d run(s) sans durée Slurm (--time) : heures-cœur inconnues": "%d run(s) without a Slurm time (--time): core-hours unknown", + "la campagne %s existe déjà": "the campaign %s already exists", + "campagne %s créée : %d run(s) préparé(s) ; %s": "campaign %s created: %d run(s) prepared; %s", + "%s reçoit les runs de l'onglet Run : pas de balayage": "%s receives the runs of the Run tab: no sweep", + "pas d'exécutable %s : compilez d'abord": "no executable %s: build first", + "aucun run préparé à lancer dans %s": "no prepared run to launch in %s", + "signac-flow submit : %s": "signac-flow submit: %s", + "La campagne %s ne peut pas être supprimée (supprimez ses runs un par un).": "The campaign %s cannot be deleted (delete its runs one by one).", + "Refusé : %s n'est pas une campagne.": "Refused: %s is not a campaign.", + "Campagne %s supprimée (%d run(s), %d job(s) Slurm annulé(s)).": "Campaign %s deleted (%d run(s), %d Slurm job(s) cancelled).", + "Campagne %s supprimée (%d run(s)).": "Campaign %s deleted (%d run(s)).", + "compilation du studio": "build of the studio", + "sources au lancement (compilation hors du studio)": "sources at launch (built outside the studio)", + "dépôt git de la campagne %s : %s": "git repository of the campaign %s: %s", + "le dépôt %s est sur un commit détaché : créez une branche avant de lancer (git -C %s switch -c )": "the repository %s is on a detached commit: create a branch before launching (git -C %s switch -c )", + "pas de physique (%s/) dans le dépôt %s": "no physics (%s/) in the repository %s", + "%s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP": "%s does not read the physics of the campaign (CANOP_PHYSICS_DIR): rebuild canoP", + "aucun run soumis sans fichier dans %s": "no run submitted without any file in %s", + "scancel a échoué : %s": "scancel failed: %s", + "Refusé : scancel a échoué (%s), rien n'a été supprimé.": "Refused: scancel failed (%s), nothing was deleted.", + "Run %s supprimé.": "Run %s deleted.", + "durée non fixée": "time not set", + "partition par défaut": "default partition", + "Ce run est encore %s dans Slurm : arrêtez-le d'abord.": "This run is still %s in Slurm: stop it first.", + "dossier inattendu : %s": "unexpected directory: %s", + "Refusé : %s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP": "Refused: %s does not read the physics of the campaign (CANOP_PHYSICS_DIR): rebuild canoP", + "Condition initiale seule (0 pas de temps, rien de commité), physique %s : %s. Elle s'affiche dans Visualisation à la fin.": "Initial condition alone (0 time steps, nothing committed), physics %s: %s. It is shown in View at the end.", + "Condition initiale seule (0 pas de temps, rien de commité), physique des sources : %s. Elle s'affiche dans Visualisation à la fin.": "Initial condition alone (0 time steps, nothing committed), physics of the sources: %s. It is shown in View at the end.", + "Condition initiale : %s, voir le Journal (%s)": "Initial condition: %s, see the Log (%s)", + "%d run(s) importé(s) dans %s ; %s": "%d run(s) imported into %s; %s", + "%d run(s) importé(s) dans %s": "%d run(s) imported into %s", + "Exemples fournis avec le code": "Examples provided with the code", + "Crée un nouveau run de cette campagne avec l'ini de l'éditeur": "Creates a new run of this campaign with the ini of the editor", + " — les modifications sont écrites dans {{ editor_run.ini }} ; « Lancer » relance ce run sur place.": " — edits are written to {{ editor_run.ini }}; “Run” relaunches this run in place.", + "Dernier lancement : canoP {{ editor_run.canop || '?' }}, physique {{ editor_run.physics }} (dépôt git de la campagne)": "Last launch: canoP {{ editor_run.canop || '?' }}, physics {{ editor_run.physics }} (git repository of the campaign)", + "Pas de run": "No run", + "{{ ini_path ? ' (base : ' + ini_path + ')' : '' }} — chargez cet ini dans une campagne pour pouvoir le lancer.": "{{ ini_path ? ' (base: ' + ini_path + ')' : '' }} — load this ini into a campaign to be able to run it.", + "Relance sur place le run dont l'ini est dans l'éditeur": "Relaunches in place the run whose ini is in the editor", + "Calcule seulement la condition initiale raffinée de l'ini de l'éditeur (0 pas de temps), sans lancer le run ni versionner, et l'affiche dans Visualisation": "Computes only the refined initial condition of the ini of the editor (0 time steps), without launching the run or versioning anything, and shows it in View", + "Nouvelle campagne": "New campaign", + "Importer les runs de _build/runs ({{ camp_import_n }})": "Import the runs of _build/runs ({{ camp_import_n }})", + "Préparer à nouveau ({{ camp_info.n_reset }})": "Prepare again ({{ camp_info.n_reset }})", + "Lancer les runs préparés ({{ camp_info ? camp_info.n_prepared : 0 }})": "Launch the prepared runs ({{ camp_info ? camp_info.n_prepared : 0 }})", + "Arrêter ({{ camp_info ? camp_info.n_alive : 0 }})": "Stop ({{ camp_info ? camp_info.n_alive : 0 }})", + "Dépôt git ": "Git repository ", + " — physique ": " — physics ", + "{{ camp_info.repo.n_physics_changed }} fichier(s) de la physique modifié(s), commités au prochain lancement": "{{ camp_info.repo.n_physics_changed }} file(s) of the physics modified, committed at the next launch", + "Arrêter {{ camp_info ? camp_info.n_alive : 0 }} run(s) ?": "Stop {{ camp_info ? camp_info.n_alive : 0 }} run(s)?", + "Supprimer le run {{ camp_detail ? camp_detail.short : '' }} ?": "Delete the run {{ camp_detail ? camp_detail.short : '' }}?", + "Supprimer la campagne {{ camp_name }} ?": "Delete the campaign {{ camp_name }}?", + "Préparer à nouveau {{ camp_info ? camp_info.n_reset : 0 }} run(s) ?": "Prepare again {{ camp_info ? camp_info.n_reset : 0 }} run(s)?", + "Lancer {{ camp_info ? camp_info.n_prepared : 0 }} run(s) ?": "Launch {{ camp_info ? camp_info.n_prepared : 0 }} run(s)?", + "run %s : %d nœuds (limite %d)": "run %s: %d nodes (limit %d)", + "run %s : %d cœurs (limite %d)": "run %s: %d cores (limit %d)", + "run %s : %d GPU (limite %d)": "run %s: %d GPUs (limit %d)", + "ligne %d : « section.clé = v1, v2, … » attendu": "line %d: “section.key = v1, v2, …” expected", + "ligne %d : section, clé ou valeurs manquantes": "line %d: missing section, key or values", + "paramètres : %s": "parameters: %s", + "refusé : %s": "refused: %s", + "Runs soumis, mais le commit du lancement a échoué : %s": "Runs submitted, but the commit of the launch failed: %s", + "Suppression incomplète de %s : %s": "Incomplete deletion of %s: %s", + "git %s : %s": "git %s: %s", + "git trop lent (%s)": "git too slow (%s)", + "Suppression incomplète : %s": "Incomplete deletion: %s", + "Refusé : %s": "Refused: %s", + "Run lancé, mais le commit du lancement a échoué : %s": "Run launched, but the commit of the launch failed: %s", + "Condition initiale impossible : %s": "Cannot compute the initial condition: %s", + "%s : job Slurm %s encore actif": "%s: Slurm job %s still active", + "Nœuds": "Nodes", + "Durée (--time)": "Time (--time)", + "GPU / processus": "GPUs / process", + "hors-campagne ne peut pas être supprimée": "hors-campagne cannot be deleted", + "Les runs soumis qui n'ont laissé aucun fichier (clone du dépôt, annulés avant de démarrer) redeviennent préparés": "The submitted runs that left no file (clone of the repository, cancelled before they started) become prepared again", + "Sélectionnez un run de la campagne.": "Select a run of the campaign.", + "Base : l'ini de l'éditeur ({{ ini_path || 'sans fichier' }}).": "Base: the ini of the editor ({{ ini_path || 'no file' }}).", + "Créer": "Create", + "Les runs de {{ camp_name }} en file ou en cours sont annulés (scancel). Leurs fichiers restent.": "The queued or running runs of {{ camp_name }} are cancelled (scancel). Their files stay.", + "Le run et ses sorties seront supprimés définitivement (annulé d'abord s'il est encore dans Slurm) :": "The run and its outputs will be deleted permanently (cancelled first if it is still in Slurm):", + "La campagne et ses {{ camp_info ? camp_info.n : 0 }} run(s), sorties comprises, seront supprimés définitivement :": "The campaign and its {{ camp_info ? camp_info.n : 0 }} run(s), outputs included, will be deleted permanently:", + "Les runs encore en file ou en cours dans Slurm sont d'abord annulés (scancel).": "The runs still queued or running in Slurm are cancelled first (scancel).", + "Les runs de {{ camp_name }} soumis qui n'ont laissé aucun fichier (ni journal, ni sortie : un clone du dépôt de la campagne, ou annulés avant de démarrer) redeviennent préparés. Leur lancement précédent reste dans leur document (history).": "The submitted runs of {{ camp_name }} that left no file (no log, no output: a clone of the repository of the campaign, or cancelled before they started) become prepared again. Their previous launch stays in their document (history).", + "Préparer": "Prepare", + "Chaque run préparé de la campagne {{ camp_name }} est soumis à Slurm avec les réglages du panneau Exécution (processus, options #SBATCH).": "Each prepared run of the campaign {{ camp_name }} is submitted to Slurm with the settings of the Execution panel (processes, #SBATCH options).", + "ligne %d : launch.%s inconnu (%s)": "line %d: unknown launch.%s (%s)", + "rien soumis (code %d)": "nothing submitted (code %d)", + "Refusé : scancel impossible (%s), rien n'a été supprimé.": "Refused: scancel could not run (%s), nothing was deleted.", + "%s : %s": "%s: %s", + "{{ camp_detail.n_outputs }} sortie(s){{ camp_detail.t ? ', dernière à t = ' + camp_detail.t : '' }}{{ camp_detail.launched ? ' — lancé le ' + camp_detail.launched : '' }}": "{{ camp_detail.n_outputs }} output(s){{ camp_detail.t ? ', last at t = ' + camp_detail.t : '' }}{{ camp_detail.launched ? ' — launched on ' + camp_detail.launched : '' }}", + "Version de canoP : pas encore lancé.": "canoP version: not launched yet.", + "Version de canoP : non enregistrée (lancé avant que le studio la note).": "canoP version: not recorded (launched before the studio noted it).", + "Ce run": "This run", + "Paramètres de ce run (différences avec l'ini de base)": "Parameters of this run (differences from the base ini)", + "Base : {{ camp_info.base }}": "Base: {{ camp_info.base }}", + "Nom (lettres, chiffres, - et _)": "Name (letters, digits, - and _)", + "Paramètres à faire varier": "Parameters to vary", + "une ligne par paramètre : section.clé = v1, v2, … (produit cartésien)": "one line per parameter: section.key = v1, v2, … (cartesian product)", + "%s : un entier est attendu (%r)": "%s: an integer is expected (%r)", + "{{ camp_detail.canop.n_modified }} fichier(s) modifié(s)": "{{ camp_detail.canop.n_modified }} modified file(s)", + "physique ": "physics ", + " (dépôt git de la campagne {{ camp_detail.physics.campaign }}, copiée dans canoP_physics/ du run)": " (git repository of the campaign {{ camp_detail.physics.campaign }}, copied into canoP_physics/ of the run)", + "Métriques (python project.py run -o metrics)": "Metrics (python project.py run -o metrics)", + "État": "State", + "Sorties": "Outputs", + "Visualiser": "View", + "Ce run dans les onglets Run (son ini), Journal et Visualisation": "This run in the Run (its ini), Log and View tabs", + "affiché dans la visualisation": "shown in the view", + # trame/canop_journal.py + "réussie": "succeeded", + "échouée": "failed", + "annulée": "cancelled", + "%.0f o": "%.0f B", + "%.1f ko": "%.1f kB", + "%.1f Mo": "%.1f MB", + "%.1f Go": "%.1f GB", + "compilation": "build", + "(pas de journal)": "(no log)", + "compilation en cours ou dernière (%s)": "running or last build (%s)", + "(journal vide ou introuvable : %s)": "(empty or missing log: %s)", + "{{ jr_nmatch }} ligne(s){{ jr_nmatch > jr_matches.length ? ' (' + jr_matches.length + ' affichées)' : '' }}": "{{ jr_nmatch }} line(s){{ jr_nmatch > jr_matches.length ? ' (' + jr_matches.length + ' shown)' : '' }}", + "expression invalide : %s": "invalid expression: %s", + "Simulation": "Simulation", + "Compilation": "Build", + "Rechercher": "Search", + "Suivre la fin": "Follow the end", + "Cliquez une ligne pour voir son contexte.": "Click a line to see its context.", + # trame/canop_view.py + "Visualisation du run rechargée": "View of the run reloaded", + "Rechargement de la visualisation impossible : %s: %s": "Cannot reload the view: %s: %s", + # trame/campaign_template/analysis.py + "Aucune valeur.": "No value.", + "{{ an_y }} en fonction de {{ an_x }}": "{{ an_y }} versus {{ an_x }}", + # trame/run_view/canoP_view.py + "Aucun résultat pour ce run : lancez-le depuis l'onglet Run ou la campagne.": "No results for this run: launch it from the Run tab or the campaign.", + "{{ n_cells }} cellules": "{{ n_cells }} cells", + "Champ": "Field", + "Palette": "Colormap", + "Maillage": "Mesh", + "Échelle auto": "Auto range", + "Vitesse": "Velocity", + "Flèches de la vitesse dans le plan (domaine 2D ou coupe 3D)": "Velocity arrows in the plane (2D domain or 3D slice)", + "Flèches": "Arrows", + "Nombre de flèches sur le grand côté": "Number of arrows along the longest side", + "Lire les pas de temps": "Play the time steps", + "images/s": "frames/s", + "Suivre le run": "Follow the run", + "Coupe": "Slice", + "Surface": "Surface", +} diff --git a/tools/trame/README.md b/tools/trame/README.md index 8fe83cb..753ca8d 100644 --- a/tools/trame/README.md +++ b/tools/trame/README.md @@ -10,14 +10,14 @@ canoP studio is a web application, built with [trame](https://kitware.github.io/ to prepare, build, run and look at canoP simulations from a browser (user documentation: `docs/user-guide/studio.md` and `campaigns.md`, ): -- **Paramètres**: load one of the ini files shipped with the code +- **Run**: load one of the ini files shipped with the code (`settings/`), edit it section by section or as text, and save it. Each key shows its type and its default value found in the C++ sources and in the physics written in Python (`physics/`), and, for the options of the model (`physics.initial_condition`, ...), their valid values. Keys that the code never reads are flagged, which usually means a typo. -- **Journal**: follow the build and run logs while they are written. -- **Visualisation**: show the results of the current run and follow them +- **Log**: follow the build and run logs while they are written. +- **View**: show the results of the current run and follow them while it runs. The view offers fields and color maps, the AMR mesh, streamlines of the velocity, a time slider, and slices or the outer surface in 3D. @@ -101,13 +101,13 @@ pykokkos-base and pykokkos itself (see the Compilation section of the main of the run) and commits the inis, views, `analysis.py` and signac files. The studio refuses to launch with an executable that does not read `CANOP_PHYSICS_DIR`. The `README.md` of each campaign tells how to - reproduce it from a clone of its repository (button "Préparer à nouveau" - of the Campagne tab). -- **Initial condition alone**: the button "Condition initiale" of the Run + reproduce it from a clone of its repository (button "Prepare again" + of the Campaign tab). +- **Initial condition alone**: the button "Initial condition" of the Run tab runs the ini of the editor without any time step (`simulation.nstepmax = 0`: canoP writes one output, the initial condition refined level by level up to `amr.max_refine`) and shows it in - the Visualisation. The run is not launched and nothing is committed: the + the View tab. The run is not launched and nothing is committed: the outputs go to `/condition_initiale/` (or `_campaigns//condition_initiale/` when the editor has no run), ignored by the repository of the campaign, with the current physics of @@ -144,8 +144,8 @@ it elsewhere, and run `tools/trame/canop-studio --setup` to reinstall it. The script prints the addresses to open, with a key: ``` -via code-server : http://127.0.0.1:8080/proxy/8090/index.html?secret=... -en direct : http://localhost:8090/index.html?secret=... +via code-server: http://127.0.0.1:8080/proxy/8090/index.html?secret=... +direct: http://localhost:8090/index.html?secret=... ``` - With code-server, open the first address, on the same host and port as diff --git a/tools/trame/campaign_template/analysis.py b/tools/trame/campaign_template/analysis.py index e55583b..d46f41d 100644 --- a/tools/trame/campaign_template/analysis.py +++ b/tools/trame/campaign_template/analysis.py @@ -17,9 +17,13 @@ panel(app) -> the right panel (trame / Vuetify widgets), showing state.an_result -`app` is the canop_app module (state, v3, html widgets...). +`app` is the canop_app module (state, v3, html widgets...). tr(text) shows a +French text in the language of the studio (translations in +tools/canop_i18n_en.py; a text without one is shown as written). """ +from canop_i18n import tr + def analyse(points, x, y): """Return the values shown in the panel; add here what this campaign needs (convergence, fits...).""" @@ -33,10 +37,10 @@ def draw(ax, points, result, x, y): def panel(app): """Build the right panel: a table of the points in state.an_result.""" v3, html = app.v3, app.html - html.Div("Aucune valeur.", v_if="!an_result || !an_result.lines.length", + html.Div(tr("Aucune valeur."), v_if="!an_result || !an_result.lines.length", classes="text-caption text-medium-emphasis pa-2") with html.Div(v_if="an_result && an_result.lines.length"): - html.Div("{{ an_y }} en fonction de {{ an_x }}", classes="text-subtitle-2 mb-1") + html.Div(tr("{{ an_y }} en fonction de {{ an_x }}"), classes="text-subtitle-2 mb-1") with v3.VTable(density="compact"): with html.Thead(): with html.Tr(): diff --git a/tools/trame/canop_analysis.py b/tools/trame/canop_analysis.py index f6a297c..37ca224 100644 --- a/tools/trame/canop_analysis.py +++ b/tools/trame/canop_analysis.py @@ -22,6 +22,8 @@ import os import shutil +from canop_i18n import tr + app = None # the canop_app module, set by bind() ANALYSIS_FILE = "analysis.py" @@ -97,7 +99,7 @@ def module(name): spec.loader.exec_module(mod) entry["module"] = mod except Exception as err: - text = "Erreur dans %s : %s: %s" % (path, type(err).__name__, err) + text = tr("Erreur dans %s : %s: %s") % (path, type(err).__name__, err) if entry.get("reported") != (mtime, text): entry["reported"] = (mtime, text) app.notify(text, "error") @@ -153,12 +155,12 @@ def refresh(): state.an_source = source(name) if not name: state.an_plot, state.an_result = None, None - state.an_info = "Choisissez une campagne." + state.an_info = tr("Choisissez une campagne.") return try: params, metrics, rows = collect(name) except Exception as err: - state.an_info = "Campagne %s : %s: %s" % (name, type(err).__name__, err) + state.an_info = tr("Campagne %s : %s: %s") % (name, type(err).__name__, err) return state.an_params, state.an_metrics = params, metrics if state.an_x not in params: @@ -167,10 +169,19 @@ def refresh(): preferred = [m for m in metrics if m not in ("n_outputs", "t_final", "mcups", "elapsed_s")] state.an_y = (preferred or metrics or [None])[0] done = sum(1 for r in rows if any(v is not None for k, v in r["metrics"].items() if k != "elapsed_s")) - state.an_info = "%s : %d run(s), %d avec des métriques" % (name, len(rows), done) + state.an_info = tr("%s : %d run(s), %d avec des métriques") % (name, len(rows), done) _redraw(rows) +def refresh_language(): + """Information line and graph in the language just chosen (called by canop_app.refresh_language). + + Only while the Analyse tab is shown: showing it refreshes them anyway. + """ + if app is not None and app.state.main_tab == "analysis": + refresh() + + def _on_campaign(): """Refresh when the campaign shown changes, if the Analyse tab is shown.""" if app.state.main_tab == "analysis": @@ -214,7 +225,7 @@ def _redraw(rows=None): state.an_result = mod.analyse(pts, state.an_x, state.an_y) except Exception as err: state.an_result = None - app.notify("analysis.py, analyse : %s: %s" % (type(err).__name__, err), "error") + app.notify(tr("analysis.py, analyse : %s: %s") % (type(err).__name__, err), "error") state.an_plot = _plot(pts, mod) if pts else None @@ -234,14 +245,14 @@ def _plot(pts, mod): try: mod.draw(ax, pts, state.an_result, state.an_x, state.an_y) except Exception as err: - app.notify("analysis.py, draw : %s: %s" % (type(err).__name__, err), "error") + app.notify(tr("analysis.py, draw : %s: %s") % (type(err).__name__, err), "error") if state.an_logx and min(xs) > 0: ax.set_xscale("log") if state.an_logy and min(ys) > 0: ax.set_yscale("log") ax.set_xlabel(state.an_x or "") ax.set_ylabel(state.an_y or "") - ax.set_title("%s : %s en fonction de %s" % (state.camp_name, state.an_y, state.an_x), fontsize=10) + ax.set_title(tr("%s : %s en fonction de %s") % (state.camp_name, state.an_y, state.an_x), fontsize=10) ax.grid(True, which="both", alpha=0.3) fig.tight_layout() buf = io.BytesIO() @@ -301,25 +312,26 @@ def analysis_tab(): _ui["stamp"] = _stamp(name) with v3.VContainer(fluid=True, classes="pa-3 d-flex flex-column", style="height: 100%"): with html.Div(classes="d-flex align-center ga-3 mb-2 flex-wrap"): - v3.VSelect(v_model=("camp_name",), items=("camp_names",), label="Campagne", density="compact", - hide_details=True, style="max-width: 260px", no_data_text="aucune campagne") - v3.VSelect(v_model=("an_x",), items=("an_params",), label="Paramètre (x)", density="compact", + v3.VSelect(v_model=("camp_name",), items=("camp_names",), label=tr("Campagne"), density="compact", + hide_details=True, style="max-width: 260px", no_data_text=tr("aucune campagne")) + v3.VSelect(v_model=("an_x",), items=("an_params",), label=tr("Paramètre (x)"), density="compact", hide_details=True, style="max-width: 220px") - v3.VSelect(v_model=("an_y",), items=("an_metrics",), label="Métrique (y)", density="compact", + v3.VSelect(v_model=("an_y",), items=("an_metrics",), label=tr("Métrique (y)"), density="compact", hide_details=True, style="max-width: 240px") v3.VCheckbox(v_model=("an_logx",), label="log x", density="compact", hide_details=True) v3.VCheckbox(v_model=("an_logy",), label="log y", density="compact", hide_details=True) - v3.VBtn(icon="mdi-refresh", click=ctrl.an_refresh, size="small", variant="text", title="Rafraîchir") + v3.VBtn(icon="mdi-refresh", click=ctrl.an_refresh, size="small", variant="text", + title=tr("Rafraîchir")) html.Div("{{ an_info }}", classes="text-caption mb-2") with html.Div(classes="d-flex ga-3", style="flex: 1 1 auto; min-height: 0"): with v3.VCard(variant="outlined", classes="pa-2 scroll-pane", style="flex: 1 1 55%; min-width: 0"): html.Img(v_if="an_plot", src=("an_plot",), style="max-width: 100%") - html.Div("Pas encore de métriques à tracer (runs terminés de la campagne, calculées par " - "« python project.py run -o metrics »).", v_if="!an_plot", + html.Div(tr("Pas encore de métriques à tracer (runs terminés de la campagne, calculées par " + "« python project.py run -o metrics »)."), v_if="!an_plot", classes="text-caption text-medium-emphasis pa-2") with v3.VCard(variant="outlined", classes="pa-2 scroll-pane", style="flex: 1 1 45%; min-width: 0"): try: mod.panel(app) except Exception as err: - html.Div("analysis.py, panel : %s: %s" % (type(err).__name__, err), classes="text-error") - html.Div("Analyse : {{ an_source }}", classes="text-caption mt-1 text-truncate") + html.Div(tr("analysis.py, panel : %s: %s") % (type(err).__name__, err), classes="text-error") + html.Div(tr("Analyse : {{ an_source }}"), classes="text-caption mt-1 text-truncate") diff --git a/tools/trame/canop_app.py b/tools/trame/canop_app.py index 8f5dc14..943da5f 100644 --- a/tools/trame/canop_app.py +++ b/tools/trame/canop_app.py @@ -23,6 +23,8 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import canop_core as core # noqa: E402 +import canop_i18n as i18n # noqa: E402 +from canop_i18n import tr, tr_js # noqa: E402 import canop_fields # noqa: E402 import canop_analysis # noqa: E402 import canop_campaign # noqa: E402 @@ -190,16 +192,22 @@ def on_main_tab(main_tab, **_): canop_campaign.refresh() -@state.change("view_run") -def on_view_run(view_run, **_): - """Show another run: update its name and path, and load its results.""" - state.view_run_path = viewed_run_dir() +def view_run_label(view_run): + """Name of the run shown in the top bar: / for a run of a campaign, else its directory.""" parts = view_run.rstrip("/").split(os.sep) if view_run else [] ic = parts[-1:] == ["condition_initiale"] # the initial condition alone of a run (Run tab) if ic: parts = parts[:-1] - state.view_run_name = ("%s / %s" % (parts[-3], parts[-1][:8]) if len(parts) > 3 and parts[-2] == "workspace" - else (parts[-1] if parts else "")) + (" / condition initiale" if ic else "") + name = ("%s / %s" % (parts[-3], parts[-1][:8]) if len(parts) > 3 and parts[-2] == "workspace" + else (parts[-1] if parts else "")) + return tr("%s / condition initiale") % name if ic else name + + +@state.change("view_run") +def on_view_run(view_run, **_): + """Show another run: update its name and path, and load its results.""" + state.view_run_path = viewed_run_dir() + state.view_run_name = view_run_label(view_run) results.forget() state.has_data = False state.time_values = [] @@ -258,7 +266,7 @@ def load_ini(path=None): if path and not os.path.isabs(path): path = os.path.join(current_settings().source, path) if not os.path.isfile(path): - notify("Fichier introuvable : %s" % path, "error") + notify(tr("Fichier introuvable : %s") % path, "error") return with open(path, encoding="utf-8", errors="replace") as fd: text = fd.read() @@ -268,7 +276,7 @@ def load_ini(path=None): state.ini_dirty = False state.view_run = "" save_settings() - notify("Chargé : %s" % path, "success") + notify(tr("Chargé : %s") % path, "success") @ctrl.add("load_example") @@ -283,7 +291,7 @@ def save_ini(): """Write the ini of the editor to its path.""" path = os.path.expanduser(state.ini_path or "") if not path: - notify("Indiquez un chemin pour le fichier ini", "warning") + notify(tr("Indiquez un chemin pour le fichier ini"), "warning") return try: os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) @@ -291,12 +299,12 @@ def save_ini(): text = state.ini_text or "" fd.write(text if text.endswith("\n") else text + "\n") except OSError as err: - notify("Écriture impossible : %s" % err, "error") + notify(tr("Écriture impossible : %s") % err, "error") return state.ini_saved = state.ini_text state.ini_dirty = False save_settings() - notify("Enregistré : %s" % path, "success") + notify(tr("Enregistré : %s") % path, "success") @ctrl.add("set_param") @@ -323,7 +331,7 @@ def add_param(): section = (state.new_section or "").strip().lower() key = (state.new_key or "").strip() if not section or not key: - notify("Section et clé requises", "warning") + notify(tr("Section et clé requises"), "warning") return value = state.new_value or "" if value == "": @@ -373,18 +381,34 @@ def on_backend(s_kokkos_backend, **_): select_backend(s_kokkos_backend) +_kokkos = {"options": None} # core.kokkos_options of the sources, read by kokkos_choices + + +def kokkos_texts(): + """Menus of the Kokkos architectures and lines of the Slurm partitions, in the current language. + + {} until kokkos_choices has read the Kokkos sources (language_texts). + """ + o = _kokkos["options"] + if o is None: + return {} + none = [{"title": tr("aucune (défaut du compilateur)"), "value": ""}] + return { + "kokkos_arch_host_items": none + [{"title": "%s — %s" % (n, l), "value": n} for n, l in o["host"]], + "kokkos_arch_gpu_items": {b: none + [{"title": "%s — %s" % (n, l), "value": n} for n, l in o.get(b, [])] + for b in core.GPU_BACKENDS}, + "slurm_partitions": core.slurm_partitions_text(), # sinfo is read once + } + + def kokkos_choices(source): """Fill the menus of the Kokkos backend and architectures, and the list of Slurm partitions. The architectures are read in the Kokkos sources. """ - o = core.kokkos_options(source) - none = [{"title": "aucune (défaut du compilateur)", "value": ""}] - state.kokkos_backends = o["backends"] - state.kokkos_arch_host_items = none + [{"title": "%s — %s" % (n, l), "value": n} for n, l in o["host"]] - state.kokkos_arch_gpu_items = {b: none + [{"title": "%s — %s" % (n, l), "value": n} for n, l in o.get(b, [])] - for b in core.GPU_BACKENDS} - state.slurm_partitions = core.slurm_partitions_text() + _kokkos["options"] = core.kokkos_options(source) + state.kokkos_backends = _kokkos["options"]["backends"] + state.update(kokkos_texts()) @ctrl.add("rescan_code") @@ -392,7 +416,7 @@ def rescan_code(): """Scan the C++ sources and the physics again.""" _code_cache.update(dir=None, cpp={}, physics={}) refresh_sections() - notify("%d paramètres trouvés dans le code" % len(code_parameters()), "success") + notify(tr("%d paramètres trouvés dans le code") % len(code_parameters()), "success") # -------------------------------------------------------------------------- @@ -459,13 +483,13 @@ def confirm_delete(): state.delete_dialog = False kind = state.delete_kind if driver.busy("build") or driver.busy("run"): - notify("Une compilation ou un run est en cours : arrêtez-le d'abord.", "error") + notify(tr("Une compilation ou un run est en cours : arrêtez-le d'abord."), "error") return settings = current_settings() path = delete_target(kind) if kind == "build" and os.path.isdir(path) and os.listdir(path) and not any( os.path.exists(os.path.join(path, f)) for f in ("CMakeCache.txt", core.BUILD_LOG, "runs")): - notify("Refusé : %s ne ressemble pas à un répertoire de build canoP." % path, "error") + notify(tr("Refusé : %s ne ressemble pas à un répertoire de build canoP.") % path, "error") return ok, msg = core.clear_directory(path, settings.source) notify(msg, "success" if ok else "error") @@ -488,7 +512,7 @@ def restart_studio(): The page reloads itself when the server is back. Builds and runs already started keep going. """ - notify("Mise à jour du studio, la page va se recharger…", "info") + notify(tr("Mise à jour du studio, la page va se recharger…"), "info") def _exec(): sys.stdout.flush() @@ -533,9 +557,9 @@ def update_jobs(): state[kind + "_log_path"] = job.log before = _previous_states.get(kind) if before in ("running", "pending") and st not in ("running", "pending"): - label = "Compilation" if kind == "build" else "Simulation" + text = tr("Compilation : %s") if kind == "build" else tr("Simulation : %s") colors = {"finished": "success", "cancelled": "warning"} - notify("%s : %s" % (label, st), colors.get(st, "error")) + notify(text % st, colors.get(st, "error")) # st: state of the job, not translated if kind == "build": state.executable = current_settings().executable() or "" elif state.follow: @@ -727,36 +751,36 @@ def reload_fields(): try: if fields_changed: importlib.reload(canop_fields) - names.append("champs dérivés") + names.append(tr("champs dérivés")) if campaign_changed: importlib.reload(canop_campaign) canop_campaign.bind(sys.modules[__name__]) - names.append("campagne") + names.append(tr("campagne")) if view_changed: importlib.reload(canop_view) setup_view_module() - names.append("visualisation") + names.append(tr("visualisation")) if journal_changed: importlib.reload(canop_journal) canop_journal.bind(sys.modules[__name__]) - names.append("journal") + names.append(tr("journal")) if analysis_changed: importlib.reload(canop_analysis) canop_analysis.bind(sys.modules[__name__]) - names.append("analyse") + names.append(tr("analyse")) if campaign_changed or view_changed or journal_changed or analysis_changed: build_ui() except Exception as err: - notify("Rechargement impossible : %s: %s" % (type(err).__name__, err), "error") + notify(tr("Rechargement impossible : %s: %s") % (type(err).__name__, err), "error") return _fields_module["error"] = None results.data_key = None # recompute the derived fields if results.reader is not None and state.has_data: update_view() if _fields_module["error"]: - notify("Erreur dans canop_fields.py : %s" % _fields_module["error"], "error") + notify(tr("Erreur dans canop_fields.py : %s") % _fields_module["error"], "error") else: - notify("Rechargé : %s" % ", ".join(names), "success") + notify(tr("Rechargé : %s") % ", ".join(names), "success") def surface(data): @@ -907,11 +931,11 @@ def load_results(go_last=True, reset_camera=False, quiet=False): changed = results.refresh() except Exception as err: # partially written file if not quiet: - notify("Lecture impossible : %s" % err, "error") + notify(tr("Lecture impossible : %s") % err, "error") return if results.reader is None: if not quiet: - notify("Pas encore de sortie dans %s" % viewed_run_dir(), "warning") + notify(tr("Pas encore de sortie dans %s") % viewed_run_dir(), "warning") return first = not state.has_data if first: @@ -1005,10 +1029,51 @@ def _on_usr1(): # -------------------------------------------------------------------------- +def language_texts(): + """State values that hold texts of the current language (recomputed when it changes).""" + return { + "build_launchers": [{"title": tr("ce nœud (direct)"), "value": "direct"}, + {"title": tr("un nœud de calcul (job Slurm, sbatch)"), "value": "sbatch"}], + **kokkos_texts(), # menus of the Kokkos architectures, Slurm partitions + } + + +def refresh_language(): + """Texts of the state in the language just chosen, in the studio and its modules.""" + state.update(language_texts()) + state.view_run_name = view_run_label(state.view_run) + for module in (canop_campaign, canop_journal, canop_analysis, canop_view): + refresh = getattr(module, "refresh_language", None) + if refresh: + refresh() + + +@state.change("s_language") +def on_language(s_language, **_): + """Another language chosen: the texts of the state and the interface are rebuilt in it.""" + if s_language == i18n.language(): + return + i18n.set_language(s_language) + refresh_language() + save_settings() + # rebuilt once this update of the page is handled, as the reloads of the view are (canop_view): a + # rebuild inside the handling of the update did not reach the page that asked for it the first time + asyncio.get_running_loop().call_soon(_rebuild_ui) + + +def _rebuild_ui(): + """Rebuild the interface and push it to the open pages.""" + with state: + build_ui() + + def initial_state(source_override=None): """Initial state of the page, from the saved settings (source_override: other sources).""" saved = load_settings() settings = core.Settings.from_dict(saved.get("settings")) + if saved.get("settings") and "language" not in saved["settings"]: + settings.language = "fr" # saved before the choice of the language: the studio was in French + i18n.set_language(settings.language) if source_override: settings.source_dir = source_override for k, v in settings.to_dict().items(): @@ -1018,12 +1083,11 @@ def initial_state(source_override=None): { "dims": [{"title": "%dD (canoP_%dd)" % (d, d), "value": d} for d in core.DIMS], "launchers": core.LAUNCHERS, - "build_launchers": [{"title": "ce nœud (direct)", "value": "direct"}, - {"title": "un nœud de calcul (job Slurm, sbatch)", "value": "sbatch"}], "gpu_requests": list(core.GPU_REQUESTS), "kokkos_backends": ["OpenMP"], "kokkos_arch_host_items": [], "kokkos_arch_gpu_items": {}, "slurm_partitions": [], "build_dir_resolved": "", "kokkos_is_gpu": False, "examples": core.example_inis(settings.source), + **language_texts(), "example_choice": None, "ini_path": "", # the editor starts empty: load an example, an ini or a run of a campaign "ini_text": "", @@ -1113,105 +1177,109 @@ def initial_state(source_override=None): def settings_panel(): """Build the settings panel of the drawer: code and build, execution, campaign limits.""" with v3.VExpansionPanels(multiple=True, v_model=("open_panels", [0, 1]), variant="accordion"): - with v3.VExpansionPanel(title="Code et compilation"): + with v3.VExpansionPanel(title=tr("Code et compilation")): with v3.VExpansionPanelText(): - v3.VTextField(label="Sources canoP", v_model=("s_source_dir",), density="compact", + v3.VTextField(label=tr("Sources canoP"), v_model=("s_source_dir",), density="compact", hide_details=True, classes="mb-2") - v3.VTextField(label="Répertoire de build", v_model=("s_build_dir",), density="compact", + v3.VTextField(label=tr("Répertoire de build"), v_model=("s_build_dir",), density="compact", placeholder="/_build", persistent_placeholder=True, hide_details=True, classes="mb-2") - v3.VSelect(label="Dimension (exécutable)", v_model=("s_dim",), items=("dims",), density="compact", - hide_details=True, classes="mb-2") - html.Div("Le modèle de la physique (physics//, en Python avec pykokkos) se choisit dans " - "l'ini : simulation.model.", classes="text-caption mb-2") - v3.VSelect(label="Backend Kokkos", v_model=("s_kokkos_backend",), items=("kokkos_backends",), + v3.VSelect(label=tr("Dimension (exécutable)"), v_model=("s_dim",), items=("dims",), + density="compact", hide_details=True, classes="mb-2") + html.Div(tr("Le modèle de la physique (physics/<modèle>/, en Python avec pykokkos) se choisit " + "dans l'ini : simulation.model."), classes="text-caption mb-2") + v3.VSelect(label=tr("Backend Kokkos"), v_model=("s_kokkos_backend",), items=("kokkos_backends",), density="compact", hide_details=True, classes="mb-2") - v3.VAutocomplete(label="Architecture CPU (Kokkos_ARCH)", v_model=("s_kokkos_arch_host",), + v3.VAutocomplete(label=tr("Architecture CPU (Kokkos_ARCH)"), v_model=("s_kokkos_arch_host",), items=("kokkos_arch_host_items",), density="compact", hide_details=True, classes="mb-2", v_if="kokkos_arch_host_items.length > 1") - v3.VAutocomplete(label="Architecture GPU (Kokkos_ARCH)", v_model=("s_kokkos_arch_gpu",), + v3.VAutocomplete(label=tr("Architecture GPU (Kokkos_ARCH)"), v_model=("s_kokkos_arch_gpu",), items=("kokkos_arch_gpu_items[s_kokkos_backend] || []",), density="compact", hide_details=True, classes="mb-2", v_if="kokkos_is_gpu && (kokkos_arch_gpu_items[s_kokkos_backend] || []).length > 1") - html.Div("Kokkos (partagé) et pykokkos sont construits avec canoP pour ce backend et ces " - "architectures (GPU : celle du GPU des runs, ex. AMPERE80 pour un A100). L'environnement, " - "les options CMake et les options Slurm des runs sont propres à chaque backend : ils " - "changent avec lui.", classes="text-caption mb-2") - html.Div("Build de cette variante : {{ build_dir_resolved }}", classes="text-caption mb-2", + html.Div(tr("Kokkos (partagé) et pykokkos sont construits avec canoP pour ce backend et ces " + "architectures (GPU : celle du GPU des runs, ex. AMPERE80 pour un A100). L'environnement, " + "les options CMake et les options Slurm des runs sont propres à chaque backend : ils " + "changent avec lui."), classes="text-caption mb-2") + html.Div(tr("Build de cette variante : {{ build_dir_resolved }}"), classes="text-caption mb-2", style="word-break: break-all") - v3.VTextarea(label=("'Environnement ' + s_kokkos_backend + ' (modules…)'",), v_model=("s_env_setup",), - rows=5, density="compact", hide_details=True, classes="mb-2 mono") - v3.VTextarea(label=("'Options CMake ' + s_kokkos_backend",), v_model=("s_cmake_options",), rows=3, - auto_grow=True, density="compact", hide_details=True, classes="mb-2 mono") - html.Div("Le backend et les architectures de Kokkos viennent des menus ci-dessus : le studio retire " - "-DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… et -DKALYPSSO_CORE_KOKKOS_BUILD de ces " - "options.", classes="text-caption mb-2") - v3.VTextField(label="Jobs de compilation", v_model=("s_build_jobs",), type="number", + # labels with the backend: a template of the current language, %s replaced in the page + v3.VTextarea(label=("%s.replace('%%s', s_kokkos_backend)" % tr_js("Environnement %s (modules…)"),), + v_model=("s_env_setup",), rows=5, density="compact", hide_details=True, + classes="mb-2 mono") + v3.VTextarea(label=("%s.replace('%%s', s_kokkos_backend)" % tr_js("Options CMake %s"),), + v_model=("s_cmake_options",), rows=3, auto_grow=True, density="compact", + hide_details=True, classes="mb-2 mono") + html.Div(tr("Le backend et les architectures de Kokkos viennent des menus ci-dessus : le studio " + "retire -DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… et -DKALYPSSO_CORE_KOKKOS_BUILD " + "de ces options."), classes="text-caption mb-2") + v3.VTextField(label=tr("Jobs de compilation"), v_model=("s_build_jobs",), type="number", density="compact", hide_details=True, classes="mb-2", - title="sur un nœud de calcul : les cœurs demandés (--cpus-per-task)") - v3.VSelect(label="Compiler sur", v_model=("s_build_launcher",), items=("build_launchers",), + title=tr("sur un nœud de calcul : les cœurs demandés (--cpus-per-task)")) + v3.VSelect(label=tr("Compiler sur"), v_model=("s_build_launcher",), items=("build_launchers",), density="compact", hide_details=True, classes="mb-2") - v3.VTextarea(label="Options Slurm de la compilation (#SBATCH)", v_model=("s_build_slurm_options",), + v3.VTextarea(label=tr("Options Slurm de la compilation (#SBATCH)"), v_model=("s_build_slurm_options",), rows=2, auto_grow=True, density="compact", hide_details=True, classes="mb-2 mono", v_show="s_build_launcher === 'sbatch'") - html.Div("Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda se compile sans GPU.", + html.Div(tr("Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda se compile sans GPU."), classes="text-caption mb-2", v_show="s_build_launcher === 'sbatch'") with html.Div(classes="d-flex ga-2"): - v3.VBtn("Configurer", click=ctrl.configure, variant="tonal", size="small", + v3.VBtn(tr("Configurer"), click=ctrl.configure, variant="tonal", size="small", disabled=("['running', 'pending'].includes(build_state)",)) - v3.VBtn("Compiler", click=ctrl.build, color="primary", size="small", + v3.VBtn(tr("Compiler"), click=ctrl.build, color="primary", size="small", prepend_icon="mdi-hammer-wrench", disabled=("['running', 'pending'].includes(build_state)",)) - html.Div("{{ executable ? 'Exécutable : ' + executable : 'Exécutable non compilé' }}", + html.Div(tr("{{ executable ? 'Exécutable : ' + executable : 'Exécutable non compilé' }}"), classes="text-caption mt-2", style="word-break: break-all") - v3.VBtn("Vider le répertoire de build", click=(ctrl.ask_delete, "['build']"), + v3.VBtn(tr("Vider le répertoire de build"), click=(ctrl.ask_delete, "['build']"), prepend_icon="mdi-delete-sweep", color="error", variant="tonal", size="small", classes="mt-3", disabled=("busy",)) - with v3.VExpansionPanel(title="Exécution"): + with v3.VExpansionPanel(title=tr("Exécution")): with v3.VExpansionPanelText(): - v3.VSelect(label="Lanceur", v_model=("s_launcher",), items=("launchers",), density="compact", + v3.VSelect(label=tr("Lanceur"), v_model=("s_launcher",), items=("launchers",), density="compact", hide_details=True, classes="mb-2") with html.Div(classes="d-flex ga-2 mb-2"): - v3.VTextField(label="Processus MPI", v_model=("s_nprocs",), type="number", + v3.VTextField(label=tr("Processus MPI"), v_model=("s_nprocs",), type="number", density="compact", hide_details=True) - v3.VTextField(label="Threads OpenMP", v_model=("s_omp_threads",), type="number", - density="compact", hide_details=True, hint="0 : non défini") + v3.VTextField(label=tr("Threads OpenMP"), v_model=("s_omp_threads",), type="number", + density="compact", hide_details=True, hint=tr("0 : non défini")) with html.Div(classes="d-flex ga-2 mb-2", v_if="kokkos_is_gpu"): - v3.VTextField(label="GPU par processus", v_model=("s_gpus_per_task",), type="number", + v3.VTextField(label=tr("GPU par processus"), v_model=("s_gpus_per_task",), type="number", density="compact", hide_details=True, - title="avec --gres : GPU par nœud") - v3.VSelect(label="Demande Slurm", v_model=("s_gpu_request",), items=("gpu_requests",), + title=tr("avec --gres : GPU par nœud")) + v3.VSelect(label=tr("Demande Slurm"), v_model=("s_gpu_request",), items=("gpu_requests",), density="compact", hide_details=True) - v3.VTextField(label="Arguments supplémentaires", v_model=("s_extra_args",), density="compact", + v3.VTextField(label=tr("Arguments supplémentaires"), v_model=("s_extra_args",), density="compact", hide_details=True, classes="mb-2") - v3.VTextarea(label=("'Options Slurm des runs ' + s_kokkos_backend + ' (#SBATCH)'",), + v3.VTextarea(label=("%s.replace('%%s', s_kokkos_backend)" + % tr_js("Options Slurm des runs %s (#SBATCH)"),), v_model=("s_slurm_options",), rows=4, density="compact", hide_details=True, classes="mono", v_show="s_launcher === 'sbatch'") - html.Div("Partitions de ce cluster (* : par défaut) :\n{{ slurm_partitions.join('\\n') }}", + html.Div(tr("Partitions de ce cluster (* : par défaut) :\n{{ slurm_partitions.join('\\n') }}"), v_if="slurm_partitions.length", classes="text-caption mt-1", style="white-space: pre-line", v_show="s_launcher === 'sbatch'") - html.Div("Garde-fous des campagnes lancées par un agent", classes="text-subtitle-2 mt-4") - html.Div("Au-delà, l'agent doit demander votre accord. Ces valeurs ne sont modifiables que " - "par vous.", classes="text-caption text-medium-emphasis mb-2") + html.Div(tr("Garde-fous des campagnes lancées par un agent"), classes="text-subtitle-2 mt-4") + html.Div(tr("Au-delà, l'agent doit demander votre accord. Ces valeurs ne sont modifiables que " + "par vous."), classes="text-caption text-medium-emphasis mb-2") with html.Div(classes="d-flex ga-2 mb-2"): - v3.VTextField(label="Runs par soumission", v_model=("s_camp_max_submit",), type="number", + v3.VTextField(label=tr("Runs par soumission"), v_model=("s_camp_max_submit",), type="number", density="compact", hide_details=True) - v3.VTextField(label="Runs par campagne", v_model=("s_camp_max_runs",), type="number", + v3.VTextField(label=tr("Runs par campagne"), v_model=("s_camp_max_runs",), type="number", density="compact", hide_details=True) with html.Div(classes="d-flex ga-2 mb-2"): - v3.VTextField(label="Nœuds par run", v_model=("s_camp_max_nodes",), type="number", + v3.VTextField(label=tr("Nœuds par run"), v_model=("s_camp_max_nodes",), type="number", density="compact", hide_details=True) - v3.VTextField(label="Cœurs par run", v_model=("s_camp_max_cores",), type="number", + v3.VTextField(label=tr("Cœurs par run"), v_model=("s_camp_max_cores",), type="number", density="compact", hide_details=True, - title="processus MPI x threads OpenMP") - v3.VTextField(label="Heures-cœur par soumission", v_model=("s_camp_max_core_hours",), type="number", - density="compact", hide_details=True, classes="mb-2", - title="somme sur les runs soumis de cœurs x durée Slurm demandée") + title=tr("processus MPI x threads OpenMP")) + v3.VTextField(label=tr("Heures-cœur par soumission"), v_model=("s_camp_max_core_hours",), + type="number", density="compact", hide_details=True, classes="mb-2", + title=tr("somme sur les runs soumis de cœurs x durée Slurm demandée")) with html.Div(classes="d-flex ga-2"): - v3.VTextField(label="GPU par run", v_model=("s_camp_max_gpus",), type="number", + v3.VTextField(label=tr("GPU par run"), v_model=("s_camp_max_gpus",), type="number", density="compact", hide_details=True) - v3.VTextField(label="Heures-GPU par soumission", v_model=("s_camp_max_gpu_hours",), + v3.VTextField(label=tr("Heures-GPU par soumission"), v_model=("s_camp_max_gpu_hours",), type="number", density="compact", hide_details=True) @@ -1222,28 +1290,28 @@ def params_tab(): canop_campaign.run_header() # launch / stop, examples, ini of the run (hot-reloaded) with v3.VRow(dense=True, align="center", classes="mt-1"): with v3.VCol(cols=12, md=4): - v3.VTextField(label="Filtrer les paramètres", v_model=("ini_filter",), density="compact", + v3.VTextField(label=tr("Filtrer les paramètres"), v_model=("ini_filter",), density="compact", prepend_inner_icon="mdi-magnify", clearable=True, hide_details=True) with v3.VCol(cols="auto"): - v3.VSwitch(label="Afficher les défauts du code", v_model=("show_defaults",), density="compact", - hide_details=True, color="primary") + v3.VSwitch(label=tr("Afficher les défauts du code"), v_model=("show_defaults",), + density="compact", hide_details=True, color="primary") with v3.VCol(cols="auto"): - v3.VChip("{{ ini_unknown }} clé(s) inconnue(s) du code", v_show="ini_unknown > 0", + v3.VChip(tr("{{ ini_unknown }} clé(s) inconnue(s) du code"), v_show="ini_unknown > 0", color="error", size="small", prepend_icon="mdi-alert") with v3.VCol(cols="auto"): - v3.VBtn("Rescanner le code", click=ctrl.rescan_code, size="small", variant="text", + v3.VBtn(tr("Rescanner le code"), click=ctrl.rescan_code, size="small", variant="text", prepend_icon="mdi-refresh") with v3.VRow(classes="mt-2"): with v3.VCol(cols=12, md=7): structured_editor() with v3.VCol(cols=12, md=5): v3.VTextarea( - label="Texte du fichier ini", + label=tr("Texte du fichier ini"), model_value=("ini_text",), rows=32, classes="mono", variant="outlined", - hint="Modifications prises en compte en quittant le champ", + hint=tr("Modifications prises en compte en quittant le champ"), persistent_hint=True, **{"__events": [("blur", "blur")]}, blur="ini_text = $event.target.value", @@ -1252,7 +1320,7 @@ def params_tab(): def structured_editor(): """Build the structured editor of the ini: one panel per section, and a form to add a key.""" - v3.VAlert("Chargez un fichier ini ou choisissez un exemple.", v_if="!ini_text", type="info", + v3.VAlert(tr("Chargez un fichier ini ou choisissez un exemple."), v_if="!ini_text", type="info", variant="tonal", density="compact") with v3.VExpansionPanels(multiple=True, v_model=("open_sections", []), v_if="ini_text"): with v3.VExpansionPanel( @@ -1264,7 +1332,7 @@ def structured_editor(): ): with v3.VExpansionPanelTitle(): html.Span("[{{ sec.name }}]", classes="font-weight-bold mono") - html.Span("{{ sec.keys.filter(k => k.set).length }} paramètre(s)", + html.Span(tr("{{ sec.keys.filter(k => k.set).length }} paramètre(s)"), classes="text-caption ml-3 text-medium-emphasis") v3.VIcon("mdi-alert", color="error", size="small", classes="ml-2", v_if="sec.keys.some(k => k.status.startsWith('UNKNOWN'))") @@ -1283,12 +1351,12 @@ def structured_editor(): with v3.VTooltip(activator="parent", location="top", max_width=520): html.Div("{{ item.description }}", v_if="item.description", classes="font-weight-medium mb-1") - html.Div("{{ item.value || item.default }} : {{ item.value_doc }}", + html.Div(tr("{{ item.value || item.default }} : {{ item.value_doc }}"), v_if="item.value_doc", classes="font-italic mb-1") html.Div("{{ item.status }}") - html.Div("type : {{ item.type }}", v_if="item.type") - html.Div("défaut : {{ item.default }}", v_if="item.default") - html.Div("valeurs : {{ item.choices }}", v_if="item.choices") + html.Div(tr("type : {{ item.type }}"), v_if="item.type") + html.Div(tr("défaut : {{ item.default }}"), v_if="item.default") + html.Div(tr("valeurs : {{ item.choices }}"), v_if="item.choices") html.Div("{{ item.files }}", v_if="item.files", classes="text-caption") with html.Td(): v3.VTextField( @@ -1311,13 +1379,13 @@ def structured_editor(): v3.VBtn(icon="mdi-close", v_if="item.set", size="x-small", variant="text", click=(ctrl.remove_param, "[sec.name, item.key]")) with v3.VCard(variant="outlined", classes="mt-3 pa-2", v_if="ini_text"): - html.Div("Ajouter un paramètre", classes="text-subtitle-2 mb-2") + html.Div(tr("Ajouter un paramètre"), classes="text-subtitle-2 mb-2") with html.Div(classes="d-flex ga-2 align-center"): - v3.VCombobox(label="Section", v_model=("new_section",), items=("code_sections",), + v3.VCombobox(label=tr("Section"), v_model=("new_section",), items=("code_sections",), density="compact", hide_details=True, style="max-width: 220px") - v3.VCombobox(label="Clé", v_model=("new_key",), items=("code_keys[new_section] || []",), + v3.VCombobox(label=tr("Clé"), v_model=("new_key",), items=("code_keys[new_section] || []",), density="compact", hide_details=True, style="max-width: 260px") - v3.VTextField(label="Valeur (défaut si vide)", v_model=("new_value",), density="compact", + v3.VTextField(label=tr("Valeur (défaut si vide)"), v_model=("new_value",), density="compact", hide_details=True) v3.VBtn(icon="mdi-plus", click=ctrl.add_param, size="small", color="primary") @@ -1394,11 +1462,16 @@ def build_ui(): layout.toolbar.density = "compact" # top line: title on the left, messages on the right with layout.toolbar: v3.VSpacer() - v3.VChip("compilation : {{ build_state }}", v_show="['running', 'pending'].includes(build_state)", + v3.VChip(tr("compilation : {{ build_state }}"), v_show="['running', 'pending'].includes(build_state)", size="small", color="primary", variant="flat", classes="mr-2") - v3.VChip("run affiché : {{ view_run_name }}", v_if="view_run", size="small", color="primary", + v3.VChip(tr("run affiché : {{ view_run_name }}"), v_if="view_run", size="small", color="primary", variant="tonal", classes="mr-3", prepend_icon="mdi-eye") + # language of the studio (canop_i18n), saved in the settings + with v3.VBtnToggle(v_model=("s_language",), mandatory=True, density="compact", variant="outlined", + divided=True, classes="mr-3", style="height: 28px"): + v3.VBtn("FR", value="fr", size="small") + v3.VBtn("EN", value="en", size="small") with layout.drawer as drawer: drawer.width = 380 settings_panel() @@ -1406,11 +1479,11 @@ def build_ui(): # 48 px for the top bar, 20 px for the footer of the layout, 38 px for the tabs and their border with html.Div(classes="d-flex flex-column", style="height: calc(100vh - 68px)"): with v3.VTabs(v_model=("main_tab",), density="compact", classes="border-b", style="flex: none"): - v3.VTab("Campagne", value="campaign", prepend_icon="mdi-chart-scatter-plot") - v3.VTab("Run", value="params", prepend_icon="mdi-file-cog") - v3.VTab("Journal", value="logs", prepend_icon="mdi-text-box-outline") - v3.VTab("Visualisation", value="view", prepend_icon="mdi-cube-outline") - v3.VTab("Analyse", value="analysis", prepend_icon="mdi-chart-line") + v3.VTab(tr("Campagne"), value="campaign", prepend_icon="mdi-chart-scatter-plot") + v3.VTab(tr("Run"), value="params", prepend_icon="mdi-file-cog") + v3.VTab(tr("Journal"), value="logs", prepend_icon="mdi-text-box-outline") + v3.VTab(tr("Visualisation"), value="view", prepend_icon="mdi-cube-outline") + v3.VTab(tr("Analyse"), value="analysis", prepend_icon="mdi-chart-line") with v3.VWindow(v_model=("main_tab",), classes="flex-grow-1", style="overflow: hidden; min-height: 0"): # same order as the tabs, so that the slide goes the same way with v3.VWindowItem(value="campaign", style="height: calc(100vh - 106px)"): @@ -1426,17 +1499,17 @@ def build_ui(): canop_analysis.analysis_tab() with v3.VDialog(v_model=("delete_dialog",), max_width=520): with v3.VCard(): - v3.VCardTitle("{{ delete_kind === 'build' ? 'Vider le répertoire de build ?' " - ": 'Supprimer tous les runs ?' }}") + v3.VCardTitle(tr("{{ delete_kind === 'build' ? 'Vider le répertoire de build ?' " + ": 'Supprimer tous les runs ?' }}")) with v3.VCardText(): - html.Div("Tout le contenu de ce répertoire sera supprimé définitivement :") + html.Div(tr("Tout le contenu de ce répertoire sera supprimé définitivement :")) html.Div("{{ delete_path }}", classes="mono my-2", style="word-break: break-all") - html.Div("Il faudra tout recompiler (configuration CMake comprise).", + html.Div(tr("Il faudra tout recompiler (configuration CMake comprise)."), v_if="delete_kind === 'build'", classes="text-caption") with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="delete_dialog = false", variant="text") - v3.VBtn("Supprimer", click=ctrl.confirm_delete, color="error", variant="flat") + v3.VBtn(tr("Annuler"), click="delete_dialog = false", variant="text") + v3.VBtn(tr("Supprimer"), click=ctrl.confirm_delete, color="error", variant="flat") v3.VSnackbar("{{ msg_text }}", v_model=("msg_show",), color=("msg_color",), timeout=6000, location="bottom right", multi_line=True) @@ -1574,7 +1647,7 @@ def main(): else: mcp_port = args.mcp_port or next((p for p in range(8190, 8300) if port_is_free("localhost", p)), 0) if args.mcp_port and not port_is_free("localhost", mcp_port): - sys.exit("canop-studio: le port MCP %d est déjà utilisé" % mcp_port) + sys.exit(tr("canop-studio: le port MCP %d est déjà utilisé") % mcp_port) if mcp_port: assistant = canop_assistant assistant.install(sys.modules[__name__], mcp_port) @@ -1593,7 +1666,7 @@ def main(): if explicit: port = int(args.port) if not port_is_free(host, port): - sys.exit("canop-studio: le port %d est déjà utilisé, choisissez-en un autre avec --port" % port) + sys.exit(tr("canop-studio: le port %d est déjà utilisé, choisissez-en un autre avec --port") % port) else: # the port of the previous start first, so that the address stays the same port_file = os.path.join(CONFIG_DIR, "port-%s" % socket.gethostname()) @@ -1604,29 +1677,29 @@ def main(): last = [] port = next((p for p in last + list(range(8090, 8200)) if port_is_free(host, p)), 0) if not port: - sys.exit("canop-studio: aucun port libre entre 8090 et 8199, utilisez --port") + sys.exit(tr("canop-studio: aucun port libre entre 8090 et 8199, utilisez --port")) with open(port_file, "w", encoding="utf-8") as out: out.write(str(port)) _ports.update(port=port, mcp=mcp_port) query = "index.html?secret=%s" % key - print("\n canoP studio, ouvrez dans votre navigateur :\n") + print(tr("\n canoP studio, ouvrez dans votre navigateur :\n")) proxy = code_server_proxy() if proxy: - print(" via code-server : %s%s" % (proxy.replace("{{port}}", str(port)), query)) - print(" (même adresse de base que celle où vous ouvrez code-server)\n") + print(tr(" via code-server : %s%s") % (proxy.replace("{{port}}", str(port)), query)) + print(tr(" (même adresse de base que celle où vous ouvrez code-server)\n")) elif os.path.exists(os.path.expanduser("~/.config/code-server")): - print(" (pas de code-server sur ce nœud, %s : pour passer par code-server," % socket.gethostname()) - print(" lancez canop-studio depuis un terminal de code-server, sur son nœud)\n") - print(" en direct : http://localhost:%d/%s" % (port, query)) - print(" (tunnel ssh : ssh -L %d:localhost:%d %s)\n" % (port, port, socket.gethostname())) - print(" La clé est gardée dans %s (supprimez-le pour en changer)." % key_file) - print(" Ctrl-C pour arrêter le serveur.\n") + print(tr(" (pas de code-server sur ce nœud, %s : pour passer par code-server,\n" + " lancez canop-studio depuis un terminal de code-server, sur son nœud)\n") % socket.gethostname()) + print(tr(" en direct : http://localhost:%d/%s") % (port, query)) + print(tr(" (tunnel ssh : ssh -L %d:localhost:%d %s)\n") % (port, port, socket.gethostname())) + print(tr(" La clé est gardée dans %s (supprimez-le pour en changer).") % key_file) + print(tr(" Ctrl-C pour arrêter le serveur.\n")) if assistant: - print(" Serveur MCP : http://127.0.0.1:%d/mcp (jeton dans %s)" + print(tr(" Serveur MCP : http://127.0.0.1:%d/mcp (jeton dans %s)") % (mcp_port, os.path.join(CONFIG_DIR, "mcp_token"))) - print(" Claude Code ouvert sur le dépôt canoP le trouve tout seul (.mcp.json).") - print(" Ailleurs, une fois, sur ce nœud :\n") + print(tr(" Claude Code ouvert sur le dépôt canoP le trouve tout seul (.mcp.json).")) + print(tr(" Ailleurs, une fois, sur ce nœud :\n")) print(" " + state.mcp_command + "\n") write_endpoint(port, mcp_port, query, proxy) sys.stdout.flush() diff --git a/tools/trame/canop_campaign.py b/tools/trame/canop_campaign.py index b1e3753..16ace87 100644 --- a/tools/trame/canop_campaign.py +++ b/tools/trame/canop_campaign.py @@ -64,6 +64,7 @@ import canop_core as core import signac +from canop_i18n import tr app = None # the canop_app module, set by bind() @@ -83,6 +84,14 @@ STATES = {"préparé": "grey", "en file": "orange", "en cours": "primary", "terminé": "success", "interrompu": "error", "échoué": "error"} + + +def state_label(state): + """A run state as shown in the page: the states themselves stay in French (signac data, MCP tools).""" + return {"préparé": tr("préparé"), "en file": tr("en file"), "en cours": tr("en cours"), + "terminé": tr("terminé"), "interrompu": tr("interrompu"), "échoué": tr("échoué")}.get(state, state) + + NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") _slurm = {"time": 0.0, "states": {}} @@ -139,6 +148,25 @@ def bind(application): start_watch() +def refresh_language(): + """Texts of the state in the language just chosen (canop_app.refresh_language). + + They are the table and details of the campaign shown (state labels, column titles, counts, origin of + the version of canoP), the preview of the sweep of a new campaign and the resources of the run of the + editor. + """ + if app is None: + return + try: + refresh() + except Exception: # signac or Slurm unavailable: the next refresh translates them + pass + _on_new_sweep() + _, job = editor_job() + if job is not None: + app.state.run_launch_effective = _effective_text(job) + + # -------------------------------------------------------------------------- # campaigns and jobs # -------------------------------------------------------------------------- @@ -269,24 +297,24 @@ def check_limits(name, job_ids): for job_id in job_ids: r = resources(proj.open_job(id=job_id)) if r["nodes"] > settings.camp_max_nodes: - problems.append("run %s : %d nœuds (limite %d)" % (job_id[:8], r["nodes"], settings.camp_max_nodes)) + problems.append(tr("run %s : %d nœuds (limite %d)") % (job_id[:8], r["nodes"], settings.camp_max_nodes)) if r["cores"] > settings.camp_max_cores: - problems.append("run %s : %d cœurs (limite %d)" % (job_id[:8], r["cores"], settings.camp_max_cores)) + problems.append(tr("run %s : %d cœurs (limite %d)") % (job_id[:8], r["cores"], settings.camp_max_cores)) if r["gpus"] > settings.camp_max_gpus: - problems.append("run %s : %d GPU (limite %d)" % (job_id[:8], r["gpus"], settings.camp_max_gpus)) + problems.append(tr("run %s : %d GPU (limite %d)") % (job_id[:8], r["gpus"], settings.camp_max_gpus)) if r["hours"] is None: unknown += 1 else: core_hours += r["cores"] * r["hours"] gpu_hours += r["gpus"] * r["hours"] if len(job_ids) > settings.camp_max_submit: - problems.append("%d runs à soumettre (limite %d)" % (len(job_ids), settings.camp_max_submit)) + problems.append(tr("%d runs à soumettre (limite %d)") % (len(job_ids), settings.camp_max_submit)) if gpu_hours > settings.camp_max_gpu_hours: - problems.append("%.0f heures-GPU demandées (limite %d)" % (gpu_hours, settings.camp_max_gpu_hours)) + problems.append(tr("%.0f heures-GPU demandées (limite %d)") % (gpu_hours, settings.camp_max_gpu_hours)) if core_hours > settings.camp_max_core_hours: - problems.append("%.0f heures-cœur demandées (limite %d)" % (core_hours, settings.camp_max_core_hours)) + problems.append(tr("%.0f heures-cœur demandées (limite %d)") % (core_hours, settings.camp_max_core_hours)) if unknown: - problems.append("%d run(s) sans durée Slurm (--time) : heures-cœur inconnues" % unknown) + problems.append(tr("%d run(s) sans durée Slurm (--time) : heures-cœur inconnues") % unknown) return problems @@ -359,19 +387,19 @@ def parse_sweep(text): if not line: continue if "=" not in line or "." not in line.split("=", 1)[0]: - raise ValueError("ligne %d : « section.clé = v1, v2, … » attendu" % n) + raise ValueError(tr("ligne %d : « section.clé = v1, v2, … » attendu") % n) name, values = line.split("=", 1) section, key = (s.strip() for s in name.split(".", 1)) # case kept (written as given) if section.lower() == "launch": section, key = "launch", key.lower() if key not in LAUNCH_KEYS: - raise ValueError("ligne %d : launch.%s inconnu (%s)" % (n, key, ", ".join(LAUNCH_KEYS))) + raise ValueError(tr("ligne %d : launch.%s inconnu (%s)") % (n, key, ", ".join(LAUNCH_KEYS))) vals = [parse_value(v) for v in values.split(",") if v.strip()] if not section or not key or not vals: - raise ValueError("ligne %d : section, clé ou valeurs manquantes" % n) + raise ValueError(tr("ligne %d : section, clé ou valeurs manquantes") % n) sweep.append(((section, key), vals)) if not sweep: - raise ValueError("aucun paramètre à faire varier") + raise ValueError(tr("aucun paramètre à faire varier")) return sweep @@ -491,7 +519,8 @@ def jobs_table(name): state = "préparé" sp = job.sp() rows.append({"id": job.id, "short": job.id[:8], "path": job.path, "state": state, "color": STATES[state], - "n_outputs": f["n_outputs"], "job_id": sid or f["job_id"], "slurm_id": sid, + "state_label": state_label(state), "n_outputs": f["n_outputs"], "job_id": sid or f["job_id"], + "slurm_id": sid, "metrics": _plain(job.doc.get("metrics")), "elapsed_s": round(f["elapsed"]) if f["elapsed"] is not None and f["elapsed"] >= 0 else None, "t": "%.4g" % f["last_time"] if f["last_time"] is not None else "", @@ -533,7 +562,7 @@ def refresh(): try: columns, rows = jobs_table(state.camp_name) except Exception as err: - app.notify("Campagne %s : %s: %s" % (state.camp_name, type(err).__name__, err), "error") + app.notify(tr("Campagne %s : %s: %s") % (state.camp_name, type(err).__name__, err), "error") return proj = project(state.camp_name) install_flow(proj.path) @@ -541,10 +570,12 @@ def refresh(): counts = {} for r in rows: counts[r["state"]] = counts.get(r["state"], 0) + 1 - state.camp_columns, state.camp_jobs = columns, rows + # the column titles of hors-campagne are keys of the parameters of its runs (summary): translated here only + titles = {"nom": tr("nom"), "créé le": tr("créé le")} + state.camp_columns, state.camp_jobs = [titles.get(c, c) for c in columns], rows state.camp_info = {"path": proj.path, "base": proj.doc.get("base_ini_path", ""), "created": proj.doc.get("created", ""), "n": len(rows), - "counts": ", ".join("%d %s" % (n, s) for s, n in counts.items()), + "counts": ", ".join("%d %s" % (n, state_label(s)) for s, n in counts.items()), "n_prepared": counts.get("préparé", 0), "n_alive": counts.get("en file", 0) + counts.get("en cours", 0), "outside": proj.doc.get("kind") == "outside", "n_reset": len(reset_names(rows)), @@ -665,8 +696,11 @@ def _on_new_sweep(**_): n *= len(vals) unknown = [("%s.%s" % name) for name, _ in sweep if core.ini_get(state.ini_text or "", name[0].lower(), name[1].lower()) is None] - state.camp_new_preview = "%d run(s)" % n + ( - " — absents de l'ini de l'éditeur (seront ajoutés) : %s" % ", ".join(unknown) if unknown else "") + if unknown: + state.camp_new_preview = tr("%d run(s) — absents de l'ini de l'éditeur (seront ajoutés) : %s") % ( + n, ", ".join(unknown)) + else: + state.camp_new_preview = tr("%d run(s)") % n def create_campaign(name, base_text, base_path, sweep_text): @@ -676,16 +710,16 @@ def create_campaign(name, base_text, base_path, sweep_text): """ name = (name or "").strip() if not NAME_RE.match(name): - return False, "nom de campagne : lettres, chiffres, - et _ uniquement", 0 + return False, tr("nom de campagne : lettres, chiffres, - et _ uniquement"), 0 path = os.path.join(root(), name) if os.path.exists(path): - return False, "la campagne %s existe déjà" % name, 0 + return False, tr("la campagne %s existe déjà") % name, 0 if not (base_text or "").strip(): - return False, "ini de base vide", 0 + return False, tr("ini de base vide"), 0 try: sweep = parse_sweep(sweep_text or "") except ValueError as err: - return False, "paramètres : %s" % err, 0 + return False, tr("paramètres : %s") % err, 0 os.makedirs(path) proj = signac.init_project(path) install_flow(path) @@ -697,9 +731,10 @@ def create_campaign(name, base_text, base_path, sweep_text): job = proj.open_job(sp).init() write_job_ini(name, proj, job) err = ensure_repo(path) - return True, "campagne %s créée : %d run(s) préparé(s)%s" % ( - name, len(proj), " ; " + err if err else ", physique copiée de canoP dans %s" % os.path.join(path, PHYSICS)), \ - len(proj) + if err: + return True, tr("campagne %s créée : %d run(s) préparé(s) ; %s") % (name, len(proj), err), len(proj) + return True, tr("campagne %s créée : %d run(s) préparé(s), physique copiée de canoP dans %s") % ( + name, len(proj), os.path.join(path, PHYSICS)), len(proj) def add_runs(name, sweep_text): @@ -709,11 +744,11 @@ def add_runs(name, sweep_text): """ proj = project(name) if proj.doc.get("kind") == "outside": - return False, "%s reçoit les runs de l'onglet Run : pas de balayage" % OUTSIDE, [] + return False, tr("%s reçoit les runs de l'onglet Run : pas de balayage") % OUTSIDE, [] try: sweep = parse_sweep(sweep_text or "") except ValueError as err: - return False, "paramètres : %s" % err, [] + return False, tr("paramètres : %s") % err, [] new = [] for sp in state_points(sweep): job = proj.open_job(sp) @@ -729,7 +764,7 @@ def add_runs(name, sweep_text): known[tuple(n)] += [v for v in vals if v not in known[tuple(n)]] proj.doc["sweep"] = [[list(n), v] for n, v in known.items()] already = len(list(state_points(sweep))) - len(new) - return True, "%d run(s) ajouté(s) à %s (%d déjà là)" % (len(new), name, already), new + return True, tr("%d run(s) ajouté(s) à %s (%d déjà là)") % (len(new), name, already), new def create(): @@ -754,16 +789,16 @@ def submit_campaign(name, only=None): """ settings = app.current_settings() if settings.launcher != "sbatch": - return False, "les campagnes se lancent avec le lanceur sbatch (panneau Exécution)", 0 + return False, tr("les campagnes se lancent avec le lanceur sbatch (panneau Exécution)"), 0 if not settings.executable(): - return False, "pas d'exécutable %s : compilez d'abord" % settings.exe_name, 0 + return False, tr("pas d'exécutable %s : compilez d'abord") % settings.exe_name, 0 proj = project(name) install_flow(proj.path) _slurm["time"] = 0.0 _, rows = jobs_table(name) todo = [r["id"] for r in rows if r["state"] == "préparé" and (only is None or r["id"] in only)] if not todo: - return False, "aucun run préparé à lancer dans %s" % name, 0 + return False, tr("aucun run préparé à lancer dans %s") % name, 0 # the physics of the campaign: committed if changed, its commit copied in each run (canoP_physics/, # relative: project.py starts canoP in the run directory); its versions at the top of each ini try: @@ -781,7 +816,7 @@ def submit_campaign(name, only=None): fd.write(with_versions(text, lines)) copy_physics(proj.path, physics, job.path) except (OSError, RuntimeError, subprocess.TimeoutExpired) as err: - return False, "refusé : %s" % err, 0 + return False, tr("refusé : %s") % err, 0 doc = launch_doc() doc["env_setup"] = doc["env_setup"].rstrip("\n") + "\n" + physics_env() doc["physics"] = physics @@ -797,13 +832,13 @@ def submit_campaign(name, only=None): _slurm["time"] = 0.0 if code != 0 or not submitted: last = [line for line in out.strip().splitlines() if line.strip()][-3:] - return False, "signac-flow submit : %s" % (" | ".join(last) or "rien soumis (code %d)" % code), 0 + return False, tr("signac-flow submit : %s") % (" | ".join(last) or tr("rien soumis (code %d)") % code), 0 try: launch_commit(proj.path, "lancement : %d run(s) de %s\n\ncanoP %s, physique %s\nruns : %s" % ( submitted, name, version.get("commit", "?"), physics, ", ".join(j[:8] for j in todo))) except (OSError, RuntimeError, subprocess.TimeoutExpired) as err: - app.notify("Runs soumis, mais le commit du lancement a échoué : %s" % err, "warning") - return True, "%d run(s) soumis avec signac-flow (python project.py submit), physique %s" % ( + app.notify(tr("Runs soumis, mais le commit du lancement a échoué : %s") % err, "warning") + return True, tr("%d run(s) soumis avec signac-flow (python project.py submit), physique %s") % ( submitted, physics[:9]), submitted @@ -840,11 +875,11 @@ def delete(): if not name: return if name == OUTSIDE: - app.notify("La campagne %s ne peut pas être supprimée (supprimez ses runs un par un)." % OUTSIDE, "error") + app.notify(tr("La campagne %s ne peut pas être supprimée (supprimez ses runs un par un).") % OUTSIDE, "error") return path = os.path.realpath(os.path.join(root(), name)) if os.path.dirname(path) != os.path.realpath(root()) or not os.path.isdir(os.path.join(path, ".signac")): - app.notify("Refusé : %s n'est pas une campagne." % path, "error") + app.notify(tr("Refusé : %s n'est pas une campagne.") % path, "error") return _slurm["time"] = 0.0 # fresh Slurm states _, rows = jobs_table(name) @@ -854,11 +889,11 @@ def delete(): q = subprocess.run(["scancel"] + alive, env=core.clean_env(), capture_output=True, text=True, timeout=30, check=False) except (OSError, subprocess.TimeoutExpired) as err: - app.notify("Refusé : scancel impossible (%s), rien n'a été supprimé." % err, "error") + app.notify(tr("Refusé : scancel impossible (%s), rien n'a été supprimé.") % err, "error") return if q.returncode != 0: - app.notify("Refusé : scancel a échoué (%s), rien n'a été supprimé." % (q.stderr.strip() or q.returncode), - "error") + app.notify(tr("Refusé : scancel a échoué (%s), rien n'a été supprimé.") + % (q.stderr.strip() or q.returncode), "error") return time.sleep(1.0) # let the cancelled jobs stop writing in their directories if state.view_run and os.path.realpath(state.view_run).startswith(path + os.sep): @@ -866,10 +901,14 @@ def delete(): try: shutil.rmtree(path) except OSError as err: - app.notify("Suppression incomplète de %s : %s" % (path, err), "error") + app.notify(tr("Suppression incomplète de %s : %s") % (path, err), "error") else: - app.notify("Campagne %s supprimée (%d run(s)%s)." % (name, len(rows), ", %d job(s) Slurm annulé(s)" - % len(alive) if alive else ""), "success") + if alive: + msg = tr("Campagne %s supprimée (%d run(s), %d job(s) Slurm annulé(s)).") % (name, len(rows), + len(alive)) + else: + msg = tr("Campagne %s supprimée (%d run(s)).") % (name, len(rows)) + app.notify(msg, "success") state.camp_name = "" refresh() @@ -967,13 +1006,20 @@ def canop_version(): variant=settings.variant) if info else {} +def _source_label(source): + """Origin of the version of canoP (canop_version) as shown: it stays in French in the job documents.""" + return {"compilation du studio": tr("compilation du studio"), + "sources au lancement (compilation hors du studio)": + tr("sources au lancement (compilation hors du studio)")}.get(source, source) + + def _version_text(v): """Version of canoP of a run as shown in its details, or None.""" if not v: return None text = {"commit": v.get("commit", ""), "short": v.get("short", ""), "branch": v.get("branch", ""), "modified": v.get("modified", []), "n_modified": len(v.get("modified", [])), - "source": v.get("source", "") + (" — build %s" % v["variant"] if v.get("variant") else ""), + "source": _source_label(v.get("source", "")) + (" — build %s" % v["variant"] if v.get("variant") else ""), "time": v.get("time", ""), "submodules": ", ".join("%s %s" % (os.path.basename(x["path"]), x.get("describe") or x["short"]) for x in v.get("submodules", []))} @@ -1085,8 +1131,8 @@ def _git(path, *args, check=True, binary=False, timeout=120): if q.returncode != 0: if check: err = q.stderr if isinstance(q.stderr, str) else q.stderr.decode(errors="replace") - raise RuntimeError("git %s : %s" % (args[0], " | ".join(err.strip().splitlines()[-2:]) - or "code %d" % q.returncode)) + raise RuntimeError(tr("git %s : %s") % (args[0], " | ".join(err.strip().splitlines()[-2:]) + or "code %d" % q.returncode)) return None return q.stdout if binary else q.stdout.rstrip() # rstrip: status lines start with a column @@ -1139,7 +1185,7 @@ def ensure_repo(path): name, v.get("commit", "?"), v.get("branch", "?"), "\nfichiers de la physique modifiés dans ces sources : " + ", ".join(changed) if changed else "")) except (OSError, RuntimeError, subprocess.TimeoutExpired) as err: - return "dépôt git de la campagne %s : %s" % (name, err) + return tr("dépôt git de la campagne %s : %s") % (name, err) _repo_cache.pop(path, None) return None @@ -1147,15 +1193,15 @@ def ensure_repo(path): def physics_commit(path): """Commit the physics of the campaign if it changed; return the last commit that changed it.""" if not _git(path, "symbolic-ref", "-q", "HEAD", check=False): - raise RuntimeError("le dépôt %s est sur un commit détaché : créez une branche avant de lancer " - "(git -C %s switch -c )" % (path, path)) + raise RuntimeError(tr("le dépôt %s est sur un commit détaché : créez une branche avant de lancer " + "(git -C %s switch -c )") % (path, path)) _git(path, "add", "-A", "--", PHYSICS) if _staged(path, PHYSICS): files = _git(path, "diff", "--cached", "--name-only", "--", PHYSICS).splitlines() _commit(path, "physique : %s" % _files_text(files, PHYSICS + "/"), PHYSICS) commit = _git(path, "log", "-1", "--format=%H", "--", PHYSICS) if not commit: - raise RuntimeError("pas de physique (%s/) dans le dépôt %s" % (PHYSICS, path)) + raise RuntimeError(tr("pas de physique (%s/) dans le dépôt %s") % (PHYSICS, path)) _repo_cache.pop(path, None) return commit @@ -1293,7 +1339,7 @@ def prepare_launch(campaign, proj): settings = app.current_settings() exe = settings.executable() if exe and not exe_reads_physics_dir(exe): - raise RuntimeError("%s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP" + raise RuntimeError(tr("%s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP") % settings.exe_name) err = ensure_repo(proj.path) if err: @@ -1301,7 +1347,7 @@ def prepare_launch(campaign, proj): try: commit = physics_commit(proj.path) except subprocess.TimeoutExpired as e: - raise RuntimeError("git trop lent (%s)" % e) from None + raise RuntimeError(tr("git trop lent (%s)") % e) from None return commit, canop_version() @@ -1342,8 +1388,8 @@ def reset_runs(name): for k in past: del job.doc[k] if not ids: - return False, "aucun run soumis sans fichier dans %s" % name, 0 - return True, "%d run(s) de %s à nouveau préparé(s)" % (len(ids), name), len(ids) + return False, tr("aucun run soumis sans fichier dans %s") % name, 0 + return True, tr("%d run(s) de %s à nouveau préparé(s)") % (len(ids), name), len(ids) def reset_prepared(): @@ -1383,8 +1429,8 @@ def stop_named(name): app.driver.jobs["run"].stop() _slurm["time"] = 0.0 if not ok: - return False, "scancel a échoué : %s" % err, 0 - return True, "%d run(s) arrêté(s)" % (len(ids) + len(direct)), len(ids) + len(direct) + return False, tr("scancel a échoué : %s") % err, 0 + return True, tr("%d run(s) arrêté(s)") % (len(ids) + len(direct)), len(ids) + len(direct) def stop_campaign(): @@ -1409,7 +1455,7 @@ def delete_job(job_id): return ok, err = _scancel(_alive_ids([row])) if not ok: - app.notify("Refusé : scancel a échoué (%s), rien n'a été supprimé." % err, "error") + app.notify(tr("Refusé : scancel a échoué (%s), rien n'a été supprimé.") % err, "error") return if row["running"] and not row["job_id"]: app.driver.jobs["run"].stop() @@ -1428,9 +1474,9 @@ def delete_job(job_id): try: job.remove() except OSError as err: - app.notify("Suppression incomplète : %s" % err, "error") + app.notify(tr("Suppression incomplète : %s") % err, "error") else: - app.notify("Run %s supprimé." % job_id[:8], "success") + app.notify(tr("Run %s supprimé.") % job_id[:8], "success") state.camp_selected, state.camp_detail = "", None _update_editor_run() refresh() @@ -1590,10 +1636,15 @@ def _load_run_launch(): "partition": _slurm_option(settings.slurm_options, "--partition", "-p") or "", "gpus_per_task": settings.gpus_per_task} state.run_launch_defaults = {k: str(sp.get(k, studio[k])) for k in RUN_LAUNCH_KEYS} + state.run_launch_effective = _effective_text(job) + + +def _effective_text(job): + """Resources requested from Slurm for a run, as shown in the Run tab.""" r = resources(job) - state.run_launch_effective = "%d processus x %d threads = %d cœurs%s, %s nœud(s), %s, %s" % ( + return tr("%d processus x %d threads = %d cœurs%s, %s nœud(s), %s, %s") % ( r["nprocs"], max(r["omp_threads"], 1), r["cores"], ", %d GPU" % r["gpus"] if r["gpus"] else "", r["nodes"], - r["time"] or "durée non fixée", r["partition"] or "partition par défaut") + r["time"] or tr("durée non fixée"), r["partition"] or tr("partition par défaut")) def _on_run_launch(run_launch=None, **_): @@ -1610,15 +1661,12 @@ def _on_run_launch(run_launch=None, **_): try: v = int(v) except ValueError: - app.notify("%s : un entier est attendu (%r)" % (k, v), "error") + app.notify(tr("%s : un entier est attendu (%r)") % (k, v), "error") continue clean[k] = v if clean != (_plain(job.doc.get("launch")) or {}): job.doc["launch"] = clean - r = resources(job) - app.state.run_launch_effective = "%d processus x %d threads = %d cœurs%s, %s nœud(s), %s, %s" % ( - r["nprocs"], max(r["omp_threads"], 1), r["cores"], ", %d GPU" % r["gpus"] if r["gpus"] else "", - r["nodes"], r["time"] or "durée non fixée", r["partition"] or "partition par défaut") + app.state.run_launch_effective = _effective_text(job) def launch_editor_run(): @@ -1626,21 +1674,21 @@ def launch_editor_run(): state = app.state campaign, job = editor_job() if job is None: - app.notify("Chargez d'abord cet ini dans une campagne (« Charger dans la campagne »).", "error") + app.notify(tr("Chargez d'abord cet ini dans une campagne (« Charger dans la campagne »)."), "error") return if app.driver.busy("run"): - app.notify("Un run de l'onglet Run tourne déjà : arrêtez-le d'abord.", "error") + app.notify(tr("Un run de l'onglet Run tourne déjà : arrêtez-le d'abord."), "error") return proj = project(campaign) _slurm["time"] = 0.0 _, rows = jobs_table(campaign) row = next((r for r in rows if r["id"] == job.id), None) if row and row["state"] in ("en file", "en cours"): - app.notify("Ce run est encore %s dans Slurm : arrêtez-le d'abord." % row["state"], "error") + app.notify(tr("Ce run est encore %s dans Slurm : arrêtez-le d'abord.") % state_label(row["state"]), "error") return text = state.ini_text or "" if not text.strip(): - app.notify("L'éditeur est vide.", "error") + app.notify(tr("L'éditeur est vide."), "error") return # the physics of the campaign: committed if changed, its commit copied in the run; the versions at # the top of the ini (also in the editor) @@ -1649,7 +1697,7 @@ def launch_editor_run(): text = with_versions(text, version_lines(campaign, version, physics)) copy_physics(proj.path, physics, job.path) except (OSError, RuntimeError, subprocess.TimeoutExpired) as err: - app.notify("Refusé : %s" % err, "error") + app.notify(tr("Refusé : %s") % err, "error") return _clear_outputs(campaign, job, [job_ini_text(proj, job), text]) job.doc["ini"] = text @@ -1672,7 +1720,7 @@ def launch_editor_run(): launch_commit(proj.path, "lancement : %s (run %s)\n\ncanoP %s, physique %s" % ( job_name(campaign, job), job.id[:8], version.get("commit", "?"), physics)) except (OSError, RuntimeError, subprocess.TimeoutExpired) as err: - app.notify("Run lancé, mais le commit du lancement a échoué : %s" % err, "warning") + app.notify(tr("Run lancé, mais le commit du lancement a échoué : %s") % err, "warning") state.log_tab = "run" _ic()["shown"] = False # the Visualisation follows the run launched _update_editor_run() @@ -1695,7 +1743,7 @@ def add_to_campaign(): state = app.state text = state.ini_text or "" if not text.strip(): - app.notify("L'éditeur est vide.", "error") + app.notify(tr("L'éditeur est vide."), "error") return target = state.camp_target or OUTSIDE proj = ensure_outside() if target == OUTSIDE else project(target) @@ -1716,7 +1764,7 @@ def add_to_campaign(): _update_editor_run() state.camp_name = target refresh() - app.notify("Run %s créé dans %s : vous pouvez le lancer." % (job.id[:8], target), "success") + app.notify(tr("Run %s créé dans %s : vous pouvez le lancer.") % (job.id[:8], target), "success") def stop_editor_run(): @@ -1724,7 +1772,7 @@ def stop_editor_run(): job = app.driver.jobs.get("run") if job is not None and job.active: job.stop() - app.notify("Run arrêté.", "warning") + app.notify(tr("Run arrêté."), "warning") app.update_jobs() @@ -1794,7 +1842,7 @@ def _prepare_ic_dir(ic_dir, job): """ real_root = os.path.realpath(root()) + os.sep if os.path.basename(ic_dir) != IC_DIR or not os.path.realpath(ic_dir).startswith(real_root): - raise OSError("dossier inattendu : %s" % ic_dir) + raise OSError(tr("dossier inattendu : %s") % ic_dir) os.makedirs(ic_dir, exist_ok=True) for name in os.listdir(ic_dir): if name in IC_KEEP: @@ -1841,27 +1889,27 @@ def generate_initial_condition(): state = app.state text = state.ini_text or "" if not text.strip(): - app.notify("L'éditeur est vide.", "error") + app.notify(tr("L'éditeur est vide."), "error") return if app.driver.busy("run"): - app.notify("Un run de l'onglet Run tourne déjà : arrêtez-le d'abord.", "error") + app.notify(tr("Un run de l'onglet Run tourne déjà : arrêtez-le d'abord."), "error") return try: campaign, job, ic_dir = ic_place() except Exception as err: # signac, git of a new hors-campagne - app.notify("Condition initiale impossible : %s" % err, "error") + app.notify(tr("Condition initiale impossible : %s") % err, "error") return settings = run_settings(job) if job is not None else app.current_settings() physics = ic_physics(campaign) exe = settings.executable() if physics and exe and not exe_reads_physics_dir(exe): - app.notify("Refusé : %s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP" + app.notify(tr("Refusé : %s ne lit pas la physique de la campagne (CANOP_PHYSICS_DIR) : recompilez canoP") % settings.exe_name, "error") return try: _prepare_ic_dir(ic_dir, job) except OSError as err: - app.notify("Condition initiale impossible : %s" % err, "error") + app.notify(tr("Condition initiale impossible : %s") % err, "error") return env = settings.env_setup.rstrip("\n") if physics: @@ -1878,15 +1926,18 @@ def generate_initial_condition(): ic["previous"] = state.view_run or "" ic.update(dir=ic_dir, job=app.driver.jobs.get("run"), ini_path=state.ini_path or "", shown=True) show_dir(ic_dir) - label = "%s / %s / condition initiale" % (campaign, job.id[:8]) if job is not None else \ - "%s / condition initiale" % campaign + label = tr("%s / %s / condition initiale") % (campaign, job.id[:8]) if job is not None else \ + tr("%s / condition initiale") % campaign if getattr(app.ctrl, "journal_set_run", None): app.ctrl.journal_set_run(os.path.join(ic_dir, core.RUN_LOG), label) _resend_journal() state.log_tab = "run" - app.notify("Condition initiale seule (0 pas de temps, rien de commité), physique %s : %s. Elle s'affiche " - "dans Visualisation à la fin." % (os.path.relpath(physics, root()) if physics else "des sources", - msg), "info") + if physics: + app.notify(tr("Condition initiale seule (0 pas de temps, rien de commité), physique %s : %s. Elle " + "s'affiche dans Visualisation à la fin.") % (os.path.relpath(physics, root()), msg), "info") + else: + app.notify(tr("Condition initiale seule (0 pas de temps, rien de commité), physique des sources : %s. " + "Elle s'affiche dans Visualisation à la fin.") % msg, "info") app.update_jobs() @@ -1902,12 +1953,12 @@ def _ic_check(): ic["job"] = None st = job.state if st != "finished": - app.notify("Condition initiale : %s, voir le Journal (%s)" % (st, os.path.join(ic["dir"], core.RUN_LOG)), + app.notify(tr("Condition initiale : %s, voir le Journal (%s)") % (st, os.path.join(ic["dir"], core.RUN_LOG)), "error") return if (app.state.view_run or "") == ic["dir"] and not app.state.has_data: app.load_results(go_last=True, reset_camera=True, quiet=True) - app.notify("Condition initiale prête : onglet Visualisation (%s)." % ic["dir"], "success") + app.notify(tr("Condition initiale prête : onglet Visualisation (%s).") % ic["dir"], "success") def ic_back(): @@ -1937,7 +1988,7 @@ def import_build_runs(): for src in old_build_runs(): alive = core.slurm_jobs_alive(src) if alive: - errors.append("%s : job Slurm %s encore actif" % (os.path.basename(src), ", ".join(alive))) + errors.append(tr("%s : job Slurm %s encore actif") % (os.path.basename(src), ", ".join(alive))) continue ini = sorted(glob.glob(os.path.join(glob.escape(src), "*.ini")))[0] with open(ini, encoding="utf-8", errors="replace") as fd: @@ -1950,7 +2001,7 @@ def import_build_runs(): os.makedirs(os.path.dirname(job.path), exist_ok=True) os.rename(src, job.path) except OSError as err: - errors.append("%s : %s" % (os.path.basename(src), err)) + errors.append(tr("%s : %s") % (os.path.basename(src), err)) continue job.init() job.doc["ini"] = text @@ -1959,8 +2010,10 @@ def import_build_runs(): app.state.view_run = job.path moved += 1 refresh() - app.notify("%d run(s) importé(s) dans %s%s" % (moved, OUTSIDE, (" ; " + " | ".join(errors)) if errors else ""), - "error" if errors else "success") + if errors: + app.notify(tr("%d run(s) importé(s) dans %s ; %s") % (moved, OUTSIDE, " | ".join(errors)), "error") + else: + app.notify(tr("%d run(s) importé(s) dans %s") % (moved, OUTSIDE), "success") # -------------------------------------------------------------------------- @@ -1974,46 +2027,48 @@ def run_header(): v3, html, ctrl = app.v3, app.html, app.ctrl with html.Div(classes="d-flex align-center ga-3 flex-wrap"): run_buttons() - v3.VAutocomplete(label="Exemples fournis avec le code", v_model=("example_choice",), items=("examples",), + v3.VAutocomplete(label=tr("Exemples fournis avec le code"), v_model=("example_choice",), items=("examples",), density="compact", hide_details=True, style="max-width: 380px; min-width: 260px", update_modelValue=(ctrl.load_example, "[$event]")) - v3.VSelect(v_if="ini_text", v_model=("camp_target",), items=("camp_names",), label="Campagne", + v3.VSelect(v_if="ini_text", v_model=("camp_target",), items=("camp_names",), label=tr("Campagne"), density="compact", hide_details=True, style="max-width: 220px; min-width: 160px") - v3.VBtn("Charger dans la campagne", v_if="ini_text", click=ctrl.add_to_campaign, size="small", + v3.VBtn(tr("Charger dans la campagne"), v_if="ini_text", click=ctrl.add_to_campaign, size="small", variant="tonal", prepend_icon="mdi-plus-box-multiple", - title="Crée un nouveau run de cette campagne avec l'ini de l'éditeur") + title=tr("Crée un nouveau run de cette campagne avec l'ini de l'éditeur")) with html.Div(classes="text-caption mono mt-2", style="word-break: break-all"): - html.Div("Éditeur vide : choisissez un exemple, ou « Charger dans l'éditeur » un run d'une campagne.", + html.Div(tr("Éditeur vide : choisissez un exemple, ou « Charger dans l'éditeur » un run d'une campagne."), v_if="!ini_text", classes="text-medium-emphasis") with html.Div(v_else_if="editor_run"): html.Span("Run {{ editor_run.campaign }} / {{ editor_run.short }}", classes="font-weight-bold") - html.Span(" — les modifications sont écrites dans {{ editor_run.ini }} ; « Lancer » relance ce run sur " - "place.") - html.Div("Dernier lancement : canoP {{ editor_run.canop || '?' }}, physique {{ editor_run.physics }} " - "(dépôt git de la campagne)", v_if="editor_run.physics", classes="text-medium-emphasis") + html.Span(tr(" — les modifications sont écrites dans {{ editor_run.ini }} ; « Lancer » relance ce run " + "sur place.")) + html.Div(tr("Dernier lancement : canoP {{ editor_run.canop || '?' }}, physique {{ editor_run.physics }} " + "(dépôt git de la campagne)"), v_if="editor_run.physics", classes="text-medium-emphasis") with html.Div(v_else=True): - html.Span("Pas de run", classes="font-weight-bold") - html.Span("{{ ini_path ? ' (base : ' + ini_path + ')' : '' }} — chargez cet ini dans une campagne pour " - "pouvoir le lancer.") + html.Span(tr("Pas de run"), classes="font-weight-bold") + html.Span(tr("{{ ini_path ? ' (base : ' + ini_path + ')' : '' }} — chargez cet ini dans une campagne " + "pour pouvoir le lancer.")) with html.Div(v_if="view_run && view_run.endsWith('/%s')" % IC_DIR, classes="d-flex align-center ga-2 mt-1"): v3.VIcon("mdi-grid", size="small", color="primary") - html.Span("Visualisation : la condition initiale seule (0 pas de temps, non versionnée), dans " - "{{ view_run }}", classes="text-caption mono", style="word-break: break-all") - v3.VBtn("Revenir au run", click=ctrl.ic_back, size="x-small", variant="tonal", prepend_icon="mdi-arrow-left") + html.Span(tr("Visualisation : la condition initiale seule (0 pas de temps, non versionnée), dans " + "{{ view_run }}"), classes="text-caption mono", style="word-break: break-all") + v3.VBtn(tr("Revenir au run"), click=ctrl.ic_back, size="x-small", variant="tonal", + prepend_icon="mdi-arrow-left") # execution of this run: the submission script, not the ini with html.Div(v_if="editor_run", classes="mt-3"): - html.Div("Exécution de ce run (script de soumission, pas l'ini) — vide : valeur par défaut, en gris", + html.Div(tr("Exécution de ce run (script de soumission, pas l'ini) — vide : valeur par défaut, en gris"), classes="text-subtitle-2 mb-1") with html.Div(classes="d-flex ga-2 flex-wrap align-center"): - for key, label, width in (("nprocs", "Processus MPI", 130), ("omp_threads", "Threads OpenMP", 140), - ("nodes", "Nœuds", 100), ("time", "Durée (--time)", 150), - ("partition", "Partition", 160), ("gpus_per_task", "GPU / processus", 130)): + for key, label, width in (("nprocs", tr("Processus MPI"), 130), ("omp_threads", tr("Threads OpenMP"), 140), + ("nodes", tr("Nœuds"), 100), ("time", tr("Durée (--time)"), 150), + ("partition", "Partition", 160), + ("gpus_per_task", tr("GPU / processus"), 130)): v3.VTextField(label=label, model_value=("run_launch.%s" % key,), v_if="kokkos_is_gpu" if key == "gpus_per_task" else None, update_modelValue="run_launch = Object.assign({}, run_launch, {%s: $event})" % key, placeholder=("run_launch_defaults.%s" % key,), persistent_placeholder=True, density="compact", hide_details=True, style="max-width: %dpx" % width) - html.Div("Demandé à Slurm : {{ run_launch_effective }}", v_if="run_launch_effective", + html.Div(tr("Demandé à Slurm : {{ run_launch_effective }}"), v_if="run_launch_effective", classes="text-caption mt-1") @@ -2021,17 +2076,17 @@ def run_buttons(): """Build the buttons of the Run tab (launch, initial condition, stop) and the run state.""" v3, html, ctrl = app.v3, app.html, app.ctrl with html.Div(classes="d-flex align-center ga-2"): - v3.VBtn("Lancer", click=ctrl.run_editor, prepend_icon="mdi-play", color="primary", size="small", + v3.VBtn(tr("Lancer"), click=ctrl.run_editor, prepend_icon="mdi-play", color="primary", size="small", disabled=("!executable || !editor_run || run_state === 'running' || run_state === 'pending'",), - title="Relance sur place le run dont l'ini est dans l'éditeur") - v3.VBtn("Condition initiale", click=ctrl.run_ic, prepend_icon="mdi-grid", color="primary", variant="tonal", - size="small", disabled=("!executable || !ini_text || run_state === 'running' || " - "run_state === 'pending'",), - title="Calcule seulement la condition initiale raffinée de l'ini de l'éditeur (0 pas de temps), " - "sans lancer le run ni versionner, et l'affiche dans Visualisation") - v3.VBtn("Arrêter", click=ctrl.stop_editor, prepend_icon="mdi-stop", color="error", variant="tonal", + title=tr("Relance sur place le run dont l'ini est dans l'éditeur")) + v3.VBtn(tr("Condition initiale"), click=ctrl.run_ic, prepend_icon="mdi-grid", color="primary", + variant="tonal", size="small", disabled=("!executable || !ini_text || run_state === 'running' || " + "run_state === 'pending'",), + title=tr("Calcule seulement la condition initiale raffinée de l'ini de l'éditeur (0 pas de temps), " + "sans lancer le run ni versionner, et l'affiche dans Visualisation")) + v3.VBtn(tr("Arrêter"), click=ctrl.stop_editor, prepend_icon="mdi-stop", color="error", variant="tonal", size="small", disabled=("run_state !== 'running' && run_state !== 'pending'",)) - v3.VChip("run : {{ run_state }}", v_show="run_state", size="small", + v3.VChip(tr("run : {{ run_state }}"), v_show="run_state", size="small", color=("{finished: 'success', running: 'primary', pending: 'warning', failed: 'error', " "cancelled: 'grey'}[run_state] || 'grey'",), variant="flat") @@ -2126,44 +2181,45 @@ def campaign_tab(): v3, html, ctrl = app.v3, app.html, app.ctrl with v3.VContainer(fluid=True, classes="pa-3 d-flex flex-column", style="height: 100%"): with html.Div(classes="d-flex align-center ga-2 mb-2"): - v3.VSelect(v_model=("camp_name",), items=("camp_names",), label="Campagne", density="compact", - hide_details=True, style="max-width: 320px", no_data_text="aucune campagne") - v3.VBtn(icon="mdi-refresh", click=ctrl.camp_refresh, size="small", variant="text", title="Rafraîchir") - v3.VBtn("Nouvelle campagne", click="camp_new_dialog = true", size="small", variant="tonal", + v3.VSelect(v_model=("camp_name",), items=("camp_names",), label=tr("Campagne"), density="compact", + hide_details=True, style="max-width: 320px", no_data_text=tr("aucune campagne")) + v3.VBtn(icon="mdi-refresh", click=ctrl.camp_refresh, size="small", variant="text", title=tr("Rafraîchir")) + v3.VBtn(tr("Nouvelle campagne"), click="camp_new_dialog = true", size="small", variant="tonal", prepend_icon="mdi-plus") - v3.VBtn("Supprimer", click="camp_delete_dialog = true", size="small", variant="tonal", color="error", + v3.VBtn(tr("Supprimer"), click="camp_delete_dialog = true", size="small", variant="tonal", color="error", prepend_icon="mdi-delete", disabled=("!camp_name || camp_name === camp_outside",), - title="hors-campagne ne peut pas être supprimée") - v3.VBtn("Importer les runs de _build/runs ({{ camp_import_n }})", v_if="camp_import_n", + title=tr("hors-campagne ne peut pas être supprimée")) + v3.VBtn(tr("Importer les runs de _build/runs ({{ camp_import_n }})"), v_if="camp_import_n", click=ctrl.camp_import, size="small", variant="tonal", prepend_icon="mdi-import") - v3.VBtn("Préparer à nouveau ({{ camp_info.n_reset }})", v_if="camp_info && camp_info.n_reset", + v3.VBtn(tr("Préparer à nouveau ({{ camp_info.n_reset }})"), v_if="camp_info && camp_info.n_reset", click="camp_reset_dialog = true", size="small", variant="tonal", prepend_icon="mdi-restore", - title="Les runs soumis qui n'ont laissé aucun fichier (clone du dépôt, annulés avant de " - "démarrer) redeviennent préparés") + title=tr("Les runs soumis qui n'ont laissé aucun fichier (clone du dépôt, annulés avant de " + "démarrer) redeviennent préparés")) v3.VSpacer() - v3.VBtn("Lancer les runs préparés ({{ camp_info ? camp_info.n_prepared : 0 }})", + v3.VBtn(tr("Lancer les runs préparés ({{ camp_info ? camp_info.n_prepared : 0 }})"), v_if="!camp_info || !camp_info.outside", click="camp_submit_dialog = true", size="small", color="primary", prepend_icon="mdi-rocket-launch", disabled=("!camp_info || !camp_info.n_prepared",)) - v3.VBtn("Arrêter ({{ camp_info ? camp_info.n_alive : 0 }})", click="camp_stop_dialog = true", + v3.VBtn(tr("Arrêter ({{ camp_info ? camp_info.n_alive : 0 }})"), click="camp_stop_dialog = true", size="small", color="error", variant="tonal", prepend_icon="mdi-stop", disabled=("!camp_info || !camp_info.n_alive",)) - html.Div("{{ camp_info.n }} run(s) : {{ camp_info.counts }} — {{ camp_info.path }}", v_if="camp_info", + html.Div(tr("{{ camp_info.n }} run(s) : {{ camp_info.counts }} — {{ camp_info.path }}"), v_if="camp_info", classes="text-caption mono", style="word-break: break-all") with html.Div(v_if="camp_info && camp_info.repo", classes="text-caption mb-2"): - html.Span("Dépôt git ", classes="font-weight-bold") + html.Span(tr("Dépôt git "), classes="font-weight-bold") html.Span("{{ camp_info.repo.branch }} {{ camp_info.repo.head_short }}", classes="mono", title=("camp_info.repo.head",)) - html.Span(" — physique ") + html.Span(tr(" — physique ")) html.Span("{{ camp_info.repo.physics_short }}", classes="mono", title=("camp_info.repo.physics",)) html.Span(" ({{ camp_info.repo.physics_dir }})", classes="mono text-medium-emphasis") - v3.VChip("{{ camp_info.repo.n_physics_changed }} fichier(s) de la physique modifié(s), commités au " - "prochain lancement", v_if="camp_info.repo.n_physics_changed", size="x-small", color="warning", - variant="tonal", classes="ml-1", title=("camp_info.repo.physics_changed.join('\\n')",)) - html.Div("Pas de dépôt git pour cette campagne (créé au prochain lancement).", + v3.VChip(tr("{{ camp_info.repo.n_physics_changed }} fichier(s) de la physique modifié(s), commités au " + "prochain lancement"), v_if="camp_info.repo.n_physics_changed", size="x-small", + color="warning", variant="tonal", classes="ml-1", + title=("camp_info.repo.physics_changed.join('\\n')",)) + html.Div(tr("Pas de dépôt git pour cette campagne (créé au prochain lancement)."), v_if="camp_info && !camp_info.repo", classes="text-caption text-medium-emphasis mb-2") - html.Div("Créez une campagne : l'ini de l'éditeur sert de base, et vous indiquez les paramètres à faire " - "varier.", v_if="!camp_names.length", classes="text-caption text-medium-emphasis") + html.Div(tr("Créez une campagne : l'ini de l'éditeur sert de base, et vous indiquez les paramètres à faire " + "varier."), v_if="!camp_names.length", classes="text-caption text-medium-emphasis") with html.Div(classes="d-flex ga-3", style="flex: 1 1 auto; min-height: 0", v_if="camp_info"): # jobs with v3.VCard(variant="outlined", classes="scroll-pane", style="flex: 1 1 60%; min-width: 0"): @@ -2172,7 +2228,7 @@ def campaign_tab(): with html.Tr(): html.Th("Run") html.Th("{{ c }}", v_for="c in camp_columns", key="c", classes="mono") - for title in ("État", "Sorties", "t"): + for title in (tr("État"), tr("Sorties"), "t"): html.Th(title) with html.Tbody(): with html.Tr(v_for="r in camp_jobs", key="r.id", click=(ctrl.camp_select_job, "[r.id]"), @@ -2181,34 +2237,34 @@ def campaign_tab(): with html.Td(classes="mono text-caption"): html.Span("{{ r.short }}") v3.VIcon("mdi-eye", v_if="r.path === view_run", size="x-small", color="primary", - classes="ml-1", title="affiché dans la visualisation") + classes="ml-1", title=tr("affiché dans la visualisation")) html.Td("{{ v }}", v_for="(v, i) in r.values", key="i", classes="mono") with html.Td(): - v3.VChip("{{ r.state }}", color=("r.color",), size="x-small", variant="flat") + v3.VChip("{{ r.state_label }}", color=("r.color",), size="x-small", variant="flat") html.Td("{{ r.n_outputs }}", classes="text-right") html.Td("{{ r.t }}", classes="mono text-right") # selected job with v3.VCard(variant="outlined", classes="pa-3 scroll-pane", style="flex: 1 1 40%; min-width: 0"): - html.Div("Sélectionnez un run de la campagne.", v_if="!camp_detail", + html.Div(tr("Sélectionnez un run de la campagne."), v_if="!camp_detail", classes="text-caption text-medium-emphasis") with html.Div(v_if="camp_detail"): with html.Div(classes="d-flex align-center ga-2 mb-1"): html.Span("{{ camp_detail.short }}", classes="text-subtitle-1 font-weight-bold mono") - v3.VChip("{{ camp_detail.state }}", color=("camp_detail.color",), size="small", + v3.VChip("{{ camp_detail.state_label }}", color=("camp_detail.color",), size="small", variant="flat") v3.VChip("job {{ camp_detail.job_id }}", v_if="camp_detail.job_id", size="small", variant="outlined") html.Div("{{ camp_detail.path }}", classes="text-caption mono mb-2", style="word-break: break-all") - html.Div("{{ camp_detail.n_outputs }} sortie(s){{ camp_detail.t ? ', dernière à t = ' + " - "camp_detail.t : '' }}" - "{{ camp_detail.launched ? ' — lancé le ' + camp_detail.launched : '' }}", + html.Div(tr("{{ camp_detail.n_outputs }} sortie(s){{ camp_detail.t ? ', dernière à t = ' + " + "camp_detail.t : '' }}" + "{{ camp_detail.launched ? ' — lancé le ' + camp_detail.launched : '' }}"), classes="text-caption mb-1") with html.Div(v_if="camp_detail.canop", classes="text-caption mb-2"): html.Span("canoP ", classes="font-weight-bold") html.Span("{{ camp_detail.canop.short }}", classes="mono", title=("camp_detail.canop.commit",)) html.Span(" ({{ camp_detail.canop.branch }})", v_if="camp_detail.canop.branch") - v3.VChip("{{ camp_detail.canop.n_modified }} fichier(s) modifié(s)", + v3.VChip(tr("{{ camp_detail.canop.n_modified }} fichier(s) modifié(s)"), v_if="camp_detail.canop.n_modified", size="x-small", color="warning", variant="tonal", classes="ml-1", title=("camp_detail.canop.modified.join('\\n')",)) @@ -2217,25 +2273,28 @@ def campaign_tab(): html.Div("{{ camp_detail.canop.source }}{{ camp_detail.canop.time ? ', ' + " "camp_detail.canop.time : '' }}", classes="text-medium-emphasis") with html.Div(v_if="camp_detail.physics", classes="text-caption mb-2"): - html.Span("physique ", classes="font-weight-bold") + html.Span(tr("physique "), classes="font-weight-bold") html.Span("{{ camp_detail.physics.short }}", classes="mono", title=("camp_detail.physics.commit",)) - html.Span(" (dépôt git de la campagne {{ camp_detail.physics.campaign }}, copiée dans " - "canoP_physics/ du run)") - html.Div("Version de canoP : {{ camp_detail.state === 'préparé' ? 'pas encore lancé' : " - "'non enregistrée (lancé avant que le studio la note)' }}.", v_if="!camp_detail.canop", + html.Span(tr(" (dépôt git de la campagne {{ camp_detail.physics.campaign }}, copiée dans " + "canoP_physics/ du run)")) + # state: the French run state, not its label + html.Div(tr("Version de canoP : pas encore lancé."), + v_if="!camp_detail.canop && camp_detail.state === 'préparé'", classes="text-caption text-medium-emphasis mb-2") + html.Div(tr("Version de canoP : non enregistrée (lancé avant que le studio la note)."), + v_else_if="!camp_detail.canop", classes="text-caption text-medium-emphasis mb-2") with html.Div(classes="d-flex ga-2 mb-3"): with v3.VBtn(click=(ctrl.camp_show, "[camp_detail.id]"), color="primary", size="small", - title="Ce run dans les onglets Run (son ini), Journal et Visualisation"): + title=tr("Ce run dans les onglets Run (son ini), Journal et Visualisation")): v3.VIcon("mdi-file-cog", size="small", classes="mr-1") v3.VIcon("mdi-text-box-outline", size="small", classes="mr-1") v3.VIcon("mdi-cube-outline", size="small", classes="mr-2") - html.Span("Visualiser") - v3.VBtn("Supprimer", click="camp_job_delete_dialog = true", size="small", + html.Span(tr("Visualiser")) + v3.VBtn(tr("Supprimer"), click="camp_job_delete_dialog = true", size="small", variant="tonal", color="error", prepend_icon="mdi-delete") - html.Div("{{ camp_info.outside ? 'Ce run' : " - "'Paramètres de ce run (différences avec l\\'ini de base)' }}", + html.Div(tr("Ce run"), v_if="camp_info.outside", classes="text-subtitle-2 mb-1") + html.Div(tr("Paramètres de ce run (différences avec l'ini de base)"), v_else=True, classes="text-subtitle-2 mb-1") with v3.VTable(density="compact"): with html.Tbody(): @@ -2243,92 +2302,92 @@ def campaign_tab(): html.Td("{{ p.name }}", classes="mono") html.Td("{{ p.value }}", classes="mono font-weight-bold") with html.Div(v_if="camp_detail.metrics && camp_detail.metrics.length", classes="mt-3"): - html.Div("Métriques (python project.py run -o metrics)", classes="text-subtitle-2 mb-1") + html.Div(tr("Métriques (python project.py run -o metrics)"), classes="text-subtitle-2 mb-1") with v3.VTable(density="compact"): with html.Tbody(): with html.Tr(v_for="m in camp_detail.metrics", key="m.name"): html.Td("{{ m.name }}", classes="mono") html.Td("{{ m.value }}", classes="mono") - html.Div("Base : {{ camp_info.base }}", v_if="camp_info.base", + html.Div(tr("Base : {{ camp_info.base }}"), v_if="camp_info.base", classes="text-caption mono mt-2", style="word-break: break-all") # new campaign with v3.VDialog(v_model=("camp_new_dialog",), max_width=640): with v3.VCard(): - v3.VCardTitle("Nouvelle campagne") + v3.VCardTitle(tr("Nouvelle campagne")) with v3.VCardText(): - html.Div("Base : l'ini de l'éditeur ({{ ini_path || 'sans fichier' }}).", classes="text-caption mb-3", - style="word-break: break-all") - v3.VTextField(v_model=("camp_new_name",), label="Nom (lettres, chiffres, - et _)", + html.Div(tr("Base : l'ini de l'éditeur ({{ ini_path || 'sans fichier' }})."), + classes="text-caption mb-3", style="word-break: break-all") + v3.VTextField(v_model=("camp_new_name",), label=tr("Nom (lettres, chiffres, - et _)"), density="compact", classes="mb-3") - v3.VTextarea(v_model=("camp_new_sweep",), label="Paramètres à faire varier", rows=5, + v3.VTextarea(v_model=("camp_new_sweep",), label=tr("Paramètres à faire varier"), rows=5, classes="mono", placeholder="hydro.cfl = 0.4, 0.6, 0.8\namr.level_max = 4, 5", persistent_placeholder=True, - hint="une ligne par paramètre : section.clé = v1, v2, … (produit cartésien)", + hint=tr("une ligne par paramètre : section.clé = v1, v2, … (produit cartésien)"), persistent_hint=True) html.Div("{{ camp_new_preview }}", classes="text-caption mt-3") with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_new_dialog = false", variant="text") - v3.VBtn("Créer", click=ctrl.camp_create, color="primary", variant="flat") + v3.VBtn(tr("Annuler"), click="camp_new_dialog = false", variant="text") + v3.VBtn(tr("Créer"), click=ctrl.camp_create, color="primary", variant="flat") # stop the campaign with v3.VDialog(v_model=("camp_stop_dialog",), max_width=520): with v3.VCard(): - v3.VCardTitle("Arrêter {{ camp_info ? camp_info.n_alive : 0 }} run(s) ?") + v3.VCardTitle(tr("Arrêter {{ camp_info ? camp_info.n_alive : 0 }} run(s) ?")) with v3.VCardText(): - html.Div("Les runs de {{ camp_name }} en file ou en cours sont annulés (scancel). Leurs fichiers " - "restent.") + html.Div(tr("Les runs de {{ camp_name }} en file ou en cours sont annulés (scancel). Leurs fichiers " + "restent.")) with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_stop_dialog = false", variant="text") - v3.VBtn("Arrêter", click=ctrl.camp_stop, color="error", variant="flat") + v3.VBtn(tr("Annuler"), click="camp_stop_dialog = false", variant="text") + v3.VBtn(tr("Arrêter"), click=ctrl.camp_stop, color="error", variant="flat") # delete one run with v3.VDialog(v_model=("camp_job_delete_dialog",), max_width=560): with v3.VCard(): - v3.VCardTitle("Supprimer le run {{ camp_detail ? camp_detail.short : '' }} ?") + v3.VCardTitle(tr("Supprimer le run {{ camp_detail ? camp_detail.short : '' }} ?")) with v3.VCardText(): - html.Div("Le run et ses sorties seront supprimés définitivement (annulé d'abord s'il est encore " - "dans Slurm) :") + html.Div(tr("Le run et ses sorties seront supprimés définitivement (annulé d'abord s'il est encore " + "dans Slurm) :")) html.Div("{{ camp_detail ? camp_detail.path : '' }}", classes="mono my-2", style="word-break: break-all") with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_job_delete_dialog = false", variant="text") - v3.VBtn("Supprimer", click=(ctrl.camp_delete_job, "[camp_detail.id]"), color="error", + v3.VBtn(tr("Annuler"), click="camp_job_delete_dialog = false", variant="text") + v3.VBtn(tr("Supprimer"), click=(ctrl.camp_delete_job, "[camp_detail.id]"), color="error", variant="flat") # delete the campaign with v3.VDialog(v_model=("camp_delete_dialog",), max_width=560): with v3.VCard(): - v3.VCardTitle("Supprimer la campagne {{ camp_name }} ?") + v3.VCardTitle(tr("Supprimer la campagne {{ camp_name }} ?")) with v3.VCardText(): - html.Div("La campagne et ses {{ camp_info ? camp_info.n : 0 }} run(s), sorties comprises, seront " - "supprimés définitivement :") + html.Div(tr("La campagne et ses {{ camp_info ? camp_info.n : 0 }} run(s), sorties comprises, seront " + "supprimés définitivement :")) html.Div("{{ camp_info ? camp_info.path : '' }}", classes="mono my-2", style="word-break: break-all") - html.Div("Les runs encore en file ou en cours dans Slurm sont d'abord annulés (scancel).", + html.Div(tr("Les runs encore en file ou en cours dans Slurm sont d'abord annulés (scancel)."), classes="text-caption") with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_delete_dialog = false", variant="text") - v3.VBtn("Supprimer", click=ctrl.camp_delete, color="error", variant="flat") + v3.VBtn(tr("Annuler"), click="camp_delete_dialog = false", variant="text") + v3.VBtn(tr("Supprimer"), click=ctrl.camp_delete, color="error", variant="flat") # prepare again the runs submitted without any file with v3.VDialog(v_model=("camp_reset_dialog",), max_width=560): with v3.VCard(): - v3.VCardTitle("Préparer à nouveau {{ camp_info ? camp_info.n_reset : 0 }} run(s) ?") + v3.VCardTitle(tr("Préparer à nouveau {{ camp_info ? camp_info.n_reset : 0 }} run(s) ?")) with v3.VCardText(): - html.Div("Les runs de {{ camp_name }} soumis qui n'ont laissé aucun fichier (ni journal, ni " - "sortie : un clone du dépôt de la campagne, ou annulés avant de démarrer) redeviennent " - "préparés. Leur lancement précédent reste dans leur document (history).") + html.Div(tr("Les runs de {{ camp_name }} soumis qui n'ont laissé aucun fichier (ni journal, ni " + "sortie : un clone du dépôt de la campagne, ou annulés avant de démarrer) redeviennent " + "préparés. Leur lancement précédent reste dans leur document (history).")) with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_reset_dialog = false", variant="text") - v3.VBtn("Préparer", click=ctrl.camp_reset, color="primary", variant="flat") + v3.VBtn(tr("Annuler"), click="camp_reset_dialog = false", variant="text") + v3.VBtn(tr("Préparer"), click=ctrl.camp_reset, color="primary", variant="flat") # submission with v3.VDialog(v_model=("camp_submit_dialog",), max_width=520): with v3.VCard(): - v3.VCardTitle("Lancer {{ camp_info ? camp_info.n_prepared : 0 }} run(s) ?") + v3.VCardTitle(tr("Lancer {{ camp_info ? camp_info.n_prepared : 0 }} run(s) ?")) with v3.VCardText(): - html.Div("Chaque run préparé de la campagne {{ camp_name }} est soumis à Slurm avec les réglages " - "du panneau Exécution (processus, options #SBATCH).") + html.Div(tr("Chaque run préparé de la campagne {{ camp_name }} est soumis à Slurm avec les réglages " + "du panneau Exécution (processus, options #SBATCH).")) with v3.VCardActions(): v3.VSpacer() - v3.VBtn("Annuler", click="camp_submit_dialog = false", variant="text") - v3.VBtn("Lancer", click=ctrl.camp_submit, color="primary", variant="flat") + v3.VBtn(tr("Annuler"), click="camp_submit_dialog = false", variant="text") + v3.VBtn(tr("Lancer"), click=ctrl.camp_submit, color="primary", variant="flat") diff --git a/tools/trame/canop_journal.py b/tools/trame/canop_journal.py index 27e4ec0..fc75347 100644 --- a/tools/trame/canop_journal.py +++ b/tools/trame/canop_journal.py @@ -23,6 +23,8 @@ import shutil import time +from canop_i18n import tr + app = None # the canop_app module, set by bind() DEFAULTS = {"jr_source": "run", "jr_path": "", "jr_title": "", "jr_size": "", "jr_follow": True, @@ -138,14 +140,15 @@ def archive_current_build_log(): def list_build_logs(): """List the build logs in state.jr_build_logs: the current one, then the archived ones, newest first.""" state = app.state - items = [{"title": "compilation en cours ou dernière (%s)" % app.core.BUILD_LOG, "value": build_log()}] + items = [{"title": tr("compilation en cours ou dernière (%s)") % app.core.BUILD_LOG, "value": build_log()}] + # the result in the file name (finished, failed, cancelled) is the state of the build job: shown translated + results = {"finished": tr("réussie"), "failed": tr("échouée"), "cancelled": tr("annulée")} if os.path.isdir(archive_dir()): for name in sorted(os.listdir(archive_dir()), reverse=True): parts = name[:-4].split("_") if len(parts) >= 4: title = "%s %s:%s — %s — %s" % (parts[0], parts[1][:2], parts[1][2:4], "_".join(parts[2:-1]), - {"finished": "réussie", "failed": "échouée", - "cancelled": "annulée"}.get(parts[-1], parts[-1])) + results.get(parts[-1], parts[-1])) else: title = name items.append({"title": title, "value": os.path.join(archive_dir(), name)}) @@ -196,7 +199,7 @@ def _on_source(jr_source, **_): if jr_source == "build": state.jr_run_path, state.jr_run_title = state.jr_path, state.jr_title list_build_logs() - state.jr_path, state.jr_title = build_log(), "compilation" + state.jr_path, state.jr_title = build_log(), tr("compilation") else: state.jr_path, state.jr_title = state.jr_run_path, state.jr_run_title state.jr_context = None @@ -225,7 +228,7 @@ def _matcher(): try: rx = re.compile(text, re.IGNORECASE) except re.error as err: - state.jr_error = "expression invalide : %s" % err + state.jr_error = tr("expression invalide : %s") % err return None return rx.search low = text.lower() @@ -277,12 +280,12 @@ def context(number): def _human(size): - """Size in bytes as text, in French units (o, ko, Mo, Go).""" - for unit in ("o", "ko", "Mo"): + """Size in bytes as text, in the units of the language (o, ko, Mo, Go in French).""" + for fmt in (tr("%.0f o"), tr("%.1f ko"), tr("%.1f Mo")): if size < 1024: - return "%.0f %s" % (size, unit) if unit == "o" else "%.1f %s" % (size, unit) + return fmt % size size /= 1024.0 - return "%.1f Go" % size + return tr("%.1f Go") % size def _push(): @@ -308,7 +311,7 @@ def _push(): except OSError: text = "" if full and not text: - text = "(pas de journal)" if not path else "(journal vide ou introuvable : %s)" % path + text = tr("(pas de journal)") if not path else tr("(journal vide ou introuvable : %s)") % path js.exec({"reset": full, "text": text, "follow": bool(state.jr_follow)}) _sent.update(path=path, offset=size, full=False) state.jr_size = _human(size) if size else "" @@ -342,6 +345,22 @@ def start_watch(): app.ctrl.add("on_server_ready")(lambda **_: asyncio.ensure_future(_watch(token))) +def refresh_language(): + """Texts of the state in the language just chosen (called by canop_app.refresh_language). + + The menu of the build logs, the title of the build log and the error of the search are recomputed; + the log itself and its size are sent again by the rebuilt interface. + """ + if app is None: + return + state = app.state + list_build_logs() + if state.jr_source == "build": # title of every build log, current or archived (_on_source) + state.jr_title = tr("compilation") + if state.jr_error: + _on_search() + + # -------------------------------------------------------------------------- # interface # -------------------------------------------------------------------------- @@ -374,19 +393,19 @@ def logs_tab(): with html.Div(classes="d-flex align-center ga-3 mb-2"): with v3.VBtnToggle(v_model=("jr_source",), mandatory=True, density="compact", variant="outlined", divided=True): - v3.VBtn("Simulation", value="run", size="small") - v3.VBtn("Compilation", value="build", size="small") + v3.VBtn(tr("Simulation"), value="run", size="small") + v3.VBtn(tr("Compilation"), value="build", size="small") v3.VSelect(v_if="jr_source === 'build'", v_model=("jr_path",), items=("jr_build_logs",), - label="Compilation", density="compact", hide_details=True, style="max-width: 420px", + label=tr("Compilation"), density="compact", hide_details=True, style="max-width: 420px", update_modelValue="jr_context = null") - v3.VTextField(v_model=("jr_search",), label="Rechercher", density="compact", hide_details=True, + v3.VTextField(v_model=("jr_search",), label=tr("Rechercher"), density="compact", hide_details=True, prepend_inner_icon="mdi-magnify", clearable=True, style="max-width: 360px") v3.VCheckbox(v_model=("jr_regex",), label="regex", density="compact", hide_details=True) - html.Span("{{ jr_nmatch }} ligne(s){{ jr_nmatch > jr_matches.length ? ' (' + jr_matches.length " - "+ ' affichées)' : '' }}", v_if="jr_search", classes="text-caption") + html.Span(tr("{{ jr_nmatch }} ligne(s){{ jr_nmatch > jr_matches.length ? ' (' + jr_matches.length " + "+ ' affichées)' : '' }}"), v_if="jr_search", classes="text-caption") html.Span("{{ jr_error }}", v_if="jr_error", classes="text-caption text-error") v3.VSpacer() - v3.VCheckbox(v_model=("jr_follow",), label="Suivre la fin", density="compact", hide_details=True) + v3.VCheckbox(v_model=("jr_follow",), label=tr("Suivre la fin"), density="compact", hide_details=True) # whole log (kept in the page, even while a search is shown) with v3.VCard(variant="outlined", classes="journal-box", v_show="!jr_search", style="flex: 1 1 auto; min-height: 0"): @@ -403,7 +422,7 @@ def logs_tab(): html.Span("{{ m.n }} ", classes="text-medium-emphasis") html.Span("{{ m.text }}") with v3.VCard(variant="outlined", classes="journal-box", style="flex: 1 1 50%; min-width: 0"): - html.Div("Cliquez une ligne pour voir son contexte.", v_if="!jr_context", + html.Div(tr("Cliquez une ligne pour voir son contexte."), v_if="!jr_context", classes="text-caption pa-2", style="color: #aaa") with html.Div(v_if="jr_context", classes="pa-2"): with html.Div(v_for="l in jr_context.lines", key="l.n", classes="mono text-caption", diff --git a/tools/trame/canop_view.py b/tools/trame/canop_view.py index 9059a59..23408cf 100644 --- a/tools/trame/canop_view.py +++ b/tools/trame/canop_view.py @@ -22,6 +22,8 @@ import os import shutil +from canop_i18n import tr + app = None # the canop_app module, set by bind() TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "run_view") @@ -162,7 +164,7 @@ def module(name): mod.app = app entry["module"] = mod except Exception as err: - _report(name, "Erreur dans %s : %s: %s" % (path, type(err).__name__, err)) + _report(name, tr("Erreur dans %s : %s: %s") % (path, type(err).__name__, err)) if previous is None: # nothing to keep: the template spec = importlib.util.spec_from_file_location("canop_run_template", os.path.join(TEMPLATE_DIR, name)) @@ -200,7 +202,8 @@ def update_overlays(data): try: module(VIEW_FILE).update_overlays(data) except Exception as err: - _report(VIEW_FILE, "Erreur dans %s : %s: %s" % (_loaded[VIEW_FILE].get("path"), type(err).__name__, err)) + _report(VIEW_FILE, tr("Erreur dans %s : %s: %s") % (_loaded[VIEW_FILE].get("path"), + type(err).__name__, err)) def draw_overlays_mpl(ax, dims): @@ -213,7 +216,8 @@ def derived_fields(f): try: return module(FIELDS_FILE).derived_fields(f) or {} except Exception as err: - _report(FIELDS_FILE, "Erreur dans %s : %s: %s" % (_loaded[FIELDS_FILE].get("path"), type(err).__name__, err)) + _report(FIELDS_FILE, tr("Erreur dans %s : %s: %s") % (_loaded[FIELDS_FILE].get("path"), + type(err).__name__, err)) return {} @@ -269,9 +273,9 @@ async def _watch(token): if app.results.reader is not None and app.state.has_data: app.update_view() if not new_run: - app.notify("Visualisation du run rechargée", "success") + app.notify(tr("Visualisation du run rechargée"), "success") except Exception as err: # keep watching - app.notify("Rechargement de la visualisation impossible : %s: %s" % (type(err).__name__, err), + app.notify(tr("Rechargement de la visualisation impossible : %s: %s") % (type(err).__name__, err), "error") diff --git a/tools/trame/check_i18n.py b/tools/trame/check_i18n.py new file mode 100644 index 0000000..250d89e --- /dev/null +++ b/tools/trame/check_i18n.py @@ -0,0 +1,122 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Check the translations of canoP studio (tools/canop_i18n.py). + +Every text wrapped in tr() or tr_js() in the studio must have an English translation in +tools/canop_i18n_en.py, with the same placeholders (%s, %(name)s, ...) and, inside {{ ... }}, the +same expression (same names, same number of quotes). A tr() of an f-string cannot be translated and +is an error. Unused translations are reported, not errors. + + python3 tools/trame/check_i18n.py [--extra fragment.json ...] [files...] + +--extra adds translations from JSON files ({"French": "English"}), checked as if they were in the +catalog. Exit status 1 when an error is found. +""" +import argparse +import ast +import glob +import json +import os +import re +import sys + +TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, TOOLS) + +PRINTF = re.compile(r"%(?:\(\w+\))?[-#0 +]*(?:\d+|\*)?(?:\.\d+)?[sdifgeExXrc%]") +MUSTACHE = re.compile(r"\{\{(.*?)\}\}", re.S) +JS_STRING = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|`(?:[^`\\]|\\.)*`") +JS_NAME = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*") + + +def default_files(): + """The Python files of the studio that may hold texts to translate.""" + files = [os.path.join(TOOLS, "canop_core.py")] + files += sorted(glob.glob(os.path.join(TOOLS, "trame", "canop_*.py"))) + files.append(os.path.join(TOOLS, "trame", "campaign_template", "analysis.py")) + files += sorted(glob.glob(os.path.join(TOOLS, "trame", "run_view", "*.py"))) + return files + + +def calls(path): + """[(line, kind, text or None)] of the tr()/tr_js() calls of a file; text None: not a constant.""" + with open(path, encoding="utf-8") as fd: + tree = ast.parse(fd.read(), path) + found = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or not node.args: + continue + func = node.func + name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else "" + if name not in ("tr", "tr_js"): + continue + arg = node.args[0] + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): + found.append((node.lineno, "text", arg.value)) + elif isinstance(arg, ast.JoinedStr): + found.append((node.lineno, "fstring", None)) + else: + found.append((node.lineno, "dynamic", None)) + return found + + +def expression_shape(text): + """Names and quote counts of the {{ ... }} expressions of a text, translation-independent.""" + shapes = [] + for expr in MUSTACHE.findall(text): + quotes = (expr.count("'"), expr.count('"')) + names = sorted(JS_NAME.findall(JS_STRING.sub("", expr))) + shapes.append((names, quotes)) + return shapes + + +def check_pair(fr, en): + """Problems of a translation, as a list of strings.""" + problems = [] + if sorted(PRINTF.findall(fr)) != sorted(PRINTF.findall(en)): + problems.append("placeholders %s != %s" % (sorted(PRINTF.findall(fr)), sorted(PRINTF.findall(en)))) + if expression_shape(fr) != expression_shape(en): + problems.append("{{ }} expressions differ") + if not en.strip() and fr.strip(): + problems.append("empty translation") + return problems + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--extra", action="append", default=[], help="JSON file of more translations") + parser.add_argument("files", nargs="*", help="files to check (default: the studio)") + args = parser.parse_args() + + from canop_i18n_en import EN # pylint: disable=import-outside-toplevel + catalog = dict(EN) + for extra in args.extra: + with open(extra, encoding="utf-8") as fd: + catalog.update(json.load(fd)) + + errors, used, dynamic = [], set(), 0 + for path in args.files or default_files(): + rel = os.path.relpath(path, os.path.dirname(TOOLS)) + for line, kind, text in calls(path): + if kind == "fstring": + errors.append("%s:%d: tr() of an f-string cannot be translated" % (rel, line)) + elif kind == "dynamic": + dynamic += 1 + elif text not in catalog: + errors.append("%s:%d: no translation for %r" % (rel, line, text)) + else: + used.add(text) + errors += ["%s:%d: %s: %r" % (rel, line, p, text) for p in check_pair(text, catalog[text])] + for text in sorted(set(catalog) - used): + if not args.files: + print("unused translation: %r" % text) + for e in errors: + print(e) + print("check_i18n: %d texts, %d translations, %d tr() of a variable, %d errors" + % (len(used), len(catalog), dynamic, len(errors))) + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/trame/run_view/canoP_view.py b/tools/trame/run_view/canoP_view.py index 000e34f..969fa70 100644 --- a/tools/trame/run_view/canoP_view.py +++ b/tools/trame/run_view/canoP_view.py @@ -23,6 +23,7 @@ """ import numpy as np +from canop_i18n import tr, tr_js # texts of the studio in its language (French or English) app = None @@ -201,19 +202,20 @@ def view_tab(): with html.Div(classes="d-flex flex-column", style="height: 100%"): with v3.VToolbar(density="compact", color="surface", classes="px-2 border-b"): v3.VSelect(v_model=("field",), items=("fields",), density="compact", hide_details=True, - label="Champ", style="max-width: 200px", classes="mr-2") + label=tr("Champ"), style="max-width: 200px", classes="mr-2") v3.VSelect(v_model=("preset",), items=("presets",), density="compact", hide_details=True, - label="Palette", style="max-width: 210px", classes="mr-2") - v3.VCheckbox(v_model=("show_edges",), label="Maillage", density="compact", hide_details=True) - v3.VCheckbox(v_model=("auto_range",),label="Échelle auto", density="compact", hide_details=True) - v3.VCheckbox(v_model=("show_arrows",), label="Vitesse", density="compact", hide_details=True, - title="Flèches de la vitesse dans le plan (domaine 2D ou coupe 3D)") + label=tr("Palette"), style="max-width: 210px", classes="mr-2") + v3.VCheckbox(v_model=("show_edges",), label=tr("Maillage"), density="compact", hide_details=True) + v3.VCheckbox(v_model=("auto_range",), label=tr("Échelle auto"), density="compact", hide_details=True) + v3.VCheckbox(v_model=("show_arrows",), label=tr("Vitesse"), density="compact", hide_details=True, + title=tr("Flèches de la vitesse dans le plan (domaine 2D ou coupe 3D)")) v3.VTextField(v_if="show_arrows", model_value=("arrow_density",), update_modelValue="arrow_density = Math.max(2, Math.min(200, parseInt($event) || 25))", - type="number", label="Flèches", density="compact", hide_details=True, - style="max-width: 90px", classes="mr-2", title="Nombre de flèches sur le grand côté") + type="number", label=tr("Flèches"), density="compact", hide_details=True, + style="max-width: 90px", classes="mr-2", title=tr("Nombre de flèches sur le grand côté")) v3.VSelect(v_if="dim === 3", v_model=("view_mode",), - items=("[{title: 'Coupe', value: 'slice'}, {title: 'Surface', value: 'surface'}]",), + items=("[{title: %s, value: 'slice'}, {title: %s, value: 'surface'}]" + % (tr_js("Coupe"), tr_js("Surface")),), density="compact", hide_details=True, style="max-width: 130px", classes="mr-2") with v3.VBtnToggle(v_if="dim === 3 && view_mode === 'slice'", v_model=("slice_axis",), mandatory=True, density="compact", variant="outlined", divided=True): @@ -261,19 +263,19 @@ def view_tab(): blur=(ctrl.set_range, "[color_range[0], $event.target.value]"), keyup_enter="$event.target.blur()", **BLUR) v3.VAlert( - "Aucun résultat pour ce run : lancez-le depuis l'onglet Run ou la campagne.", + tr("Aucun résultat pour ce run : lancez-le depuis l'onglet Run ou la campagne."), v_if="!has_data", type="info", variant="tonal", classes="ma-4", style="position: absolute; top: 0; left: 0; right: 0", ) with v3.VToolbar(density="compact", color="surface", classes="px-2 border-t"): v3.VBtn(icon=("anim_playing ? 'mdi-pause' : 'mdi-play'",), click="anim_playing = !anim_playing", size="small", variant="text", disabled=("time_values.length < 2",), - title="Lire les pas de temps") + title=tr("Lire les pas de temps")) v3.VSlider(v_model=("time_index",), min=0, max=("Math.max(time_values.length - 1, 0)",), step=1, density="compact", hide_details=True, classes="mx-2", disabled=("time_values.length < 2",)) html.Span("{{ time_label }}", classes="text-caption mono mr-3", style="min-width: 170px") - v3.VSelect(v_model=("anim_fps",), items=("[2, 4, 8, 12, 20]",), label="images/s", density="compact", + v3.VSelect(v_model=("anim_fps",), items=("[2, 4, 8, 12, 20]",), label=tr("images/s"), density="compact", hide_details=True, style="max-width: 100px", classes="mr-2") - v3.VCheckbox(v_model=("follow",), label="Suivre le run", density="compact", hide_details=True) - html.Span("{{ n_cells }} cellules", v_if="has_data", classes="text-caption ml-2") + v3.VCheckbox(v_model=("follow",), label=tr("Suivre le run"), density="compact", hide_details=True) + html.Span(tr("{{ n_cells }} cellules"), v_if="has_data", classes="text-caption ml-2") diff --git a/tools/vscode/build_vsix.py b/tools/vscode/build_vsix.py index 7dcfb9a..ac64ad4 100644 --- a/tools/vscode/build_vsix.py +++ b/tools/vscode/build_vsix.py @@ -16,7 +16,9 @@ import zipfile HERE = os.path.dirname(os.path.abspath(__file__)) -FILES = ["package.json", "extension.js", "media/canop.svg", "media/canop.png"] +# package.nls*.json: the texts of package.json ("%key%"), in English and in French (VS Code chooses by its language) +FILES = ["package.json", "package.nls.json", "package.nls.fr.json", "extension.js", "media/canop.svg", + "media/canop.png"] CONTENT_TYPES = """ diff --git a/tools/vscode/extension.js b/tools/vscode/extension.js index cb6bcf6..b7d9894 100644 --- a/tools/vscode/extension.js +++ b/tools/vscode/extension.js @@ -14,6 +14,31 @@ const path = require("path"); // replaced by build_vsix.py with the canop-studio script of the repository const INSTALLED_SCRIPT = "__CANOP_STUDIO_SCRIPT__"; +// texts in the language of VS Code: French as written in the code when it is French, else English +// (the texts of package.json are in package.nls.json and package.nls.fr.json) +const FRENCH = (vscode.env.language || "").toLowerCase().startsWith("fr"); +const EN = { + "tools/trame/canop-studio introuvable : réglez canopStudio.script": + "tools/trame/canop-studio not found: set canopStudio.script", + "En cours": "Running", + "Arrêté": "Stopped", + "Erreur": "Error", + "Afficher": "Show", + "Démarrer et afficher": "Start and show", + "Arrêter": "Stop", + "Journal": "Log", + "canoP studio : démarrage…": "canoP studio: starting…", + "canoP studio : ": "canoP studio: ", + "canoP studio arrêté (les builds et runs déjà lancés continuent).": + "canoP studio stopped (the builds and runs already started go on).", + "canoP studio ne tournait pas.": "canoP studio was not running.", + "canoP studio : pas encore de journal.": "canoP studio: no log yet.", +}; + +function tr(text) { + return FRENCH ? text : (EN[text] || text); +} + function studioScript() { const configured = vscode.workspace.getConfiguration("canopStudio").get("script"); const candidates = []; @@ -32,7 +57,7 @@ function runStudio(arg) { return new Promise((resolve) => { const script = studioScript(); if (!script) { - resolve({ ok: false, error: "tools/trame/canop-studio introuvable : réglez canopStudio.script" }); + resolve({ ok: false, error: tr("tools/trame/canop-studio introuvable : réglez canopStudio.script") }); return; } cp.execFile(script, [arg], { timeout: 180000, cwd: path.dirname(path.dirname(path.dirname(script))) }, @@ -66,11 +91,11 @@ class Panel { getChildren() { const s = this.status; const items = []; - const state = new vscode.TreeItem(s.running ? "En cours" : "Arrêté"); + const state = new vscode.TreeItem(s.running ? tr("En cours") : tr("Arrêté")); state.iconPath = new vscode.ThemeIcon(s.running ? "pass-filled" : "circle-outline"); state.description = s.running ? `port ${s.port}, pid ${s.pid}` : ""; if (s.ok === false) { - state.label = "Erreur"; + state.label = tr("Erreur"); state.description = s.error; state.tooltip = s.error; } @@ -81,9 +106,9 @@ class Panel { it.command = { command, title: label }; items.push(it); }; - add(s.running ? "Afficher" : "Démarrer et afficher", "play", "canopStudio.open"); - if (s.running) add("Arrêter", "debug-stop", "canopStudio.stop"); - add("Journal", "output", "canopStudio.log"); + add(s.running ? tr("Afficher") : tr("Démarrer et afficher"), "play", "canopStudio.open"); + if (s.running) add(tr("Arrêter"), "debug-stop", "canopStudio.stop"); + add(tr("Journal"), "output", "canopStudio.log"); return items; } } @@ -101,11 +126,11 @@ function activate(context) { context.subscriptions.push(vscode.commands.registerCommand("canopStudio.open", async () => { const info = await vscode.window.withProgress( - { location: vscode.ProgressLocation.Notification, title: "canoP studio : démarrage…" }, + { location: vscode.ProgressLocation.Notification, title: tr("canoP studio : démarrage…") }, () => runStudio("--open")); await panel.refresh(); if (!info.ok) { - vscode.window.showErrorMessage("canoP studio : " + info.error); + vscode.window.showErrorMessage(tr("canoP studio : ") + info.error); return; } await vscode.commands.executeCommand("simpleBrowser.show", await browserUrl(info)); @@ -114,10 +139,10 @@ function activate(context) { context.subscriptions.push(vscode.commands.registerCommand("canopStudio.stop", async () => { const out = await runStudio("--stop"); await panel.refresh(); - if (!out.ok) vscode.window.showErrorMessage("canoP studio : " + out.error); + if (!out.ok) vscode.window.showErrorMessage(tr("canoP studio : ") + out.error); else vscode.window.showInformationMessage(out.stopped_pid - ? "canoP studio arrêté (les builds et runs déjà lancés continuent)." - : "canoP studio ne tournait pas."); + ? tr("canoP studio arrêté (les builds et runs déjà lancés continuent).") + : tr("canoP studio ne tournait pas.")); })); context.subscriptions.push(vscode.commands.registerCommand("canopStudio.log", async () => { @@ -126,7 +151,7 @@ function activate(context) { ? path.join(process.env.WORKDIR, ".canop-studio", `studio-${require("os").hostname()}.log`) : null); if (!log || !fs.existsSync(log)) { - vscode.window.showInformationMessage("canoP studio : pas encore de journal."); + vscode.window.showInformationMessage(tr("canoP studio : pas encore de journal.")); return; } await vscode.window.showTextDocument(vscode.Uri.file(log), { preview: true }); diff --git a/tools/vscode/package.json b/tools/vscode/package.json index 674cecb..b7bb791 100644 --- a/tools/vscode/package.json +++ b/tools/vscode/package.json @@ -21,10 +21,10 @@ ] }, "commands": [ - { "command": "canopStudio.open", "title": "Ouvrir canoP studio", "category": "canoP", "icon": "$(play)" }, - { "command": "canopStudio.stop", "title": "Arrêter canoP studio", "category": "canoP", "icon": "$(debug-stop)" }, - { "command": "canopStudio.log", "title": "Journal de canoP studio", "category": "canoP", "icon": "$(output)" }, - { "command": "canopStudio.refresh", "title": "Rafraîchir", "category": "canoP", "icon": "$(refresh)" } + { "command": "canopStudio.open", "title": "%command.open%", "category": "canoP", "icon": "$(play)" }, + { "command": "canopStudio.stop", "title": "%command.stop%", "category": "canoP", "icon": "$(debug-stop)" }, + { "command": "canopStudio.log", "title": "%command.log%", "category": "canoP", "icon": "$(output)" }, + { "command": "canopStudio.refresh", "title": "%command.refresh%", "category": "canoP", "icon": "$(refresh)" } ], "menus": { "view/title": [ @@ -39,7 +39,7 @@ "canopStudio.script": { "type": "string", "default": "", - "description": "Path of tools/trame/canop-studio. Empty: looked for in the workspace folders, then the path given at installation." + "description": "%config.script%" } } } diff --git a/tools/vscode/package.nls.fr.json b/tools/vscode/package.nls.fr.json new file mode 100644 index 0000000..bac28ef --- /dev/null +++ b/tools/vscode/package.nls.fr.json @@ -0,0 +1,7 @@ +{ + "command.open": "Ouvrir canoP studio", + "command.stop": "Arrêter canoP studio", + "command.log": "Journal de canoP studio", + "command.refresh": "Rafraîchir", + "config.script": "Chemin de tools/trame/canop-studio. Vide : cherché dans les dossiers de l'espace de travail, puis le chemin donné à l'installation." +} diff --git a/tools/vscode/package.nls.json b/tools/vscode/package.nls.json new file mode 100644 index 0000000..09ad6d9 --- /dev/null +++ b/tools/vscode/package.nls.json @@ -0,0 +1,7 @@ +{ + "command.open": "Open canoP studio", + "command.stop": "Stop canoP studio", + "command.log": "canoP studio log", + "command.refresh": "Refresh", + "config.script": "Path of tools/trame/canop-studio. Empty: looked for in the workspace folders, then the path given at installation." +}