Skip to content

Instantly share code, notes, and snippets.

@baptadn
Created October 2, 2024 14:15
Show Gist options
  • Select an option

  • Save baptadn/00e4db9f20560565108a1eb26b66865e to your computer and use it in GitHub Desktop.

Select an option

Save baptadn/00e4db9f20560565108a1eb26b66865e to your computer and use it in GitHub Desktop.
MDX translation script
import 'dotenv/config'
import fs from 'fs/promises'
import path from 'path'
import OpenAI from 'openai'
import ProgressBar from 'progress'
export const translate = async (mdxPath: string) => {
try {
const content = await fs.readFile(mdxPath, 'utf-8')
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'system',
content:
'Translate the provided MDX text from French to English. Maintain the original style and improve the translation for fluent English. Do not translate the `slug` attribute in the meta header. Do not add MDX code fence markers.',
},
{
role: 'user',
content: content,
},
],
stream: true,
})
let translatedContent = ''
const bar = new ProgressBar('๐Ÿ‡บ๐Ÿ‡ธ Translating [:bar] :percent', {
total: 100,
complete: 'โ–‘',
})
let currentProgression = 0
for await (const part of stream) {
translatedContent += part.choices[0]?.delta?.content || ''
const percent = Math.floor((translatedContent.length * 100) / content.length)
if (percent > currentProgression) {
bar.tick()
currentProgression = percent
}
}
const enPath = path.join(path.dirname(mdxPath), 'en', path.basename(mdxPath))
await fs.mkdir(path.dirname(enPath), { recursive: true })
const updatedContent = translatedContent
.replace('../../components/Layout/BlogPost', '../../../components/Layout/BlogPost')
.replace(/^(---\s*\n)/, '$1lang: en\n')
await fs.writeFile(enPath, updatedContent)
console.log(`โœ… Translation saved to: ${enPath}`)
} catch (error) {
console.error('โŒ Error during translation:', error)
}
}
;(async () => {
const mdxPath = process.argv?.[2]
if (!mdxPath) {
console.error('โŒ no path')
return
}
await translate(mdxPath)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment