#!/usr/bin/env node /* * Translate the built-in exercise catalogue into Spanish, one batch at a time. * * The pt-BR pack was produced on the author's machine with the `claude` CLI (see * translate-pt-br-exercise-names.mjs). This one talks to any OpenAI-compatible * /chat/completions endpoint instead, because that is what a self-hosted instance actually has: * the same router the Coach runs on. * * COACH_BASE_URL=https://ai.example.com OPENAI_COMPAT_API_KEY=… \ * node scripts/translate-es-exercise-names.mjs * * Resumable by design: ids already in the source file are skipped, so a run that stops half way * (a rate limit, a Ctrl-C, a model that goes quiet) continues where it left off, and re-running * after a review only re-translates what was deleted. That matters because the file is 1,324 * entries — a translation pass that had to start over would never be repeated. * * What it does NOT do is claim the result is reviewed: the header of the generated pack says the * names came from a model, exactly as the pt-BR one does, until a named human reviews them. */ import { readFileSync, writeFileSync, mkdirSync, existsSync } 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', 'es.json') const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js') const option = (name, fallback) => { const raw = process.argv.find(a => a.startsWith(`--${name}=`))?.split('=').slice(1).join('=') return raw === undefined ? fallback : Number(raw) } const limit = option('limit', Infinity) const batchSize = option('batch-size', 60) const baseUrl = (process.env.COACH_BASE_URL || '').replace(/\/+$/, '') const key = process.env.COACH_API_KEY || process.env.OPENAI_COMPAT_API_KEY || '' const model = process.env.COACH_MODEL || '' if (!baseUrl || !model) { console.error('Set COACH_BASE_URL (no /v1 suffix) and COACH_MODEL. COACH_API_KEY if the endpoint needs one.') process.exit(1) } // The terminology the app will show, fixed here rather than left to each batch's taste: a // catalogue where "dumbbell" is a mancuerna in one row and a pesa in the next reads as broken, // and these are the same words the test asserts. const RULES = `- Return only the Spanish title in "name". Never append or repeat the English title. - Preserve exercise identity, equipment, stance, grip, direction, side, assisted/weighted status and version qualifiers. - Use established Spanish gym terminology. These core lifts have one right answer, use it every time: bench press → press de banca · squat → sentadilla · deadlift → peso muerto · lunge → zancada pull-up → dominada · chin-up → dominada supina · push-up → flexión · dip → fondo sit-up → abdominal · crunch → crunch · plank → plancha · row → remo · pulldown → jalón al pecho shoulder press → press de hombros · overhead press → press militar · lateral raise → elevación lateral curl → curl de bíceps · triceps extension → extensión de tríceps · pushdown → extensión en polea calf raise → elevación de gemelos · leg press → prensa de piernas · leg extension → extensión de piernas leg curl → curl femoral · hip thrust → hip thrust · glute bridge → puente de glúteos fly → aperturas · shrug → encogimiento de hombros · upright row → remo al mentón · stretch → estiramiento - Translate qualifiers faithfully and consistently: assisted → asistido · weighted → con peso · male → masculino · female → femenino barbell → barra · dumbbell → mancuerna · kettlebell → kettlebell · Smith → Smith cable → polea · machine → máquina · band → banda elástica stability ball → fitball · medicine ball → balón medicinal reverse → inverso · close grip → agarre cerrado · wide grip → agarre amplio underhand → agarre supino · overhand → agarre prono · neutral grip → agarre neutro one arm / single arm → a una mano · alternate → alterno · both arms → a dos manos seated → sentado · standing → de pie · lying → tumbado · kneeling → de rodillas bent over → inclinado · incline → en banco inclinado · decline → en banco declinado - NEVER start the title with the equipment. Spanish names the movement first and puts the equipment after it, joined with "con" ("en" for a bench, ball or machine): band squat → Sentadilla con banda · barbell row → Remo con barra · dumbbell press on exercise ball → Press en fitball con mancuerna · machine chest press → Press de pecho en máquina. "Banda sentadilla", "Mancuerna press", "Barra remo" are wrong and must never appear. - A named variation still translates its head noun: goblet squat → sentadilla goblet, hack squat → sentadilla hack, Jefferson squat → sentadilla Jefferson, Rocky pull-up pulldown → jalón al pecho estilo Rocky. Do not leave the English head noun in place. - Keep loanwords that are the established term in Spanish (kettlebell, Smith, leg press, face pull, burpee, hip thrust, crunch). - Use sentence case: only the first word and proper nouns are capitalised. - Do not repair or reinterpret questionable source mechanics; translate the title faithfully. - Use the metadata only to disambiguate the English title.` const system = 'You translate exercise names for a Spanish-language gym app. You answer with JSON and nothing else.' const schema = { type: 'object', properties: { translations: { type: 'array', items: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: ['id', 'name'], additionalProperties: false } } }, required: ['translations'], additionalProperties: false } async function ask(batch) { const input = batch.map(({ id, n, bp, eq, tg }) => ({ id, english: n, bodyPart: bp, equipment: eq, target: tg })) const res = await fetch(`${baseUrl}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) }, body: JSON.stringify({ model, messages: [ { role: 'system', content: system }, { role: 'user', content: `Translate every exercise title below into concise, natural Spanish for a gym app. Use neutral Spanish that reads correctly in Spain and in Latin America.\n\nRules:\n- Return only the structured JSON required by the schema, with every ID exactly once and in input order.\n${RULES}\n\nINPUT:\n${JSON.stringify(input)}` } ], temperature: 0, response_format: { type: 'json_schema', json_schema: { name: 'translations', schema } }, max_tokens: 8000 }) }) if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`) const text = await res.text() // The endpoint this project runs against appends the streaming terminator to a non-streamed // answer, so the body is a JSON object followed by "data: [DONE]". Take the first value. const data = JSON.parse(text.slice(0, text.lastIndexOf('}') + 1)) const content = data.choices?.[0]?.message?.content if (!content) throw new Error('the answer had no content') const parsed = JSON.parse(content) if (!Array.isArray(parsed.translations)) throw new Error('the answer had no translations array') return parsed.translations } const { EXDB } = await import(pathToFileURL(exercisesPath).href) mkdirSync(dirname(sourcePath), { recursive: true }) const done = existsSync(sourcePath) ? JSON.parse(readFileSync(sourcePath, 'utf8')) : {} const pending = EXDB.filter(ex => !String(done[ex.id] || '').trim()).slice(0, limit) console.log(`${Object.keys(done).length}/${EXDB.length} already translated · ${pending.length} to go · ${model} at ${baseUrl}`) let added = 0 for (let start = 0; start < pending.length; start += batchSize) { const batch = pending.slice(start, start + batchSize) const label = `[${start + 1}-${start + batch.length}/${pending.length}]` for (let attempt = 1; attempt <= 3; attempt++) { try { const translations = await ask(batch) const got = new Map(translations.map(t => [String(t.id), String(t.name || '').trim()])) const missed = batch.filter(ex => !got.get(ex.id)) for (const ex of batch) if (got.get(ex.id)) done[ex.id] = got.get(ex.id) added += batch.length - missed.length writeFileSync(sourcePath, JSON.stringify(done, null, 2) + '\n') console.log(`${label} ok — ${batch.length - missed.length}/${batch.length}${missed.length ? ` (sin traducir: ${missed.map(m => m.id).join(', ')})` : ''}`) break } catch (e) { console.log(`${label} intento ${attempt} falló: ${e.message.slice(0, 140)}`) if (attempt === 3) console.log(`${label} se salta; vuelve a ejecutarlo para reintentar esos`) else await new Promise(r => setTimeout(r, 2000 * attempt)) } } } console.log(`\n${Object.keys(done).length}/${EXDB.length} en ${sourcePath}`) if (Object.keys(done).length < EXDB.length) { console.log('Incompleto a propósito: vuelve a ejecutarlo y continúa donde se quedó.') process.exitCode = 1 }