Author: Levan Velijanashvili (me@stichoza.com)
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Model::unguard();
     $tr = new TranslateClient('en', 'ar');
     $countries = json_decode(File::get(__DIR__ . "/u_countries.json"), true);
     Country::whereNotNull('id')->delete();
     City::whereNotNull('id')->delete();
     State::whereNotNull('id')->delete();
     foreach ($countries as $country) {
         $name = $tr->translate($country['name']);
         //$country['name'];
         $newCountry = Country::create(['name' => $name, 'iso_3166_2' => $country['iso_3166_2'], 'calling_code' => $country['calling_code']]);
     }
     $countries = Country::get();
     foreach ($countries as $country) {
         $new_cities = [];
         $new_states = [];
         $states = DB::connection('tests')->table('states')->select('states.*')->join('countries', function ($j) use($country) {
             $j->on('countries.id', '=', 'states.country_id')->where('countries.sortname', '=', $country->iso_3166_2);
         })->get();
         foreach ($states as $state) {
             $new_cities[] = ['id' => $state->id, 'name' => $tr->translate($state->name), 'country_id' => $country->id];
             $cities = DB::connection('tests')->table('cities')->select('cities.*')->join('states', function ($j) use($state) {
                 $j->on('states.id', '=', 'cities.state_id')->where('states.id', '=', $state->id);
             })->get();
             foreach ($cities as $city) {
                 $new_states[] = ['id' => $city->id, 'name' => $tr->translate($city->name), 'city_id' => $state->id];
             }
         }
         DB::table('lists_cities')->insert($new_cities);
         DB::table('lists_states')->insert($new_states);
     }
 }
 /**
  * Creates a translation.
  *
  * @param Model  $locale
  * @param string $text
  * @param Model  $parentTranslation
  *
  * @return Model
  */
 protected function firstOrCreateTranslation(Model $locale, $text, $parentTranslation = null)
 {
     // We'll check to see if there's a cached translation
     // first before we try and hit the database.
     $cachedTranslation = $this->getCacheTranslation($locale, $text);
     if ($cachedTranslation instanceof Model) {
         return $cachedTranslation;
     }
     // Check if auto translation is enabled. If so we'll run
     // the text through google translate and
     // save it, then cache it.
     if ($parentTranslation && $this->autoTranslateEnabled()) {
         $googleTranslate = new TranslateClient();
         $googleTranslate->setSource($parentTranslation->locale->code);
         $googleTranslate->setTarget($locale->code);
         try {
             $text = $googleTranslate->translate($text);
         } catch (ErrorException $e) {
             // Request to translate failed, set the text
             // to the parent translation
             $text = $parentTranslation->translation;
         } catch (UnexpectedValueException $e) {
             // Looks like something other than text was passed in,
             // we'll set the text to the parent translation
             // for this exception as well
             $text = $parentTranslation->translation;
         }
     }
     $translation = $this->translationModel->firstOrCreate([$locale->getForeignKey() => $locale->getKey(), $this->translationModel->getForeignKey() => isset($parentTranslation) ? $parentTranslation->getKey() : null, 'translation' => $text]);
     // Cache the translation so it's retrieved faster next time
     $this->setCacheTranslation($translation);
     return $translation;
 }
 /**
  * Execute command
  *
  * @param InputInterface  $input  Input
  * @param OutputInterface $output Output
  *
  * @return int|null|void
  *
  * @throws Exception
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->startCommand($output, false);
     $domains = $input->getOption('domain');
     $languages = $input->getOption('language');
     $project = $this->createProject($input);
     while (true) {
         $randomTranslation = $project->getRandomMissingTranslation($domains, $languages);
         if (!$randomTranslation instanceof Translation) {
             $this->printMessage($output, 'Trans Server', 'No more translations for you!');
             break;
         }
         $masterTranslation = $randomTranslation->getMasterTranslation();
         $translator = new TranslateClient($masterTranslation->getLanguage(), $randomTranslation->getLanguage());
         $translation = $translator->translate($masterTranslation->getValue());
         $this->printMessage($output, 'Trans Server', 'Language : ' . $randomTranslation->getLanguage())->printMessage($output, 'Trans Server', 'Key : ' . $randomTranslation->getKey())->printMessage($output, 'Trans Server', 'Original : ' . $randomTranslation->getMasterTranslation()->getValue())->printMessage($output, 'Trans Server', 'Translation : ' . $translation);
         $randomTranslation->setValue($translation);
         $masterStructure = $randomTranslation->getStructure();
         $this->overwriteLastValueFromStructure($masterStructure, $translation);
         $randomTranslation->setStructure($masterStructure);
         $project->addTranslation($randomTranslation)->save();
         $output->writeln('');
     }
     $this->finishCommand($output);
 }
Exemple #4
0
function translateToLocal($languagecode, $text)
{
    if ($languagecode == 'en') {
        //no conversion in case of english to english
        return $text;
    }
    $tr = new TranslateClient();
    $resultTwo = $tr->setSource('en')->setTarget($languagecode)->translate($text);
    return $resultTwo;
}
Exemple #5
0
function translate($text, $lang)
{
    $tr = new TranslateClient();
    // Default is from 'auto' to 'en'
    $tr->setSource('en');
    // Translate from English
    $tr->setTarget($lang);
    // Translate to Georgian
    echo $tr->translate($text);
}
Exemple #6
0
function translateTest()
{
    require __DIR__ . '/vendor/autoload.php';
    echo "<h1>Translation</h1>";
    $tr = new TranslateClient();
    // Default is from 'auto' to 'en'
    $tr->setSource('it');
    // Translate from English
    $tr->setTarget('en');
    // Translate to Georgian
    echo "Ciao a tutti ==> ";
    echo $tr->translate('Ciao a tutti!');
}
 public function testStaticAndNonstaticDetection()
 {
     $this->tr->translate('გამარჯობა');
     TranslateClient::translate(null, 'en', 'Cześć');
     $this->assertEquals($this->tr->getLastDetectedSource(), 'pl');
     $this->assertEquals(TranslateClient::getLastDetectedSource(), 'pl');
     $this->tr->translate('გამარჯობა');
     $this->assertEquals($this->tr->getLastDetectedSource(), 'ka');
     $this->assertEquals(TranslateClient::getLastDetectedSource(), 'ka');
 }
function getScore($comment)
{
    require __DIR__ . '/vendor/autoload.php';
    require_once __DIR__ . '/libs/sentimentAnalysis/autoload.php';
    //Translate first
    $tr = new TranslateClient();
    // Default is from 'auto' to 'en'
    //$tr->setSource('it');
    //$tr->setTarget('en');
    $comment = $tr->translate($comment);
    //Calculate sentiment
    $sentiment = new \PHPInsight\Sentiment();
    // calculations:
    $scores = $sentiment->score($comment);
    $class = $sentiment->categorise($comment);
    $toReturn['dom'] = $class;
    $toReturn['pos'] = $scores['pos'];
    $toReturn['neg'] = $scores['neg'];
    $toReturn['neu'] = $scores['neu'];
    return $toReturn;
}
 public function testArrayTranslation()
 {
     $this->tr->setSource('en')->setTarget('ka');
     $resultCat = $this->tr->translate('cat');
     $resultDog = $this->tr->translate('dog');
     $resultFish = $this->tr->translate('fish');
     $arrayResults = $this->tr->translate(['cat', 'dog', 'fish']);
     $arrayZesults = TranslateClient::translate('en', 'ka', ['cat', 'dog', 'fish']);
     $this->assertEquals($resultCat, $arrayResults[0], 'კატა');
     $this->assertEquals($resultDog, $arrayResults[1], 'ძაღლი');
     $this->assertEquals($resultFish, $arrayResults[2], 'თევზი');
     $this->assertEquals($resultCat, $arrayZesults[0], 'კატა');
     $this->assertEquals($resultDog, $arrayZesults[1], 'ძაღლი');
     $this->assertEquals($resultFish, $arrayZesults[2], 'თევზი');
 }
 /**
  * Summary.
  *
  * @since  0.9.0
  * @see
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param \Silex\Application                        $app
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  * @author nguyenvanduocit
  */
 public function translate(Request $request, Application $app)
 {
     $resultObject = new AttachmentResponse();
     $from = $request->get('from');
     $to = $request->get('to', 'en');
     $text = $request->get('text');
     $translator = new TranslateClient($from, $to);
     $translatedText = $translator->translate($text);
     if ($translatedText) {
         $from = $from ? $from : $translator->getLastDetectedSource();
         $messageFormat = '%1$s -> %2$s : %3$s';
         $message = sprintf($messageFormat, $from, $to, $translatedText);
         $resultObject->setText($message);
     } else {
         $resultObject->setErrorCode(404);
         $detectedSource = $translator->getLastDetectedSource();
         if (!$detectedSource) {
             $resultObject->setText('Can not detect your language');
         } else {
             $resultObject->setText('Can not translate your text.');
         }
     }
     return new JsonResponse($resultObject);
 }
 public static function fetchFromGoogle()
 {
     $trans_command = new Command();
     $trans_command->option('i')->aka('in')->describedAs("Input Language")->required()->default("en");
     $trans_command->option('o')->aka('out')->describedAs("Output Language");
     echo "Translate from {$trans_command['in']} to " . (isset($trans_command['out']) ? $trans_command['out'] : 'all') . "\n";
     $tr = new TranslateClient();
     $tr->setSource($trans_command['in']);
     $tr->setTarget($trans_command['out']);
     $langauges = Language::search()->exec();
     $untranslated_phrases = PhraseReplacement::search()->where('is_translated', 'No')->exec();
     foreach ($untranslated_phrases as $i => $phrase) {
         /* @var $phrase PhraseReplacement */
         /* @var $original PhraseOriginal */
         /* @var $langauge Language */
         $langauge = $langauges[$phrase->language_id];
         $translator = $tr->setTarget($langauge->code);
         $original = PhraseOriginal::search()->where('original_id', $phrase->original_id)->execOne();
         $output = $translator->translate($original->value);
         $phrase->value = $output;
         $phrase->is_translated = "Yes";
         $phrase->save();
     }
 }
 public function postTranslate()
 {
     $group = Input::get('group');
     $key = Input::get('key');
     $lang = Input::get('lang');
     $key = str_replace('.', '/', $group) . '.' . $key;
     if (Lang::has($key, 'en')) {
         $word = Lang::get($key, [], 'en');
         if ($translated = Cache::get($word . ':' . $lang)) {
             // Cached
         } else {
             $translated = TranslateClient::translate('en', $lang, $word);
             Cache::put($word . ':' . $lang, $translated, 30);
         }
     } else {
         $translated = null;
     }
     $translated = sentence_case($translated);
     $translated = str_replace([' .', '\''], ['.', '’'], $translated);
     if (stripos($lang, 'fr') === 0) {
         $translated = preg_replace('/\\s+\\?/', '&nbsp;?', $translated);
     }
     return ['word' => $translated];
 }
Exemple #13
0
<?php

include './vendor/autoload.php';
use Stichoza\GoogleTranslate\TranslateClient;
$tr = new TranslateClient('en', 'id');
echo '<pre style="padding:10px; background:#ddd;">';
echo $tr->translate('Hello World!');
echo '</pre>';
echo '<pre style="padding:10px; background:#ddd;">';
print_r($tr->translate(['I can dance', 'I like trains', 'Double rainbow']));
echo '</pre>';
 public function getGoogleTranslation($message, $language)
 {
     $arr_parts = $this->parse_safe_translate($message);
     $translation = '';
     foreach ($arr_parts as $str) {
         if (!stristr($str, '{')) {
             if (strlen($translation) > 0 and substr($translation, -1) === '}') {
                 $translation .= ' ';
             }
             $translation .= TranslateClient::translate(Yii::$app->language, $language, $str);
             // GoogleTranslate::staticTranslate($str, Yii::$app->language, $language);
         } else {
             // add space prefix unless it's first
             if (strlen($translation) > 0) {
                 $translation .= ' ' . $str;
             } else {
                 $translation .= $str;
             }
         }
     }
     print_r($translation);
     return $translation;
 }
 /**
  * {@inheritdoc}
  */
 public function translate($text)
 {
     return $this->client->translate($text);
 }
#!/usr/bin/php
<?php 
require 'vendor/autoload.php';
use Stichoza\GoogleTranslate\TranslateClient;
$tr = new TranslateClient('ko', 'en');
echo $tr->translate('안녕하세요.');
 public function testTranslationEquality()
 {
     $resultOne = TranslateClient::translate('en', 'ka', 'Hello');
     $resultTwo = $this->tr->setSource('en')->setTarget('ka')->translate('Hello');
     $this->assertEquals($resultOne, $resultTwo, 'გამარჯობა');
 }
 public function postTranslate(Request $request)
 {
     $text = TranslateClient::translate($request->input('origin'), $request->input('target'), $request->input('text'));
     $key = $request->input('key');
     return compact('key', 'text');
 }
Exemple #19
0
<?php

include_once "Stichoza\\GoogleTranslate\\TranslateClient.php";
use Stichoza\GoogleTranslate\TranslateClient;
$t = new TranslateClient();
$resultOne = TranslateClient::translate('en', 'ka', 'Hello');
//$resultTwo = $t->setSource('en')->setTarget('ka')->translate('Hello');
 /**
  * @expectedException InvalidArgumentException
  */
 public function testStaticInvalidArgumentException2()
 {
     TranslateClient::translate(1);
 }
Exemple #21
-2
 /**
  * @param $str
  * @param string $fromLocale
  * @param string $toLocale
  * @return string
  */
 public function autoTranslation($str, $fromLocale = 'en', $toLocale = 'de')
 {
     try {
         $translation = TranslateClient::translate($fromLocale, $toLocale, $str);
     } catch (\Exception $e) {
         error_log($e);
         $translation = $str;
     }
     return $translation;
 }