translator-common
marginalia/libs/translator-common is what the Conlang Translator and the Real Language Translator share, written so that a third plugin can use it: any plugin that
keeps a story in one language and lets the models, the exports and the readers deal with another. Read Libraries for plugins first for how a library is embedded
and what that implies (a copy per plugin, no shared state, parameters instead of constants).
The idea
A translator plugin stores the translated text in the story and keeps the text the model wrote it from, the source, beside it:
flowchart LR
subgraph Story["a part"]
T["stored text<br/>… “Da ja-se vek.” …"]
P["AnchoredPassage<br/>(range of the speech)<br/>attributes: Span<br/>source, speaker, hash"]
end
T --- P
P -->|Reverse| M["what a model reads<br/>… “I see the enemy.” …"]
P -->|SpeechExportContributor| E["an export<br/>translation / source / footnotes"]
P -->|ReaderText + ReaderView| R["the reader of a published book<br/>click shows the source"]
P -->|SourcePopover| A["the author's click"]Everything that gives the story to a model reads the source (PartTextRegistry, The text a model reads), the export is decided by the author in the
dialog (The text of an export), and a click shows the source. The translation itself (the prompt, the answer, what is acceptable) is the plugin's: that is
where an invented language (a lexicon, new words) and a real one (a script, politeness) differ, so it is not in the library.
What is in it
Building a translator plugin on it
marginalia/plugins/reallang-translator is the smaller example (no lexicon, no designer); the Conlang Translator is the larger one. The steps:
1. The identity of your plugin. The id of your passage kind and the CSS class of the mark are yours, unique among plugins:
public final class MyKind {
public static final String ID = "my-translator.speech"; // the id of the kind
public static final String MARK = "my-passage"; // the CSS class of the mark
}
and the rule for the mark in your own CSS (mark.my-passage { border-bottom: 1px dotted ...; cursor: help; }).
2. Register in onExtensionLoad:
PluginLog.set(log);
PassageAccess passages = new PassageAccess(MyKind.ID);
passageKinds.register(new SpeechPassageKind(MyKind.ID, MyKind.MARK)); // the mark and the click
partTexts.register(owner, new SpeechTransformer(passages)); // the models read the source
exportTexts.register(owner, new SpeechExportContributor(passages, session -> chosenMode(session))); // the export
passageKinds is the core's PassageKinds, partTexts the PartTextRegistry, exportTexts the ExportTextRegistry; unregister all three in onExtensionUnload. chosenMode
reads the field you added to the export dialog (below); return null or ExportMode.TRANSLATED for no change.
3. The export field. Decorate ExportDialog.createExtensionFields on leave, add ExportChoice.field(label, mode -> text) to the list it returns and keep it in a
WeakHashMap keyed by the dialog (instrumented); chosenMode(session) is map.get(session.source()).getValue(). Add the field only for a book that has your passages.
4. The viewer. Decorate Viewer.createPart on leave: when the part has passages of your kind (passageService.listForParts(ids, MyKind.ID)), call
ReaderView.apply(view, part, mode, TranslatedPassages.of(passageService, passageKinds, partId), p -> TranslatedPassages.markClass(passageKinds, p, MyKind.MARK)); the mode is
ReaderMode.of(...) of the book's setting for the readers. Passing the passages of every plugin is what makes a book that holds two kinds draw right (see below).
5. CSS and texts. ExtensionHasCss.getCss returns CommonStyles.css() + "\n" + MyStyles.css() for Main and Viewer. Your own texts are your own
PluginLocalizationBundle; the library's screens have theirs.
6. Translating a part (yours; the library gives the pieces). The shape both plugins follow:
TranslationWriter writer = new TranslationWriter(MyKind.ID);
Reverse.Result read = writer.readOf(part); // the English of a part that is translated already
String source = read.text(); // what you send to the model
String raw = new ModelClient("my-translator").ask(model, book, system, user);
// parse the answer (ModelJson.object finds the JSON in it), check it (the quote is in `source`, the language is right...), then
List<TranslationPlan.Accepted> accepted = ...; // (speech, start, end) of the ones you accept
TranslationPlan plan = TranslationPlan.make(source, accepted);
writer.write(book, part, plan, read, languageId, modelName,
(span, planned) -> span.setReading(readingOf(planned.speech()))); // what only you know goes on the Span
write replaces the text of the part with a version in the history (ChatMessageService.replaceText: a text that says what the old one said, The text a model
reads), removes the old passages of the part except the ones the author edited, and makes a passage of every planned speech;
it throws TranslationWriter.ChangedMeanwhile when the part is not what you read. writeSelection does the same for one sentence the author selected, revert puts the source back.
Run it on a worker thread: PartRuns for a part, RangeRuns (with RangeLoop) for a range, new RangeDialog(...) for the window of a range.
7. Who speaks. Keep a Speakers in the attributes of the book (it is Gson-friendly) and give the author new SpeakersEditor(speakers, onChange); put the notes of the
characters in your prompt.
8. More than one language in a book (both plugins do it; it needs nothing from the core). The book keeps the language it names first (the inherited setting) with Speakers, and a list of
BookLanguage for the others. A translation is one pass per language: the rules, the lexicon and the speakers of one language, and only its speeches. The passes run one after the other, and a pass must
leave the speeches of the other languages translated, which write does when the plan holds them:
Reverse.Result read = writer.readOf(part); // the English of ALL the languages
List<TranslationPlan.Accepted> carried = writer.carried(part, read, languageId); // the speeches of the other languages (a RunScope.MISSING run: carried(part, read, languageId, true), all of them)
// ... ask the model for this language; drop the accepted speeches that TranslationWriter.overlapsAny(carried, start, end)
accepted.addAll(carried);
TranslationPlan plan = TranslationPlan.make(read.text(), accepted);
if (plan.translatedCount() == 0) { /* nothing was translated in this pass */ }
writer.write(book, part, plan, read, languageId, modelName, extra); // the carried passages are made again with their own Span
The passages tell their language (Span.language), so a retranslation or a revert of one language (writer.revert(book, part, read, languageId)) leaves the others alone, and
Speakers.mayBeInvolved(Speakers.namesOf(pov, present)) spares the request for a language none of whose speakers is in the part. The menus ask the language with LanguageChoiceDialog, the range
dialog has a field for it, and the commands take an optional language.
The contract a passage depends on
A passage is used only when the text at its range still has the hash it was made for (Span.isEdited). Every consumer in the library checks it (the reverse, the export,
the popover). It is what keeps the author's edits safe (an edited speech has no trustworthy source and is left as it is) and what lets the passage of another plugin, whose
range an earlier edit shifted, drop out instead of corrupting text. If you write a consumer of your own passages, apply the same check; Reverse, ExportText and
SourcePopover have tests that pin it.
Two plugins in one book
Each plugin has its own passage kind, so the passages never mix. Models read the source of both (PartTextRegistry merges the substitutions of every transformer on
the stored text); the export puts both plugins' edits together once (The text of an export). The published book's viewer draws a part once, from the
passages of every plugin (TranslatedPassages), each with the mark of its own kind: the first plugin whose decorator reaches the part does it for both (ReaderView leaves a flag on
the part, a string key, so the copy of the class in the other bundle sees it) and the second finds it done. The consequence for a book with both is that one reader mode rules
the page (the one of the plugin that decorates first); the author sets the same in both. A click finds its passage in the list that was drawn, whichever plugin it is.
A translator does not read the translated speech of the other plugin as its source: the stored text it sends to its model has the other plugin's translation in it (only its own passages are reversed), so the model sees that speech in the other language and, being told to translate the English, leaves it alone.
Tests
The library has plain unit tests (mvn test in marginalia/libs/translator-common): ReverseTest, TranslationPlanTest, SelectionRangeTest, SpanTest, SpeakersTest,
SpeechTransformerTest, ExportTextTest (through the core registry), ReaderTextTest, RangeLoopTest, CarriedSpeechesTest (the speeches of the other languages kept through a write and a revert), TranslationWriter has no other unit test here (it needs the services; the plugins' tests of the translation go through it), ModelJsonTest, SourcePopoverTest (a Vaadin component built without a browser: the
library's test dependencies include the servlet API for that) and TranslatorCommonLocalizationTest (every text has its Japanese and Chinese translation, with the same
%s / %d placeholders). A plugin that adds texts to its own bundle has its own such test (ConlangTranslatorLocalizationTest is the template).