Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

i18n(de): the tooling for a staged German exercise-name pack

Mirko Köster5fb7f53959fa
diff --git a/scripts/build-de-exercise-names.mjs b/scripts/build-de-exercise-names.mjs
new file mode 100644
index 000000000..bcf14c8c2
--- /dev/null
+++ b/scripts/build-de-exercise-names.mjs
@@ -0,0 +1,45 @@
+#!/usr/bin/env node
+// Regenerates frontend/src/exercise-names/de.js from the curated source in
+// scripts/exercise-name-sources/de.json.
+//
+// node scripts/build-de-exercise-names.mjs
+//
+// German ships as a stage: the 999 catalogue entries that use equipment, and not the 325
+// body-weight ones, whose names keep their English title through the per-exercise fallback in
+// exerciseNameFor. The coverage gate below is therefore not "how many" but "exactly which" —
+// a pack that quietly lost a dumbbell entry, or gained a body-weight one, is a different
+// promise from the one the README makes.
+
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { stagedExercises } from './de-name-rules.mjs'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const sourcePath = join(root, 'scripts', 'exercise-name-sources', 'de.json')
+const outputPath = join(root, 'frontend', 'src', 'exercise-names', 'de.js')
+const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js')
+
+const source = JSON.parse(readFileSync(sourcePath, 'utf8'))
+const { EXDB } = await import(pathToFileURL(exercisesPath))
+const staged = stagedExercises(EXDB)
+const expected = new Set(staged.map(exercise => exercise.id))
+const known = new Map(EXDB.map(exercise => [exercise.id, exercise]))
+
+for (const id of Object.keys(source)) {
+ const exercise = known.get(id)
+ if (!exercise) throw new Error(`Unknown exercise ID: ${id}`)
+ if (typeof source[id] !== 'string' || !source[id].trim()) throw new Error(`${id}: name must be a non-empty string`)
+ if (!expected.has(id)) throw new Error(`${id} (${exercise.n}) is ${exercise.eq || 'equipment-free'} — outside the staged equipment set`)
+}
+const missing = staged.filter(exercise => !source[exercise.id])
+if (missing.length) {
+ const sample = missing.slice(0, 5).map(exercise => `${exercise.id} (${exercise.n})`).join(', ')
+ throw new Error(`Incomplete de exercise names: ${Object.keys(source).length}/${staged.length} — missing ${missing.length}, e.g. ${sample}`)
+}
+
+const ordered = {}
+for (const exercise of staged) ordered[exercise.id] = source[exercise.id].trim()
+mkdirSync(dirname(outputPath), { recursive: true })
+writeFileSync(outputPath, '// generated by scripts/build-de-exercise-names.mjs — edit scripts/exercise-name-sources/de.json\nexport default ' + JSON.stringify(ordered) + '\n')
+console.log(`Generated ${staged.length}/${EXDB.length} de exercise names (equipment exercises; ${EXDB.length - staged.length} body-weight names stay English).`)
diff --git a/scripts/de-name-rules.mjs b/scripts/de-name-rules.mjs
new file mode 100644
index 000000000..3853bd871
--- /dev/null
+++ b/scripts/de-name-rules.mjs
@@ -0,0 +1,155 @@
+// The German exercise-name rules, in one place. Imported by translate-de-exercise-names.mjs,
+// which checks every batch during translation and sends violations back to the model as a
+// correction, and by frontend/src/lib/de-exercise-names.test.js, which fails the build. The two
+// callers share this definition deliberately: inline copies are how a rule drifts unseen.
+//
+// Every `fix` quotes the offending word. A generic instruction ("use the German term") is
+// ignored by a small model often enough to stall a stage; naming the text is what lands.
+
+// German ships as a stage: the catalogue entries done with equipment, and not the body-weight
+// ones, which keep their English title through the per-exercise fallback in exerciseNameFor.
+// The builder, the translator and the test all read the staged set from here, so "which
+// exercises does German cover" has exactly one answer.
+export const BODY_WEIGHT = 'body weight'
+export const stagedExercises = EXDB => EXDB.filter(exercise => exercise.eq && exercise.eq !== BODY_WEIGHT)
+
+// Equipment is identity: a barbell row and a dumbbell row are different exercises, so the
+// German name has to carry the same equipment the catalogue records. Keyed by the EXDB `eq`
+// field rather than by words in the English title, which names the same machine differently
+// from one entry to the next ("lever seated calf raise" is a leverage machine). The required
+// terms are the ones frontend/src/locales/de.js already shows in the equipment filter — a name
+// that called a Kabelzug a "Seilzug" would read as a different machine from the one the filter
+// offers.
+export const EQUIPMENT_TERMS = [
+ ['upper body ergometer', /Oberkörper-?Ergometer/iu, 'Oberkörper-Ergometer'],
+ ['olympic barbell', /Olympia-?(Langhantel|Stange)/iu, 'Olympia-Langhantel'],
+ ['elliptical machine', /Crosstrainer/iu, 'Crosstrainer'],
+ ['stepmill machine', /Treppenmaschine|Stepper/iu, 'Treppenmaschine'],
+ ['leverage machine', /Hebelmaschine|Maschine|Gerät/iu, 'Hebelmaschine'],
+ ['resistance band', /Widerstandsband|Fitnessband|Band/iu, 'Widerstandsband'],
+ ['stability ball', /Gymnastikball/iu, 'Gymnastikball'],
+ ['stationary bike', /Ergometer|Fahrradergometer/iu, 'Ergometer'],
+ ['medicine ball', /Medizinball/iu, 'Medizinball'],
+ ['skierg machine', /SkiErg/iu, 'SkiErg'],
+ ['smith machine', /Multipresse/iu, 'Multipresse'],
+ ['wheel roller', /Bauchroller|Bauchrad/iu, 'Bauchroller'],
+ ['sled machine', /Schlitten/iu, 'Schlitten'],
+ ['ez barbell', /SZ-?(Stange|Hantel)/iu, 'SZ-Stange'],
+ ['bosu ball', /Bosu/iu, 'Bosu-Ball'],
+ ['kettlebell', /Kettlebell/iu, 'Kettlebell'],
+ ['trap bar', /Trap-?(Stange|Bar)/iu, 'Trap-Stange'],
+ ['dumbbell', /Kurzhantel/iu, 'Kurzhantel'],
+ ['barbell', /Langhantel/iu, 'Langhantel'],
+ ['cable', /Kabelzug|Kabel/iu, 'Kabelzug'],
+ ['roller', /Rolle|Roller/iu, 'Rolle'],
+ ['hammer', /Hammer/iu, 'Hammer'],
+ ['rope', /Seil|Rope/iu, 'Seil'],
+ ['tire', /Reifen/iu, 'Reifen'],
+ ['band', /Band/iu, 'Band'],
+]
+
+// Qualifiers that change what the exercise is, rather than how it is described. Dropping
+// "assisted" or "one arm" silently turns the name into another exercise that already exists in
+// the catalogue. Variants are generous on purpose: only the distinction has to survive.
+export const QUALIFIER_TERMS = [
+ ['assisted', /assistiert|unterstützt/iu, 'assistiert'],
+ ['weighted', /Zusatzgewicht|gewichtet|mit Gewicht/iu, 'mit Zusatzgewicht'],
+ ['one arm|single arm|one-arm|single-arm', /einarmig|einem Arm/iu, 'einarmig'],
+ ['one leg|single leg|one-leg|single-leg', /einbeinig|einem Bein/iu, 'einbeinig'],
+ ['seated', /sitzend|Sitzen|Sitz/iu, 'sitzend'],
+ ['standing', /stehend|Stehen|Stand/iu, 'stehend'],
+ ['lying', /liegend|Liegen/iu, 'liegend'],
+ ['kneeling', /kniend|Knien/iu, 'kniend'],
+ ['incline', /Schräg|schräg/u, 'Schrägbank'],
+ ['decline', /Negativ|negativ/u, 'Negativbank'],
+]
+
+// Terminology the prompt asks for but no rule enforces, because the idiomatic German name is
+// often built from a different word than the muscle it trains ("lat pulldown" is a Latzug, not
+// a Latissimus-anything). Enforcing these produced false failures on correct names.
+export const PREFERRED_TERMS = [
+ ['glutes', 'Gesäß'], ['hamstrings', 'Beinbeuger'], ['quads', 'Beinstrecker'],
+ ['lats', 'Latissimus (im Namen meist „Latzug")'], ['abs', 'Bauch'], ['calves', 'Waden'],
+ ['delts', 'Schultern'], ['triceps', 'Trizeps'], ['biceps', 'Bizeps'],
+ ['press', 'Drücken'], ['row', 'Rudern'], ['squat', 'Kniebeuge'], ['deadlift', 'Kreuzheben'],
+ ['curl', 'Curl'], ['raise', 'Heben'], ['extension', 'Strecken'], ['fly', 'Fliegende'],
+ ['pull-up', 'Klimmzug'], ['push-up', 'Liegestütz'], ['lunge', 'Ausfallschritt'],
+ ['crunch', 'Crunch'], ['plank', 'Plank'], ['stretch', 'Dehnung'],
+]
+
+// Words that are the established German term too, so finding them in both names is not a leak.
+// This list is the escape hatch from the inverted check below — every entry is a decision.
+const LOANWORDS = new Set([
+ 'bosu', 'burpee', 'burpees', 'crunch', 'crunches', 'curl', 'curls', 'dip', 'dips',
+ 'ergometer', 'hack', 'hammer', 'kettlebell', 'kettlebells', 'pilates', 'plank', 'planks',
+ 'romanian', 'scott', 'sit-up', 'sit-ups', 'skierg', 'smith', 'sprint', 'sprints', 'step',
+ 'stepper', 'sumo', 'trap', 'yoga', 'v', 't', 'x', 'z', 'l', 'band', 'bands',
+ // German gyms say Battle Ropes, not Kampfseile; the rope rule accepts either word for that
+ // reason. Everything else on this list is a term with no German equivalent in use.
+ 'battle', 'battling', 'rope', 'ropes',
+])
+
+// Swiss spellings of words this codebase writes with ß. DATE_LOCALES maps de to de-DE, and
+// de-CH is derived from de by replacing ß with ss (i18n-core.js) — so the base pack has to be
+// the ß one, or the Swiss locale derives nothing and the two spellings drift apart again.
+// No trailing boundary: German compounds ("Gesässdehnung", "Fussgelenk") are exactly where the
+// Swiss form hides. "Masse" is left out on purpose — it is legitimate German for mass, and only
+// vowel length tells it apart from Maße, which is why the derivation runs ß → ss and never back.
+const SWISS_FORMS = /\b(gesäss|füsse|fuss|gross|aussen|schliess|strasse)\w*/iu
+
+const words = s => s.toLowerCase().match(/[a-zäöüß][a-zäöüß-]*/giu) || []
+
+// Returns [] for a name that breaks nothing. `exercise` is an EXDB entry (its `n` and `eq` are
+// what the rules read). Each violation is { rule, fix }; `fix` is written as an instruction that
+// quotes the actual text, because that is what a 12B model acts on.
+export function checkName(exercise, german) {
+ const english = exercise.n
+ const equipment = exercise.eq
+ const violations = []
+ const add = (rule, fix) => violations.push({ rule, fix })
+ const name = typeof german === 'string' ? german : ''
+
+ if (!name.trim()) return [{ rule: 'empty', fix: `Translate "${english}" — the name is empty.` }]
+ if (name !== name.trim()) add('whitespace', `Remove the leading or trailing space from "${name}".`)
+ if (/[.!?]$/u.test(name)) add('punctuation', `Remove the final "${name.slice(-1)}" from "${name}" — a name is not a sentence.`)
+ if (/[()]/u.test(name)) add('parentheses', `Remove the parentheses from "${name}" — the app appends the English title itself.`)
+ if (name[0] !== name[0].toLocaleUpperCase('de')) add('capitalisation', `Start "${name}" with a capital letter.`)
+
+ const swiss = name.match(SWISS_FORMS)
+ if (swiss) add('sharp-s', `Write "${swiss[0]}" with ß, not ss — the app derives the Swiss spelling itself.`)
+
+ const [, required, term] = EQUIPMENT_TERMS.find(([eq]) => eq === equipment) || []
+ if (required && !required.test(name)) {
+ add('equipment', `"${english}" is done with a ${equipment}: the German name must say "${term}". "${name}" does not.`)
+ }
+ for (const [pattern, required, term] of QUALIFIER_TERMS) {
+ if (!new RegExp(`(^|[^a-z])(${pattern})([^a-z]|$)`, 'iu').test(english)) continue
+ if (!required.test(name)) add('qualifier', `"${english}" is ${pattern.split('|')[0]}: the German name must say "${term}". "${name}" does not.`)
+ }
+
+ // Inverted English-leak check: anything the German name shares with the English one is a leak
+ // unless it is on the loanword list. An enumerated list of forbidden English words missed a
+ // different word every time it was written.
+ const englishWords = new Set(words(english))
+ for (const word of new Set(words(name))) {
+ if (!englishWords.has(word) || LOANWORDS.has(word)) continue
+ add('english', `"${word}" is still English in "${name}". Write the German word instead.`)
+ }
+ return violations
+}
+
+// The terminology block the translator puts in its prompt. Built from the tables above so the
+// prompt and the checks can never describe different rules.
+export function promptGlossary() {
+ const line = ([english, , term]) => `- ${english} → ${term}`
+ return [
+ 'EQUIPMENT (identity — always carry it over):',
+ ...EQUIPMENT_TERMS.map(line),
+ '',
+ 'QUALIFIERS (identity — always carry them over):',
+ ...QUALIFIER_TERMS.map(([english, , term]) => `- ${english.split('|')[0]} → ${term}`),
+ '',
+ 'PREFERRED TERMS (use unless the idiomatic German name is built differently):',
+ ...PREFERRED_TERMS.map(([english, term]) => `- ${english} → ${term}`),
+ ].join('\n')
+}
diff --git a/scripts/exercise-name-sources/README.md b/scripts/exercise-name-sources/README.md
index b35d3ae55..e1380000a 100644
--- a/scripts/exercise-name-sources/README.md
+++ b/scripts/exercise-name-sources/README.md
@@ -21,3 +21,46 @@ The initial translations were produced from the English EXDB titles with LLM
assistance and must not be described as reviewed by a native speaker unless a
named human reviewer completes that review. They are original translations and
were not copied from another Portuguese exercise dataset.
+
+---
+
+# German exercise names
+
+`de.json` is the editable source for the German exercise-name pack, and it
+covers a stage rather than the whole catalogue: the 999 built-in exercises
+that use equipment, and not the 325 whose equipment is `body weight`. Those
+keep their English title — the app falls back per exercise, so a partial pack
+costs nothing beyond the names it does not yet carry. Which exercises the
+stage contains is enforced, not approximate: `scripts/de-name-rules.mjs`
+defines the set, and the builder refuses a source that misses one of them or
+adds a body-weight entry.
+
+`de-CH` ships no pack of its own. It derives this one by replacing ß with ss,
+so German names are written with ß here and the Swiss spelling follows
+automatically.
+
+Generate the runtime pack with:
+
+```sh
+node scripts/build-de-exercise-names.mjs
+```
+
+Translate a stage — one equipment family at a time, dry run first, `--apply`
+to write:
+
+```sh
+node scripts/translate-de-exercise-names.mjs --equipment='trap bar'
+node scripts/translate-de-exercise-names.mjs --equipment=dumbbell --apply
+```
+
+Equipment and identity-changing qualifiers (assisted, weighted, one-arm,
+seated, incline …) are checked against `scripts/de-name-rules.mjs` while the
+batch is still in hand: a violation goes back to the model as a correction
+naming the offending word, and a batch that cannot be fixed is never written.
+The same rules run again in `frontend/src/lib/de-exercise-names.test.js`, so
+CI fails on anything edited in by hand afterwards.
+
+The translations were produced from the English EXDB titles with LLM
+assistance and must not be described as reviewed by a native speaker unless a
+named human reviewer completes that review. They are original translations and
+were not copied from another German exercise dataset.
diff --git a/scripts/translate-de-exercise-names.mjs b/scripts/translate-de-exercise-names.mjs
new file mode 100644
index 000000000..6dbd1a0cf
--- /dev/null
+++ b/scripts/translate-de-exercise-names.mjs
@@ -0,0 +1,196 @@
+#!/usr/bin/env node
+// Translates a stage of English exercise titles into German, in schema-validated, checkpointed
+// batches. Mirrors translate-pt-br-exercise-names.mjs, with the rule check and correction loop
+// translate-de-stage.mjs proved necessary; see exercise-name-sources/README.md.
+//
+// node scripts/translate-de-exercise-names.mjs --equipment=dumbbell [--limit=40] [--apply]
+// node scripts/translate-de-exercise-names.mjs --ids=0025,1234 --max-retries=2
+//
+// Without --apply nothing is written: the batch is translated, checked and printed English
+// beside German, which is the cheap way to judge a prompt or model change before a whole stage
+// rides on it. Body-weight exercises are outside the staged set and are never offered here.
+
+import { spawnSync } from 'node:child_process'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { checkName, promptGlossary, stagedExercises } from './de-name-rules.mjs'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const sourcePath = join(root, 'scripts', 'exercise-name-sources', 'de.json')
+const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js')
+const claude = process.env.CLAUDE_BIN || 'claude'
+const codex = process.env.CODEX_BIN || 'codex'
+
+const option = name => process.argv.find(arg => arg.startsWith(`--${name}=`))?.split('=').slice(1).join('=')
+const equipment = option('equipment')
+// Named exercises, for re-running the handful a review rejected without touching the rest.
+const ids = option('ids')?.split(',').map(id => id.trim()).filter(Boolean)
+const provider = option('provider') || 'claude'
+const limit = Number(option('limit') || (ids ? ids.length : 40))
+const batchSize = Number(option('batch-size') || 40)
+const maxRetries = Number(option('max-retries') ?? 2)
+const apply = process.argv.includes('--apply')
+
+if (!equipment && !ids) throw new Error('Usage: translate-de-exercise-names.mjs (--equipment=dumbbell|all | --ids=0025,1234) [--limit=40] [--batch-size=40] [--max-retries=2] [--provider=claude|codex] [--model=NAME] [--apply]')
+if (equipment && ids) throw new Error('Pass --equipment or --ids, not both')
+if (!['claude', 'codex'].includes(provider)) throw new Error('provider must be claude or codex')
+const model = option('model') || (provider === 'claude' ? 'sonnet' : '')
+if (!Number.isInteger(limit) || limit < 1 || !Number.isInteger(batchSize) || batchSize < 1) {
+ throw new Error('limit and batch-size must be positive integers')
+}
+
+// The first stage of a language creates the source file; every later one extends it.
+const translations = existsSync(sourcePath) ? JSON.parse(readFileSync(sourcePath, 'utf8')) : {}
+const { EXDB } = await import(pathToFileURL(exercisesPath))
+const staged = stagedExercises(EXDB)
+const inStage = new Map(staged.map(exercise => [exercise.id, exercise]))
+
+const selected = ids
+ ? ids.map(id => {
+ const exercise = inStage.get(id)
+ // Loud, because a typo'd or body-weight ID would otherwise just shorten the sample silently.
+ if (!exercise) throw new Error(`${id} is not in the staged equipment set (unknown, or body weight)`)
+ return exercise
+ })
+ : equipment === 'all' ? staged : staged.filter(exercise => exercise.eq === equipment)
+
+if (!selected.length) throw new Error(`No staged exercises for --equipment=${equipment}. Values are the catalogue's own, e.g. dumbbell, cable, barbell, "leverage machine".`)
+const pending = selected.filter(exercise => !translations[exercise.id]).slice(0, limit)
+const skipped = selected.length - selected.filter(exercise => !translations[exercise.id]).length
+if (skipped) console.log(`Skipping ${skipped} of ${selected.length} selected: already in de.json.`)
+if (!pending.length) {
+ console.log('Everything selected is already translated.')
+ process.exit(0)
+}
+
+const next = { ...translations }
+// One request to whichever provider, returning the parsed { translations: [...] } envelope.
+// Extracted so the caller can retry it with a correction prompt without duplicating any of it.
+// Async like its sibling in translate-de-stage.mjs, so a provider that speaks HTTP rather than
+// a subprocess slots in without turning the loop below inside out.
+const requestStructured = async (prompt, batch) => {
+ let structured
+ const schema = {
+ type: 'object',
+ properties: {
+ translations: {
+ type: 'array', minItems: batch.length, maxItems: batch.length,
+ items: {
+ type: 'object',
+ properties: { id: { type: 'string' }, name: { type: 'string', minLength: 1 } },
+ required: ['id', 'name'], additionalProperties: false
+ }
+ }
+ },
+ required: ['translations'], additionalProperties: false
+ }
+ if (provider === 'claude') {
+ const result = spawnSync(claude, [
+ '-p', '--model', model, '--effort', 'high', '--no-session-persistence',
+ '--permission-mode', 'dontAsk', '--disallowedTools', 'Bash', 'Edit', 'Write', 'Read',
+ '--output-format', 'json', '--max-budget-usd', '2', '--json-schema', JSON.stringify(schema)
+ ], { input: prompt, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
+ if (result.status !== 0) throw new Error(result.stderr || result.stdout || `Claude exited ${result.status}`)
+ const envelope = JSON.parse(result.stdout)
+ if (envelope.is_error || !envelope.structured_output) throw new Error(envelope.result || 'Claude returned no structured output')
+ structured = envelope.structured_output
+ } else {
+ const temp = mkdtempSync(join(tmpdir(), 'opengym-de-names-'))
+ const schemaPath = join(temp, 'schema.json')
+ const outputPath = join(temp, 'output.json')
+ try {
+ writeFileSync(schemaPath, JSON.stringify(schema))
+ const result = spawnSync(codex, [
+ 'exec', '--skip-git-repo-check', '--ephemeral', '--ignore-user-config',
+ '--sandbox', 'read-only', '--output-schema', schemaPath,
+ '--output-last-message', outputPath, '-'
+ ], { input: prompt, encoding: 'utf8', cwd: temp, maxBuffer: 16 * 1024 * 1024 })
+ if (result.status !== 0) throw new Error(result.stderr || result.stdout || `Codex exited ${result.status}`)
+ structured = JSON.parse(readFileSync(outputPath, 'utf8'))
+ } finally {
+ rmSync(temp, { recursive: true, force: true })
+ }
+ }
+ return structured
+}
+
+for (let start = 0; start < pending.length; start += batchSize) {
+ const batch = pending.slice(start, start + batchSize)
+ const input = batch.map(({ id, n, bp, eq, tg }) => ({ id, english: n, bodyPart: bp, equipment: eq, target: tg }))
+ const basePrompt = `Translate every exercise title below into concise, natural German for a gym app.
+
+Rules:
+- Return only the structured JSON required by the schema, with every ID exactly once and in input order.
+- Return only the German title in "name". Do not append, repeat or bracket the English title — the app shows it itself.
+- A title is a noun phrase, not a sentence: no final full stop, and German noun capitalisation ("Bankdrücken mit Langhantel", "Rudern am Kabelzug").
+- Preserve exercise identity: equipment, stance, grip, direction, side, assisted/weighted status and version qualifiers all distinguish one catalogue entry from another.
+- Prefer established German gym terminology (Bankdrücken, Kniebeuge, Kreuzheben, Rudern, Latzug, Klimmzug, Liegestütz, Ausfallschritt, Wadenheben, Beinpresse, Fliegende, Nackendrücken).
+- Use standard German ß (Gesäß, Fuß), not the Swiss ss — the app derives the Swiss spelling from this pack.
+- Avoid unnecessary anglicisms: no Glutes, Hamstrings, Core. Established loanwords such as Kettlebell, Burpee, Crunch and Plank are fine.
+- Do not repair or reinterpret questionable source mechanics; translate the title faithfully.
+- Use the metadata only to disambiguate the English title.
+
+TERMINOLOGY:
+${promptGlossary()}
+
+INPUT:
+${JSON.stringify(input)}`
+
+ console.log(`Translating names ${start + 1}-${start + batch.length} of ${pending.length} with ${provider} (${batch[0].id}…${batch.at(-1).id})`)
+
+ // Validate and retry. The rules are the ones CI enforces (scripts/de-name-rules.mjs), so
+ // checking them here turns a failure discovered hours later into a correction the model can act
+ // on while it still has the batch in hand. A batch that cannot be fixed is never written.
+ let prompt = basePrompt
+ let accepted
+ for (let attempt = 0; ; attempt++) {
+ const structured = await requestStructured(prompt, batch)
+ const received = new Map(structured.translations.map(row => [row.id, row.name.trim()]))
+ if (received.size !== batch.length) throw new Error(`${provider} returned duplicate or missing IDs`)
+
+ const problems = []
+ for (const exercise of batch) {
+ const name = received.get(exercise.id)
+ if (!name) throw new Error(`${exercise.id}: missing translated name`)
+ const broken = checkName(exercise, name)
+ if (broken.length) problems.push({ id: exercise.id, name, broken })
+ }
+
+ if (!problems.length) {
+ accepted = received
+ if (attempt) console.log(` clean after ${attempt} correction${attempt > 1 ? 's' : ''}`)
+ break
+ }
+
+ const summary = problems.map(p => ` ${p.id}: ${p.broken.map(v => v.rule).join(', ')}\n ${p.name}`).join('\n')
+ if (attempt >= maxRetries) {
+ throw new Error(`${problems.length} rule violation(s) still present after ${maxRetries + 1} attempts:\n${summary}`)
+ }
+ console.log(` ${problems.length} violation(s), correcting (${attempt + 1}/${maxRetries}):\n${summary}`)
+
+ // Only the broken names are quoted back. Re-sending the whole batch as "wrong" invites the
+ // model to rewrite names that were already fine, which loses good work and breaks other rules.
+ prompt = `${basePrompt}
+
+Your previous answer broke these rules. Return the FULL JSON for every ID again, changing only the names listed here:
+${problems.map(p => `- ${p.id} was: ${JSON.stringify(p.name)}\n${p.broken.map(v => ` ${v.fix}`).join('\n')}`).join('\n')}`
+ }
+
+ for (const exercise of batch) next[exercise.id] = accepted.get(exercise.id)
+ if (apply) {
+ writeFileSync(sourcePath, JSON.stringify(next, null, 2) + '\n')
+ console.log(`Checkpoint: ${Object.keys(next).length}/${staged.length} names`)
+ }
+}
+
+if (!apply) {
+ // A dry run exists to be read: a bare count leaves nothing to judge a new model or a changed
+ // prompt by, which is the whole reason for running without --apply.
+ for (const exercise of pending) console.log(`\n${exercise.id}\n EN ${exercise.n}\n DE ${next[exercise.id]}`)
+ console.log(`\nValidated ${pending.length} names. Re-run with --apply to update ${sourcePath}.`)
+ process.exit(0)
+}
+
+console.log(`Updated ${sourcePath}: ${Object.keys(next).length}/${staged.length} names`)