use of com.google.cloud.datalabeling.v1beta1.InputConfig 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.datalabeling.v1beta1.InputConfig 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.datalabeling.v1beta1.InputConfig in project java-datalabeling by googleapis.
the class LabelVideoIT method setUp.
@Before
public void setUp() {
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try (DataLabelingServiceClient dataLabelingServiceClient = DataLabelingServiceClient.create()) {
// Create the dataset
CreateDataset.createDataset(PROJECT_ID, datasetName);
ProjectName projectName = ProjectName.of(PROJECT_ID);
// Get the Dataset
ListDatasetsRequest datasetsRequest = ListDatasetsRequest.newBuilder().setParent(projectName.toString()).build();
ListDatasetsPagedResponse datasetsResponse = dataLabelingServiceClient.listDatasets(datasetsRequest);
for (Dataset returnedDataset : datasetsResponse.getPage().iterateAll()) {
if (returnedDataset.getDisplayName().equals("LABEL_VIDEO_DATASET_NAME")) {
dataset = returnedDataset;
}
}
// Import the images
// ImportData.importData(dataset.getName(), DATASET_GCS_SOURCE_URI);
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(DATASET_GCS_SOURCE_URI).setMimeType("text/csv").build();
InputConfig inputConfig = InputConfig.newBuilder().setDataType(// DataTypes: AUDIO, IMAGE, VIDEO, TEXT
DataType.VIDEO).setGcsSource(gcsSource).build();
ImportDataRequest importDataRequest = ImportDataRequest.newBuilder().setName(dataset.getName()).setInputConfig(inputConfig).build();
ImportDataOperationResponse response = dataLabelingServiceClient.importDataAsync(importDataRequest).get();
System.out.format("Imported items: %d\n", response.getImportCount());
// Create the instruction
CreateInstruction.createInstruction(PROJECT_ID, INSTRUCTION_GCS_SOURCE_URI);
// Create the annotation spec set
CreateAnnotationSpecSet.createAnnotationSpecSet(PROJECT_ID);
// Get the instruction
ListInstructionsRequest instructionsRequest = ListInstructionsRequest.newBuilder().setParent(projectName.toString()).build();
ListInstructionsPagedResponse instructionsResponse = dataLabelingServiceClient.listInstructions(instructionsRequest);
for (Instruction returnedInstruction : instructionsResponse.getPage().iterateAll()) {
if (returnedInstruction.getDisplayName().equals("YOUR_INSTRUCTION_DISPLAY_NAME")) {
instruction = returnedInstruction;
}
}
// Get the annotation spec set
ListAnnotationSpecSetsRequest annotationRequest = ListAnnotationSpecSetsRequest.newBuilder().setParent(projectName.toString()).build();
ListAnnotationSpecSetsPagedResponse annotationsResponse = dataLabelingServiceClient.listAnnotationSpecSets(annotationRequest);
for (AnnotationSpecSet returnedAnnotation : annotationsResponse.getPage().iterateAll()) {
if (returnedAnnotation.getDisplayName().equals("YOUR_ANNOTATION_SPEC_SET_DISPLAY_NAME")) {
annotationSpecSet = returnedAnnotation;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.google.cloud.datalabeling.v1beta1.InputConfig in project java-datalabeling by googleapis.
the class ImportData method importData.
// Import data to an existing dataset.
static void importData(String datasetName, String gcsSourceUri) throws IOException {
// String datasetName = DataLabelingServiceClient.formatDatasetName(
// "YOUR_PROJECT_ID", "YOUR_DATASETS_UUID");
// String gcsSourceUri = "gs://YOUR_BUCKET_ID/path_to_data";
// [END datalabeling_import_data_beta]
String endpoint = System.getenv("DATALABELING_ENDPOINT");
if (endpoint == null) {
endpoint = DataLabelingServiceSettings.getDefaultEndpoint();
}
// [START datalabeling_import_data_beta]
DataLabelingServiceSettings settings = DataLabelingServiceSettings.newBuilder().setEndpoint(endpoint).build();
try (DataLabelingServiceClient dataLabelingServiceClient = DataLabelingServiceClient.create(settings)) {
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(gcsSourceUri).setMimeType("text/csv").build();
InputConfig inputConfig = InputConfig.newBuilder().setDataType(// DataTypes: AUDIO, IMAGE, VIDEO, TEXT
DataType.IMAGE).setGcsSource(gcsSource).build();
ImportDataRequest importDataRequest = ImportDataRequest.newBuilder().setName(datasetName).setInputConfig(inputConfig).build();
OperationFuture<ImportDataOperationResponse, ImportDataOperationMetadata> operation = dataLabelingServiceClient.importDataAsync(importDataRequest);
ImportDataOperationResponse response = operation.get();
System.out.format("Imported items: %d\n", response.getImportCount());
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
use of com.google.cloud.datalabeling.v1beta1.InputConfig 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());
}
}
Aggregations