use of com.google.cloud.automl.v1beta1.GcsSource in project google-cloud-java by GoogleCloudPlatform.
the class TranslateSnippetsBeta method batchTranslateText.
// [END translate_translate_text_beta]
/**
* Translates a batch of texts on GCS and stores the result in a GCS location.
*
* @param projectId - Id of the project.
* @param location - location name.
* @param sourceUri - Google Cloud Storage URI. Location where text is stored.
* @param destinationUri - Google Cloud Storage URI where result will be stored.
*/
// [START translate_batch_translate_text_beta]
static BatchTranslateResponse batchTranslateText(String projectId, String location, String sourceUri, String destinationUri) {
try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build();
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(sourceUri).build();
InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();
GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(destinationUri).build();
OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
BatchTranslateTextRequest batchTranslateTextRequest = BatchTranslateTextRequest.newBuilder().setParent(locationName.toString()).setSourceLanguageCode("en").addTargetLanguageCodes("sr").addInputConfigs(inputConfig).setOutputConfig(outputConfig).build();
// Call the API
BatchTranslateResponse response = translationServiceClient.batchTranslateTextAsync(batchTranslateTextRequest).get(300, TimeUnit.SECONDS);
System.out.printf("Total Characters: %d\n", response.getTotalCharacters());
System.out.printf("Translated Characters: %d\n", response.getTranslatedCharacters());
return response;
} catch (Exception e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
use of com.google.cloud.automl.v1beta1.GcsSource in project spring-cloud-gcp by spring-cloud.
the class DocumentOcrTemplate method runOcrForDocument.
/**
* Runs OCR processing for a specified {@code document} and generates OCR output files
* under the path specified by {@code outputFilePathPrefix}.
*
* <p>
* For example, if you specify an {@code outputFilePathPrefix} of
* "gs://bucket_name/ocr_results/myDoc_", all the output files of OCR processing will be
* saved under prefix, such as:
*
* <ul>
* <li>gs://bucket_name/ocr_results/myDoc_output-1-to-5.json
* <li>gs://bucket_name/ocr_results/myDoc_output-6-to-10.json
* <li>gs://bucket_name/ocr_results/myDoc_output-11-to-15.json
* </ul>
*
* <p>
* Note: OCR processing operations may take several minutes to complete, so it may not be
* advisable to block on the completion of the operation. One may use the returned
* {@link ListenableFuture} to register callbacks or track the status of the operation.
*
* @param document The {@link GoogleStorageLocation} of the document to run OCR processing
* @param outputFilePathPrefix The {@link GoogleStorageLocation} of a file, folder, or a
* bucket describing the path for which all output files shall be saved under
*
* @return A {@link ListenableFuture} allowing you to register callbacks or wait for the
* completion of the operation.
*/
public ListenableFuture<DocumentOcrResultSet> runOcrForDocument(GoogleStorageLocation document, GoogleStorageLocation outputFilePathPrefix) {
Assert.isTrue(document.isFile(), "Provided document location is not a valid file location: " + document);
GcsSource gcsSource = GcsSource.newBuilder().setUri(document.uriString()).build();
String contentType = extractContentType(document);
InputConfig inputConfig = InputConfig.newBuilder().setMimeType(contentType).setGcsSource(gcsSource).build();
GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputFilePathPrefix.uriString()).build();
OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(this.jsonOutputBatchSize).build();
AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder().addFeatures(DOCUMENT_OCR_FEATURE).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> result = imageAnnotatorClient.asyncBatchAnnotateFilesAsync(Collections.singletonList(request));
return extractOcrResultFuture(result);
}
use of com.google.cloud.automl.v1beta1.GcsSource in project java-translate by googleapis.
the class BatchTranslateTextWithGlossaryAndModel method batchTranslateTextWithGlossaryAndModel.
// Batch translate text with Model and Glossary
public static void batchTranslateTextWithGlossaryAndModel(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, String glossaryId, String modelId) throws IOException, ExecutionException, InterruptedException, TimeoutException {
// the "close" method on the client to safely clean up any remaining background resources.
try (TranslationServiceClient client = TranslationServiceClient.create()) {
// Supported Locations: `global`, [glossary location], or [model location]
// Glossaries must be hosted in `us-central1`
// Custom Models must use the same location as your model. (us-central1)
String location = "us-central1";
LocationName parent = LocationName.of(projectId, location);
// Configure the source of the file from a GCS bucket
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();
// Configure where to store the output in a GCS bucket
GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
// Configure the glossary used in the request
GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
TranslateTextGlossaryConfig glossaryConfig = TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();
// Configure the model used in the request
String modelPath = String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);
// Build the request that will be sent to the API
BatchTranslateTextRequest request = BatchTranslateTextRequest.newBuilder().setParent(parent.toString()).setSourceLanguageCode(sourceLanguage).addTargetLanguageCodes(targetLanguage).addInputConfigs(inputConfig).setOutputConfig(outputConfig).putGlossaries(targetLanguage, glossaryConfig).putModels(targetLanguage, modelPath).build();
// Start an asynchronous request
OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future = client.batchTranslateTextAsync(request);
System.out.println("Waiting for operation to complete...");
// random number between 300 - 450 (maximum allowed seconds)
long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS);
// Display the translation for each input text provided
System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
}
}
use of com.google.cloud.automl.v1beta1.GcsSource in project java-translate by googleapis.
the class CreateGlossary method createGlossary.
// Create a equivalent term sets glossary
// https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
public static void createGlossary(String projectId, String glossaryId, List<String> languageCodes, String inputUri) throws IOException, ExecutionException, InterruptedException {
// the "close" method on the client to safely clean up any remaining background resources.
try (TranslationServiceClient client = TranslationServiceClient.create()) {
// Supported Locations: `global`, [glossary location], or [model location]
// Glossaries must be hosted in `us-central1`
// Custom Models must use the same location as your model. (us-central1)
String location = "us-central1";
LocationName parent = LocationName.of(projectId, location);
GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
// Supported Languages: https://cloud.google.com/translate/docs/languages
Glossary.LanguageCodesSet languageCodesSet = Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build();
// Configure the source of the file from a GCS bucket
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
GlossaryInputConfig inputConfig = GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build();
Glossary glossary = Glossary.newBuilder().setName(glossaryName.toString()).setLanguageCodesSet(languageCodesSet).setInputConfig(inputConfig).build();
CreateGlossaryRequest request = CreateGlossaryRequest.newBuilder().setParent(parent.toString()).setGlossary(glossary).build();
// Start an asynchronous request
OperationFuture<Glossary, CreateGlossaryMetadata> future = client.createGlossaryAsync(request);
System.out.println("Waiting for operation to complete...");
Glossary response = future.get();
System.out.println("Created Glossary.");
System.out.printf("Glossary name: %s\n", response.getName());
System.out.printf("Entry count: %s\n", response.getEntryCount());
System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
}
}
use of com.google.cloud.automl.v1beta1.GcsSource in project java-translate by googleapis.
the class BatchTranslateDocument method batchTranslateDocument.
// Batch translate document
public static void batchTranslateDocument(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, int timeout) throws IOException, ExecutionException, InterruptedException, TimeoutException {
// refer to https://github.com/googleapis/java-translate/issues/613
TranslationServiceSettings.Builder translationServiceSettingsBuilder = TranslationServiceSettings.newBuilder();
TimedRetryAlgorithm timedRetryAlgorithm = OperationTimedPollAlgorithm.create(RetrySettings.newBuilder().setTotalTimeout(Duration.ofSeconds(1000)).build());
translationServiceSettingsBuilder.batchTranslateDocumentOperationSettings().setPollingAlgorithm(timedRetryAlgorithm);
TranslationServiceSettings translationServiceSettings = translationServiceSettingsBuilder.build();
// up any remaining background resources.
try (TranslationServiceClient client = TranslationServiceClient.create(translationServiceSettings)) {
// The ``global`` location is not supported for batch translation
LocationName parent = LocationName.of(projectId, "us-central1");
// Google Cloud Storage location for the source input. This can be a single file
// (for example, ``gs://translation-test/input.docx``) or a wildcard
// (for example, ``gs://translation-test/*``).
// Supported file types: https://cloud.google.com/translate/docs/supported-formats
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
BatchDocumentInputConfig batchDocumentInputConfig = BatchDocumentInputConfig.newBuilder().setGcsSource(gcsSource).build();
GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
BatchDocumentOutputConfig batchDocumentOutputConfig = BatchDocumentOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
BatchTranslateDocumentRequest request = BatchTranslateDocumentRequest.newBuilder().setParent(parent.toString()).setSourceLanguageCode(sourceLanguage).addTargetLanguageCodes(targetLanguage).addInputConfigs(batchDocumentInputConfig).setOutputConfig(batchDocumentOutputConfig).build();
OperationFuture<BatchTranslateDocumentResponse, BatchTranslateDocumentMetadata> future = client.batchTranslateDocumentAsync(request);
System.out.println("Waiting for operation to complete...");
// random number between timeout
long randomNumber = ThreadLocalRandom.current().nextInt(timeout, timeout + 100);
BatchTranslateDocumentResponse response = future.get(randomNumber, TimeUnit.SECONDS);
System.out.println("Total Pages: " + response.getTotalPages());
}
}
Aggregations