'No file received']); exit; } $file = $_FILES['file']; logMessage("File received: " . $file['name']); // Check for upload errors if ($file['error'] !== UPLOAD_ERR_OK) { $uploadErrors = [ 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk', 8 => 'A PHP extension stopped the file upload' ]; $errorMessage = isset($uploadErrors[$file['error']]) ? $uploadErrors[$file['error']] : 'Unknown upload error'; logMessage("File upload error: " . $errorMessage, 'ERROR'); echo json_encode(['error' => 'File upload error: ' . $errorMessage]); exit; } // Verify file if (!file_exists($file['tmp_name']) || !is_readable($file['tmp_name'])) { logMessage("Temporary file does not exist or is not readable: " . $file['tmp_name'], 'ERROR'); echo json_encode(['error' => 'Temporary file does not exist or is not readable']); exit; } // Get translation parameters $source_lang = $_POST['source_lang'] ?? ''; $target_lang = $_POST['target_lang'] ?? ''; $formality = $_POST['formality'] ?? 'default'; logMessage("Source Language: $source_lang"); logMessage("Target Language: $target_lang"); logMessage("Formality: $formality"); // Initialize Storage Helper logMessage("Initializing Storage Helper"); $storageHelper = new StorageHelper(); // Upload file to local storage logMessage("Uploading file to local storage: " . $file['name']); $sourceFile = $storageHelper->uploadSourceFile($file['tmp_name'], $file['name']); if (!$sourceFile) { logMessage("Failed to save file to local storage", 'ERROR'); echo json_encode(['error' => 'Failed to save file to local storage']); exit; } // Set up target info for the translated file logMessage("Setting up target info for translated file"); $targetInfo = $storageHelper->getTargetInfo($file['name'], $target_lang); if (!$targetInfo) { logMessage("Failed to set up target file info", 'ERROR'); echo json_encode(['error' => 'Failed to set up target file info']); exit; } // Prepare the request to Microsoft Document Translation API $batchTranslationUrl = MS_API_ENDPOINT . 'translator/document/batches?api-version=' . MS_API_VERSION; logMessage("Prepared translation API URL: $batchTranslationUrl"); // Format the source and target language codes correctly $formattedSourceLang = $source_lang !== 'AUTO' ? strtolower($source_lang) : ''; $formattedTargetLang = strtolower($target_lang); // Handle special cases for Microsoft's language codes if ($formattedTargetLang === 'en-gb') { $formattedTargetLang = 'en-GB'; } else if ($formattedTargetLang === 'en-us') { $formattedTargetLang = 'en-US'; } else if ($formattedTargetLang === 'pt-pt') { $formattedTargetLang = 'pt-PT'; } else if ($formattedTargetLang === 'pt-br') { $formattedTargetLang = 'pt-BR'; } // Generate URLs for Microsoft Translator API $sourceUrl = $sourceFile['file_url']; // Direct file URL $targetUrl = $targetInfo['blob_url']; // Directory URL for target logMessage("Source URL: $sourceUrl"); logMessage("Target URL: $targetUrl"); // Create the request body for Document Translation API $requestBody = [ 'inputs' => [ [ 'source' => [ 'sourceUrl' => $sourceUrl, 'storageSource' => 'AzureBlob', // We say AzureBlob but using local URLs 'language' => $formattedSourceLang ?: 'en' ], 'targets' => [ [ 'targetUrl' => $targetUrl, 'storageSource' => 'AzureBlob', 'language' => $formattedTargetLang, 'category' => 'general' ] ] ] ] ]; // Set formality if supported if ($formality === 'more' || $formality === 'less') { $requestBody['inputs'][0]['targets'][0]['formality'] = ($formality === 'more') ? 'Formal' : 'Informal'; } logMessage("Prepared request body: " . json_encode($requestBody, JSON_PRETTY_PRINT)); // Make the API call $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $batchTranslationUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Ocp-Apim-Subscription-Key: ' . MS_API_KEY, 'Ocp-Apim-Subscription-Region: ' . MS_API_REGION, 'Content-Type: application/json' ]); $jsonBody = json_encode($requestBody); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBody); logMessage("Sending request to Microsoft Translator API"); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); logMessage("CURL Info: " . json_encode(curl_getinfo($ch))); curl_close($ch); if ($response === false) { $error = curl_error($ch); logMessage("cURL Error: " . $error, 'ERROR'); echo json_encode(['error' => 'cURL error: ' . $error]); } else { logMessage("API Response Code: $httpCode"); logMessage("API Response: $response"); if ($httpCode >= 400) { logMessage("HTTP Error Response: $httpCode - $response", 'ERROR'); echo json_encode(['error' => "HTTP Error: $httpCode", 'details' => $response]); } else { $result = json_decode($response, true); if (json_last_error() === JSON_ERROR_NONE) { // Store information for later use if (isset($result['id'])) { // Create a custom response that matches what our frontend expects $translationResponse = [ 'document_id' => $result['id'], // Microsoft's batch ID 'document_key' => json_encode([ 'source_blob' => $sourceFile['blob_name'], 'target_blob' => $targetInfo['blob_name'], 'ms_response' => $result ]) ]; echo json_encode($translationResponse); logMessage("Translation job submitted successfully with ID: " . $result['id']); } else { logMessage("Microsoft Translator API error: " . json_encode($result), 'ERROR'); echo json_encode(['error' => 'Microsoft Translator API response missing ID', 'details' => $result]); } } else { logMessage("Invalid JSON response: " . json_last_error_msg(), 'ERROR'); echo json_encode(['error' => 'Invalid JSON response: ' . json_last_error_msg(), 'raw_response' => $response]); } } } } catch (Exception $e) { logMessage("Exception: " . $e->getMessage() . "\nStack trace: " . $e->getTraceAsString(), 'ERROR'); echo json_encode(['error' => 'Server error: ' . $e->getMessage()]); } } else { logMessage("Received non-POST request", 'ERROR'); echo json_encode(['error' => 'Invalid request method']); } ?>