Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion sdk/formrecognizer/Azure.AI.FormRecognizer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
- `RecognizeReceiptsOperation` now returns a `RecognizedReceiptCollection`.
- `RecognizeCustomFormsOperation` now returns a `RecognizedFormCollection`.

### Added
### New Features

- `FormRecognizerClient` and `FormTrainingClient` support authentication with Azure Active Directory.
- Support to copy a custom model from one Form Recognizer resource to another.

### Fixes

Expand Down
3 changes: 3 additions & 0 deletions sdk/formrecognizer/Azure.AI.FormRecognizer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ var client = new FormRecognizerClient(new Uri(endpoint), new DefaultAzureCredent
- Training custom models to recognize all fields and values found in your custom forms. A `CustomFormModel` is returned indicating the form types the model will recognize, and the fields it will extract for each form type.
- Training custom models to recognize specific fields and values you specify by labeling your custom forms. A `CustomFormModel` is returned indicating the fields the model will extract, as well as the estimated accuracy for each field.
- Managing models created in your account.
- Copying a custom model from one Form Recognizer resource to another.

Please note that models can also be trained using a graphical user interface such as the [Form Recognizer Labeling Tool][labeling_tool].

Expand Down Expand Up @@ -357,6 +358,7 @@ Samples showing how to use the Cognitive Services Form Recognizer library are av
- [Recognize custom forms][recognize_custom_forms]
- [Train a model][train_a_model]
- [Manage custom models][manage_custom_models]
- [Copy a custom model between Form Recognizer resources][copy_custom_models]

## Contributing

Expand Down Expand Up @@ -400,6 +402,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
[recognize_custom_forms]: samples/Sample3_RecognizeCustomForms.md
[train_a_model]: samples/Sample4_TrainModel.md
[manage_custom_models]: samples/Sample5_ManageCustomModels.md
[copy_custom_models]: samples/Sample6_CopyCustomModel.md

[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_sub]: https://azure.microsoft.com/free/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ You can find samples for each of the main functions below.
- [Recognize custom forms](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples/Sample3_RecognizeCustomForms.md)
- [Train a model](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples/Sample4_TrainModel.md)
- [Manage custom models](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples/Sample5_ManageCustomModels.md)
- [Copy a custom model between Form Recognizer resources](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples/Sample6_CopyCustomModel.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Copy a custom model between Form Recognizer resources

This sample demonstrates how to copy a custom model between Form Recognizer resources.

To get started you'll need a Cognitive Services resource or a Form Recognizer resource. See [README][README] for prerequisites and instructions.

## Copy a custom model
There are several scenarios that require the models to be copied between Form Recognizer resources, like for example, to keep a backup of the created models.
Copies can be made:
- Within same Form Recognizer resource
- Across other Form Recognizer resources that exist in any other supported region.

For this sample, you will copy a model across Form recognizer resource. It assumes you have the credentials for both the source and the target Form Recognizer resources.

## Creating the source and target `FormTrainingClient`

To create a new `FormTrainingClient` you need the endpoint and credentials from your resource. In the sample below you'll use a Form Recognizer API key credential by creating an `AzureKeyCredential` object.
You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.

### Source client
The source client that contains the custom model we want to copy.

```C# Snippet:FormRecognizerSample6CreateCopySourceClient
string endpoint = "<source_endpoint>";
string apiKey = "<source_apiKey>";
var sourcecredential = new AzureKeyCredential(apiKey);
var sourceClient = new FormTrainingClient(new Uri(endpoint), sourcecredential);
```

### Target client
The target client where we want to copy the custom model to.

```C# Snippet:FormRecognizerSample6CreateCopyTargetClient
string endpoint = "<target_endpoint>";
string apiKey = "<target_apiKey>";
var targetCredential = new AzureKeyCredential(apiKey);
var targetClient = new FormTrainingClient(new Uri(endpoint), targetCredential);
```

### Authorize the copy
Before starting the copy, we need to get a `CopyAuthorization` from the target Form Recognizer resource that will give us permission to execute the copy.
```C# Snippet:FormRecognizerSample6GetCopyAuthorization
string resourceId = "<resourceId>";
string resourceRegion = "<region>";
CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceId, resourceRegion);
```

`CopyAuthorization` provides the convenience method `ToJson` that will serialize the authorization properties into a json format string.
```C# Snippet:FormRecognizerSample6ToJson
string jsonTargetAuth = targetAuth.ToJson();
```

To deserealize a string that contains authorizaiton information, use the `FromJson` method from `CopyAuthorization`.
```C# Snippet:FormRecognizerSample6FromJson
CopyAuthorization targetCopyAuth = CopyAuthorization.FromJson(jsonTargetAuth);
```

### Execute the copy
Now that we have authorization from the target Form Recognizer resource, we execute the copy from the `sourceClient` where the model to copy lives.

```C# Snippet:FormRecognizerSample6CopyModel
string modelId = "<source_modelId>";
CustomFormModelInfo newModel = await sourceClient.StartCopyModelAsync(modelId, targetCopyAuth).WaitForCompletionAsync();

Console.WriteLine($"Original modelID => {modelId}");
Console.WriteLine($"Copied modelID => {newModel.ModelId}");
```


To see the full example source files, see:
* [Copy custom models](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/tests/samples/Sample7_CopyModel.cs)

[README]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer#getting-started
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Text.Json;

namespace Azure.AI.FormRecognizer.Training
{
/// <summary>
/// Authorization for copying a custom model into the target Form Recognizer resource.
/// </summary>
public class CopyAuthorization
{
/// <summary>Model identifier in the target Form Recognizer Resource. </summary>
public string ModelId { get; }
/// <summary> The time when the access token expires. The date is represented as the number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. </summary>
//public DateTimeOffset ExpiresOn { get; set; }
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue #12181

public long ExpiresOn { get; }
/// <summary> Token claim used to authorize the request. </summary>
internal string _accessToken { get; }
/// <summary> Azure Resource Id of the target Form Recognizer resource where the model is copied to. </summary>
internal string _resourceId { get; }
/// <summary> Location of the target Form Recognizer resource. A valid Azure region name supported by Cognitive Services. </summary>
internal string _region { get; }

internal CopyAuthorization(string modelId, string accessToken, long expirationDateTimeTicks, string resourceId, string region)
{
ModelId = modelId;
_accessToken = accessToken;
//ExpiresOn = DateTimeOffset.FromUnixTimeSeconds(expirationDateTimeTicks);
ExpiresOn = expirationDateTimeTicks;
_resourceId = resourceId;
_region = region;
}

internal CopyAuthorization(CopyAuthorizationResult copyAuth, string resourceId, string region)
: this(copyAuth.ModelId, copyAuth.AccessToken, copyAuth.ExpirationDateTimeTicks, resourceId, region) { }

/// <summary>
/// Deserializes an opaque string into a <see cref="CopyAuthorization"/> object.
/// </summary>
/// <param name="accessToken">Opaque string with the access token information for a specific model.</param>
public static CopyAuthorization FromJson(string accessToken)
{
CopyAuthorizationParse parse = JsonSerializer.Deserialize<CopyAuthorizationParse>(accessToken);
return new CopyAuthorization(
parse.modelId,
parse.accessToken,
//DateTimeOffset.FromUnixTimeSeconds(parse.expirationDateTimeTicks),
parse.expirationDateTimeTicks,
parse.resourceId,
parse.resourceRegion);
}

/// <summary>
/// Converts the CopyAuthorization object to its equivalent json representation.
/// </summary>
public string ToJson()
{
var toParse = new CopyAuthorizationParse(this);
return JsonSerializer.Serialize(toParse);
}

private class CopyAuthorizationParse
{
public string modelId { get; set; }
public string accessToken { get; set; }
public long expirationDateTimeTicks { get; set; }
public string resourceId { get; set; }
public string resourceRegion { get; set; }

public CopyAuthorizationParse() { }

public CopyAuthorizationParse(CopyAuthorization target)
{
modelId = target.ModelId;
accessToken = target._accessToken;
//expirationDateTimeTicks = target.ExpiresOn.ToUnixTimeSeconds();
expirationDateTimeTicks = target.ExpiresOn;
resourceId = target._resourceId;
resourceRegion = target._region;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.AI.FormRecognizer.Training
{
[CodeGenModel("CopyAuthorizationResult")]
internal partial class CopyAuthorizationResult
{
}
}
Loading