39301-vm/api/translate.php
2026-03-25 08:05:46 +00:00

51 lines
1.4 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
require_once __DIR__ . '/../ai/LocalAIApi.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$text = trim($input['text'] ?? '');
$targetLang = trim($input['target_lang'] ?? '');
if (!$text || !$targetLang) {
http_response_code(400);
echo json_encode(['error' => 'Missing text or target_lang']);
exit;
}
$response = LocalAIApi::createResponse([
'input' => [
['role' => 'system', 'content' => 'You are a helpful translator. Translate the user input accurately. Output only the translated text.'],
['role' => 'user', 'content' => "Translate the following text to {$targetLang}: \"{$text}\""],
],
], [
'poll_interval' => 2,
'poll_timeout' => 30
]);
if (empty($response['success'])) {
http_response_code(500);
error_log("AI Translation Failed: " . json_encode($response));
echo json_encode(['error' => 'AI translation failed', 'details' => $response['error'] ?? 'Unknown error']);
exit;
}
$translatedText = LocalAIApi::extractText($response);
// Clean up any accidental quotes if the model adds them despite instructions
$translatedText = trim($translatedText, "
'" );
echo json_encode(['translation' => $translatedText]);