NReed.Dev

Sitecore | Optimizely | .NET

Using Sitecore Powershell Extensions to Automate Translating Content

We were weeks into content entry and discovered post deployment that some translated content had been removed and was no longer in the trashcan. I decided to use Sitecore Powershell Extensions (SPE) to try and assist authors in restoring the language versions of their lost content (and try to hurry along by automating the translations as well).

This is how I set about trying to do that.

First I grabbed the parent item and iterated on that and its children (and its children’s children), as to make sure that I would capture all of the items. Second I take the item and run it through Microsoft’s Cognitive Translation API. Upon getting the result I update the item in Sitecore and move on.

If there is already a language version of that item in my desired language then the script operates on that.

This script can also be used to automate creating language versions. You can see that script here.

PowerShell
function Create-LanguageVersionsAndTranslate-Text {
    param (
        [Sitecore.Data.Items.Item]$item
    )
    # Check if item is a media item
    #{F1828A2C-7E5D-4BBD-98CA-320474871548} == Image
    #{DAF085E8-602E-43A6-8299-038FF171349F} == Jpeg
    if ($item.TemplateId -eq "{F1828A2C-7E5D-4BBD-98CA-320474871548}" || $item.TemplateId -eq "{DAF085E8-602E-43A6-8299-038FF171349F}") {
        # Iterate through target languages
        foreach ($lang in $targetLanguages) {
            # Check if language version already exists
            $languageItem = $item.Versions | Where-Object { $_.Language.Name -eq $lang }
            if ($languageItem -eq $null) {
                # Create language version
                $languageItem = Add-ItemVersion -Item $item -TargetLanguage $lang -IfExist Skip
            }
           # Translate alt text (or any field you want to translate)
            $altText = $item.Fields["Alt"].Value
            # Set text to convert
            $textToConvert = $altText
            # Build Conversion Body
            $textBody = @(@{ Text = $textToConvert })
            $text = $textBody | ConvertTo-Json
            $text = '['+$text+']'
            # Convert
            $conversionResult = Invoke-RestMethod -Uri $convertURI -Method Post -Headers $headers -Body $text -ContentType "application/json"
            Write-Host -ForegroundColor 'yellow' "'$($textToConvert)' converted to '$($conversionResult.translations[0].text)'"
            $translatedAltText = $conversionResult.translations[0].text
            # Set translated alt text or any field you wish
            $languageItem.Editing.BeginEdit()
            $languageItem.Fields["Alt"].Value = $translatedAltText
            $languageItem.Editing.EndEdit()
        }
    }
}
function Process-MediaLibraryItems {
    param (
        [Sitecore.Data.Items.Item]$parentItem
    )
    # Process current item
    Create-LanguageVersionsAndTranslate-Text -item $parentItem
$descendants = Get-ChildItem -Path $parentItem.Paths.FullPath -Recurse
    # Recursively process child items
    foreach ($child in $descendants) {
        Create-LanguageVersionsAndTranslate-Text -item $child
    }
}
# Set API Key
$apiKey = "{your-apiKey}"
# Set Translation API endpoint
$translateBaseURI = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"
# Set source language code
$fromLang = "en" #original language of the item
# Set target language code
$toLang = "fr" #desired language 
# Set headers
$headers = @{
    "Ocp-Apim-Subscription-Key" = $apiKey
    "Ocp-Apim-Subscription-Region" = "eastus2"
    "Content-Type" = "application/json"
}
# Build Conversion URI
$convertURI = "$translateBaseURI&from=$fromLang&to=$toLang"
Write-Host $convertURI
$mediaLibraryPath = "/sitecore/content-path"
$targetLanguages = @("fr-CA") # Add target languages as needed
$mediaLibraryRoot = Get-Item -Path $mediaLibraryPath
Process-MediaLibraryItems -parentItem $mediaLibraryRoot

Leave a Reply

Your email address will not be published. Required fields are marked *