$text, 'source' => 'en', 'target' => 'sl', 'format' => 'text' ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $resp = curl_exec($ch); $err = curl_error($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err) { throw new Exception('Curl error: ' . $err); } if ($code < 200 || $code >= 300) { throw new Exception('HTTP ' . $code . ' response: ' . $resp); } $json = json_decode($resp, true); return $json['translatedText'] ?? null; } echo "Processing " . count($rows) . " rows...\n"; $i = 0; foreach ($rows as &$r) { $i++; // CSV columns: file,keycode,suggested_sl,suggested_en,placeholder $file = $r[0] ?? ''; $keycode = $r[1] ?? ''; $s_sl = $r[2] ?? ''; $s_en = $r[3] ?? ''; if (trim($s_sl) !== '') { // already populated continue; } // Build an English humanized guess from keycode if suggested_en is empty if (trim($s_en) !== '') { $source = $s_en; } else { $source = strtolower(str_replace('_', ' ', $keycode)); // Make it sentence-like: capitalize first letter and replace multiple spaces $source = preg_replace('/\s+/', ' ', $source); $source = ucfirst($source); } try { $translated = translateText($source, $libreUrl); if ($translated === null) { $translated = ''; } $r[2] = $translated; echo "[{$i}] OK: {$keycode} -> {$translated}\n"; } catch (\Throwable $e) { echo "[{$i}] WARN: {$keycode} -> " . $e->getMessage() . "\n"; // leave blank on error } // Rate limit: sleep 0.5s usleep(500000); } unset($r); // Write out CSV $ofh = fopen($out, 'w'); fputcsv($ofh, $header); foreach ($rows as $row) { fputcsv($ofh, $row); } fclose($ofh); echo "Wrote updated CSV to: $out\n"; exit(0);