@php /** * Auto Translate - Google Translate Free API Integration * * Receives rows with empty 'ceviri' field and translates 'icerik' to target 'dil' * Uses Google Translate unofficial free API endpoint * * POST Parameters: * - rows: array of objects with {id, icerik, dil} * * Returns JSON: * - success: boolean * - translated: array of {id, ceviri} * - errors: array of error messages */ header('Content-Type: application/json'); $rows = $request->input('rows', []); if (empty($rows)) { echo json_encode([ 'success' => false, 'message' => 'No rows provided', 'translated' => [], 'errors' => [] ]); exit; } $translated = []; $errors = []; /** * Convert snake_case or technical format to readable sentence * Example: "paint_cycle" -> "Paint Cycle" * Example: "protocol_date_cleaning" -> "Protocol Date Cleaning" * * @param string $text Input text (may contain underscores) * @return string Formatted readable text */ function formatToReadable($text) { // Replace underscores with spaces $text = str_replace('_', ' ', $text); // Replace multiple spaces with single space $text = preg_replace('/\s+/', ' ', $text); // Trim whitespace $text = trim($text); // Convert to title case (capitalize first letter of each word) $text = ucwords(strtolower($text)); return $text; } /** * Check if text looks like a technical/column name * (contains underscores or is all lowercase with no spaces) * * @param string $text Text to check * @return bool True if text appears to be technical format */ function isTechnicalFormat($text) { // Contains underscore if (strpos($text, '_') !== false) { return true; } // All lowercase with no spaces (like "paintcycle") if ($text === strtolower($text) && strpos($text, ' ') === false && strlen($text) > 3) { return true; } return false; } /** * Translate text using Google Translate Free API * * @param string $text Source text to translate * @param string $targetLang Target language code (e.g., 'ru', 'tr') * @param string $sourceLang Source language code (default: 'en') * @return string|null Translated text or null on failure */ function googleTranslate($text, $targetLang, $sourceLang = 'en') { if (empty($text) || empty($targetLang)) { return null; } // Skip if source and target are the same if ($sourceLang === $targetLang) { return $text; } $url = 'https://translate.googleapis.com/translate_a/single'; $params = [ 'client' => 'gtx', 'sl' => $sourceLang, 'tl' => $targetLang, 'dt' => 't', 'q' => $text ]; $fullUrl = $url . '?' . http_build_query($params); // Use cURL for better control $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $fullUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', CURLOPT_HTTPHEADER => [ 'Accept: application/json', 'Accept-Language: en-US,en;q=0.9' ] ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($curlError || $httpCode !== 200) { return null; } // Parse response - Google returns nested array structure $data = json_decode($response, true); if (!$data || !isset($data[0])) { return null; } // Extract translated text from nested arrays $translatedText = ''; foreach ($data[0] as $segment) { if (isset($segment[0])) { $translatedText .= $segment[0]; } } return $translatedText ?: null; } // Process each row foreach ($rows as $row) { $id = $row['id'] ?? null; $icerik = $row['icerik'] ?? ''; $dil = $row['dil'] ?? ''; if (!$id) { $errors[] = "Row missing ID"; continue; } if (empty($icerik)) { $errors[] = "Row $id: Empty source text (icerik)"; continue; } if (empty($dil)) { $errors[] = "Row $id: No target language specified"; continue; } // Format technical text (snake_case) to readable format before translation $readableText = $icerik; if (isTechnicalFormat($icerik)) { $readableText = formatToReadable($icerik); } // Translate the formatted text $translatedText = googleTranslate($readableText, $dil, 'en'); if ($translatedText === null) { $errors[] = "Row $id: Translation failed for '$icerik' to '$dil'"; continue; } // Update the database try { db('translate')->where('id', $id)->update([ 'ceviri' => $translatedText, 'updated_at' => now() ]); $translated[] = [ 'id' => $id, 'ceviri' => $translatedText ]; } catch (\Exception $e) { $errors[] = "Row $id: Database update failed - " . $e->getMessage(); } // Small delay to avoid rate limiting usleep(100000); // 100ms delay between requests } echo json_encode([ 'success' => count($translated) > 0, 'message' => count($translated) . ' rows translated successfully', 'translated' => $translated, 'errors' => $errors, 'total_requested' => count($rows), 'total_translated' => count($translated), 'total_errors' => count($errors) ]); @endphp