private/New-AzureTranslation.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function New-AzureTranslation
{
    [CmdletBinding()]
    param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipeline = $true)]
        [string]
        $Value,

        [Parameter(Mandatory = $true)]
        [CultureInfo]
        $From,

        [Parameter(Mandatory = $true)]
        [CultureInfo]
        $To,

        [Parameter()]
        [String]
        $ApiVersion = '3.0'
    )

    begin
    {

        $azureUri = 'https://api.cognitive.microsofttranslator.com/translate?api-version={0}&from={1}&to={2}' -f $ApiVersion, $From.TwoLetterISOLanguageName, $To.TwoLetterISOLanguageName
        $key = Get-TranslationApiKey -Provider Azure

        if (-not $key)
        {
            Write-Error -Message 'No valid API key found. Try adding one with Add-TranslationApiKey -Provider Azure. See https://docs.microsoft.com/en-us/azure/cognitive-services/translator/translator-info-overview for more information.' -RecommendedAction 'Add API key'
            return
        }

        $header = @{
            'Ocp-Apim-Subscription-Key' = $key
        }

        Write-Verbose -Message $('Using endpoint {0} with API key {1}' -f $azureUri, $($( -join $key[0, 1]) + $('*' * 28) + $( -join $key[-2, -1])))

        $requestCollector = New-Object -TypeName System.Collections.Specialized.OrderedDictionary
        $count = 0
        $requestCollector.Add($count, @())
    }

    process
    {
        if ($requestCollector[$count].Count -gt 23)
        {
            $count ++
            $requestCollector.Add($count, @())
        }

        Write-Verbose -Message "Adding '$Value' to collection ($($requestCollector[$count].Count) elements)"
        $requestCollector[$count] += @{ Text = $Value }
    }

    end
    {
        Write-Verbose -Message "Requesting $($requestCollector.Count) batch(es) of translations"
        foreach ($entry in $requestCollector.GetEnumerator())
        {
            $jsonBody = ConvertTo-Json -InputObject $entry.Value
            Write-Verbose -Message "Using body `n`n$jsonBody"
            $(Invoke-RestMethod -Method Post -Uri $azureUri -Body $jsonBody -Headers $header -ContentType application/json).translations.text
        }
    }

}