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
2023-07-02 12:01:35 +02:00
This PowerShell script translates the given text file into another language and writes the output on the console.
2021-10-16 16:50:10 +02:00
.PARAMETER File
2023-07-02 12:01:35 +02:00
Specifies the path to the file to be translated
2021-10-16 16:50:10 +02:00
.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
2022-09-06 21:42:04 +02:00
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"; }
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
Start-Sleep -seconds 6 # 10 requests per minute maximum
return $Result.translatedText
}
2021-04-08 08:39:13 +02:00
try {
2023-07-02 12:01:35 +02:00
if ($File -eq "" ) { $File = Read-Host "Enter the file path" }
if ($SourceLang -eq "" ) { $SourceLang = Read-Host "Enter the source language" }
if ($TargetLang -eq "" ) { $TargetLang = Read-Host "Enter the target language" }
2021-07-15 15:51:22 +02:00
$Lines = Get-Content -path $File
foreach($Line in $Lines) {
2023-06-30 22:18:13 +02:00
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
2023-06-30 22:18:13 +02:00
Write-Output $Result
}
2021-09-27 10:09:45 +02:00
exit 0 # success
2021-04-08 08:39:13 +02:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-04-08 08:39:13 +02:00
exit 1
}