Skip to content

Commit f3abea1

Browse files
authored
add: Translate Document & Batch Translate Document samples (#694)
* translate document sample and test Change-Id: Id0f943163f063e114aaec5703f3160a5b9c71485 * remove comment Change-Id: I13ee4f8692c76416564d05485271a50929ff42cf * lint Change-Id: I3eb785d6a164748484726ad359a8ae7f8156051d * batch translate document Change-Id: Id36d46f363cb061c38ddf099e23836020757b9f2 * batch translate document Change-Id: Ifbf6c3faec2352237f44d714c31360349b950efb * update year Change-Id: Icb80b2a660ee38de5cbbd09e497eeaf4d3532371 * refactor error handling Change-Id: Ic7493f025e1c98b3c4e0dbc6a48919e8a2df309e * refactor error handling Change-Id: Ibe57fa98dbb060039d8b60684238294f3f4746f1
1 parent 8271a21 commit f3abea1

4 files changed

+268
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Copyright 2021 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
const {assert} = require('chai');
18+
const {describe, it, before, after} = require('mocha');
19+
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;
20+
const {Storage} = require('@google-cloud/storage');
21+
const cp = require('child_process');
22+
const uuid = require('uuid');
23+
24+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
25+
26+
const REGION_TAG = 'translate_batch_translate_document';
27+
28+
describe(REGION_TAG, () => {
29+
const translationClient = new TranslationServiceClient();
30+
const location = 'us-central1';
31+
const bucketUuid = uuid.v4();
32+
const bucketName = `translation-${bucketUuid}/BATCH_OUTPUT/`;
33+
const storage = new Storage();
34+
35+
before(async () => {
36+
const projectId = await translationClient.getProjectId();
37+
38+
//Create bucket if needed
39+
try {
40+
await storage.createBucket(projectId, {
41+
location: 'US',
42+
storageClass: 'COLDLINE',
43+
});
44+
} catch (error) {
45+
if (error.code !== 409) {
46+
//if it's not a duplicate bucket error, let the user know
47+
console.error(error);
48+
throw error;
49+
}
50+
}
51+
});
52+
53+
it('should batch translate the input documents', async function () {
54+
this.retries(3);
55+
const projectId = await translationClient.getProjectId();
56+
const inputUri = 'gs://cloud-samples-data/translation/async_invoices/*';
57+
58+
const outputUri = `gs://${projectId}/${bucketName}`;
59+
const output = execSync(
60+
`node v3beta1/${REGION_TAG}.js ${projectId} ${location} ${inputUri} ${outputUri}`
61+
);
62+
assert.match(output, /Total Pages: /);
63+
64+
this.timeout(500000);
65+
});
66+
67+
// Delete the folder from GCS for cleanup
68+
after(async () => {
69+
const projectId = await translationClient.getProjectId();
70+
const options = {
71+
prefix: `translation-${bucketUuid}`,
72+
};
73+
74+
const bucket = await storage.bucket(projectId);
75+
const [files] = await bucket.getFiles(options);
76+
const length = files.length;
77+
if (length > 0) {
78+
await Promise.all(files.map(file => file.delete()));
79+
}
80+
});
81+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2021 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
const {assert} = require('chai');
18+
const {describe, it} = require('mocha');
19+
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;
20+
const cp = require('child_process');
21+
22+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
23+
24+
const REGION_TAG = 'translate_translate_document';
25+
26+
describe(REGION_TAG, () => {
27+
it('should translate the input document', async () => {
28+
const translationClient = new TranslationServiceClient();
29+
const projectId = await translationClient.getProjectId();
30+
const location = 'global';
31+
const inputUri = 'gs://cloud-samples-data/translation/fake_invoice.pdf';
32+
const output = execSync(
33+
`node v3beta1/${REGION_TAG}.js ${projectId} ${location} ${inputUri}`
34+
);
35+
assert.match(output, /Response: Mime Type/);
36+
});
37+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright 2021 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
function main(
18+
projectId = 'YOUR_PROJECT_ID',
19+
location = 'us-central1',
20+
inputUri = 'gs://cloud-samples-data/translation/async_invoices/*',
21+
outputUri = 'gs://YOUR_PROJECT_ID/translation/BATCH_DOCUMENT_TRANSLATION_OUTPUT/'
22+
) {
23+
// [START translate_batch_translate_document]
24+
/**
25+
* TODO(developer): Uncomment these variables before running the sample.
26+
*/
27+
// const projectId = 'YOUR_PROJECT_ID';
28+
// const location = 'us-central1';
29+
// const inputUri = 'path_to_your_files';
30+
// const outputUri = 'path_to_your_output_bucket';
31+
32+
// Imports the Google Cloud Translation library
33+
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;
34+
35+
// Instantiates a client
36+
const translationClient = new TranslationServiceClient();
37+
38+
const documentInputConfig = {
39+
gcsSource: {
40+
inputUri: inputUri,
41+
},
42+
};
43+
44+
async function batchTranslateDocument() {
45+
// Construct request
46+
const request = {
47+
parent: translationClient.locationPath(projectId, location),
48+
documentInputConfig: documentInputConfig,
49+
sourceLanguageCode: 'en-US',
50+
targetLanguageCodes: ['sr-Latn'],
51+
inputConfigs: [
52+
{
53+
gcsSource: {
54+
inputUri: inputUri,
55+
},
56+
},
57+
],
58+
outputConfig: {
59+
gcsDestination: {
60+
outputUriPrefix: outputUri,
61+
},
62+
},
63+
};
64+
65+
// Batch translate documents using a long-running operation.
66+
// You can wait for now, or get results later.
67+
const [operation] = await translationClient.batchTranslateDocument(request);
68+
69+
// Wait for operation to complete.
70+
const [response] = await operation.promise();
71+
72+
console.log(`Total Pages: ${response.totalPages}`);
73+
}
74+
75+
batchTranslateDocument();
76+
// [END translate_batch_translate_document]
77+
}
78+
79+
process.on('unhandledRejection', err => {
80+
console.error(err.message);
81+
process.exitCode = 1;
82+
});
83+
main(...process.argv.slice(2));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Copyright 2021 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
function main(
18+
projectId = 'YOUR_PROJECT_ID',
19+
location = 'global',
20+
inputUri = 'path_to_your_file'
21+
) {
22+
// [START translate_translate_document]
23+
/**
24+
* TODO(developer): Uncomment these variables before running the sample.
25+
*/
26+
// const projectId = 'YOUR_PROJECT_ID';
27+
// const location = 'global';
28+
// const inputUri = 'path_to_your_file';
29+
30+
// Imports the Google Cloud Translation library
31+
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;
32+
33+
// Instantiates a client
34+
const translationClient = new TranslationServiceClient();
35+
36+
const documentInputConfig = {
37+
gcsSource: {
38+
inputUri: inputUri,
39+
},
40+
};
41+
42+
async function translateDocument() {
43+
// Construct request
44+
const request = {
45+
parent: translationClient.locationPath(projectId, location),
46+
documentInputConfig: documentInputConfig,
47+
sourceLanguageCode: 'en-US',
48+
targetLanguageCode: 'sr-Latn',
49+
};
50+
51+
// Run request
52+
const [response] = await translationClient.translateDocument(request);
53+
54+
console.log(
55+
`Response: Mime Type - ${response.documentTranslation.mimeType}`
56+
);
57+
}
58+
59+
translateDocument();
60+
// [END translate_translate_document]
61+
}
62+
63+
process.on('unhandledRejection', err => {
64+
console.error(err.message);
65+
process.exitCode = 1;
66+
});
67+
main(...process.argv.slice(2));

0 commit comments

Comments
 (0)