Exemple #1
0
    def recognize(self, session_id):
        """Returns the result of detect intent with streaming audio as input.

        Using the same `session_id` between requests allows continuation
        of the conversaion."""
        session_client = dialogflow.SessionsClient()

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

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

        self.audio_stream.reset()
        self._recorder.add_processor(self.audio_stream)

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

        requests = self.audio_stream.request_stream(audio_config, session)
        responses = session_client.streaming_detect_intent(requests)

        print('=' * 20)
        try:
            for response in responses:
                print('Intermediate transcript: "{}".'.format(
                    response.recognition_result.transcript))
                print('is_final?: "{}".'.format(
                    response.recognition_result.is_final))
                if response.recognition_result.is_final == True:
                    self._recorder.remove_processor(self.audio_stream)
                    self.audio_stream.end_audio()
            # 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))
            return query_result

        except:
            print('May be timeout')
            print('=' * 20)
            self._recorder.remove_processor(self.audio_stream)
            self.audio_stream.end_audio()
            return
Exemple #2
0
def detect_intent_texts(project_id, session_id, text, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    if text:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
        return response.query_result.fulfillment_text
Exemple #3
0
def get_type(text_to_be_analyzed):
    if not USE_DIALOGFLOW:
        return None
    try:
        session_client = dialogflow.SessionsClient(credentials=credentials)
        session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
        text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session, query_input=query_input)
        return response.query_result.parameters['chart_type']
    except:
        return None
Exemple #4
0
def detect_intent_texts(text):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)
    query_input = dialogflow.types.QueryInput(text=text_input)
    response = session_client.detect_intent(session=session,
                                            query_input=query_input)
    if response.query_result.intent.display_name != '':
        return response.query_result.intent.display_name
    return text
Exemple #5
0
    def __init__(self,
                 DIALOGFLOW_PROJECT_ID,
                 DIALOGFLOW_LANGUAGE_CODE='en',
                 SESSION_ID='me'):
        self.DIALOGFLOW_PROJECT_ID = DIALOGFLOW_PROJECT_ID
        self.DIALOGFLOW_LANGUAGE_CODE = DIALOGFLOW_LANGUAGE_CODE
        self.SESSION_ID = SESSION_ID

        # create session
        self.session_client = dialogflow.SessionsClient()
        self.session = self.session_client.session_path(
            DIALOGFLOW_PROJECT_ID, SESSION_ID)
def send_to_dialogflow(text_to_be_analyzed):
    os.environ[
        "GOOGLE_APPLICATION_CREDENTIALS"] = 'modx-7c366-a60fb8dbc5ea.json'
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path('modx-7c366', '1')
    text_input = dialogflow.types.TextInput(text=text_to_be_analyzed,
                                            language_code='en')
    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)
    return response.query_result.fulfillment_text
Exemple #7
0
def send_to_dialogflow(text_to_be_analyzed):
    os.environ[
        "GOOGLE_APPLICATION_CREDENTIALS"] = 'new-drphfu-289d9a316551.json'
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path('new-drphfu', 'en-US')
    text_input = dialogflow.types.TextInput(text=text_to_be_analyzed,
                                            language_code='en')
    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)
    return response.query_result.fulfillment_text
def detect_intent_audio(project_id, session_id, language_code):
    import os as operational
    import requests as reques

    print('Beginning file download with requests')

    url = 'https://api.wassenger.com/v1/io/5d9785b6036345001b5a85f8/files/5d98de1478a4b00028de8765/download?token=905bd94b9d3a26df733849887c838b9cc5ee1538b72fb1937edf027d5b7b71c71b2c54f1c894e4a2'
    r = reques.get(url)

    audioPath = '/home/fernando/olivetti/olivetti-flask/cat3.ogg'
    with open(audioPath, 'wb') as f:
        f.write(r.content)
    operational.system("ftransc -f flac cat3.ogg")
    audioPath = '/home/fernando/Documents/audios/cat3.flac'
    # Retrieve HTTP meta-data
    print(r.status_code)
    print(r.headers['content-type'])
    print(r.encoding)
    """Returns the result of detect intent with an audio file as input.

    Using the same `session_id` between requests allows continuation
    of the conversaion."""
    import dialogflow_v2 as dialogflow2

    session_client = dialogflow.SessionsClient()

    # Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
    audio_encoding = dialogflow2.enums.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(audioPath, 'rb') as audio_file:
        input_audio = audio_file.read()

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

    response = session_client.detect_intent(
        session=session, query_input=query_input,
        input_audio=input_audio)

    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))
def empFunc(emp, id):
    while True:
        os.environ[
            "GOOGLE_APPLICATION_CREDENTIALS"] = 'private_key.json'  # API key

        DIALOGFLOW_PROJECT_ID = 'your project id GCP '
        DIALOGFLOW_LANGUAGE_CODE = 'en'
        SESSION_ID = 'me'

        text_to_be_analyzed = "hi"

        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(DIALOGFLOW_PROJECT_ID,
                                              SESSION_ID)
        print(session)
        statement = takeCommand().lower()
        text_input = dialogflow.types.TextInput(
            text=statement, language_code=DIALOGFLOW_LANGUAGE_CODE)
        query_input = dialogflow.types.QueryInput(text=text_input)
        try:
            response = session_client.detect_intent(session=session,
                                                    query_input=query_input)
        except InvalidArgument:
            raise
        # print(response)
        print("Query text:", response.query_result.query_text)
        print("Detected intent:", response.query_result.intent.display_name)
        print("Detected intent confidence:",
              response.query_result.intent_detection_confidence)
        print("Fulfillment text:", response.query_result.fulfillment_text)
        speak(response.query_result.fulfillment_text)
        if (response.query_result.intent.display_name == 'leave'):
            # print(json_format.MessageToDict(response.query_result.output_contexts.parameters))
            for context in response.query_result.output_contexts:
                for key, value in context.parameters.fields.items():
                    print(value)
                    # if (response.query_result.intent.display_name == 'report'):
                    #     pass
            mp = mysql.connector.connect(host='localhost',
                                         user='******',
                                         password='******')

            cur = mp.cursor()
            queryline = "SELECT * FROM mydb.emp_resource_empresource where emp_id = \'" + id + "\' ;"
            cur.execute(queryline)

            row = cur.fetchone()
            casual = str(row[3])
            total_leave = str(row[4])
            medi_leave = str(row[5])
            sp = id + " your casual leaves are " + casual + ". Your  total leave's are " + total_leave + " and your medical leave are " + medi_leave + "."
            speak(sp)
def detect_intent_texts(project_id, session_id, text, language_code):
    session_client = dialogflow.SessionsClient()
    # session_client.from_service_account_file(GOOGLE_APPLICATION_CREDENTIALS)
    session = session_client.session_path(project_id, session_id)

    if text:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        return response.query_result.fulfillment_text
Exemple #11
0
def detect_intent_texts(project_id, session_id, text, language_code):
    """
        Dialogflow helper function that sends and receives answer
    """
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    if text:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
        return response.query_result.fulfillment_text
	def save_context_delito(self, llave, session_id):
		self.env['imco.norma.mail.analisis.nltk.contextos'].sudo().create({
			'channel_id': session_id,
			'message_id': self.id,
			'valor': ("delito_" + llave.lower() )})
		session_client = dialogflow.SessionsClient()
		# crea una sesion en dialog flow si no existe para identificar la conversacion
		session = session_client.session_path(PROJECT_ID, session_id)
		#Inicializa el objeto de dialogflow para contextos
		contexts_client = dialogflow.ContextsClient()
		context_name = contexts_client.context_path(PROJECT_ID, session_id, ("delito_" + llave.lower() ) )
		context = dialogflow.types.Context(name = context_name, lifespan_count = 100)
		response_ctx = contexts_client.create_context(session, context)
Exemple #13
0
def request_response_to_dialogflow(project_id, session_id, message,
                                   language_code):
    session_client = dialogflow.SessionsClient()
    session_path = session_client.session_path(project_id, session_id)

    if message:
        textInput = dialogflow.types.TextInput(text=message,
                                               language_code=language_code)
        queryInput = dialogflow.types.QueryInput(text=textInput)
        response = session_client.detect_intent(session=session_path,
                                                query_input=queryInput)

        return response.query_result.fulfillment_text
Exemple #14
0
def detect_intent_texts(project_id, session_id, text, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    if text:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        from google.protobuf.json_format import MessageToDict
        response = MessageToDict(response)
        return response
Exemple #15
0
def detect_intent_texts(project_id, session_id, text, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    if text:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)  # getting text input
        query_input = dialogflow.types.QueryInput(
            text=text_input)  # preparing query input for intent detection
        response = session_client.detect_intent(
            session=session, query_input=query_input)  # preparing response

        return response.query_result  # accessing query
Exemple #16
0
def detect_intent_texts(project_id, session_id, text, language_code):
	session_client = dialogflow.SessionsClient()
	session = session_client.session_path(project_id, session_id)
	
	if text:
		text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
		query_input = dialogflow.types.QueryInput(text=text_input)
		response = session_client.detect_intent(session=session, query_input=query_input)

		# Send a JSON object that holds the message from Dialog-Flow and intent name 
		message = {"message": response.query_result.fulfillment_text, "intent": response.query_result.intent.display_name}
													
		return message
Exemple #17
0
def dialogflow_client():
    """TODO"""
    # https://github.com/googleapis/dialogflow-python-client-v2/issues/71
    project_id = os.getenv('APPSETTING_DIALOGFLOW_PROJECT_ID',
                            config.DIALOGFLOW_PROJECT_ID)
    app_creds_json = os.getenv('APPSETTING_GOOGLE_APPLICATION_CREDENTIALS',
                            json.dumps(config.GOOGLE_APPLICATION_CREDENTIALS))

    credentials = Credentials.from_service_account_info(json.loads(app_creds_json))
    session_client = dialogflow.SessionsClient(credentials=credentials)
    session_id = 'unique'
    session = session_client.session_path(project_id, session_id)
    return session, session_client
Exemple #18
0
def textMessage(bot, update, chat_data):
    print('Chat data', chat_data, chat_data.get('mode', MODE_DIALOG))
    if chat_data.get('mode', MODE_DIALOG) == MODE_MULTIPLY:
        print('Checking answer: ', chat_data.get('last_answer', None), ' == ',
              int(update.message.text))
        res = multiplyTraining(answer=int(update.message.text),
                               last_answer=chat_data.get('last_answer', None))
        chat_data['mode'] = MODE_DIALOG
        bot.send_message(chat_id=update.message.chat_id, text=res)
    else:
        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(DIALOGFLOW_PROJECT_ID,
                                              SESSION_ID)
        text_input = dialogflow.types.TextInput(
            text=update.message.text, language_code=DIALOGFLOW_LANGUAGE_CODE)
        query_input = dialogflow.types.QueryInput(text=text_input)
        try:
            response = session_client.detect_intent(session=session,
                                                    query_input=query_input)
        except InvalidArgument:
            raise

        print("Query text:", response.query_result.query_text)
        print("Detected intent:", response.query_result.intent.display_name)
        print("Detected intent confidence:",
              response.query_result.intent_detection_confidence)
        print("Fulfillment text:", response.query_result.fulfillment_text)

        if response.query_result.intent.display_name == 'Farytale':
            bot.send_message(chat_id=update.message.chat_id,
                             text=response.query_result.fulfillment_text)
            tale = getTale()
            for line in tale:
                bot.send_message(chat_id=update.message.chat_id, text=line)
            bot.send_message(
                chat_id=update.message.chat_id,
                text="Вот и сказочке конец, а кто слушал - молодец!")
        elif response.query_result.intent.display_name == 'Multiply':
            chat_data['mode'] = MODE_MULTIPLY
            last_answer, q = multiplyTraining()
            chat_data['last_answer'] = last_answer
            bot.send_message(chat_id=update.message.chat_id,
                             text=response.query_result.fulfillment_text +
                             " " + q)
        else:
            text = response.query_result.fulfillment_text

            bot.send_message(chat_id=update.message.chat_id,
                             text=text if text else 'Что?')

        print('Chat data up', chat_data)
Exemple #19
0
def response_from_dialogflow(project_id, session_id, message, language_code):
    # step1. DialogFlow와 사용자가 상호작용할 세션 클라이언트 생성
    session_client = dialogflow.SessionsClient()
    session_path = session_client.session_path(project_id, session_id)
    # projects/프로젝트아이디/agent/sessions/세션아이디 로 생성된다
    print('[session_path]', session_path, sep='\n')
    if message:  # 사용자가 대화를 입력한 경우.대화는 utf-8로 인코딩된 자연어.256자를 넘어서는 안된다
        # step2.사용자 메시지(일반 텍스트)로 TextInput생성
        text_input = dialogflow.types.TextInput(text=message,
                                                language_code=language_code)
        print('[text_input]', text_input, sep='\n')

        # step 3. 생성된 TextInput객체로 QueryInput객체 생성(DialogFlow로 전송할 질의 생성)
        query_input = dialogflow.types.QueryInput(text=text_input)
        print('[query_input]', query_input, sep='\n')

        response = session_client.detect_intent(session=session_path,
                                                query_input=query_input)
        print('[response]', response, sep='\n')
        # 가공 _ code에 따라서 실행이 달라짐 1 : 단순응답 (변화 필요) 2: 날씨 응답(파이썬)  3: 자전거가게 (스프링에서 처리, 고객 주소 필요)
        res = MessageToJson(response)  #응답받고
        res = json.loads(res)  #json으로 변환하여 결과값을 빼낼 수 있는 상태로

        isCode = is_json_key_present(res)  #code 값 존재여부 판단/
        print(isCode)
        if isCode:
            code = res['queryResult']['fulfillmentMessages'][0]['payload'][
                'code']

            if code == "2":  # 날씨
                location = res['queryResult']['fulfillmentMessages'][0][
                    'payload']['location']
                time = res['queryResult']['fulfillmentMessages'][0]['payload'][
                    'time']
                print(location)
                weatherInfo = get_weather_info(location, time, code)
                return weatherInfo

            elif code == "3":
                msg = res['queryResult']['fulfillmentMessages'][0]['payload'][
                    'msg']
                return jsonify({'code': code, 'msg': msg})

            elif code == "4":
                return jsonify({'code': code})

        else:
            return jsonify({
                'code': '1',
                'msg': response.query_result.fulfillment_text
            })
 def detect_intent_text(self, text):
     """Use the Dialogflow API to detect a user's intent. Goto the Dialogflow
     console to define intents and params.
     @:param text: Google Speech API fulfillment text
     @:return query_result: Dialogflow's query_result with action parameters
     """
     session_client = dialogflow.SessionsClient()
     session = session_client.session_path(self.project_id, self.session_id)
     text_input = dialogflow.types.TextInput(
         text=text, language_code=self.language_code)
     query_input = dialogflow.types.QueryInput(text=text_input)
     response = session_client.detect_intent(session=session,
                                             query_input=query_input)
     return response.query_result
Exemple #21
0
def welcome():
	#Setting Google Dialogflow Credentials and invoking SDK
	service_account_info = json.loads(credentials_dgf)
	credentials = service_account.Credentials.from_service_account_info(service_account_info)
	session_client = dialogflow.SessionsClient(credentials=credentials)
	session = session_client.session_path(project_id, call_id)
	event_input = dialogflow.types.EventInput(name='Welcome', language_code=lang_code)
	query_input = dialogflow.types.QueryInput(event=event_input)
	response = session_client.detect_intent(session=session, query_input=query_input)
	print response		
	output_text = response.query_result.fulfillment_text
	output_text = output_text.decode('utf-8')
	print output_text
	return output_text
Exemple #22
0
def main(words):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow.types.TextInput(
        text=words, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except Exception as e:
        raise play_audio(f"Ошибка распознание текста: {e}")

    for x in cmd['translate']:
        if x in response.query_result.fulfillment_text:
            translator = Translator(from_lang="Russian", to_lang="English")
            lang = translator.translate(response.query_result.parameters.
                                        fields['language'].string_value)
            if response.query_result.parameters.fields[
                    'language-from'].string_value != '':
                lang_from = translator.translate(
                    response.query_result.parameters.fields['language-from'].
                    string_value)
            else:
                lang_from = "Russian"
                translator = Translator(from_lang=lang_from, to_lang=lang)
                text = translator.translate(response.query_result.parameters.
                                            fields['any'].string_value)
                print(f"Перевод: {text}")
                play_audio(text)

    for x in cmd['determine']:
        if response.query_result.fulfillment_text == x:
            print(
                f"Ответ: {numexpr.evaluate(''.join([i if i != 'х' else '*' if 'x' in i else '*' for i in response.query_result.parameters.fields['any'].string_value.split(' ')]))}"
            )

    for x in cmd['search']:
        if response.query_result.fulfillment_text == x:
            link = response.query_result.parameters.fields['any'].string_value
            wikipedia.set_lang("ru")
            result = str(wikipedia.summary(link, sentences=1))
            print(f"Ответ: {result}")
            play_audio(result)

    for x in cmd['time']:
        if response.query_result.fulfillment_text == x:
            now = datetime.datetime.now()
            response.query_result.fulfillment_text = f"{response.query_result.fulfillment_text} {now.strftime('%H:%M')}"

    play_audio(response.query_result.fulfillment_text)
Exemple #23
0
 def _query(self, recipient_id, message):
     session_client = dialogflow.SessionsClient()
     session = session_client.session_path(
         current_app.config['DIALOGFLOW_PROJECT_ID'],
         SESSION_IDS.setdefault(recipient_id, str(uuid.uuid1())))
     text_input = dialogflow.types.TextInput(
         text=message,
         language_code=current_app.config['DIALOGFLOW_LANGUAGE_CODE'])
     query_input = dialogflow.types.QueryInput(text=text_input)
     try:
         return session_client.detect_intent(session=session,
                                             query_input=query_input)
     except InvalidArgument:
         raise
Exemple #24
0
 async def _dialog_response(self, message):
     text_to_be_analyzed = message.content
     session_client = dialogflow.SessionsClient()
     session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
     text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
     query_input = dialogflow.types.QueryInput(text=text_input)
     try:
         response = session_client.detect_intent(session=session, query_input=query_input)
     except InvalidArgument:
         print("intent error")
         return
     response_text = response.query_result.fulfillment_text
     if response_text:
         await message.channel.send(response_text)
Exemple #25
0
def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    import random
    import dialogflow
    import string

    ## Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        ## Allows GET requests from any origin with the Content-Type
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    ## Set CORS headers for the main request
    headers = {'Access-Control-Allow-Origin': '*'}

    request_json = request.get_json(force=True)

    project_id = request_json["project_id"]
    text = request_json["text"]
    language_code = request_json["lang"]

    string_len = random.randint(1, 10)
    string_list = [
        random.choice(string.ascii_lowercase) for i in range(0, string_len)
    ]
    session_id = ''.join(string_list)

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)
    query_input = dialogflow.types.QueryInput(text=text_input)
    response = session_client.detect_intent(session=session,
                                            query_input=query_input)
    response_text = response.query_result.fulfillment_text

    return (response_text, 200, headers)
    def __init__(self,
                 project_id=None,
                 service_account_json=None,
                 language_code="en"):
        self.project_id = project_id
        self.language_code = language_code

        credentials = None
        if service_account_json:
            credentials = Credentials.from_service_account_file(
                service_account_json)

        self.session_client = dialogflow.SessionsClient(
            credentials=credentials)
Exemple #27
0
def get_intent_dialogflow(msg):

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow.types.TextInput(
        text=msg, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except InvalidArgument:
        raise

    return response
def chatbot(request):
    # --- 新增 --- #
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)

    if 'user_input' in request.POST: ##
        text_to_be_analyzed = request.POST.get('user_input')
        text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
        query_input = dialogflow.types.QueryInput(text=text_input)

        try:
            response = session_client.detect_intent(session=session, query_input=query_input)
            m = Message.objects.create(user_input_text=response.query_result.query_text, detected_intent = response.query_result.intent.display_name, detected_intent_confidence = response.query_result.intent_detection_confidence, chatbot_output_text = response.query_result.fulfillment_text)
            m.save()
            messages = Message.objects.order_by('timestamp')

            context = {'user_input_text':response.query_result.query_text, 'detected_intent':  response.query_result.intent.display_name, 'detected_intent_confidence': response.query_result.intent_detection_confidence,'chatbot_output_text ': response.query_result.fulfillment_text}

            m_lastone = Message.objects.last()
            print("---")
            print("Query text:", response.query_result.query_text)
            print("Detected intent:", response.query_result.intent.display_name)
            print("Detected intent confidence:", response.query_result.intent_detection_confidence)
            print("Fulfillment text:", response.query_result.fulfillment_text)

            #------- 新增 -------#
            mytext = response.query_result.fulfillment_text
            tts = gTTS(text=mytext, lang='zh-tw', slow=False)

            rand = random.randint(0,3)
            tts.save("./static/result_{}.mp3".format(rand))
            mixer.init()
            mixer.music.load("./static/result_{}.mp3".format(rand))
            mixer.music.play()
            while mixer.music.get_busy(): # check if the file is playing
                pass
            mixer.music.load('./static/result_copy.mp3')
            
            os.remove("./static/result_{}.mp3".format(rand))
            #------- 新增 -------#

            return render(request, 'home/chatbot.html', {'m_lastone': m_lastone})

        except InvalidArgument:
            raise

    # --- --- #

    return render(request, 'home/chatbot.html', locals())
Exemple #29
0
def call2dialogflow(input_text):
    """Calls to Dialogflow API. Receives the text to analyze.

    Parameters
    ----------
    input_text : str
    	The text introduced by the user in the chat.

    Returns
    -------
	dict
		a dictionary with the fulfillment and the intent as keys.
    """

    # Init API
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(PROJECT_ID, SESSION_ID)
    text_input = dialogflow.types.TextInput(text=input_text,
                                            language_code=LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)

    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except InvalidArgument:
        raise Exception('Dialogflow request failed')

    r = {
        'fulfillment': response.query_result.fulfillment_text,
        'intent': response.query_result.intent.display_name,
    }
    # and (r['intent']!= 'Default Fallback Intent')
    if (response.query_result.all_required_params_present):
        # There is no need to ask again
        valorFields = None
        if (r['intent'] == "GuardarGusto") or (r['intent']
                                               == "GuardarAlergia"):
            valorFields = "Ingredientes"
        elif (r['intent'] == "GuardarReceta") or (r['intent']
                                                  == "MostrarReceta"):
            valorFields = "Receta"
        else:
            # raise ValueError
            return r

        r['fields'] = response.query_result.parameters.fields[valorFields]
    else:
        logger.debug('[Dialogflow] - Missing required params')
    return r
Exemple #30
0
def get_bot_response():
    userText = request.args.get('msg')
    text_to_be_analyzed = userText

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow.types.TextInput(
        text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)

    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except InvalidArgument:
        raise

    response = response.query_result.fulfillment_text
    a = 0
    string = userText
    res = [int(i) for i in string.split() if i.isdigit()]
    orderNo = ' '.join(map(str, res))
    if (len(orderNo)) == 5:
        a = 1
        ref = db.reference('boxes')
        ref1 = db.reference('boxes', app1)
        ref2 = db.reference('boxes', app2)
        for val in ref2.get().items():
            if (val[1]['orderId'] == int(orderNo)):
                response = "Product Name : " + val[1][
                    'productName'] + " <br/> " + val[1]['Status'] + " " + val[
                        1]['Location']

        for val in ref.get().items():
            if (val[1]['orderId'] == int(orderNo)):
                response = response + " <br/>" + val[1]['Status'] + " " + val[
                    1]['Location']

        for val in ref1.get().items():
            if (val[1]['orderId'] == int(orderNo)):
                response = response + " <br/>" + val[1]['Status'] + " " + val[
                    1]['Location'] + " <br/>Delivery Date :" + val[1][
                        'deliveryDate']

    if (len(orderNo) == 0):
        response = response
    elif (len(orderNo) != 5):
        response = "Please enter a valid order ID"

    return str(response)