39301-vm/api/translate.php
2026-03-25 07:49:33 +00:00

47 lines
1.5 KiB
PHP

<?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;
}
$prompt = "Translate the following text to {$targetLang}. Provide ONLY the translation, without any additional text, quotes, or explanations.";
$response = LocalAIApi::createResponse([
'model' => 'gemini-2.0-flash-001', // Using a fast model if available, or default
'input' => [
['role' => 'system', 'content' => 'You are a helpful translator. Translate the user input accurately. Output only the translated text.'],
['role' => 'user', 'content' => $text],
],
]);
if (empty($response['success'])) {
http_response_code(500);
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, " \t\n\r\0\x0B\"'");
echo json_encode(['translation' => $translatedText]);