use of com.google.cloud.redis.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.redis.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.redis.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.redis.v1beta1.InputConfig in project java-document-ai by googleapis.
the class BatchParseFormBeta method batchParseFormGcs.
public static void batchParseFormGcs(String projectId, String location, String outputGcsBucketName, String outputGcsPrefix, String inputGcsUri) throws IOException, InterruptedException, ExecutionException, TimeoutException {
// the "close" method on the client to safely clean up any remaining background resources.
try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create()) {
// Configure the request for processing the PDF
String parent = String.format("projects/%s/locations/%s", projectId, location);
// Improve form parsing results by providing key-value pair hints.
// For each key hint, key is text that is likely to appear in the
// document as a form field name (i.e. "DOB").
// Value types are optional, but can be one or more of:
// ADDRESS, LOCATION, ORGANIZATION, PERSON, PHONE_NUMBER, ID,
// NUMBER, EMAIL, PRICE, TERMS, DATE, NAME
KeyValuePairHint keyValuePairHint = KeyValuePairHint.newBuilder().setKey("Phone").addValueTypes("PHONE_NUMBER").build();
KeyValuePairHint keyValuePairHint2 = KeyValuePairHint.newBuilder().setKey("Contact").addValueTypes("EMAIL").addValueTypes("NAME").build();
// Setting enabled=True enables form extraction
FormExtractionParams params = FormExtractionParams.newBuilder().setEnabled(true).addKeyValuePairHints(keyValuePairHint).addKeyValuePairHints(keyValuePairHint2).build();
GcsSource inputUri = GcsSource.newBuilder().setUri(inputGcsUri).build();
// mime_type can be application/pdf, image/tiff,
// and image/gif, or application/json
InputConfig config = InputConfig.newBuilder().setGcsSource(inputUri).setMimeType("application/pdf").build();
GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(String.format("gs://%s/%s", outputGcsBucketName, outputGcsPrefix)).build();
OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setPagesPerShard(1).build();
ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setFormExtractionParams(params).setInputConfig(config).setOutputConfig(outputConfig).build();
BatchProcessDocumentsRequest requests = BatchProcessDocumentsRequest.newBuilder().addRequests(request).setParent(parent).build();
// Batch process document using a long-running operation.
OperationFuture<BatchProcessDocumentsResponse, OperationMetadata> future = client.batchProcessDocumentsAsync(requests);
// Wait for operation to complete.
System.out.println("Waiting for operation to complete...");
future.get(360, TimeUnit.SECONDS);
System.out.println("Document processing complete.");
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Bucket bucket = storage.get(outputGcsBucketName);
// List all of the files in the Storage bucket.
Page<Blob> blobs = bucket.list(Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(outputGcsPrefix));
int idx = 0;
for (Blob blob : blobs.iterateAll()) {
if (!blob.isDirectory()) {
System.out.printf("Fetched file #%d\n", ++idx);
// Read the results
// Download and store json data in a temp file.
File tempFile = File.createTempFile("file", ".json");
Blob fileInfo = storage.get(BlobId.of(outputGcsBucketName, blob.getName()));
fileInfo.downloadTo(tempFile.toPath());
// Parse json file into Document.
FileReader reader = new FileReader(tempFile);
Document.Builder builder = Document.newBuilder();
JsonFormat.parser().merge(reader, builder);
Document document = builder.build();
// Get all of the document text as one big string.
String text = document.getText();
// Process the output.
if (document.getPagesCount() > 0) {
Document.Page page1 = document.getPages(0);
for (Document.Page.FormField field : page1.getFormFieldsList()) {
String fieldName = getText(field.getFieldName(), text);
String fieldValue = getText(field.getFieldValue(), text);
System.out.println("Extracted form fields pair:");
System.out.printf("\t(%s, %s))", fieldName, fieldValue);
}
}
// Clean up temp file.
tempFile.deleteOnExit();
}
}
}
}
use of com.google.cloud.redis.v1beta1.InputConfig in project java-document-ai by googleapis.
the class ParseFormBeta method parseForm.
public static void parseForm(String projectId, String location, String inputGcsUri) throws IOException, ExecutionException, InterruptedException {
// the "close" method on the client to safely clean up any remaining background resources.
try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create()) {
// Configure the request for processing the PDF
String parent = String.format("projects/%s/locations/%s", projectId, location);
// Improve form parsing results by providing key-value pair hints.
// For each key hint, key is text that is likely to appear in the
// document as a form field name (i.e. "DOB").
// Value types are optional, but can be one or more of:
// ADDRESS, LOCATION, ORGANIZATION, PERSON, PHONE_NUMBER, ID,
// NUMBER, EMAIL, PRICE, TERMS, DATE, NAME
KeyValuePairHint keyValuePairHint = KeyValuePairHint.newBuilder().setKey("Phone").addValueTypes("PHONE_NUMBER").build();
KeyValuePairHint keyValuePairHint2 = KeyValuePairHint.newBuilder().setKey("Contact").addValueTypes("EMAIL").addValueTypes("NAME").build();
// Setting enabled=True enables form extraction
FormExtractionParams params = FormExtractionParams.newBuilder().setEnabled(true).addKeyValuePairHints(keyValuePairHint).addKeyValuePairHints(keyValuePairHint2).build();
GcsSource uri = GcsSource.newBuilder().setUri(inputGcsUri).build();
// mime_type can be application/pdf, image/tiff,
// and image/gif, or application/json
InputConfig config = InputConfig.newBuilder().setGcsSource(uri).setMimeType("application/pdf").build();
ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setParent(parent).setFormExtractionParams(params).setInputConfig(config).build();
// Recognizes text entities in the PDF document
Document response = client.processDocument(request);
// Get all of the document text as one big string
String text = response.getText();
// Process the output
if (response.getPagesCount() > 0) {
Document.Page page1 = response.getPages(0);
for (Document.Page.FormField field : page1.getFormFieldsList()) {
String fieldName = getText(field.getFieldName(), text);
String fieldValue = getText(field.getFieldValue(), text);
System.out.println("Extracted form fields pair:");
System.out.printf("\t(%s, %s))", fieldName, fieldValue);
}
}
}
}
Aggregations