async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger = logging.getLogger(__name__) # logger.debug('DEFINE ACTION') # logger.debug(tracker.current_state()) last_entities = tracker.current_state()['latest_message']['entities'] word = '' thing_type = '' slotsets = [] for raw_entity in last_entities: logger.debug(raw_entity) if raw_entity.get('entity', '') == "thing": if len(word) <= 0: word = raw_entity.get('value', '') thing_type = 'thing' slotsets.append(SlotSet('thing', word)) if raw_entity.get('entity', '') == "place": if len(word) <= 0: word = raw_entity.get('value', '') thing_type = 'place' slotsets.append(SlotSet('place', word)) if raw_entity.get('entity', '') == "person": if len(word) <= 0: word = raw_entity.get('value', '') thing_type = 'person' slotsets.append(SlotSet('person', word)) site = tracker.current_state().get('sender_id') slotsets.append(SlotSet('last_wikipedia_search', 0)) if word and len(word) > 0: cached_fact = await find_fact('summary', word.lower()) if cached_fact: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + word}) parts = cached_fact.get('answer').split('. ') summary = remove_text_inside_brackets( parts[0]).ljust(200)[:200].strip() dispatcher.utter_message(text=summary) #slotsets.append(FollowupAction('action_end')) else: await publish('hermod/' + site + '/tts/say', {"text": "Looking now"}) await publish('hermod/' + site + '/display/startwaiting', {}) loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, lookup_wikipedia, word) logger.debug('WIKI call done') if result: logger.debug(result) parts = result.get('answer').split('. ') summary = remove_text_inside_brackets( parts[0]).ljust(200)[:200].strip() await save_fact('summary', result.get('thing'), result.get('answer'), site, '') await publish('hermod/' + site + '/display/show', {'frame': result.get('url')}) await publish( 'hermod/' + site + '/display/show', { 'buttons': [{ "label": 'Tell me more', "text": 'tell me more' }] }) dispatcher.utter_message(text=summary) #slotsets.append(FollowupAction('action_end')) else: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + word}) dispatcher.utter_message(text="I can't find the topic " + word) slotsets.append(FollowupAction('action_end')) else: dispatcher.utter_message( text="I didn't hear your question. Try again") await publish('hermod/' + site + '/display/stopwaiting', {}) return slotsets
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("======Inside Action Search Best Restaurants====") print() ## extract the required slots location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") ## extract the entities locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) ## if we latitude & longitude entities are found, set it to slot if (latEntity and lonEntity): lat = latEntity lon = lonEntity ## if user wants to search the best restaurants in his current location if (user_locationEntity or (latEntity and lonEntity)): ##check if we already have the user location coordinates stoed in slots if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] ## store the user provided details to slot SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) ## if user wants to search best restaurants by location name if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] print("Entities: ", entity_id, " ", entity_type, " ", city_id, " ", locationEntity) ## search the best restaurts by calling zomatoApi api restaurants = zomatoApi.getLocationDetails(entity_id, entity_type) ## check if restaurants details found if (len(restaurants) > 0): dispatcher.utter_message( "Here are few top rated restaurants that I have found 🤩") dispatcher.utter_custom_json({ "payload": "cardsCarousel", "data": restaurants["best_restaurants"] }) return [] dispatcher.utter_message( "Sorry we couldn't find any best restaurants ☹️".format( cuisine, location)) return [UserUtteranceReverted()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionSearchRestaurants====") print() ## extract the required slots location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") ## extract the entities locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) ## if we latitude & longitude entities are found, set it to slot if (latEntity and lonEntity): lat = latEntity lon = lonEntity ## if user wants to search restaurants in his current location if (user_locationEntity or (latEntity and lonEntity)): ##check if we already have the user location coordinates stoed in slots if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] ## store the user provided details to slot SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) ## if user wants to search restaurants by location name if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) if (locationEntities["restaurants_available"] == "no"): dispatcher.utter_message( "Sorry I couldn't find any restaurants 😓") return [] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] SlotSet("location", locationEntities["title"]) ##get the cuisine id for the cuisine name user provided cuisine_id = zomatoApi.getCuisineId(cuisine, city_id) print("Entities: ", entity_id, " ", entity_type, " ", cuisine_id, " ", location, " ", cuisine) print() ## if we didn't find the restaurant for which user has provided the cuisine name if (cuisine_id == None): dispatcher.utter_message( "Sorry we couldn't find any restaurants that serves {} cuisine in {}" .format(cuisine, location)) return [UserUtteranceReverted()] else: ## search the restaurts by calling zomatoApi api restaurants = zomatoApi.searchRestaurants(entity_id, entity_type, cuisine_id, "") ## check if restaurants found if (len(restaurants) > 0): dispatcher.utter_message( "Here are the few restaurants that matches your preferences 😋" ) dispatcher.utter_custom_json({ "payload": "cardsCarousel", "data": restaurants }) return [] dispatcher.utter_message( "Sorry we couldn't find any restaurants that serves {} cuisine in {} 😞" .format(cuisine, location)) return [UserUtteranceReverted()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: tmdb.API_KEY = "5ce7e4a66621977d06b1c0e75961699b" discover = tmdb.Discover() s = [ "Did that answer your question?", "I hope that answered your question", "Is that what you were looking for?" ] is_year = False movies = [] if tracker.get_slot( "DATE") is not None: # what movies released on x date date = next(tracker.get_latest_entity_values("DATE")) date = date.replace("the ", "") date = date.replace("of ", "") p = re.compile( '\\s*[0-9]{1,2}st' ) # matches 1 or 2 digits from 1 to 9 followed by st, occuring anywhere in string if p.search(date) is not None: sub = p.search(date).group() date = p.sub("", date) sub = sub.replace('st', ' ') print(sub) date = sub.lstrip() + date else: date = date.replace("nd", "") date = date.replace("rd", "") date = date.replace("th", "") print(date) try: date_object = datetime.strptime(date, '%d %B %Y').date() is_year = False except ValueError: try: date_object = datetime.strptime(date, '%B %d %Y').date() is_year = False except ValueError: try: date_object = datetime.strptime(date, '%Y').date() is_year = True except ValueError: dispatcher.utter_message( "I don't understand your question") dispatcher.utter_message( 'If you are asking about a date, ' 'try it in the format of "1st January 2020" or "January 1st 2020"' ) return [] if is_year: release = date_object.strftime("%Y") response = discover.movie(primary_release_year=release) else: release = date_object.strftime("%B %d %Y") response = discover.movie(primary_release_date_gte=release, primary_release_date_lte=release) if response['results']: for i in range(0, 3): movies.append(response['results'][i]['title']) if len(movies) == 3: break titles = "" if len(movies) == 0: dispatcher.utter_message("No movies were released on that day") return [] elif len(movies) == 1: titles = movies[0] elif len(movies) == 2: titles = movies[0] + " and " + movies[1] else: titles = movies[0] + " , " + movies[1] + " and " + movies[2] if tracker.get_slot("genre") is not None: genre = next(tracker.get_latest_entity_values("genre")) if is_year: dispatcher.utter_message("The most popular " + genre + " movies from that year were " + titles) else: dispatcher.utter_message("The most popular " + genre + " movies from that date were " + titles) dispatcher.utter_message(random.choice(s)) else: if is_year: dispatcher.utter_message( "The most popular movies from that year were " + titles) else: dispatcher.utter_message( "The most popular movies from that date were " + titles) dispatcher.utter_message(random.choice(s)) elif tracker.get_slot( "title") is not None: # what date did x movie release title = next(tracker.get_latest_entity_values("title")) response = search.movie(query=title) movie_id = response['results'][0]['id'] movie = tmdb.Movies(movie_id) title = response['results'][0]['title'] release = movie.info()['release_date'] dispatcher.utter_message(title + "was released on " + release) dispatcher.utter_message(random.choice(s)) else: dispatcher.utter_message( "I don't understand your question. You can ask for help to see what kinds of questions you can ask" ) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: tmdb.API_KEY = "5ce7e4a66621977d06b1c0e75961699b" search = tmdb.Search() # movie_credits = None s = [ "Did that answer your question?", "I hope that answered your question", "Is that what you were looking for?" ] if tracker.get_slot("action") is not None: action = next(tracker.get_latest_entity_values("action")) if tracker.get_slot("title") is not None: title = next(tracker.get_latest_entity_values("title")) response = search.movie(query=title) movieID = response['results'][0]['id'] movie = tmdb.Movies(movieID) title = response['results'][0]['title'] movie_credits = movie.credits() crew = movie_credits['crew'] if action == 'starred': action = 'starred in' name = movie_credits['cast'][0]['name'] elif action == 'directed': for person in crew: if person["department"] == "Directing": name = person["name"] break elif action == 'wrote': for person in crew: if person["department"] == "Writing": name = person["name"] break dispatcher.utter_message( name + " " + action + " " + title) # Who stars in X? PERSON stars in X dispatcher.utter_message(random.choice(s)) elif tracker.get_slot("PERSON") is not None: name = next(tracker.get_latest_entity_values("PERSON")) response = search.person(query=name) role = response['results'][0]['known_for_department'] movies = [ response['results'][0]['known_for'][0]['title'], response['results'][0]['known_for'][1]['title'], response['results'][0]['known_for'][2]['title'] ] if action == 'starred': action = 'starring in' elif action == 'directed': action = 'directing' elif action == 'wrote': action = 'writing' # what movies has PERSON starred in? they have starred in xyz dispatcher.utter_message(name + " is known for " + action + " " + movies[0] + ", " + movies[1] + " and " + movies[2]) dispatcher.utter_message(random.choice(s)) else: dispatcher.utter_message( "I don't understand your question. You can ask for help to see what kinds of questions you can ask" ) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: str((tracker.latest_message)['text']) dispatcher.utter_message(template="utter_ask_password") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # dispatcher.utter_message(text="Hello World! new checking") # return []
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: if _has_211(tracker) and not tracker.get_slot(HAS_ASSISTANCE_SLOT): dispatcher.utter_message(template="utter_check_delivery_services") if tracker.get_slot(PROVINCE_SLOT) == "qc": dispatcher.utter_message(template="utter_may_call_211_qc") else: dispatcher.utter_message( template="utter_may_call_211_other_provinces") dispatcher.utter_message(template="utter_explain_211") else: dispatcher.utter_message(template="utter_remind_delivery_services") dispatcher.utter_message(template="utter_remind_pharmacist_services") return []
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: libro = tracker.get_slot('libro') autores = tracker.get_slot('autores') intent = tracker.latest_message['intent'].get('name') numIndexes = 0 numberofmorebooksearch = 0 if intent == "consulta_libros_kw": if libro is not None: dispatcher.utter_message(template="utter_libros_kw", libro=libro) numIndexes = 2 numberofmorebooksearch = 2 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libros_autor": if autores is not None: dispatcher.utter_message(template="utter_libros_autor", autores=autores) numIndexes = 2 numberofmorebooksearch = 2 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libro_titulo_autor" or intent == 'solo_libro_autor': if libro is not None and autores is not None: dispatcher.utter_message(template="utter_libro_titulo_autor", libro=libro, autores=autores) numIndexes = 1 numberofmorebooksearch = 1 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libro_kw": if libro is not None: dispatcher.utter_message(template="utter_libro_kw", libro=libro) numIndexes = 1 numberofmorebooksearch = 1 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libros_titulo" or intent == "solo_libros": if libro is not None: dispatcher.utter_message(template="utter_libros_titulo", libro=libro) numIndexes = 2 numberofmorebooksearch = 2 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libro_titulo" or intent == "solo_libro": if libro is not None: dispatcher.utter_message(template="utter_libro_titulo", libro=libro) numIndexes = 1 numberofmorebooksearch = 1 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libro_autor": if autores is not None: dispatcher.utter_message(template="utter_libro_autor", autores=autores) numIndexes = 1 numberofmorebooksearch = 1 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libros_titulo_autor": if libro is not None and autores is not None: dispatcher.utter_message(template="utter_libros_titulo_autor", libro=libro, autores=autores) numIndexes = 2 numberofmorebooksearch = 2 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libros_kw_autor": if libro is not None and autores is not None: dispatcher.utter_message(template="utter_libros_kw_autor", libro=libro, autores=autores) numIndexes = 2 numberofmorebooksearch = 2 else: dispatcher.utter_message(template="utter_especifica_libro") elif intent == "consulta_libro_kw_autor": if libro is not None and autores is not None: dispatcher.utter_message(template="utter_libro_kw_autor", libro=libro, autores=autores) numIndexes = 1 numberofmorebooksearch = 1 else: dispatcher.utter_message(template="utter_especifica_libro") return [ SlotSet('searchindex', numIndexes), SlotSet('numberofmorebooksearch', numberofmorebooksearch) ]
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: meal = tracker.get_slot("meal") if not meal: dispatcher.utter_message(fallback_message) return [SlotSet("meal", None)] meal = self.meal_parser(meal) cached = redis.StrictRedis(host="127.0.0.1", port=6379, db=2) dt = datetime.now() + timedelta(hours=9) tg_str = str(dt.month) + str(dt.day) + meal + "eng" tg = cached.get(tg_str) if not tg: response = requests.get("http://mini.snu.kr/cafe/today/-/eng") if response.status_code != 200: dispatcher.utter_message("mini.snu.ac.kr doesn't reply") return [SlotSet("meal", None)] parsed_soup = bs(response.content, "html.parser") trs = parsed_soup.find_all("tr") targets = [] for tr in trs: for td in tr.td.contents: if meal in td: targets.append(tr) for target in targets: [s.extract() for s in target("span")] k = 0 response_message = "" try: if targets == []: response_message = "Tell me the exact name of the cafeteria" elif meal == "301": for target in targets: response_message = (response_message + engineering[k] + "<br>") k = k + 1 for child in target.contents[2].children: response_message = (response_message + str(child) + "<br>") elif meal == "공깡": for target in targets: response_message = (response_message + eng_ggang[k] + "<br>") k = k + 1 for child in target.contents[2].children: response_message = (response_message + str(child) + "<br>") elif meal == "두레미담": for target in targets: response_message = (response_message + agricultural[k] + "<br>") k = k + 1 for child in target.contents[2].children: response_message = (response_message + str(child) + "<br>") else: if not (meal == "Student Center" or meal == "Dormitory" or meal == "901"): k = 1 for target in targets: response_message = response_message + time[k] + "<br>" k = k + 1 for child in target.contents[2].children: response_message = (response_message + str(child) + "<br>") except IndexError as e: dispatcher.utter_message(idxerr_msg) return [SlotSet("meal", None)] dispatcher.utter_message(response_message) cached.set(tg_str, response_message) return [SlotSet("meal", None)] try: tg = tg.decode("utf-8") except (UnicodeDecodeError, AttributeError): pass dispatcher.utter_message(tg) return [SlotSet("meal", None)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message("还有什么可以帮您的吗?") return [AllSlotsReset()]
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger = logging.getLogger(__name__) # logger.debug('DEFINE ACTION') # logger.debug(tracker.current_state()) last_entities = tracker.current_state()['latest_message']['entities'] attribute = '' thing = '' thing_type = '' slotsets = [] # pull thing parameters from saved slots ? slots = tracker.current_state().get('slots') for raw_entity in last_entities: # logger.debug(raw_entity) if raw_entity.get('entity', '') == "attribute": if not len(attribute) > 0: attribute = raw_entity.get('value', '') slotsets.append(SlotSet('attribute', attribute)) if raw_entity.get('entity', '') == "thing": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'thing' slotsets.append(SlotSet('thing', thing)) if raw_entity.get('entity', '') == "place": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'place' slotsets.append(SlotSet('place', thing)) if raw_entity.get('entity', '') == "person": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'person' slotsets.append(SlotSet('person', thing)) if raw_entity.get('entity', '') == "word": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'word' slotsets.append(SlotSet('thing', thing)) # logger.debug(last_entities) # logger.debug('THING FROM ENTITIES'+thing) # logger.debug('ATTRIBUTE FROM ENTITIES'+attribute) # logger.debug('SLOTS') # logger.debug(slots) for slot in slots: if slot == "thing" or slot == "person" or slot == "place" and slot in slots and slots[ slot] and len(slots[slot]) > 0: if not thing or len(thing) <= 0: # logger.debug('SET FROM SLOT '+str(slot)+' ' +str(slots[slot])) thing = slots[slot] thing_type = slot # if slot == "attribute" : # logger.debug('SET FROM SLOT '+str(slot)+' ' +str(slots[slot])) # attribute = slots[slot] site = tracker.current_state().get('sender_id') if attribute and thing and len(attribute) > 0 and len(thing) > 0: cached_fact = await find_fact(attribute.lower(), thing.lower()) if cached_fact: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + thing}) if cached_fact.get( 'mnemonic', False) and len(cached_fact.get('mnemonic')) > 0: await publish( 'hermod/' + site + '/display/show', { 'buttons': [{ "label": 'Tell me the memory aid', "text": 'Tell me the memory aid' }] }) dispatcher.utter_message(text="The " + attribute + " of " + thing + " is " + cached_fact.get('answer')) else: slotsets.append(SlotSet('mnemonic', None)) await publish('hermod/' + site + '/tts/say', {"text": "Looking now"}) await publish('hermod/' + site + '/display/startwaiting', {}) loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, lookup_wikidata, attribute, thing) #result = lookup_wikidata(attribute,thing) if result and len(result) > 0: # convert to spoken numbers if attribute == "population": p = inflect.engine() result = p.number_to_words(result) await save_fact(attribute.lower(), thing.lower(), result, site, thing_type) await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + thing}) dispatcher.utter_message(text="The " + attribute + " of " + thing + " is " + result) # TODO send hermod/XX/display/url {'url':'https://en.wiktionary.org/wiki/'+word} else: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + thing}) dispatcher.utter_message(text="I don't know the " + attribute + " of " + thing) #slotsets.append(FollowupAction('action_end')) # no thing :( elif attribute and len(attribute) > 0: dispatcher.utter_message( text="I didn't hear your question. Try again") # fallback to wikipedia search if attribute isn't specified elif thing and len(thing) > 0: cached_fact = await find_fact('summary', thing.lower()) if cached_fact: word = cached_fact.get('thing') await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + word}) parts = cached_fact.get('answer').split('. ') summary = parts[0].ljust(200)[:200].strip() dispatcher.utter_message(textsummary) #slotsets.append(FollowupAction('action_end')) else: await publish('hermod/' + site + '/tts/say', {"text": "Looking now"}) await publish('hermod/' + site + '/display/startwaiting', {}) loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, lookup_wikipedia, thing) if result: parts = result.get('answer').split('. ') summary = parts[0].ljust(200)[:200].strip() await save_fact('summary', result.get('thing'), result.get('answer'), site, '') await publish('hermod/' + site + '/display/show', {'frame': result.get('url')}) await publish( 'hermod/' + site + '/display/show', { 'buttons': [{ "label": 'Tell me more', "text": 'tell me more' }] }) dispatcher.utter_message(text=result.get('thing') + ". " + summary) #slotsets.append(FollowupAction('action_end')) else: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + thing}) dispatcher.utter_message(text="I can't find the topic " + thing) slotsets.append(FollowupAction('action_end')) # await publish('hermod/'+site+'/display/show',{'frame':'https://en.wikipedia.org/wiki/'+thing}) # result = await lookup_wikipedia(thing) # if result and len(result) > 0: # dispatcher.utter_message(text=thing + ". " + result) # else: # dispatcher.utter_message(text="I can't find the topic "+thing) # slotsets.append(FollowupAction('action_end')) else: dispatcher.utter_message( text="I didn't hear your question. Try again") await publish('hermod/' + site + '/display/stopwaiting', {}) return slotsets
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger = logging.getLogger(__name__) last_entities = tracker.current_state()['latest_message']['entities'] attribute = '' thing = '' thing_type = '' slotsets = [] # pull thing parameters from saved slots ? slots = tracker.current_state().get('slots') for raw_entity in last_entities: # logger.debug(raw_entity) if raw_entity.get('entity', '') == "attribute": if not len(attribute) > 0: attribute = raw_entity.get('value', '') slotsets.append(SlotSet('attribute', attribute)) if raw_entity.get('entity', '') == "thing": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'thing' slotsets.append(SlotSet('thing', thing)) if raw_entity.get('entity', '') == "place": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'place' slotsets.append(SlotSet('place', thing)) if raw_entity.get('entity', '') == "person": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'person' slotsets.append(SlotSet('person', thing)) if raw_entity.get('entity', '') == "word": if not len(thing) > 0: thing = raw_entity.get('value', '') thing_type = 'word' slotsets.append(SlotSet('thing', thing)) # logger.debug(last_entities) # logger.debug('THING FROM ENTITIES'+thing) # logger.debug('ATTRIBUTE FROM ENTITIES'+attribute) # logger.debug('SLOTS') # logger.debug(slots) for slot in slots: if slot == "thing" or slot == "person" or slot == "place" and slot in slots and slots[ slot] and len(slots[slot]) > 0: if not thing or len(thing) <= 0: logger.debug('SET FROM SLOT ' + str(slot) + ' ' + str(slots[slot])) thing = slots[slot] thing_type = slot if slot == "attribute": if not attribute or len(attribute) <= 0: logger.debug('SET FROM SLOT ' + str(slot) + ' ' + str(slots[slot])) attribute = slots[slot] # logger.debug('THING FROM SLOTS'+thing) # logger.debug('ATTRIBUTE FROM SLOTS'+attribute) site = tracker.current_state().get('sender_id') if len(attribute) > 0 and len(thing) > 0: result = await find_fact(attribute, thing) # logger.debug('MNEMON LOOKUP FACT') # logger.debug(result) if result and result.get('mnemonic', False): dispatcher.utter_message(text="The memory aid for the " + attribute + " of " + thing + " is, " + result.get('mnemonic')) else: dispatcher.utter_message( text="I don't know a memory aid for the " + attribute + " of " + thing) else: dispatcher.utter_message( text="I don't know which memory aid you want") #slotsets.append(FollowupAction('action_end')) return slotsets
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger = logging.getLogger(__name__) # logger.debug('DEFINE ACTION') # logger.debug(tracker.current_state()) last_entities = tracker.current_state()['latest_message']['entities'] word = '' thing_type = '' last_wikipedia_search = 1 slotsets = [] slots = tracker.current_state().get('slots') for slot in slots: if slot == "thing" or slot == "person" or slot == "place": if not word or len(word) <= 0: logger.debug('SET FROM SLOT ' + str(slot) + ' ' + str(slots[slot])) word = slots[slot] thing_type = slot if slot == "last_wikipedia_search" and slots[ slot] and slots[slot] > 0: last_wikipedia_search = slots[slot] + 1 site = tracker.current_state().get('sender_id') if word and len(word) > 0: cached_fact = await find_fact('summary', word.lower()) if cached_fact: #await publish('hermod/'+site+'/display/show',{'frame':'https://en.wikipedia.org/wiki/'+word}) parts = cached_fact.get('answer').split('. ') summary = remove_text_inside_brackets( parts[last_wikipedia_search]).ljust(200)[:200].strip() # two sentences per request for more if len(parts) > (last_wikipedia_search + 1): summary2 = remove_text_inside_brackets( parts[last_wikipedia_search]).ljust(200)[:200].strip() summary = ". ".join(summary, summary2) last_wikipedia_search = last_wikipedia_search + 1 if summary and len(summary) > 0: dispatcher.utter_message(text=summary) else: dispatcher.utter_message( text="I don't know any more information about " + word) slotsets.append(FollowupAction('action_end')) #slotsets.append(FollowupAction('action_end')) else: await publish('hermod/' + site + '/tts/say', {"text": "Looking now"}) await publish('hermod/' + site + '/display/startwaiting', {}) loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, lookup_wikipedia, word) #result = lookup_wikipedia(word) if result: parts = result.get('answer').split('. ') #summary = parts[last_wikipedia_search].ljust(200)[:200].strip() summary = remove_text_inside_brackets( parts[last_wikipedia_search]).ljust(200)[:200].strip() await save_fact('summary', result.get('thing'), result.get('answer'), site, '') await publish( 'hermod/' + site + '/display/show', { 'frame': 'https://en.wikipedia.org/wiki/' + result.get('thing') }) dispatcher.utter_message(text=summary) #slotsets.append(FollowupAction('action_end')) else: await publish( 'hermod/' + site + '/display/show', {'frame': 'https://en.wikipedia.org/wiki/' + word}) dispatcher.utter_message(text="I can't find the topic " + word) slotsets.append(FollowupAction('action_end')) slotsets.append( SlotSet('last_wikipedia_search', int(last_wikipedia_search))) else: dispatcher.utter_message( text="I didn't hear your question. Try again") await publish('hermod/' + site + '/display/stopwaiting', {}) return slotsets
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None l_name = tracker.get_slot('product_name') if l_name is None: txt = domain['templates']['utter_default'][1]['text'] response = [{ "type": "text", "data": { "content": txt, "speak": True, } }] print(json.dumps(response)) dispatcher.utter_message(json.dumps(response)) else: p_name = l_name[0] response = dbconnector.get_product_detail(p_name, exact=False) if response is None: content = "Rất tiếc, tôi không thể tìm thấy sản phẩm " + p_name res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) else: review = response['review_articles'] lent = len(review) if lent > 0: request_url = os.getenv('PERSONALREVIEWSUMMARY_API', 'http://localhost:5000' ) + '/v1/api/personalsummarization' review_url = response['review_articles'][0]['url'] # TODO: get user profile vector via service input_data = { 'user_demands': { 'screen': 0.1, 'battery': 0.9, 'camera': 0.4, 'config': 0.6, 'design': 0.2, 'durability': 0.1, 'feature': 0.4, 'sound': 0.9 }, 'product_url': review_url, "req_type": "long" } request_data = json.dumps(input_data) logger.info(request_data) logger.info(request_url) reviewservice_response = requests.post(url=request_url, data=request_data) logger.info(reviewservice_response) # print (response.content) reviewservice_result = json.loads( reviewservice_response.content) logger.info(reviewservice_result['summary']) id = random.randint(0, lent - 1) review_product = [{ "type": "text", "data": { "content": "Bạn có thể tham khảo link sau: " + review[id]['url'] + "\n" + "Tóm tắt:" + reviewservice_result['summary'], "speak": False } }] else: review_product = [{ "type": "text", "data": { "content": "Rất tiếc, chúng tôi không thể tìm thấy trải nghiệm của sản phẩm", "speak": True } }] dispatcher.utter_message( json.dumps(review_product, default=json_util.default)) print(json.dumps(review_product, default=json_util.default))
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: logger.info("query_assignments") context = tracker.get_slot("context") courseId = [] batchId = [] courseId = set(object_list( "courseId", tracker, )) batchId = set(object_list( "batchId", tracker, )) logger.info(f"course id is {courseId}") logger.info(f"bATCH id is {batchId}") url = "api/v2/assignments/students/papers?" if tracker.get_slot("context") == "help_late_assignments": params = { "filterBy": "overdue", "page": 1, "size": 10, "courseId": list(courseId), "batchId": list(batchId), "filterByGradeType": "", "keyword": "", "assignmentType": "PAPER" } else: params = { "filterBy": "notSubmitted", "page": 1, "size": 10, "courseId": list(courseId), "batchId": list(batchId), "filterByGradeType": "", "keyword": "", "assignmentType": "PAPER" } text = assignment_list(context, url, params, tracker) if not text: if tracker.get_slot("context") == "help_late_assignments": dispatcher.utter_message( "I couldn't find any late assignments at the moment. 😁") else: dispatcher.utter_message( "I couldn't find any upcoming assignments at the moment. Check again later!😊 " ) return [FollowupAction("action_bottom_top_menu")] if text is None: # for exception dispatcher.utter_message( "I couldn't find your assignments. Something must be wrong.🤔Check again later, sorry." ) return [FollowupAction("action_bottom_top_menu")] dispatcher.utter_message(text) return [FollowupAction("action_bottom_top_menu")]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None l_name = tracker.get_slot('product_name') if l_name is None: txt = domain['templates']['utter_default'][1]['text'] response = [{ "type": "text", "data": { "content": txt, "speak": True, } }] print(json.dumps(response)) dispatcher.utter_message(json.dumps(response)) else: p_name = l_name[0] response = dbconnector.get_product_detail(p_name, exact=False) if response is None: content = "Rất tiếc, tôi không thể tìm thấy sản phẩm " + p_name res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) else: print(response) review = response['review_videos'] print('====') if review == []: content = "Rất tiếc, chúng tôi không thể tìm thấy video trải nghiệm của sản phẩm " + p_name res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) else: lent = len(review) id = random.randint(0, lent - 1) # price_history = response['price_history'] # print() review_product = [{ "type": "text", "data": [{ "url": review[id]['url'], "title": review[id]['title'] }] }] dispatcher.utter_message( json.dumps(review_product, default=json_util.default)) print(json.dumps(review_product, default=json_util.default))
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """ Trả về generic template 6 sản phẩm hot + quick replies đòi xem thêm :param dispatcher: :param tracker: :param domain: :return: """ print('_____' + self.name()) prefix_name = tracker.get_slot(Entities.prefix_name) customer_name = tracker.get_slot(Entities.customer_name) bot_position = tracker.get_slot(Entities.bot_position) query = f''' select distinct mainapp_shoe.id as shoe_id, mainapp_shoe.shoeName, mainapp_shoe.shoeModel, mainapp_shoe.shoeThumbnail, mainapp_shoe.dateCreated, mainapp_shoe.image_static, mainapp_shoe.viewCount, mainapp_shoe.quantitySold, mainapp_shoe.favouriteCount, mainapp_category.categoryName, mainapp_detailshoe.newPrice from mainapp_shoe inner join mainapp_detailshoe on mainapp_shoe.id = mainapp_detailshoe.shoe_id inner join mainapp_category on mainapp_shoe.category_id = mainapp_category.id where active = 1 order by dateCreated desc limit 0, 5; ''' shoes = SqlUtils.get_result(query, Shoe) shoes: List[Shoe] detail_shoes = SqlUtils.get_result(query, DetailShoe) if len(detail_shoes) == 0 or len(shoes) == 0: err_code = ErrorCode.ERR_IN_ACT_GET_NEW_SHOE err_message = f'Xin lỗi {prefix_name}{customer_name}, hệ thống đã xảy ra lỗi. error code={err_code}' dispatcher.utter_message(text=err_message) else: dispatcher.utter_message(text='Đây là 5 đôi bên ' + bot_position + ' mới nhập đó ' + prefix_name + customer_name) dispatcher.utter_message( text= f'Đôi mới nhất được nhập từ ngày {shoes[0].dateCreated}, mời {prefix_name} xem:' ) # horizontal_template_elements = [] # for index in range(len(shoes)): # shoe = shoes[index] # detail_shoe = detail_shoes[index] # # buttons = [ # PostBackButton( # title='Xem đôi này ' + shoe.shoeModel, # str_send_to_webhook='tôi muốn xem mẫu ' + shoe.shoeModel + ' id ' + str(shoe.shoe_id) # ), # UrlButton( # title='Xem trên website', # url_access=MyWebUrl.get_detail_shoe_url(shoe.shoe_id) # ), # ] # # element = HorizontalTemplateElement( # image_url=MyWebUrl.get_shoe_image_url(shoe.shoeThumbnail), # # image_url='https://www.w3schools.com/w3css/img_lights.jpg', # title=shoe.shoeName, # subtitle=price_format(detail_shoe.newPrice), # default_action=HorizontalTemplateElement.DefaultAction(MyWebUrl.get_detail_shoe_url(shoe.shoe_id)), # list_buttons=buttons, # ) # horizontal_template_elements.append(element) # horizontal_template = HorizontalTemplate(horizontal_template_elements) horizontal_template = HorizontalTemplate.from_shoes_detail_shoe( shoes=shoes, detail_shoes=detail_shoes) dispatcher.utter_message( json_message=horizontal_template.to_json_message()) # xem tiep quick_reply_elements = [ QuickReplyElement(QuickReplyElement.TEXT, 'Xem thêm', 'còn đôi nào khác k?'), QuickReplyElement(QuickReplyElement.TEXT, 'Thôi', 'tôi muốn xem menu'), ] quick_replies = QuickReplies( text_before_template='Xin hãy chọn một hành động', list_quick_reply_elements=quick_reply_elements) dispatcher.utter_message( json_message=quick_replies.to_json_message()) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message("actoin triggered") return []
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: """Define what the form has to do after all required slots are filled""" department = tracker.get_slot(EntitySlotEnum.DEPARTMENT) vm_environment = tracker.get_slot(EntitySlotEnum.VM_ENVIRONMENT) vm_ram = tracker.get_slot(EntitySlotEnum.VM_RAM) vm_cpu_cores = tracker.get_slot(EntitySlotEnum.VM_CPU_CORES) vm_disk_space = tracker.get_slot(EntitySlotEnum.VM_DISK_SPACE) vm_scalability = tracker.get_slot(EntitySlotEnum.VM_SCALABILITY) observations = tracker.get_slot(EntitySlotEnum.OBSERVATIONS) request_description = ( "Solicito una maquina virtual con las siguientes caracteristicas: " + f"Departamento: {department} ||" + f"Entorno: {vm_environment} ||" + f"Memoria RAM: {vm_ram} ||" + f"No CPUs: {vm_cpu_cores} ||" + f"Disco duro: {vm_disk_space} Gb ||" + f"Escalabilidad: {vm_scalability if vm_scalability is not None else 'No'} ||" + f"Observaciones: {observations}") logger.info(f"{self.name()}: {request_description}") events = [ SlotSet(EntitySlotEnum.ITILCATEGORY_ID, None), SlotSet(EntitySlotEnum.DEPARTMENT, None), SlotSet(EntitySlotEnum.VM_ENVIRONMENT, None), SlotSet(EntitySlotEnum.VM_RAM, None), SlotSet(EntitySlotEnum.VM_CPU_CORES, None), SlotSet(EntitySlotEnum.VM_DISK_SPACE, None), SlotSet(EntitySlotEnum.VM_SCALABILITY, None), SlotSet(EntitySlotEnum.OBSERVATIONS, None), ] if tracker.get_slot(EntitySlotEnum.CONFIRM): # priorities = GLPIService.priority_values() # priority_values = list(priorities.keys()) # glpi_priority = priorities[priority_values[1]] # media ticket: Ticket = Ticket({ "username": "******", # TODO: set the actual logged in user "title": "Peticion de Maquina Virtual", "description": remove_accents(request_description), # 'priority': glpi_priority "itilcategories_id": 54, # Equipos de computo }) if local_mode: dispatcher.utter_message( f"Esta acción crearía un ticket con la siguiente información: {ticket}" ) ticket_id: Text = "DUMMY" events.append(SlotSet(EntitySlotEnum.TICKET_NO, ticket_id)) else: # TODO: integrate with GLPI try: response = glpi.create_ticket(ticket, ticket_type=2) # Solicitud ticket_id = response["id"] # This is not actually required as its value is sent directly to the utter_message events.append(SlotSet(EntitySlotEnum.TICKET_NO, ticket_id)) except GlpiException as e: logger.error("Error when trying to create a ticket", e) logger.error(f"Ticket: {ticket}") dispatcher.utter_message( template=UtteranceEnum.PROCESS_FAILED) return events dispatcher.utter_message(template=UtteranceEnum.TICKET_NO, ticket_no=ticket_id) dispatcher.utter_message(template=UtteranceEnum.CONFIRM_REQUEST) else: events.append(SlotSet(EntitySlotEnum.TICKET_NO, None)) dispatcher.utter_message(template=UtteranceEnum.PROCESS_CANCELLED) return events
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message("Hello World! from custom action") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None list_product_name = tracker.get_slot('product_name') product1 = list_product_name[0].strip() lent = len(list_product_name) if lent == 1: product2 = 'Samsung Galaxy A80' else: product2 = list_product_name[1].strip() print('===') print(product1) print(product2) print('===') response1 = dbconnector.get_product_detail(product1, exact=False) response2 = dbconnector.get_product_detail(product2, exact=False) print('===') print(response1) print(response2) print('===') if response1 is None: content = "Rất tiếc, tôi không thể tìm thấy sản phẩm " + product1 res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) elif response2 is None: content = "Rất tiếc, tôi không thể tìm thấy sản phẩm " + product2 res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) else: if len(response2['review_articles']) > 0: request_url = os.getenv( 'PERSONALREVIEWSUMMARY_API', 'http://tigi-personalreviewsummary:5000' ) + '/v1/api/personalsummarization' review_url = response2['review_articles'][0]['url'] # TODO: get user profile vector via service input_data = { 'user_demands': { 'screen': 0.1, 'battery': 0.9, 'camera': 0.4, 'config': 0.6, 'design': 0.2, 'durability': 0.1, 'feature': 0.4, 'sound': 0.9 }, 'product_url': review_url, "req_type": "short" } request_data = json.dumps(input_data) logger.info(request_data) logger.info(request_url) reviewservice_response = requests.post(url=request_url, data=request_data) logger.info(reviewservice_response) # print (response.content) reviewservice_result = json.loads( reviewservice_response.content) logger.info(reviewservice_result['summary']) desc2 = reviewservice_result['summary'] else: desc2 = p_name if len(response1['review_articles']) > 0: request_url = os.getenv( 'PERSONALREVIEWSUMMARY_API', 'http://tigi-personalreviewsummary:5000' ) + '/v1/api/personalsummarization' review_url = response1['review_articles'][0]['url'] # TODO: get user profile vector via service input_data = { 'user_demands': { 'screen': 0.1, 'battery': 0.9, 'camera': 0.4, 'config': 0.6, 'design': 0.2, 'durability': 0.1, 'feature': 0.4, 'sound': 0.9 }, 'product_url': review_url, "req_type": "short" } request_data = json.dumps(input_data) logger.info(request_data) logger.info(request_url) reviewservice_response = requests.post(url=request_url, data=request_data) logger.info(reviewservice_response) # print (response.content) reviewservice_result = json.loads( reviewservice_response.content) logger.info(reviewservice_result['summary']) desc1 = reviewservice_result['summary'] else: desc1 = p_name specs1 = { "Chip": response1['chipset'], "Kích thước màn hình": response1['screen_size'], "Bộ nhớ": response1['memory'], "Camera sau": response1['main_camera'], "Camera trước": response1['selfie_camera'] } specs2 = { "Chip": response2['chipset'], "Kích thước màn hình": response2['screen_size'], "Bộ nhớ": response2['memory'], "Camera sau": response2['main_camera'], "Camera trước": response2['selfie_camera'] } compare_product = [{ "type": "compare", "data": [{ "image": response1['image'], "name": response1['product'], "brand": response1['brand'], "desc": desc1, "lowest_price": response1['lowest_price'], "rating": response1['rating'], "specs": specs1 }, { "image": response2['image'], "name": response2['product'], "brand": response2['brand'], "desc": desc2, "lowest_price": response2['lowest_price'], "rating": response2['rating'], "specs": specs2 }] }] #dispatcher.utter_message(json.dumps(compare_product)) print('=====================') battery1 = int(response1['battery'].replace(' mAh', '')) battery2 = int(response2['battery'].replace(' mAh', '')) screen_size1 = response1['screen_size'].replace('\"', '') sz1 = float(screen_size1) screen_size2 = response2['screen_size'].replace('\"', '') sz2 = float(screen_size2) print(battery1) print(battery2) range_battery = abs(battery2 - battery1) range_screen_size = abs(sz2 - sz1) a = round(range_battery * 100 / battery2) print(a) print(range_screen_size) if a > 20: txt = 'Bạn nên dùng sản phẩm ' + product2 + ' vì nó lớn hơn tận ' + str( a) + '% so với ' + product1 elif 0.6 < range_screen_size < 0.8: txt = 'Bạn nên dùng sản phẩm ' + product2 + ' vì nó có kích thước màn hình to hơn ' + product1 else: txt = 'Bạn nên cân nhắc kỹ 2 sản phẩm này nha' suggest = { "type": "text", "data": { "content": txt, "speak": False, } } compare_product.insert(0, suggest) logger.info(json.dumps(compare_product)) dispatcher.utter_message(json.dumps(compare_product)) return None
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: s = [ "Did that answer your question?", "I hope that answered your question", "Is that what you were looking for?" ] gen_dict = { 28: 'an action', 12: 'an adventure', 16: 'an animation', 35: 'a comedy', 80: 'a crime', 99: 'a documentary', 18: 'a drama', 10751: 'a family', 14: 'a fantasy', 36: 'a history', 27: 'a horror', 10402: 'a music', 9648: 'a mystery', 10749: 'a romance', 878: 'a science fiction', 10770: 'a tv movie', 53: 'a thriller', 10752: 'a war', 37: 'a western' } tmdb.API_KEY = "5ce7e4a66621977d06b1c0e75961699b" search = tmdb.Search() # "Tell me about the movie Superman" if tracker.get_slot("title") is not None: title = next(tracker.get_latest_entity_values("title")) if tracker.get_slot("type") is not None: type = tracker.get_slot("type") if type == show: response = search.tv(query=title) else: response = search.movie(query=title) else: response = search.movie(query=title) id = response['results'][0]['id'] movie = tmdb.Movies(id) title = response['results'][0]['title'] g = response['results'][0]['genre_ids'][0] genre = gen_dict.get(g) credits = movie.credits() actor = credits['cast'][0]['name'] release = movie.info()['release_date'] plot = movie.info()['overview'] crew = credits['crew'] for person in crew: if person["department"] == "Directing": director = person["name"] break dispatcher.utter_message(title + " is " + genre + " movie starring " + actor + " and directed by " + director + ". It was released on " + release + "\nSummary: " + plot) dispatcher.utter_message(random.choice(s)) else: dispatcher.utter_message( "I don't understand your question. You can ask for help to see what kinds of questions you can ask" ) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None l_attribute = [ 'product_color', 'product_memory', 'product_battery', 'product_screensize', 'product_waterproof', 'product_selfie_score', 'product_lowest_price', 'product_ram', 'product_brand', 'product_demand' ] # if os.path.exists(PATH + 'personal.csv'): # os.remove(PATH + 'personal.csv') l_product_name = tracker.get_slot('product_name') suggestion = None if l_product_name is not None: # print('Cos ten dien thoai r' + product_name) data_row = dbconnector.get_product_detail(l_product_name[0], exact=False) print('---') print(data_row) print('---') if data_row is None: content = "Rất tiếc, tôi không thể tìm thấy sản phẩm " + l_product_name[ 0] res = [{ "type": "text", "data": { "content": content, "speak": True, } }] dispatcher.utter_message(json.dumps(res)) print(json.dumps(res)) return [] else: # print(data_row) img = data_row['image'] desc = data_row['specs'] name = data_row['product'] data_l_pr = [{"image": img, "description": desc, "name": name}] else: # Handle result from natural language understanding hungph # After contest, we can improve by implement concat value of extracted entity from NLU # Now let's me use rule-based # Read all defined filter intent from csv file try: atrribute_message += tracker.latest_message.get('text') except NameError: atrribute_message = tracker.latest_message.get('text') nlu_filter = [] filter_attribute = None filter_value = None for item in l_attribute: filter_attribute = tracker.get_slot(item) # Handle for True/False and product brand attribute which has no value if item in ['product_waterproof', 'product_brand']: filter_value = '' else: filter_value = tracker.get_slot('attr_level') if filter_attribute is not None: filter_element = {} if item == 'product_brand': filter_element['attribute'] = 'name' filter_element['value'] = filter_attribute nlu_filter.append(filter_element) elif item == 'product_demand': for demand in filter_attribute: filter_element['attribute'] = demand filter_element['value'] = '' nlu_filter.append(filter_element) filter_element = {} else: filter_element['attribute'] = filter_attribute filter_element[ 'value'] = '' if filter_value == None else filter_value nlu_filter.append(filter_element) filter_attribute = None filter_value = None print('[INFO] Received filter from NLU block: ' + str(nlu_filter)) # add_header_csv() filter_path = './filter.csv' filter_df = pd.read_csv(filter_path) # Set filter list to be all available filter filter_list = [] filter_text = [] for _, row in filter_df.iterrows(): # Create list for the current row filter_text_row = row.text filter_row = { 'attribute': row.attribute, 'operator': row.operator, 'value': row.value } filter_list.append(filter_row) filter_text.append(filter_text_row) # Set filter_attributes to be input of recommender API filter_attributes = [] for filter in nlu_filter: if filter['value'] == None: print( '[ERROR] Please check your NLU again. Maybe value of attribute is empty !' ) return False l_cased_filter = (str(filter['attribute']) + ' ' + str(filter['value'])).strip().lower() if l_cased_filter in filter_text: indices = [ i for i, x in enumerate(filter_text) if x == l_cased_filter ] for match_i in indices: filter_attributes.append({ 'attribute': filter_list[match_i]['attribute'], 'operator': filter_list[match_i]['operator'], 'value': filter_list[match_i]['value'] }) if filter['attribute'] == 'name': filter_attributes.append({ 'attribute': 'name', 'operator': 'find', 'value': filter['value'] }) print( '[INFO] Filter attribute list before handle call external recommender API: ' + str(filter_attributes)) input_data = { "input_string": atrribute_message, "count": "6", "filter_attributes": filter_attributes } # Boss thanhnd correct for me pls request_url = os.getenv( 'RECOMMENDER_API', 'http://tigi-recommender:5000') + '/v1/api/recommend' logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # filter_attributes = result request_data = json.dumps(input_data) logger.info("Request to server: " + str(request_data)) response = requests.post(url=request_url, data=request_data) logger.info("Response from server: " + str(response.content)) # print (response.content) item_re = json.loads(response.content) fix_rank = {'galaxy a80': 0, 'iphone x': 1, 'galaxy s10': 2} def cmp_items(a, b): proda = a['product'].lower() prodb = b['product'].lower() if proda in fix_rank and prodb in fix_rank: return -1 if fix_rank[proda] < fix_rank[prodb] else 1 elif proda in fix_rank: return -1 elif prodb in fix_rank: return 1 else: return -1 if proda < prodb else 1 item_re = sorted(item_re, key=cmp_to_key(cmp_items)) logger.info("Sorted: " + str(item_re)) # End handle result from nlu and call recommend api hungph l_brand = [item['brand'] for item in item_re] l_product = [item['product'] for item in item_re] # brand = 'Apple' # product_name = 'iPhone X' # print(l_brand) # print(l_product[1]) i = 0 data_l_pr = [] for i in range(len(l_brand)): # condition = { # "product" : l_product[i], # "brand": l_brand[i] # } # print(condition) data_row = dbconnector.get_product_detail_icase( l_brand[i], l_product[i]) if data_row: # print(data_row) img = data_row['image'] desc = data_row['specs'] name = data_row['product'] # data_l_pr = [] data_l_pr.append({ "image": img, "description": desc, "name": name }) best_product_name = data_l_pr[0]['name'] suggestion = { "type": "text", "data": { "content": "Trong những sản phẩm này, Tizzie cho rằng " + best_product_name + " sẽ phù hợp nhất với nhu cầu chơi game và công việc hàng ngày ở một mức giá tốt.", "speak": True } } mess = [ { "type": "item", "data": data_l_pr }, ] if suggestion: mess.append(suggestion) dispatcher.utter_message(json.dumps(mess, default=json_util.default)) print(mess)
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: tmdb.API_KEY = "5ce7e4a66621977d06b1c0e75961699b" discover = tmdb.Discover() s = [ "Did that answer your question?", "I hope that answered your question", "Is that what you were looking for?" ] gen_dict = { 28: 'action', 12: 'adventure', 16: 'animation', 35: 'comedy', 80: 'crime', 99: 'documentary', 18: 'drama', 10751: 'family', 14: 'fantasy', 36: 'history', 27: 'horror', 10402: 'music', 9648: 'mystery', 10749: 'romance', 878: 'science fiction', 10770: 'tv movie', 53: 'thriller', 10752: 'war', 37: 'western' } is_year = None movies = [] if tracker.get_slot( "genre" ) is not None: # tell me about action movies from 2018 -> get the genre and year (not full date) genre = next(tracker.get_latest_entity_values("genre")) genreID = list(gen_dict.keys())[list( gen_dict.values()).index(genre)] if tracker.get_slot("DATE") is not None: date = next(tracker.get_latest_entity_values("DATE")) p = re.compile( '\\s[0-9]{1,2}st' ) # matches 1 or 2 digits from 1 to 9 followed by st, occuring anywhere in string if p.search(date) is not None: sub = p.search(date).group() date = p.sub("", date) sub = sub.replace('st', ' ') date = sub.lstrip() + date else: date = date.replace("nd", "") date = date.replace("rd", "") date = date.replace("th", "") try: date_object = datetime.strptime(date, '%d %B %Y').date() is_year = False except ValueError: try: date_object = datetime.strptime(date, '%B %d %Y').date() is_year = False except ValueError: try: date_object = datetime.strptime(date, '%Y').date() is_year = True except ValueError: dispatcher.utter_message( "I don't understand your question") dispatcher.utter_message( 'If you are asking about a date, try it in the format of "1st of January 2020" or "January 1st 2020"' ) return [] if is_year: release = date_object.strftime("%Y") response = discover.movie(primary_release_year=release, with_genres=genreID) else: release = date_object.strftime("%B %d %Y") response = discover.movie(primary_release_date_gte=release, primary_release_date_lte=release, with_genres=genreID) if response['results']: for i in range(0, 3): movies.append(response['results'][i]['title']) if len(movies) == 3: break titles = "" if len(movies) == 0: dispatcher.utter_message( "No " + genre + " movies were released on that day") elif len(movies) == 1: titles = movies[0] elif len(movies) == 2: titles = movies[0] + " and " + movies[1] else: titles = movies[0] + " , " + movies[1] + " and " + movies[2] # the most popular GENRE movies released IN YEAR/ ON JANUARY 1ST YEAR/ ON if is_year: dispatcher.utter_message("The most popular " + genre + " movies from that year were " + titles) dispatcher.utter_message(random.choice(s)) else: dispatcher.utter_message("The most popular " + genre + " movies from that date were " + titles) dispatcher.utter_message(random.choice(s)) else: # genre, date, type dispatcher.utter_message( "I don't understand your question. You can ask for help to see what kinds of questions you can ask" ) # tell me about action movies from 2018 return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None l_name = tracker.get_slot('product_name') if l_name is None: txt = domain['templates']['utter_default'][1]['text'] response = [{ "type": "text", "data": { "content": txt, "speak": True, } }] print(json.dumps(response)) dispatcher.utter_message(json.dumps(response)) else: p_name = l_name[0] response = dbconnector.get_product_detail(p_name, exact=False) url_image = response['image'] product = response['product'] brand = response['brand'] if len(response['review_articles']) > 0: request_url = os.getenv( 'PERSONALREVIEWSUMMARY_API', 'http://tigi-personalreviewsummary:5000' ) + '/v1/api/personalsummarization' review_url = response['review_articles'][0]['url'] # TODO: get user profile vector via service input_data = { 'user_demands': { 'screen': 0.1, 'battery': 0.9, 'camera': 0.4, 'config': 0.6, 'design': 0.2, 'durability': 0.1, 'feature': 0.4, 'sound': 0.9 }, 'product_url': review_url, "req_type": "short" } request_data = json.dumps(input_data) logger.info(request_data) logger.info(request_url) reviewservice_response = requests.post(url=request_url, data=request_data) logger.info(reviewservice_response) # print (response.content) reviewservice_result = json.loads( reviewservice_response.content) logger.info(reviewservice_result['summary']) desc = reviewservice_result['summary'] else: desc = p_name lowest_price = response['lowest_price'] rating = response['rating'] specs = { "Chip": response['chipset'], "Kích thước màn hình": response['screen_size'], "Bộ nhớ": response['memory'], "Camera sau": response['main_camera'], "Camera truoc": response['selfie_camera'] } detail_product = [{ "type": "detail", "data": [{ "image": url_image, "product": product, "brand": brand, "desc": desc, "lowest_price": lowest_price, "specs": specs }] }] dispatcher.utter_message(json.dumps(detail_product)) print(json.dumps(detail_product))
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionAskCuisine====") print() location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") if (latEntity and lonEntity): lat = latEntity lon = lonEntity if (user_locationEntity or (latEntity and lonEntity)): if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] SlotSet("location", locationEntities["title"]) print("locationDetails: ", locationEntities) print() ## check if the restaurants are available in the user provided location if (locationEntities["restaurants_available"] == "no"): dispatcher.utter_message( "Sorry, No restaurants available in the location you have provided 🤯" ) return [UserUtteranceReverted()] else: locationDetails = zomatoApi.getLocationDetails( locationEntities["entity_id"], locationEntities["entity_type"]) dispatcher.utter_template("utter_ask_cuisine", tracker) dispatcher.utter_custom_json({ "payload": "quickReplies", "data": locationDetails["top_cuisines"] }) return [ SlotSet("city_id", locationEntities["city_id"]), SlotSet("location_id", locationEntities["entity_id"]), SlotSet("location_type", locationEntities["entity_type"]) ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: is_QA = get_user_property((tracker.current_state())["sender_id"], 'is_QA') if is_QA > 0: answer = call_api_question_answer(tracker.latest_message['text']) dispatcher.utter_message(answer) #set_user_property((tracker.current_state())["sender_id"], 'is_QA', is_QA - 1) return None l_name = tracker.get_slot('product_name') if l_name is None: txt = domain['templates']['utter_default'][1]['text'] response = [{ "type": "text", "data": { "content": txt, "speak": False, } }] print(json.dumps(response)) dispatcher.utter_message(json.dumps(response)) else: p_name = l_name[0] response = dbconnector.get_product_detail(p_name, exact=False) price_history = response['price_history'] print(price_history) print('-----') lent = len(price_history) response_history = [] today = datetime.date.today() inserted_date = datetime.date.today() - datetime.timedelta(15) first_date = price_history[0]['update_time'].date() index = 0 while inserted_date < first_date: h = price_history[0].copy() h['update_time'] = datetime.datetime.fromordinal( inserted_date.toordinal()) response_history.append(h) #print("\tAdd first ", price_history[index]['update_time'], inserted_date) inserted_date += datetime.timedelta(1) while inserted_date <= today: while index < len(price_history) and price_history[index][ 'update_time'].date() < inserted_date: response_history.append(price_history[index]) #print("\tAdd leftover ", price_history[index]['update_time']) index += 1 if index < len(price_history) and price_history[index][ 'update_time'].date() == inserted_date: response_history.append(price_history[index]) #print("\tAdd true date ", price_history[index]['update_time']) index += 1 elif index > 0: h = price_history[index - 1].copy() h['update_time'] = datetime.datetime.fromordinal( inserted_date.toordinal()) response_history.append(h) #print("\tAdd old data ", price_history[index-1]['update_time']) else: break inserted_date += datetime.timedelta(1) #print(response_history) history_product = [{ "type": "price_history", "data": response_history }] dispatcher.utter_message( json.dumps(history_product, default=json_util.default)) print(json.dumps(history_product, default=json_util.default))
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain): config = {"user_key": "c021e17456f14a6acfad27e5019aee36"} zomato = zomatopy.initialize_app(config) #Getting the location, cuisine and budget from the tracker loc = tracker.get_slot('location').lower() cuisine = tracker.get_slot('cuisine').lower() budget_min = int(tracker.get_slot('budget_min')) budget_max = int(tracker.get_slot("budget_max")) location_detail = zomato.get_location(loc, 1) d1 = json.loads(location_detail) lat = d1["location_suggestions"][0]["latitude"] #latittude lon = d1["location_suggestions"][0]["longitude"] #longitude cuisines_dict = { 'american': 1, 'chinese': 25, 'italian': 55, 'mexican': 73, 'north indian': 50, 'south indian': 85 } #getting the restaurants as per the preferences results = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 100) d = json.loads(results) response = "" if d['results_found'] == 0: dispatcher.utter_message( "Sorry! I could not find any suitable restaurants as per your preferences.\n" ) else: price_range = [1] #Setting the price range if budget_min == 300 and budget_max == 700: price_range = [2] elif budget_min == 10000: price_range = [3, 4] #Filtering the list of restaurants based on the price range and storing in a list res_recom = [ res for res in d['restaurants'] if res['restaurant']['price_range'] in price_range ] #sorting the restaurants based on the user ratings res_recom_sorted = sorted(res_recom, key=lambda x: x['restaurant'][ 'user_rating']['aggregate_rating'], reverse=True) global email_res res_response = [ res for index, res in enumerate(res_recom_sorted) if index <= 4 ] #List of restaurants to display email_res = [ res for index, res in enumerate(res_recom_sorted) if index < 10 ] #List of restaurants to send over email #Getting the response in a string for index, restaurant in enumerate(res_response): response= response + str(index) + ". " + restaurant['restaurant']['name']+ " at "+ \ restaurant['restaurant']['location']['address'] + " has been rated " +\ str(restaurant["restaurant"]['user_rating']['aggregate_rating']) + "\n\n" dispatcher.utter_message( "------Here are some recommendations for you!------\n" + response) return [SlotSet('location', loc)]
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger = logging.getLogger(__name__) # logger.debug('DEFINE ACTION') #logger.debug(CONFIG) # logger.debug(tracker.current_state()) last_entities = tracker.current_state()['latest_message']['entities'] site = tracker.current_state().get('sender_id') word = '' slots = tracker.current_state().get('slots') for slot in slots: if slot == "word": if not word or len(word) <= 0: word = slots[slot] for raw_entity in last_entities: # logger.debug(raw_entity) if raw_entity.get('entity', '') == "word": word = raw_entity.get('value', '') slotsets = [] if word and len(word) > 0: word_record = await find_word(word) if not word_record: # try fuzzy match word_record = await search_word(word) if word_record: slotsets.append(SlotSet('word', word_record.get('word'))) meanings = word_record.get('meanings') if len(meanings) > 0: meaning = meanings[0] if meaning.get('def', False): meaning_parts = [] if meaning.get('speech_part', False): meaning_parts.append(' the {} '.format( meaning.get('speech_part'))) meaning_parts.append(word_record.get('word')) meaning_parts.append(' means {}.'.format( meaning.get('def'))) if meaning.get( 'synonyms', False) and len(meaning.get('synonyms')) > 0: if len(meaning.get('synonyms')) > 1: meaning_parts.append( ' It has synonyms {}.'.format(", ".join( meaning.get('synonyms')))) else: meaning_parts.append( ' It has a synonym {}. '.format( meaning.get('synonyms')[0])) await publish( 'hermod/' + site + '/display/show', { 'frame': 'https://en.wiktionary.org/wiki/' + word_record.get('word') }) #slotsets.append(SlotSet('last_wiktionary_search',0)) if len(meanings) > 1: meaning2 = meanings[1] meaning_parts.append(' It can also be ') if meaning2.get('speech_part', False): meaning_parts.append(' an {} '.format( meaning2.get('speech_part'))) meaning_parts.append(' {}.'.format( meaning2.get('def'))) if meaning2.get('synonyms', False) and len( meaning2.get('synonyms')) > 0: if len(meaning2.get('synonyms')) > 1: meaning_parts.append( ' with synonyms {}'.format(", ".join( meaning2.get('synonyms')))) else: meaning_parts.append( ' with a synonym {}'.format( meaning2.get('synonyms')[0])) dispatcher.utter_message(text="".join(meaning_parts)) slotsets.append(FollowupAction('action_end')) else: dispatcher.utter_message( text="I didn't hear the word you want defined. Try again") return slotsets