Files
Sprachmittler/docs/TRANSLATION_OUTPUT.md
T
schihei 64078e2f04 feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)
M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes.

M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open.

Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
2026-11-26 13:30:32 +01:00

6.5 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.

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

If NLLanguageRecognizer reports the target language with confidence ≥ 0.5 and all detected candidates agree, show "This text already appears to be in {language}" and offer "Translate anyway". Do not block: short text, names and mixed text are often misdetected.

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.