'Chinese', 'fr' => 'French', 'ja' => 'Japanese', 'pt-br' => 'Portuguese (Brazilian)', 'ru' => 'Russian', 'tr' => 'Turkish', ]; function makeGeminiRequest(string $systemPrompt, string $userPrompt, string $model, string $apiKey, int $reties = 2): string { $url = "https://generativelanguage.googleapis.com/v1beta/models/$model:generateContent"; $body = json_encode([ "contents" => [ ["role" => "model", "parts" => ['text' => $systemPrompt]], ["role" => "user", "parts" => ['text' => $userPrompt]] ], ]); $response = @file_get_contents($url, false, stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => "Content-Type: application/json\r\nX-Goog-Api-Key: $apiKey\r\nContent-Length: " . strlen($body) . "\r\n", 'content' => $body, 'timeout' => 300, ] ])); $generatedDocs = json_decode($response, true)['candidates'][0]['content']['parts'][0]['text'] ?? ''; if (!$response || !$generatedDocs) { print_r(error_get_last()); print_r($response); if ($reties > 0) { echo "Retrying... ($reties retries left)\n"; sleep(SLEEP_SECONDS_BETWEEN_REQUESTS); return makeGeminiRequest($systemPrompt, $userPrompt, $model, $apiKey, $reties - 1); } exit(1); } return $generatedDocs; } function createPrompt(string $language, string $englishFile, string $currentTranslation): array { $systemPrompt = << trim($filename), $fileToTranslate); $apiKey = $_SERVER['GEMINI_API_KEY'] ?? $_ENV['GEMINI_API_KEY'] ?? ''; if (!$apiKey) { echo 'Enter gemini api key ($GEMINI_API_KEY): '; $apiKey = trim(fgets(STDIN)); } $files = array_filter(scandir(__DIR__), fn($filename) => str_ends_with($filename, '.md')); foreach ($files as $file) { $englishFile = file_get_contents(__DIR__ . "/$file"); if ($fileToTranslate && !in_array($file, $fileToTranslate)) { continue; } foreach (LANGUAGES as $language => $languageName) { echo "Translating $file to $languageName\n"; $currentTranslation = file_get_contents(__DIR__ . "/$language/$file") ?: ''; [$systemPrompt, $userPrompt] = createPrompt($language, $englishFile, $currentTranslation); $markdown = makeGeminiRequest($systemPrompt, $userPrompt, MODEL, $apiKey); echo "Writing translated file to $language/$file\n"; file_put_contents(__DIR__ . "/$language/$file", sanitizeMarkdown($markdown)); echo "sleeping to avoid rate limiting...\n"; sleep(SLEEP_SECONDS_BETWEEN_REQUESTS); } }