{"id":1127,"date":"2023-04-16T21:44:01","date_gmt":"2023-04-16T21:44:01","guid":{"rendered":"http:\/\/oqtacore-blog-473533498.us-east-1.elb.amazonaws.com\/?p=1127"},"modified":"2023-09-22T16:27:06","modified_gmt":"2023-09-22T16:27:06","slug":"aws-lambda-to-translate-your-app-using-deepl-for-free","status":"publish","type":"post","link":"https:\/\/oqtacore.com\/blog\/aws-lambda-to-translate-your-app-using-deepl-for-free\/","title":{"rendered":"AWS Lambda to translate your app using Deepl for free"},"content":{"rendered":"<p>Imagine you have a modern app that you would want to translate to other languages quickly using machine translation. Using this code, you can translate your app to all languages in minutes. For free.<\/p>\n<p><!--more--><\/p>\n<p>Chances are, you do not want to spend $200 per language. You just want to quickly rollout your app to all possible locales, see the engagement and metrics, and then decide if you want to move forward.<\/p>\n<p>Here is AWS Lambda code that takes a file named &#8220;app_main.en.json&#8221; from S3 and creates translated copies of it named\u00a0 &#8220;app_main.fr.json&#8221;, &#8220;app_main.de.json&#8221;, etc.<\/p>\n<p>You will need to create a free account at Deepl to get an API authentication key.<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">const AWS = require('aws-sdk');\r\nconst S3 = new AWS.S3();\r\nconst https = require('https');\r\n\r\nconst SOURCE_LOCALE = 'en'; \/\/ Replace with the source locale of your i18next JSON file\r\nconst TARGET_LOCALES = ['de', 'fr', 'es']; \/\/ add or remove languages as needed\r\nconst FILE_NAME = 'app_main';\r\nconst BUCKET = 'your bucket';\r\nconst DEEPL_API_KEY = 'Register at Deepl to get your API authentication key';\r\n\r\nexports.handler = async (event) =&gt; {\r\n    \/\/ Retrieve the i18next JSON file from S3\r\n    const params = {\r\n        Bucket: BUCKET,\r\n        Key: `${FILE_NAME}.${SOURCE_LOCALE}.json`\r\n    };\r\n    const data = await S3.getObject(params).promise();\r\n    const i18nData = JSON.parse(data.Body.toString('utf-8'));\r\n\r\n    \/\/ Loop through each target language and translate the i18n data using DeepL API\r\n    const translations = {};\r\n    const savePromises = [];\r\n    for (const language of TARGET_LOCALES) {\r\n        const translatedJson = {};\r\n        const promises = Object.entries(i18nData).map(async ([key, value]) =&gt; { translatedJson[key] = await translate(value, language); });\r\n\r\n        await Promise.all(promises);\r\n\r\n        const s3Params = {\r\n            Bucket: BUCKET,\r\n            Key: `${FILE_NAME}.${language}.json`,\r\n            Body: JSON.stringify(translatedJson),\r\n            ContentType: 'application\/json'\r\n        };\r\n        const savePromise = S3.putObject(s3Params).promise();\r\n        savePromises.push(savePromise);\r\n    }\r\n\r\n    await Promise.all(savePromises);\r\n\r\n    return {\r\n        statusCode: 200,\r\n        body: JSON.stringify(translations)\r\n    };\r\n};\r\n\r\n\/\/ Helper function to translate the i18n data using DeepL API\r\nfunction translate(text, targetLanguage) {\r\n    return new Promise((resolve, reject) =&gt; {\r\n        const apiKey = DEEPL_API_KEY;\r\n        const options = {\r\n            hostname: 'api-free.deepl.com',\r\n            path: '\/v2\/translate',\r\n            method: 'POST',\r\n            headers: {\r\n                'Content-Type': 'application\/x-www-form-urlencoded'\r\n            }\r\n        };\r\n        const request = https.request(options, (response) =&gt; {\r\n            let chunks = [];\r\n            response.on('data', (chunk) =&gt; {\r\n                chunks.push(chunk);\r\n            });\r\n            response.on('end', () =&gt; {\r\n                const translation = JSON.parse(Buffer.concat(chunks).toString());\r\n                console.log(JSON.stringify(translation));\r\n                resolve(translation.translations[0].text);\r\n            });\r\n        });\r\n\r\n        request.on('error', (error) =&gt; {\r\n            reject(error);\r\n        });\r\n\r\n        const data = new URLSearchParams();\r\n        data.append('text', text);\r\n        data.append('auth_key', apiKey);\r\n        data.append('source_lang', SOURCE_LOCALE);\r\n        data.append('target_lang', targetLanguage);\r\n        request.write(data.toString());\r\n        request.end();\r\n    });\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Imagine you have a modern app that you would want to translate to other languages quickly using machine translation. Using this code, you can translate your app to all languages in minutes. For free.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_mo_disable_npp":"","yasr_overall_rating":0,"yasr_post_is_review":"","yasr_auto_insert_disabled":"","yasr_review_type":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-1127","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"acf":{"image":1176},"yasr_visitor_votes":{"number_of_votes":0,"sum_votes":0,"stars_attributes":{"read_only":false,"span_bottom":false}},"_links":{"self":[{"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/posts\/1127","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/comments?post=1127"}],"version-history":[{"count":6,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/posts\/1127\/revisions"}],"predecessor-version":[{"id":1177,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/posts\/1127\/revisions\/1177"}],"wp:attachment":[{"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/media?parent=1127"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/categories?post=1127"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/oqtacore.com\/blog\/wp-json\/wp\/v2\/tags?post=1127"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}