[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: Deepl перевод api
ElikBerg
Есть проблема:
исходное
English(EN).sql (образец)

-- Direction: LTR
-- Export date: 2023.05.11
-- version: 4.9.1
-- Language SQL Dump: ENGLISH (EN)


INSERT INTO `{prefix}languages` (`Code`, `Key`, `Status`, `Date_format`, `Direction`, `Locale`) VALUES ('en', 'english', 'active', '%b %d, %Y', 'ltr', '');

INSERT INTO `{prefix}lang_keys` (`Code`, `Module`, `Key`, `Value`, `Plugin`, `Status`) VALUES

('en', 'frontEnd', 'listings_of_category', 'Listings of the {category} category', '', 'active'),
('en', 'admin', 'links_type', 'Listing type URL', '', 'active'),
('en', 'common', 'account_fields+name+First_name', 'First Name', '', 'active'),
('en', 'frontEnd', 'registration_complete_auto_login', 'You''ve been logged into the account automatically; you may [add listing] and use other features on the site.', '', 'active'),
('en', 'common', 'photos_leave', '{count} pictures enabled', '', 'active'),
('en', 'common', 'set_primary_notice', 'The picture has been set as primary.', '', 'active'),
('en', 'common', 'images_number', 'Number of pictures', '', 'active'),
('en', 'common', 'listing_number', 'Number of listings', '', 'active'),
('en', 'common', 'profile_information', 'Profile Settings', '', 'active'),
('en', 'common', 'account_information', 'Account Settings', '', 'active'),
('en', 'common', 'crop_too_small', 'The selected area on the picture is too small; enlarge the area and try again.', '', 'active'),
('en', 'common', 'crop_completed', 'The picture has been successfully cropped and saved.', '', 'active'),
('en', 'common', 'listing_live_for', 'Listing live for', '', 'active'),
('en', 'common', 'error_listing_expired', 'The listing has expired.', '', 'active'),
('en', 'admin', 'edit_listing_no_form_fields_error', 'Listing form of the category doesn''t have any fields.', '', 'active'),
('en', 'admin', 'replace_plan_option', 'Please select another listing package for all listings added under the <b>{plan}</b> before removing it.', '', 'active'),
('en', 'admin', 'full_plan_delete', 'Remove the listing package and disable all listings in main and mirror categories.', '', 'active'),
('en', 'admin', 'full_plan_drop', 'Remove the listing package and hide all the listings added.', '', 'active'),
('en', 'admin', 'submit_form_empty', 'Listing form of the <b>{category}</b> category is empty; click [here] to populate it with fields.', '', 'active'),
('en', 'admin', 'replace_account', 'Assign all the listings to another user before removing it.', '', 'active'),
('en', 'admin', 'full_username_delete', 'Remove the user account with all its listings irretrievably.', '', 'active'),
('en', 'admin', 'listing_type_edited', 'You''ve successfully edited the listing type.', '', 'active'),
('en', 'admin', 'ability_to_add', 'Allow users to add listings to "{type}".', '', 'active'),
('en', 'admin', 'listing_made_featured', 'You''ve successfully upgraded the selected listings to featured.', '', 'active'),
('en', 'common', 'pages+name+listing_remove', 'Remove Listing', '', 'active'),
('en', 'frontEnd', 'pages+title+listing_remove', 'Remove incomplete listing', '', 'active'),
('en', 'common', 'pages+name+upgrade_listing', 'Upgrade Listing', '', 'active'),
('en', 'frontEnd', 'pages+title+upgrade_listing', 'Upgrade Listing', '', 'active'),
('en', 'frontEnd', 'pages+title+edit_listing', 'Edit Listing', '', 'active'),
('en', 'common', 'pages+name+edit_listing', 'Edit Listing', '', 'active'),
('en', 'frontEnd', 'pages+title+my_profile', 'Edit My Profile', '', 'active'),
('en', 'admin', 'config+name+featured', 'Featured Settings', '', 'active'),

который надо перевести на Русский. и получить на выходе Russian(RU).sql

есть index.php

<?php

error_reporting(E_ALL);

require_once 'translation_functions.php';

$inputFile = 'English(EN).sql';
$outputFile = 'Russian(RU).sql';

if (!file_exists($inputFile)) {
logError('Input file not found.');
exit;
}

$logFile = '/home/admin/web/site.com/public_html/translation_log.txt';
if (file_exists($logFile)) {
unlink($logFile); // Удаляем предыдущий лог-файл, если существует
}

$inputContent = file_get_contents($inputFile);
$lines = explode("\n", $inputContent);

$outputContent = '';

foreach ($lines as $line) {
if (startsWith($line, 'INSERT INTO')) {
$translatedLine = translateLine($line); // Вызов функции перевода строки
$outputContent .= $translatedLine . "\n";
} else {
$outputContent .= $line . "\n";
}
}

// Записываем переведенный контент в выходной файл
file_put_contents($outputFile, $outputContent);

// Записываем состояние процесса и ошибки в лог-файл
$logContent = "Translation process completed.\n";
$logContent .= "Input file: $inputFile\n";
$logContent .= "Output file: $outputFile\n";
if (file_exists($logFile)) {
$logContent .= file_get_contents($logFile);
}
file_put_contents($logFile, $logContent);

// Функция для проверки, начинается ли строка с указанной подстроки
function startsWith($string, $substring) {
return substr($string, 0, strlen($substring)) === $substring;
}
?>

translation_functions.php

<?php

// Функция для перевода текста с помощью API Deepl
function translateText($text, $target_lang) {
// Замените 'YOUR_API_KEY' на ваш API-ключ Deepl
$api_key = 'api-key';

$url = 'https://api-free.deepl.com/v2/translate';
$data = [
'auth_key' => $api_key,
'text' => $text,
'target_lang' => $target_lang,
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
curl_close($ch);

$translated_text = json_decode($response, true)['translations'][0]['text'];

return $translated_text;
}

// Функция обработки строки с переводом
function processTranslationLine($line) {
logStatus('Processing translation line: ' . $line);

$translatedLine = '';
preg_match_all("/'([^']+)'/", $line, $matches);

if (!empty($matches[1])) {
foreach ($matches[1] as $value) {
logStatus('Translating value: ' . $value);

// Перевод значения на русский язык
$translatedValue = translateText($value, 'RU');
$translatedLine .= "'" . addslashes($translatedValue) . "', ";
}

$translatedLine = rtrim($translatedLine, ', ');
}

return str_replace($matches[0], $translatedLine, $line);
}

// Функция для перевода строки
function translateLine($line) {
logStatus('Translating line: ' . $line);

logStatus('Processing translation line: ' . $line);
$translatedLine = processTranslationLine($line);

logStatus('Translated line: ' . $translatedLine);

return $translatedLine;
}

// Логирование ошибок и состояния процесса
function logError($error) {
$logFile = __DIR__ . '/translation_log.txt';
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[$timestamp] ERROR: $error\n";

file_put_contents($logFile, $logMessage, FILE_APPEND);
}

function logStatus($status) {
$logFile = __DIR__ . '/translation_log.txt';
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[$timestamp] $status\n";

file_put_contents($logFile, $logMessage, FILE_APPEND);
}

?>

в лог пишет

Translation process completed.
Input file: English(EN).sql
Output file: Russian(RU).sql

но файл Russian(RU).sql выдает как из исходного без перевода. где то ошибка.
PHP 7.2
Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.