Поделиться через


DocumentModelAdministrationClient class

Клиент для взаимодействия с функциями управления моделями службы Распознавателя документов, такими как создание, чтение, перечисление, удаление и копирование моделей.

Примеры.

Azure Active Directory

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

Ключ API (ключ подписки)

import { AzureKeyCredential, DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new AzureKeyCredential("<API key>");
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

Конструкторы

DocumentModelAdministrationClient(string, KeyCredential, DocumentModelAdministrationClientOptions)

Создание экземпляра DocumentModelAdministrationClient из конечной точки ресурса и статического ключа API (KeyCredential),

Пример:

import { AzureKeyCredential, DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new AzureKeyCredential("<API key>");
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);
DocumentModelAdministrationClient(string, TokenCredential, DocumentModelAdministrationClientOptions)

Создайте экземпляр DocumentModelAdministrationClient из конечной точки ресурса и удостоверения TokenCredentialAzure.

Дополнительные сведения о проверке подлинности с помощью Azure Active Directory см. в пакете @azure/identity.

Пример:

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

Методы

beginBuildDocumentClassifier(string, DocumentClassifierDocumentTypeSources, BeginBuildDocumentClassifierOptions)

Создайте новый классификатор документов с заданным идентификатором классификатора и типами документов.

Идентификатор классификатора должен быть уникальным среди классификаторов в ресурсе.

Типы документов задаются в виде объекта, который сопоставляет имя типа документа с набором обучающих данных для этого типа документа. Поддерживаются два метода ввода обучающих данных:

  • azureBlobSource, который обучает классификатор с помощью данных в заданном контейнере хранилища BLOB-объектов Azure.
  • azureBlobFileListSource, который аналогичен azureBlobSource файлам, включенным в набор обучающих данных, но обеспечивает более детальный контроль над ними с помощью списка файлов в формате JSONL.

Служба Распознавателя документов считывает набор обучающих данных из контейнера службы хранилища Azure в виде URL-адреса контейнера с маркером SAS, который позволяет серверной части службы взаимодействовать с контейнером. Как минимум, требуются разрешения на чтение и составление списка. Кроме того, данные в данном контейнере должны быть организованы в соответствии с определенным соглашением, которое задокументировано в документации сервиса для построения пользовательских классификаторов документов.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const newClassifiedId = "aNewClassifier";
const containerUrl1 = "<training data container SAS URL 1>";
const containerUrl2 = "<training data container SAS URL 2>";

const poller = await client.beginBuildDocumentClassifier(
  newClassifiedId,
  {
    // The document types. Each entry in this object should map a document type name to a
    // `ClassifierDocumentTypeDetails` object
    formX: {
      azureBlobSource: {
        containerUrl: containerUrl1,
      },
    },
    formY: {
      azureBlobFileListSource: {
        containerUrl: containerUrl2,
        fileList: "path/to/fileList.jsonl",
      },
    },
  },
  {
    // Optionally, a text description may be attached to the classifier
    description: "This is an example classifier!",
  },
);

// Classifier building, like model creation operations, returns a poller that eventually produces a
// DocumentClassifierDetails object
const classifierDetails = await poller.pollUntilDone();

const {
  classifierId, // identical to the classifierId given when creating the classifier
  description, // identical to the description given when creating the classifier (if any)
  createdOn, // the Date (timestamp) that the classifier was created
  docTypes, // information about the document types in the classifier and their details
} = classifierDetails;
beginBuildDocumentModel(string, DocumentModelSource, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Создайте новую модель с заданным идентификатором из источника содержимого модели.

Идентификатор модели может состоять из любого текста, если он не начинается со слова "prebuilt-" (поскольку эти модели относятся к предварительно созданным моделям Распознавателя документов, которые являются общими для всех ресурсов) и если он еще не существует в ресурсе.

Источник содержимого описывает механизм, который служба будет использовать для чтения входных обучающих данных. Для получения дополнительной информации см. тип.<xref:DocumentModelContentSource>

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const containerSasUrl = "<SAS url to the blob container storing training documents>";

// You must provide the model ID. It can be any text that does not start with "prebuilt-".
// For example, you could provide a randomly generated GUID using the "uuid" package.
// The second parameter is the SAS-encoded URL to an Azure Storage container with the training documents.
// The third parameter is the build mode: one of "template" (the only mode prior to 4.0.0-beta.3) or "neural".
// See https://aka.ms/azsdk/formrecognizer/buildmode for more information about build modes.
const poller = await client.beginBuildDocumentModel(
  "<model ID>",
  { azureBlobSource: { containerUrl: containerSasUrl } },
  "template",
  {
    // The model description is optional and can be any text.
    description: "This is my new model!",
    onProgress: ({ status }) => {
      console.log(`operation status: ${status}`);
    },
  },
);
const model = await poller.pollUntilDone();

console.log(`Model ID: ${model.modelId}`);
console.log(`Description: ${model.description}`);
console.log(`Created: ${model.createdOn}`);

// A model may contain several document types, which describe the possible object structures of fields extracted using
// this model

console.log("Document Types:");
for (const [docType, { description, fieldSchema: schema }] of Object.entries(
  model.docTypes ?? {},
)) {
  console.log(`- Name: "${docType}"`);
  console.log(`  Description: "${description}"`);

  // For simplicity, this example will only show top-level field names
  console.log("  Fields:");

  for (const [fieldName, fieldSchema] of Object.entries(schema)) {
    console.log(`  - "${fieldName}" (${fieldSchema.type})`);
    console.log(`    ${fieldSchema.description ?? "<no description>"}`);
  }
}
beginBuildDocumentModel(string, string, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Постройте новую модель с заданным идентификатором из набора входных документов и помеченных полей.

Идентификатор модели может состоять из любого текста, если он не начинается со слова "prebuilt-" (поскольку эти модели относятся к предварительно созданным моделям Распознавателя документов, которые являются общими для всех ресурсов) и если он еще не существует в ресурсе.

Служба Распознавателя документов считывает набор обучающих данных из контейнера службы хранилища Azure в виде URL-адреса контейнера с маркером SAS, который позволяет серверной части службы взаимодействовать с контейнером. Как минимум, требуются разрешения на чтение и составление списка. Кроме того, данные в данном контейнере должны быть организованы в соответствии с определенным соглашением, которое задокументировано в документации сервиса для построения пользовательских моделей.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const containerSasUrl = "<SAS url to the blob container storing training documents>";

// You must provide the model ID. It can be any text that does not start with "prebuilt-".
// For example, you could provide a randomly generated GUID using the "uuid" package.
// The second parameter is the SAS-encoded URL to an Azure Storage container with the training documents.
// The third parameter is the build mode: one of "template" (the only mode prior to 4.0.0-beta.3) or "neural".
// See https://aka.ms/azsdk/formrecognizer/buildmode for more information about build modes.
const poller = await client.beginBuildDocumentModel("<model ID>", containerSasUrl, "template", {
  // The model description is optional and can be any text.
  description: "This is my new model!",
  onProgress: ({ status }) => {
    console.log(`operation status: ${status}`);
  },
});
const model = await poller.pollUntilDone();

console.log(`Model ID: ${model.modelId}`);
console.log(`Description: ${model.description}`);
console.log(`Created: ${model.createdOn}`);

// A model may contain several document types, which describe the possible object structures of fields extracted using
// this model

console.log("Document Types:");
for (const [docType, { description, fieldSchema: schema }] of Object.entries(
  model.docTypes ?? {},
)) {
  console.log(`- Name: "${docType}"`);
  console.log(`  Description: "${description}"`);

  // For simplicity, this example will only show top-level field names
  console.log("  Fields:");

  for (const [fieldName, fieldSchema] of Object.entries(schema)) {
    console.log(`  - "${fieldName}" (${fieldSchema.type})`);
    console.log(`    ${fieldSchema.description ?? "<no description>"}`);
  }
}
beginComposeDocumentModel(string, Iterable<string>, BeginComposeDocumentModelOptions)

Создает одну составную модель из нескольких существующих подмоделей.

Полученная скомпонованная модель объединяет типы документов моделей компонентов и вставляет шаг классификации в конвейер извлечения, чтобы определить, какая из ее подмоделей компонентов наиболее подходит для заданных входных данных.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const composeModelId = "aNewComposedModel";
const subModelIds = ["documentType1Model", "documentType2Model", "documentType3Model"];

// The resulting composed model can classify and extract data from documents
// conforming to any of the above document types
const poller = await client.beginComposeDocumentModel(composeModelId, subModelIds, {
  description: "This is a composed model that can handle several document types.",
});
// Model composition, like all other model creation operations, returns a poller that eventually produces a
// ModelDetails object
const modelDetails = await poller.pollUntilDone();

const {
  modelId, // identical to the modelId given when creating the model
  description, // identical to the description given when creating the model
  createdOn, // the Date (timestamp) that the model was created
  docTypes, // information about the document types of the composed submodels
} = modelDetails;
beginCopyModelTo(string, CopyAuthorization, BeginCopyModelOptions)

Копирует модель с заданным идентификатором в ресурс и идентификатор модели, закодированный заданным разрешением на копирование.

Смотрите CopyAuthorization и getCopyAuthorization.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// We create the copy authorization using a client authenticated with the destination resource. Note that these two
// resources can be the same (you can copy a model to a new ID in the same resource).
const copyAuthorization = await client.getCopyAuthorization("<destination model ID>");

// Finally, use the _source_ client to copy the model and await the copy operation
// We need a client for the source model's resource
const sourceEndpoint = "https://<source resource name>.cognitiveservices.azure.com";
const sourceCredential = new AzureKeyCredential("<source api key>");
const sourceClient = new DocumentModelAdministrationClient(sourceEndpoint, sourceCredential);
const poller = await sourceClient.beginCopyModelTo("<source model ID>", copyAuthorization);

// Model copying, like all other model creation operations, returns a poller that eventually produces a ModelDetails
// object
const modelDetails = await poller.pollUntilDone();

const {
  modelId, // identical to the modelId given when creating the copy authorization
  description, // identical to the description given when creating the copy authorization
  createdOn, // the Date (timestamp) that the model was created
  docTypes, // information about the document types of the model (identical to the original, source model)
} = modelDetails;
deleteDocumentClassifier(string, OperationOptions)

Удаляет классификатор с заданным идентификатором из ресурса клиента, если он существует. Эту операцию НЕЛЬЗЯ отменить.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

await client.deleteDocumentClassifier("<classifier ID to delete>");
deleteDocumentModel(string, DeleteDocumentModelOptions)

Удаляет модель с заданным идентификатором из ресурса клиента, если она существует. Эту операцию НЕЛЬЗЯ отменить.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

await client.deleteDocumentModel("<model ID to delete>");
getCopyAuthorization(string, GetCopyAuthorizationOptions)

Создает авторизацию для копирования модели в ресурс, используемый с методом beginCopyModelTo .

Это CopyAuthorization предоставляет другому ресурсу когнитивной службы право на создание модели в ресурсе этого клиента с идентификатором модели и необязательным описанием, которые закодированы в авторизации.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// The copyAuthorization data structure stored below grants any cognitive services resource the right to copy a
// model into the client's resource with the given destination model ID.
const copyAuthorization = await client.getCopyAuthorization("<destination model ID>");
getDocumentClassifier(string, OperationOptions)

Извлекает сведения о классификаторе (DocumentClassifierDetails) по идентификатору.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const foundClassifier = "<classifier ID>";

const {
  classifierId, // identical to the ID given when calling `getDocumentClassifier`
  description, // a textual description of the classifier, if provided during classifier creation
  createdOn, // the Date (timestamp) that the classifier was created
  // information about the document types in the classifier and their corresponding traning data
  docTypes,
} = await client.getDocumentClassifier(foundClassifier);

// The `docTypes` property is a map of document type names to information about the training data
// for that document type.
for (const [docTypeName, classifierDocTypeDetails] of Object.entries(docTypes)) {
  console.log(`- '${docTypeName}': `, classifierDocTypeDetails);
}
getDocumentModel(string, GetModelOptions)

Извлекает сведения о модели (DocumentModelDetails) по идентификатору.

Этот метод может получать информацию как о пользовательских, так и о предварительно собранных моделях.

Критическое изменение

В предыдущих версиях REST API и SDK Распознавателя документов метод getModel мог возвращать любую модель, даже ту, которую не удалось создать из-за ошибок. В новых сервисных версиях и listDocumentModels выпускают getDocumentModelтолько успешно созданные модели (т.е. модели, которые «готовы» к использованию). Неудачные модели теперь извлекаются через API "operations", см. getOperation и listOperations.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// The ID of the prebuilt business card model
const prebuiltModelId = "prebuilt-businessCard";

const {
  modelId, // identical to the modelId given when calling `getDocumentModel`
  description, // a textual description of the model, if provided during model creation
  createdOn, // the Date (timestamp) that the model was created
  // information about the document types in the model and their field schemas
  docTypes: {
    // the document type of the prebuilt business card model
    "prebuilt:businesscard": {
      // an optional, textual description of this document type
      description: businessCardDescription,
      // the schema of the fields in this document type, see the FieldSchema type
      fieldSchema,
      // the service's confidences in the fields (an object with field names as properties and numeric confidence
      // values)
      fieldConfidence,
    },
  },
} = await client.getDocumentModel(prebuiltModelId);
getOperation(string, GetOperationOptions)

Получает информацию об операции (OperationDetails) по ее идентификатору.

Операции представляют собой задачи, не связанные с анализом, такие как построение, компоновка или копирование модели.

getResourceDetails(GetResourceDetailsOptions)

Получение основной информации о ресурсе этого клиента.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const {
  // Information about the custom models in the current resource
  customDocumentModels: {
    // The number of custom models in the current resource
    count,
    // The maximum number of models that the current resource can support
    limit,
  },
} = await client.getResourceDetails();
listDocumentClassifiers(ListModelsOptions)

Перечислите подробную информацию о классификаторах в ресурсе. Эта операция поддерживает разбиение на страницы.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

for await (const details of client.listDocumentClassifiers()) {
  const {
    classifierId, // The classifier's unique ID
    description, // a textual description of the classifier, if provided during creation
    docTypes, // information about the document types in the classifier and their corresponding traning data
  } = details;
}

// The listDocumentClassifiers method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listDocumentClassifiers().byPage();

for await (const page of pages) {
  // Each page is an array of classifiers and can be iterated synchronously
  for (const details of page) {
    const {
      classifierId, // The classifier's unique ID
      description, // a textual description of the classifier, if provided during creation
      docTypes, // information about the document types in the classifier and their corresponding traning data
    } = details;
  }
}
listDocumentModels(ListModelsOptions)

Перечислите краткие описания моделей в ресурсе. Будут включены как индивидуальные, так и предварительно собранные модели. Эта операция поддерживает разбиение на страницы.

Сводка модели (DocumentModelSummary) содержит только основные сведения о модели и не включает сведения о типах документов в модели (например, схемы полей и значения достоверности).

Чтобы получить доступ к полной информации о модели, используйте getDocumentModel.

Критическое изменение

В предыдущих версиях REST API и SDK Распознавателя документов метод listModels возвращал все модели, даже те, которые не удалось создать из-за ошибок. В новых сервисных версиях и getDocumentModel выпускают listDocumentModelsтолько успешно созданные модели (т.е. модели, которые «готовы» к использованию). Неудачные модели теперь извлекаются через API "operations", см. getOperation и listOperations.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// Iterate over all models in the current resource
for await (const summary of client.listDocumentModels()) {
  const {
    modelId, // The model's unique ID
    description, // a textual description of the model, if provided during model creation
  } = summary;

  // You can get the full model info using `getDocumentModel`
  const model = await client.getDocumentModel(modelId);
}

// The listDocumentModels method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listDocumentModels().byPage();

for await (const page of pages) {
  // Each page is an array of models and can be iterated synchronously
  for (const summary of page) {
    const {
      modelId, // The model's unique ID
      description, // a textual description of the model, if provided during model creation
    } = summary;

    // You can get the full model info using `getDocumentModel`
    const model = await client.getDocumentModel(modelId);
  }
}
listOperations(ListOperationsOptions)

Перечислите операции создания модели в ресурсе. При этом будут выполнены все операции, включая операции, в которых не удалось успешно создать модели. Эта операция поддерживает разбиение на страницы.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

for await (const operation of client.listOperations()) {
  const {
    operationId, // the operation's GUID
    status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled"
    percentCompleted, // the progress of the operation, from 0 to 100
  } = operation;
}

// The listOperations method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listOperations().byPage();

for await (const page of pages) {
  // Each page is an array of operation info objects and can be iterated synchronously
  for (const operation of page) {
    const {
      operationId, // the operation's GUID
      status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled"
      percentCompleted, // the progress of the operation, from 0 to 100
    } = operation;
  }
}

Сведения о конструкторе

DocumentModelAdministrationClient(string, KeyCredential, DocumentModelAdministrationClientOptions)

Создание экземпляра DocumentModelAdministrationClient из конечной точки ресурса и статического ключа API (KeyCredential),

Пример:

import { AzureKeyCredential, DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new AzureKeyCredential("<API key>");
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);
new DocumentModelAdministrationClient(endpoint: string, credential: KeyCredential, options?: DocumentModelAdministrationClientOptions)

Параметры

endpoint

string

URL-адрес конечной точки экземпляра Azure Cognitive Services

credential
KeyCredential

KeyCredential, содержащий ключ подписки экземпляра Cognitive Services

options
DocumentModelAdministrationClientOptions

необязательные параметры для настройки всех методов в клиенте

DocumentModelAdministrationClient(string, TokenCredential, DocumentModelAdministrationClientOptions)

Создайте экземпляр DocumentModelAdministrationClient из конечной точки ресурса и удостоверения TokenCredentialAzure.

Дополнительные сведения о проверке подлинности с помощью Azure Active Directory см. в пакете @azure/identity.

Пример:

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);
new DocumentModelAdministrationClient(endpoint: string, credential: TokenCredential, options?: DocumentModelAdministrationClientOptions)

Параметры

endpoint

string

URL-адрес конечной точки экземпляра Azure Cognitive Services

credential
TokenCredential

экземпляр TokenCredential из пакета @azure/identity

options
DocumentModelAdministrationClientOptions

необязательные параметры для настройки всех методов в клиенте

Сведения о методе

beginBuildDocumentClassifier(string, DocumentClassifierDocumentTypeSources, BeginBuildDocumentClassifierOptions)

Создайте новый классификатор документов с заданным идентификатором классификатора и типами документов.

Идентификатор классификатора должен быть уникальным среди классификаторов в ресурсе.

Типы документов задаются в виде объекта, который сопоставляет имя типа документа с набором обучающих данных для этого типа документа. Поддерживаются два метода ввода обучающих данных:

  • azureBlobSource, который обучает классификатор с помощью данных в заданном контейнере хранилища BLOB-объектов Azure.
  • azureBlobFileListSource, который аналогичен azureBlobSource файлам, включенным в набор обучающих данных, но обеспечивает более детальный контроль над ними с помощью списка файлов в формате JSONL.

Служба Распознавателя документов считывает набор обучающих данных из контейнера службы хранилища Azure в виде URL-адреса контейнера с маркером SAS, который позволяет серверной части службы взаимодействовать с контейнером. Как минимум, требуются разрешения на чтение и составление списка. Кроме того, данные в данном контейнере должны быть организованы в соответствии с определенным соглашением, которое задокументировано в документации сервиса для построения пользовательских классификаторов документов.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const newClassifiedId = "aNewClassifier";
const containerUrl1 = "<training data container SAS URL 1>";
const containerUrl2 = "<training data container SAS URL 2>";

const poller = await client.beginBuildDocumentClassifier(
  newClassifiedId,
  {
    // The document types. Each entry in this object should map a document type name to a
    // `ClassifierDocumentTypeDetails` object
    formX: {
      azureBlobSource: {
        containerUrl: containerUrl1,
      },
    },
    formY: {
      azureBlobFileListSource: {
        containerUrl: containerUrl2,
        fileList: "path/to/fileList.jsonl",
      },
    },
  },
  {
    // Optionally, a text description may be attached to the classifier
    description: "This is an example classifier!",
  },
);

// Classifier building, like model creation operations, returns a poller that eventually produces a
// DocumentClassifierDetails object
const classifierDetails = await poller.pollUntilDone();

const {
  classifierId, // identical to the classifierId given when creating the classifier
  description, // identical to the description given when creating the classifier (if any)
  createdOn, // the Date (timestamp) that the classifier was created
  docTypes, // information about the document types in the classifier and their details
} = classifierDetails;
function beginBuildDocumentClassifier(classifierId: string, docTypeSources: DocumentClassifierDocumentTypeSources, options?: BeginBuildDocumentClassifierOptions): Promise<DocumentClassifierPoller>

Параметры

classifierId

string

уникальный идентификатор классификатора для создания

docTypeSources
DocumentClassifierDocumentTypeSources

типы документов, включаемые в классификатор, и их источники (карта названий типов документов до ClassifierDocumentTypeDetails)

options
BeginBuildDocumentClassifierOptions

Необязательные параметры для операции сборки классификатора

Возвращаемое значение

длительная операция (поллер), которая в конечном итоге приведет к получению сведений о созданном классификаторе или ошибке

beginBuildDocumentModel(string, DocumentModelSource, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Создайте новую модель с заданным идентификатором из источника содержимого модели.

Идентификатор модели может состоять из любого текста, если он не начинается со слова "prebuilt-" (поскольку эти модели относятся к предварительно созданным моделям Распознавателя документов, которые являются общими для всех ресурсов) и если он еще не существует в ресурсе.

Источник содержимого описывает механизм, который служба будет использовать для чтения входных обучающих данных. Для получения дополнительной информации см. тип.<xref:DocumentModelContentSource>

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const containerSasUrl = "<SAS url to the blob container storing training documents>";

// You must provide the model ID. It can be any text that does not start with "prebuilt-".
// For example, you could provide a randomly generated GUID using the "uuid" package.
// The second parameter is the SAS-encoded URL to an Azure Storage container with the training documents.
// The third parameter is the build mode: one of "template" (the only mode prior to 4.0.0-beta.3) or "neural".
// See https://aka.ms/azsdk/formrecognizer/buildmode for more information about build modes.
const poller = await client.beginBuildDocumentModel(
  "<model ID>",
  { azureBlobSource: { containerUrl: containerSasUrl } },
  "template",
  {
    // The model description is optional and can be any text.
    description: "This is my new model!",
    onProgress: ({ status }) => {
      console.log(`operation status: ${status}`);
    },
  },
);
const model = await poller.pollUntilDone();

console.log(`Model ID: ${model.modelId}`);
console.log(`Description: ${model.description}`);
console.log(`Created: ${model.createdOn}`);

// A model may contain several document types, which describe the possible object structures of fields extracted using
// this model

console.log("Document Types:");
for (const [docType, { description, fieldSchema: schema }] of Object.entries(
  model.docTypes ?? {},
)) {
  console.log(`- Name: "${docType}"`);
  console.log(`  Description: "${description}"`);

  // For simplicity, this example will only show top-level field names
  console.log("  Fields:");

  for (const [fieldName, fieldSchema] of Object.entries(schema)) {
    console.log(`  - "${fieldName}" (${fieldSchema.type})`);
    console.log(`    ${fieldSchema.description ?? "<no description>"}`);
  }
}
function beginBuildDocumentModel(modelId: string, contentSource: DocumentModelSource, buildMode: DocumentModelBuildMode, options?: BeginBuildDocumentModelOptions): Promise<DocumentModelPoller>

Параметры

modelId

string

уникальный идентификатор модели, которую необходимо создать

contentSource
DocumentModelSource

Источник содержимого, предоставляющий обучающие данные для этой модели

buildMode

DocumentModelBuildMode

режим, используемый при построении модели (см. DocumentModelBuildMode)

options
BeginBuildDocumentModelOptions

Необязательные параметры для операции сборки модели

Возвращаемое значение

длительная операция (поллер), которая в конечном итоге выдаст информацию о созданной модели или ошибку

beginBuildDocumentModel(string, string, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Постройте новую модель с заданным идентификатором из набора входных документов и помеченных полей.

Идентификатор модели может состоять из любого текста, если он не начинается со слова "prebuilt-" (поскольку эти модели относятся к предварительно созданным моделям Распознавателя документов, которые являются общими для всех ресурсов) и если он еще не существует в ресурсе.

Служба Распознавателя документов считывает набор обучающих данных из контейнера службы хранилища Azure в виде URL-адреса контейнера с маркером SAS, который позволяет серверной части службы взаимодействовать с контейнером. Как минимум, требуются разрешения на чтение и составление списка. Кроме того, данные в данном контейнере должны быть организованы в соответствии с определенным соглашением, которое задокументировано в документации сервиса для построения пользовательских моделей.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const containerSasUrl = "<SAS url to the blob container storing training documents>";

// You must provide the model ID. It can be any text that does not start with "prebuilt-".
// For example, you could provide a randomly generated GUID using the "uuid" package.
// The second parameter is the SAS-encoded URL to an Azure Storage container with the training documents.
// The third parameter is the build mode: one of "template" (the only mode prior to 4.0.0-beta.3) or "neural".
// See https://aka.ms/azsdk/formrecognizer/buildmode for more information about build modes.
const poller = await client.beginBuildDocumentModel("<model ID>", containerSasUrl, "template", {
  // The model description is optional and can be any text.
  description: "This is my new model!",
  onProgress: ({ status }) => {
    console.log(`operation status: ${status}`);
  },
});
const model = await poller.pollUntilDone();

console.log(`Model ID: ${model.modelId}`);
console.log(`Description: ${model.description}`);
console.log(`Created: ${model.createdOn}`);

// A model may contain several document types, which describe the possible object structures of fields extracted using
// this model

console.log("Document Types:");
for (const [docType, { description, fieldSchema: schema }] of Object.entries(
  model.docTypes ?? {},
)) {
  console.log(`- Name: "${docType}"`);
  console.log(`  Description: "${description}"`);

  // For simplicity, this example will only show top-level field names
  console.log("  Fields:");

  for (const [fieldName, fieldSchema] of Object.entries(schema)) {
    console.log(`  - "${fieldName}" (${fieldSchema.type})`);
    console.log(`    ${fieldSchema.description ?? "<no description>"}`);
  }
}
function beginBuildDocumentModel(modelId: string, containerUrl: string, buildMode: DocumentModelBuildMode, options?: BeginBuildDocumentModelOptions): Promise<DocumentModelPoller>

Параметры

modelId

string

уникальный идентификатор модели, которую необходимо создать

containerUrl

string

URL-адрес в кодировке SAS для контейнера службы хранилища Azure, содержащего набор обучающих данных

buildMode

DocumentModelBuildMode

режим, используемый при построении модели (см. DocumentModelBuildMode)

options
BeginBuildDocumentModelOptions

Необязательные параметры для операции сборки модели

Возвращаемое значение

длительная операция (поллер), которая в конечном итоге выдаст информацию о созданной модели или ошибку

beginComposeDocumentModel(string, Iterable<string>, BeginComposeDocumentModelOptions)

Создает одну составную модель из нескольких существующих подмоделей.

Полученная скомпонованная модель объединяет типы документов моделей компонентов и вставляет шаг классификации в конвейер извлечения, чтобы определить, какая из ее подмоделей компонентов наиболее подходит для заданных входных данных.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const composeModelId = "aNewComposedModel";
const subModelIds = ["documentType1Model", "documentType2Model", "documentType3Model"];

// The resulting composed model can classify and extract data from documents
// conforming to any of the above document types
const poller = await client.beginComposeDocumentModel(composeModelId, subModelIds, {
  description: "This is a composed model that can handle several document types.",
});
// Model composition, like all other model creation operations, returns a poller that eventually produces a
// ModelDetails object
const modelDetails = await poller.pollUntilDone();

const {
  modelId, // identical to the modelId given when creating the model
  description, // identical to the description given when creating the model
  createdOn, // the Date (timestamp) that the model was created
  docTypes, // information about the document types of the composed submodels
} = modelDetails;
function beginComposeDocumentModel(modelId: string, componentModelIds: Iterable<string>, options?: BeginComposeDocumentModelOptions): Promise<DocumentModelPoller>

Параметры

modelId

string

уникальный идентификатор модели, которую необходимо создать

componentModelIds

Iterable<string>

Итерируемый объект строк, представляющих уникальные идентификаторы моделей для составления

options
BeginComposeDocumentModelOptions

Необязательные настройки для создания модели

Возвращаемое значение

длительная операция (поллер), которая в конечном итоге выдаст информацию о созданной модели или ошибку

beginCopyModelTo(string, CopyAuthorization, BeginCopyModelOptions)

Копирует модель с заданным идентификатором в ресурс и идентификатор модели, закодированный заданным разрешением на копирование.

Смотрите CopyAuthorization и getCopyAuthorization.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// We create the copy authorization using a client authenticated with the destination resource. Note that these two
// resources can be the same (you can copy a model to a new ID in the same resource).
const copyAuthorization = await client.getCopyAuthorization("<destination model ID>");

// Finally, use the _source_ client to copy the model and await the copy operation
// We need a client for the source model's resource
const sourceEndpoint = "https://<source resource name>.cognitiveservices.azure.com";
const sourceCredential = new AzureKeyCredential("<source api key>");
const sourceClient = new DocumentModelAdministrationClient(sourceEndpoint, sourceCredential);
const poller = await sourceClient.beginCopyModelTo("<source model ID>", copyAuthorization);

// Model copying, like all other model creation operations, returns a poller that eventually produces a ModelDetails
// object
const modelDetails = await poller.pollUntilDone();

const {
  modelId, // identical to the modelId given when creating the copy authorization
  description, // identical to the description given when creating the copy authorization
  createdOn, // the Date (timestamp) that the model was created
  docTypes, // information about the document types of the model (identical to the original, source model)
} = modelDetails;
function beginCopyModelTo(sourceModelId: string, authorization: CopyAuthorization, options?: BeginCopyModelOptions): Promise<DocumentModelPoller>

Параметры

sourceModelId

string

уникальный идентификатор исходной модели, которая будет скопирована

authorization
CopyAuthorization

авторизация на копирование модели, созданная с помощью метода getCopyAuthorization

options
BeginCopyModelOptions

Необязательные настройки для

Возвращаемое значение

длительная операция (поллер), которая в конечном итоге приведет к получению скопированной информации о модели или ошибке

deleteDocumentClassifier(string, OperationOptions)

Удаляет классификатор с заданным идентификатором из ресурса клиента, если он существует. Эту операцию НЕЛЬЗЯ отменить.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

await client.deleteDocumentClassifier("<classifier ID to delete>");
function deleteDocumentClassifier(classifierId: string, options?: OperationOptions): Promise<void>

Параметры

classifierId

string

уникальный идентификатор классификатора, который нужно удалить из ресурса

options
OperationOptions

Необязательные настройки для запроса

Возвращаемое значение

Promise<void>

deleteDocumentModel(string, DeleteDocumentModelOptions)

Удаляет модель с заданным идентификатором из ресурса клиента, если она существует. Эту операцию НЕЛЬЗЯ отменить.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

await client.deleteDocumentModel("<model ID to delete>");
function deleteDocumentModel(modelId: string, options?: DeleteDocumentModelOptions): Promise<void>

Параметры

modelId

string

уникальный идентификатор модели, которую нужно удалить из ресурса

options
DeleteDocumentModelOptions

Необязательные настройки для запроса

Возвращаемое значение

Promise<void>

getCopyAuthorization(string, GetCopyAuthorizationOptions)

Создает авторизацию для копирования модели в ресурс, используемый с методом beginCopyModelTo .

Это CopyAuthorization предоставляет другому ресурсу когнитивной службы право на создание модели в ресурсе этого клиента с идентификатором модели и необязательным описанием, которые закодированы в авторизации.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// The copyAuthorization data structure stored below grants any cognitive services resource the right to copy a
// model into the client's resource with the given destination model ID.
const copyAuthorization = await client.getCopyAuthorization("<destination model ID>");
function getCopyAuthorization(destinationModelId: string, options?: GetCopyAuthorizationOptions): Promise<CopyAuthorization>

Параметры

destinationModelId

string

уникальный идентификатор целевой модели (идентификатор, в который будет скопирована модель)

options
GetCopyAuthorizationOptions

Необязательные настройки для создания авторизации копирования

Возвращаемое значение

разрешение на копирование, которое кодирует заданный modelId и необязательное описание

getDocumentClassifier(string, OperationOptions)

Извлекает сведения о классификаторе (DocumentClassifierDetails) по идентификатору.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const foundClassifier = "<classifier ID>";

const {
  classifierId, // identical to the ID given when calling `getDocumentClassifier`
  description, // a textual description of the classifier, if provided during classifier creation
  createdOn, // the Date (timestamp) that the classifier was created
  // information about the document types in the classifier and their corresponding traning data
  docTypes,
} = await client.getDocumentClassifier(foundClassifier);

// The `docTypes` property is a map of document type names to information about the training data
// for that document type.
for (const [docTypeName, classifierDocTypeDetails] of Object.entries(docTypes)) {
  console.log(`- '${docTypeName}': `, classifierDocTypeDetails);
}
function getDocumentClassifier(classifierId: string, options?: OperationOptions): Promise<DocumentClassifierDetails>

Параметры

classifierId

string

уникальный идентификатор классификатора для запроса

options
OperationOptions

Необязательные настройки для запроса

Возвращаемое значение

информация о классификаторе с заданным идентификатором

getDocumentModel(string, GetModelOptions)

Извлекает сведения о модели (DocumentModelDetails) по идентификатору.

Этот метод может получать информацию как о пользовательских, так и о предварительно собранных моделях.

Критическое изменение

В предыдущих версиях REST API и SDK Распознавателя документов метод getModel мог возвращать любую модель, даже ту, которую не удалось создать из-за ошибок. В новых сервисных версиях и listDocumentModels выпускают getDocumentModelтолько успешно созданные модели (т.е. модели, которые «готовы» к использованию). Неудачные модели теперь извлекаются через API "operations", см. getOperation и listOperations.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// The ID of the prebuilt business card model
const prebuiltModelId = "prebuilt-businessCard";

const {
  modelId, // identical to the modelId given when calling `getDocumentModel`
  description, // a textual description of the model, if provided during model creation
  createdOn, // the Date (timestamp) that the model was created
  // information about the document types in the model and their field schemas
  docTypes: {
    // the document type of the prebuilt business card model
    "prebuilt:businesscard": {
      // an optional, textual description of this document type
      description: businessCardDescription,
      // the schema of the fields in this document type, see the FieldSchema type
      fieldSchema,
      // the service's confidences in the fields (an object with field names as properties and numeric confidence
      // values)
      fieldConfidence,
    },
  },
} = await client.getDocumentModel(prebuiltModelId);
function getDocumentModel(modelId: string, options?: GetModelOptions): Promise<DocumentModelDetails>

Параметры

modelId

string

уникальный идентификатор модели для запроса

options
GetModelOptions

Необязательные настройки для запроса

Возвращаемое значение

информация о модели с заданным идентификатором

getOperation(string, GetOperationOptions)

Получает информацию об операции (OperationDetails) по ее идентификатору.

Операции представляют собой задачи, не связанные с анализом, такие как построение, компоновка или копирование модели.

function getOperation(operationId: string, options?: GetOperationOptions): Promise<OperationDetails>

Параметры

operationId

string

идентификатор операции для запроса

options
GetOperationOptions

Необязательные настройки для запроса

Возвращаемое значение

Promise<OperationDetails>

информация об операции с заданным идентификатором

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// The ID of the operation, which should be a GUID
const findOperationId = "<operation GUID>";

const {
  operationId, // identical to the operationId given when calling `getOperation`
  kind, // the operation kind, one of "documentModelBuild", "documentModelCompose", or "documentModelCopyTo"
  status, // the status of the operation, one of "notStarted", "running", "failed", "succeeded", or "canceled"
  percentCompleted, // a number between 0 and 100 representing the progress of the operation
  createdOn, // a Date object that reflects the time when the operation was started
  lastUpdatedOn, // a Date object that reflects the time when the operation state was last modified
} = await client.getOperation(findOperationId);

getResourceDetails(GetResourceDetailsOptions)

Получение основной информации о ресурсе этого клиента.

Пример

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const {
  // Information about the custom models in the current resource
  customDocumentModels: {
    // The number of custom models in the current resource
    count,
    // The maximum number of models that the current resource can support
    limit,
  },
} = await client.getResourceDetails();
function getResourceDetails(options?: GetResourceDetailsOptions): Promise<ResourceDetails>

Параметры

options
GetResourceDetailsOptions

Необязательные настройки для запроса

Возвращаемое значение

Promise<ResourceDetails>

основная информация о ресурсе данного клиента

listDocumentClassifiers(ListModelsOptions)

Перечислите подробную информацию о классификаторах в ресурсе. Эта операция поддерживает разбиение на страницы.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

for await (const details of client.listDocumentClassifiers()) {
  const {
    classifierId, // The classifier's unique ID
    description, // a textual description of the classifier, if provided during creation
    docTypes, // information about the document types in the classifier and their corresponding traning data
  } = details;
}

// The listDocumentClassifiers method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listDocumentClassifiers().byPage();

for await (const page of pages) {
  // Each page is an array of classifiers and can be iterated synchronously
  for (const details of page) {
    const {
      classifierId, // The classifier's unique ID
      description, // a textual description of the classifier, if provided during creation
      docTypes, // information about the document types in the classifier and their corresponding traning data
    } = details;
  }
}
function listDocumentClassifiers(options?: ListModelsOptions): PagedAsyncIterableIterator<DocumentClassifierDetails, DocumentClassifierDetails[], PageSettings>

Параметры

options
ListModelsOptions

Необязательные настройки запросов классификатора

Возвращаемое значение

асинхронная итерируемая информация о классификаторе с поддержкой разбиения на страницы

listDocumentModels(ListModelsOptions)

Перечислите краткие описания моделей в ресурсе. Будут включены как индивидуальные, так и предварительно собранные модели. Эта операция поддерживает разбиение на страницы.

Сводка модели (DocumentModelSummary) содержит только основные сведения о модели и не включает сведения о типах документов в модели (например, схемы полей и значения достоверности).

Чтобы получить доступ к полной информации о модели, используйте getDocumentModel.

Критическое изменение

В предыдущих версиях REST API и SDK Распознавателя документов метод listModels возвращал все модели, даже те, которые не удалось создать из-за ошибок. В новых сервисных версиях и getDocumentModel выпускают listDocumentModelsтолько успешно созданные модели (т.е. модели, которые «готовы» к использованию). Неудачные модели теперь извлекаются через API "operations", см. getOperation и listOperations.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

// Iterate over all models in the current resource
for await (const summary of client.listDocumentModels()) {
  const {
    modelId, // The model's unique ID
    description, // a textual description of the model, if provided during model creation
  } = summary;

  // You can get the full model info using `getDocumentModel`
  const model = await client.getDocumentModel(modelId);
}

// The listDocumentModels method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listDocumentModels().byPage();

for await (const page of pages) {
  // Each page is an array of models and can be iterated synchronously
  for (const summary of page) {
    const {
      modelId, // The model's unique ID
      description, // a textual description of the model, if provided during model creation
    } = summary;

    // You can get the full model info using `getDocumentModel`
    const model = await client.getDocumentModel(modelId);
  }
}
function listDocumentModels(options?: ListModelsOptions): PagedAsyncIterableIterator<DocumentModelSummary, DocumentModelSummary[], PageSettings>

Параметры

options
ListModelsOptions

Необязательные настройки для запросов модели

Возвращаемое значение

Асинхронный итерируемый объект сводок моделей с поддержкой разбиения на страницы

listOperations(ListOperationsOptions)

Перечислите операции создания модели в ресурсе. При этом будут выполнены все операции, включая операции, в которых не удалось успешно создать модели. Эта операция поддерживает разбиение на страницы.

Примеры

Асинхронная итерация

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

for await (const operation of client.listOperations()) {
  const {
    operationId, // the operation's GUID
    status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled"
    percentCompleted, // the progress of the operation, from 0 to 100
  } = operation;
}

// The listOperations method is paged, and you can iterate by page using the `byPage` method.
const pages = client.listOperations().byPage();

for await (const page of pages) {
  // Each page is an array of operation info objects and can be iterated synchronously
  for (const operation of page) {
    const {
      operationId, // the operation's GUID
      status, // the operation status, one of "notStarted", "running", "succeeded", "failed", or "canceled"
      percentCompleted, // the progress of the operation, from 0 to 100
    } = operation;
  }
}
function listOperations(options?: ListOperationsOptions): PagedAsyncIterableIterator<OperationSummary, OperationSummary[], PageSettings>

Параметры

options
ListOperationsOptions

Необязательные настройки для запросов на операции

Возвращаемое значение

Асинхронная итерируемость объектов оперативной информации, поддерживающая подкачку