Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Simplify, improve and document the i18n pipeline (#2898)
Dhruv Bhanushali90dcb5224704
diff --git a/documentation/frontend/guides/index.md b/documentation/frontend/guides/index.mdindex 7a0562669..dab55e5be 100644--- a/documentation/frontend/guides/index.md+++ b/documentation/frontend/guides/index.md@@ -8,4 +8,5 @@ deploytestanalyticsicons+translate```diff --git a/documentation/frontend/guides/translate.md b/documentation/frontend/guides/translate.mdnew file mode 100644index 000000000..f506dc3c3--- /dev/null+++ b/documentation/frontend/guides/translate.md@@ -0,0 +1,33 @@+# Translate++## Fallbacks++If the translation for a string is missing, the list of fallback languages will+be checked, in order, for a translation. If one is found, it will be used. If+none is found, the final fallback, which is English will be used to render the+text.++For example, _Español de México_ / Spanish (Mexico) falls back to _Español_ /+Spanish (Spain) as the latter has a higher translation coverage.++If you know that a particular language is compatible with another with higher+translation coverage, you can modify the fallback chain defined in the+`frontend/src/locales/scripts/locale-fallback.json` file, and submit a PR.++Going back to the same example, it would be defined in the fallback file as+follows.++```json+{+ "es-mx": ["es"]+}+```++English is the final fallback for all languages as it always has 100% coverage.+You need not define it explicitly as it's specified as the default.++```json+{+ "default": ["en"]+}+```diff --git a/documentation/frontend/reference/i18n.md b/documentation/frontend/reference/i18n.mdnew file mode 100644index 000000000..1fd695c82--- /dev/null+++ b/documentation/frontend/reference/i18n.md@@ -0,0 +1,75 @@+# Internationalization++The frontend uses Nuxt's [i18n module](https://i18n.nuxtjs.org/) to support+[internationalization](https://developer.mozilla.org/en-US/docs/Glossary/I18N),+enabling localization of the user interface.++WordPress uses GlotPress for managing translations, which is built on top of the+[`gettext` standard](https://www.gnu.org/software/gettext/). On the other hand,+Nuxt (and most JS-based i18n libraries) use+[JSON](https://kazupon.github.io/vue-i18n/guide/formatting.html) for managing+translations. This disconnect means that Openverse translations must convert+from JSON to POT and back again. Hence there is quite a bit of scaffolding+involved.++## Upload pipeline++This pipeline deals with how translations strings are extracted from the+frontend application and provided to GlotPress for translation.++### Steps++- Create a POT file from the `en.json5` file.++ **Script:** `i18n:generate-pot`++- Upload this+ [POT file](https://github.com/WordPress/openverse/blob/translations/openverse.pot)+ to a fixed URL. Currently the file is hosted in the `translations` branch of+ the [WordPress/openverse](https://github.com/WordPress/openverse) repo.++- GlotPress presents the strings, fuzzy translations and other helpful context+ to translators in a web UI to help them provide a translation.++## Download pipeline++This pipeline deals with how translations are retrieved from GlotPress,+processed and loaded into Nuxt via the Nuxt i18n module.++### Steps++- Parse and extract the list of all locales from GlotPress's PHP source code.+ Then narrow down the list to locales available in the WP GlotPress instance+ and populate their coverage percentage from the+ [GlotPress stats](https://translate.wordpress.org/projects/meta/openverse/).++ The output is written to `wp-locales.json`.++ **Script:** `i18n:create-locales-list`++- Download all translations from GlotPress as JED 1.x JSON files. The flattened+ JED 1.x (derived from the flattened POT files) files are converted back into+ the nested JSON as expected by Nuxt i18n.++ This script uses the `wp-locales.json` file for the list of locales, if+ downloading each locale separately and in parallel.++ **Script:** `i18n:get-translations`++- Separate the locales into three groups based on the JSON files emitted by+ `i18n:get-translations`.++ - **translated:** JSON file is present with mappings, written to+ `valid-locales.json`.+ - **untranslated:** JSON file is present but empty, written to both+ `valid-locales.json` and `untranslated-locales.json`.+ - **invalid:** JSON file is not present, written to `invalid-locales.json`.++ **Script:** `i18n:update-locales`++- Pass the list of valid locales (along with extra fields) into the Nuxt i18n+ module. This is configured in the Nuxt configuration file, `nuxt.config.ts`.++- Pass the fallback locale mappings to the underlying Vue i18n plugin. This is+ configured in the plugin configuration file,+ `frontend/src/plugins/vue-i18n.ts`.diff --git a/documentation/frontend/reference/index.md b/documentation/frontend/reference/index.mdindex bfa79a228..ced85c513 100644--- a/documentation/frontend/reference/index.md+++ b/documentation/frontend/reference/index.md@@ -3,6 +3,7 @@```{toctree}:titlesonly:+i18nfeature_flagstesting_guidelinesplaywright_testsdiff --git a/frontend/.gitignore b/frontend/.gitignoreindex 5b57678d3..a094d805f 100644--- a/frontend/.gitignore+++ b/frontend/.gitignore@@ -20,6 +20,7 @@ src/locales/openverse.zipsrc/locales/*.jsonsrc/locales/scripts/valid-locales.jsonsrc/locales/scripts/untranslated-locales.json+src/locales/scripts/invalid-locales.jsonsrc/locales/scripts/wp-locales.json# Workspace mock-filesdiff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex 718f1f79c..1f937ef4e 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -93,18 +93,20 @@ const filenames: NonNullable<NuxtConfig["build"]>["filenames"] = {const openverseLocales = [{- // unique identifier for the locale in Vue i18n- code: "en",+ /* Nuxt i18n fields */++ code: "en", // unique identifier for the locale in Vue i18n+ dir: "ltr",+ file: "en.json",+ iso: "en", // used for SEO purposes (html lang attribute)++ /* Custom fields */+name: "English",nativeName: "English",- // ISO code used for SEO purposes (html lang attribute)- iso: "en",- // wp_locale as found in GlotPress- wpLocale: "en_US",- file: "en.json",},...(locales ?? []),-].filter((l) => Boolean(l.iso)) as LocaleObject[]+].filter((l) => Boolean(l.code)) as LocaleObject[]const port = process.env.PORT || 8443const isProdNotPlaywright = isProd && !(process.env.PW === "true")diff --git a/frontend/src/locales/scripts/create-wp-locale-list.js b/frontend/src/locales/scripts/create-wp-locale-list.jsindex 8feefb0c1..fec81aa14 100644--- a/frontend/src/locales/scripts/create-wp-locale-list.js+++ b/frontend/src/locales/scripts/create-wp-locale-list.js@@ -33,16 +33,9 @@ const createPropertyRePatterns = ({properties = ["english_name","native_name",- "lang_code_iso_639_1",- "lang_code_iso_639_2",- "country_code",- "slug",- "nplurals",- "plural_expression",- "google_code",- "facebook_locale",+ "lang_code_iso_639_1", // used for HTML lang attribute+ "slug", // unique identifier used by Nuxt i18n"text_direction",- "wp_locale",],} = {}) => {const propertyRePatterns = {}@@ -73,10 +66,7 @@ function parseLocaleData(rawData) {data[camelCasedPropName] = value[1]}})- return {- wpLocale: wpLocale,- data,- }+ return [wpLocale, data]}}@@ -89,21 +79,22 @@ function parseLocaleData(rawData) {* @returns {Promise<{}>}*/async function getWpLocaleData() {- const locales = {}-const data = await getGpLocalesData()const rawLocalesData = data.split("new GP_Locale();").splice(1).map((item) => item.trim())- rawLocalesData.forEach((rawData) => {- const localeData = parseLocaleData(rawData)- if (localeData) {- locales[localeData.wpLocale] = localeData.data- }- })+ const locales = Object.fromEntries(+ rawLocalesData.map(parseLocaleData).filter(Boolean)+ )+ console.log(`${rawLocalesData.length} locales found in GP source code.`)+const unsortedLocales = await addFetchedTranslationStatus(locales)+ console.log(+ `${Object.keys(unsortedLocales).length} locales found in WP GP instance.`+ )+return Object.keys(unsortedLocales).sort().reduce((accumulator, currentValue) => {diff --git a/frontend/src/locales/scripts/get-translations-status.js b/frontend/src/locales/scripts/get-translations-status.jsindex b0f437962..cc608f912 100644--- a/frontend/src/locales/scripts/get-translations-status.js+++ b/frontend/src/locales/scripts/get-translations-status.js@@ -10,22 +10,11 @@ const axios = require("./axios")const baseUrl = "https://translate.wordpress.org/projects/meta/openverse/"-function parseRow(row, locales) {+function parseRow(row) {const cells = row.querySelectorAll("td")- const langLink = cells[0].querySelector("a")- const langName = langLink.text.trim()- const langObject = locales.find((locale) => {- return locale.name === langName- })- if (langObject) {- const percentTranslated = parseInt(- cells[1].text.trim().replace("%", ""),- 10- )- langObject.code = langObject.slug- langObject.translated = percentTranslated- return langObject- }+ const langName = cells[0].querySelector("a").text.trim()+ const percentTranslated = parseInt(cells[1].text.trim().replace("%", ""), 10)+ return [langName, percentTranslated]}/**@@ -35,22 +24,25 @@ function parseRow(row, locales) {* locale object.*/const addFetchedTranslationStatus = async (gpLocales) => {- const locales = Object.values(gpLocales)-- const localesData = {}const raw = await axios.get(baseUrl)-const parsed = parser.parse(raw.data)- parsed- .querySelector("tbody")- .querySelectorAll("tr")- .forEach((row) => {- const locale = parseRow(row, locales)- if (locale) {- localesData[locale.wpLocale] = locale- }- })- return localesData+ const langPercent = Object.fromEntries(+ parsed.querySelector("tbody").querySelectorAll("tr").map(parseRow)+ )++ return Object.fromEntries(+ Object.entries(gpLocales)+ .filter(([, langObject]) =>+ Object.hasOwnProperty.apply(langPercent, [langObject.name])+ )+ .map(([langKey, langObject]) => [+ langKey,+ {+ ...langObject,+ translated: langPercent[langObject.name],+ },+ ])+ )}module.exports = { addFetchedTranslationStatus }diff --git a/frontend/src/locales/scripts/get-validated-locales.js b/frontend/src/locales/scripts/get-validated-locales.jsindex de7ef21ae..0707db2e1 100644--- a/frontend/src/locales/scripts/get-validated-locales.js+++ b/frontend/src/locales/scripts/get-validated-locales.js@@ -13,30 +13,40 @@ const { addFetchedTranslationStatus } = require("./get-translations-status")* @returns {{* translated: import('./types').I18nLocaleProps[],* untranslated: import('./types').I18nLocaleProps[]+ * invalid: import('./types').I18nLocaleProps[],* }}*/const getValidatedLocales = async () => {const result = {translated: [],untranslated: [],+ invalid: [],}const updatedLocaleList = await addFetchedTranslationStatus(localesList)const allLocales = Object.values(updatedLocaleList).map((locale) => ({+ /* Nuxt i18n fields */+code: locale.slug,- name: locale.name,- nativeName: locale.nativeName ?? locale.name,- iso: locale.langCodeIso_639_1,- wpLocale: locale.wpLocale,dir: locale.textDirection || "ltr",- translated: locale.translated,file: `${locale.slug}.json`,+ iso: locale.langCodeIso_639_1 ?? undefined,++ /* Custom fields */++ name: locale.name,+ nativeName: locale.nativeName || locale.name,+ translated: locale.translated,}))for (const locale of allLocales) {const fileLocation = `${process.cwd()}/src/locales/${locale.file}`if (fs.existsSync(fileLocation)) {- result.translated.push(locale)+ if (Object.keys(JSON.parse(fs.readFileSync(fileLocation))).length) {+ result.translated.push(locale)+ } else {+ result.untranslated.push(locale)+ }} else {- result.untranslated.push(locale)+ result.invalid.push(locale)}}return result@@ -44,16 +54,30 @@ const getValidatedLocales = async () => {try {getValidatedLocales().then((locales) => {+ console.log(`Found ${locales.translated.length} locales with translations.`)const fileName = "valid-locales.json"+ const valid = [...locales.translated, ...locales.untranslated]fs.writeFileSync(process.cwd() + `/src/locales/scripts/` + fileName,- JSON.stringify(locales.translated, null, 2) + "\n"+ JSON.stringify(valid, null, 2) + "\n"+ )++ console.log(+ `Found ${locales.untranslated.length} locales without translations.`)const untranslatedFileName = "untranslated-locales.json"fs.writeFileSync(process.cwd() + `/src/locales/scripts/` + untranslatedFileName,JSON.stringify(locales.untranslated, null, 2) + "\n")++ console.log(`Found ${locales.invalid.length} invalid locales.`)+ const invalidFileName = "invalid-locales.json"+ fs.writeFileSync(+ process.cwd() + `/src/locales/scripts/` + invalidFileName,+ JSON.stringify(locales.invalid, null, 2) + "\n"+ )+console.log(`> Wrote locale metadata for @nuxt/i18n.`)})} catch (err) {diff --git a/frontend/src/locales/scripts/locale-fallback.json b/frontend/src/locales/scripts/locale-fallback.jsonnew file mode 100644index 000000000..22a1106ea--- /dev/null+++ b/frontend/src/locales/scripts/locale-fallback.json@@ -0,0 +1,10 @@+{+ "es-ar": ["es"],+ "es-cl": ["es"],+ "es-co": ["es"],+ "es-do": ["es"],+ "es-ec": ["es"],+ "es-mx": ["es"],+ "es-ve": ["es"],+ "default": ["en"]+}diff --git a/frontend/src/plugins/vue-i18n.ts b/frontend/src/plugins/vue-i18n.tsindex e39d9ed17..2d944babf 100644--- a/frontend/src/plugins/vue-i18n.ts+++ b/frontend/src/plugins/vue-i18n.ts@@ -1,6 +1,8 @@+import fallbackLocale from "~/locales/scripts/locale-fallback.json"+export default () => {return {- fallbackLocale: "en",+ fallbackLocale,silentFallbackWarn: true,pluralizationRules: {/**diff --git a/frontend/typings/nuxt__types/index.d.ts b/frontend/typings/nuxt__types/index.d.tsindex b048c9902..328aa168c 100644--- a/frontend/typings/nuxt__types/index.d.ts+++ b/frontend/typings/nuxt__types/index.d.ts@@ -52,5 +52,6 @@ declare module "@nuxtjs/i18n" {export interface LocaleObject {name: stringnativeName: string+ translated: number}}