com.google.api.gax.longrunning.OperationFuture Java Examples

The following examples show how to use com.google.api.gax.longrunning.OperationFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UndeployModel.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void undeployModel(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    UndeployModelRequest request =
        UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
    OperationFuture<Empty, OperationMetadata> future = client.undeployModelAsync(request);

    future.get();
    System.out.println("Model undeployment finished");
  }
}
 
Example #2
Source File: AnnotateVideoFn.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Call the Video Intelligence Cloud AI service and return annotation results.
 *
 * @param elementURI This or elementContents is required. GCS address of video to be annotated
 * @param elementContents this or elementURI is required. Hex-encoded contents of video to be
 *     annotated
 * @param videoContext Optional context for video annotation.
 * @return
 */
List<VideoAnnotationResults> getVideoAnnotationResults(
    String elementURI, ByteString elementContents, VideoContext videoContext)
    throws InterruptedException, ExecutionException {
  AnnotateVideoRequest.Builder requestBuilder =
      AnnotateVideoRequest.newBuilder().addAllFeatures(featureList);
  if (elementURI != null) {
    requestBuilder.setInputUri(elementURI);
  } else if (elementContents != null) {
    requestBuilder.setInputContent(elementContents);
  } else {
    throw new IllegalArgumentException("Either elementURI or elementContents should be non-null");
  }
  if (videoContext != null) {
    requestBuilder.setVideoContext(videoContext);
  }
  AnnotateVideoRequest annotateVideoRequest = requestBuilder.build();
  OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> annotateVideoAsync =
      videoIntelligenceServiceClient.annotateVideoAsync(annotateVideoRequest);
  return annotateVideoAsync.get().getAnnotationResultsList();
}
 
Example #3
Source File: DeployModel.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void deployModel(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    DeployModelRequest request =
        DeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
    OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

    future.get();
    System.out.println("Model deployment finished");
  }
}
 
Example #4
Source File: QuickstartTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws IOException, InterruptedException, ExecutionException {
  blob.delete();
  bucket.delete();

  ClusterControllerSettings clusterControllerSettings =
      ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build();

  try (ClusterControllerClient clusterControllerClient =
      ClusterControllerClient.create(clusterControllerSettings)) {
    for (Cluster element :
        clusterControllerClient.listClusters(PROJECT_ID, REGION).iterateAll()) {
      if (element.getClusterName() == CLUSTER_NAME) {
        OperationFuture<Empty, ClusterOperationMetadata> deleteClusterAsyncRequest =
            clusterControllerClient.deleteClusterAsync(PROJECT_ID, REGION, CLUSTER_NAME);
        deleteClusterAsyncRequest.get();
        break;
      }
    }
  }
}
 
Example #5
Source File: SubmitHadoopFsJobTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException, ExecutionException, InterruptedException {
  bout = new ByteArrayOutputStream();
  System.setOut(new PrintStream(bout));

  ClusterControllerSettings clusterControllerSettings =
      ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build();

  try (ClusterControllerClient clusterControllerClient =
      ClusterControllerClient.create(clusterControllerSettings)) {
    // Create the Dataproc cluster.
    Cluster cluster = Cluster.newBuilder().setClusterName(CLUSTER_NAME).build();
    OperationFuture<Cluster, ClusterOperationMetadata> createClusterAsyncRequest =
        clusterControllerClient.createClusterAsync(PROJECT_ID, REGION, cluster);
    createClusterAsyncRequest.get();
  }
}
 
Example #6
Source File: DeployModel.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void deployModel(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    DeployModelRequest request =
        DeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
    OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

    future.get();
    System.out.println("Model deployment finished");
  }
}
 
Example #7
Source File: UndeployModel.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void undeployModel(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    UndeployModelRequest request =
        UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
    OperationFuture<Empty, OperationMetadata> future = client.undeployModelAsync(request);

    future.get();
    System.out.println("Model undeployment finished");
  }
}
 
Example #8
Source File: VisionObjectDetectionDeployModelNodeCount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void visionObjectDetectionDeployModelNodeCount(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    ImageObjectDetectionModelDeploymentMetadata metadata =
        ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
    DeployModelRequest request =
        DeployModelRequest.newBuilder()
            .setName(modelFullId.toString())
            .setImageObjectDetectionModelDeploymentMetadata(metadata)
            .build();
    OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

    future.get();
    System.out.println("Model deployment finished");
  }
}
 
Example #9
Source File: VisionClassificationDeployModelNodeCount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
static void visionClassificationDeployModelNodeCount(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
    ImageClassificationModelDeploymentMetadata metadata =
        ImageClassificationModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
    DeployModelRequest request =
        DeployModelRequest.newBuilder()
            .setName(modelFullId.toString())
            .setImageClassificationModelDeploymentMetadata(metadata)
            .build();
    OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);

    future.get();
    System.out.println("Model deployment finished");
  }
}
 
Example #10
Source File: DeleteGlossary.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void deleteGlossary(String projectId, String glossaryId)
    throws InterruptedException, ExecutionException, IOException {

  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // 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)
    GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
    DeleteGlossaryRequest request =
        DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

    // Start an asynchronous request
    OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future =
        client.deleteGlossaryAsync(request);

    System.out.println("Waiting for operation to complete...");
    DeleteGlossaryResponse response = future.get();
    System.out.format("Deleted Glossary: %s\n", response.getName());
  }
}
 
Example #11
Source File: Recognize.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Performs transcription on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote FLAC audio file to transcribe.
 */
public static void transcribeGcsWithAutomaticPunctuation(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {
    // Configure request with raw PCM audio
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .setEnableAutomaticPunctuation(true)
            .build();

    // Set the remote path for the audio file
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speechClient.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    // Just print the first result here.
    SpeechRecognitionResult result = response.get().getResultsList().get(0);

    // There can be several alternative transcripts for a given chunk of speech. Just use the
    // first (most likely) one here.
    SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);

    // Print out the result
    System.out.printf("Transcript : %s\n", alternative.getTranscript());
  }
}
 
Example #12
Source File: Recognize.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Transcribe a remote audio file with multi-language recognition
 *
 * @param gcsUri the path to the remote audio file
 */
public static void transcribeMultiLanguageGcs(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {

    ArrayList<String> languageList = new ArrayList<>();
    languageList.add("es-ES");
    languageList.add("en-US");

    // Configure request to enable multiple languages
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setSampleRateHertz(16000)
            .setLanguageCode("ja-JP")
            .addAllAlternativeLanguageCodes(languageList)
            .build();

    // Set the remote path for the audio file
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speechClient.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    for (SpeechRecognitionResult result : response.get().getResultsList()) {

      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);

      // Print out the result
      System.out.printf("Transcript : %s\n\n", alternative.getTranscript());
    }
  }
}
 
Example #13
Source File: ModelApi.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates using the AutoML client to create a model.
 *
 * @param projectId the Id of the project.
 * @param computeRegion the Region name.
 * @param dataSetId the Id of the dataset to which model is created.
 * @param modelName the Name of the model.
 */
public static void createModel(
    String projectId, String computeRegion, String dataSetId, String modelName)
    throws IOException, InterruptedException, ExecutionException {
  // Instantiates a client
  try (AutoMlClient client = AutoMlClient.create()) {

    // A resource that represents Google Cloud Platform location.
    LocationName projectLocation = LocationName.of(projectId, computeRegion);

    // Set model metadata.
    TranslationModelMetadata translationModelMetadata =
        TranslationModelMetadata.newBuilder().setBaseModel("").build();

    // Set model name, dataset and metadata.
    Model myModel =
        Model.newBuilder()
            .setDisplayName(modelName)
            .setDatasetId(dataSetId)
            .setTranslationModelMetadata(translationModelMetadata)
            .build();

    // Create a model with the model metadata in the region.
    OperationFuture<Model, OperationMetadata> response =
        client.createModelAsync(projectLocation, myModel);

    System.out.println(
        String.format(
            "Training operation name: %s", response.getInitialFuture().get().getName()));
    System.out.println("Training started...");
  }
}
 
Example #14
Source File: SubmitHadoopFsJobTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws IOException, InterruptedException, ExecutionException {

  ClusterControllerSettings clusterControllerSettings =
      ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build();

  try (ClusterControllerClient clusterControllerClient =
      ClusterControllerClient.create(clusterControllerSettings)) {
    OperationFuture<Empty, ClusterOperationMetadata> deleteClusterAsyncRequest =
        clusterControllerClient.deleteClusterAsync(PROJECT_ID, REGION, CLUSTER_NAME);
    deleteClusterAsyncRequest.get();
  }
}
 
Example #15
Source File: VisionObjectDetectionCreateModel.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void createModel(String projectId, String datasetId, String displayName)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // A resource that represents Google Cloud Platform location.
    LocationName projectLocation = LocationName.of(projectId, "us-central1");
    // Set model metadata.
    ImageObjectDetectionModelMetadata metadata =
        ImageObjectDetectionModelMetadata.newBuilder().build();
    Model model =
        Model.newBuilder()
            .setDisplayName(displayName)
            .setDatasetId(datasetId)
            .setImageObjectDetectionModelMetadata(metadata)
            .build();

    // Create a model with the model metadata in the region.
    OperationFuture<Model, OperationMetadata> future =
        client.createModelAsync(projectLocation, model);
    // OperationFuture.get() will block until the model is created, which may take several hours.
    // You can use OperationFuture.getInitialFuture to get a future representing the initial
    // response to the request, which contains information while the operation is in progress.
    System.out.format("Training operation name: %s\n", future.getInitialFuture().get().getName());
    System.out.println("Training started...");
  }
}
 
Example #16
Source File: BatchPredict.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void batchPredict(String projectId, String modelId, String inputUri, String outputUri)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (PredictionServiceClient client = PredictionServiceClient.create()) {
    // Get the full path of the model.
    ModelName name = ModelName.of(projectId, "us-central1", modelId);
    GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
    BatchPredictInputConfig inputConfig =
        BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();
    GcsDestination gcsDestination =
        GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
    BatchPredictOutputConfig outputConfig =
        BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
    BatchPredictRequest request =
        BatchPredictRequest.newBuilder()
            .setName(name.toString())
            .setInputConfig(inputConfig)
            .setOutputConfig(outputConfig)
            .build();

    OperationFuture<BatchPredictResult, OperationMetadata> future =
        client.batchPredictAsync(request);

    System.out.println("Waiting for operation to complete...");
    BatchPredictResult response = future.get();
    System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
  }
}
 
Example #17
Source File: ImportDataset.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void importDataset(String projectId, String datasetId, String path)
    throws IOException, ExecutionException, InterruptedException, TimeoutException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the complete path of the dataset.
    DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

    // Get multiple Google Cloud Storage URIs to import data from
    GcsSource gcsSource =
        GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

    // Import data from the input URI
    InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
    System.out.println("Processing import...");

    // Start the import job
    OperationFuture<Empty, OperationMetadata> operation =
        client.importDataAsync(datasetFullId, inputConfig);

    System.out.format("Operation name: %s%n", operation.getName());

    // If you want to wait for the operation to finish, adjust the timeout appropriately. The
    // operation will still run if you choose not to wait for it to complete. You can check the
    // status of your operation using the operation's name.
    Empty response = operation.get(45, TimeUnit.MINUTES);
    System.out.format("Dataset imported. %s%n", response);
  } catch (TimeoutException e) {
    System.out.println("The operation's polling period was not long enough.");
    System.out.println("You can use the Operation's name to get the current status.");
    System.out.println("The import job is still running and will complete as expected.");
    throw e;
  }
}
 
Example #18
Source File: PurgeProducts.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void purgeOrphanProducts(String projectId, String computeRegion) throws Exception {

    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // boolean force = true;

    try (ProductSearchClient client = ProductSearchClient.create()) {
      String parent = LocationName.format(projectId, computeRegion);

      // The purge operation is async.
      PurgeProductsRequest request =
          PurgeProductsRequest.newBuilder()
              .setDeleteOrphanProducts(true)
              // The operation is irreversible and removes multiple products.
              // The user is required to pass in force=True to actually perform the
              // purge.
              // If force is not set to True, the service raises an exception.
              .setForce(true)
              .setParent(parent)
              .build();

      OperationFuture response = client.purgeProductsAsync(request);
      response.getPollingFuture().get(180, TimeUnit.SECONDS);

      System.out.println("Orphan products deleted.");
    }
  }
 
Example #19
Source File: VisionObjectDetectionCreateDataset.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void createDataset(String projectId, String displayName)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // A resource that represents Google Cloud Platform location.
    LocationName projectLocation = LocationName.of(projectId, "us-central1");

    ImageObjectDetectionDatasetMetadata metadata =
        ImageObjectDetectionDatasetMetadata.newBuilder().build();
    Dataset dataset =
        Dataset.newBuilder()
            .setDisplayName(displayName)
            .setImageObjectDetectionDatasetMetadata(metadata)
            .build();
    OperationFuture<Dataset, OperationMetadata> future =
        client.createDatasetAsync(projectLocation, dataset);

    Dataset createdDataset = future.get();

    // Display the dataset information.
    System.out.format("Dataset name: %s\n", createdDataset.getName());
    // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
    // required for other methods.
    // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
    String[] names = createdDataset.getName().split("/");
    String datasetId = names[names.length - 1];
    System.out.format("Dataset id: %s\n", datasetId);
  }
}
 
Example #20
Source File: TranslateCreateDataset.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void createDataset(String projectId, String displayName)
    throws IOException, ExecutionException, InterruptedException {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // A resource that represents Google Cloud Platform location.
    LocationName projectLocation = LocationName.of(projectId, "us-central1");

    // Specify the source and target language.
    TranslationDatasetMetadata translationDatasetMetadata =
        TranslationDatasetMetadata.newBuilder()
            .setSourceLanguageCode("en")
            .setTargetLanguageCode("ja")
            .build();
    Dataset dataset =
        Dataset.newBuilder()
            .setDisplayName(displayName)
            .setTranslationDatasetMetadata(translationDatasetMetadata)
            .build();
    OperationFuture<Dataset, OperationMetadata> future =
        client.createDatasetAsync(projectLocation, dataset);

    Dataset createdDataset = future.get();

    // Display the dataset information.
    System.out.format("Dataset name: %s\n", createdDataset.getName());
    // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
    // required for other methods.
    // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
    String[] names = createdDataset.getName().split("/");
    String datasetId = names[names.length - 1];
    System.out.format("Dataset id: %s\n", datasetId);
  }
}
 
Example #21
Source File: Recognize.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Performs non-blocking speech recognition on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote LINEAR16 audio file to transcribe.
 */
public static void asyncRecognizeGcs(String gcsUri) throws Exception {
  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  try (SpeechClient speech = SpeechClient.create()) {

    // Configure remote file request for FLAC
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speech.longRunningRecognizeAsync(config, audio);
    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    for (SpeechRecognitionResult result : results) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
      System.out.printf("Transcription: %s\n", alternative.getTranscript());
    }
  }
}
 
Example #22
Source File: PurgeProductsInProductSet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void purgeProductsInProductSet(
    String projectId, String location, String productSetId) throws Exception {

  // String projectId = "YOUR_PROJECT_ID";
  // String location = "us-central1";
  // String productSetId = "YOUR_PRODUCT_SET_ID";
  // boolean force = true;

  try (ProductSearchClient client = ProductSearchClient.create()) {

    String parent = LocationName.format(projectId, location);
    ProductSetPurgeConfig productSetPurgeConfig =
        ProductSetPurgeConfig.newBuilder().setProductSetId(productSetId).build();

    PurgeProductsRequest request =
        PurgeProductsRequest.newBuilder()
            .setParent(parent)
            .setProductSetPurgeConfig(productSetPurgeConfig)
            // The operation is irreversible and removes multiple products.
            // The user is required to pass in force=True to actually perform the
            // purge.
            // If force is not set to True, the service raises an exception.
            .setForce(true)
            .build();

    OperationFuture<Empty, BatchOperationMetadata> response = client.purgeProductsAsync(request);
    response.getPollingFuture().get(180, TimeUnit.SECONDS);

    System.out.println("Products removed from product set.");
  }
}
 
Example #23
Source File: ObjectDetectionDeployModelNodeCount.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
static void objectDetectionDeployModelNodeCount(String projectId, String modelId)
    throws IOException, ExecutionException, InterruptedException {
  // String projectId = "YOUR_PROJECT_ID";
  // String modelId = "YOUR_MODEL_ID";

  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (AutoMlClient client = AutoMlClient.create()) {
    // Get the full path of the model.
    ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);

    // Set how many nodes the model is deployed on
    ImageObjectDetectionModelDeploymentMetadata deploymentMetadata =
        ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();

    DeployModelRequest request =
        DeployModelRequest.newBuilder()
            .setName(modelFullId.toString())
            .setImageObjectDetectionModelDeploymentMetadata(deploymentMetadata)
            .build();
    // Deploy the model
    OperationFuture<Empty, OperationMetadata> future = client.deployModelAsync(request);
    future.get();
    System.out.println("Model deployment on 2 nodes finished");
  }
}
 
Example #24
Source File: ImportProductSets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Import images of different products in the product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param gcsUri - Google Cloud Storage URI.Target files must be in Product Search CSV format.
 * @throws Exception - on client errors.
 */
public static void importProductSets(String projectId, String computeRegion, String gcsUri)
    throws Exception {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    Builder gcsSource = ImportProductSetsGcsSource.newBuilder().setCsvFileUri(gcsUri);

    // Set the input configuration along with Google Cloud Storage URI
    ImportProductSetsInputConfig inputConfig =
        ImportProductSetsInputConfig.newBuilder().setGcsSource(gcsSource).build();

    // Import the product sets from the input URI.
    OperationFuture<ImportProductSetsResponse, BatchOperationMetadata> response =
        client.importProductSetsAsync(formattedParent, inputConfig);

    System.out.println(String.format("Processing operation name: %s", response.getName()));
    ImportProductSetsResponse results = response.get();
    System.out.println("Processing done.");
    System.out.println("Results of the processing:");

    for (int i = 0; i < results.getStatusesCount(); i++) {
      System.out.println(
          String.format(
              "Status of processing line %s of the csv: %s", i, results.getStatuses(i)));
      // Check the status of reference image.
      if (results.getStatuses(i).getCode() == 0) {
        ReferenceImage referenceImage = results.getReferenceImages(i);
        System.out.println(referenceImage);
      } else {
        System.out.println("No reference image.");
      }
    }
  }
}
 
Example #25
Source File: SpannerDatabaseAdminTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void executeDdlStrings_createsDatabaseIfMissing() throws Exception {
	when(this.mockDatabasePage.getValues()).thenReturn(Arrays.asList(
			new Database(this.databaseId, State.READY, this.databaseAdminClient)));

	OperationFuture<Void, UpdateDatabaseDdlMetadata> mockFuture = mock(OperationFuture.class);
	when(this.databaseAdminClient.updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null)).thenReturn(mockFuture);
	when(mockFuture.get()).thenReturn(null);

	this.spannerDatabaseAdminTemplate.executeDdlStrings(this.ddlList, true);

	verify(this.databaseAdminClient, times(0)).createDatabase("fakeinstance", "fakedb", Arrays.asList("describe Something"));
	verify(this.databaseAdminClient).updateDatabaseDdl("fakeinstance", "fakedb", this.ddlList, null);
}
 
Example #26
Source File: ClientLibraryOperations.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Drops a single table.
 */
public void deleteSingleTable() {
  OperationFuture<Void, UpdateDatabaseDdlMetadata> ddlFuture =
      this.databaseAdminClient.updateDatabaseDdl(
          INSTANCE_NAME,
          DATABASE_NAME,
          Collections.singletonList("DROP TABLE " + AIRPORT_TABLE), null);

  try {
    ddlFuture.get();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #27
Source File: CreateCampaignExperiment.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an experiment by issuing an asynchronous operation and immediately blocking to get the
 * result.
 *
 * @param googleAdsClient the API client to use.
 * @param customerId the customer ID to operate on.
 * @param baseCampaignId the original campaign ID.
 * @param draftId the draft campaign ID.
 * @return a newly created experiment.
 */
private CreateCampaignExperimentMetadata createExperiment(
    GoogleAdsClient googleAdsClient, long customerId, long baseCampaignId, long draftId) {
  // Defines the experiment to be created.
  CampaignExperiment experiment =
      CampaignExperiment.newBuilder()
          .setCampaignDraft(
              StringValue.of(ResourceNames.campaignDraft(customerId, baseCampaignId, draftId)))
          .setName(StringValue.of("Campaign experiment #" + System.currentTimeMillis()))
          .setTrafficSplitPercent(Int64Value.of(50))
          .setTrafficSplitType(CampaignExperimentTrafficSplitType.RANDOM_QUERY)
          .build();

  // Creates an API service client.
  try (CampaignExperimentServiceClient campaignExperimentServiceClient =
      googleAdsClient.getLatestVersion().createCampaignExperimentServiceClient()) {
    // Issues the create request.
    OperationFuture<Empty, CreateCampaignExperimentMetadata> campaignExperimentAsync =
        campaignExperimentServiceClient.createCampaignExperimentAsync(
            String.valueOf(customerId), experiment);

    // Block on the long running (i.e. async) operation result.
    try {
      return campaignExperimentAsync.getMetadata().get();
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException("Create operation failed", e);
    }
  }
}
 
Example #28
Source File: AddCompleteCampaignsUsingMutateJob.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Polls the server until the mutate job execution finishes by setting the total time to wait
 * before time-out.
 *
 * @param operationResponse the operation response used to poll the server.
 */
private void pollMutateJob(OperationFuture operationResponse) {
  try {
    operationResponse.get(MAX_TOTAL_POLL_INTERVAL_SECONDS, TimeUnit.SECONDS);
  } catch (InterruptedException | ExecutionException | TimeoutException e) {
    System.err.printf("Failed polling the mutate job. Exception: %s%n", e);
    System.exit(1);
  }
}
 
Example #29
Source File: AddCompleteCampaignsUsingMutateJob.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Requests the API to run the mutate job for executing all uploaded mutate job operations.
 *
 * @param mutateJobServiceClient the mutate job service client.
 * @param mutateJobResourceName the resource name of mutate job to be run.
 * @return the operation response from running mutate job.
 */
private OperationFuture runMutateJob(
    MutateJobServiceClient mutateJobServiceClient, String mutateJobResourceName) {
  OperationFuture operationResponse =
      mutateJobServiceClient.runMutateJobAsync(mutateJobResourceName);
  System.out.printf(
      "Mutate job with resource name '%s' has been executed.%n", mutateJobResourceName);

  return operationResponse;
}
 
Example #30
Source File: Recognize.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Transcribe a remote audio file with multi-channel recognition
 *
 * @param gcsUri the path to the audio file
 */
public static void transcribeMultiChannelGcs(String gcsUri) throws Exception {

  try (SpeechClient speechClient = SpeechClient.create()) {

    // Configure request to enable multiple channels
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            .setSampleRateHertz(44100)
            .setAudioChannelCount(2)
            .setEnableSeparateRecognitionPerChannel(true)
            .build();

    // Set the remote path for the audio file
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speechClient.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }
    // Just print the first result here.
    for (SpeechRecognitionResult result : response.get().getResultsList()) {

      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);

      // Print out the result
      System.out.printf("Transcript : %s\n", alternative.getTranscript());
      System.out.printf("Channel Tag : %s\n\n", result.getChannelTag());
    }
  }
}