in dialogflow/streaming_transcription.py [0:0]
def main():
"""start bidirectional streaming from microphone input to Dialogflow API"""
# Create conversation.
conversation = conversation_management.create_conversation(
project_id=PROJECT_ID, conversation_profile_id=CONVERSATION_PROFILE_ID
)
conversation_id = conversation.name.split("conversations/")[1].rstrip()
# Create end user participant.
end_user = participant_management.create_participant(
project_id=PROJECT_ID, conversation_id=conversation_id, role="END_USER"
)
participant_id = end_user.name.split("participants/")[1].rstrip()
mic_manager = ResumableMicrophoneStream(SAMPLE_RATE, CHUNK_SIZE)
print(mic_manager.chunk_size)
sys.stdout.write(YELLOW)
sys.stdout.write('\nListening, say "Quit" or "Exit" to stop.\n\n')
sys.stdout.write("End (ms) Transcript Results/Status\n")
sys.stdout.write("=====================================================\n")
with mic_manager as stream:
while not stream.closed:
terminate = False
while not terminate:
try:
print(f"New Streaming Analyze Request: {stream.restart_counter}")
stream.restart_counter += 1
# Send request to streaming and get response.
responses = participant_management.analyze_content_audio_stream(
conversation_id=conversation_id,
participant_id=participant_id,
sample_rate_herz=SAMPLE_RATE,
stream=stream,
timeout=RESTART_TIMEOUT,
language_code="en-US",
single_utterance=False,
)
# Now, print the final transcription responses to user.
for response in responses:
if response.message:
print(response)
if response.recognition_result.is_final:
print(response)
# offset return from recognition_result is relative
# to the beginning of audio stream.
offset = response.recognition_result.speech_end_offset
stream.is_final_offset = int(
offset.seconds * 1000 + offset.microseconds / 1000
)
transcript = response.recognition_result.transcript
# Half-close the stream with gRPC (in Python just stop yielding requests)
stream.is_final = True
# Exit recognition if any of the transcribed phrase could be
# one of our keywords.
if re.search(r"\b(exit|quit)\b", transcript, re.I):
sys.stdout.write(YELLOW)
sys.stdout.write("Exiting...\n")
terminate = True
stream.closed = True
break
except DeadlineExceeded:
print("Deadline Exceeded, restarting.")
if terminate:
conversation_management.complete_conversation(
project_id=PROJECT_ID, conversation_id=conversation_id
)
break