feat(i18n): plural forms per language, translation import and glossary

i18n check accepts the few/many forms a language adds, comparing them with
the English other form; i18n missing lists the work as TSV (or every key with
--all for review) and i18n import merges translated rows into the culture's
resx files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 16:47:34 +00:00
1 parent 5dcff487bb
commit 8dec8fb969
4 files changed
+216 -17

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ All notable changes. Format: Keep a Changelog; versions follow SemVer; commits f
### Added
- Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin.
- `Titano.Testing`: in-house test framework and runner with JUnit XML output and GitHub annotations.
- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages), `en` + `it` catalogs, `i18n check/export`.
- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages), `en` + `it` catalogs, `i18n check/export/missing/import`, translation glossary.
- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon` (program icons generated at build time).
- Core contracts: image buffers and decoder providers, video encoder providers, domain model, TIFF/IFD reader, sRGB helpers, atomic file writes, logging.
- `Titano.Ui` design system: DESIGN.md tokens (dark/light), 100+ stroke icons, styles for every standard control, custom chrome window with snap layouts, navigation rail, job bar, Auto/manual slider, chips, status glyphs, toasts, empty states.
+2
View File
@@ -123,3 +123,5 @@ One line per decision: date · decision · alternative · reason.
| 2026-10-02 | Server settings page writes only edited keys to `server.json`; environment-fixed settings are locked; restart-only keys are flagged. Windows service: LocalSystem, automatic start, name `TitanoServer`. Admin panel: strict CSP (SVG charts, no inline styles), light theme only. | Rewrite the whole file / theme toggle | Secrets never written; DESIGN.md wins over the mockup toggle. |
| 2026-10-02 | Migrations are numbered without gaps (0001 initial, 0002 archive index, 0003 server uploads). | Keep 0005 | Parallel workstreams picked numbers to avoid collisions; renumbered at merge. |
| 2026-10-02 | `xaml-lint` checks keyed value resources against the property type (GridLength for column/row sizes, Thickness, CornerRadius, Double). | Rely on Windows smoke tests | A Double used as a column width compiles and only fails when the template loads on Windows; the lint now fails on Linux too. |
| 2026-10-02 | Languages with more plural forms add `key.few` / `key.many` beside the English `key.one` / `key.other`; `i18n check` accepts them, compares their placeholders with English `other` and lets any plural form omit the count. | One English-shaped key set for every language | "Rendered once" style forms cannot cover Russian 21 or Arabic 3–10 otherwise. |
| 2026-10-02 | Translations go through `i18n missing` (TSV out) and `i18n import` (TSV in) against `i18n/GLOSSARY.md` plus a per-language `glossary.tsv`; each language is translated and then reviewed by a second pass. | Edit resx by hand | Same path for machine translation and community corrections; keys, placeholders and budgets are validated in one place. |
+91
View File
@@ -0,0 +1,91 @@
# Translation glossary
English (`i18n/en`) is the source. Every other language is machine translated with this glossary and marked
"Machine translated" in About; community corrections arrive through the public releases repository.
Each language keeps its own term list in `i18n/<culture>/glossary.tsv` (`English term<TAB>translation<TAB>note`),
written before its strings and followed by every string of that language.
## Workflow
```
dotnet run --project src/Titano.Tools -- i18n missing --culture de > de.todo.tsv # key, English, budget, note
dotnet run --project src/Titano.Tools -- i18n import --culture de de.tsv # key<TAB>translation
dotnet run --project src/Titano.Tools -- i18n check
```
## Rules
- Keep every placeholder with its format exactly: `{0}`, `{1:N0}`, `{0:0.#}`. Reorder them freely when the grammar
needs it; never add or drop one. Plural forms may omit `{0}` (English `Rendered once`).
- Plurals: keys ending `.one` / `.other` are plural forms. Add `.few` and `.many` where the language's rule
(`src/Titano.Core/Localization/PluralRules.cs`) selects them: `pl`, `ru`, `uk` use one/few/many; `cs`, `sk`, `hr`,
`sl`, `lt`, `ro`, `he` use one/few/other; `lv` uses one/many/other; `ar` uses one/few/many/other.
Languages without plural forms (`ja`, `zh-Hans`, `zh-Hant`, `ko`, `vi`, `th`, `id`, `ms`) still provide both
`.one` and `.other`, usually identical.
- Budget: the third column of `i18n missing` is the hard ceiling in characters (1.6 × the English budget).
Labels (budget 48) name a thing or an action in at most three words; tooltips, errors and advisor reasons
(budget 320) are complete sentences.
- Labels: no trailing full stop, no colon, sentence case where the language has case. Buttons use the imperative or
infinitive form the platform's own UI uses for that language (Windows conventions).
- Keep the English typography marks with their meaning: `…` means the action opens a dialog; `·` separates items;
`—` introduces a detail; `«»`/`“”`: use the language's own quotation marks.
- Units and abbreviations follow the language (`d`, `h`, `min`, `s`; decimal separators come from the culture at run
time, never from the string).
- Formality: address the user as the platform does (de: Sie; fr: vous; es: tú; pt-BR: você; ru/uk: вы; pl: bez
formy grzecznościowej where the UI style allows; ja: です/ます; ko: 합니다체).
- Never translate: Titano, RAW, DNG, JPEG, PNG, TIFF, GIF, APNG, MP4, AVI, MJPEG, H.264, HEVC, AV1, ProRes, EXIF,
XMP, ICC, sRGB, Rec.709, Rec.2020, HDR, SDR, LUT, fps, ISO, EV, GPU, CPU, NVENC, Quick Sync, AMF, SHA-256, TLS,
HTTPS, URL, API, PostgreSQL, SQLite, Docker, Unraid, Windows, JSON, CSV, ZIP, UTC, `Ctrl`, `Shift`, `Alt`,
`Enter`, `Esc`, file names, file extensions and anything in backticks.
## Terms
| English | Meaning | Italian (reference) |
|---|---|---|
| Sequence | One shoot: one folder of frames, one project | Sequenza |
| Frame | One photo of a sequence | Fotogramma |
| Hero frame | The frame shown as the sequence thumbnail | Fotogramma di copertina |
| Library | The list of sequences in the archive | Libreria |
| Archive | The managed folder tree holding all sequences | Archivio |
| Import | Copying frames from a memory card into the archive | Importa / importazione |
| Card profile | Saved import rules for one memory card | Profilo scheda |
| Adopt | Take an existing folder into the archive without copying | Adotta / adozione |
| Scan | Walk the archive and index new or changed files | Scansione |
| Rebuild | Recreate the index from the sidecars on disk | Ricostruisci |
| Verify | Re-hash files and compare with the recorded hash | Verifica |
| Sidecar | The `sequence.json` manifest stored next to the frames | Sidecar (file sidecar) |
| Orphans | Files on disk that no sequence references | File orfani |
| Duplicates | Frames whose content hash appears more than once | Duplicati |
| Thumbnail | Small preview image | Miniatura |
| Proxy | Reduced JPEG stand-in used for preview and fast renders | Proxy |
| Tier | How a frame's pixels are obtained (embedded preview, proxy, full decode) | Livello |
| Light analysis | Metadata-only analysis (exposure, interval, gaps) | Analisi rapida |
| Deep analysis | Pixel analysis (flicker, motion, colour) | Analisi approfondita |
| Advisor | Rule engine that proposes settings with reasons | Consigli (assistente) |
| Auto | A value the advisor sets until the user overrides it | Auto |
| Deflicker | Smoothing brightness jumps between frames | Deflicker |
| Holy grail | Day-to-night shoot with changing exposure | Holy grail |
| Keyframe | A frame where an editor value is pinned | Fotogramma chiave |
| Ramp | Gradual change of a value across frames | Rampa |
| Crop | Rectangle of the frame kept in the output | Ritaglio |
| Stabilise | Remove camera shake | Stabilizza |
| Frame blending | Mixing neighbouring frames for smooth motion | Fusione fotogrammi |
| Motion blur | Simulated blur from frame blending | Sfocatura di movimento |
| Render | Produce a video or image sequence; also the produced file | Rendering / render |
| Export | The editor tab that configures a render | Esporta |
| Preset | Saved bundle of export values | Preset |
| Sequence preset | Project settings plus export preset suggested by the advisor | Preset di sequenza |
| Encoder | The component that writes a codec (hardware or managed) | Encoder |
| Codec / Container | Video compression format / file format holding it | Codec / Contenitore |
| Job | Any long, resumable operation (scan, import, render…) | Attività |
| Queue | Jobs waiting to run | Coda |
| Checkpoint | Saved progress a job resumes from | Punto di ripresa |
| Server | The Titano server holding a shared archive | Server |
| Render node | A desktop lending its GPU to the server for renders | Nodo di rendering |
| Uploader | The tray app that sends camera files to the server | Caricatore |
| Sync | Keeping the desktop and the server archive aligned | Sincronizzazione |
| Conflict | A sequence changed on both sides since the last sync | Conflitto |
| Pairing | Linking a desktop or uploader to a server with a code | Associazione |
| Fingerprint | SHA-256 of the server certificate shown for trust | Impronta |
| Token | Saved sign-in credential | Token |
| Diagnostics bundle | ZIP with logs and system data for a bug report | Pacchetto diagnostico |
+122 -16
View File
@@ -10,6 +10,8 @@ namespace Titano.Tools.Commands;
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets and that
/// every key used in code/XAML/admin JS exists (BRIEF §16).
/// <c>i18n export --out dir</c>: one JSON per culture for the web admin.
/// <c>i18n missing --culture xx [--all]</c>: untranslated (or all) keys as TSV for a translator or reviewer.
/// <c>i18n import --culture xx file.tsv</c>: merges translated <c>key&lt;TAB&gt;text</c> rows into the culture's resx files.
/// </summary>
internal sealed partial class I18nCommand : ICommand
{
@@ -17,11 +19,11 @@ internal sealed partial class I18nCommand : ICommand
private static readonly HashSet<string> SentenceAreas = new(StringComparer.Ordinal) { "Tooltips", "Errors", "Advisor" };
public string Name => "i18n";
public string Summary => "check | export --out <dir> (resource completeness and web export)";
public string Summary => "check | export --out <dir> | missing --culture <c> [--all] | import --culture <c> <tsv>";
public Task<int> RunAsync(string[] args)
{
var a = new Args(args);
var a = new Args(args, "all");
var sub = a.Positional.FirstOrDefault() ?? "check";
var root = Args.RepoRoot();
var catalog = Catalog.Load(Path.Combine(root, "i18n"));
@@ -29,7 +31,9 @@ internal sealed partial class I18nCommand : ICommand
{
"check" => Check(root, catalog),
"export" => Export(catalog, a.Get("out") ?? throw new ToolException("--out <dir> required")),
"missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required")),
"missing" => Missing(catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"), a.Has("all")),
"import" => Import(root, catalog, a.Get("culture") ?? throw new ToolException("--culture <code> required"),
a.Positional.ElementAtOrDefault(1) ?? throw new ToolException("TSV file required")),
_ => throw new ToolException($"Unknown i18n subcommand '{sub}'"),
});
}
@@ -66,18 +70,15 @@ internal sealed partial class I18nCommand : ICommand
else missing++;
continue;
}
var p1 = Placeholders(entry.Value);
var p2 = Placeholders(translated.Value);
if (!p1.SetEquals(p2))
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}");
var area = key.Split('.')[0];
var limit = (int)(Limit(key, area, entry.Comment) * 1.6);
if (translated.Value.Length > limit)
warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})");
CheckTranslation(culture, key, entry, translated, en, errors, warnings);
}
if (missing > 0) warnings.Add($"{culture}: {missing} key(s) not translated yet");
foreach (var key in strings.Keys.Where(k => !en.ContainsKey(k)))
errors.Add($"{culture}: orphan key {key}");
foreach (var (key, translated) in strings.Where(s => !en.ContainsKey(s.Key)))
{
// Languages with more plural forms than English add key.few / key.many next to key.one / key.other.
if (PluralStem(key, en) is { } other) CheckTranslation(culture, key, other, translated, en, errors, warnings);
else errors.Add($"{culture}: orphan key {key}");
}
}
var areas = en.Keys.Select(k => k[..k.IndexOf('.')]).ToHashSet(StringComparer.Ordinal);
@@ -98,17 +99,122 @@ internal sealed partial class I18nCommand : ICommand
return errors.Count == 0 ? 0 : 1;
}
private static int Missing(Catalog catalog, string culture)
/// <summary>A translation keeps the English placeholders and stays within 1.6× the English budget. Plural forms
/// are compared with the English <c>other</c> form and may drop the count <c>{0}</c> (as English "Rendered once" does).</summary>
private static void CheckTranslation(string culture, string key, Entry source, Entry translated, Dictionary<string, Entry> en, List<string> errors, List<string> warnings)
{
var p2 = Placeholders(translated.Value);
if (PluralStem(key, en) is { } other)
{
var p1 = Placeholders(other.Value);
p1.Remove("0");
if (!p2.IsSubsetOf([.. p1, "0"]) || !p1.IsSubsetOf(p2))
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1.Prepend("0"))}}}");
}
else
{
var p1 = Placeholders(source.Value);
if (!p1.SetEquals(p2))
errors.Add($"{culture}: {key} placeholders {{{string.Join(",", p2)}}} differ from en {{{string.Join(",", p1)}}}");
}
if (string.IsNullOrWhiteSpace(translated.Value))
errors.Add($"{culture}: {key} is empty");
var limit = (int)(Limit(key, key.Split('.')[0], source.Comment) * 1.6);
if (translated.Value.Length > limit)
warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})");
}
/// <summary>The English <c>other</c> form when <paramref name="key"/> is a plural form of an English plural key.</summary>
private static Entry? PluralStem(string key, Dictionary<string, Entry> en)
{
var dot = key.LastIndexOf('.');
if (dot <= 0 || !PluralSuffix().IsMatch(key[(dot + 1)..])) return null;
return en.GetValueOrDefault(key[..dot] + ".other");
}
/// <summary>Untranslated keys as <c>key, English, budget, note</c>; with <c>--all</c> every key plus its current
/// translation (plural forms the language adds included) for review.</summary>
private static int Missing(Catalog catalog, string culture, bool all)
{
var en = catalog.Cultures["en"];
catalog.Cultures.TryGetValue(culture, out var target);
foreach (var (key, entry) in en.OrderBy(k => k.Key, StringComparer.Ordinal))
target ??= [];
var rows = en.Select(e => (Key: e.Key, Source: e.Value))
.Concat(target.Keys.Where(k => !en.ContainsKey(k)).Select(k => (Key: k, Source: PluralStem(k, en)!)))
.Where(r => r.Source is not null)
.OrderBy(r => r.Key, StringComparer.Ordinal);
foreach (var (key, source) in rows)
{
if (target is null || !target.ContainsKey(key)) Console.WriteLine($"{key}\t{entry.Value}");
if (source.Comment is not null && source.Comment.Contains("invariant", StringComparison.OrdinalIgnoreCase)) continue;
var translated = target.GetValueOrDefault(key);
if (translated is not null && !all) continue;
var budget = (int)(Limit(key, key.Split('.')[0], source.Comment) * 1.6);
Console.WriteLine(all ? $"{key}\t{source.Value}\t{budget}\t{source.Comment}\t{translated?.Value}" : $"{key}\t{source.Value}\t{budget}\t{source.Comment}");
}
return 0;
}
/// <summary>
/// Merges <c>key&lt;TAB&gt;text</c> rows (further columns and <c>#</c> lines ignored) into
/// <c>i18n/&lt;culture&gt;/&lt;Area&gt;.&lt;culture&gt;.resx</c>, replacing existing values and keeping keys sorted.
/// Keys must exist in English or be a plural form of an English plural key; placeholders are verified by <c>check</c>.
/// </summary>
private static int Import(string root, Catalog catalog, string culture, string tsv)
{
if (culture.Equals("en", StringComparison.OrdinalIgnoreCase)) throw new ToolException("English is the source; edit i18n/en directly");
if (!Languages.Shipped.Contains(culture, StringComparer.OrdinalIgnoreCase)) throw new ToolException($"{culture} is not a shipped language");
culture = Languages.Shipped.First(c => c.Equals(culture, StringComparison.OrdinalIgnoreCase));
var en = catalog.Cultures["en"];
var rows = new Dictionary<string, string>(StringComparer.Ordinal);
var line = 0;
foreach (var raw in File.ReadLines(tsv))
{
line++;
if (raw.Length == 0 || raw.StartsWith('#')) continue;
var cells = raw.Split('\t');
if (cells.Length < 2) throw new ToolException($"{tsv}:{line}: expected key<TAB>text");
var key = cells[0].Trim();
if (!en.ContainsKey(key) && PluralStem(key, en) is null) throw new ToolException($"{tsv}:{line}: unknown key {key}");
if (!rows.TryAdd(key, cells[1])) throw new ToolException($"{tsv}:{line}: duplicate key {key}");
}
var dir = Path.Combine(root, "i18n", culture);
Directory.CreateDirectory(dir);
var written = 0;
foreach (var group in rows.GroupBy(r => r.Key[..r.Key.IndexOf('.')], StringComparer.Ordinal))
{
var path = Path.Combine(dir, $"{group.Key}.{culture}.resx");
var values = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (File.Exists(path))
{
foreach (var data in XDocument.Load(path).Root!.Elements("data"))
values[(string)data.Attribute("name")!] = (string?)data.Element("value") ?? string.Empty;
}
foreach (var (key, value) in group) values[key] = value;
WriteResx(path, values);
written += group.Count();
}
Console.WriteLine($"{culture}: {written} string(s) imported");
return 0;
}
private static void WriteResx(string path, IEnumerable<KeyValuePair<string, string>> values)
{
var sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n");
sb.Append(" <resheader name=\"resmimetype\"><value>text/microsoft-resx</value></resheader>\n");
sb.Append(" <resheader name=\"version\"><value>2.0</value></resheader>\n");
sb.Append(" <resheader name=\"reader\"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>\n");
sb.Append(" <resheader name=\"writer\"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>\n");
foreach (var (key, value) in values)
sb.Append($" <data name=\"{Escape(key)}\" xml:space=\"preserve\"><value>{Escape(value)}</value></data>\n");
sb.Append("</root>\n");
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(false));
}
private static string Escape(string s) => s.Replace("&", "&amp;", StringComparison.Ordinal).Replace("<", "&lt;", StringComparison.Ordinal)
.Replace(">", "&gt;", StringComparison.Ordinal).Replace("\"", "&quot;", StringComparison.Ordinal);
private static int Limit(string key, string area, string? comment)
{
if (comment is not null && comment.Contains("long", StringComparison.OrdinalIgnoreCase)) return 200;