|
| 1 | +import logging |
| 2 | + |
| 3 | +from openai import AzureOpenAI |
| 4 | +from azure.cognitiveservices.speech import SpeechRecognizer, SpeechSynthesizer, ResultReason, CancellationReason, PropertyId |
| 5 | +from azure.ai.translation.text import TextTranslationClient |
| 6 | +from azure.ai.translation.text.models import InputTextItem |
| 7 | + |
| 8 | +from event_handler import EventHandler |
| 9 | + |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +base_language = 'en' |
| 14 | + |
| 15 | + |
| 16 | +class Cli: |
| 17 | + def __init__(self, |
| 18 | + openai_client: AzureOpenAI, |
| 19 | + assistant_id: str, |
| 20 | + speech_recognizer: SpeechRecognizer, |
| 21 | + speech_synthesizer: SpeechSynthesizer, |
| 22 | + text_translator: TextTranslationClient): |
| 23 | + self.openai_client = openai_client |
| 24 | + self.assistant_id = assistant_id |
| 25 | + self.speech_recognizer = speech_recognizer |
| 26 | + self.speech_synthesizer = speech_synthesizer |
| 27 | + self.text_translator = text_translator |
| 28 | + self.language = '' |
| 29 | + self.thread_id = '' |
| 30 | + |
| 31 | + def run(self): |
| 32 | + thread = self.openai_client.beta.threads.create() |
| 33 | + self.thread_id = thread.id |
| 34 | + |
| 35 | + print("Say something...") |
| 36 | + |
| 37 | + while True: |
| 38 | + try: |
| 39 | + user_input = self.recognize() |
| 40 | + |
| 41 | + base_language_text = user_input |
| 42 | + if not self.language.startswith(base_language): |
| 43 | + base_language_text = self.translate(text=user_input, language=base_language) |
| 44 | + |
| 45 | + output_text = self.assistant(content=base_language_text) |
| 46 | + |
| 47 | + if not self.language.startswith(base_language): |
| 48 | + output_text = self.translate(text=output_text, language=self.language) |
| 49 | + |
| 50 | + self.synthesize(output_text) |
| 51 | + except Exception as e: |
| 52 | + logger.error("failure: {}".format(e)) |
| 53 | + continue |
| 54 | + |
| 55 | + def recognize(self) -> str: |
| 56 | + response = self.speech_recognizer.recognize_once() |
| 57 | + |
| 58 | + reason = response.reason |
| 59 | + if reason != ResultReason.RecognizedSpeech: |
| 60 | + error = 'Failed to recognize speech.' |
| 61 | + if reason == ResultReason.NoMatch: |
| 62 | + error = "No speech could be recognized: {}".format(response.no_match_details) |
| 63 | + elif reason == ResultReason.Canceled: |
| 64 | + cancellation_details = response.cancellation_details |
| 65 | + error = "Speech Recognition canceled: {}".format(cancellation_details.reason) |
| 66 | + if cancellation_details.reason == CancellationReason.Error: |
| 67 | + error += "Error details: {}".format(cancellation_details.error_details) |
| 68 | + raise Exception("Speech recognition failed with error: {}".format(error)) |
| 69 | + |
| 70 | + self.language = response.properties[PropertyId.SpeechServiceConnection_AutoDetectSourceLanguageResult] |
| 71 | + logger.info("Recognized (language={}): {}".format(self.language, response.text)) |
| 72 | + |
| 73 | + return response.text |
| 74 | + |
| 75 | + def synthesize(self, text: str) -> None: |
| 76 | + response = self.speech_synthesizer.speak_text(text) |
| 77 | + |
| 78 | + if response.reason != ResultReason.SynthesizingAudioCompleted: |
| 79 | + cancellation_details = response.cancellation_details |
| 80 | + error = "Speech synthesis canceled: {}".format(cancellation_details.reason) |
| 81 | + if cancellation_details.reason == CancellationReason.Error: |
| 82 | + if cancellation_details.error_details: |
| 83 | + error += "Error details: {}".format(cancellation_details.error_details) |
| 84 | + raise Exception("Speech synthesis failed with error: {}".format(error)) |
| 85 | + |
| 86 | + logger.info("Speech synthesized for text [{}]".format(text)) |
| 87 | + |
| 88 | + def translate(self, text: str, language: str) -> str: |
| 89 | + content = InputTextItem(text=text) |
| 90 | + translation = self.text_translator.translate(content=[content], to=[language]) |
| 91 | + if len(translation) == 0 or len(translation[0].translations) == 0: |
| 92 | + raise Exception("Failed to translate to {} text: {}".format(language, text)) |
| 93 | + |
| 94 | + logger.info("Translated [{}] to [{}]".format(text, translation[0].translations[0].text)) |
| 95 | + return translation[0].translations[0].text |
| 96 | + |
| 97 | + def assistant(self, content: str) -> str: |
| 98 | + self.openai_client.beta.threads.messages.create( |
| 99 | + thread_id=self.thread_id, |
| 100 | + role="user", |
| 101 | + content=content |
| 102 | + ) |
| 103 | + |
| 104 | + event_handler = EventHandler() |
| 105 | + with self.openai_client.beta.threads.runs.stream(assistant_id=self.assistant_id, thread_id=self.thread_id, |
| 106 | + event_handler=event_handler) as stream: |
| 107 | + stream.until_done() |
| 108 | + |
| 109 | + return event_handler.get_result() |
0 commit comments