restore source edge whitespace on translated fragments
Formatting splits a sentence across text nodes mid-phrase, and no model reliably reproduces a fragment's leading or trailing whitespace — a dropped edge space glues two words together once the fragments are concatenated back into the document. The source fragment now decides the edges.
This commit is contained in:
parent
7dfad0ee07
commit
b94df99297
1 changed files with 13 additions and 1 deletions
|
|
@ -26,6 +26,16 @@ export async function translateText(
|
||||||
return translated[0] ?? ''
|
return translated[0] ?? ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Restore the source fragment's leading/trailing whitespace on a translation.
|
||||||
|
// No model reliably reproduces edge whitespace, and formatting splits sentences
|
||||||
|
// mid-phrase, so a dropped edge space glues two words together in the rendered
|
||||||
|
// output. The source fragment is authoritative for the edges.
|
||||||
|
function restoreEdgeWhitespace(source: string, translated: string): string {
|
||||||
|
const leading = source.match(/^\s*/)![0]
|
||||||
|
const trailing = source.match(/\s*$/)![0]
|
||||||
|
return leading + translated.trim() + trailing
|
||||||
|
}
|
||||||
|
|
||||||
export async function translateTexts(
|
export async function translateTexts(
|
||||||
texts: string[],
|
texts: string[],
|
||||||
targetLanguage: string,
|
targetLanguage: string,
|
||||||
|
|
@ -49,7 +59,9 @@ export async function translateTexts(
|
||||||
const translated = await openrouterTranslateTexts(translatable, targetLanguage, sourceLanguage)
|
const translated = await openrouterTranslateTexts(translatable, targetLanguage, sourceLanguage)
|
||||||
|
|
||||||
const out = [...texts]
|
const out = [...texts]
|
||||||
indexes.forEach((target, i) => { out[target] = translated[i]! })
|
indexes.forEach((target, i) => {
|
||||||
|
out[target] = restoreEdgeWhitespace(texts[target]!, translated[i]!)
|
||||||
|
})
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue