Skip to content

Commit 9e0b6ea

Browse files
FadyEssamFadyEssam2maririos
authored
Add code samples for document translator sdk (Azure#21214)
* Add code samples for document translator sdk * adjust spacing * Add Document Translator Sample in README * allow passing document path in Document Translator code samples * Remove csproj and Program.cs from Document translator samples * address PR comments * edit comment in Document Translator Samples * modify sample to compy with our CI Co-authored-by: Fady Essam <faanis@microsoft.com> Co-authored-by: Mariana Rios Flores <mariari@microsoft.com>
1 parent 3cfc85a commit 9e0b6ea

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed

sdk/translation/Azure.AI.Translation.Document/samples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,6 @@ Azure Cognitive Services Document Translation is a cloud service that translates
2424

2525
## Advanced samples
2626
- [Multiple Inputs](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/translation/Azure.AI.Translation.Document/samples/Sample4_MultipleInputs.md)
27+
- [Create Storage Containers And Submit Operation (code sample)](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/translation/Azure.AI.Translation.Document/tests/samples/Sample_StartTranslationWithAzureBlob.cs)
2728

2829
[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/textanalytics/Azure.AI.TextAnalytics/README.md
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.IO;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
using Azure.AI.Translation.Document.Tests;
9+
using Azure.Core.TestFramework;
10+
using Azure.Storage;
11+
using Azure.Storage.Blobs;
12+
using Azure.Storage.Sas;
13+
using NUnit.Framework;
14+
15+
namespace Azure.AI.Translation.Document.Samples
16+
{
17+
[LiveOnly]
18+
public partial class DocumentTranslationSamples : SamplesBase<DocumentTranslationTestEnvironment>
19+
{
20+
[Test]
21+
[Ignore("Samples not working yet")]
22+
public async Task StartTranslationWithAzureBlob()
23+
{
24+
/**
25+
FILE: SampleTranslationWithAzureBlob.cs
26+
DESCRIPTION:
27+
This sample demonstrates how to use Azure Blob Storage to set up the necessary resources to create a translation
28+
operation. Run the sample to create containers, upload documents, and generate SAS tokens for the source/target
29+
containers. Once the operation is completed, use the storage library to download your documents locally.
30+
31+
PREREQUISITE:
32+
This sample requires you install Azure.Storage.Blobs nuget package:
33+
https://www.nuget.org/packages/Azure.Storage.Blobs
34+
35+
USAGE:
36+
Set the environment variables with your own values before running the sample:
37+
1) AZURE_DOCUMENT_TRANSLATION_ENDPOINT - the endpoint to your Document Translation resource.
38+
2) AZURE_DOCUMENT_TRANSLATION_KEY - your Document Translation API key.
39+
3) AZURE_STORAGE_SOURCE_ENDPOINT - the endpoint to your Storage account
40+
4) AZURE_STORAGE_ACCOUNT_NAME - the name of your storage account
41+
5) AZURE_STORAGE_SOURCE_KEY - the shared access key to your storage account
42+
Optional environment variables - if not set, they will be created for you
43+
6) AZURE_STORAGE_SOURCE_CONTAINER_NAME - the name of your source container
44+
7) AZURE_STORAGE_TARGET_CONTAINER_NAME - the name of your target container
45+
8) AZURE_DOCUMENT_PATH - (optional) the path and file extension of your document in this directory
46+
e.g. "path/mydocument.txt"
47+
**/
48+
string endpoint = TestEnvironment.Endpoint;
49+
string apiKey = TestEnvironment.ApiKey;
50+
51+
var client = new DocumentTranslationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
52+
53+
#region Snippet:StartTranslationWithAzureBlobAsync
54+
Uri storageEndpoint = new Uri(Environment.GetEnvironmentVariable("AZURE_STORAGE_SOURCE_ENDPOINT"));
55+
string storageAccountName = Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT_NAME");
56+
string storageAccountKey = Environment.GetEnvironmentVariable("AZURE_STORAGE_SOURCE_KEY");
57+
string sourceContainerName = Environment.GetEnvironmentVariable("AZURE_STORAGE_SOURCE_CONTAINER_NAME");
58+
string targetContainerName = Environment.GetEnvironmentVariable("AZURE_STORAGE_TARGET_CONTAINER_NAME");
59+
string documentPath = Environment.GetEnvironmentVariable("AZURE_DOCUMENT_PATH");
60+
61+
// Create source and target storage containers
62+
BlobServiceClient blobServiceClient = new BlobServiceClient(storageEndpoint, new StorageSharedKeyCredential(storageAccountName, storageAccountKey));
63+
BlobContainerClient sourceContainerClient = await blobServiceClient.CreateBlobContainerAsync(sourceContainerName ?? "translation-source-container").ConfigureAwait(false);
64+
BlobContainerClient targetContainerClient = await blobServiceClient.CreateBlobContainerAsync(targetContainerName ?? "translation-target-container").ConfigureAwait(false);
65+
66+
// Upload blob (file) to the source container
67+
BlobClient srcBlobClient = sourceContainerClient.GetBlobClient(string.IsNullOrWhiteSpace(documentPath) ? Path.GetFileName(documentPath) : "example_source_document.txt");
68+
69+
if (!string.IsNullOrWhiteSpace(documentPath))
70+
{
71+
using (FileStream uploadFileStream = File.OpenRead(documentPath))
72+
{
73+
await srcBlobClient.UploadAsync(uploadFileStream, true).ConfigureAwait(false);
74+
}
75+
}
76+
else
77+
{
78+
await srcBlobClient.UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("Hello.\nThis is a testing text.")), true).ConfigureAwait(false);
79+
}
80+
81+
Console.WriteLine($"Uploaded document {srcBlobClient.Uri} to source storage container");
82+
83+
// Generate SAS tokens for source & target
84+
Uri srcSasUri = sourceContainerClient.GenerateSasUri(BlobContainerSasPermissions.List | BlobContainerSasPermissions.Read, DateTime.UtcNow.AddMinutes(30));
85+
Uri tgtSasUri = targetContainerClient.GenerateSasUri(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Delete, DateTime.UtcNow.AddMinutes(30));
86+
87+
// Submit the translation operation and wait for it to finish
88+
var operationRequest = new DocumentTranslationInput(srcSasUri, tgtSasUri, "es");
89+
DocumentTranslationOperation operationResult = await client.StartTranslationAsync(operationRequest);
90+
await operationResult.WaitForCompletionAsync();
91+
92+
Console.WriteLine($"Operation status: {operationResult.Status}");
93+
Console.WriteLine($"Operation created on: {operationResult.CreatedOn}");
94+
Console.WriteLine($"Operation last updated on: {operationResult.LastModified}");
95+
Console.WriteLine($"Total number of translations on documents: {operationResult.DocumentsTotal}");
96+
Console.WriteLine("\nOf total documents...");
97+
Console.WriteLine($"{operationResult.DocumentsFailed} failed");
98+
Console.WriteLine($"{operationResult.DocumentsSucceeded} succeeded");
99+
100+
await foreach (DocumentStatusResult document in operationResult.GetAllDocumentStatusesAsync())
101+
{
102+
if (document.Status == TranslationStatus.Succeeded)
103+
{
104+
Console.WriteLine($"Document at {document.SourceDocumentUri} was translated to {document.TranslateTo} language.You can find translated document at {document.TranslatedDocumentUri}");
105+
}
106+
else
107+
{
108+
Console.WriteLine($"Document ID: {document.DocumentId}, Error Code: {document.Error.ErrorCode}, Message: {document.Error.Message}");
109+
}
110+
}
111+
112+
#endregion
113+
}
114+
}
115+
}

0 commit comments

Comments
 (0)