PowerShell/Scripts/translate-text.ps1

47 lines
1.6 KiB
PowerShell
Raw Normal View History

2021-09-27 10:38:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2021-10-04 21:29:23 +02:00
Translates text into other languages
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2022-01-30 10:49:30 +01:00
This PowerShell script translates text into other languages.
2021-10-16 16:50:10 +02:00
.PARAMETER Text
Specifies the text to translate
.PARAMETER SourceLang
2023-07-02 12:01:35 +02:00
Specifies the source language (English by default)
2021-10-16 16:50:10 +02:00
.PARAMETER TargetLang
2023-07-02 12:01:35 +02:00
Specifies the target language (all by default)
2021-07-13 21:10:02 +02:00
.EXAMPLE
2023-07-02 12:01:35 +02:00
PS> ./translate-text "Hello World" en all
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-30 10:49:30 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2020-12-29 15:14:21 +01:00
#>
2020-10-10 18:51:57 +02:00
2023-07-02 12:01:35 +02:00
param([string]$Text = "", [string]$SourceLangCode = "en", [string]$TargetLangCode = "all")
2020-05-03 18:54:49 +02:00
2022-01-02 12:04:56 +01:00
function UseLibreTranslate { param([string]$Text, [string]$SourceLangCode, [string]$TargetLangCode)
$Parameters = @{"q"="$Text"; "source"="$SourceLangCode"; "target"="$TargetLangCode"; }
2023-06-30 22:18:13 +02:00
$Result = (Invoke-WebRequest -Uri https://libretranslate.de/translate -Method POST -Body ($Parameters|ConvertTo-Json) -ContentType "application/json" -useBasicParsing).content | ConvertFrom-Json
return $Result.translatedText
}
2020-05-03 18:54:49 +02:00
2020-10-05 13:12:12 +02:00
try {
2023-07-02 12:01:35 +02:00
if ($Text -eq "" ) { $Text = Read-Host "Enter the text to translate" }
2021-07-15 15:51:22 +02:00
2023-07-02 12:01:35 +02:00
if ($TargetLangCode -eq "all") {
2022-01-02 12:04:56 +01:00
$TargetLangCodes = "ar","de","es","fr","ga","hi","it","ja","ko","pt","ru","zh"
foreach($TargetLangCode in $TargetLangCodes) {
$Translation = UseLibreTranslate $Text $SourceLangCode $TargetLangCode
2023-07-02 12:01:35 +02:00
Write-Output "$($TargetLangCode): $Translation"
Start-Sleep -seconds 6 # 10 requests maximum per minute
2021-04-09 12:53:22 +02:00
}
} else {
2022-01-02 12:04:56 +01:00
$Translation = UseLibreTranslate $Text $SourceLangCode $TargetLangCode
2023-07-02 12:01:35 +02:00
Write-Output "$Translation"
2020-10-05 13:12:12 +02:00
}
2021-09-27 10:09:45 +02:00
exit 0 # success
2020-12-09 10:30:55 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2020-12-09 10:30:55 +01:00
exit 1
}