Skip to content

Instantly share code, notes, and snippets.

@chrispage1
Last active November 28, 2024 10:43
Show Gist options
  • Save chrispage1/35cd2425e499410882d9888c750a2b56 to your computer and use it in GitHub Desktop.
Save chrispage1/35cd2425e499410882d9888c750a2b56 to your computer and use it in GitHub Desktop.
DeepL File Translation script
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
define('LARAVEL_START', microtime(true));
// this project requires access to Laravel features
$path = '~/laravel-project-dir/';
require_once $path . 'vendor/autoload.php';
$app = (require_once $path . 'bootstrap/app.php');
$app->make(Kernel::class)->bootstrap();
// path that contains the source file (must be EN.docx)
$fileDir = '~/files/';
$translations = ['IT', 'FR', 'NL', 'ES', 'PT', 'DE'];
// upload our document
function getClient(): PendingRequest
{
$apiKey = 'XXXXXX-XXXXX-XXXXX-XXXXX-XXXXX';
return Http::withToken($apiKey, 'DeepL-Auth-Key')
->baseUrl('https://api.deepl.com/v2/');
}
foreach ($translations as $translation) {
dump("Beginning $translation translation...");
$response = getClient()
->asMultipart()
->attach('file', file_get_contents($fileDir . '/EN.docx'), 'EN.docx')
->post('document', ['target_lang' => $translation]);
if (!$response->successful()) {
dd($response->json());
}
/** @var array{document_id: string, document_key: string} $data */
$data = $response->json();
$attempt = 0;
do {
sleep(3);
dump('Check #' . ++$attempt);
$status = getClient()->post('document/' . $data['document_id'], [
'document_key' => $data['document_key'],
])->json('status');
} while ($status !== 'done');
dump("Downloading $translation...");
sleep(1);
getClient()->sink($fileDir . $translation . '.docx')
->post('document/' . $data['document_id'] . '/result', [
'document_key' => $data['document_key'],
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment