Spaces:
Running on Zero
Running on Zero
File size: 6,389 Bytes
70650b7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | # M18 β Translation Service
**Spec version:** v1.0 (Phase 2)
**Depends on:** M03 (bus), X04 (config), X03 (observability), `transformers`, `torch`
**Depended on by:** UI marketplace + chat (one-click translate), M19 STT (with `translate_to_en=true`)
---
## 1. Responsibility
Provide `trans.text@1.0`. Translate between languages, with strong emphasis on:
- German β English (default)
- German β Plattdeutsch (Niederrhein-specific, Christof's domain)
- Major European languages
- Optionally Arabic, Turkish, Russian, Ukrainian β useful in refugee-context emergencies
---
## 2. File layout
```
hearthnet/services/translation/
βββ __init__.py
βββ service.py
βββ backends/
βββ __init__.py
βββ base.py
βββ nllb.py # facebook/nllb-200-distilled-600M
βββ plattdeutsch.py # specialised fine-tune, optional
```
---
## 3. Public API
### 3.1 `backends/base.py`
```python
@dataclass(frozen=True)
class TranslationResult:
text: str
from_lang: str # ISO 639-1
to_lang: str
confidence: float # 0..1 if backend supports; else 1.0 placeholder
ms: int
class TranslationBackend(Protocol):
name: str
languages_pairs: list[tuple[str, str]] # supported (from, to) pairs
max_chars: int
async def warm(self) -> None: ...
async def close(self) -> None: ...
async def translate(
self,
text: str,
*,
from_lang: str, # "auto" supported
to_lang: str,
domain: str | None,
) -> TranslationResult: ...
def detect_language(self, text: str) -> str | None: ...
def health(self) -> dict: ...
```
### 3.2 Concrete backends
```python
class NllbBackend(TranslationBackend):
"""facebook/nllb-200-distilled-600M (or larger variants).
200+ language pairs out of the box."""
def __init__(
self,
model: str = "facebook/nllb-200-distilled-600M",
device: str = "auto",
max_chars: int = TRANSLATION_MAX_CHARS,
):
...
class PlattdeutschBackend(TranslationBackend):
"""Optional specialised fine-tune.
If a Plattdeutsch fine-tune is present in models_dir, registers deβnds pair.
Otherwise no-op (the backend reports zero language pairs and is filtered out)."""
def __init__(
self,
models_dir: Path,
device: str = "auto",
):
...
```
### 3.3 `service.py`
```python
class TranslationService:
name = "translation"
version = "1.0"
def __init__(self, config: TranslationConfig):
self._backends: list[TranslationBackend] = self._build_backends(config)
def capabilities(self) -> list[tuple[CapabilityDescriptor, Callable, ParamsPredicate]]:
"""One trans.text entry per backend. params declare languages_pairs."""
async def start(self) -> None: ...
async def stop(self) -> None: ...
def health(self) -> dict: ...
async def handle_translate(self, req: RouteRequest) -> dict:
"""CAP2 Β§4.10."""
```
### 3.4 `params_compatible` predicate
```python
def params_compatible(offered: dict, requested: dict) -> bool:
if "backend" in requested and requested["backend"] != offered.get("backend"):
return False
pair = (requested.get("from"), requested.get("to"))
if pair[0] == "auto":
# auto-detect; backend must support at least one source β target pair
return any(t == pair[1] for (_, t) in offered.get("languages_pairs", []))
return pair in offered.get("languages_pairs", [])
```
---
## 4. Behaviour
### 4.1 Auto-detection
`from: "auto"`:
1. Call `detect_language(text)` (NLLB has internal language detection)
2. Substitute detected lang
3. Translate
### 4.2 Domain hints
`domain: "everyday" | "medical" | "legal" | "emergency"` is advisory. NLLB ignores it; specialised fine-tunes may use it.
### 4.3 Niederrhein focus
`PlattdeutschBackend` is Christof's local interest. When installed:
- Registers pairs `("de", "nds")` and `("nds", "de")`
- Optionally `("en", "nds")` if fine-tune extends
- Used by the marketplace UI's "auf Platt" button in [M08 settings](../../modules/M08-ui.md) ext
### 4.4 Length limits
- Single request: β€ `TRANSLATION_MAX_CHARS` (4000)
- For longer texts, callers chunk by paragraph and recombine
### 4.5 Batching
Internal: requests within 100 ms batched up to 8 strings per forward pass. Improves GPU utilisation. Demultiplexed back. Transparent to callers.
### 4.6 Caching
In-memory LRU cache `(text_hash, from, to) β result`, max 10k entries. Big wins for marketplace UI which re-translates same posts on every refresh.
---
## 5. Errors
| Condition | Wire code |
|-----------|-----------|
| Pair not supported by any backend | `not_found` |
| Text too long | `bad_request` |
| Detection failed | `bad_request` |
| Backend OOM | `capacity_exceeded` |
---
## 6. Configuration
```python
config.translation.enabled = True
config.translation.backends = [
TranslationBackendConfig(name="nllb", model="facebook/nllb-200-distilled-600M", device="auto"),
TranslationBackendConfig(name="plattdeutsch", models_dir=Path("~/.hearthnet/models/plattdeutsch")),
]
```
Constants: `TRANSLATION_MAX_CHARS`.
---
## 7. Tests
### Unit
- `test_descriptor_schema_validates`
- `test_params_compatible_pair_must_match`
- `test_auto_detect_substitutes_source_lang`
- `test_text_too_long_rejected`
- `test_cache_hit_returns_immediately`
### Integration
- `test_german_to_english_quality` (BLEU above floor)
- `test_plattdeutsch_pair_registered_when_finetune_present`
- `test_marketplace_one_click_translate_end_to_end`
---
## 8. Cross-references
| What | Where |
|------|-------|
| `trans.text@1.0` wire | [CAP2 Β§4.10](../CAPABILITY_CONTRACT_v2.md) |
| STT translate-to-EN feature | [M19 Β§4.3](M19-stt-tts.md) |
| Marketplace one-click | [M08 ext](../../modules/M08-ui.md) |
| Niederrhein context | Christof's domain |
---
## 9. Open questions
1. **Fine-tune in-the-loop.** A community could fine-tune the Plattdeutsch model on its own corpus over time. Reserved.
2. **Document-level translation.** Currently per-string. Document-coherence translation (better than chunked) is Phase 3.
3. **Glossary support.** Domain glossaries (technical terms, names) preserved across translation. Phase 2.5.
|