Skip to content

Commit c7ad006

Browse files
authored
Update python.md
1 parent e546ce0 commit c7ad006

File tree

1 file changed

+23
-18
lines changed
  • articles/ai-services/speech-service/includes/quickstarts/openai-speech

1 file changed

+23
-18
lines changed

articles/ai-services/speech-service/includes/quickstarts/openai-speech/python.md

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ Follow these steps to create a new console application.
4848

4949
1. Copy the following code into `openai-speech.py`:
5050

51-
```Python
51+
```Python
5252
import os
5353
import azure.cognitiveservices.speech as speechsdk
5454
import openai
@@ -75,26 +75,30 @@ Follow these steps to create a new console application.
7575
# The language of the voice that responds on behalf of Azure OpenAI.
7676
speech_config.speech_synthesis_voice_name='en-US-JennyMultilingualNeural'
7777
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_output_config)
78+
79+
# tts sentence end mark
80+
tts_sentence_end = [ ".", "!", "?", ";", "。", "!", "?", ";", "\n" ]
7881
7982
# Prompts Azure OpenAI with a request and synthesizes the response.
8083
def ask_openai(prompt):
84+
# Ask Azure OpenAI in streaming way
85+
response = openai.Completion.create(engine=deployment_id, prompt=prompt, max_tokens=200, stream=True)
86+
collected_messages = []
87+
last_tts_request = None
8188
82-
# Ask Azure OpenAI
83-
response = openai.Completion.create(engine=deployment_id, prompt=prompt, max_tokens=100)
84-
text = response['choices'][0]['text'].replace('\n', ' ').replace(' .', '.').strip()
85-
print('Azure OpenAI response:' + text)
86-
87-
# Azure text to speech output
88-
speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
89-
90-
# Check result
91-
if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
92-
print("Speech synthesized to speaker for text [{}]".format(text))
93-
elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled:
94-
cancellation_details = speech_synthesis_result.cancellation_details
95-
print("Speech synthesis canceled: {}".format(cancellation_details.reason))
96-
if cancellation_details.reason == speechsdk.CancellationReason.Error:
97-
print("Error details: {}".format(cancellation_details.error_details))
89+
# iterate through the stream response stream
90+
for chunk in response:
91+
if len(chunk['choices']) > 0:
92+
chunk_message = chunk['choices'][0]['text'] # extract the message
93+
collected_messages.append(chunk_message) # save the message
94+
if chunk_message in tts_sentence_end: # sentence end found
95+
text = ''.join(collected_messages).strip() # join the recieved message together to build a sentence
96+
if text != '': # if sentence only have \n or space, we could skip
97+
print(f"Speech synthesized to speaker for: {text}")
98+
last_tts_request = speech_synthesizer.speak_text_async(text)
99+
collected_messages.clear()
100+
if last_tts_request:
101+
last_tts_request.get()
98102
99103
# Continuously listens for speech input to recognize and send as text to Azure OpenAI
100104
def chat_with_open_ai():
@@ -128,7 +132,8 @@ Follow these steps to create a new console application.
128132
chat_with_open_ai()
129133
except Exception as err:
130134
print("Encountered exception. {}".format(err))
131-
```
135+
```
136+
132137
1. To increase or decrease the number of tokens returned by Azure OpenAI, change the `max_tokens` parameter. For more information tokens and cost implications, see [Azure OpenAI tokens](/azure/ai-services/openai/overview#tokens) and [Azure OpenAI pricing](https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/).
133138

134139
Run your new console application to start speech recognition from a microphone:

0 commit comments

Comments
 (0)