def detect_intent_texts_with_location(project_id, location_id, session_id,
                                      texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient(
        client_options={
            "api_endpoint": f"{location_id}-dialogflow.googleapis.com"
        })

    session = (
        f"projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}"
    )
    print(f"Session path: {session}\n")

    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(request={
            "session": session,
            "query_input": query_input
        })

        print("=" * 20)
        print(f"Query text: {response.query_result.query_text}")
        print(
            f"Detected intent: {response.query_result.intent.display_name} (confidence: {response.query_result.intent_detection_confidence,})\n"
        )
        print(f"Fulfillment text: {response.query_result.fulfillment_text}\n")
コード例 #2
0
    def send_message(self, text, user_id, language_code="en"):

        session_client = dialogflow.SessionsClient()

        session = session_client.session_path(self.PROJECT_ID, user_id)
        print("Session path: {}\n".format(session))

        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"session": session, "query_input": query_input}
        )

        print("=" * 20)
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )

        print(response.query_result)

        return response.query_result.intent.display_name
コード例 #3
0
def text_message(update, context):
    project_id = context.bot_data['project_id']

    text = update.message.text

    user_id = update.message.chat_id
    session_id = "tg-id" + str(user_id)

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.TextInput(text=text, language_code="ru")
    query_input = dialogflow.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(request={
            "session": session,
            "query_input": query_input
        })
        response = response.query_result.fulfillment_text

        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=response)

    except Exception:
        logger.exception("Error")
コード例 #4
0
ファイル: dialogflow_connector.py プロジェクト: uvacw/CART
def detect_intent_texts(session_id, text):
    '''Connects to DialogFlow using the environment variables 'DF_LANGUAGE_CODE' to determine the language code, 'DF_CREDENTIALS' for authentication.
    Credentials need to be stored as an environment variable. Before doing so, line-breaks need to be removed, and double-quotes turned into single-quotes.
    '''

    try:
        language_code = os.environ['DF_LANGUAGE_CODE']

        credentials = os.environ['DF_CREDENTIALS']

        credentials = ast.literal_eval(credentials)

        project_id = credentials['project_id']

        cr = Credentials.from_service_account_info(credentials)
        session_client = dialogflow.SessionsClient(credentials=cr)

        session = session_client.session_path(project_id, session_id)
        print('Session path: {}\n'.format(session))

        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(request={
            'session': session,
            'query_input': query_input
        })

        response = proto_message_to_dict(response.query_result)
    except Exception as e:
        response = 'DialogFlow error: ' + str(e)

    return response
コード例 #5
0
ファイル: vk_bot.py プロジェクト: acev3/dialogflow
def detect_intent_texts(project_id, session_id, texts, language_code="ru-RU"):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    logger.info("Session path: {}\n".format(session))
    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)
        response = session_client.detect_intent(request={
            "session": session,
            "query_input": query_input
        })
        logger.info("=" * 20)
        logger.info("Query text: {}".format(response.query_result.query_text))
        logger.info("Detected intent: {} (confidence: {})\n".format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence,
        ))
        logger.info("Fulfillment text: {}\n".format(
            response.query_result.fulfillment_text))
    if response.query_result.intent.is_fallback:
        return False
    return response.query_result.fulfillment_text
コード例 #6
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.TextInput(
            text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={'session': session, 'query_input': query_input})

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
コード例 #7
0
def detect_intent_texts(project_id, session_id, text, language_code):
    """Returns the result of detect intent from with texts as inputs
    and is the text fallback or not.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.TextInput(
        text=text,
        language_code=language_code,
    )
    query_input = dialogflow.QueryInput(
        text=text_input
    )

    response = session_client.detect_intent(
        request={"session": session, "query_input": query_input}
    )

    text_result = response.query_result.fulfillment_text
    text_is_fallback = False

    if response.query_result.intent.is_fallback:
        text_is_fallback = True

    return text_result, text_is_fallback
コード例 #8
0
ファイル: dialogflow.py プロジェクト: Ivanwg/TelegramBots
def detect_intent_text(session_id, text):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    text_input = dialogflow.TextInput(text=text, language_code=language_code)

    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })

    print("=" * 20)
    print("Query text: {}".format(response.query_result.query_text))
    print("Detected intent: {} (confidence: {})\n".format(
        response.query_result.intent.display_name,
        response.query_result.intent_detection_confidence,
    ))
    print("Fulfillment text: {}\n".format(
        response.query_result.fulfillment_text))
    return response.query_result.fulfillment_text
コード例 #9
0
ファイル: detect_intent.py プロジェクト: MokkoFm/verb-bot
def detect_intent_texts(project_id, session_id, text, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    text_input = dialogflow.TextInput(text=text, language_code=language_code)
    query_input = dialogflow.QueryInput(text=text_input)
    response = session_client.detect_intent(
        session=session, query_input=query_input)
    return response.query_result
コード例 #10
0
 def __init__(self, project_id='bot-test-303915', session_id=123456789):
     self.__project_id = project_id
     self.__session_id = session_id
     self.__session_client = dialogflow.SessionsClient()
     self.__session = self.__session_client.session_path(project_id, session_id)
     self.__courses = []
     self.__attributes = []
     self.__data = yaml.full_load(open('courses3.yaml'))
コード例 #11
0
def detect_intent_stream(project_id, session_id, audio_file_path,
                         language_code):
    """Returns the result of detect intent with streaming audio as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow
    session_client = dialogflow.SessionsClient()

    # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
    audio_encoding = dialogflow.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 16000

    session_path = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session_path))

    def request_generator(audio_config, audio_file_path):
        query_input = dialogflow.QueryInput(audio_config=audio_config)

        # The first request contains the configuration.
        yield dialogflow.StreamingDetectIntentRequest(session=session_path,
                                                      query_input=query_input)

        # Here we are reading small chunks of audio data from a local
        # audio file.  In practice these chunks should come from
        # an audio input device.
        with open(audio_file_path, 'rb') as audio_file:
            while True:
                chunk = audio_file.read(4096)
                if not chunk:
                    break
                # The later requests contains audio data.
                yield dialogflow.StreamingDetectIntentRequest(
                    input_audio=chunk)

    audio_config = dialogflow.InputAudioConfig(
        audio_encoding=audio_encoding,
        language_code=language_code,
        sample_rate_hertz=sample_rate_hertz)

    requests = request_generator(audio_config, audio_file_path)
    responses = session_client.streaming_detect_intent(requests=requests)

    print('=' * 20)
    for response in responses:
        print('Intermediate transcript: "{}".'.format(
            response.recognition_result.transcript))

    # Note: The result from the last response is the final transcript along
    # with the detected content.
    query_result = response.query_result

    print('=' * 20)
    print('Query text: {}'.format(query_result.query_text))
    print('Detected intent: {} (confidence: {})\n'.format(
        query_result.intent.display_name,
        query_result.intent_detection_confidence))
    print('Fulfillment text: {}\n'.format(query_result.fulfillment_text))
コード例 #12
0
    def answer_to_user(self, update, context):
        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(os.environ['GOOGLE_PROJECT_NAME'],
                                                        f'tg-{update.message.chat_id}')
        text_input = dialogflow.TextInput(text=update.message.text, language_code='ru')
        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(request={'session': session, 'query_input': query_input})
        update.message.reply_text(response.query_result.fulfillment_text)
コード例 #13
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)
        query_input = dialogflow.QueryInput(text=text_input)
        response = session_client.detect_intent(request={
            "session": session,
            "query_input": query_input
        })
    return response.query_result  #.fulfillment_text
コード例 #14
0
async def post_dialogflow(username: str, request: dict):
    text = request["text"]
    name = request["name"]

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path('gitrich-9txq', str(uuid.uuid4()))

    text_input = dialogflow.TextInput(text=text, language_code='en')
    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })

    params = response.query_result.parameters

    try:
        price = params["unit-currency"]["amount"]
        price = f"{price:.2f}"
    except TypeError:
        return ErrorResponseModel("Price not found within text", 400,
                                  "Please provide the price of the item")

    if params["foods"] != "":
        category = "Food & Drinks"
    else:
        category = "Entertainment"

    receipt = {
        "name":
        name,
        "amount":
        price,
        "items": {},
        "category":
        category,
        "image":
        "",
        "date":
        datetime.now(
            pytz.timezone('Asia/Singapore')).strftime('%d/%m/%Y %H:%M:%S')
    }

    success, receipt = await add_receipt(username, receipt)

    if not (success):
        return ErrorResponseModel("Unexpected Error Occured", 400,
                                  "Please check request body again")

    return ResponseModel(receipt, 201, "Successfully uploaded adhoc receipt")
def detect_intent_with_sentiment_analysis(project_id, session_id, texts,
                                          language_code):
    """Returns the result of detect intent with texts as inputs and analyzes the
    sentiment of the query text.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session_path))

    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        # Enable sentiment analysis
        sentiment_config = dialogflow.SentimentAnalysisRequestConfig(
            analyze_query_text_sentiment=True)

        # Set the query parameters with sentiment analysis
        query_params = dialogflow.QueryParameters(
            sentiment_analysis_request_config=sentiment_config)

        response = session_client.detect_intent(
            request={
                "session": session_path,
                "query_input": query_input,
                "query_params": query_params,
            })

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print("Detected intent: {} (confidence: {})\n".format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence,
        ))
        print("Fulfillment text: {}\n".format(
            response.query_result.fulfillment_text))
        # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
        print("Query Text Sentiment Score: {}\n".format(
            response.query_result.sentiment_analysis_result.
            query_text_sentiment.score))
        print("Query Text Sentiment Magnitude: {}\n".format(
            response.query_result.sentiment_analysis_result.
            query_text_sentiment.magnitude))
コード例 #16
0
def detect_intent_texts(project_id, session_id, text, language_code):
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.TextInput(text=text, language_code=language_code)

    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })

    if not response.query_result.intent.is_fallback:
        return response.query_result.fulfillment_text
コード例 #17
0
    def __init__(self, trans_obj: Translator, lang):
        self.lang = lang
        self.lang_to_code = supported_speech_langs()
        self.situation = "You are walking down the street during the last day of summer break before school \
                         starts again in the summer. You decide to go to a small food place around the corner.\
                         Your goal is to get through this meal and the conversation. \n"

        self.session_client = dialogflow.SessionsClient()  #for the convo bot
        self.session = self.session_client.session_path("botlate", 123456)

        #sentiment client
        self.sent_client = language_v1.LanguageServiceClient()
        self.type_ = language_v1.Document.Type.PLAIN_TEXT

        self.trans_obj = trans_obj
        self.elem_counter = 0
        self.convo_elems = self.load_convo_elems()
コード例 #18
0
def detect_intent_with_texttospeech_response(project_id, session_id, texts,
                                             language_code):
    """Returns the result of detect intent with texts as inputs and includes
    the response in an audio format.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session_path))

    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        # Set the query parameters with sentiment analysis
        output_audio_config = dialogflow.OutputAudioConfig(
            audio_encoding=dialogflow.OutputAudioEncoding.
            OUTPUT_AUDIO_ENCODING_LINEAR_16)

        request = dialogflow.DetectIntentRequest(
            session=session_path,
            query_input=query_input,
            output_audio_config=output_audio_config,
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print("Detected intent: {} (confidence: {})\n".format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence,
        ))
        print("Fulfillment text: {}\n".format(
            response.query_result.fulfillment_text))
        # The response's audio_content is binary.
        with open("output.wav", "wb") as out:
            out.write(response.output_audio)
            print('Audio content written to file "output.wav"')
コード例 #19
0
def detect_intent_audio(project_id, session_id, audio_file_path,
                        language_code):
    """Returns the result of detect intent with an audio file as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
    audio_encoding = dialogflow.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 16000

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    with open(audio_file_path, "rb") as audio_file:
        input_audio = audio_file.read()

    audio_config = dialogflow.InputAudioConfig(
        audio_encoding=audio_encoding,
        language_code=language_code,
        sample_rate_hertz=sample_rate_hertz,
    )
    query_input = dialogflow.QueryInput(audio_config=audio_config)

    request = dialogflow.DetectIntentRequest(
        session=session,
        query_input=query_input,
        input_audio=input_audio,
    )
    response = session_client.detect_intent(request=request)

    print("=" * 20)
    print("Query text: {}".format(response.query_result.query_text))
    print("Detected intent: {} (confidence: {})\n".format(
        response.query_result.intent.display_name,
        response.query_result.intent_detection_confidence,
    ))
    print("Fulfillment text: {}\n".format(
        response.query_result.fulfillment_text))
コード例 #20
0
def detect_intent_texts(text):

    project_id = 'esoteric-virtue-306011'
    session_id = '123456789'
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.TextInput(text=text, language_code='en-US')

    query_input = dialogflow.QueryInput(text=text_input)

    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })

    return response.query_result
コード例 #21
0
ファイル: myapp.py プロジェクト: limseungchan/pythonProject1
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.
    Using the same `session_id` between requests allows continuation
    of the conversation."""
    # 건들지 않아도 되는 부분 시작
    from google.cloud import dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(request={
            'session': session,
            'query_input': query_input
        })

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))

        # 건들지 않아도 되는 부분 끝

        # 인텐트 이름 [3]
        intent_name = response.query_result.intent.display_name

        # 여기에서 intent_name에 따른 기능 분리 [4]
        if (intent_name == "WriteToFirestore"):
            res = save_query_by_parameters(
                response.query_result.parameters)  # [5]

        return res
コード例 #22
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(request={
            'session': session,
            'query_input': query_input
        })

        if not response.query_result.intent.is_fallback:
            return response.query_result.fulfillment_text
コード例 #23
0
def detect_intent(text, session_id):
    if session_id == None:
        session_id = uuid.uuid4()

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(PROJECTID, session_id)
    text_input = dialogflow.TextInput(text=text, language_code='en')
    query_input = dialogflow.QueryInput(text=text_input)
    response = session_client.detect_intent(request={
        "session": session,
        "query_input": query_input
    })
    print("=" * 20)
    print("Query text: {}".format(response.query_result.query_text))
    print("Detected intent: {} (confidence: {})\n".format(
        response.query_result.intent.display_name,
        response.query_result.intent_detection_confidence,
    ))
    if response.query_result.all_required_params_present:
        display_name = response.query_result.intent.display_name
        if display_name == 'cases_intent' or display_name == 'facilities_intent':
            return (
                True,
                response.query_result.parameters["location"]["street-address"],
                response.query_result.parameters["geo-city"],
                response.query_result.intent.display_name,
                session_id,
            )  #all required, street, city, intent, session_id
        return (
            False,
            response.query_result.fulfillment_text,
            session_id,
        )

    return (
        False,
        response.query_result.fulfillment_text,
        session_id,
    )  #False, fulfillment_messsage, session_id
コード例 #24
0
ファイル: app.py プロジェクト: sv1r4/shome.assistant
    def detectEvent(self, session_id, event_name, payload):
        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(self._project_id, session_id)

        parameters = Struct(fields={'value': Value(string_value=payload)})

        js = self.safeParseJson(payload)

        if hasattr(js, 'items'):
            for key, value in js.items():
                nKey = self.normilizeKeyDialogflow(key)
                parameters[nKey] = value

        event_input = dialogflow.EventInput(name=event_name,
                                            language_code='ru-RU',
                                            parameters=parameters)

        query_input = dialogflow.QueryInput(event=event_input)

        try:
            response = session_client.detect_intent(session=session,
                                                    query_input=query_input)
            self.handleDialogflowResponse(response)
        except:
            print("error detect event")
            self._isEndConversation = True

        if not self._isEndConversation:
            self.playSound(self._wake_sound_file)
            print('event conversation continue')
            self.stopDetectHotword()
            self.runDetectIntent(session_id)
        else:
            print('event conversation finished')
            self.stopDetectIntent()
            self.runDetectHotword()
コード例 #25
0
    def answer_to_user(self, event):
        try:
            session_client = dialogflow.SessionsClient()
            session = session_client.session_path(
                os.environ['GOOGLE_PROJECT_NAME'], f'vk-{event.user_id}')
            text_input = dialogflow.TextInput(text=event.text,
                                              language_code='ru')
            query_input = dialogflow.QueryInput(text=text_input)

            response = session_client.detect_intent(request={
                'session': session,
                'query_input': query_input
            })
            if not response.query_result.intent.is_fallback:
                self.vk_api.messages.send(
                    user_id=event.user_id,
                    message=response.query_result.fulfillment_text,
                    random_id=random.randint(1, 1000))
        except InvalidArgument:
            self.vk_api.messages.send(
                user_id=event.user_id,
                message=
                'Введена слишком длинная строка. Длинна строки не должна превышать 256 символов.',
                random_id=random.randint(1, 1000))
コード例 #26
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    from google.cloud import dialogflow
    import os
    os.environ[
        "GOOGLE_APPLICATION_CREDENTIALS"] = "/home/reflect9/mysite/firstbot-iidr-e3bf3507f860.json"

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    responses = []
    for text in texts:
        text_input = dialogflow.TextInput(text=text,
                                          language_code=language_code)
        query_input = dialogflow.QueryInput(text=text_input)
        response = session_client.detect_intent(request={
            "session": session,
            "query_input": query_input
        })
        responses.append({
            "query": response.query_result.query_text,
            "intent": response.query_result.intent.display_name,
            "confidence": response.query_result.intent_detection_confidence,
            "answer": response.query_result.fulfillment_text
        })
    return responses
コード例 #27
0
ファイル: app.py プロジェクト: sv1r4/shome.assistant
    def runDetectIntent(self, session_id):
        print("run detect intent")
        self._isIntentDetect = True

        session_client = dialogflow.SessionsClient()
        audio_encoding = dialogflow.AudioEncoding.AUDIO_ENCODING_LINEAR_16
        sample_rate_hertz = 16000
        language_code = 'ru-RU'
        session_id = '{}'.format(session_id)
        print("session #{}".format(session_id))

        session_path = session_client.session_path(self._project_id,
                                                   session_id)
        print('Session path: {}\n'.format(session_path))

        def _audio_callback_intent(in_data, frame_count, time_info, status):
            if not self._is_playing:
                self._buff.put(in_data)
            return None, pyaudio.paContinue

        try:
            num_channels = 1
            audio_format = pyaudio.paInt16
            frame_length = 4096

            audio_config = dialogflow.InputAudioConfig(
                audio_encoding=audio_encoding,
                language_code=language_code,
                sample_rate_hertz=sample_rate_hertz)

            self._pa = pyaudio.PyAudio()
            self._audio_stream = self._pa.open(
                rate=sample_rate_hertz,
                channels=num_channels,
                format=audio_format,
                input=True,
                frames_per_buffer=frame_length,
                input_device_index=self._input_device_index,
                stream_callback=_audio_callback_intent)

            self._audio_stream.start_stream()

            print("Waiting for command ...\n")

            def request_generator(audio_config):
                query_input = dialogflow.QueryInput(audio_config=audio_config)
                output_audio_config = dialogflow.OutputAudioConfig(
                    audio_encoding=dialogflow.OutputAudioEncoding.
                    OUTPUT_AUDIO_ENCODING_LINEAR_16)

                # The first request contains the configuration.
                yield dialogflow.StreamingDetectIntentRequest(
                    session=session_path,
                    query_input=query_input,
                    single_utterance=True,
                    output_audio_config=output_audio_config)

                while True:
                    chunk = self._buff.get()
                    if chunk is None:
                        print("chunk none")
                        return
                    if not self._isIntentDetect:
                        print("done intent")
                        return
                    yield dialogflow.StreamingDetectIntentRequest(
                        input_audio=chunk)

            requests = request_generator(audio_config)

            responses = session_client.streaming_detect_intent(requests)

            print('=' * 20)
            self._isEndConversation = True
            for response in responses:
                self.handleDialogflowResponse(response)

            self.stopDetectIntent()

            if self._isEndConversation:
                print('end conversation')
                print("send mqtt end detectinetnt event")
                self._mqtt.publish(self._endDetectIntentEventTopic, "1")
                self.runDetectHotword()
            else:
                self.playSound(self._wake_sound_file)
                print('conversation continue')
                self.runDetectIntent(session_id)

        except KeyboardInterrupt:
            print('stopping ...')
        finally:
            if self._audio_stream is not None:
                self._audio_stream.stop_stream()
                self._audio_stream.close()

            # delete Porcupine last to avoid segfault in callback.
            if self._porcupine is not None:
                self._porcupine.delete()
コード例 #28
0
import discord.ext.commands as commands
from google.oauth2 import service_account
from google.cloud import dialogflow
import os
import uuid
import asyncio
import json
import config

DIALOGFLOW_AUTH = json.loads(os.environ.get("DIALOGFLOW_AUTH"))
session_client = dialogflow.SessionsClient(
    credentials=service_account.Credentials.from_service_account_info(DIALOGFLOW_AUTH))
DIALOGFLOW_PROJECT_ID = DIALOGFLOW_AUTH['project_id']
SESSION_LIFETIME = 10 * 60  # 10 minutes to avoid repeated false positives


class DialogFlow(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.session_ids = {}

    async def process_message(self, message):
        if message.content.startswith(self.bot.command_prefix):
            return
        if not config.Misc.fetch("dialogflow_state"):
            return
        if not config.Misc.fetch("dialogflow_debug_state"):
            if not config.DialogflowChannels.fetch(message.channel.id):
                return
            roles = message.author.roles[1:]
            exceptionroles = config.DialogflowExceptionRoles.fetch_all()
コード例 #29
0
from google.cloud import dialogflow
from google.oauth2 import service_account

from constants import GOOGLE_SERVICE_ACCOUNT_FILE_PATH, DEFAULT_DIALOGFLOW_LANGUAGE_CODE, DIALOGFLOW_PROJECT_ID

credentials = service_account.Credentials.from_service_account_file(
    GOOGLE_SERVICE_ACCOUNT_FILE_PATH)
session_client = dialogflow.SessionsClient(credentials=credentials)


# Attempts to match an intent with given free text input
def detect_intent_via_text(session_id, text):
    text_input = dialogflow.TextInput(
        text=text, language_code=DEFAULT_DIALOGFLOW_LANGUAGE_CODE)

    return __detect_intent(session_id, dialogflow.QueryInput(text=text_input))


# Attempts to match an intent with given event input
def detect_intent_via_event(session_id, event):
    event_input = dialogflow.EventInput(
        name=event, language_code=DEFAULT_DIALOGFLOW_LANGUAGE_CODE)

    return __detect_intent(session_id,
                           dialogflow.QueryInput(event=event_input))


def __detect_intent(session_id, query_input):
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, session_id)

    response = session_client.detect_intent(request={
コード例 #30
0
ファイル: dialog_test3.py プロジェクト: manasm11/lop_
 def __init__(self, project_id, session_id=123456789):
     self.__project_id = project_id
     self.__session_id = session_id
     self.__session_client = dialogflow.SessionsClient()
     self.__session = self.__session_client.session_path(project_id, session_id)