Bibliotecas de cliente do Natural Language

Nesta página, apresentamos os primeiros passos para usar as bibliotecas de cliente do Cloud para a API Cloud Natural Language. Saiba mais sobre as bibliotecas de cliente das APIs Cloud, incluindo as bibliotecas de cliente mais antigas das APIs do Google, em Explicações sobre bibliotecas de cliente.

Como instalar a biblioteca de cliente

C#

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em C#.

Se você estiver usando o Visual Studio 2017 ou uma versão posterior, abra a janela do gerenciador de pacotes nuget e digite o seguinte:

Install-Package Google.Apis

Se você estiver usando as ferramentas da interface de linha de comando do .NET Core para instalar as dependências, execute o seguinte comando:

dotnet add package Google.Apis

Go

Para mais informações, consulte Como configurar um ambiente de desenvolvimento do Go.

go get cloud.google.com/go/language/apiv1

Java

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Java.

Se você estiver usando o Maven, adicione o código abaixo ao arquivo pom.xml. Para mais informações sobre BOMs, consulte BOM das bibliotecas do Google Cloud Platform.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.34.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-language</artifactId>
  </dependency>

Se você estiver usando o Gradle, adicione isto às dependências:

implementation 'com.google.cloud:google-cloud-language:2.42.0'

Se você estiver usando o sbt, adicione o seguinte às suas dependências:

libraryDependencies += "com.google.cloud" % "google-cloud-language" % "2.42.0"

Se você estiver usando o Visual Studio Code, o IntelliJ ou o Eclipse, poderá adicionar bibliotecas de cliente ao projeto usando estes plug-ins de IDE:

Os plug-ins também oferecem outras funcionalidades, como gerenciamento de chaves de contas de serviço. Consulte a documentação de cada plug-in para mais detalhes.

Node.js

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Node.js.

npm install --save @google-cloud/language

PHP

Para mais informações, consulte Como usar o PHP no Google Cloud.

composer require google/apiclient

Python

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Python.

pip install --upgrade google-cloud-language

Ruby

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Ruby.

gem install google-api-client

Como configurar a autenticação

Para executar a biblioteca de cliente, você precisa primeiro configurar a autenticação. Para isso, crie uma conta de serviço e defina uma variável de ambiente. Conclua os passos a seguir para configurar a autenticação. Para outras formas de autenticação, consulte a documentação de autenticação do GCP.

Forneça credenciais de autenticação ao código do aplicativo definindo a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS. Essa variável se aplica somente à sessão de shell atual. Se você quiser que a variável seja aplicada em sessões de shell futuras, defina a variável no arquivo de inicialização de shell, por exemplo, no arquivo ~/.bashrc ou ~/.profile.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Exemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Exemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para prompt de comando:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Como usar a biblioteca de cliente

O exemplo a seguir mostra como usar a biblioteca de cliente.

Go


// Sample language-quickstart uses the Google Cloud Natural API to analyze the
// sentiment of "Hello, world!".
package main

import (
	"context"
	"fmt"
	"log"

	language "cloud.google.com/go/language/apiv1"
	languagepb "google.golang.org/genproto/googleapis/cloud/language/v1"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := language.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the text to analyze.
	text := "Hello, world!"

	// Detects the sentiment of the text.
	sentiment, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})
	if err != nil {
		log.Fatalf("Failed to analyze text: %v", err)
	}

	fmt.Printf("Text: %v\n", text)
	if sentiment.DocumentSentiment.Score >= 0 {
		fmt.Println("Sentiment: positive")
	} else {
		fmt.Println("Sentiment: negative")
	}
}

Java

// Imports the Google Cloud client library
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (LanguageServiceClient language = LanguageServiceClient.create()) {

      // The text to analyze
      String text = "Hello, world!";
      Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();

      // Detects the sentiment of the text
      Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

      System.out.printf("Text: %s%n", text);
      System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());
    }
  }
}

Node.js

async function quickstart() {
  // Imports the Google Cloud client library
  const language = require('@google-cloud/language');

  // Instantiates a client
  const client = new language.LanguageServiceClient();

  // The text to analyze
  const text = 'Hello, world!';

  const document = {
    content: text,
    type: 'PLAIN_TEXT',
  };

  // Detects the sentiment of the text
  const [result] = await client.analyzeSentiment({document: document});
  const sentiment = result.documentSentiment;

  console.log(`Text: ${text}`);
  console.log(`Sentiment score: ${sentiment.score}`);
  console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}

Python

# Imports the Google Cloud client library
from google.cloud import language_v1

# Instantiates a client
client = language_v1.LanguageServiceClient()

# The text to analyze
text = u"Hello, world!"
document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)

# Detects the sentiment of the text
sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment

print("Text: {}".format(text))
print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude))

Outros recursos