Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Como gerar relatórios de uso com rótulos (Advanced)
A API Cloud Translation é compatível com a adição de rótulos definidos pelo usuário (pares de chave-valor) às solicitações TranslateText, BatchTranslateText e DetectLanguage.
As informações sobre o uso de uma solicitação são encaminhadas ao sistema de faturamento. Nele, é possível filtrar as cobranças por rótulo.
Caso de uso
Com relação aos rótulos, um caso de uso importante é quando empresas fornecem serviços de tradução a vários clientes. É possível usar um único projeto para vários clientes. Para fins de faturamento, é essencial associar solicitações específicas aos respectivos clientes. É aí que os rótulos são usados. Ao fazer uma chamada em nome de
um cliente, você inclui um rótulo específico dele na solicitação. Esses rótulos estão
disponíveis para filtragem na seção Relatórios
do Google Cloud.
Requisitos dos rótulos
Os rótulos aplicados a uma solicitação precisam atender aos requisitos a seguir:
Cada solicitação pode ter vários rótulos. O número máximo é de 64.
Cada rótulo precisa ser um par de chave-valor.
As chaves têm comprimento mínimo de 1 e máximo de 63 caracteres. Além disso, elas não podem estar vazias. Os valores podem estar vazios e ter um comprimento máximo de 63 caracteres.
As chaves e os valores contêm apenas letras minúsculas, caracteres numéricos, sublinhados e traços. Todos os caracteres precisam usar a codificação UTF-8. Caracteres internacionais são permitidos.
A parte da chave de um rótulo precisa ser única em uma solicitação. Por exemplo, {'country':'india'} é apropriado, mas {'country':'india','country':'sweden'} não é permitido.
As chaves precisam começar com uma letra minúscula ou um caractere internacional.
Rótulos e faturamento
No Cloud Translation, é possível usar rótulos para organizar as taxas
por conta de faturamento. Você não será cobrado pelo uso de rótulos
do Cloud Translation.
As taxas são associadas à conta de faturamento do projeto que inclui a
solicitação. Ou, se um modelo personalizado ou de tradução automática neural (NMT) for usado, as taxas
serão associadas ao projeto que contém o
modelo.
Para fins de cobrança, todas as solicitações faturáveis podem ter rótulos próprios. Elas incluem tradução em lote, detecção de idiomas e tradução de textos.
Como criar e gerenciar rótulos por meio da API Cloud Translation
Use a API Cloud Translation para adicionar rótulos a uma solicitação.
REST
No exemplo a seguir, os rótulos {'country':'russia'} e {'env':'test'} são adicionados à solicitação translateText.
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
PROJECT_NUMBER_OR_ID: o ID numérico ou alfanumérico do projeto do Google Cloud
Método HTTP e URL:
POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID:translateText
Acesse o console de faturamento do
Google Cloud, na visualização Relatórios, para usar esses rótulos como filtros de uso de
solicitações.
No painel, clique no ícone de hambúrguer no canto superior à esquerda e selecione “Faturamento”
no menu suspenso. Se tiver várias contas de faturamento, será exibida uma página que solicitará a você a escolha de uma opção. Clique em "Ir para a conta de faturamento vinculada".
Na página "Faturamento", selecione Relatórios no painel de navegação à esquerda.
Utilize os filtros no painel de navegação à direita para verificar o uso das solicitações.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2024-12-05 UTC."],[],[],null,["# Reporting usage with labels (Advanced)\n======================================\n\nThe Cloud Translation API supports adding user-defined labels (key-value pairs)\nto `TranslateText`, `BatchTranslateText` and `DetectLanguage` requests.\nInformation about a request's usage is forwarded to the billing system where\nyou can break down your billing charges by filtering by label.\n\nUse case\n--------\n\nAn important use case for labels involves customers who provide translation\nservices to many clients. A single project can be used for multiple clients. For\nbilling purposes it's important to associate specific requests with their\nrespective clients. That's where labels come in. When making a call on behalf of\na client, you label the request with a client specific label. These labels are\nthen available for filtering purposes in the **Reports** section of\nthe Google Cloud.\n\nRequirements for labels\n-----------------------\n\nThe labels applied to a request must meet the following requirements:\n\n- Each request can have multiple labels, up to a maximum of 64.\n- Each label must be a key-value pair.\n- Keys have a minimum length of 1 character and a maximum length of 63 characters, and cannot be empty. Values can be empty, and have a maximum length of 63 characters.\n- Keys and values contain only lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 encoding, and international characters are allowed.\n- The key portion of a label must be unique within a single request (for example, `{'country':'india'}` is fine, but `{'country':'india','country':'sweden'}` is not allowed).\n- Keys must start with a lowercase letter or international character.\n\nLabels and billing\n------------------\n\nIn Cloud Translation, you can use labels to organize [fees](/translate/pricing)\nby billing account. You aren't changed for the use of Cloud Translation\nlabels.\n\nFees are associated with the billing account of the project that contains the\nrequest. Or, if a custom or Neural Machine Translation (NMT) model is used, fees\nare associated with the [project that contains the\nmodel](/translate/pricing#charged-projects).\n\nFor billing purposes, all billable requests can have labels of their own. These\nbillable requests include batch translation, detect language, and translate\ntext.\n\nCreating and managing labels using the Cloud Translation API\n------------------------------------------------------------\n\nUse the Cloud Translation API to add labels to a request.\n\n\n### REST\n\nIn the following example, the labels `{'country':'russia'}`,`{'env':'test'}` are added to the `translateText` request.\n\n\nBefore using any of the request data,\nmake the following replacements:\n\n- \u003cvar translate=\"no\"\u003ePROJECT_NUMBER_OR_ID\u003c/var\u003e: the numeric or alphanumeric ID of your Google Cloud project\n\n\nHTTP method and URL:\n\n```\nPOST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID:translateText\n```\n\n\nRequest JSON body:\n\n```\n{\n source_language_code: 'en',\n target_language_code: 'ru',\n contents: 'Dr. Watson, come here!',\n labels: {'country':'russia','env':'test'}\n}\n\n```\n\nTo send your request, expand one of these options:\n\n#### curl (Linux, macOS, or Cloud Shell)\n\n| **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) , or by using [Cloud Shell](/shell/docs), which automatically logs you into the `gcloud` CLI . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\nSave the request body in a file named `request.json`,\nand execute the following command:\n\n```\ncurl -X POST \\\n -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"x-goog-user-project: PROJECT_NUMBER_OR_ID\" \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n -d @request.json \\\n \"https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID:translateText\"\n```\n\n#### PowerShell (Windows)\n\n| **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\nSave the request body in a file named `request.json`,\nand execute the following command:\n\n```\n$cred = gcloud auth print-access-token\n$headers = @{ \"Authorization\" = \"Bearer $cred\"; \"x-goog-user-project\" = \"PROJECT_NUMBER_OR_ID\" }\n\nInvoke-WebRequest `\n -Method POST `\n -Headers $headers `\n -ContentType: \"application/json; charset=utf-8\" `\n -InFile request.json `\n -Uri \"https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID:translateText\" | Select-Object -Expand Content\n```\n\nYou should receive a JSON response similar to the following:\n\n```\n{\n \"translations\": [\n {\n \"translatedText\": \"Доктор Ватсон, иди сюда!\"\n }\n ]\n}\n```\n\n\u003cbr /\u003e\n\nPricing report\n--------------\n\nGo to the [Google Cloud](https://console.cloud.google.com/billing)\nbilling console **Reports** view to use these labels as filters for request\nusage.\n\n1. From the dashboard, click the hamburger icon on the upper left-hand side and select \"Billing\" from the drop-down. If you have multiple billing accounts a page appears that asks you to make a selection. Click \"Go to linked billing account.\"\n2. From the Billing page, select **Reports** in the left-hand nav.\n3. Use the filters in the right-hand nav to check usage of requests."]]