Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement free Google translation service #12

Merged
merged 2 commits into from
Oct 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"nikic/php-parser": "^v5.2",
"google/cloud-translate": "^1.17",
"openai-php/client": "^0.10.1",
"deeplcom/deepl-php": "^1.9"
"deeplcom/deepl-php": "^1.9",
"stichoza/google-translate-php": "^5.2"
},
"scripts": {
"test": "vendor/bin/phpunit tests"
Expand Down
83 changes: 82 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion config/translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
| Supported: "google", "openai", "deepl"
|
*/
'default' => env('DEFAULT_TRANSLATOR_SERVICE', 'openai'),
'default' => env('DEFAULT_TRANSLATOR_SERVICE', 'free_google'),
'translators' => [
'free_google' => [
'driver' => Bottelet\TranslationChecker\Translator\FreeGoogleTranslator::class,
],
'google' => [
'driver' => Bottelet\TranslationChecker\Translator\GoogleTranslator::class,
'type' => env('GOOGLE_TRANSLATE_TYPE', 'service_account'),
Expand Down
12 changes: 12 additions & 0 deletions docs/translation-services/free-google.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
title: Free Google
layout: default
parent: Translation Services
nav_order: 0
---

# Google Translation API

Access Google Translate free of charge, without needing to set up API keys.

Based on this [powerful package](https://github.com/Stichoza/google-translate-php)
6 changes: 4 additions & 2 deletions docs/translation-services/google.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ parent: Translation Services
nav_order: 1
---

# Google Translation API
# Google Cloud Translation API

For Google Cloud Translate (More advanced translation than free Google previously), you need to set the following
environment variables

For Google Translate, you need to set the following environment variables
```bash
GOOGLE_TRANSLATE_TYPE=service_account
GOOGLE_TRANSLATE_PROJECT_ID=your_project_id
Expand Down
8 changes: 8 additions & 0 deletions src/TranslationCheckerServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Bottelet\TranslationChecker\Sort\AlphabeticSort;
use Bottelet\TranslationChecker\Sort\SorterContract;
use Bottelet\TranslationChecker\Translator\DeeplTranslator;
use Bottelet\TranslationChecker\Translator\FreeGoogleTranslator;
use Bottelet\TranslationChecker\Translator\GoogleTranslator;
use Bottelet\TranslationChecker\Translator\OpenAiTranslator;
use Bottelet\TranslationChecker\Translator\TranslatorContract;
Expand Down Expand Up @@ -37,6 +38,13 @@ public function register(): void
);
});

$this->app->bind(FreeGoogleTranslator::class, function ($app) {
return new FreeGoogleTranslator(
$app->make(VariableRegexHandler::class),
new \Stichoza\GoogleTranslate\GoogleTranslate()
);
});

$this->app->bind(OpenAiTranslator::class, function ($app) {
$factory = OpenAI::factory();
if ($app->config['translator.translators.openai.api_key']) {
Expand Down
78 changes: 78 additions & 0 deletions src/Translator/FreeGoogleTranslator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace Bottelet\TranslationChecker\Translator;

use Bottelet\TranslationChecker\Translator\VariableHandlers\VariableRegexHandler;
use Stichoza\GoogleTranslate\Exceptions\LargeTextException;
use Stichoza\GoogleTranslate\Exceptions\RateLimitException;
use Stichoza\GoogleTranslate\Exceptions\TranslationRequestException;
use Stichoza\GoogleTranslate\GoogleTranslate;

class FreeGoogleTranslator implements TranslatorContract
{
public function __construct(
protected VariableRegexHandler $variableHandler,
protected GoogleTranslate $translateClient,
) {
}

/**
* @throws LargeTextException
* @throws RateLimitException
* @throws TranslationRequestException
*/
public function translate(string $text, string $targetLanguage, string $sourceLanguage = 'en'): string
{
$replaceVariablesText = $this->variableHandler->replacePlaceholders($text);

$translation = $this->translateClient
->setSource($sourceLanguage)
->setTarget($targetLanguage)
->translate($replaceVariablesText);

if (!isset($translation)) {
return '';
}

return $this->variableHandler->restorePlaceholders($translation);
}

/**
* @param array<string> $texts Array of texts to translate.
* @param string $targetLanguage
* @param string $sourceLanguage
* @return array<string, string> Array of translated texts.
*
* @throws LargeTextException
* @throws RateLimitException
* @throws TranslationRequestException
*/
public function translateBatch(array $texts, string $targetLanguage, string $sourceLanguage = 'en'): array
{
$textsToTranslate = array_map([$this->variableHandler, 'replacePlaceholders'], $texts);

$translations = [];
foreach ($textsToTranslate as $text) {
$translations[] = $this->translateClient
->setSource($sourceLanguage)
->setTarget($targetLanguage)
->translate($text);
}

$translatedKeys = [];
foreach ($translations as $index => $translation) {
$translatedText = $translation ? $this->variableHandler->restorePlaceholders($translation) : '';
$translatedKeys[$texts[$index]] = $translatedText;
}

return $translatedKeys;
}

public function isConfigured(): bool
{
/** @var array<string, null|string> $freeGoogleConfig */
$freeGoogleConfig = config('translator.translators.free_google');

return !in_array(null, $freeGoogleConfig, true);
}
}
132 changes: 132 additions & 0 deletions tests/Translator/FreeGoogleTranslatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace Bottelet\TranslationChecker\Tests\Translator;

use Bottelet\TranslationChecker\Translator\FreeGoogleTranslator;
use Bottelet\TranslationChecker\Translator\GoogleTranslator;
use Bottelet\TranslationChecker\Translator\VariableHandlers\VariableRegexHandler;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;

class FreeGoogleTranslatorTest extends \Bottelet\TranslationChecker\Tests\TestCase
{
/** @var VariableRegexHandler|MockObject */
private $variableHandlerMock;

/** @var \Stichoza\GoogleTranslate\GoogleTranslate|MockObject */
private $translateClientMock;

/** @var FreeGoogleTranslator */
private $freeGoogleTranslator;

protected function setUp(): void
{
parent::setUp();
$this->translateClientMock = $this->createMock(\Stichoza\GoogleTranslate\GoogleTranslate::class);
$this->variableHandlerMock = $this->createMock(VariableRegexHandler::class);
$this->freeGoogleTranslator = new FreeGoogleTranslator($this->variableHandlerMock, $this->translateClientMock);
}

#[Test]
public function freeGoogleTranslateIfTextKeyNotReturned(): void
{
$this->translateClientMock->method('translate')->willReturn(null);

$this->variableHandlerMock->method('restorePlaceholders')->willReturn('Translated text');

$result = $this->freeGoogleTranslator->translate('Hello', 'fr', 'en');

$this->assertEquals('', $result);
}

#[Test]
public function translate(): void
{
$text = 'Hello, world!';
$translatedText = 'Bonjour le monde!';
$targetLanguage = 'fr';

$this->variableHandlerMock
->method('replacePlaceholders')
->willReturn($text);

$this->variableHandlerMock
->method('restorePlaceholders')
->willReturn($translatedText);

$this->translateClientMock
->method('setSource')
->with('en')
->willReturn($this->translateClientMock);

$this->translateClientMock
->method('setTarget')
->with($targetLanguage)
->willReturn($this->translateClientMock);

$this->translateClientMock
->method('translate')
->with($text)
->willReturn($translatedText);

$result = $this->freeGoogleTranslator->translate($text, $targetLanguage);

$this->assertSame($translatedText, $result);
}

#[Test]
public function translateBatch(): void
{
$texts = ['Hello, world!', 'Good morning'];
$translatedTexts = ['Bonjour le monde!', 'Bonjour'];
$targetLanguage = 'fr';
$sourceLanguage = 'en';

$this->variableHandlerMock
->expects($this->exactly(count($texts)))
->method('replacePlaceholders')
->willReturnArgument(0);

$this->variableHandlerMock
->expects($this->exactly(count($texts)))
->method('restorePlaceholders')
->willReturnArgument(0);

$this->translateClientMock
->expects($this->exactly(count($texts)))
->method('setSource')
->with($sourceLanguage)
->willReturnSelf();

$this->translateClientMock
->expects($this->exactly(count($texts)))
->method('setTarget')
->with($targetLanguage)
->willReturnSelf();

$this->translateClientMock->expects($this->exactly(count($texts)))
->method('translate')
->willReturnOnConsecutiveCalls(...$translatedTexts);

$result = $this->freeGoogleTranslator->translateBatch($texts, $targetLanguage, $sourceLanguage);

$this->assertSame(
[
'Hello, world!' => 'Bonjour le monde!',
'Good morning' => 'Bonjour'],
$result
);
}

#[Test]
public function testGoogleTranslatorBinding(): void
{
$this->assertInstanceOf(GoogleTranslator::class, app(GoogleTranslator::class));
}

#[Test]
public function testGoogleTranslatorHasValidCredentials(): void
{
$this->assertTrue($this->freeGoogleTranslator->isConfigured());
}
}