PowerShell/Scripts/translate-file.ps1

49 lines
1.8 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 a text file into another language
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2022-01-30 10:49:30 +01:00
This PowerShell script translates a text file into another language.
2021-10-16 16:50:10 +02:00
.PARAMETER File
Specifies the file to translate
.PARAMETER SourceLang
Specifies the source language
.PARAMETER TargetLang
Specifies the target language
2021-07-13 21:10:02 +02:00
.EXAMPLE
2021-09-25 19:43:22 +02:00
PS> ./translate-file C:\Memo.txt en de
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-30 10:49:30 +01:00
.NOTES
Author: Markus Fleschutz / License: CC0
2021-04-08 08:39:13 +02:00
#>
2021-07-15 15:51:22 +02:00
param([string]$File = "", [string]$SourceLang = "", [string]$TargetLang = "")
2021-04-08 08:39:13 +02:00
function UseLibreTranslate { param([string]$Text, [string]$SourceLang, [string]$TargetLang)
$Parameters = @{"q"="$Text"; "source"="$SourceLang"; "target"="$TargetLang"; }
$Result = (Invoke-WebRequest -Uri https://libretranslate.com/translate -Method POST -Body ($Parameters|ConvertTo-Json) -ContentType "application/json").content | ConvertFrom-Json
start-sleep -milliseconds 3000 # 20 requests per minute maximum
return $Result.translatedText
}
2021-04-08 08:39:13 +02:00
try {
2021-07-15 15:51:22 +02:00
if ($File -eq "" ) { $File = read-host "Enter path to file" }
if ($SourceLang -eq "" ) { $SourceLang = read-host "Enter language used in this file" }
if ($TargetLang -eq "" ) { $TargetLang = read-host "Enter language to translate to" }
$Lines = Get-Content -path $File
foreach($Line in $Lines) {
if ("$Line" -eq "") { write-output "$Line"; continue }
if ("$Line" -eq " ") { write-output "$Line"; continue }
if ("$Line" -like "===*") { write-output "$Line"; continue }
if ("$Line" -like "---*") { write-output "$Line"; continue }
if ("$Line" -like "!*(/*)") { write-output "$Line"; continue }
$Result = UseLibreTranslate $Line $SourceLang $TargetLang
write-output $Result
}
2021-09-27 10:09:45 +02:00
exit 0 # success
2021-04-08 08:39:13 +02:00
} catch {
2021-09-16 20:19:10 +02:00
"⚠️ Error: $($Error[0]) ($($MyInvocation.MyCommand.Name):$($_.InvocationInfo.ScriptLineNumber))"
2021-04-08 08:39:13 +02:00
exit 1
}