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
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")
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
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
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
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")
def audio_stream_request_generator(self): """ Reads the sound from the ros-topic in an generator """ query_input = dialogflow.QueryInput(audio_config=self.audio_config) # The first request contains the configuration. yield dialogflow.StreamingDetectIntentRequest( session=self.session, query_params=self.query_params, query_input=query_input) # Save data to audio file if self.save_audio_requests: filename = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ".wav" wf = wave.open(filename, "w") wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(16000) # Here we are reading small chunks of audio from a queue while not rospy.is_shutdown() and not self.cancel_stream_intent: try: chunk = self.audio_chunk_queue.popleft() except IndexError as e: # Wait for new sound data, should come within 0.1s since it is sent in 10Hz rospy.sleep(0.1) continue if self.save_audio_requests: wf.writeframes(chunk) # The later requests contains audio data. yield dialogflow.StreamingDetectIntentRequest(input_audio=chunk) rospy.loginfo("AVBRÖT STREAMING INTENT!!") if self.save_audio_requests: wf.close()
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
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))
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
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)
def request(username, text): session = session_client.session_path(project_id, username) 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 format(response.query_result.fulfillment_text)
def get_response(self, text, language_code='en'): '''Returns response object using session_client object''' text_input = dialogflow.TextInput(text=text, language_code=language_code) query_input = dialogflow.QueryInput(text=text_input) self.__response = self.__session_client.detect_intent( request={"session": self.__session, "query_input": query_input} ) # print(self.__response) return self.__response
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() if len(roles) != 0 and len(roles) != len(exceptionroles): return for role in roles: if role.id not in exceptionroles: return if message.author.id in self.session_ids: session_id = self.session_ids[message.author.id] else: session_id = uuid.uuid4() self.session_ids[message.author.id] = session_id session = session_client.session_path(DIALOGFLOW_PROJECT_ID, session_id) if not message.content: return text_input = dialogflow.TextInput(text=message.content[0:256], language_code='en') query_input = dialogflow.QueryInput(text=text_input) response = session_client.detect_intent(request={'session': session, 'query_input': query_input}) response_text = response.query_result.fulfillment_text response_data = response.query_result.parameters intent_id = response.query_result.intent.name.split('/')[-1] formatted_response = str(dict(response_data)).replace("'", '"') query = config.Dialogflow.select(f"dialogflow.intent_id = '{intent_id}' AND ((dialogflow.data IS NULL) " f"OR dialogflow.data = '{formatted_response}')") results = list(query) if not len(results): return dialogflowReply = results[0].as_dict() if not dialogflowReply["response"]: await self.bot.reply_to_msg(message, response_text) else: if dialogflowReply["response"].startswith(self.bot.command_prefix): commandname = dialogflowReply["response"].lower().lstrip(self.bot.command_prefix).split(" ")[0] if command := config.Commands.fetch(commandname): await self.bot.reply_to_msg(message, command.response) else:
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
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))
def send_to_bot(self, txt): #translate to English text = self.trans_obj.translate("en", txt) #sends to bot and returns intent, response text_input = dialogflow.TextInput( text=text, language_code=self.lang_to_code[self.lang]) query_input = dialogflow.QueryInput(text=text_input) response = self.session_client.detect_intent(request={ "session": self.session, "query_input": query_input }) return response.query_result.intent.display_name, response.query_result.fulfillment_text
def chatbot_fallback(text): with app.app_context(): session_id = app.config["STAGE"] session = SESSION_CLIENT.session_path(PROJECT_ID, str(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 }) send_message(response.query_result.fulfillment_text)
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
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)
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"')
def detect_intent_text(self, text): """ Send text to dialogflow and publish response """ self.cancel_stream_intent = True text_input = dialogflow.TextInput(text=text, language_code=self.language) query_input = dialogflow.QueryInput(text=text_input) response = self.session_client.detect_intent(session=self.session, query_input=query_input) rospy.loginfo('-' * 10 + " %s " + '-' * 10, self.project_id) rospy.loginfo('Query text: {}'.format( response.query_result.query_text)) rospy.loginfo('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) rospy.loginfo('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) self.cancel_stream_intent = False return response.query_result
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))
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
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
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
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
def detect_intent_event(self, event_msg): """ Send event to dialogflow and publish response """ self.cancel_stream_intent = True event_input = dialogflow.EventInput(language_code=self.language, name=event_msg.name) params = struct_pb2.Struct() for param in event_msg.parameters: params[param.key] = param.value event_input.parameters = params query_input = dialogflow.QueryInput(event=event_input) response = self.session_client.detect_intent(session=self.session, query_input=query_input) rospy.loginfo('-' * 10 + " %s " + '-' * 10, self.project_id) rospy.loginfo('Query text: {}'.format( response.query_result.query_text)) rospy.loginfo('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) rospy.loginfo('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) self.cancel_stream_intent = False return response.query_result
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)