Search in sources :

Example 16 with SpeechRecognitionAlternative

use of com.google.cloud.videointelligence.v1.SpeechRecognitionAlternative in project java-speech by googleapis.

the class SpeechTranscribeMultiRegion method speechTranscribeMultiRegion.

/**
 * Transcribe a remote audio file with multi-channel recognition
 *
 * @param gcsUri the path to the audio file
 */
public static void speechTranscribeMultiRegion(String gcsUri) throws Exception {
    // Use the SpeechSettings to initialize the SpeechClient with the new endpoint.
    String endPoint = "eu-speech.googleapis.com:443";
    SpeechSettings speechSettings = SpeechSettings.newBuilder().setEndpoint(endPoint).build();
    // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
    try (SpeechClient speech = SpeechClient.create(speechSettings)) {
        // Configure remote file request
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.FLAC).setLanguageCode("en-US").setSampleRateHertz(16000).build();
        // Set the remote path for the audio file
        RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();
        // Use blocking call to get audio transcript
        RecognizeResponse response = speech.recognize(config, audio);
        List<SpeechRecognitionResult> results = response.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());
        }
    }
}
Also used : SpeechRecognitionAlternative(com.google.cloud.speech.v1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1.RecognitionAudio) RecognitionConfig(com.google.cloud.speech.v1.RecognitionConfig) SpeechSettings(com.google.cloud.speech.v1.SpeechSettings) SpeechClient(com.google.cloud.speech.v1.SpeechClient) RecognizeResponse(com.google.cloud.speech.v1.RecognizeResponse) SpeechRecognitionResult(com.google.cloud.speech.v1.SpeechRecognitionResult)

Example 17 with SpeechRecognitionAlternative

use of com.google.cloud.videointelligence.v1.SpeechRecognitionAlternative in project java-speech by googleapis.

the class TranscribeDiarization method transcribeDiarization.

// Transcribe the given audio file using speaker diarization.
static void transcribeDiarization(String fileName) throws IOException {
    Path path = Paths.get(fileName);
    byte[] content = Files.readAllBytes(path);
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SpeechClient client = SpeechClient.create()) {
        // Get the contents of the local audio file
        RecognitionAudio recognitionAudio = RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
        SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder().setEnableSpeakerDiarization(true).setMinSpeakerCount(2).setMaxSpeakerCount(2).build();
        // Configure request to enable Speaker diarization
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(RecognitionConfig.AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(8000).setDiarizationConfig(speakerDiarizationConfig).build();
        // Perform the transcription request
        RecognizeResponse recognizeResponse = client.recognize(config, recognitionAudio);
        // Speaker Tags are only included in the last result object, which has only one alternative.
        SpeechRecognitionAlternative alternative = recognizeResponse.getResults(recognizeResponse.getResultsCount() - 1).getAlternatives(0);
        // The alternative is made up of WordInfo objects that contain the speaker_tag.
        WordInfo wordInfo = alternative.getWords(0);
        int currentSpeakerTag = wordInfo.getSpeakerTag();
        // For each word, get all the words associated with one speaker, once the speaker changes,
        // add a new line with the new speaker and their spoken words.
        StringBuilder speakerWords = new StringBuilder(String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
        for (int i = 1; i < alternative.getWordsCount(); i++) {
            wordInfo = alternative.getWords(i);
            if (currentSpeakerTag == wordInfo.getSpeakerTag()) {
                speakerWords.append(" ");
                speakerWords.append(wordInfo.getWord());
            } else {
                speakerWords.append(String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
                currentSpeakerTag = wordInfo.getSpeakerTag();
            }
        }
        System.out.println(speakerWords.toString());
    }
}
Also used : Path(java.nio.file.Path) SpeechRecognitionAlternative(com.google.cloud.speech.v1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1.RecognitionAudio) SpeakerDiarizationConfig(com.google.cloud.speech.v1.SpeakerDiarizationConfig) RecognitionConfig(com.google.cloud.speech.v1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1.SpeechClient) RecognizeResponse(com.google.cloud.speech.v1.RecognizeResponse) WordInfo(com.google.cloud.speech.v1.WordInfo)

Example 18 with SpeechRecognitionAlternative

use of com.google.cloud.videointelligence.v1.SpeechRecognitionAlternative in project java-speech by googleapis.

the class TranscribeDiarizationGcs method transcribeDiarizationGcs.

// Transcribe the give gcs file using speaker diarization
public static void transcribeDiarizationGcs(String gcsUri) throws IOException, ExecutionException, InterruptedException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SpeechClient speechClient = SpeechClient.create()) {
        SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder().setEnableSpeakerDiarization(true).setMinSpeakerCount(2).setMaxSpeakerCount(2).build();
        // Configure request to enable Speaker diarization
        RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(RecognitionConfig.AudioEncoding.LINEAR16).setLanguageCode("en-US").setSampleRateHertz(8000).setDiarizationConfig(speakerDiarizationConfig).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> future = speechClient.longRunningRecognizeAsync(config, audio);
        System.out.println("Waiting for response...");
        // Speaker Tags are only included in the last result object, which has only one alternative.
        LongRunningRecognizeResponse response = future.get();
        SpeechRecognitionAlternative alternative = response.getResults(response.getResultsCount() - 1).getAlternatives(0);
        // The alternative is made up of WordInfo objects that contain the speaker_tag.
        WordInfo wordInfo = alternative.getWords(0);
        int currentSpeakerTag = wordInfo.getSpeakerTag();
        // For each word, get all the words associated with one speaker, once the speaker changes,
        // add a new line with the new speaker and their spoken words.
        StringBuilder speakerWords = new StringBuilder(String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
        for (int i = 1; i < alternative.getWordsCount(); i++) {
            wordInfo = alternative.getWords(i);
            if (currentSpeakerTag == wordInfo.getSpeakerTag()) {
                speakerWords.append(" ");
                speakerWords.append(wordInfo.getWord());
            } else {
                speakerWords.append(String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
                currentSpeakerTag = wordInfo.getSpeakerTag();
            }
        }
        System.out.println(speakerWords.toString());
    }
}
Also used : LongRunningRecognizeResponse(com.google.cloud.speech.v1.LongRunningRecognizeResponse) SpeechRecognitionAlternative(com.google.cloud.speech.v1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1.RecognitionAudio) SpeakerDiarizationConfig(com.google.cloud.speech.v1.SpeakerDiarizationConfig) RecognitionConfig(com.google.cloud.speech.v1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1.SpeechClient) LongRunningRecognizeMetadata(com.google.cloud.speech.v1.LongRunningRecognizeMetadata) WordInfo(com.google.cloud.speech.v1.WordInfo)

Example 19 with SpeechRecognitionAlternative

use of com.google.cloud.videointelligence.v1.SpeechRecognitionAlternative in project java-video-intelligence by googleapis.

the class Detect method speechTranscription.

// [START video_speech_transcription_gcs_beta]
/**
 * Transcribe speech from a video stored on GCS.
 *
 * @param gcsUri the path to the video file to analyze.
 */
public static void speechTranscription(String gcsUri) throws Exception {
    // Instantiate a com.google.cloud.videointelligence.v1p1beta1.VideoIntelligenceServiceClient
    try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
        // Set the language code
        SpeechTranscriptionConfig config = SpeechTranscriptionConfig.newBuilder().setLanguageCode("en-US").setEnableAutomaticPunctuation(true).build();
        // Set the video context with the above configuration
        VideoContext context = VideoContext.newBuilder().setSpeechTranscriptionConfig(config).build();
        // Create the request
        AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder().setInputUri(gcsUri).addFeatures(Feature.SPEECH_TRANSCRIPTION).setVideoContext(context).build();
        // asynchronously perform speech transcription on videos
        OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> response = client.annotateVideoAsync(request);
        System.out.println("Waiting for operation to complete...");
        // Display the results
        for (VideoAnnotationResults results : response.get(300, TimeUnit.SECONDS).getAnnotationResultsList()) {
            for (SpeechTranscription speechTranscription : results.getSpeechTranscriptionsList()) {
                try {
                    // Print the transcription
                    if (speechTranscription.getAlternativesCount() > 0) {
                        SpeechRecognitionAlternative alternative = speechTranscription.getAlternatives(0);
                        System.out.printf("Transcript: %s\n", alternative.getTranscript());
                        System.out.printf("Confidence: %.2f\n", alternative.getConfidence());
                        System.out.println("Word level information:");
                        for (WordInfo wordInfo : alternative.getWordsList()) {
                            double startTime = wordInfo.getStartTime().getSeconds() + wordInfo.getStartTime().getNanos() / 1e9;
                            double endTime = wordInfo.getEndTime().getSeconds() + wordInfo.getEndTime().getNanos() / 1e9;
                            System.out.printf("\t%4.2fs - %4.2fs: %s\n", startTime, endTime, wordInfo.getWord());
                        }
                    } else {
                        System.out.println("No transcription found");
                    }
                } catch (IndexOutOfBoundsException ioe) {
                    System.out.println("Could not retrieve frame: " + ioe.getMessage());
                }
            }
        }
    }
}
Also used : AnnotateVideoRequest(com.google.cloud.videointelligence.v1p1beta1.AnnotateVideoRequest) VideoContext(com.google.cloud.videointelligence.v1p1beta1.VideoContext) VideoIntelligenceServiceClient(com.google.cloud.videointelligence.v1p1beta1.VideoIntelligenceServiceClient) AnnotateVideoProgress(com.google.cloud.videointelligence.v1p1beta1.AnnotateVideoProgress) SpeechRecognitionAlternative(com.google.cloud.videointelligence.v1p1beta1.SpeechRecognitionAlternative) SpeechTranscriptionConfig(com.google.cloud.videointelligence.v1p1beta1.SpeechTranscriptionConfig) VideoAnnotationResults(com.google.cloud.videointelligence.v1p1beta1.VideoAnnotationResults) SpeechTranscription(com.google.cloud.videointelligence.v1p1beta1.SpeechTranscription) WordInfo(com.google.cloud.videointelligence.v1p1beta1.WordInfo) AnnotateVideoResponse(com.google.cloud.videointelligence.v1p1beta1.AnnotateVideoResponse)

Example 20 with SpeechRecognitionAlternative

use of com.google.cloud.videointelligence.v1.SpeechRecognitionAlternative in project google-cloud-java by googleapis.

the class RecognizeSpeech method main.

public static void main(String... args) throws Exception {
    // Instantiates a client
    SpeechClient speech = SpeechClient.create();
    // The path to the audio file to transcribe
    // for example "./resources/audio.raw";
    String fileName = "your/speech/audio/file.raw";
    // Reads the audio file into memory
    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);
    ByteString audioBytes = ByteString.copyFrom(data);
    // Builds the sync recognize request
    RecognitionConfig config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setSampleRateHertz(16000).setLanguageCode("en-US").build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
    // Performs speech recognition on the audio file
    RecognizeResponse response = speech.recognize(config, audio);
    List<SpeechRecognitionResult> results = response.getResultsList();
    for (SpeechRecognitionResult result : results) {
        List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
        for (SpeechRecognitionAlternative alternative : alternatives) {
            System.out.printf("Transcription: %s%n", alternative.getTranscript());
        }
    }
    speech.close();
}
Also used : Path(java.nio.file.Path) SpeechRecognitionAlternative(com.google.cloud.speech.v1.SpeechRecognitionAlternative) RecognitionAudio(com.google.cloud.speech.v1.RecognitionAudio) ByteString(com.google.protobuf.ByteString) RecognitionConfig(com.google.cloud.speech.v1.RecognitionConfig) SpeechClient(com.google.cloud.speech.v1.SpeechClient) RecognizeResponse(com.google.cloud.speech.v1.RecognizeResponse) ByteString(com.google.protobuf.ByteString) SpeechRecognitionResult(com.google.cloud.speech.v1.SpeechRecognitionResult)

Aggregations

RecognitionConfig (com.google.cloud.speech.v1.RecognitionConfig)24 SpeechClient (com.google.cloud.speech.v1.SpeechClient)24 SpeechRecognitionAlternative (com.google.cloud.speech.v1.SpeechRecognitionAlternative)24 Path (java.nio.file.Path)23 RecognitionConfig (com.google.cloud.speech.v1p1beta1.RecognitionConfig)22 SpeechClient (com.google.cloud.speech.v1p1beta1.SpeechClient)22 SpeechRecognitionAlternative (com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative)22 RecognitionAudio (com.google.cloud.speech.v1.RecognitionAudio)21 RecognitionAudio (com.google.cloud.speech.v1p1beta1.RecognitionAudio)20 SpeechRecognitionResult (com.google.cloud.speech.v1.SpeechRecognitionResult)19 SpeechRecognitionResult (com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult)18 LongRunningRecognizeResponse (com.google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse)17 StreamingRecognitionConfig (com.google.cloud.speech.v1.StreamingRecognitionConfig)16 LongRunningRecognizeResponse (com.google.cloud.speech.v1.LongRunningRecognizeResponse)14 RecognizeResponse (com.google.cloud.speech.v1.RecognizeResponse)14 RecognizeResponse (com.google.cloud.speech.v1p1beta1.RecognizeResponse)12 ByteString (com.google.protobuf.ByteString)12 StreamingRecognizeResponse (com.google.cloud.speech.v1.StreamingRecognizeResponse)10 StreamingRecognitionConfig (com.google.cloud.speech.v1p1beta1.StreamingRecognitionConfig)10 LongRunningRecognizeMetadata (com.google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata)8