DocumentModelAdministrationClient class

Un cliente para interactuar con las características de administración de modelos del servicio Form Recognizer, como crear, leer, enumerar, eliminar y copiar modelos.

Ejemplos:

Azure Active Directory

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

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

const client = new DocumentModelAdministrationClient(endpoint, credential);

Clave de API (clave de suscripción)

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

const endpoint = "https://<resource name>.cognitiveservices.azure.com";
const credential = new AzureKeyCredential("<api key>");

const client = new DocumentModelAdministrationClient(endpoint, credential);

Constructores

DocumentModelAdministrationClient(string, KeyCredential, DocumentModelAdministrationClientOptions)

Creación de una instancia documentModelAdministrationClient desde un punto de conexión de recurso y una clave de API estática (KeyCredential),

Ejemplo:

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

const endpoint = "https://<resource name>.cognitiveservices.azure.com";
const credential = new AzureKeyCredential("<api key>");

const client = new DocumentModelAdministrationClient(endpoint, credential);
DocumentModelAdministrationClient(string, TokenCredential, DocumentModelAdministrationClientOptions)

Cree una instancia documentModelAdministrationClient desde un punto de conexión de recurso y una identidad de TokenCredentialAzure.

Consulte el @azure/identity paquete para más información sobre la autenticación con Azure Active Directory.

Ejemplo:

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

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

const client = new DocumentModelAdministrationClient(endpoint, credential);

Métodos

beginBuildDocumentClassifier(string, DocumentClassifierDocumentTypeSources, BeginBuildDocumentClassifierOptions)

Cree un nuevo clasificador de documentos con el identificador de clasificador y los tipos de documento especificados.

El identificador del clasificador debe ser único entre clasificadores dentro del recurso.

Los tipos de documento se proporcionan como un objeto que asigna el nombre del tipo de documento al conjunto de datos de entrenamiento para ese tipo de documento. Se admiten dos métodos de entrada de datos de entrenamiento:

  • azureBlobSource, que entrena un clasificador mediante los datos del contenedor de Azure Blob Storage especificado.
  • azureBlobFileListSource, que es similar a azureBlobSource pero permite un control más específico sobre los archivos que se incluyen en el conjunto de datos de entrenamiento mediante una lista de archivos con formato JSONL.

El servicio Form Recognizer lee el conjunto de datos de entrenamiento de un contenedor de Azure Storage, dado como una dirección URL al contenedor con un token de SAS que permite al back-end del servicio comunicarse con el contenedor. Como mínimo, se requieren los permisos de "lectura" y "lista". Además, los datos del contenedor especificado deben organizarse según una convención determinada, que se documenta en la documentación del servicio para crear clasificadores de documentos personalizados.

Ejemplo

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

const poller = await client.beginBuildDocumentClassifier(
  classifierId,
  {
    // 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)

Cree un nuevo modelo con un identificador determinado a partir de un origen de contenido del modelo.

El id. de modelo puede constar de cualquier texto, siempre y cuando no comience por "precompilado" (ya que estos modelos hacen referencia a modelos creados previamente Form Recognizer que son comunes a todos los recursos) y, siempre y cuando aún no exista dentro del recurso.

El origen de contenido describe el mecanismo que usará el servicio para leer los datos de entrenamiento de entrada. Consulte el <xref:DocumentModelContentSource> tipo para obtener más información.

Ejemplo

const modelId = "aNewModel";

const poller = await client.beginBuildDocumentModel(modelId, { containerUrl: "<SAS-encoded blob container URL>" }, {
  // Optionally, a text description may be attached to the model
  description: "This is an example model!"
});

// Model building, 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 in the model and their field schemas
} = modelDetails;
beginBuildDocumentModel(string, string, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Cree un nuevo modelo con un identificador determinado a partir de un conjunto de documentos de entrada y campos etiquetados.

El id. de modelo puede constar de cualquier texto, siempre y cuando no comience por "precompilado" (ya que estos modelos hacen referencia a modelos creados previamente Form Recognizer que son comunes a todos los recursos) y, siempre y cuando aún no exista dentro del recurso.

El servicio Form Recognizer lee el conjunto de datos de entrenamiento de un contenedor de Azure Storage, dado como una dirección URL al contenedor con un token de SAS que permite al back-end del servicio comunicarse con el contenedor. Como mínimo, se requieren los permisos de "lectura" y "lista". Además, los datos del contenedor especificado deben organizarse según una convención determinada, que se documenta en la documentación del servicio para crear modelos personalizados.

Ejemplo

const modelId = "aNewModel";
const containerUrl = "<training data container SAS URL>";

const poller = await client.beginBuildDocumentModel(modelId, containerUrl, {
  // Optionally, a text description may be attached to the model
  description: "This is an example model!"
});

// Model building, 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 in the model and their field schemas
} = modelDetails;
beginComposeDocumentModel(string, Iterable<string>, BeginComposeDocumentModelOptions)

Crea un único modelo compuesto a partir de varios submodelos preexistentes.

El modelo compuesto resultante combina los tipos de documento de sus modelos de componentes e inserta un paso de clasificación en la canalización de extracción para determinar cuál de sus submodelos de componentes es más adecuado para la entrada especificada.

Ejemplo

const modelId = "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(modelId, 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)

Copia un modelo con el identificador especificado en el recurso y el identificador del modelo codificados por una autorización de copia determinada.

Consulte CopyAuthorization y getCopyAuthorization.

Ejemplo

// 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);

// 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
const poller = await sourceClient.beginCopyModelTo("<source model ID>");

// 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)

Elimina un clasificador con el identificador especificado del recurso del cliente, si existe. No se puede revertir esta operación.

Ejemplo

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

Elimina un modelo con el identificador especificado del recurso del cliente, si existe. No se puede revertir esta operación.

Ejemplo

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

Crea una autorización para copiar un modelo en el recurso, que se usa con el beginCopyModelTo método .

CopyAuthorization Concede a otro recurso de Cognitive Services el derecho a crear un modelo en el recurso de este cliente con el identificador de modelo y la descripción opcional que se codifican en la autorización.

Ejemplo

// 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)

Recupera información sobre un clasificador (DocumentClassifierDetails) por identificador.

Ejemplo

const classifierId = "<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(classifierId);

// 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)

Recupera información sobre un modelo (DocumentModelDetails) por identificador.

Este método puede recuperar información sobre modelos personalizados y precompilados.

Cambio importante

En versiones anteriores de la API REST y el SDK de Form Recognizer, el getModel método podría devolver cualquier modelo, incluso uno que no se pudo crear debido a errores. En las nuevas versiones de servicio y getDocumentModellistDocumentModelssolo producen modelos creados correctamente (es decir, modelos que están "listos" para su uso). Los modelos con errores ahora se recuperan a través de las API de "operaciones", consulte getOperation y listOperations.

Ejemplo

// The ID of the prebuilt business card model
const modelId = "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,
      // 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(modelId);
getOperation(string, GetOperationOptions)

Recupera información sobre una operación (OperationDetails) por su identificador.

Las operaciones representan tareas que no son de análisis, como compilar, redactar o copiar un modelo.

getResourceDetails(GetResourceDetailsOptions)

Recupere información básica sobre el recurso de este cliente.

Ejemplo

const {
  // Information about the custom models in the current resource
  customDocumentModelDetails: {
    // 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)

Enumere los detalles sobre los clasificadores del recurso. Esta operación admite la paginación.

Ejemplos

Iteración asincrónica

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;
}

Por página

// 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)

Enumera los resúmenes de los modelos del recurso. Se incluirán modelos personalizados y precompilados. Esta operación admite la paginación.

El resumen del modelo (DocumentModelSummary) incluye solo la información básica sobre el modelo y no incluye información sobre los tipos de documento del modelo (como los esquemas de campo y los valores de confianza).

Para acceder a la información completa sobre el modelo, use getDocumentModel.

Cambio importante

En versiones anteriores de la API REST y el SDK de Form Recognizer, el listModels método devolvería todos los modelos, incluso aquellos que no se pudieron crear debido a errores. En las nuevas versiones de servicio y listDocumentModelsgetDocumentModelsolo producen modelos creados correctamente (es decir, modelos que están "listos" para su uso). Los modelos con errores ahora se recuperan a través de las API de "operaciones", consulte getOperation y listOperations.

Ejemplos

Iteración asincrónica

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);
}

Por página

// 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 model 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)

Enumera las operaciones de creación de modelos en el recurso. Esto generará todas las operaciones, incluidas las que no pudieron crear modelos correctamente. Esta operación admite la paginación.

Ejemplos

Iteración asincrónica

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;
}

Por página

// 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;
  }
}

Detalles del constructor

DocumentModelAdministrationClient(string, KeyCredential, DocumentModelAdministrationClientOptions)

Creación de una instancia documentModelAdministrationClient desde un punto de conexión de recurso y una clave de API estática (KeyCredential),

Ejemplo:

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

const endpoint = "https://<resource name>.cognitiveservices.azure.com";
const credential = new AzureKeyCredential("<api key>");

const client = new DocumentModelAdministrationClient(endpoint, credential);
new DocumentModelAdministrationClient(endpoint: string, credential: KeyCredential, options?: DocumentModelAdministrationClientOptions)

Parámetros

endpoint

string

la dirección URL del punto de conexión de una instancia de Azure Cognitive Services

credential
KeyCredential

KeyCredential que contiene la clave de suscripción de la instancia de Cognitive Services

options
DocumentModelAdministrationClientOptions

opciones opcionales para configurar todos los métodos en el cliente

DocumentModelAdministrationClient(string, TokenCredential, DocumentModelAdministrationClientOptions)

Cree una instancia documentModelAdministrationClient desde un punto de conexión de recurso y una identidad de TokenCredentialAzure.

Consulte el @azure/identity paquete para más información sobre la autenticación con Azure Active Directory.

Ejemplo:

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

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

const client = new DocumentModelAdministrationClient(endpoint, credential);
new DocumentModelAdministrationClient(endpoint: string, credential: TokenCredential, options?: DocumentModelAdministrationClientOptions)

Parámetros

endpoint

string

la dirección URL del punto de conexión de una instancia de Azure Cognitive Services

credential
TokenCredential

una instancia de TokenCredential del @azure/identity paquete

options
DocumentModelAdministrationClientOptions

opciones opcionales para configurar todos los métodos en el cliente

Detalles del método

beginBuildDocumentClassifier(string, DocumentClassifierDocumentTypeSources, BeginBuildDocumentClassifierOptions)

Cree un nuevo clasificador de documentos con el identificador de clasificador y los tipos de documento especificados.

El identificador del clasificador debe ser único entre clasificadores dentro del recurso.

Los tipos de documento se proporcionan como un objeto que asigna el nombre del tipo de documento al conjunto de datos de entrenamiento para ese tipo de documento. Se admiten dos métodos de entrada de datos de entrenamiento:

  • azureBlobSource, que entrena un clasificador mediante los datos del contenedor de Azure Blob Storage especificado.
  • azureBlobFileListSource, que es similar a azureBlobSource pero permite un control más específico sobre los archivos que se incluyen en el conjunto de datos de entrenamiento mediante una lista de archivos con formato JSONL.

El servicio Form Recognizer lee el conjunto de datos de entrenamiento de un contenedor de Azure Storage, dado como una dirección URL al contenedor con un token de SAS que permite al back-end del servicio comunicarse con el contenedor. Como mínimo, se requieren los permisos de "lectura" y "lista". Además, los datos del contenedor especificado deben organizarse según una convención determinada, que se documenta en la documentación del servicio para crear clasificadores de documentos personalizados.

Ejemplo

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

const poller = await client.beginBuildDocumentClassifier(
  classifierId,
  {
    // 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>

Parámetros

classifierId

string

el identificador único del clasificador que se va a crear.

docTypeSources
DocumentClassifierDocumentTypeSources

los tipos de documento que se van a incluir en el clasificador y sus orígenes (una asignación de nombres de tipo de documento a ClassifierDocumentTypeDetails)

options
BeginBuildDocumentClassifierOptions

configuración opcional para la operación de compilación del clasificador

Devoluciones

una operación de larga duración (sondeo) que finalmente generará los detalles del clasificador creados o un error.

beginBuildDocumentModel(string, DocumentModelSource, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Cree un nuevo modelo con un identificador determinado a partir de un origen de contenido del modelo.

El id. de modelo puede constar de cualquier texto, siempre y cuando no comience por "precompilado" (ya que estos modelos hacen referencia a modelos creados previamente Form Recognizer que son comunes a todos los recursos) y, siempre y cuando aún no exista dentro del recurso.

El origen de contenido describe el mecanismo que usará el servicio para leer los datos de entrenamiento de entrada. Consulte el <xref:DocumentModelContentSource> tipo para obtener más información.

Ejemplo

const modelId = "aNewModel";

const poller = await client.beginBuildDocumentModel(modelId, { containerUrl: "<SAS-encoded blob container URL>" }, {
  // Optionally, a text description may be attached to the model
  description: "This is an example model!"
});

// Model building, 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 in the model and their field schemas
} = modelDetails;
function beginBuildDocumentModel(modelId: string, contentSource: DocumentModelSource, buildMode: DocumentModelBuildMode, options?: BeginBuildDocumentModelOptions): Promise<DocumentModelPoller>

Parámetros

modelId

string

el identificador único del modelo que se va a crear.

contentSource
DocumentModelSource

un origen de contenido que proporciona los datos de entrenamiento para este modelo

buildMode

DocumentModelBuildMode

modo que se va a usar al compilar el modelo (vea DocumentModelBuildMode)

options
BeginBuildDocumentModelOptions

configuración opcional para la operación de compilación del modelo

Devoluciones

una operación de larga duración (sondeo) que finalmente generará la información del modelo creada o un error.

beginBuildDocumentModel(string, string, DocumentModelBuildMode, BeginBuildDocumentModelOptions)

Cree un nuevo modelo con un identificador determinado a partir de un conjunto de documentos de entrada y campos etiquetados.

El id. de modelo puede constar de cualquier texto, siempre y cuando no comience por "precompilado" (ya que estos modelos hacen referencia a modelos creados previamente Form Recognizer que son comunes a todos los recursos) y, siempre y cuando aún no exista dentro del recurso.

El servicio Form Recognizer lee el conjunto de datos de entrenamiento de un contenedor de Azure Storage, dado como una dirección URL al contenedor con un token de SAS que permite al back-end del servicio comunicarse con el contenedor. Como mínimo, se requieren los permisos de "lectura" y "lista". Además, los datos del contenedor especificado deben organizarse según una convención determinada, que se documenta en la documentación del servicio para crear modelos personalizados.

Ejemplo

const modelId = "aNewModel";
const containerUrl = "<training data container SAS URL>";

const poller = await client.beginBuildDocumentModel(modelId, containerUrl, {
  // Optionally, a text description may be attached to the model
  description: "This is an example model!"
});

// Model building, 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 in the model and their field schemas
} = modelDetails;
function beginBuildDocumentModel(modelId: string, containerUrl: string, buildMode: DocumentModelBuildMode, options?: BeginBuildDocumentModelOptions): Promise<DocumentModelPoller>

Parámetros

modelId

string

el identificador único del modelo que se va a crear.

containerUrl

string

DIRECCIÓN URL codificada por SAS en un contenedor de Azure Storage que contiene el conjunto de datos de entrenamiento

buildMode

DocumentModelBuildMode

modo que se va a usar al compilar el modelo (vea DocumentModelBuildMode)

options
BeginBuildDocumentModelOptions

configuración opcional para la operación de compilación del modelo

Devoluciones

una operación de larga duración (sondeo) que finalmente generará la información del modelo creada o un error.

beginComposeDocumentModel(string, Iterable<string>, BeginComposeDocumentModelOptions)

Crea un único modelo compuesto a partir de varios submodelos preexistentes.

El modelo compuesto resultante combina los tipos de documento de sus modelos de componentes e inserta un paso de clasificación en la canalización de extracción para determinar cuál de sus submodelos de componentes es más adecuado para la entrada especificada.

Ejemplo

const modelId = "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(modelId, 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>

Parámetros

modelId

string

el identificador único del modelo que se va a crear.

componentModelIds

Iterable<string>

un iterable de cadenas que representan los identificadores de modelo únicos de los modelos que se van a componer.

options
BeginComposeDocumentModelOptions

configuración opcional para la creación de modelos

Devoluciones

una operación de larga duración (sondeo) que finalmente generará la información del modelo creada o un error.

beginCopyModelTo(string, CopyAuthorization, BeginCopyModelOptions)

Copia un modelo con el identificador especificado en el recurso y el identificador del modelo codificados por una autorización de copia determinada.

Consulte CopyAuthorization y getCopyAuthorization.

Ejemplo

// 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);

// 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
const poller = await sourceClient.beginCopyModelTo("<source model ID>");

// 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>

Parámetros

sourceModelId

string

el identificador único del modelo de origen que se copiará.

authorization
CopyAuthorization

una autorización para copiar el modelo, creado mediante getCopyAuthorization

options
BeginCopyModelOptions

configuración opcional para

Devoluciones

una operación de larga duración (sondeo) que finalmente generará la información del modelo copiada o un error.

deleteDocumentClassifier(string, OperationOptions)

Elimina un clasificador con el identificador especificado del recurso del cliente, si existe. No se puede revertir esta operación.

Ejemplo

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

Parámetros

classifierId

string

el identificador único del clasificador que se va a eliminar del recurso.

options
OperationOptions

configuración opcional para la solicitud

Devoluciones

Promise<void>

deleteDocumentModel(string, DeleteDocumentModelOptions)

Elimina un modelo con el identificador especificado del recurso del cliente, si existe. No se puede revertir esta operación.

Ejemplo

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

Parámetros

modelId

string

el identificador único del modelo que se va a eliminar del recurso.

options
DeleteDocumentModelOptions

configuración opcional para la solicitud

Devoluciones

Promise<void>

getCopyAuthorization(string, GetCopyAuthorizationOptions)

Crea una autorización para copiar un modelo en el recurso, que se usa con el beginCopyModelTo método .

CopyAuthorization Concede a otro recurso de Cognitive Services el derecho a crear un modelo en el recurso de este cliente con el identificador de modelo y la descripción opcional que se codifican en la autorización.

Ejemplo

// 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>

Parámetros

destinationModelId

string

el identificador único del modelo de destino (el identificador en el que se va a copiar el modelo)

options
GetCopyAuthorizationOptions

configuración opcional para crear la autorización de copia

Devoluciones

una autorización de copia que codifica el modelId especificado y una descripción opcional

getDocumentClassifier(string, OperationOptions)

Recupera información sobre un clasificador (DocumentClassifierDetails) por identificador.

Ejemplo

const classifierId = "<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(classifierId);

// 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>

Parámetros

classifierId

string

el identificador único del clasificador que se va a consultar.

options
OperationOptions

configuración opcional para la solicitud

Devoluciones

información sobre el clasificador con el identificador especificado

getDocumentModel(string, GetModelOptions)

Recupera información sobre un modelo (DocumentModelDetails) por identificador.

Este método puede recuperar información sobre modelos personalizados y precompilados.

Cambio importante

En versiones anteriores de la API REST y el SDK de Form Recognizer, el getModel método podría devolver cualquier modelo, incluso uno que no se pudo crear debido a errores. En las nuevas versiones de servicio y getDocumentModellistDocumentModelssolo producen modelos creados correctamente (es decir, modelos que están "listos" para su uso). Los modelos con errores ahora se recuperan a través de las API de "operaciones", consulte getOperation y listOperations.

Ejemplo

// The ID of the prebuilt business card model
const modelId = "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,
      // 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(modelId);
function getDocumentModel(modelId: string, options?: GetModelOptions): Promise<DocumentModelDetails>

Parámetros

modelId

string

el identificador único del modelo que se va a consultar.

options
GetModelOptions

configuración opcional para la solicitud

Devoluciones

información sobre el modelo con el identificador especificado

getOperation(string, GetOperationOptions)

Recupera información sobre una operación (OperationDetails) por su identificador.

Las operaciones representan tareas que no son de análisis, como compilar, redactar o copiar un modelo.

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

Parámetros

operationId

string

el identificador de la operación que se va a consultar.

options
GetOperationOptions

configuración opcional para la solicitud

Devoluciones

Promise<OperationDetails>

información sobre la operación con el identificador especificado

Ejemplo

// The ID of the operation, which should be a GUID
const operationId = "<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(operationId);

getResourceDetails(GetResourceDetailsOptions)

Recupere información básica sobre el recurso de este cliente.

Ejemplo

const {
  // Information about the custom models in the current resource
  customDocumentModelDetails: {
    // 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>

Parámetros

options
GetResourceDetailsOptions

configuración opcional para la solicitud

Devoluciones

Promise<ResourceDetails>

información básica sobre el recurso de este cliente

listDocumentClassifiers(ListModelsOptions)

Enumere los detalles sobre los clasificadores del recurso. Esta operación admite la paginación.

Ejemplos

Iteración asincrónica

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;
}

Por página

// 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>

Parámetros

options
ListModelsOptions

configuración opcional para las solicitudes del clasificador

Devoluciones

un iterable asincrónico de detalles del clasificador que admite la paginación

listDocumentModels(ListModelsOptions)

Enumera los resúmenes de los modelos del recurso. Se incluirán modelos personalizados y precompilados. Esta operación admite la paginación.

El resumen del modelo (DocumentModelSummary) incluye solo la información básica sobre el modelo y no incluye información sobre los tipos de documento del modelo (como los esquemas de campo y los valores de confianza).

Para acceder a la información completa sobre el modelo, use getDocumentModel.

Cambio importante

En versiones anteriores de la API REST y el SDK de Form Recognizer, el listModels método devolvería todos los modelos, incluso aquellos que no se pudieron crear debido a errores. En las nuevas versiones de servicio y listDocumentModelsgetDocumentModelsolo producen modelos creados correctamente (es decir, modelos que están "listos" para su uso). Los modelos con errores ahora se recuperan a través de las API de "operaciones", consulte getOperation y listOperations.

Ejemplos

Iteración asincrónica

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);
}

Por página

// 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 model 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>

Parámetros

options
ListModelsOptions

configuración opcional para las solicitudes del modelo

Devoluciones

un iterable asincrónico de resúmenes de modelo que admite la paginación

listOperations(ListOperationsOptions)

Enumera las operaciones de creación de modelos en el recurso. Esto generará todas las operaciones, incluidas las que no pudieron crear modelos correctamente. Esta operación admite la paginación.

Ejemplos

Iteración asincrónica

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;
}

Por página

// 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>

Parámetros

options
ListOperationsOptions

configuración opcional para las solicitudes de operación

Devoluciones

un iterable asincrónico de objetos de información de operación que admite la paginación