DEV Community

Cover image for Using ChatGPT To Translate React App into Over 40 Languages in Just 100 Seconds

Using ChatGPT To Translate React App into Over 40 Languages in Just 100 Seconds

Utilizing Chat GPT to Translate a React Application into Over 40 Languages in Just 100 Seconds

GitHub Repo : https://github.com/idurar/idurar-erp-crm

In this article, we will explore how Chat GPT, an AI-powered language model, can be utilized to effortlessly translate a React application into more than 40 languages within a mere 100 seconds. This powerful approach not only expedites the translation process but also eliminates the need for maintaining multiple translation issues.

Watch Video on Youtube : click here

Utilizing Chat GPT to Translate a React Application into Over 40 Languages in Just 100 Seconds

require('dotenv').config({ path: '.env' });
require('dotenv').config({ path: '.env.local' });
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

const OpenAI = require('openai');
const fs = require('fs');

const openai = new OpenAI({
  apiKey: OPENAI_API_KEY,
});

function objectToText(obj) {
  let text = '{\n';
  Object.entries(obj).forEach(([key, value]) => {
    text += `${key}: "${value}",\n`;
  });
  text += '}';
  return text;
}

const generateBackendFile = ({ language, newLanguageContent }) => {
  const txt = objectToText(newLanguageContent);
  const fileContent = `module.exports = ${txt}`;

  const filePath = '../backend/src/locale/translation/' + language + '.js';

  fs.writeFile(filePath, fileContent, (err) => {
    if (err) {
      console.error(err);
      return;
    }
  });
};

const generateFrontendFile = ({ language, newLanguageContent }) => {
  const txt = objectToText(newLanguageContent);
  const fileContent = `const lang = ${txt}\n export default lang`;

  const filePath = '../frontend/src/locale/translation/' + language + '.js';

  fs.writeFile(filePath, fileContent, (err) => {
    if (err) {
      console.error(err);
      return;
    }
  });
};
// Creating an instance of OpenAIApi with API key from the environment variables

async function translate(language, langObject) {
  const objText = objectToText(langObject);
  const response = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo-16k',
    messages: [
      {
        role: 'system',
        content:
          'You will be provided with text as js object, and your task is to translate all text into requested language , and return result as valid json',
      },
      {
        role: 'user',
        content: `translate this into ${language} language : ${objText}`,
      },
    ],
    temperature: 0.5,
    max_tokens: 12000,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
  });
  const list = response.choices[0].message.content;
  return list;
}

const languages = require('../locale/languages');

const missedWords = require(`./missedWords`);

async function generateTranslation(language) {
  const filePath = `../locale/translation/${language.value}`;
  const currentLang = require(filePath);

  const result = await translate(language.label, missedWords);
  const translatedFile = JSON.parse(result);

  const newLanguageContent = { ...currentLang, ...translatedFile };

  generateBackendFile({ language: language.value, newLanguageContent });
  generateFrontendFile({ language: language.value, newLanguageContent });
}

languages.forEach(({ label, value }) => {
  generateTranslation({ label, value });
});

Enter fullscreen mode Exit fullscreen mode

The project at hand is housed in a repository called idurar erp crm. By visiting this repository and showing your support with a star, you can gain access to the code and delve deeper into the implementation details.

One of the key highlights of the showcased application is its extensive multilingual support. With over 40 languages available, users from various linguistic backgrounds can benefit from this React application. Achieving such comprehensive language integration was made possible by harnessing the capabilities of Chat GPT.

Initially, the development team requested contributions from fellow developers by creating specific translation issues within the repository. This approach proved successful in collecting valuable translations from enthusiastic contributors. However, as the project evolved and grew in scope, managing individual translation issues became cumbersome.

To address this challenge, a custom script was devised. This script leverages the power of OpenAI's Chat GPT and streamlines the translation process. The first step involves establishing a connection with OpenAI by utilizing the provided OpenAI key stored in the environment variables.

Once connected, the script proceeds to loop over the language files within the React application. For each language file, the script interacts with Chat GPT and initiates the translation process. By sending the language file to Chat GPT along with the desired target language, the script receives the translated version as output.

To further simplify the translation workflow, an NPM package manager integration was implemented. By executing the command npm run translate, developers can trigger the translation process for all the files specified as arguments in the message world. This seamless integration significantly enhances the efficiency and convenience of translating multiple files at once.

The project presented in the video not only showcases the immense potential of Chat GPT in accelerating the localization efforts of React applications but also serves as an excellent educational resource. By studying this project, developers can gain valuable insights into leveraging AI-powered solutions to optimize their own development processes.

In conclusion, the implementation of Chat GPT for translating a React application into numerous languages opens up new avenues for global accessibility and user reach. The idler.com project stands as a testament to the dedication and hard work put forth by its creator. We highly recommend exploring this project and leveraging its learnings to propel your development endeavors forward.

As part of the engaging online community surrounding this project, we encourage you to support the speaker's YouTube channel by liking, subscribing, and posting your questions. Rest assured, they have committed to responding to every comment, ensuring a fruitful exchange of ideas and knowledge.

Open Source ERP CRM

Top comments (0)