Files

66 lines
1.9 KiB
PHP
Executable File

<?php
// includes/Translate.php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class Translate {
private $client;
public function __construct() {
$this->client = new Client([
'base_uri' => LIBRETRANSLATE_URL,
'timeout' => 10.0,
'verify' => false
]);
}
public function translate($text, $targetLang, $sourceLang = 'auto') {
try {
$response = $this->client->post('/translate', [
'json' => [
'q' => $text,
'source' => $sourceLang,
'target' => $targetLang,
'format' => 'text'
]
]);
$body = json_decode($response->getBody()->getContents(), true);
if (isset($body['translatedText'])) {
return $body['translatedText'];
}
return null;
} catch (RequestException $e) {
error_log("Error en traducción: " . $e->getMessage());
return null;
}
}
public function translateBatch($texts, $targetLang, $sourceLang = 'auto') {
try {
$response = $this->client->post('/translate', [
'json' => [
'q' => $texts,
'source' => $sourceLang,
'target' => $targetLang,
'format' => 'text'
]
]);
$body = json_decode($response->getBody()->getContents(), true);
// LibreTranslate devuelve un array de objetos con la clave 'translatedText'
if (isset($body['translatedText']) && is_array($body['translatedText'])) {
return $body['translatedText'];
}
} catch (RequestException $e) {
error_log("Error en traducción por lotes: " . $e->getMessage());
return null;
}
return null;
}
}