Merge main (v1.2.11) into coach: Pairing, Notizen, Aufwaerm-Saetze, GitLab-CI
Der Coach-Zweig stand seit v1.2.7. Konflikte: beide Seiten behalten (Server-Imports, Store-Felder, Home-Titel mit naechster Einheit, history.js), das Dockerfile behaelt seine zwei Targets und kopiert die neuen Server-Module mit, compose zeigt auf die GitLab-Registry. pt-BR: die 139 Coach-Strings in die Sie-Form gebracht, Fingerprint nachgezogen.
This commit is contained in:
commit
4a9e1e3456
148 files changed
+24456
-761
No files matched your search
@@ -6,6 +6,7 @@
|
||||
// node scripts/build-instructions.mjs [path-to-exercises.json]
|
||||
//
|
||||
// Without an argument the dataset is downloaded from the upstream repo.
|
||||
// Brazilian Portuguese is curated separately; see instruction-sources/README.md.
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const sourcePath = join(root, 'scripts', 'exercise-name-sources', 'pt-BR.json')
|
||||
const outputPath = join(root, 'frontend', 'src', 'exercise-names', 'pt-BR.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 known = new Set(EXDB.map(exercise => exercise.id))
|
||||
|
||||
for (const id of Object.keys(source)) {
|
||||
if (!known.has(id)) 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 (Object.keys(source).length !== EXDB.length) {
|
||||
throw new Error(`Incomplete pt-BR exercise names: ${Object.keys(source).length}/${EXDB.length}`)
|
||||
}
|
||||
|
||||
const ordered = {}
|
||||
for (const exercise of EXDB) ordered[exercise.id] = source[exercise.id].trim()
|
||||
mkdirSync(dirname(outputPath), { recursive: true })
|
||||
writeFileSync(outputPath, '// generated by scripts/build-pt-br-exercise-names.mjs — edit scripts/exercise-name-sources/pt-BR.json\nexport default ' + JSON.stringify(ordered) + '\n')
|
||||
console.log(`Generated ${EXDB.length}/${EXDB.length} pt-BR exercise names.`)
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const sourcePath = join(root, 'scripts', 'instruction-sources', 'pt-BR.json')
|
||||
const outputPath = join(root, 'frontend', 'src', 'instr', 'pt-BR.js')
|
||||
const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js')
|
||||
|
||||
const translations = JSON.parse(readFileSync(sourcePath, 'utf8'))
|
||||
const { EXDB } = await import(pathToFileURL(exercisesPath))
|
||||
const exercises = new Map(EXDB.map(exercise => [exercise.id, exercise]))
|
||||
|
||||
for (const [id, steps] of Object.entries(translations)) {
|
||||
const exercise = exercises.get(id)
|
||||
if (!exercise) throw new Error(`Unknown exercise ID: ${id}`)
|
||||
if (!Array.isArray(steps) || steps.length === 0) throw new Error(`${id}: translation must contain steps`)
|
||||
if (steps.length !== exercise.st.length) {
|
||||
throw new Error(`${id}: expected ${exercise.st.length} steps, received ${steps.length}`)
|
||||
}
|
||||
steps.forEach((step, index) => {
|
||||
if (typeof step !== 'string' || !step.trim()) throw new Error(`${id}: empty step ${index + 1}`)
|
||||
if (step === exercise.st[index]) throw new Error(`${id}: step ${index + 1} is still English`)
|
||||
})
|
||||
}
|
||||
|
||||
const ordered = Object.fromEntries(EXDB.filter(exercise => translations[exercise.id]).map(exercise => [exercise.id, translations[exercise.id]]))
|
||||
writeFileSync(outputPath, '// generated by scripts/build-pt-br-instructions.mjs — edit scripts/instruction-sources/pt-BR.json\nexport default ' + JSON.stringify(ordered) + '\n')
|
||||
|
||||
const stepCount = Object.values(ordered).reduce((total, steps) => total + steps.length, 0)
|
||||
console.log(`${outputPath}: ${Object.keys(ordered).length}/${EXDB.length} exercises, ${stepCount} steps`)
|
||||
@@ -0,0 +1,23 @@
|
||||
# Brazilian Portuguese exercise names
|
||||
|
||||
`pt-BR.json` is the editable source for the Brazilian Portuguese exercise-name
|
||||
pack. It maps every built-in EXDB exercise ID to a Portuguese title. The app
|
||||
combines that title with the unchanged English source at runtime:
|
||||
|
||||
```text
|
||||
Elevação assistida das pernas deitada (assisted lying leg raise)
|
||||
```
|
||||
|
||||
Custom exercise names are never translated. IDs, plan data, workout history,
|
||||
imports and exports continue to use the canonical catalogue entries.
|
||||
|
||||
Generate the runtime pack with:
|
||||
|
||||
```sh
|
||||
node scripts/build-pt-br-exercise-names.mjs
|
||||
```
|
||||
|
||||
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.
|
||||
File diff suppressed because it is too large.
Load diff
+12
-1
@@ -1,11 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Manually download the exercise images (JPG) and animations (GIF) into ./media.
|
||||
# You normally DON'T need this — `docker compose up` fetches them automatically.
|
||||
# Source: hasaneyldrm/exercises-dataset (CC).
|
||||
# Source: hasaneyldrm/exercises-dataset — MIT for the metadata and instruction text, but the
|
||||
# images and GIFs are © Gym visual (https://gymvisual.com/), used under that dataset's terms.
|
||||
# openGym does not redistribute or relicense them. See NOTICE.md.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
cat <<'EOF'
|
||||
↓ Downloading exercise media (~140 MB) from github.com/hasaneyldrm/exercises-dataset
|
||||
Metadata and instruction text: MIT.
|
||||
Images and animations: © Gym visual — https://gymvisual.com/
|
||||
Used under that dataset's terms, not openGym's AGPL; openGym does not redistribute them.
|
||||
Terms: https://gymvisual.com/content/3-terms-and-conditions-of-use
|
||||
Reusing this media yourself, commercially or not, needs your own licence from Gym visual.
|
||||
Details in NOTICE.md.
|
||||
EOF
|
||||
git clone --depth 1 https://github.com/hasaneyldrm/exercises-dataset "$tmp"
|
||||
mkdir -p media/img media/gif
|
||||
cp "$tmp"/images/*.jpg media/img/
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Brazilian Portuguese exercise glossary
|
||||
|
||||
Preferred terms keep the instruction pack consistent with Brazilian gym usage.
|
||||
|
||||
| English | Use in pt-BR | Avoid |
|
||||
|---|---|---|
|
||||
| abdomen / abs / engage your core | abdômen / contraia o abdômen | abdómen |
|
||||
| calf / calves | panturrilha / panturrilhas | gémeos |
|
||||
| hip | quadril | anca |
|
||||
| shoulder blade | escápula | omoplata |
|
||||
| rotator cuff | manguito rotador | coifa dos rotadores |
|
||||
| dumbbell | halter | peso de mão |
|
||||
| barbell | barra | barra de peso |
|
||||
| Smith machine | máquina Smith | barra guiada, unless describing the bar |
|
||||
| overhand grip | pegada pronada | pegada por cima |
|
||||
| underhand grip | pegada supinada | pegada invertida / inversa |
|
||||
| reverse grip | determine from the stated palm direction | pegada invertida / inversa |
|
||||
| pull-up bar | barra fixa | barra de elevações |
|
||||
| push-up | flexão de braços | flexão |
|
||||
| set | série | conjunto |
|
||||
| repetition / rep | repetição | repetiçãozinha |
|
||||
| bodyweight | peso corporal | peso do corpo, when used as a category |
|
||||
| starting position | posição inicial | posição de partida |
|
||||
| resistance band / band | faixa elástica | banda |
|
||||
| stability ball | bola de estabilidade | bola suíça |
|
||||
| floor / ground | chão | piso |
|
||||
|
||||
Write instructions using Brazilian `você` conventions and neutral imperative
|
||||
forms: `mantenha`, `contraia`, `eleve`, `retorne`. Avoid Portuguese (Portugal)
|
||||
terms such as `ecrã`, `anca`, `abdómen`, `gémeos`, `ginásio` and second-person
|
||||
forms such as `mantém`, `contrai`, `eleva`, `retorna`.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Curated exercise-instruction translations
|
||||
|
||||
`pt-BR.json` is the editable source for Brazilian Portuguese exercise
|
||||
instructions. It is intentionally separate from the upstream-generated packs:
|
||||
the upstream exercise dataset does not currently ship Portuguese instructions.
|
||||
|
||||
## Provenance and review status
|
||||
|
||||
The translations are produced from the English instructions in
|
||||
`frontend/src/lib/exercises-data.js` with language-model assistance from OpenAI
|
||||
Codex and, for larger structured batches, Anthropic Claude Code. They are
|
||||
original translations, not copied from another Portuguese exercise dataset.
|
||||
Each batch is structurally checked against the English source and audited for
|
||||
Brazilian terminology. It must not be described as native-speaker reviewed
|
||||
until a named human reviewer has actually completed that review.
|
||||
|
||||
The translation policy is meaning-faithful rather than word-for-word: preserve
|
||||
the number and order of steps, retain the intended movement and safety cues,
|
||||
and clarify the referenced limb only when the English would otherwise be
|
||||
ambiguous in Portuguese. Do not silently repair questionable exercise mechanics
|
||||
from the source dataset; record those separately for upstream correction.
|
||||
Known source inconsistencies are recorded in `SOURCE_DIVERGENCES.md`.
|
||||
|
||||
Add translations in small, reviewable batches. Every translated exercise must
|
||||
preserve the English instruction-step count. Then regenerate the runtime pack:
|
||||
|
||||
```sh
|
||||
node scripts/build-pt-br-instructions.mjs
|
||||
```
|
||||
|
||||
The generator rejects unknown IDs, empty steps, mismatched step counts and
|
||||
steps left unchanged in English. The frontend test also verifies that the
|
||||
generated `frontend/src/instr/pt-BR.js` exactly matches this source.
|
||||
|
||||
Do not add `pt-BR` to `INSTR_LANGS` until all 1,324 exercise IDs are translated
|
||||
and the full automated corpus gates pass. Until then, the released app must
|
||||
continue to show the honest English-instructions notice instead of silently
|
||||
mixing Portuguese and English.
|
||||
|
||||
Use the terminology in `GLOSSARY.md` for every batch.
|
||||
|
||||
For a structured batch, use `scripts/translate-pt-br-stage.mjs` with a dataset
|
||||
body part and limit. It calls Claude in read-only structured-output mode and
|
||||
checkpoints only after every returned ID and step count in that batch validates,
|
||||
so a long stage can resume safely. The normal pack builder and frontend tests
|
||||
remain mandatory after generation.
|
||||
|
||||
Use `--provider=codex` to run the same schema-constrained workflow through an
|
||||
authenticated Codex CLI when Claude is unavailable. Both providers run without
|
||||
write tools; only this validator updates the curated JSON after a valid batch.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Known English-source divergences
|
||||
|
||||
The pt-BR pack preserves the source dataset's exercise identity and step order.
|
||||
When the English mechanics are internally inconsistent, the translation should
|
||||
not silently redefine the exercise. Record those cases here for a separate
|
||||
upstream correction.
|
||||
|
||||
| Exercise | English-source issue | pt-BR handling |
|
||||
|---|---|---|
|
||||
| `0023` barbell alternate biceps curl | Says to hold a barbell in each hand and later refers to multiple barbells. | Translated faithfully; equipment issue remains upstream. |
|
||||
| `0984` band lying hip internal rotation | The title says internal rotation, while step 3 directs the knees outward. | Direction translated faithfully. |
|
||||
| `3667` side lying hip adduction | Step 3 says to engage the adductors while lifting the top leg, which describes abduction. | Muscle cue translated faithfully. |
|
||||
| `2139` hands bike | Step 2 says to place the feet on pedals of an upper-body ergometer. | Setup translated faithfully. |
|
||||
| `0987` band one arm single leg split squat | Step 2 says to extend one leg forward but rest that foot on a bench behind the user. | Portuguese clarifies that the other foot rests behind, preserving usable split-squat mechanics; this intentional divergence is documented here. |
|
||||
| `3294` archer push up | Step 3 says to bend both elbows although the preceding step extends one arm. | Portuguese identifies the supporting arm to avoid an ambiguous unsafe cue; this intentional clarification is documented here. |
|
||||
@@ -0,0 +1,37 @@
|
||||
# Brazilian Portuguese instruction translation plan
|
||||
|
||||
Translate in schema-validated, checkpointed batches. After a stage, regenerate
|
||||
the runtime pack and run the frontend suite; after the complete corpus, perform
|
||||
the independent language/content review. Progress is measured from
|
||||
`pt-BR.json`, not from generated files.
|
||||
|
||||
| Stage | Dataset body part | Total exercises | Order |
|
||||
|---:|---|---:|---|
|
||||
| 0 | Foundation sample across categories | 20 translated | Complete |
|
||||
| 1 | Waist / abs / core | 169 | Complete |
|
||||
| 2 | Chest / pectorals | 163 | Complete |
|
||||
| 3 | Back / lats / upper back | 203 | Complete |
|
||||
| 4 | Shoulders / delts | 143 | Complete |
|
||||
| 5 | Upper arms / biceps / triceps | 292 | Complete |
|
||||
| 6 | Lower arms / forearms | 37 | Complete |
|
||||
| 7 | Upper legs / glutes / quads / hamstrings | 227 | Complete |
|
||||
| 8 | Lower legs / calves | 59 | Complete |
|
||||
| 9 | Cardio and neck | 31 | Complete |
|
||||
| 10 | Full-corpus terminology and independent QA | 1,324 | Ready for review |
|
||||
|
||||
The body-part stages cover all 1,324 dataset IDs exactly once. The foundation
|
||||
sample already contributes to several stages, so stage progress must exclude
|
||||
IDs already present in the source file. Do not add `pt-BR` to `INSTR_LANGS`
|
||||
until Stage 10 confirms 1,324/1,324 coverage.
|
||||
|
||||
## Checkpoints
|
||||
|
||||
- Stage 1 completed in 2026-08-19: 169/169 waist IDs. Combined corpus progress
|
||||
is 179/1,324 exercises and 996 instruction steps because the foundation
|
||||
sample also contains 10 exercises from later stages.
|
||||
- Stages 2–9 completed in 2026-08-19: source coverage reached 1,324/1,324.
|
||||
Automated Stage 10 gates passed for 7,710/7,710 steps: exact ID and step
|
||||
coverage, non-empty content, curated-source parity, glossary/English/PT-PT
|
||||
leakage checks, complete frontend tests and production build. The independent
|
||||
full-corpus review prompt is prepared separately for Claude Code; do not claim
|
||||
native-speaker review unless a named human actually performs one.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const sourcePath = join(root, 'scripts', 'exercise-name-sources', 'pt-BR.json')
|
||||
const glossaryPath = join(root, 'scripts', 'instruction-sources', 'GLOSSARY.md')
|
||||
const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js')
|
||||
const claude = process.env.CLAUDE_BIN || 'claude'
|
||||
const option = name => process.argv.find(arg => arg.startsWith(`--${name}=`))?.split('=').slice(1).join('=')
|
||||
const limit = Number(option('limit') || 1324)
|
||||
const batchSize = Number(option('batch-size') || 80)
|
||||
const apply = process.argv.includes('--apply')
|
||||
|
||||
if (!Number.isInteger(limit) || limit < 1 || !Number.isInteger(batchSize) || batchSize < 1) {
|
||||
throw new Error('limit and batch-size must be positive integers')
|
||||
}
|
||||
|
||||
const existing = JSON.parse(readFileSync(sourcePath, 'utf8'))
|
||||
const glossary = readFileSync(glossaryPath, 'utf8')
|
||||
const { EXDB } = await import(pathToFileURL(exercisesPath))
|
||||
const pending = EXDB.filter(exercise => !existing[exercise.id]).slice(0, limit)
|
||||
const next = { ...existing }
|
||||
|
||||
for (let start = 0; start < pending.length; start += batchSize) {
|
||||
const batch = pending.slice(start, start + batchSize)
|
||||
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
|
||||
}
|
||||
const input = batch.map(({ id, n, bp, eq, tg }) => ({ id, english: n, bodyPart: bp, equipment: eq, target: tg }))
|
||||
const prompt = `Translate every exercise title below into concise, natural Brazilian Portuguese 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 Portuguese title in "name". Do not append or repeat the English title.
|
||||
- Preserve exercise identity, equipment, stance, grip, direction, side, assisted/weighted status and version qualifiers.
|
||||
- Prefer established Brazilian gym terminology (for example: supino, agachamento, remada, puxada, rosca, elevação, extensão, flexão de braços, barra fixa, afundo, levantamento terra).
|
||||
- Keep accepted equipment or exercise names such as kettlebell, Smith, hack squat, leg press and Romanian deadlift when that is the clearest Brazilian usage.
|
||||
- Use sentence case, not Title Case. Do not use Portuguese (Portugal) terms.
|
||||
- Do not repair or reinterpret questionable source mechanics; translate the title faithfully.
|
||||
- Use the metadata only to disambiguate the English title.
|
||||
|
||||
GLOSSARY:
|
||||
${glossary}
|
||||
|
||||
INPUT:
|
||||
${JSON.stringify(input)}`
|
||||
|
||||
console.log(`Translating names ${start + 1}-${start + batch.length} of ${pending.length} (${batch[0].id}…${batch.at(-1).id})`)
|
||||
const result = spawnSync(claude, [
|
||||
'-p', '--model', 'sonnet', '--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')
|
||||
const rows = envelope.structured_output.translations
|
||||
const received = new Map(rows.map(row => [row.id, row.name.trim()]))
|
||||
if (received.size !== batch.length) throw new Error('Claude returned duplicate or missing IDs')
|
||||
for (const exercise of batch) {
|
||||
const name = received.get(exercise.id)
|
||||
if (!name) throw new Error(`${exercise.id}: missing translated name`)
|
||||
next[exercise.id] = name
|
||||
}
|
||||
if (apply) {
|
||||
writeFileSync(sourcePath, JSON.stringify(next, null, 2) + '\n')
|
||||
console.log(`Checkpoint: ${Object.keys(next).length}/${EXDB.length} names`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!apply) console.log(`Validated ${pending.length} names. Re-run with --apply to update the source.`)
|
||||
else console.log(`Updated ${sourcePath}: ${Object.keys(next).length}/${EXDB.length} names`)
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const sourcePath = join(root, 'scripts', 'instruction-sources', 'pt-BR.json')
|
||||
const glossaryPath = join(root, 'scripts', 'instruction-sources', 'GLOSSARY.md')
|
||||
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 stageOrder = ['chest', 'back', 'shoulders', 'upper arms', 'lower arms', 'upper legs', 'lower legs', 'cardio', 'neck']
|
||||
|
||||
const option = name => process.argv.find(arg => arg.startsWith(`--${name}=`))?.split('=').slice(1).join('=')
|
||||
const bodyPart = option('body-part')
|
||||
const provider = option('provider') || 'claude'
|
||||
const limit = Number(option('limit') || 10)
|
||||
const batchSize = Number(option('batch-size') || 10)
|
||||
const apply = process.argv.includes('--apply')
|
||||
|
||||
if (!bodyPart) throw new Error('Usage: translate-pt-br-stage.mjs --body-part=waist|all [--limit=10] [--batch-size=10] [--apply]')
|
||||
if (!['claude', 'codex'].includes(provider)) throw new Error('provider must be claude or codex')
|
||||
if (!Number.isInteger(limit) || limit < 1 || !Number.isInteger(batchSize) || batchSize < 1) {
|
||||
throw new Error('limit and batch-size must be positive integers')
|
||||
}
|
||||
|
||||
const translations = JSON.parse(readFileSync(sourcePath, 'utf8'))
|
||||
const glossary = readFileSync(glossaryPath, 'utf8')
|
||||
const { EXDB } = await import(pathToFileURL(exercisesPath))
|
||||
const requestedParts = bodyPart === 'all' ? stageOrder : [bodyPart]
|
||||
const pending = requestedParts
|
||||
.flatMap(part => EXDB.filter(exercise => exercise.bp === part && !translations[exercise.id]))
|
||||
.slice(0, limit)
|
||||
|
||||
if (!pending.length) {
|
||||
console.log(`No untranslated ${bodyPart} exercises remain.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const next = { ...translations }
|
||||
for (let start = 0; start < pending.length; start += batchSize) {
|
||||
const batch = pending.slice(start, start + batchSize)
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
translations: {
|
||||
type: 'array', minItems: batch.length, maxItems: batch.length,
|
||||
items: {
|
||||
oneOf: batch.map(exercise => ({
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { const: exercise.id },
|
||||
steps: { type: 'array', minItems: exercise.st.length, maxItems: exercise.st.length, items: { type: 'string', minLength: 1 } }
|
||||
},
|
||||
required: ['id', 'steps'], additionalProperties: false
|
||||
}))
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['translations'], additionalProperties: false
|
||||
}
|
||||
const input = batch.map(({ id, n, st }) => ({ id, name: n, steps: st }))
|
||||
const prompt = `Translate every instruction step below from English into natural Brazilian Portuguese for a fitness app.
|
||||
|
||||
Rules:
|
||||
- Return only the structured JSON required by the schema, with every ID exactly once and in input order.
|
||||
- Preserve the exact number, order, movement meaning and safety cues of the English steps.
|
||||
- Use Brazilian você conventions and neutral imperatives: mantenha, contraia, eleve, retorne.
|
||||
- Follow the glossary. In particular, translate "engage your core/abs" as "contraia o abdômen", never "ative o core".
|
||||
- Do not use Portuguese (Portugal) wording. Do not add explanations or repair source mechanics.
|
||||
- Translate only instruction steps; IDs remain unchanged.
|
||||
|
||||
GLOSSARY:
|
||||
${glossary}
|
||||
|
||||
INPUT:
|
||||
${JSON.stringify(input)}`
|
||||
|
||||
console.log(`Translating ${start + 1}-${start + batch.length} of ${pending.length} with ${provider} (${batch[0].id}…${batch.at(-1).id})`)
|
||||
let structured
|
||||
if (provider === 'claude') {
|
||||
const result = spawnSync(claude, [
|
||||
'-p', '--model', 'sonnet', '--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-pt-br-'))
|
||||
const schemaPath = join(temp, 'schema.json')
|
||||
const outputPath = join(temp, 'output.json')
|
||||
const codexSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
translations: {
|
||||
type: 'array', minItems: batch.length, maxItems: batch.length,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
steps: { type: 'array', items: { type: 'string' } }
|
||||
},
|
||||
required: ['id', 'steps'], additionalProperties: false
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['translations'], additionalProperties: false
|
||||
}
|
||||
try {
|
||||
writeFileSync(schemaPath, JSON.stringify(codexSchema))
|
||||
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 })
|
||||
}
|
||||
}
|
||||
|
||||
const rows = structured.translations
|
||||
const received = new Map(rows.map(row => [row.id, row.steps]))
|
||||
if (received.size !== batch.length) throw new Error(`${provider} returned duplicate or missing IDs`)
|
||||
for (const exercise of batch) {
|
||||
const steps = received.get(exercise.id)
|
||||
if (!steps || steps.length !== exercise.st.length) throw new Error(`${exercise.id}: invalid step count`)
|
||||
next[exercise.id] = steps
|
||||
}
|
||||
if (apply) {
|
||||
writeFileSync(sourcePath, JSON.stringify(next, null, 2) + '\n')
|
||||
console.log(`Checkpoint: ${Object.keys(next).length}/${EXDB.length} exercises`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!apply) {
|
||||
console.log(`Validated ${pending.length} translations. Re-run with --apply to update ${sourcePath}.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
console.log(`Updated ${sourcePath}: ${Object.keys(next).length}/${EXDB.length} exercises`)
|
||||
Reference in new issue
Block a user