Пример #1
0
    def test_log(log_store):
        CONSOLE_TEXT = "console log"
        logger_console.addHandler(log_store)
        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]
        logger_console.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["warning"]
        logger_console.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["error"]
        logger_console.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["critical"]

        CONSOLE_TEXT = "debug log"
        logger_debug.addHandler(log_store)
        logger_debug.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]
        logger_debug.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]
        logger_debug.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["warning"]
        logger_debug.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["error"]
        logger_debug.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["critical"]

        CONSOLE_TEXT = "root log"
        logger_root.addHandler(log_store)
        logger_root.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]
        logger_root.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]
        logger_root.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["warning"]
        logger_root.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["error"]
        logger_root.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["critical"]

        assert len(log_store.messages["critical"]) == 3
        log_store.reset()
        assert len(log_store.messages["critical"]) == 0

        CONSOLE_TEXT = "root log 2"
        logger.addHandler(log_store)
        logger.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]
        logger.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]
        logger.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["warning"]
        logger.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["error"]
        logger.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["critical"]
Пример #2
0
    def test_handler_level_manipulation(log_store):
        CONSOLE_TEXT = "console log"
        logger_console.setLevel(logging.DEBUG)
        logger_console.addHandler(log_store)
        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]

        for handler in logger_console.handlers:
            handler.setLevel(logging.INFO)
        log_store.reset()
        assert len(log_store.messages["debug"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]
Пример #3
0
 def check_message_for_pattern(message: intent_pb2.Intent.Message,
                               pattern: str) -> bool:
     logger_console.debug({
         "message": "checking response for text",
         "content": pattern,
         "pattern": pattern
     })
     if message.HasField("text"):
         has_match = SingleMessageHandler._pattern_match_text(
             message, pattern)
         if has_match:
             return has_match
     if message.HasField("card"):
         has_match = SingleMessageHandler._pattern_match_card(
             message, pattern)
         if has_match:
             return has_match
     return False
Пример #4
0
    def __init__(self, device_id: Optional[int] = None) -> None:
        import pysoundio

        logging.debug("Initializing PySoundIo streamer")

        self.mute = False
        self.buffer: queue.Queue = queue.Queue(maxsize=CHUNK * 50)
        logging.info("Starting stream")
        # start recording
        self.pysoundio_object: pysoundio.PySoundIo = pysoundio.PySoundIo(
            backend=None)
        self.pysoundio_object.start_input_stream(
            device_id=device_id,
            channels=MONO,
            sample_rate=RATE,
            block_size=CHUNK,
            dtype=pysoundio.SoundIoFormatS16LE,
            read_callback=self.callback,
        )
        logger_console.debug("Streamer initialized")
Пример #5
0
    def callback(self, data, length):
        if self.response is not None:
            # if we are currently playing a response
            if self.idx <= len(self.response):
                # if the response is still being played: calculate the length in bytes, overwrite the output
                # data with the portion of the response, increase the index and return
                num_bytes = length * SAMPLEWIDTH * MONO
                data[:] = self.response[self.idx:self.idx + num_bytes]  # noqa:
                self.idx += num_bytes
                return

            # if the whole response was played: remove the response and set task done in the response queue
            self.response = None
            self.responses.task_done()
            logger_console.debug("done playing")

        if not self.responses.empty():
            # if there is a response to play, get get it from the queue and reset the index
            self.response = self.responses.get()
            self.idx = WAV_HEADER_LENGTH
            logger_console.debug("start playing")
Пример #6
0
 def play(self, data: bytes) -> None:
     self.responses.put(data)
     logger_console.debug(f"output {len(data)} bytes")
     self.responses.join()
Пример #7
0
def main(
    pipeline_id: str,
    session_id: str,
    save_to_disk: bool,
    streamer_name: str,
    initial_intent_display_name: Optional[str] = None,
) -> None:
    session_id = session_id if session_id else str(uuid.uuid4())
    with open("csi.json") as f:
        config: ClientConfig = ClientConfig.from_json(f.read())

    client: Client = Client(config=config,
                            use_secure_channel=config.grpc_cert is not None)
    conversations_service: Conversations = client.services.conversations

    if "pyaudio" in streamer_name:
        # Get audio stream (iterator of audio chunks):
        streamer: StreamerInInterface = PyAudioStreamerIn()
        streaming_request: Iterator[
            S2sStreamRequest] = streamer.create_s2s_request(
                pipeline_id=pipeline_id,
                session_id=session_id,
                save_to_disk=save_to_disk,
                initial_intent_display_name=initial_intent_display_name,
            )
        player: StreamerOutInterface = PyAudioStreamerOut()

    elif "pysoundio" in streamer_name:
        # Get audio stream (iterator of audio chunks):
        streamer = PySoundIoStreamerIn()
        streaming_request = streamer.create_s2s_request(
            pipeline_id=pipeline_id,
            session_id=session_id,
            save_to_disk=save_to_disk,
            initial_intent_display_name=initial_intent_display_name,
        )
        player = PySoundIoStreamerOut()
    else:
        raise ValueError(f'Unknown streamer name "{streamer_name}".')

    i = 0
    j = 0

    for response in conversations_service.s2s_stream(streaming_request):
        if response.HasField("detect_intent_response"):
            query_result: QueryResult = response.detect_intent_response.query_result
            print(
                f"INTENT {i}: {query_result.query_text} -> {query_result.intent.display_name}"
            )
            i += 1
            j = 0
        elif response.HasField("synthetize_response"):
            t2s_response: SynthesizeResponse = response.synthetize_response
            print(f"RESPONSE \t{j}: {t2s_response.text}")
            j += 1
            streamer.mute = True
            logger_console.debug("muted")
            player.play(response.synthetize_response.audio)
            # playing the audio is a bit delayed, so still wait.
            time.sleep(0.2)
            streamer.mute = False
            logger_console.debug("unmuted")
Пример #8
0
    def test_level_manipulation(log_store):
        CONSOLE_TEXT = "console log"
        logger_console.addHandler(log_store)
        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["debug"]

        logger_console.setLevel(logging.INFO)
        log_store.reset()
        assert len(log_store.messages["debug"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["info"]

        logger_console.setLevel(logging.WARN)
        log_store.reset()
        assert len(log_store.messages["info"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["info"]
        logger_console.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["warning"]

        logger_console.setLevel(logging.ERROR)
        log_store.reset()
        assert len(log_store.messages["warning"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["info"]
        logger_console.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["warning"]
        logger_console.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["error"]

        logger_console.setLevel(logging.CRITICAL)
        log_store.reset()
        assert len(log_store.messages["error"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["info"]
        logger_console.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["warning"]
        logger_console.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["error"]
        logger_console.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT in log_store.messages["critical"]

        logger_console.setLevel(logging.CRITICAL + 1)
        log_store.reset()
        assert len(log_store.messages["error"]) == 0

        logger_console.debug(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["debug"]
        logger_console.info(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["info"]
        logger_console.warning(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["warning"]
        logger_console.error(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["error"]
        logger_console.critical(CONSOLE_TEXT)
        assert CONSOLE_TEXT not in log_store.messages["critical"]
Пример #9
0
def main(pipeline_id: str, session_id: str, save_to_disk: bool,
         streamer_name: str) -> None:
    with open("csi.json") as f:
        csi_config: CsiClientConfig = CsiClientConfig.from_json(f.read())
    csi_client: CsiClient = CsiClient(config=csi_config,
                                      use_secure_channel=csi_config.grpc_cert
                                      is not None)
    conversations_service: Conversations = csi_client.services.conversations

    with open("sip.json") as f:
        sip_config: SipClientConfig = SipClientConfig.from_json(f.read())
    sip_client: SipClient = SipClient(config=sip_config,
                                      use_secure_channel=sip_config.grpc_cert
                                      is not None)
    sip_service: Sip = sip_client.services.sip

    session_id = session_id if session_id else str(uuid.uuid4())

    if "pyaudio" in streamer_name:
        # Get audio stream (iterator of audio chunks):
        streamer: StreamerInInterface = PyAudioStreamerIn()
        streaming_request: Iterator[
            S2sStreamRequest] = streamer.create_s2s_request(
                pipeline_id=pipeline_id,
                session_id=session_id,
                save_to_disk=save_to_disk,
            )
        player: StreamerOutInterface = PyAudioStreamerOut()

    elif "pysoundio" in streamer_name:
        # Get audio stream (iterator of audio chunks):
        streamer = PySoundIoStreamerIn()
        streaming_request = streamer.create_s2s_request(
            pipeline_id=pipeline_id,
            session_id=session_id,
            save_to_disk=save_to_disk)
        player = PySoundIoStreamerOut()
    else:
        raise ValueError(f'Unknown streamer name "{streamer_name}".')

    i = 0
    j = 0

    for response in conversations_service.s2s_stream(streaming_request):
        if response.HasField("detect_intent_response"):
            query_result: QueryResult = response.detect_intent_response.query_result
            print(
                f"INTENT {i}: {query_result.query_text} -> {query_result.intent.display_name}"
            )
            i += 1
            j = 0
        elif response.HasField("synthetize_response"):
            t2s_response: SynthesizeResponse = response.synthetize_response
            print(f"RESPONSE \t{j}: {t2s_response.text}")
            j += 1
            streamer.mute = True  # type: ignore
            logger_console.debug("muted")
            player.play(response.synthetize_response.audio)
            # playing the audio is a bit delayed, so still wait.
            time.sleep(0.2)
            streamer.mute = False  # type: ignore
            logger_console.debug("unmuted")
        elif response.HasField("sip_trigger"):
            sip_trigger: SipTrigger = response.sip_trigger
            print(f"TRIGGER \t{j}: {sip_trigger.type}")
            j += 1
            if sip_trigger.type is SipTrigger.SipTriggerType.HANGUP:
                sip_service.end_call(EndCallRequest(hard_hangup=True))
                streamer.close()