How to use @google-cloud/translate - 10 common examples

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 / v3beta1 / translate_list_codes_beta.js View on Github external
function main(projectId = 'YOUR_PROJECT_ID', location = 'global') {
  // [START translate_list_codes_beta]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

  // Instantiates a client
  const translationClient = new TranslationServiceClient();

  async function listLanguages() {
    // Construct request
    const request = {
      parent: translationClient.locationPath(projectId, location),
    };

    // Run request
    const [response] = await translationClient.getSupportedLanguages(request);

    console.log(`Supported languages:`);
    for (const language of response.languages) {
      console.log(`Language Code: ${language.languageCode}`);
    }
  }
github googleapis / nodejs-translate / samples / v3 / translate_translate_text.js View on Github external
location = 'global',
  text = 'text to translate'
) {
  // [START translate_v3_translate_text]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';
  // const text = 'text to translate';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();
  async function translateText() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
      contents: [text],
      mimeType: 'text/plain', // mime types: text/plain, text/html
      sourceLanguageCode: 'en',
      targetLanguageCode: 'sr-Latn',
    };

    try {
      // Run request
      const [response] = await translationClient.translateText(request);

      for (const translation of response.translations) {
        console.log(`Translation: ${translation.translatedText}`);
github googleapis / nodejs-translate / samples / v3beta1 / translate_translate_text_beta.js View on Github external
location = 'global',
  text = 'text to translate'
) {
  // [START translate_translate_text_beta]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';
  // const text = 'text to translate';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

  // Instantiates a client
  const translationClient = new TranslationServiceClient();
  async function translateText() {
    // Construct request
    const request = {
      parent: translationClient.locationPath(projectId, location),
      contents: [text],
      mimeType: 'text/plain', // mime types: text/plain, text/html
      sourceLanguageCode: 'en-US',
      targetLanguageCode: 'sr-Latn',
    };

    // Run request
    const [response] = await translationClient.translateText(request);

    for (const translation of response.translations) {
      console.log(`Translation: ${translation.translatedText}`);
    }
github googleapis / nodejs-translate / samples / v3 / translate_delete_glossary.js View on Github external
location = 'us-central1',
  glossaryId = 'glossary-id'
) {
  // [START translate_v3_delete_glossary]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';
  // const glossaryId = 'YOUR_GLOSSARY_ID';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();

  async function deleteGlossary() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
      name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
    };

    try {
      // Delete glossary using a long-running operation
      const [operation] = await translationClient.deleteGlossary(request);

      // Wait for operation to complete.
      const [response] = await operation.promise();

      console.log(`Deleted glossary: ${response.name}`);
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 GoogleCloudPlatform / node-red-contrib-google-cloud / translate.js View on Github external
};
            try {
                const responseArray = await translationServiceClient.translateText(request);
                msg.payload = responseArray[0];
                node.send(msg);
            }
            catch(e) {
                console.log(e);
            }
        } // Input


        // We must have EITHER credentials or a keyFilename.  If neither are supplied, that
        // is an error.  If both are supplied, then credentials will be used.
        if (credentials) {
            translationServiceClient = new translate.v3beta1.TranslationServiceClient({
                "credentials": credentials
            });
        } else if (keyFilename) {
            translationServiceClient = new translate.v3beta1.TranslationServiceClient({
                "keyFilename": keyFilename
            });
        } else {
            translationServiceClient = new translate.v3beta1.TranslationServiceClient({});
        }

        node.on("input", Input);
    } // TranslateNode
github googleapis / nodejs-translate / samples / v3beta1 / translate_detect_language_beta.js View on Github external
function main(
  projectId = 'YOUR_PROJECT_ID',
  location = 'global',
  text = 'text to translate'
) {
  // [START translate_detect_language_beta]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

  // Instantiates a client
  const translationClient = new TranslationServiceClient();

  async function detectLanguage() {
    // Construct request
    const request = {
      parent: translationClient.locationPath(projectId, location),
      content: text,
    };

    // Run request
    const [response] = await translationClient.detectLanguage(request);

    console.log(`Detected Languages:`);
    for (const language of response.languages) {

@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