-
-
Save baptadn/00e4db9f20560565108a1eb26b66865e to your computer and use it in GitHub Desktop.
MDX translation script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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