Files
Sprachmittler/docs/TRANSLATION_OUTPUT.md
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00

130 lines
8.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.
- Part size: **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.
- Capture limit: part size × `maximumPartsPerSelection` (1–8, default **1**). `1` rejects a selection longer than one part; higher values accept it and translate it part by part. The dense part size is configurable up to 4000.
- Reassemble with the original separators (usually `\n\n`). Do not collapse or invent paragraph breaks.
- Translate parts sequentially; one request in flight.
- Show “Part i of n” while a multi-part request streams and “n parts” when it finishes.
- A part 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:
```json
{
"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.