/****************************************************************************************** Copyright (C) 2019 Gaman SP z o.o Online library help: https://gaman-gt.com/solutions/google_cloud_voice_api/javadoc/index.html If presented solution interested you, you have questions or ideas how we can improve this article feel free to contact us using the following email addresses. Our team is always happy to answer your questions and help you with your deployment. Contact us using following email addresses: General, Sales mailbox (info@gaman-gt.com) Support mailbox (support@gaman-gt.com) To find out more about Gaman Team and our project please visit our Website: https://gaman-gt.com BEFOR YOU BEGIN: - Replace ENTER YOUR GOOGLE CLOUD API KEY HERE with your private Google Cloud API key ******************************************************************************************/ package org.gaman.googlecloud; import java.net.URISyntaxException; import org.gaman.googlecloud.api.speech.RecognizeRequest; import org.gaman.googlecloud.api.speech.RecognizeResponse; import org.gaman.googlecloud.api.speech.objects.SpeechContext; import org.gaman.googlecloud.api.exceptions.GoogleCloudApiException; import org.gaman.googlecloud.api.operations.GetOperationRequest; import org.gaman.googlecloud.api.operations.GetOperationResponse; import org.gaman.googlecloud.api.operations.ListOperationsRequest; import org.gaman.googlecloud.api.operations.ListOperationsResponse; import org.gaman.googlecloud.api.speech.LongRunningRecognizeResponse; import org.gaman.googlecloud.api.speech.objects.SpeechContexts; import org.gaman.googlecloud.api.speech.objects.SpeechRecognitionAlternative; import org.gaman.googlecloud.api.speech.objects.WordInfo; import org.gaman.googlecloud.api.text.SynthesizeRequest; import org.gaman.googlecloud.api.text.SynthesizeResponse; import org.gaman.googlecloud.api.text.objects.AudioConfig; import org.gaman.googlecloud.api.text.objects.SynthesisInput; import org.gaman.googlecloud.api.text.objects.VoiceSelectionParams; import org.gaman.googlecloud.api.util.GoogleCloudHelper; import org.gaman.googlecloud.api.util.GoogleCloudHelper.AudioEffectsProfile; import org.gaman.googlecloud.api.util.GoogleCloudHelper.AudioEncoding_ASR; import org.gaman.googlecloud.api.voices.ListVoicesRequest; import org.gaman.googlecloud.api.voices.ListVoicesResponse; import org.junit.Test; import static org.junit.Assert.*; public class ApiTest { protected enum RecognitionSourceType {File, URI }; protected static String googleCloudApiKey = ""; protected Api api = null; // ENABLE TESTS // -- Operations protected boolean ENABLE_TEST_OPERATIONS_GET = false; protected boolean ENABLE_TEST_OPERATIONS_LIST = false; // -- Speech protected boolean ENABLE_TEST_SPEECH_LONG_RUNNING_RECOGNIZE = false; protected boolean ENABLE_TEST_SPEECH_RECOGNIZE = false; // -- Text protected boolean ENABLE_TEST_TEXT_SYNTHESIZE = false; // -- Voices protected boolean ENABLE_TEST_VOICES_LIST = true; // INPUT // Operations Get protected static String GET_name = "4090587238162913762"; // Speech Recognize protected static RecognitionSourceType RECOGNIZE_recognitionSource = RecognitionSourceType.File; protected static String RECOGNIZE_fileSamplePath = "C:\\Temp\\WAV\\read_past.wav"; //protected static String RECOGNIZE_fileSamplePath = "C:\\Temp\\WAV\\fuck.wav"; protected static String RECOGNIZE_fileSampleUri = "http://www.signalogic.com/melp/EngSamples/Orig/male.wav"; // -- Text protected static String SYNTHESIZE_text = "To jest pierwszy test"; protected static String SYNTHESIZE_ssml = ""; protected static int SYNTHESIZE_sampleRateHertz = 8000; protected static AudioEffectsProfile[] SYNTHESIZE_audioEffectsProfile = { AudioEffectsProfile.TELEPHONY_CLASS_APPLICATION }; protected static String SYNTHESIZE_filePath = "C:\\Temp\\WAV\\"; // ----------------------------------------------------------------------------- // Konstruktor public ApiTest() { try { this.api = new Api(googleCloudApiKey); } catch (URISyntaxException initException) { StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = initException.getStackTrace(); sb.append(initException.getClass().getName()).append(": ").append(initException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } } // ----------------------------------------------------------------------------- // TESTY //---------- OPERATIONS @Test public void operations_get() { if (!ENABLE_TEST_OPERATIONS_GET) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("OPERATIONS GET TEST"); if (this.api != null) { GetOperationRequest getRequest = new GetOperationRequest(GET_name); // API Call GetOperationResponse getResponse = this.api.operations_get(getRequest); // Response content System.out.println("Response JSON: " + getResponse.getRawData()); // Parse errors if (getResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(getResponse.getParseWarningMessage()); } } } catch (GoogleCloudApiException googleCloudException) { System.out.println("--------------------"); System.out.println("Operations Get exception - Google api exception"); System.out.println("Code: " + ((Integer)googleCloudException.getCode()).toString()); System.out.println("Message: " + googleCloudException.getMessage()); System.out.println("Status: " + googleCloudException.getStatus()); } catch (Exception listException) { System.out.println("--------------------"); System.out.println("Operations Get exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = listException.getStackTrace(); sb.append(listException.getClass().getName()).append(": ").append(listException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } @Test public void operations_list() { if (!ENABLE_TEST_OPERATIONS_LIST) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("OPERATIONS LIST TEST"); if (this.api != null) { ListOperationsRequest listRequest = new ListOperationsRequest(); // API Call ListOperationsResponse listResponse = this.api.operations_list(listRequest); // Response content System.out.println("Response JSON: " + listResponse.getRawData()); // Parse errors if (listResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(listResponse.getParseWarningMessage()); } } } catch (GoogleCloudApiException googleCloudException) { System.out.println("--------------------"); System.out.println("Operations List exception - Google api exception"); System.out.println("Code: " + ((Integer)googleCloudException.getCode()).toString()); System.out.println("Message: " + googleCloudException.getMessage()); System.out.println("Status: " + googleCloudException.getStatus()); } catch (Exception listException) { System.out.println("--------------------"); System.out.println("Operations List exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = listException.getStackTrace(); sb.append(listException.getClass().getName()).append(": ").append(listException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } //-------------- SPEECH @Test public void speech_longRunningRecognize() { if (!ENABLE_TEST_SPEECH_LONG_RUNNING_RECOGNIZE) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("SPEECH LONG RUNNING RECOGNIZE TEST"); if (this.api != null) { RecognizeRequest recognizeRequest = new RecognizeRequest(); // Config // encoding //recognizeRequest.getConfig().setEncoding(AudioEncoding.LINEAR16); // sample rate //recognizeRequest.getConfig().setSampleRateHertz(24000); // language code //recognizeRequest.getConfig().setLanguageCode("en-US"); //recognizeRequest.getConfig().setLanguageCode(GoogleCloudHelper.LanguageCode.de_DE); // max alternatives //recognizeRequest.getConfig().setMaxAlternatives(5); // profanity filter //recognizeRequest.getConfig().setProfanityFilter(false); // speech contexts SpeechContext speachContexts = new SpeechContext(new String[] {"he", "has write"}); //recognizeRequest.getConfig().setSpeechContexts(speachContexts); // word time offsets //recognizeRequest.getConfig().setEnableWordTimeOffsets(true); // Audio switch (RECOGNIZE_recognitionSource) { case URI: recognizeRequest.getAudio().setUri(RECOGNIZE_fileSampleUri); break; case File: default: recognizeRequest.getAudio().setContentPath(RECOGNIZE_fileSamplePath); break; } // Request content System.out.println("Request JSON: " + recognizeRequest.toJson()); System.out.println(""); System.out.println("------------------------------------------------------------------------------------------"); System.out.println(""); // API Call LongRunningRecognizeResponse longRunningRecognizeResponse = this.api.speech_longRunningRecognize(recognizeRequest); // Response content System.out.println("Response JSON: " + longRunningRecognizeResponse.getRawData()); // Parse errors if (longRunningRecognizeResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(longRunningRecognizeResponse.getParseWarningMessage()); } // Response from objects System.out.println("------------------------------------------------------------------------------------------"); System.out.println("Response pulled from object"); } else { System.out.println("Api object is null - test skipped."); } } catch (GoogleCloudApiException googleCloudException) { System.out.println("--------------------"); System.out.println("Speech Long Running Recognize exception - Google api exception"); System.out.println("Code: " + ((Integer)googleCloudException.getCode()).toString()); System.out.println("Message: " + googleCloudException.getMessage()); System.out.println("Status: " + googleCloudException.getStatus()); } catch (Exception recognizeException) { System.out.println("--------------------"); System.out.println("Speech Long Running Recognize exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = recognizeException.getStackTrace(); sb.append(recognizeException.getClass().getName()).append(": ").append(recognizeException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } @Test public void speech_recognize() { if (!ENABLE_TEST_SPEECH_RECOGNIZE) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("SPEECH RECOGNIZE TEST"); if (this.api != null) { RecognizeRequest recognizeRequest = new RecognizeRequest(); // Config // encoding recognizeRequest.getConfig().setEncoding(AudioEncoding_ASR.LINEAR16); // sample rate recognizeRequest.getConfig().setSampleRateHertz(24000); // language code recognizeRequest.getConfig().setLanguageCode("en-US"); //recognizeRequest.getConfig().setLanguageCode(GoogleCloudHelper.LanguageCode.de_DE); // max alternatives recognizeRequest.getConfig().setMaxAlternatives(5); // profanity filter recognizeRequest.getConfig().setProfanityFilter(false); // speech contexts SpeechContexts speachContexts = new SpeechContexts(); SpeechContext speachContext = new SpeechContext(new String[] {"he", "has write"}); speachContexts.add(speachContext); recognizeRequest.getConfig().setSpeechContexts(speachContexts); // word time offsets recognizeRequest.getConfig().setEnableWordTimeOffsets(true); // Audio switch (RECOGNIZE_recognitionSource) { case URI: recognizeRequest.getAudio().setUri(RECOGNIZE_fileSampleUri); break; case File: default: recognizeRequest.getAudio().setContentPath(RECOGNIZE_fileSamplePath); break; } // Request content System.out.println("Request JSON: " + recognizeRequest.toJson()); System.out.println(""); System.out.println("------------------------------------------------------------------------------------------"); System.out.println(""); // API Call RecognizeResponse recognizeResponse = this.api.speech_recognize(recognizeRequest); // Response content System.out.println("Response JSON: " + recognizeResponse.getRawData()); // Parse errors if (recognizeResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(recognizeResponse.getParseWarningMessage()); } // Response from objects System.out.println("------------------------------------------------------------------------------------------"); System.out.println("Response pulled from object"); // Restore data for (SpeechRecognitionAlternative alternative : recognizeResponse.getResults().get(0).getAlternatives()) { System.out.println("--------------------"); System.out.println("Transcript: " + alternative.getTranscript()); System.out.println("Confidence: " + alternative.getConfidence()); if (alternative.getWords() != null) for (WordInfo wordInfo : alternative.getWords()) System.out.println("WordInfo: Word: " + wordInfo.getWord() + ", StartTime(S): " + wordInfo.getStartTimeString() + ", StartTime(F): " + wordInfo.getStartTime() + ", EndTime(S): " + wordInfo.getEndTimeString() + ", EndTime(F): " + wordInfo.getEndTime()); } } else { System.out.println("Api object is null - test skipped."); } } catch (GoogleCloudApiException googleCloudException) { System.out.println("--------------------"); System.out.println("Speech Recognize exception - Google api exception"); System.out.println("Code: " + ((Integer)googleCloudException.getCode()).toString()); System.out.println("Message: " + googleCloudException.getMessage()); System.out.println("Status: " + googleCloudException.getStatus()); } catch (Exception recognizeException) { System.out.println("--------------------"); System.out.println("Speech Recognize exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = recognizeException.getStackTrace(); sb.append(recognizeException.getClass().getName()).append(": ").append(recognizeException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } //------ TEXT TO SPEECH @Test public void text_synthesize() { if (!ENABLE_TEST_TEXT_SYNTHESIZE) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("TEXT SYNTHESIZE TEST"); if (this.api != null) { SynthesizeRequest synthesizeRequest = new SynthesizeRequest(); // Config // SynthesisInput SynthesisInput input = new SynthesisInput(); // Text input.setText(SYNTHESIZE_text); // SSML //input.setSsml(SYNTHESIZE_ssml); synthesizeRequest.setInput(input); // Voice VoiceSelectionParams voice = new VoiceSelectionParams(); // Language voice.setLanguageCode(GoogleCloudHelper.LanguageCode.pl_PL); synthesizeRequest.setVoice(voice); // AudioConfig AudioConfig audioConfig = new AudioConfig(); // Audio Encoding audioConfig.setAudioEncoding(GoogleCloudHelper.AudioEncoding_TTS.LINEAR16); // Sample Rate //audioConfig.setSampleRateHertz(SYNTHESIZE_sampleRateHertz); // Audio Effects Profiles audioConfig.setEffectsProfileId(SYNTHESIZE_audioEffectsProfile); synthesizeRequest.setAudioConfig(audioConfig); // Audio // Request content System.out.println("Request JSON: " + synthesizeRequest.toJson()); System.out.println(""); System.out.println("------------------------------------------------------------------------------------------"); System.out.println(""); // API Call SynthesizeResponse synthesizeResponse = this.api.text_synthesize(synthesizeRequest); // Response content System.out.println("Response JSON: " + synthesizeResponse.getRawData()); // Parse errors if (synthesizeResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(synthesizeResponse.getParseWarningMessage()); } // Response from objects System.out.println("------------------------------------------------------------------------------------------"); System.out.println("Audio file details"); System.out.println(""); String fileName = synthesizeResponse.generateAudioFile(SYNTHESIZE_filePath); System.out.println("File path: " + SYNTHESIZE_filePath); System.out.println("File name: " + fileName); } else { System.out.println("Api object is null - test skipped."); } } catch (GoogleCloudApiException googleCloudException) { System.out.println("--------------------"); System.out.println("Text Synthesize exception - Google api exception"); System.out.println("Code: " + ((Integer)googleCloudException.getCode()).toString()); System.out.println("Message: " + googleCloudException.getMessage()); System.out.println("Status: " + googleCloudException.getStatus()); } catch (Exception recognizeException) { System.out.println("--------------------"); System.out.println("Text Synthesize exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = recognizeException.getStackTrace(); sb.append(recognizeException.getClass().getName()).append(": ").append(recognizeException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } //-------------- VOICES @Test public void voices_list() { if (!ENABLE_TEST_VOICES_LIST) return; try { System.out.println("------------------------------------------------------------------------------------------"); System.out.println("VOICES LIST TEST"); if (this.api != null) { // Config ListVoicesRequest listVoicesRequest = new ListVoicesRequest(); //listVoicesRequest.setLanguageCode("en-*"); listVoicesRequest.setLanguageCode("*"); // API Call ListVoicesResponse listVoicesResponse = this.api.voices_list(listVoicesRequest); // Response content System.out.println("Response JSON: " + listVoicesResponse.getRawData()); // Parse errors if (listVoicesResponse.getParseWarning()) { System.out.println(""); System.out.println("--------------------"); System.out.println("Parser warnings"); System.out.println(listVoicesResponse.getParseWarningMessage()); } } } catch (Exception recognizeException) { System.out.println("--------------------"); System.out.println("Voices List exception"); StringBuilder sb = new StringBuilder(500); StackTraceElement[] st = recognizeException.getStackTrace(); sb.append(recognizeException.getClass().getName()).append(": ").append(recognizeException.getMessage()).append("\n"); for (StackTraceElement st1 : st) { sb.append("\t at ").append(st1.toString()).append("\n"); } System.out.println(sb.toString()); } System.out.println("------------------------------------------------------------------------------------------"); } }