Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Message that somehow wasn't published after modification of javascript program

OK, I have modified my javascript in response to certain suggestions, and here is the latest version, which produced the error message included just after running the following code (the error displayed follows the code):  
 
async function myFunction() {
const projectId = 'sixth-sequencer-373709';
const location = 'global';
const sourceLanguage = 'ar';
const targetLanguage = 'en';
const bucketName = 'legrandtimonier1951';
const inputPath = '/v3/arabic/arabic_input.docx';
const outputPath = '/v3/english/english_output.docx';
 
// Initialize clients
const credentials = await google.auth.getClient({
});
const translationClient = new TranslationServiceClient({ credentials });
 
// Construct input config
const inputConfig = {
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
content: fs.readFileSync(inputPath).toString('base64')
};
 
// Construct output config
const outputConfig = {
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
gcsDestination: {
uri: `gs://${bucketName}/${outputPath}`
}
};
 
// Construct glossary config
const glossaryConfig = {
glossary: `projects/${projectId}/locations/${location}/glossaries/${targetLanguage}`,
glossaryConfig: {
ignoreCase: true,
inputConfig: {
mimeType: 'application/x-tmx+xml'
},
 
entryGroup: {
displayName: `Glossary for ${targetLanguage}`,
storageLocation: {
bucket: bucketName,
object: `glossary_${targetLanguage}.tmx`
}
}
}
}
};
 
// Construct request
const request = {
parent: `projects/${projectId}/locations/${location}`,
sourceLanguageCode: sourceLanguage,
targetLanguageCodes: [targetLanguage],
inputConfigs: [inputConfig],
outputConfig: outputConfig,
glossaries: [glossaryConfig],
};
 
// Call the translation API
const [operation] = await translationClient.batchTranslateDocument(request);
 
// Wait for the translation operation to complete
const [response] = await operation.promise();
 
// Download the translated document from GCS
const outputFile = `gs://${bucketName}/${outputPath}`;
await storage.bucket(bucketName).file(outputPath).download({ destination: outputPath });
 
console.log(`Translation complete. The translated file is located at ${outputPath}.`);
 

const { TranslationServiceClient } = require('@google-cloud/translate');
const { Storage } = require('@google-cloud/storage');
const fs = require('fs');

// JSON Key file for Cloud Translation API
const translationKeyFile = '/home/gurqinfo/v3_cloud_translation_key.json';
const translationKeyFileContents = fs.readFileSync(translationKeyFile);
const translationCredentials = JSON.parse(translationKeyFileContents);

// JSON key file for Google Storage API
const storageKeyFile = '/home/gurqinfo/v3_cloud_storage_key.json';
const storageKeyFileContents = fs.readFileSync(storageKeyFile);
const storageCredentials = JSON.parse(storageKeyFileContents);

// Clients instantiated with their explicit credentials
const translationClient = new TranslationServiceClient({ credentials: translationCredentials });
const storage = new Storage({ credentials: storageCredentials });

async function translateDocxFile(inputPath, outputPath, targetLanguage) {
const fileContent = fs.readFileSync(inputPath);

// Input config for translation request
const inputConfig = {
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
content: fileContent,
};

// Output config for translation request
const outputConfig = {
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
gcsDestination: {
bucket: bucketName,
object: outputPath,
},
};

// Glossary config for translation request
const glossaryConfig = {
glossary: {
languageCodesSet: {
languageCodes: [sourceLanguage, targetLanguage],
},
inputConfig: {
gcsSource: {
inputUri: `gs://${bucketName}/ar2en1.tmx`,
},
},
},
};

// Construct request
const request = {
parent: `projects/${projectId}/locations/${location}`,
sourceLanguageCode: sourceLanguage,
targetLanguageCodes: [targetLanguage],
inputConfigs: [inputConfig],
outputConfig: outputConfig,
glossaries: [glossaryConfig],
};

try {
// Run the batchTranslateDocument method
const [operation] = await translationClient.batchTranslateDocument(request);
console.log(`Translation operation ${operation.name} started.`);
// Wait for the operation to complete
const [response] = await operation.promise();
console.log(`Translation operation ${operation.name} completed.`);
console.log(`Total Pages: ${response.totalPages}`);
return response.translations[0].gcsDestination.object;
} catch (error) {
console.error(`Translation error: ${error}`);
throw error;
}
}

// Call the translateDocxFile function with input and output file paths
const inputPath = 'gs://legrandtimonier1951/v3/arabic/arabic_input.docx';
const outputPath = 'v3/english/english_output.docx';

translateDocxFile(inputPath, outputPath, targetLanguage);

myFunction();
 
-------------------
 
Error message when the above program is run:
 
home/gurqinfo/working/final1.js:61
    const [operation] = await translationClient.batchTranslateDocument(request);
                        ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47
 
I tried to do what I was told to do by ChatGPT with regard to placing
async function myFunction() { async function myFunction() ... at the
very beginning and calling it at the very end. But still no luck. 
 
I'll continue to work at getting this thing to work until it does, hoping that certain other community members might benefit from this exercise, too, changing, in each person's case, the language codes + glossary used to suit their particular translation needs. Easy to do once the rest of the program is fixed.
 
 
1 3 299
3 REPLIES 3

What you appear to be running into is a JavaScript language puzzle rather than anything specific to Google Cloud ...

At a logical level, your program appears to be:

async function myFunction() {
 // Do something
}

await myFunction()

 The way to read this is that you have defined a function called myFunction that is asynchronous ... meaning it returns a Promise immediately and then runs when the app would otherwise be idle.  You then have a blocking call waiting for the function to end.  Unfortunately, you can't block in the main code of JavaScript.  An alternative would be:

async function myFunction() {
 // Do something
}

async function run() {
  // Do something before calling myFunction
  await myFunction()
  // Do something when myFunction finishes
}

run()

 

Many thanks for this. Now I know what it's not (a Google Cloud thing) and how to go about fixing it (thinking harder). Regards

Ok, I've thought about this and now realize there is no need for the async
function for what I wanted to do. That was just confusing matters. Getting
closer I think now that I've abandoned that approach. Thanks for your
earlier guidance.