Document-Level and Context-Aware Translation › Code Implementation
Language AI HandbookAll chapters We will build a small, self-contained pipeline that demonstrates the core mechanics: segmenting a document, simulating sentence-level terminology drift, measuring consistency, and enforcing glossary terms with placeholders. The point is to make the concepts concrete, not to build a production system. Real systems replace the toy translator with an NMT model or an LLM and add the safeguards discussed above.
Setup
The examples use NumPy and Matplotlib. The hidden first cell calls the book helper to seed the random number generators.
Segmenting a document
We start with a short English document and split it with a regular expression. This pattern splits after an abbreviation followed by a space, as in “Dr. Tan,” and misses a break when a closing quote follows the punctuation. Use a sentence segmenter when those cases matter.
PythonIn [5]Expand
import re
from collections import Counter
document = (
"Acme Cloud Storage keeps your files safe. "
"With Cloud Storage, Acme offers unlimited space for teams. "
"The Cloud Storage dashboard shows usage in real time. "
"Teams rely on Cloud Storage every day."
)
def segment(text):
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
sentences = segment(document)ConsoleOut [6]Expand
1. Acme Cloud Storage keeps your files safe. 2. With Cloud Storage, Acme offers unlimited space for teams. 3. The Cloud Storage dashboard shows usage in real time. 4. Teams rely on Cloud Storage every day.
The document contains four sentences, each mentioning the glossary term "Cloud Storage".
Simulating sentence-level terminology drift
The scripted baseline assigns one of three Spanish variants to each source sentence. Its fixed rule makes the example reproducible. It does not run a translation model.
PythonIn [7]Expand
VARIANTS = [
"almacenamiento en la nube",
"almacenamiento de nube",
"nube de almacenamiento",
]
def sentence_level_term(sentence, options):
key = sum(ord(c) for c in sentence)
return options[key % len(options)]
sentence_choices = [sentence_level_term(s, VARIANTS) for s in sentences]ConsoleOut [8]Expand
'nube de almacenamiento' <- Acme Cloud Storage keeps your files safe. 'almacenamiento de nube' <- With Cloud Storage, Acme offers unlimited space for teams. 'almacenamiento de nube' <- The Cloud Storage dashboard shows usage in real time. 'almacenamiento en la nube' <- Teams rely on Cloud Storage every day.
Each sentence gets a target term, but the choices are not coordinated. This is the sentence-level baseline.
Measuring consistency
We compute the majority-variant share, as defined earlier. The demonstration has one source occurrence per sentence. A score of 1.0 requires every occurrence to have the same rendering.
PythonIn [9]Expand
def consistency(choices):
# One entry per source occurrence, with None for a missing rendering.
counts = Counter(choice for choice in choices if choice is not None)
majority_count = max(counts.values(), default=0)
share = majority_count / len(choices) if choices else None
return share, counts
sentence_consistency, sentence_counts = consistency(sentence_choices)ConsoleOut [10]Expand
Majority-variant share: 50.00% Distinct variants used : 3 2x almacenamiento de nube 1x nube de almacenamiento 1x almacenamiento en la nube
The code fixture yields a different assignment from the hand-written illustration. It uses the required form once in four occurrences, so term accuracy is 25%. Its most common variant, almacenamiento de nube, appears twice, so the majority-variant share is 50%.
@fig-term-variant-counts shows the distribution.
VisualizationOut [11]Expand

The chart makes the drift visible. A document reader would see the same thing, spread across paragraphs.
Protecting glossary terms
Now we implement the placeholder pipeline. The function finds glossary terms, replaces them with placeholders, and returns the mapping needed to restore them. Terms are sorted by length so a multiword term takes precedence over a shorter match at the same starting position. The search scans left to right.
PythonIn [12]Expand
marker_pattern = re.compile(r"⟦T[0-9]+⟧", flags=re.IGNORECASE)
def protect(text, glossary):
if marker_pattern.search(text):
raise ValueError("Source text contains a reserved glossary marker")
if not glossary:
return text, {}
terms = sorted(glossary, key=len, reverse=True)
alternatives = "|".join(re.escape(term) for term in terms)
pattern = re.compile(rf"(?<!\w)(?:{alternatives})(?!\w)")
mapping = {}
def insert_marker(match):
placeholder = f"⟦T{len(mapping)}⟧"
mapping[placeholder] = glossary[match.group()]
return placeholder
return pattern.sub(insert_marker, text), mapping
def restore(text, mapping):
targets = {marker.casefold(): target for marker, target in mapping.items()}
observed = Counter(
match.group().casefold() for match in marker_pattern.finditer(text)
)
if observed != Counter(targets.keys()):
raise ValueError(
"Expected markers to appear exactly once after translation"
)
return marker_pattern.sub(
lambda match: targets[match.group().casefold()], text
)ConsoleOut [13]Expand
Protected : With ⟦T0⟧, ⟦T1⟧ offers unlimited space for teams.
Mapping : {'⟦T0⟧': 'almacenamiento en la nube', '⟦T1⟧': 'Acme'}
Restored : with almacenamiento en la nube, Acme offers unlimited space for teams.The toy translator changes ⟦T0⟧ to ⟦t0⟧. Restoration matches markers without regard to case and checks that each expected marker appears exactly once. The check also catches a marker dropped or duplicated by an engine.
Applying the pipeline to the document
We run every sentence through the pipeline. The toy translator lower-cases its input to simulate a transformation, then we restore the glossary targets.
PythonIn [14]Expand
def toy_mt(protected_text):
return protected_text.lower()
document_outputs = []
for s in sentences:
p, m = protect(s, glossary)
document_outputs.append(restore(toy_mt(p), m))
variant_pattern = re.compile(
r"(?<!\w)(?:"
+ "|".join(re.escape(variant) for variant in VARIANTS)
+ r")(?!\w)"
)
protected_choices = []
for output in document_outputs:
matches = variant_pattern.findall(output)
protected_choices.append(matches[0] if len(matches) == 1 else None)
protected_consistency, protected_counts = consistency(protected_choices)ConsoleOut [15]Expand
Acme almacenamiento en la nube keeps your files safe. with almacenamiento en la nube, Acme offers unlimited space for teams. the almacenamiento en la nube dashboard shows usage in real time. teams rely on almacenamiento en la nube every day. Protected majority-variant share: 100%
The scorer checks the restored output text for one recognized rendering per sentence because this fixture has one source occurrence per sentence. Every restored output contains the required term, giving a consistency score of 1.0 in @fig-term-consistency-before-after. The scripted baseline assigns variants by a separate rule. The bars compare the two fixtures and do not estimate the effect of enabling glossary protection on one translation model.
VisualizationOut [16]Expand

These graphs score Cloud Storage alone. The scorer recognizes a rendering at all four occurrences in both fixtures, so the term has 100% coverage in each. The accuracy check uses the glossary as its reference. A mistaken glossary entry could still score 1.0 against that reference, so verify the entries before scoring.
Consistency alone can hide systematic wrongness. The next cell computes matching term-accuracy values for the same four-sentence toy document and glossary, using the glossary target as the reference.
PythonIn [17]Expand
required_term = glossary["Cloud Storage"]
accuracy_sentence = sum(v == required_term for v in sentence_choices) / len(
sentence_choices
)
accuracy_protected = sum(v == required_term for v in protected_choices) / len(
protected_choices
)
metric_labels = ["Consistency", "Accuracy"]
sentence_metrics = [sentence_consistency, accuracy_sentence]
protected_metrics = [protected_consistency, accuracy_protected]
metric_positions = np.arange(len(metric_labels))VisualizationOut [18]Expand

Choosing a pronoun from a supplied antecedent
The pronoun example illustrates a different step. Given an antecedent whose features are already known, the toy function uses its gender and number to choose an English pronoun. The example supplies the antecedent directly.
PythonIn [19]Expand
def english_pronoun(entity):
if entity["number"] == "pl":
return "they"
return "he" if entity["gender"] == "m" else "she"
entities = [
{"name": "María", "gender": "f", "number": "sg"},
{"name": "el gerente", "gender": "m", "number": "sg"},
]
sentence_level_default = "he"
document_level_choice = english_pronoun(entities[0])ConsoleOut [20]Expand
Source (es): María llamó al banco. Dijo que enviaría el contrato. Sentence-level default pronoun : he Pronoun from supplied antecedent: she
The fixture assumes that María is the intended subject of Dijo and supplies her features directly. A translation system that resolves the subject would have to infer it before choosing the pronoun.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!