Files
Sprachmittler/docs/TRANSLATION_OUTPUT.md
T
schihei 940abcc996 feat(settings): mother-tongue language routing table
Replace the single reverse-direction pair with a general routing table. The saved target is the mother tongue and the default target for every source; languageRoutes is an empty-by-default, source-unique list of source-to-target rules (for example Chinese -> English, Traditional Chinese -> English, German -> English). Rules apply only when the source is confidently detected; otherwise the mother tongue is used. Same-language rules are dropped.\n\nThe panel shows the effective direction and a banner explaining a rule, with a one-capture override back to the mother tongue; the panel picker is now a session-only override. Persistent rules are edited in Settings. The old autoSwitchTarget/fallbackTargetLanguage keys are ignored, so the default after migration is everything -> mother tongue.\n\nAdd LanguageRoute, generalize the direction policy and tests, add the rules UI, and update ADR-022, architecture, translation output, user guide, README and progress. Verified: make verify green; empty rules translate French -> German, a Chinese -> English rule produces Chinese (Simplified) -> English with the banner, and the rules table renders in Settings.
2026-11-26 18:31:45 +01:00

7.6 KiB
Raw Blame History

Translation output

Modules: SprachmittlerText (analysis, chunking), SprachmittlerEngines (prompt selection, validation). Load the translation-quality skill before changing anything here.

1. Prompt policy

  • Default Translation is the canonical prompt for v1. It is byte-exact in docs/HYMT3_MODEL.md §3.
  • v1 starts with Default Translation for every content class. Structured Data 1 (JSON/HTML/Markdown) and Delimiters are the only fallbacks, used once after a protected token was lost. They are selected by the deterministic PromptPolicy, never by a user instruction.
  • Terminology, Style and Structured Data 2 are reserved for future glossary/style/context features; not v1.
  • No other prompt text is allowed. The user cannot type a prompt in v1.

The prompt prefix depends only on the target language. Append the source last. Do not add timestamps, app names, source language or dynamic instructions.

2. Input normalisation (N1–N3)

Rule Transformation Notes
N1 Line endings → \n; strip BOM, NUL and C0 controls except \t and \n; Unicode NFC. Applied to the source before analysis and to the translation after T1.
N2 Trim outer whitespace. Internal whitespace is preserved.
N3 Keep zero-width joiner/non-joiner; strip U+200B. They matter in Indic scripts and emoji sequences.

3. Chunking

  • Paragraph boundaries (blank lines) first.
  • Then sentence boundaries (., !, ?, 。, !, ?, … followed by whitespace/end).
  • Then word boundaries; never split a grapheme cluster.
  • Limits: 4000 characters for Latin/Cyrillic/Greek; 2000 for CJK, Thai, Lao, Khmer, Burmese, Tibetan, Arabic-script and other dense scripts. The limit is script-based, not language-based.
  • Reassemble with the original separators (usually \n\n). Do not collapse or invent paragraph breaks.
  • Translate chunks sequentially; one request in flight.
  • A chunk failure stops the sequence and is shown as chunkFailed(index:); the panel keeps the partial translation and disables Replace.

4. Protected tokens

Scan the source for:

Kind Pattern examples
URL https://…, http://…, www.…
E-mail name@example.com
Mustache {{name}}, {{ name }}
Template literal ${name}
printf %s, %d, %1$@, %02d
Markdown code span `code`
Fenced code block ```…```
HTML tag <a href="…">, </div>
JSON key a quoted string followed by : inside a JSON object
File path /Users/…, C:\… (best effort)

Validation: every protected token in the source must appear in the translation exactly once (or the same count). If one is missing:

  1. Retry once with the documented Delimiters prompt (or Structured Data 1 for JSON/HTML/Markdown).
  2. If it is still missing, warning missingProtectedToken; Replace is disabled by default; Copy remains available.

Do not substitute tokens with sentinels in v1: sentinels can leak into the output and are harder to audit.

5. Output rules T1–T4

Rule Transformation Default
T1 Strip leading/trailing whitespace and NUL; line endings → \n. on
T2 Preserve internal whitespace, line breaks, Markdown, HTML, LaTeX and code exactly as produced. always
T3 No spelling, grammar, style, terminology or punctuation edits. No de-duplication. No "cleanup" of model wording. always
T4 Do not strip a preamble or explanation. Detect it, warn, keep the raw text, disable Replace by default. always

The panel shows the T1 output. There is no hidden rewrite. If the model returns a preamble, the user sees it. Markdown rendering in the panel is presentation only: validation, Copy and Replace all use the raw T1 string, including its Markdown markers. See ADR-021.

6. Preamble detection

Heuristic (not a rewrite):

  • The first non-empty line is at most 80 characters.
  • It ends with : (or :).
  • It is followed by a blank line and at least one more non-empty line.
  • It matches common forms in the target language or English: "Here is the translation", "Translation", "Übersetzung", "Hier ist die Übersetzung", "Translation:", etc. A pure : heuristic with the length rule is enough for v1; keep the list in one file.

If detected: warning preambleDetected(firstLine:); the panel shows a banner; Replace is disabled by default; the user can Copy the raw text or click Retry.

7. Truncation and repetition

  • done_reason == "length" → warning truncated; Replace disabled by default.
  • Repetition: the same normalised line (≥ 8 chars) repeated ≥ 6 times consecutively, or a 64-character window repeated ≥ 8 times in the last 2048 characters. Cancel the stream early and warn repetitionLoop.
  • Empty output after T1 → emptyOutput; no Copy/Replace of an empty string.

8. Same-language input and language routing

NLLanguageRecognizer reports the dominant language with a confidence and several candidates. Hypotheses below 0.05 are ignored, so a confident single-language text is not treated as mixed. The source is considered to be language X only when the confidence is at least 0.5 and every meaningful candidate resolves to X.

The saved target is the mother tongue. Every source language without a rule is translated into the mother tongue. Optional languageRoutes map a source language to a target language; a rule is used only when its source is confidently detected. Rules with source equal to target are ignored, and routes are deduplicated by source.

When a rule applies, the prompt, chunking and validation use its target. The panel shows the effective direction (for example "French → English"), a banner explains the rule, and "Translate to German" (the mother tongue) overrides the direction for that capture only. The panel's language picker is a session-only override; persistent rules are managed in Settings. When no rule applies, the same-language advisory appears if the source is the mother tongue.

Detection is advisory: short, mixed or uncertain text keeps the mother tongue, and the user can change the target for that result.

9. Numbers and units

Do not require exact string equality: locales legitimately change decimal and thousands separators. Normalise numeric tokens (remove spaces and thousands separators; map ,/. in ambiguous cases) and require the numeric value to be present. Units may be translated (tokens/s → Token/s); human review covers meaning.

10. CLI JSON output

sprachmittler-cli translate --json emits:

{
  "schema": "sprachmittler-translation-v1",
  "sourceLanguage": "en",
  "targetLanguage": "de",
  "model": "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
  "sourceCharacters": 148,
  "translation": "Die obige Grafik …",
  "warnings": [],
  "timing": { "firstTokenMs": 980, "totalMs": 6520, "promptTokens": 178, "outputTokens": 246 }
}

No source text is included unless --include-source is passed explicitly for debugging. Never write this JSON to disk automatically.

Until T2.4, sourceLanguage is null; until T2.5, warnings is empty. As of M2 both are populated: sourceLanguage is the advisory NLLanguageRecognizer code (still nullable) and warnings contains the stable warning codes from TranslationWarning.code. timing.promptTokens and timing.outputTokens are summed over chunks and retry attempts.

11. Tests

  • Prompt selection for each content class; default stays default.
  • Chunker round-trip and limits.
  • Every protected-token kind; missing-token retry; second failure blocks Replace.
  • Preamble, truncation, repetition, empty output.
  • Same-language warning.
  • T1 only: internal whitespace, Markdown and code unchanged.
  • Numeric normalisation.