-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtranslate.ts
More file actions
707 lines (587 loc) · 22.1 KB
/
translate.ts
File metadata and controls
707 lines (587 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import crypto from 'node:crypto'
import fs from 'node:fs/promises'
import path from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { isDeepStrictEqual } from 'node:util'
import { removeLeadingSlash } from '@rspress/shared'
import { Command } from 'commander'
import { render } from 'ejs'
import matter from 'gray-matter'
import { AzureOpenAI, RateLimitError } from 'openai'
import { pRateLimit } from 'p-ratelimit'
import { logger } from 'rspress/core'
import { glob } from 'tinyglobby'
import { cyan, red } from 'yoctocolors'
import {
mdProcessor,
mdxProcessor,
normalizeImgSrc,
type NormalizeImgSrcOptions,
} from '../plugins/index.js'
import {
Language,
SUPPORTED_LANGUAGES,
TITLE_TRANSLATION_MAP,
} from '../shared/index.js'
import type { GlobalCliOptions, TranslateOptions } from '../types.js'
import { pathExists } from '../utils/index.js'
import {
escapeMarkdownHeadingIds,
getMatchedDocFilePaths,
parseBoolean,
parseTerms,
} from './helpers.js'
import { loadConfig } from './load-config.js'
export interface I18nFrontmatter {
i18n?: {
additionalPrompts?: string
disableAutoTranslation?: boolean
}
sourceSHA?: string
title?: string
description?: string
}
export const TERMS_SUPPORTED_LANGUAGES: Language[] = ['en', 'zh', 'ru']
// Directories that should be copied instead of translated
const COPY_ONLY_DIRECTORIES = [
'apis/advanced_apis/**',
'apis/kubernetes_apis/**',
]
const DEFAULT_SYSTEM_PROMPT = `
You are a professional technical documentation engineer, skilled in writing high-quality technical documentation in <%= targetLang %>. Please accurately translate the following text from <%= sourceLang %> to <%= targetLang %>, maintaining the style consistent with technical documentation in <%= sourceLang %>.
## Baseline Requirements
- Sentences should be fluent and conform to the expression habits of the <%= targetLang %> language.
- Input format is MDX; output format must also retain the original MDX format. Do not translate the names of jsx components such as <Overview />, and do not wrap output in unnecessary code blocks.
- **CRITICAL**: Do not translate or modify ANY link content in the document. This includes:
- URLs in markdown links: [text](URL) - keep URL exactly as is
- Reference-style links: [text][ref] and [ref]: URL - keep both ref and URL unchanged
- Inline URLs: https://example.com - keep completely unchanged
- Image links:  - keep src unchanged, but alt text can be translated
- Anchor links: [text](#anchor) - keep #anchor unchanged
- Any href attributes in HTML tags - keep unchanged
- Do not translate professional technical terms and proper nouns, including but not limited to: Kubernetes, Docker, CLI, API, REST, GraphQL, JSON, YAML, Git, GitHub, GitLab, AWS, Azure, GCP, Linux, Windows, macOS, Node.js, React, Vue, Angular, TypeScript, JavaScript, Python, Java, Go, Rust, etc. Keep these terms in their original form.
- The title field and description field in frontmatter should be translated, other frontmatter fields should retain and do not translate.
- Content within MDX components needs to be translated, whereas MDX component names and parameter keys do not.
- Do not modify or translate any placeholders in the format of __ANCHOR_N__ (where N is a number). These placeholders must be kept exactly as they appear in the source text.
- Keep original escape characters like backslash, angle brackets, etc. unchanged during translation.
- Do not add any escape characters to special characters like [], (), {}, etc. unless they were explicitly present in the source text. For example:
- If source has "Architecture [Optional]", keep it as "Architecture [Optional]" (not "Architecture \\[Optional]")
- If source has "Function (param)", keep it as "Function (param)" (not "Function \\(param)")
- Only add escape characters if they were present in the original text
- Preserve and do not translate the following comments, nor modify their content:
- {/* release-notes-for-bugs */}
- <!-- release-notes-for-bugs -->
- Remove and do not retain the following comments:
- {/* reference-start */}
- {/* reference-end */}
- <!-- reference-start -->
- <!-- reference-end -->
- Ensure the original Markdown format remains intact during translation, such as frontmatter, code blocks, lists, tables, etc.
- Do not translate the content of the code block.
<% if (titleTranslationPrompt) { %>
<%- titleTranslationPrompt %>
<% } %>
<% if (terms) { %>
<%- terms %>
<% } %>
<% if (isChunk) { %>
## Chunk Translation Notice
This is part of a larger document that has been split into smaller chunks for translation. Please translate this chunk as if it's part of a continuous document, maintaining consistency with the overall document style and context.
<% } %>
<% if (userPrompt || additionalPrompts) { %>
## Additional Requirements
These are additional requirements for the translation. They should be met along with the baseline requirements, and in case of any conflict, the baseline requirements should take precedence.
The text for translation is provided below, within triple quotes:
"""
<% if (userPrompt) { %>
<%- userPrompt %>
<% } %>
<% if (additionalPrompts) { %>
<%- additionalPrompts %>
<% } %>
"""
<% } %>
`.trim()
let openai: AzureOpenAI | undefined
const openaiModel = process.env.AZURE_OPENAI_MODEL || 'gpt-4.1-mini'
export interface InternalTranslateOptions extends TranslateOptions {
source: Language
sourceContent: string
target: Language
additionalPrompts?: string
isChunk?: boolean
}
const resolveTerms = async (
sourceLang: Language,
targetLang: Language,
sourceContent: string,
) => {
const parsedTerms = await parseTerms()
// Filter terms that exist in source content and have translations for both source and target languages
const relevantTerms = parsedTerms.filter((term) => {
// Check if term has both source and target language translations
const sourceTranslation = term[sourceLang]
const targetTranslation = term[targetLang]
if (!sourceTranslation || !targetTranslation) {
return false
}
// Check if the source translation appears in the source content (case-insensitive)
const sourceTermRegex = new RegExp(
`\\b${sourceTranslation.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`,
'i',
)
return sourceTermRegex.test(sourceContent)
})
if (relevantTerms.length === 0) {
logger.debug('No relevant terms found for translation')
return ''
}
const sourceLangName = Language[sourceLang]
const targetLangName = Language[targetLang]
const terms =
`- The following is a common related terminology vocabulary table (${sourceLangName} <=> ${targetLangName}), you should use it to translate the matched text.\n` +
relevantTerms
.map((term) => ` * ${term[sourceLang]} <=> ${term[targetLang]}`)
.join('\n')
logger.debug('Resolved terms:', terms)
return terms
}
const ANCHOR_REGEX = /\\\\?\{#[\w-]+\}/g
function replaceAnchorsWithPlaceholders(content: string): {
content: string
anchors: string[]
} {
// Handle escaped underscores in anchor IDs (e.g., \{#independent\_doc\_site} -> \{#independent_doc_site})
// This is necessary because MDX processor automatically escapes underscores in heading IDs
// to ensure proper Markdown parsing, but we need the original unescaped form for anchor matching
const unescapedContent = content.replace(/\\_/g, '_')
const anchors: string[] = []
const contentWithPlaceholders = unescapedContent.replace(
ANCHOR_REGEX,
(match) => {
anchors.push(match)
return `__ANCHOR_${anchors.length - 1}__`
},
)
return { content: contentWithPlaceholders, anchors }
}
function restoreAnchors(content: string, anchors: string[]): string {
return content.replace(/__ANCHOR_(\d+)__/g, (_, index: string) => {
const numIndex: number = parseInt(index, 10)
if (isNaN(numIndex) || numIndex < 0 || numIndex >= anchors.length) {
throw new Error(`Invalid anchor index: ${index}`)
}
const anchor: string = anchors[numIndex]
return anchor
})
}
function extractFirstLevelHeading(content: string): string | null {
const lines = content.split('\n')
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('# ')) {
return trimmed.substring(2).trim()
}
}
return null
}
function getTitleTranslation(
title: string,
sourceLang: Language,
targetLang: Language,
): string | null {
for (const translations of TITLE_TRANSLATION_MAP) {
if (translations[sourceLang] === title && translations[targetLang]) {
return translations[targetLang]
}
}
return null
}
function splitContentIntoChunks(
content: string,
maxChunkSize: number,
): string[] {
const lines = content.split('\n')
const chunks: string[] = []
let currentChunk: string[] = []
let currentSize = 0
for (const line of lines) {
const lineSize = Buffer.byteLength(line + '\n', 'utf8')
// If adding this line would exceed the chunk size, and we have content in current chunk
if (currentSize + lineSize > maxChunkSize && currentChunk.length > 0) {
chunks.push(currentChunk.join('\n'))
currentChunk = [line]
currentSize = lineSize
} else {
currentChunk.push(line)
currentSize += lineSize
}
}
// Add the last chunk if it has content
if (currentChunk.length > 0) {
chunks.push(currentChunk.join('\n'))
}
return chunks
}
export const translateWithChunks = async (
options: InternalTranslateOptions,
): Promise<string> => {
const { sourceContent } = options
const maxChunkSize = 60 * 1024
const contentSize = Buffer.byteLength(sourceContent, 'utf8')
if (contentSize <= maxChunkSize) {
return translate(options)
}
logger.info(
`Content size (${Math.round(contentSize / 1024)}KB) exceeds limit, splitting into chunks...`,
)
const chunks = splitContentIntoChunks(sourceContent, maxChunkSize)
logger.info(`Split content into ${chunks.length} chunks`)
const translatedChunks: string[] = []
for (let i = 0; i < chunks.length; i++) {
logger.info(`Translating chunk ${i + 1}/${chunks.length}...`)
const translatedChunk = await translate({
...options,
sourceContent: chunks[i],
isChunk: true,
})
translatedChunks.push(translatedChunk)
}
const result = translatedChunks.join('\n')
logger.info(`Successfully translated ${chunks.length} chunks`)
return result
}
export const translate = async ({
source,
sourceContent,
target,
systemPrompt,
userPrompt = '',
additionalPrompts = '',
isChunk = false,
}: InternalTranslateOptions) => {
if (!openai) {
openai = new AzureOpenAI({
endpoint:
process.env.AZURE_OPENAI_ENDPOINT ||
'https://azure-ai-api-gateway.alauda.cn',
apiKey: process.env.AZURE_OPENAI_API_KEY,
apiVersion: process.env.OPENAI_API_VERSION || '2025-03-01-preview',
})
}
const sourceLang = Language[source]
const targetLang = Language[target]
let terms = ''
if (
[source, target].every((lang) => TERMS_SUPPORTED_LANGUAGES.includes(lang))
) {
terms = await resolveTerms(source, target, sourceContent)
}
const firstLevelHeading = extractFirstLevelHeading(sourceContent)
let titleTranslationPrompt = ''
if (firstLevelHeading) {
const titleTranslation = getTitleTranslation(
firstLevelHeading,
source,
target,
)
if (titleTranslation) {
titleTranslationPrompt = `- The heading "${firstLevelHeading}" should be translated as "${titleTranslation}".`
}
}
const { content: contentWithPlaceholders, anchors } =
replaceAnchorsWithPlaceholders(sourceContent)
const finalSystemPrompt = await render(
systemPrompt?.trim() || DEFAULT_SYSTEM_PROMPT,
{
sourceLang,
targetLang,
userPrompt,
additionalPrompts: additionalPrompts,
terms,
titleTranslationPrompt,
isChunk,
},
{ async: true },
)
logger.debug('Final system prompt:\n', finalSystemPrompt)
const { choices } = await openai.chat.completions.parse({
messages: [
{
role: 'system',
content: finalSystemPrompt,
},
{
role: 'user',
content: contentWithPlaceholders,
},
],
model: openaiModel,
temperature: 0.2,
})
const { content, refusal } = choices[0].message
if (refusal) {
throw new Error(refusal)
}
return restoreAnchors(content!, anchors)
}
const limit = pRateLimit({
interval: 60_000, // 1min
rate: 50,
concurrency: 10,
})
export interface TranslateCommandOptions {
source: Language
target: Language
glob: string[]
copy?: boolean
}
const supportedLanguages = SUPPORTED_LANGUAGES.join(', ')
export const translateCommand = new Command('translate')
.description('Translate the documentation')
.argument('[root]', 'Root directory of the documentation')
.option(
'-s, --source <language>',
`Document source language, one of ${supportedLanguages}`,
'en',
)
.option(
'-t, --target <language>',
`Document target language, one of ${supportedLanguages}`,
'zh',
)
.requiredOption(
'-g, --glob <path...>',
'Glob patterns of source dirs/files to translate',
)
.option(
'-C, --copy [boolean]',
'Wether to copy relative assets to the target directory instead of following links',
parseBoolean,
false,
)
.action(async function (root?: string) {
const {
source,
target,
glob: globs,
copy,
force,
...globalOptions
} = this.optsWithGlobals<TranslateCommandOptions & GlobalCliOptions>()
if (
!Object.hasOwn(Language, source) ||
!Object.hasOwn(Language, target) ||
source === target
) {
logger.error(
`Translate from language \`${cyan(source)}\` to \`${cyan(target)}\` is not supported.`,
)
process.exitCode = 1
return
}
const { config } = await loadConfig(root, globalOptions)
const docsDir = config.root!
const sourceDir = path.resolve(docsDir, source)
const targetDir = path.resolve(docsDir, target)
if (!(await pathExists(sourceDir, 'directory'))) {
logger.error(`The directory "${cyan(sourceDir)}" does not exist.`)
process.exitCode = 1
return
}
const sourceMatched = await glob(globs.map(removeLeadingSlash), {
absolute: true,
cwd: sourceDir,
onlyFiles: false,
})
const sourceFilePaths = await getMatchedDocFilePaths(sourceMatched)
const allSourceFilePaths = new Set(sourceFilePaths.flat())
const internalFilePaths = await glob(config.internalRoutes || [], {
absolute: true,
cwd: docsDir,
})
for (const internalFilePath of internalFilePaths) {
allSourceFilePaths.delete(internalFilePath)
}
// Get copy-only files using glob patterns
const copyOnlyFilePaths = await glob(COPY_ONLY_DIRECTORIES, {
absolute: true,
cwd: sourceDir,
})
const copyOnlyFilePathsSet = new Set(copyOnlyFilePaths)
if (allSourceFilePaths.size === 0) {
logger.error(
`No files matched by the glob patterns: ${globs.map((g) => `\`${cyan(g)}\``).join(', ')}`,
)
process.exitCode = 1
return
}
if (isDeepStrictEqual(globs, ['*'])) {
logger.warn(
`You're running in a special mode, all files except \`${cyan('internalRoutes')}\` will be translated, and all ${red('unmatched')} target files will be ${red('removed')}.`,
)
const targetMatched = await glob(globs.map(removeLeadingSlash), {
absolute: true,
cwd: targetDir,
onlyFiles: false,
})
const targetFilePaths = await getMatchedDocFilePaths(targetMatched)
const allTargetFilePaths = new Set(targetFilePaths.flat())
for (const internalFilePath of internalFilePaths) {
allTargetFilePaths.delete(internalFilePath)
}
const toRemoveTargetFilePaths: string[] = []
for (const targetFilePath of allTargetFilePaths) {
const targetRelativePath = path.relative(targetDir, targetFilePath)
const sourceFilePath = path.resolve(sourceDir, targetRelativePath)
if (!allSourceFilePaths.has(sourceFilePath)) {
toRemoveTargetFilePaths.push(targetFilePath)
}
}
if (toRemoveTargetFilePaths.length > 0) {
logger.warn(
'Found unmatched target files will be removed:\n' +
toRemoveTargetFilePaths.map((file) => `- ${red(file)}`).join('\n'),
)
await Promise.all(toRemoveTargetFilePaths.map((file) => fs.rm(file)))
}
}
const executor = async () =>
await Promise.all(
[...allSourceFilePaths].map(async (sourceFilePath) => {
const sourceContent = await fs.readFile(sourceFilePath, 'utf-8')
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { sourceSHA: _sourceSHA, ...sourceFrontmatter } = matter(
sourceContent,
).data as I18nFrontmatter
if (sourceFrontmatter.i18n?.disableAutoTranslation) {
allSourceFilePaths.delete(sourceFilePath)
return
}
const sourceSHA = crypto
.createHash('sha256')
.update(sourceContent)
.digest('hex')
const targetFilePath = sourceFilePath.replace(sourceDir, targetDir)
let targetContent: string | undefined
let targetFrontmatter: I18nFrontmatter | undefined
if (await pathExists(targetFilePath, 'file')) {
targetContent = await fs.readFile(targetFilePath, 'utf-8')
targetFrontmatter = matter(targetContent).data as I18nFrontmatter
if (!force && targetFrontmatter.sourceSHA === sourceSHA) {
allSourceFilePaths.delete(sourceFilePath)
return
}
}
const shouldCopyOnly = copyOnlyFilePathsSet.has(sourceFilePath)
await limit(async () => {
const sourceRelativePath = path.relative(docsDir, sourceFilePath)
const targetRelativePath = path.relative(docsDir, targetFilePath)
if (shouldCopyOnly) {
logger.info(
`Copying ${cyan(sourceRelativePath)} to ${cyan(targetRelativePath)}`,
)
// For copy-only files, we still update the sourceSHA but don't translate
const newFrontmatter = { ...sourceFrontmatter, sourceSHA }
delete newFrontmatter.i18n
const { content } = matter(sourceContent)
targetContent = matter.stringify(
content.startsWith('\n') ? content : '\n' + content,
newFrontmatter,
)
const targetBase = path.dirname(targetFilePath)
await fs.mkdir(targetBase, { recursive: true })
await fs.writeFile(targetFilePath, targetContent)
logger.info(
`${cyan(sourceRelativePath)} copied to ${cyan(targetRelativePath)}`,
)
} else {
logger.info(
`Translating ${cyan(sourceRelativePath)} to ${cyan(targetRelativePath)}`,
)
const isMdx = sourceFilePath.endsWith('.mdx')
const processor = isMdx ? mdxProcessor : mdProcessor
const ast = processor.parse(
escapeMarkdownHeadingIds(sourceContent),
)
const targetBase = path.dirname(targetFilePath)
const normalizeImgSrcOptions: NormalizeImgSrcOptions = {
localPublicBase: path.resolve(docsDir, 'public'),
sourceBase: path.dirname(sourceFilePath),
targetBase,
translating: { source, target, copy },
}
const normalizedSourceContent = processor.stringify({
...ast,
children: ast.children.map((it) =>
normalizeImgSrc(it, normalizeImgSrcOptions),
),
})
targetContent = await translateWithChunks({
...config.translate,
source,
sourceContent: normalizedSourceContent,
target,
additionalPrompts: sourceFrontmatter.i18n?.additionalPrompts,
})
const newFrontmatter = { ...sourceFrontmatter, sourceSHA }
delete newFrontmatter.i18n
const { data, content } = matter(targetContent)
const typedData = data as I18nFrontmatter
if (typedData.title && typeof typedData.title === 'string') {
newFrontmatter.title = typedData.title
}
if (
typedData.description &&
typeof typedData.description === 'string'
) {
newFrontmatter.description = typedData.description
}
if (sourceFrontmatter.title) {
const titleTranslation = getTitleTranslation(
sourceFrontmatter.title,
source,
target,
)
if (titleTranslation) {
newFrontmatter.title = titleTranslation
}
}
if (typeof newFrontmatter.title !== 'string') {
delete newFrontmatter.title
}
targetContent = matter.stringify(
content.startsWith('\n') ? content : '\n' + content,
newFrontmatter,
)
await fs.mkdir(targetBase, { recursive: true })
await fs.writeFile(targetFilePath, targetContent)
logger.info(
`${cyan(sourceRelativePath)} translated to ${cyan(targetRelativePath)}`,
)
}
allSourceFilePaths.delete(sourceFilePath)
})
}),
)
let retry = 0
while (retry < 15) {
try {
await executor()
return
} catch (error) {
if (error instanceof RateLimitError) {
const retryAfter =
Number(error.headers.get('retry-after')) || 60 * ++retry
logger.warn(`Rate limit exceeded, retrying in ${retryAfter}s...`)
await setTimeout(retryAfter)
continue
}
throw error
}
}
logger.error(
`Failed to translate after ${retry} retries, please try again later.`,
)
process.exitCode = 1
})