Develop natural language solutions in Azure
Lab
Recognize and synthesize speech
Code 1
from dotenv import load_dotenv
from datetime import datetime
import os
# Import namespaces
# Import namespaces
from azure.core.credentials import AzureKeyCredential
import azure.cognitiveservices.speech as speech_sdk
def main():
# Clear the console
os.system('cls' if os.name=='nt' else 'clear')
try:
global speech_config
# Get config settings
load_dotenv()
speech_key = os.getenv('KEY')
speech_region = os.getenv('REGION')
# Configure speech service
# Configure speech service
speech_config = speech_sdk.SpeechConfig(speech_key, speech_region)
print('Ready to use speech service in:', speech_config.region)
# Get spoken input
command = TranscribeCommand()
if command.lower() == 'what time is it?':
TellTime()
except Exception as ex:
print(ex)
def TranscribeCommand():
command = ''
# Configure speech recognition
# Configure speech recognition
current_dir = os.getcwd()
audioFile = current_dir + '/time.wav'
audio_config = speech_sdk.AudioConfig(filename=audioFile)
speech_recognizer = speech_sdk.SpeechRecognizer(speech_config, audio_config)
# Process speech input
# Process speech input
print("Listening...")
speech = speech_recognizer.recognize_once_async().get()
if speech.reason == speech_sdk.ResultReason.RecognizedSpeech:
command = speech.text
print(command)
else:
print(speech.reason)
if speech.reason == speech_sdk.ResultReason.Canceled:
cancellation = speech.cancellation_details
print(cancellation.reason)
print(cancellation.error_details)
# Return the command
return command
def TellTime():
now = datetime.now()
response_text = 'The time is {}:{:02d}'.format(now.hour,now.minute)
# Configure speech synthesis
# Configure speech synthesis
output_file = "output.wav"
speech_config.speech_synthesis_voice_name = "en-GB-RyanNeural"
audio_config = speech_sdk.audio.AudioConfig(filename=output_file)
speech_synthesizer = speech_sdk.SpeechSynthesizer(speech_config, audio_config,)
# Synthesize spoken output
# Synthesize spoken output
speak = speech_synthesizer.speak_text_async(response_text).get()
if speak.reason != speech_sdk.ResultReason.SynthesizingAudioCompleted:
print(speak.reason)
else:
print("Spoken output saved in " + output_file)
# Print the response
print(response_text)
if __name__ == "__main__":
main()
Code 2:
from dotenv import load_dotenv
from datetime import datetime
import os
# Import namespaces
# Import namespaces
from azure.core.credentials import AzureKeyCredential
import azure.cognitiveservices.speech as speech_sdk
def main():
# Clear the console
os.system('cls' if os.name=='nt' else 'clear')
try:
global speech_config
# Get config settings
load_dotenv()
speech_key = os.getenv('KEY')
speech_region = os.getenv('REGION')
# Configure speech service
# Configure speech service
speech_config = speech_sdk.SpeechConfig(speech_key, speech_region)
print('Ready to use speech service in:', speech_config.region)
# Get spoken input
command = TranscribeCommand()
if command.lower() == 'what time is it?':
TellTime()
except Exception as ex:
print(ex)
def TranscribeCommand():
command = ''
# Configure speech recognition
# Configure speech recognition
current_dir = os.getcwd()
audioFile = current_dir + '/time.wav'
audio_config = speech_sdk.AudioConfig(filename=audioFile)
speech_recognizer = speech_sdk.SpeechRecognizer(speech_config, audio_config)
# Process speech input
# Process speech input
print("Listening...")
speech = speech_recognizer.recognize_once_async().get()
if speech.reason == speech_sdk.ResultReason.RecognizedSpeech:
command = speech.text
print(command)
else:
print(speech.reason)
if speech.reason == speech_sdk.ResultReason.Canceled:
cancellation = speech.cancellation_details
print(cancellation.reason)
print(cancellation.error_details)
# Return the command
return command
def TellTime():
now = datetime.now()
response_text = 'The time is {}:{:02d}'.format(now.hour,now.minute)
# Configure speech synthesis
# Configure speech synthesis
output_file = "output.wav"
speech_config.speech_synthesis_voice_name = "en-GB-RyanNeural"
audio_config = speech_sdk.audio.AudioConfig(filename=output_file)
speech_synthesizer = speech_sdk.SpeechSynthesizer(speech_config, audio_config,)
# Synthesize spoken output
# Print the response
print(response_text)
if __name__ == "__main__":
main()
analyze text lab
code:
from dotenv import load_dotenv
import os
# Import namespaces
# import namespaces
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
def main():
try:
# Get Configuration Settings
load_dotenv()
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
ai_key = os.getenv('AI_SERVICE_KEY')
# Create client using endpoint and key
# Create client using endpoint and key
credential = AzureKeyCredential(ai_key)
ai_client = TextAnalyticsClient(endpoint=ai_endpoint, credential=credential)
# Analyze each text file in the reviews folder
reviews_folder = 'reviews'
for file_name in os.listdir(reviews_folder):
# Read the file contents
print('\n-------------\n' + file_name)
text = open(os.path.join(reviews_folder, file_name), encoding='utf8').read()
print('\n' + text)
# Get language
# Get language
detectedLanguage = ai_client.detect_language(documents=[text])[0]
print('\nLanguage: {}'.format(detectedLanguage.primary_language.name))
# Get sentiment
# Get sentiment
sentimentAnalysis = ai_client.analyze_sentiment(documents=[text])[0]
print("\nSentiment: {}".format(sentimentAnalysis.sentiment))
# Get key phrases
# Get key phrases
phrases = ai_client.extract_key_phrases(documents=[text])[0].key_phrases
if len(phrases) > 0:
print("\nKey Phrases:")
for phrase in phrases:
print('\t{}'.format(phrase))
# Get entities
# Get entities
entities = ai_client.recognize_entities(documents=[text])[0].entities
if len(entities) > 0:
print("\nEntities")
for entity in entities:
print('\t{} ({})'.format(entity.text, entity.category))
# Get linked entities
# Get linked entities
entities = ai_client.recognize_linked_entities(documents=[text])[0].entities
if len(entities) > 0:
print("\nLinks")
for linked_entity in entities:
print('\t{} ({})'.format(linked_entity.name, linked_entity.url))
except Exception as ex:
print(ex)
if __name__ == "__main__":
main()
