How to use the @google-cloud/translate.Translate function in @google-cloud/translate

To help you get started, we’ve selected a few @google-cloud/translate examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googleapis / nodejs-translate / samples / translate.js View on Github external
function detectLanguageSample(text) {
  // [START translate_detect_language]
  // Imports the Google Cloud client library
  const {Translate} = require('@google-cloud/translate').v2;

  // Creates a client
  const translate = new Translate();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const text = 'The text for which to detect language, e.g. Hello, world!';

  // Detects the language. "text" can be a string for detecting the language of
  // a single piece of text, or an array of strings for detecting the languages
  // of multiple texts.
  async function detectLanguage() {
    let [detections] = await translate.detect(text);
    detections = Array.isArray(detections) ? detections : [detections];
    console.log('Detections:');
    detections.forEach(detection => {
      console.log(`${detection.input} => ${detection.language}`);
    });
github firebase / extensions / firestore-translate-text / functions / lib / index.js View on Github external
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const translate_1 = require("@google-cloud/translate");
const config_1 = require("./config");
const logs = require("./logs");
const validators = require("./validators");
var ChangeType;
(function (ChangeType) {
    ChangeType[ChangeType["CREATE"] = 0] = "CREATE";
    ChangeType[ChangeType["DELETE"] = 1] = "DELETE";
    ChangeType[ChangeType["UPDATE"] = 2] = "UPDATE";
})(ChangeType || (ChangeType = {}));
const translate = new translate_1.Translate({ projectId: process.env.PROJECT_ID });
// Initialize the Firebase Admin SDK
admin.initializeApp();
logs.init();
exports.fstranslate = functions.handler.firestore.document.onWrite((change) => __awaiter(this, void 0, void 0, function* () {
    logs.start();
    const { languages, inputFieldName, outputFieldName } = config_1.default;
    if (validators.fieldNamesMatch(inputFieldName, outputFieldName)) {
        logs.fieldNamesNotDifferent();
        return;
    }
    if (validators.fieldNameIsTranslationPath(inputFieldName, outputFieldName, languages)) {
        logs.inputFieldNameIsOutputPath();
        return;
    }
    const changeType = getChangeType(change);
    try {
github googleapis / nodejs-translate / samples / translate.js View on Github external
function listLanguagesSample() {
  // [START translate_list_codes]
  // Imports the Google Cloud client library
  const {Translate} = require('@google-cloud/translate').v2;

  // Creates a client
  const translate = new Translate();

  async function listLanguages() {
    // Lists available translation language with their names in English (the default).
    const [languages] = await translate.getLanguages();

    console.log('Languages:');
    languages.forEach(language => console.log(language));
  }

  listLanguages();
  // [END translate_list_codes]
}
github firebase / extensions / rtdb-translate-text / functions / lib / index.js View on Github external
step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const translate_1 = require("@google-cloud/translate");
const config_1 = require("./config");
const logs = require("./logs");
var ChangeType;
(function (ChangeType) {
    ChangeType[ChangeType["CREATE"] = 0] = "CREATE";
    ChangeType[ChangeType["DELETE"] = 1] = "DELETE";
    ChangeType[ChangeType["UPDATE"] = 2] = "UPDATE";
})(ChangeType || (ChangeType = {}));
const translate = new translate_1.Translate({ projectId: process.env.PROJECT_ID });
// Initialize the Firebase Admin SDK
admin.initializeApp();
logs.init();
exports.rtdbtranslate = functions.handler.database.ref.onWrite((change) => __awaiter(this, void 0, void 0, function* () {
    logs.start();
    const changeType = getChangeType(change);
    try {
        switch (changeType) {
            case ChangeType.CREATE:
                yield handleCreateDocument(change.after);
                break;
            case ChangeType.DELETE:
                yield handleDeleteDocument(change.after);
                break;
            case ChangeType.UPDATE:
                yield handleUpdateDocument(change.before, change.after);
github ioBroker / ioBroker.docs / engine / build-lib / translation.js View on Github external
'use strict';

const request = require('request');
const fs = require('fs');
let lastRequest = null;
const {Translate} = require('@google-cloud/translate');
// Your Google Cloud Platform project ID
const projectId = 'web-site-1377';
process.env.GOOGLE_APPLICATION_CREDENTIALS = __dirname + '/../google-keys.json';

// Instantiates a client
const translate = new Translate({projectId: projectId,});

const TRANSLATE_DELAY = 5000;

/**
 * Choose the right translation API
 * @param {string} text The text to translate
 * @param {string} targetLang The target language
 * @param {string} yandex api key
 * @returns {Promise}
 */
async function _translateText(text, targetLang, yandex, sourceLang) {
    if (yandex) {
        return await translateYandex(text, targetLang, yandex, sourceLang);
    } else {
        return await translateGoogle(text, targetLang, sourceLang);
    }
github thisandagain / washyourmouthoutwithsoap / bin / build.js View on Github external
const persist = require('../lib/persist');

const en = require('../data/_en.json');

// Global settings & storage
const CONCURRENCY_LIMIT = 4;
const LOCALES = ['sq','hy','eu','be','bg','ca','hr','cs','da','nl','en','et','fi','fr','gl','de','el','hi','hu','is','id','it','ja','kn','ko','la','lv','lt','mk','ms','ml','mt','mr','mn','my','fa','pl','pt','ro','ru','gd','sr','sk','sl','es','sv','te','th','tr','uk','uz','vi','cy','zu'];
const BASE_LOCALE = 'en';
const DELIMITER = ':';
const ERROR_CREDENTIALS = 'Invalid credentials';

// Validate CLI argument & create translation client
if (typeof argv._[0] === 'undefined') throw new Error(ERROR_CREDENTIALS);
if (argv._[0] === '') throw new Error(ERROR_CREDENTIALS);
process.env.GOOGLE_APPLICATION_CREDENTIALS = path.resolve(__dirname, argv._[0]);
const client = new Translate();

// Create processing queue
const q = async.queue(function (job, callback) {
    const key = job.locale + DELIMITER + job.word;

    // Check to see if locale + word exists in local storage database
    db.get(key, function (err, val) {
        if (typeof val !== 'undefined') return callback();
        if (typeof err.notFound === 'undefined') return callback(err);

        // Explicitly set source and destination languages
        const options = {
          from: BASE_LOCALE,
          to: job.locale
        };
github freeCodeCamp / freeCodeCamp / tools / translation / translate-guide-old.js View on Github external
const createTranslateText = target => text => {
  if (!text) {
    return '';
  }
  const translate = new Translate();

  return translate
    .translate(text, target)
    .then(results => {
      let translations = results[0];
      translations = Array.isArray(translations)
        ? translations
        : [translations];
      return translations;
    })
    .catch(err => {
      console.log(err);
    });
};
github freeCodeCamp / freeCodeCamp / curriculum / md-translation.js View on Github external
const createTranslateText = target => text => {
  if (!text) {
    return '';
  }
  const translate = new Translate();

  return translate
    .translate(text, target)
    .then(results => {
      let translations = results[0];
      translations = Array.isArray(translations)
        ? translations
        : [translations];
      return translations;
    })
    .catch(err => {
      console.log(err);
    });
};
github nullabork / talkbot / src / helpers / bot-stuff.js View on Github external
constructor(shard_number, total_shards) {

    if (!shard_number) shard_number = 0;
    if (!total_shards) total_shards = 1;

    Common.out('Setting up client for shard ID#' + shard_number + '. Total count of shards is ' + total_shards);

    this.auth = auth;
    this.bot = new Discord.Client();

    this.translate_client = new tl8.Translate({
      projectId: "talk-bork",
    });
  }

@google-cloud/translate

Cloud Translation API Client Library for Node.js

Apache-2.0
Latest version published 4 months ago

Package Health Score

91 / 100
Full package analysis