示例#1
0
    def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:

        slot_values = self.extract_other_slots(dispatcher, tracker, domain)
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)

        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))

        else:
            temp = tracker.get_latest_entity_values('PER')
            aux = None
            for i in temp:
                if i.lower() != "hola":
                    aux = i
            aux2 = next(tracker.get_latest_entity_values('persona'), None)
            loc = next(tracker.get_latest_entity_values('LOC'), None)
            misc = next(tracker.get_latest_entity_values('MISC'), None)
            if aux is None and aux2 is not None:
                return [SlotSet('persona', aux2.title())]
            elif aux is not None and aux is not "Hola":
                return [SlotSet('persona', aux.title())]
            elif loc is not None:
                return [SlotSet('persona', loc)]
            elif misc is not None:
                return [SlotSet('persona', misc)]
            else:
                dispatcher.utter_message(template="utter_tell_me_name")
                return []

        return [SlotSet(slot, value) for slot, value in slot_values.items()]
示例#2
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     transform_dic = {
         '优势': 'strength',
         '介绍': 'info',
         '报价': 'price',
         '解读项': 'items'
     }
     scene = None
     try:
         scene = next(tracker.get_latest_entity_values("scene"))
     except:
         scene = tracker.get_slot("scene")
     finally:
         if scene is None:
             scene = '报价'
     text_order = {-1: "最便宜", 0: "最贵", 1: "第二贵"}
     order = int(next(tracker.get_latest_entity_values("order"))) - 1
     with driver.session() as session:
         product, res = session.read_transaction(get_product_of,
                                                 transform_dic[scene],
                                                 order)
         dispatcher.utter_message(
             text=f"{text_order[order]}的产品是{product},它的{scene}是:{res}")
     return [SlotSet("scene", scene), SlotSet("product", product)]
示例#3
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        print("====Inside ActionSearchRestaurants Without Cuisine====")
        print()
        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")

        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)

        ##set the cuisine to any of the cuisine name or you leave it empyt
        cuisine_id = ""
        restaurants = zomatoApi.searchRestaurants(entity_id, entity_type,
                                                  cuisine_id, "")
        dispatcher.utter_message(
            "Here are the few restaurants I have found 😋!!!")
        dispatcher.utter_custom_json({
            "payload": "cardsCarousel",
            "data": restaurants
        })
示例#4
0
    def run(dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        user_id = (tracker.current_state())["sender_id"]
        cust_name = next(tracker.get_latest_entity_values("cust_name"), None)
        cust_sex = next(tracker.get_latest_entity_values("cust_sex"), None)
        bot_position = "Mình"
        dispatcher.utter_message("here's what I found:")
        if (cust_sex is None):
            cust_sex = "Quý khách"

        if (cust_sex == "anh") | (cust_sex == "chị"):
            bot_position = "em"
        elif (cust_sex == "cô") | (cust_sex == "chú"):
            bot_position = "cháu"
        else:
            cust_sex = "bạn"
            bot_position = "mình"

        if not cust_name:
            #dispatcher.utter_template("utter_greet_name",tracker)
            return []

        return [
            SlotSet('cust_name', cust_name),
            SlotSet('cust_sex', cust_sex),
            SlotSet('bot_position', bot_position)
        ]
示例#5
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        sender = tracker.sender_id
        entity = tracker.latest_message["entities"][0]['entity']

        if entity == 'interval':
            interval = next(tracker.get_latest_entity_values(entity))
            interval = interval.split(" ")
            interval_str = "del " + interval[0] + "-" + interval[
                1] + " al " + interval[2] + "-" + interval[3]

            end_range = int(interval[2])
            links = []

            if int(interval[3]) > int(interval[1]):
                end_range = int(interval[0]) + (12 - int(interval[0])) + int(
                    interval[2])

            for x in range(int(interval[0]), end_range + 1):
                if x <= 12:
                    links.append(generate_nomina(str(x) + "-" + interval[1]))

            dispatcher.utter_message("Aquí tienes las nóminas del periodo " +
                                     interval_str)

            for link in links:
                dispatcher.utter_message("media " + link)

        elif entity == 'month':
            months = next(tracker.get_latest_entity_values(entity))
            months = months.split("/")
            utter_months = ""
            month_str = ""

            links = []

            if len(months) == 1:
                unit_month = months[0].split(" ")
                # print("UNIT MONTH ", unit_month)
                month_str = unit_month[0] + "-" + unit_month[1]
                utter_months = "Aqui tienes la nomina del " + month_str

                links.append(generate_nomina(month_str))

            elif len(months) > 1:
                for month in months:
                    month = month.split(" ")
                    links.append(generate_nomina(month[0] + "-" + month[1]))
                    month_str = month_str + month[0] + "-" + month[1] + ", "
                utter_months = "Aqui están las nominas de los meses " + month_str.strip(
                    ", ")

            dispatcher.utter_message(utter_months)

            for link in links:
                dispatcher.utter_message("media " + link)

        return []
示例#6
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        feat = eval(next(tracker.get_latest_entity_values("feature"), None))
        flag = eval(next(tracker.get_latest_entity_values("flag"), None))
        message = calc_tax(tracker.sender_id, feat, flag)
        dispatcher.utter_message(text=message)

        return []
示例#7
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        rezim = next(tracker.get_latest_entity_values("rezim_vzt"), None)
        procenta = next(tracker.get_latest_entity_values("procenta"), None)
        logger.info("Vypinam VZT rezim {}, {}[%]".format(rezim, procenta))
        self.call_service("climate.set_preset_mode", entity_id="climate.atrea", preset_mode="Off")
        dispatcher.utter_message(template = "utter_potvrzeni")

        return []
示例#8
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:

        currLoc = None  #Replace with func to get current location
        source = next(tracker.get_latest_entity_values('loc'), currLoc)
        destination = next(tracker.get_latest_entity_values('loc'), None)
示例#9
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:

        currLoc = None  #Replace with func to get current location
        location = next(tracker.get_latest_entity_values('loc'), currLoc)
        activity = next(tracker.get_latest_entity_values('activity'), None)
        cuisine = next(tracker.get_latest_entity_values('cuisine'), None)
        ambience = next(tracker.get_latest_entity_values('ambience'), None)
        outdoor_seating = next(
            tracker.get_latest_entity_values('outdoor_seating'), None)
        age_allowed = next(tracker.get_latest_entity_values('age_allowed'),
                           None)
        noise_level = next(tracker.get_latest_entity_values('noise_level'),
                           None)
        accept_credit_card = next(
            tracker.get_latest_entity_values('accept_credit_card'), None)
        price_range = next(tracker.get_latest_entity_values('price_range'),
                           None)
        wifi = next(tracker.get_latest_entity_values('wifi'), None)

        if isinstance(activity, str):
            activity = [activity]

        rows = query_yelp_db_2(conn,
                               location,
                               activity=activity,
                               cuisine=cuisine,
                               ambience=ambience,
                               outdoor_seating=outdoor_seating,
                               age_allowed=age_allowed,
                               noise_level=noise_level,
                               accept_credit_card=accept_credit_card,
                               price_range=price_range,
                               wifi=wifi)

        if isinstance(rows, list):
            new_rows = []
            for i, rowj in enumerate((analyze_tweets([row[2] for row in rows],
                                                     10, twitter_api))):
                for row in rows:
                    if rowj in row:
                        new_rows.append(
                            str(i + 1) + ": " + rowj + '<br>Tip: ' + row[-1])

            dispatcher.utter_message('<br><br>'.join(new_rows))
        else:
            dispatcher.utter_message(rows)
        for row in rows:
            print(row[2], row[9], row[10])
示例#10
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        sender = tracker.sender_id
        intent = tracker.latest_message["intent"]["name"]

        if intent == "category_appointment":
            date = tracker.slots.get("day")
            date = get_date_formatted(date=date)
            period = next(tracker.get_latest_entity_values("period"))

            if period == "medio dia":
                period = 'noon'
            elif period == "mañana":
                period = 'morning'
            elif period == 'tarde':
                period = 'afternoon'

            message = get_availability(date, period)

        elif intent == "appointment_with_category":
            entity = tracker.latest_message["entities"][0]['entity']
            if entity == 'day':
                day = next(tracker.get_latest_entity_values(entity))
                SlotSet("day", day)
                date = get_date_formatted(day)
                period = 'noon'
                message = get_availability(date, period)

            elif entity == 'interval':
                interval = next(tracker.get_latest_entity_values(entity))
                interval = interval.split(' - ')[0]
                date = interval.split('from: ')[1]
                interval = date.split('T')[1]
                day = date.split('T')[0]
                day = day.split('-')
                day = day[2] + '-' + day[1] + '-' + day[0]
                day = '00:00:00 ' + day
                SlotSet('day', day)

                period = None
                if interval[:2] == '12':
                    period = 'afternoon'
                elif interval[:2] == '04':
                    period = 'morning'

                date = get_date_formatted(day)
                message = get_availability(date, period)

        dispatcher.utter_message(message)

        return []
示例#11
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     try:
         feat = eval(next(tracker.get_latest_entity_values("feature"),
                          None))
         flag = eval(next(tracker.get_latest_entity_values("flag"), None))
         message = property_count(feat, flag)
         dispatcher.utter_message(text=message)
     except:
         message = dispatcher.utter_message(template="utter_sorry")
         dispatcher.utter_message(message)
     save_data(tracker.sender_id, (tracker.latest_message)['text'], message)
     return []
示例#12
0
    def validate_nom_personne(
        self,
        slot_value: Any,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: DomainDict,
    ) -> Dict[Text, Any]:
        """Validate nom_prenom value."""

        username = ""
        prediction = tracker.latest_message
        entities = prediction['entities']

        print(str(tracker.get_latest_entity_values('username')))

        if entities is not None and len(entities) > 0:
            if (tracker.get_latest_entity_values('username') is not None):
                print(entities[0])
                print("-----11111111---- " + entities[0]["value"])
                username = entities[0]["value"]  # "Kabore"
        elif username == "":
            # get one entity value
            username = tracker.get_latest_entity_values('username')
            print(username)

        myintent = prediction["intent"].get("name")
        if (myintent == "salutations"):
            return {"nom_personne": None}

        slot_value_nom_personne = tracker.get_slot("nom_personne")
        print("user_name  : ", slot_value_nom_personne)

        # prediction['entities'][0]['entity']
        # return [SlotSet("entity", entity_type)]
        if username is not None and username != "":
            return {"nom_personne": username}

        elif slot_value is not None:
            # Le nom_prenom est valid, tu peux donc faire la suite de tes action
            print("La valeur de mon slot. ----   " + str(slot_value))
            dispatcher.utter_message("Bonjour .....1111.")
            return {"nom_personne": slot_value}

        else:
            # La validation à echouer
            # Comme tu as mis un loop l'utilisateur sera demander de nouveau
            dispatcher.utter_message("Bonjour ......")
            return {"nom_personne": None}
示例#13
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        bind_logger(tracker)
        metadata = next(tracker.get_latest_entity_values(METADATA_ENTITY_NAME))
        hashed_id = metadata[REMINDER_ID_PROPERTY_NAME]
        reminder_id = self.hashids.decode(hashed_id)[0]

        session = session_factory()
        try:
            reminder = _query_reminder(session, reminder_id)

            self._send_reminder(dispatcher, tracker, reminder, hashed_id)

            reminder.last_reminded_at = datetime.utcnow()
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

        return []
示例#14
0
    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[EventType]:

        events = self._get_events()
        location = next(tracker.get_latest_entity_values("location"), None)
        events_for_location = None
        if location:
            location = location.title()
            events_for_location = [
                e for e in events if e.city.lower() == location.lower()
                or e.country.lower() == location.lower()
            ]

        if not events:
            dispatcher.utter_message(
                text=
                "Looks like we don't have currently have any Rasa events planned."
            )
        else:
            self._utter_events(tracker, dispatcher, events,
                               events_for_location, location)

        return []
示例#15
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        result = ""
        local = next(tracker.get_latest_entity_values('GPE'), None)
        if local is None:
            latitude, longitude = "-24.7105133", "-53.7477903"
            result = "Não entendi o local que deseja. Vou dizer a temperatura de Toledo, Paraná, Brazil. "
        else:
            geolocation = geocoder.tomtom(
                location=local, key=tomtom_KEY)
            geo_json = geolocation.json
            geo_json = json.dumps(geo_json)
            geo_json = json.loads(geo_json)
            latitude, longitude = str(geo_json['lat']), str(geo_json['lng'])

        url = "http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric&lang=pt_br".format(
            latitude, longitude, openweathermap_KEY)

        response = requests.request("GET", url)
        json_data = response.json()
        description = json_data['weather'][0]['description'].capitalize()
        temperatura = json_data['main']['temp']
        umidade = json_data['main']['humidity']
        result += '{}. A temperatura no momento é de {}°C e umidade do ar é de {}%.'.format(
            description, temperatura, umidade)

        dispatcher.utter_message(text=result)

        return []
示例#16
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        file = open("outputRomana.csv", "a")

        last_message = tracker.latest_message.get("text", "")
        file.write(str(last_message))
        file.write(",")

        page_type = next(tracker.get_latest_entity_values('page_type'), None)

        if page_type is not None:
            if "principală" in page_type:
                dispatcher.utter_message("Mergi la pagina principala")
                file.write("Mergi la pagina principala")
                file.write("\n")
            elif "anterioară" in page_type:
                dispatcher.utter_message("Mergi la pagina anterioara")
                file.write("Mergi la pagina anterioara")
                file.write("\n")
            else:
                dispatcher.utter_message("Mergi la pagina urmatoare")
                file.write("Mergi la pagina urmatoare")
                file.write("\n")
            file.close()
            return []

        dispatcher.utter_message(template="utter_repeat")

        file.close()
        return []
示例#17
0
    def _utter_next_event(self, tracker: Tracker,
                          dispatcher: CollectingDispatcher) -> None:
        location = next(tracker.get_latest_entity_values("location"), None)
        events = self._get_events()

        if location:
            events_for_location = [
                e for e in events
                if e.city == location or e.country == location
            ]
            if not events_for_location and events:
                next_event = events[0]
                dispatcher.utter_template(
                    "utter_no_event_for_location_but_next",
                    tracker,
                    **next_event.as_kwargs(),
                )
            elif events_for_location:
                next_event = events_for_location[0]
                dispatcher.utter_template("utter_next_event_for_location",
                                          tracker, **next_event.as_kwargs())
        elif events:
            next_event = events[0]
            dispatcher.utter_template("utter_next_event", tracker,
                                      **next_event.as_kwargs())
示例#18
0
    async def validate_insurance_policy_type(
        self,
        value: Text,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> Dict[Text, Any]:
        """Validates value of 'insurance_policy_type' slot"""
        if tracker.get_intent_of_latest_message() == "get_a_quote":
            return {"insurance_policy_type": None}

        insurance_policy_type = tracker.get_slot("insurance_policy_type")

        if isinstance(insurance_policy_type, list):
            insurance_policy_type = next(
                tracker.get_latest_entity_values("quote_insurance_type"), None
            )
            # insurance_policy_type = insurance_policy_type[0]

        print(value, insurance_policy_type)
        categories = [category.lower() for category in list_categories()]
        x = "{}, " * (len(categories) - 1) + "{}."
        if insurance_policy_type.lower() not in categories:
            dispatcher.utter_message(
                f"You can only select from these available policies.  {x} \nPlease choose one of those options.".format(
                    *categories
                )
            )
            return {"insurance_policy_type": None}

        return {"insurance_policy_type": insurance_policy_type}
示例#19
0
	def run(self, dispatcher: CollectingDispatcher,
			tracker: Tracker,
			domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

		data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf", "languages.csv")
		wals_data = pd.read_csv(data_path)
		entities = list(tracker.get_latest_entity_values("language"))

		if len(entities) > 0:
			query_lang = entities.pop()
			query_lang = str(google_translate(query_lang))
			if len(query_lang.split())>1:
				query_lang=query_lang.split()[-1]
			query_lang = query_lang.lower().capitalize().strip()
			print(query_lang, 'translated')
			out_row = wals_data[wals_data["Name"] == query_lang].to_dict("records")
			print(out_row)
			if out_row:
				out_row = out_row[0]
				out_text = "Die Sprache %s gehört zur Familie %s \nmit der Gattung %s \nund hat ISO-Code %s" % (out_row["Name"], out_row["Family"], out_row["Genus"], out_row["ISO_codes"])
				dispatcher.utter_message(text = out_text)
			else:
				dispatcher.utter_message(text = "Es tut uns leid! Wir haben keine Aufzeichnungen für die Sprache` %s" % query_lang)

				return []
示例#20
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf",
                                 "languages.csv")
        wals_data = pd.read_csv(data_path)
        entities = list(tracker.get_latest_entity_values("language"))

        if len(entities) > 0:
            query_lang = entities.pop()
            # import pdb;pdb.set_trace()
            query_lang = translator.translate(query_lang, dest='en').text
            query_lang = query_lang.lower().capitalize()
            print(query_lang)

            out_row = wals_data[wals_data["Name"] == query_lang].to_dict(
                "records")

            if len(out_row) > 0:
                out_row = out_row[0]
                out_text = "La lingua %s appartiene alla famiglia %s\n con Genus as %s\n e ha il codice ISO %s\n Hai trovato quello che cercavi?" % (
                    translator.translate(out_row["Name"], dest='en').text,
                    translator.translate(out_row["Family"], dest='en').text,
                    translator.translate(out_row["Genus"], dest='en').text,
                    translator.translate(out_row["ISO_codes"], dest='en').text)
                # out_text = "La lingua %s appartiene alla famiglia %s\n con Genus as %s\n e ha il codice ISO %s\n Hai trovato quello che cercavi?" % ((out_row["Name"]), (out_row["Family"]),(out_row["Genus"]), (out_row["ISO_codes"]))
                dispatcher.utter_message(text=out_text)
            else:
                dispatcher.utter_message(
                    text="Scusate! Non abbiamo record per la lingua %s" %
                    query_lang)

        return []
示例#21
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf",
                                 "languages.csv")
        wals_data = pd.read_csv(data_path)
        entities = list(tracker.get_latest_entity_values("language"))

        if len(entities) > 0:
            query_lang = entities.pop()
            query_lang = google_translate(query_lang)
            query_lang = query_lang.lower().capitalize().strip()
            # print(query_lang)

            out_row = wals_data[wals_data["Name"] == query_lang].to_dict(
                "records")

            if len(out_row) > 0:
                out_row = out_row[0]
                out_text = "Language %s is spoken at \n lattitude:  %s\n Longitude: %s\n \n" % (
                    out_row["Name"], out_row["Latitude"], out_row["Longitude"])
                dispatcher.utter_message(text=out_text)
            else:
                dispatcher.utter_message(
                    text="Sorry! We don't have records for the language %s" %
                    query_lang)

        return []
示例#22
0
 def run(
     self,
     dispatcher: CollectingDispatcher,
     tracker: Tracker,
     domain: Dict[Text, Any],
 ) -> List[Dict]:
     dict_vitri = {
         "bến ninh kiều":
         "Nằm ở: 38 Hai Bà Trưng, ​​Tân An, Ninh Kiều, Cần Thơ",
         "chợ nổi cái răng":
         "Nằm ở: 46 Hai Bà Trưng, Lê Bình, Cái Răng, Cần Thơ",
         "nhà cổ bình thuỷ":
         "Nằm ở: 144 Bùi Hữu Nghĩa, Bình Thuỷ, Bình Thủy, Cần Thơ, Việt Nam",
         "chùa ông":
         "Nằm ở: 32, Hai Bà Trưng, Tân An, Ninh Kiều, Cần Thơ, Việt Nam",
         "vườn cây mỹ khánh":
         "Nằm ở: Mỹ Khánh, Phong Điền, Cần Thơ, Việt Nam",
         "chợ đêm":
         "Nằm ở: Hai Bà Trưng, Tân An, Ninh Kiều, Cần Thơ, Việt Nam"
     }
     if any(tracker.get_latest_entity_values("vi_tri")):
         # entity was picked up, validate slot
         vitri = tracker.get_slot("vi_tri")
         ask = dict_vitri[vitri]
         dispatcher.utter_template("utter_vitri",
                                   tracker,
                                   vi_tri=vitri,
                                   tt_vitri=ask)
     else:
         # no entity was picked up, we want to ask again
         dispatcher.utter_template("utter_no_vitri", tracker)
     return []
示例#23
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf",
                                 "languages.csv")
        wals_data = pd.read_csv(data_path)
        entities = list(tracker.get_latest_entity_values("language"))

        if len(entities) > 0:
            query_lang = entities.pop()
            query_lang = query_lang.lower().capitalize()
            print(query_lang)

            out_row = wals_data[wals_data["Name"] == query_lang].to_dict(
                "records")

            if len(out_row) > 0:
                out_row = out_row[0]
                out_text = "Language %s belongs to the Family %s\n with Genus as %s\n and has ISO code %s" % (
                    out_row["Name"], out_row["Family"], out_row["Genus"],
                    out_row["ISO_codes"])
                dispatcher.utter_message(text=out_text)
            else:
                dispatcher.utter_message(
                    text="Sorry! We don't have records for the language %s" %
                    query_lang)

        return []
示例#24
0
 async def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]):
     cuisine = tracker.get_slot('cuisine')
     number_of_seats = tracker.get_slot('number_for_restaurant')
     outdoor_seating = tracker.get_slot('outdoor_seating')
     required_details = next(
         tracker.get_latest_entity_values('restaurant_form_details'), None)
     if required_details != None:
         if required_details == 'cuisine':
             cuisines = self.cuisine_db()
             dispatcher.utter_message(text="Avaialble Cuisines are")
             dispatcher.utter_message(text=cuisines)
         if required_details == 'people':
             dispatcher.utter_message(
                 text="number of people can range from 1 to 10")
     else:
         if cuisine == None:
             cuisines = self.cuisine_db()
             dispatcher.utter_message(text="Avaialble Cuisines are")
             dispatcher.utter_message(text=cuisines)
             return []
         if number_of_seats == None:
             dispatcher.utter_message(
                 text="Number of people can range from 1 to 10")
             return []
         if outdoor_seating == None:
             dispatcher.utter_message(
                 text=
                 "Enter Yes if u want to sit outside or no if you want to sit inside"
             )
             return []
     return []
示例#25
0
    async def validate_dob(
        self,
        value: Text,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> Dict[Text, Any]:
        """Validates value of 'dob' slot"""

        # check whether entered date is a valid dob
        dob = tracker.get_slot("dob")

        # Sometimes slot is being double filled.
        if isinstance(dob, list):
            dob = next(tracker.get_latest_entity_values("dob"), None)
        print(value, dob)

        # Check if date matches required pattern
        if bool(re.match(DOB_PATTERN, str(dob))):
            return {"dob": dob}
        else:
            dispatcher.utter_message(
                f"{dob}, is not in the required format, enter date as 'dd/mm/yyy' "
            )
            return {"dob": None}
示例#26
0
	def run(self, dispatcher: CollectingDispatcher,
	    tracker: Tracker,
	    domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

		data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf", "country_lang.csv")
		wals_data_lang = pd.read_csv(data_path)
		entities = list(tracker.get_latest_entity_values("country"))
		print("intent found")
		if len(entities) > 0:
			query_country = entities.pop()
			query_country = str(google_translate(query_country))
			if len(query_country.split()) > 1:
				query_country = query_country.split()[-1]
			query_country = query_country.lower().capitalize().strip()
			print("entity found")
			# filtered = wals_data_lang[wals_data_lang["macroarea"] == query_country].to_dict("records")
			# print("entity found")
			# out_list = []
			# for record in filtered:
			# 	out_list.append(record["ascii_name"])
			#
			# if len(out_list) < 5 and len(out_list) > 0:
			# 	out_str = ", ".join(out_list[:5])
			out_str = wals_data_lang[wals_data_lang["Country"] == query_country]["Languages"]
			if len(out_str) > 0:
				out_str = out_str.values[0]

			if len(out_str) > 0:
			    dispatcher.utter_message(text = "Einige der in {} gesprochenen Sprachen sind: {}".format(query_country, out_str))
			else:#Wir entschuldigen uns. Amerika existiert nicht in unserer Datenbank.
			    dispatcher.utter_message(text = "Wir entschuldigen uns. %s existiert nicht in unserer Datenbank. " % query_country)

		return []
示例#27
0
 def run(self, dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     schedule_type = next(tracker.get_latest_entity_values('schedule'), None)
     if schedule_type is not None:
         dispatcher.utter_message("Θα βρείτε το {}".format(schedule_type)+" στον παρακάτω σύνδεσμο: \n https://ihst.csd.auth.gr/courses-exams-schedule/")
     else:
         dispatcher.utter_message("Θα βρείτε τα προγράμματα μαθημάτων και εξετάσεων στον παρακάτω σύνδεσμο: \n https://ihst.csd.auth.gr/courses-exams-schedule/")
     return []
示例#28
0
 def run(
     self,
     dispatcher: CollectingDispatcher,
     tracker: Tracker,
     domain: Dict[Text, Any],
 ) -> List[Dict]:
     dict_thongtin = {
         "bến ninh kiều":
         "Theo Wiki: Bến Ninh Kiều là một địa danh du lịch có từ lâu và hấp dẫn du khách bởi phong cảnh sông nước hữu tình và vị trí thuận lợi nhìn ra dòng sông Hậu. Từ lâu bến Ninh Kiều đã trở thành biểu tượng về nét đẹp thơ mộng bên bờ sông Hậu của cả Thành phố Cần Thơ, thu hút nhiều du khách đến tham quan và đi vào thơ ca.",
         "chợ nổi cái răng":
         "Theo Wiki: Chợ nổi Cái Răng là chợ nổi chuyên trao đổi, mua bán nông sản, các loại trái cây, hàng hóa, thực phẩm, ăn uống ở trên sông và là điểm tham quan đặc sắc của quận Cái Răng, thành phố Cần Thơ",
         "nhà cổ bình thuỷ":
         "Bằng giá trị kiến trúc, lịch sử của mình, nhà cổ Bình Thủy đã được công nhận là “di tích nghệ thuật cấp quốc gia”, ngày càng thu hút nhiều khách đến thăm cũng như các đoàn làm phim về mượn bối cảnh cho những thước phim của mình.",
         "chùa ông":
         "Theo Wiki: Chùa Ông (Cần Thơ), tên gốc là Quảng Triệu Hội Quán (chữ Hán: 廣肇會館;广肇会馆). Đây là một ngôi chùa của người Hoa gốc Quảng Đông tại Cần Thơ, và là một di tích lịch sử cấp quốc gia kể từ năm 1993.",
         "vườn cây mỹ khánh":
         "Đặt chân tới vườn trái cây này thì bạn sẽ được tham quan hơn 20 giống cây trồng khác nhau sẽ cho bạn một trải nghiệm đặc biệt.",
         "chợ đêm":
         "Ở đây có bán rất nhiều món ngon, trong đó có những món đặc trưng của miền Tây mà tiêu biểu là những món chè"
     }
     if any(tracker.get_latest_entity_values("thong_tin")):
         # entity was picked up, validate slot
         thongtin = tracker.get_slot("thong_tin")
         ask = dict_thongtin[thongtin]
         dispatcher.utter_template("utter_thongtin",
                                   tracker,
                                   thong_tin=thongtin,
                                   tt_thongtin=ask)
     else:
         # no entity was picked up, we want to ask again
         dispatcher.utter_template("utter_no_thongtin", tracker)
     return []
def get_recent_media(dispatcher: CollectingDispatcher, tracker: Tracker,
                     domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
    media_type = next(tracker.get_latest_entity_values(MEDIA_TYPE_SLOT), None)
    _LOGGER.warning(json.dumps(media_type))
    media_type = SYNONYMS.get(media_type, None)
    success, recent_media = query_recent_media(media_type)
    _LOGGER.warning(json.dumps(recent_media))

    if not success or not recent_media:
        dispatcher.utter_message(template="utter_media_failed")
    else:
        movies = ", ".join(recent_media.get('movies', []))
        episodes = ", ".join(recent_media.get('episodes', []))
        if not movies and not episodes:
            dispatcher.utter_message(
                text=
                "It appears we haven't added any recent media to our library")
        else:
            message = "We recently added"
            if movies:
                message += f" the movies {movies}"
            if movies and episodes:
                message += " and"
            if episodes:
                message += f" tv episodes {episodes}"

            dispatcher.utter_message(text=message)

    return [SlotSet("media_type", "")]
示例#30
0
    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[EventType]:
        spacy_entities = ["place", "date", "name", "organisation"]
        duckling = [
            "money",
            "duration",
            "distance",
            "ordinals",
            "time",
            "amount-of-money",
            "numbers",
        ]

        entity_to_extract = next(tracker.get_latest_entity_values("entity"),
                                 None)

        extractor = "CRFEntityExtractor"
        if entity_to_extract in spacy_entities:
            extractor = "SpacyEntityExtractor"
        elif entity_to_extract in duckling:
            extractor = "DucklingHTTPExtractor"

        return [SlotSet("entity_extractor", extractor)]