Search in sources :

Example 1 with DetectLanguageResponse

use of com.google.cloud.translate.v3.DetectLanguageResponse in project google-cloud-java by GoogleCloudPlatform.

the class TranslateSnippetsBeta method detectLanguageOfText.

// [END translate_list_language_names_beta]
/**
 * Detects the language of a given text.
 *
 * @param projectId - Id of the project.
 * @param location - location name.
 * @param text - Text for detection
 */
// [START translate_detect_language_beta]
static DetectLanguageResponse detectLanguageOfText(String projectId, String location, String text) {
    try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
        LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build();
        DetectLanguageRequest detectLanguageRequest = DetectLanguageRequest.newBuilder().setParent(locationName.toString()).setMimeType("text/plain").setContent(text).build();
        // Call the API
        DetectLanguageResponse response = translationServiceClient.detectLanguage(detectLanguageRequest);
        System.out.format("Detected Language Code: %s", response.getLanguages(0).getLanguageCode());
        return response;
    } catch (Exception e) {
        throw new RuntimeException("Couldn't create client.", e);
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3beta1.TranslationServiceClient) DetectLanguageResponse(com.google.cloud.translate.v3beta1.DetectLanguageResponse) DetectLanguageRequest(com.google.cloud.translate.v3beta1.DetectLanguageRequest) LocationName(com.google.cloud.translate.v3beta1.LocationName)

Example 2 with DetectLanguageResponse

use of com.google.cloud.translate.v3.DetectLanguageResponse in project java-docs-samples by GoogleCloudPlatform.

the class OcrProcessImage method detectText.

// [END functions_ocr_process]
// [START functions_ocr_detect]
private void detectText(String bucket, String filename) {
    logger.info("Looking for text in image " + filename);
    List<AnnotateImageRequest> visionRequests = new ArrayList<>();
    String gcsPath = String.format("gs://%s/%s", bucket, filename);
    ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature textFeature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
    AnnotateImageRequest visionRequest = AnnotateImageRequest.newBuilder().addFeatures(textFeature).setImage(img).build();
    visionRequests.add(visionRequest);
    // Detect text in an image using the Cloud Vision API
    AnnotateImageResponse visionResponse;
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        visionResponse = client.batchAnnotateImages(visionRequests).getResponses(0);
        if (visionResponse == null || !visionResponse.hasFullTextAnnotation()) {
            logger.info(String.format("Image %s contains no text", filename));
            return;
        }
        if (visionResponse.hasError()) {
            // Log error
            logger.log(Level.SEVERE, "Error in vision API call: " + visionResponse.getError().getMessage());
            return;
        }
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a Cloud Function)
        logger.log(Level.SEVERE, "Error detecting text: " + e.getMessage(), e);
        return;
    }
    String text = visionResponse.getFullTextAnnotation().getText();
    logger.info("Extracted text from image: " + text);
    // Detect language using the Cloud Translation API
    DetectLanguageRequest languageRequest = DetectLanguageRequest.newBuilder().setParent(LOCATION_NAME).setMimeType("text/plain").setContent(text).build();
    DetectLanguageResponse languageResponse;
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
        languageResponse = client.detectLanguage(languageRequest);
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a function)
        logger.log(Level.SEVERE, "Error detecting language: " + e.getMessage(), e);
        return;
    }
    if (languageResponse.getLanguagesCount() == 0) {
        logger.info("No languages were detected for text: " + text);
        return;
    }
    String languageCode = languageResponse.getLanguages(0).getLanguageCode();
    logger.info(String.format("Detected language %s for file %s", languageCode, filename));
    // Send a Pub/Sub translation request for every language we're going to translate to
    for (String targetLanguage : TO_LANGS) {
        logger.info("Sending translation request for language " + targetLanguage);
        OcrTranslateApiMessage message = new OcrTranslateApiMessage(text, filename, targetLanguage);
        ByteString byteStr = ByteString.copyFrom(message.toPubsubData());
        PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
        try {
            publisher.publish(pubsubApiMessage).get();
        } catch (InterruptedException | ExecutionException e) {
            // Log error
            logger.log(Level.SEVERE, "Error publishing translation request: " + e.getMessage(), e);
            return;
        }
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) DetectLanguageResponse(com.google.cloud.translate.v3.DetectLanguageResponse) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) DetectLanguageRequest(com.google.cloud.translate.v3.DetectLanguageRequest) PubsubMessage(com.google.pubsub.v1.PubsubMessage) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with DetectLanguageResponse

use of com.google.cloud.translate.v3.DetectLanguageResponse in project java-translate by googleapis.

the class DetectLanguage method detectLanguage.

// Detecting the language of a text string
public static void detectLanguage(String projectId, String text) throws IOException {
    // 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)
        LocationName parent = LocationName.of(projectId, "global");
        // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
        DetectLanguageRequest request = DetectLanguageRequest.newBuilder().setParent(parent.toString()).setMimeType("text/plain").setContent(text).build();
        DetectLanguageResponse response = client.detectLanguage(request);
        // The most probable language is first.
        for (DetectedLanguage language : response.getLanguagesList()) {
            // The language detected
            System.out.printf("Language code: %s\n", language.getLanguageCode());
            // Confidence of detection result for this language
            System.out.printf("Confidence: %s\n", language.getConfidence());
        }
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) DetectLanguageResponse(com.google.cloud.translate.v3.DetectLanguageResponse) DetectedLanguage(com.google.cloud.translate.v3.DetectedLanguage) DetectLanguageRequest(com.google.cloud.translate.v3.DetectLanguageRequest) LocationName(com.google.cloud.translate.v3.LocationName)

Aggregations

DetectLanguageRequest (com.google.cloud.translate.v3.DetectLanguageRequest)2 DetectLanguageResponse (com.google.cloud.translate.v3.DetectLanguageResponse)2 TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)2 DetectedLanguage (com.google.cloud.translate.v3.DetectedLanguage)1 LocationName (com.google.cloud.translate.v3.LocationName)1 DetectLanguageRequest (com.google.cloud.translate.v3beta1.DetectLanguageRequest)1 DetectLanguageResponse (com.google.cloud.translate.v3beta1.DetectLanguageResponse)1 LocationName (com.google.cloud.translate.v3beta1.LocationName)1 TranslationServiceClient (com.google.cloud.translate.v3beta1.TranslationServiceClient)1 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)1 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)1 Feature (com.google.cloud.vision.v1.Feature)1 Image (com.google.cloud.vision.v1.Image)1 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)1 ImageSource (com.google.cloud.vision.v1.ImageSource)1 ByteString (com.google.protobuf.ByteString)1 PubsubMessage (com.google.pubsub.v1.PubsubMessage)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1