示例#1
0
    def _merge_slots(
            self,
            entities: Optional[List[Dict[Text, Any]]] = None) -> List[SlotSet]:
        """Take a list of entities and create tracker slot set events.

        If an entity type matches a slots name, the entities value is set
        as the slots value by creating a ``SlotSet`` event."""

        entities = entities if entities else self.latest_message.entities
        new_slots = [
            SlotSet(e["entity"], e["value"]) for e in entities
            if e["entity"] in self.slots.keys()
        ]
        return new_slots
示例#2
0
	def run(self, dispatcher, tracker, domain):
		tier1_city_list = [ 'ahmedabad','bangalore','chennai','delhi','hyderabad','kolkata','mumbai','pune' ]
		tier2_city_list = [ 'agra','ajmer','aligarh','allahabad','amravati','amritsar','asansol','aurangabad','bareilly','belgaum','bhavnagar','bhiwandi',
							'bhopal','bhubaneswar','bikaner','bokaro steel city','chandigarh','coimbatore','cuttack','dehradun','dhanbad','durg-bhilai nagar',
							'durgapur','erode','faridabad','firozabad','ghaziabad','gorakhpur','gulbarga','guntur','gurgaon','guwahati','gwalior',
							'hubli-dharwad','indore','jabalpur','jaipur','jalandhar','jammu','jamnagar','jamshedpur','jhansi','jodhpur','kannur','kanpur',
							'kakinada','kochi','kottayam','kolhapur','kollam','kota','kozhikode','kurnool','lucknow','ludhiana','madurai','malappuram',
							'mathura','goa','mangalore','meerut','moradabad','mysore','nagpur','nanded','nashik','nellore','noida','palakkad','patna',
							'pondicherry','raipur','rajkot','rajahmundry','ranchi','rourkela','salem','sangli','siliguri','solapur','srinagar','sultanpur',
							'surat','thiruvananthapuram','thrissur','tiruchirappalli','tirunelveli','tiruppur','ujjain','vijayapura','vadodara','varanasi',
							'vasai-virar city','vijayawada','visakhapatnam','warangal']

		try:

			loc = str(tracker.get_slot('location')).lower()

			if loc in tier1_city_list or loc in tier2_city_list:
				return [SlotSet('valid_location',"true")]
			else:
				return [SlotSet('valid_location',"false")]

		except:
			return [SlotSet('valid_location',"false")]
示例#3
0
 def run(self, dispatcher, tracker, domain):
     api_key = "a9a88636051c1d2696509f00024370d0"
     location = tracker.get_slot('location')
     url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(
         location, api_key)
     weather = self._get_weather(url)
     response = ""
     if not weather:
         response = "Sorry I cannot find the weather info for {}".format(
             location)
     else:
         response = WeatherAction.TEMPLATE.format(location, weather)
     dispatcher.utter_message(response)
     return [SlotSet('location', location)]
示例#4
0
    def run(self, dispatcher, tracker, domain):

        #prod = tracker.get_slot('product')
        #router = tracker.get_slot('router')
        recs = tracker.get_slot('recs')
        confirmationNumber = All  #later generate through some process

        #response = """Your product {} is ordered for you. It will be shipped to your address. Your confirmation number is {}""".format(router, confirmationNumber)

        response = """You re in provide report- here Pull report from DB and feed it to the bot""".format(
            recs, confirmationNumber)

        dispatcher.utter_message(response)
        return [SlotSet('router', router)]
示例#5
0
def test_get_or_create():
    slot_key = 'location'
    slot_val = 'Easter Island'
    store = InMemoryTrackerStore(domain)

    tracker = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER_ID)
    ev = SlotSet(slot_key, slot_val)
    tracker.update(ev)
    assert tracker.get_slot(slot_key) == slot_val

    store.save(tracker)

    again = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER_ID)
    assert again.get_slot(slot_key) == slot_val
示例#6
0
    def run(self, dispatcher, tracker, domain):
        if "intro_template" in self.rule["display"]:
            dispatcher.utter_template(self.rule["display"]["intro_template"],
                                      tracker)

        disambiguation_message = self.get_disambiguation_message(
            dispatcher, self.rule, self.payloads, self.intents, tracker)
        dispatcher.utter_response(disambiguation_message)

        return_value = []
        if self.rule['slot_name']:
            return_value.append(
                SlotSet(self.rule['slot_name'], self.rule['parse_data']))
        return return_value
示例#7
0
 def ValidateCuisine(self,dispatcher,tracker):
         cuisine = tracker.get_slot('cuisine')
         validation_status=True
         if cuisine!=None:
                 with open('./data/lookup/syn_cuisine.json') as json_file:
                         json_cusine=json.load(json_file)
                 if json_cusine.get(str(cuisine).lower())!=None:
                         cuisine_val=json_cusine.get(str(cuisine).lower())
                         tracker.update(SlotSet("cuisine",cuisine_val))
                 else:
                         validation_status=False
         else:
                 validation_status=False
         return validation_status
示例#8
0
 def run(self, dispatcher, tracker, domain):
     search_api = SearchAPI()
     product = tracker.get_slot("product")
     version = tracker.get_slot("version")
     keywords = tracker.get_slot("keywords")
     print(product)
     print(version)
     print(keywords)
     if (product == None and keywords == None):
         return
     if (product != None and keywords == None):
         return
     results = search_api.search(product, version, keywords)
     return [SlotSet("matches", results)]
示例#9
0
	def run(self, dispatcher, tracker, domain):
		setval = tracker.get_slot("cuisine")
		if (setval !=''):
			your_slot_value = setval
		else:
			your_slot_value = tracker.latest_message.text
			
		cuisine_list=['chinese','mexican','italian','american','south indian','north indian']
		if (your_slot_value == None):
			dispatcher.utter_template("utter_wrong_cuisine",tracker)
		elif (your_slot_value.lower() not in city_list):
			dispatcher.utter_template("utter_wrong_cuisine",tracker)	
		else:
			return [SlotSet('cuisine',your_slot_value)]
示例#10
0
	def run(self, dispatcher, tracker, domain):
		setval = tracker.get_slot("budget")
		if (setval !=''):
			your_slot_value = setval
		else:
			your_slot_value = tracker.latest_message.text
			
		budget_list=['Lesser than Rs. 300','Rs. 300 to 700','More than 700']
		if (your_slot_value == None):
			dispatcher.utter_template("utter_wrong_budget",tracker)
		elif (your_slot_value.lower() not in city_list):
			dispatcher.utter_template("utter_wrong_budget",tracker)	
		else:
			return [SlotSet('budget',your_slot_value)]
示例#11
0
 def run(self, dispatcher, tracker, domain):
     result = []
     movie = tracker.get_slot("movie.name")
     if movie is None:
         dispatcher.utter_message(error_messages())
     else:
         movie_db = DBManager()
         result = movie_db.get_language(movie)
         if result[1] is None:
             dispatcher.utter_message(error_messages())
         else:
             dispatcher.utter_message("Language of " + result[0] + " is: " +
                                      result[1])
             return [SlotSet("movie.language", result[1])]
    def run(self, dispatcher, tracker, domain):

        print("Will you help me with some information regarding the dataset\n")

        obs = None
        while type(obs) is not int:
            try:
                obs = input("Please enter the number of observations : ")
                obs = int(obs)
                print("The number of observations are: ", obs)
            except ValueError:
                print(obs, "Please enter an integer..\n")

        return [SlotSet("num_observations", obs)]
示例#13
0
 def run(self, dispatcher, tracker, domain):
     movie = tracker.get_slot("movie.name")
     if movie is None:
         dispatcher.utter_message(
             "I'm afraid I didn't understand the movie title")
     else:
         movie_buff = MovieBuff(URI)
         result = movie_buff.get_budget(movie)
         if result is None:
             dispatcher.utter_message("I'm sorry, but I don't know :(")
         else:
             dispatcher.utter_message("The budget for this movie was " +
                                      str(result) + "$")
             return [SlotSet("movie.budget", result)]
示例#14
0
	def run(self, dispatcher, tracker, domain):
		loc = tracker.get_slot('location')
		cuisine = tracker.get_slot('cuisine')
		price = tracker.get_slot('budget')

		global restaurants

		restaurants = results(loc, cuisine, price)
		top5 = restaurants.head(5) 
		
		# top 5 results to display
		if len(top5)>0:
			response = 'Showing you top results:' + "\n"
			for index, row in top5.iterrows():
				response = response + str(row["restaurant_name"]) + ' in ' + row['restaurant_address'] + ' has been rated ' + str(row['restaurant_rating'])+"\n"
			
			dispatcher.utter_message(str(response))
			return [SlotSet('budget',price)]

		else:
			response = 'No restaurants found' 
			dispatcher.utter_message(str(response))
			return [SlotSet('location',None), SlotSet('cuisine',None), SlotSet('budget',None)]
示例#15
0
文件: actions.py 项目: amar198/AI
    def run(self, dispatcher, tracker, domain):
        cities = pd.read_csv('city-list.csv')  #reading the city-list.csv file.
        slot_city_name = str(tracker.get_slot('location')).lower(
        )  #fetching the location entered by user and saved in location slot.

        #checking if city name exist in tier1/2 list
        #if no records found then send message to the user else nothing
        if len((cities.loc[cities['city_name'].str.lower() == slot_city_name]
                )) == 0:
            dispatcher.utter_message('We do not operate in this city yet.')
            slot_city_name = ''  # clearing the city name as it's invalid.

        #setting the location slot with the value provided by the user or if its invalid city then with a blank value.
        return [SlotSet('location', slot_city_name)]
示例#16
0
文件: actions.py 项目: jpvgc45/botj
    def run(self, dispatcher, tracker, domain):
        import datetime
        budget = tracker.get_slot('budget')
        company = tracker.get_slot('company_name')
        email = tracker.get_slot('email')
        jobfunction = tracker.get_slot('job_function')
        name = tracker.get_slot('person_name')
        use_case = tracker.get_slot('use_case')
        date = datetime.datetime.now().strftime("%d/%m/%Y")

        sales_info = [
            company, use_case, budget, date, name, jobfunction, email
        ]

        gdrive = GDriveService()
        try:
            gdrive.store_data(sales_info)
            return [SlotSet('data_stored', True)]
        except Exception as e:
            logger.error("Failed to write data to gdocs. Error: {}"
                         "".format(e.message),
                         exc_info=True)
            return [SlotSet('data_stored', False)]
示例#17
0
 def run(self, dispatcher, tracker, domain):
     variety = tracker.get_slot('Variety')
     conn = lite.connect('wine.db')
     sql = ("SELECT DISTINCT points FROM reviews WHERE points IS NOT NULL "
            "AND variety like (?) limit 1")
     args = ("%" + variety + "%", )
     cur = conn.execute(sql, args)
     rating = cur.fetchall()
     for row in rating:
         row = row[0]
         dispatcher.utter_message("{} has a rating"
                                  " of {}".format(variety, row))
     conn.close()
     return [SlotSet('Variety', variety)]
示例#18
0
    def run(self, dispatcher, tracker, domain):
        locations = [
            "Ahmedabad", "Bangalore", "Chennai", "Delhi", "Hyderabad",
            "Kolkata", "Mumbai", "Pune", "Agra", "Ajmer", "Aligarh",
            "Allahabad", "Amravati", "Amritsar", "Asansol", "Aurangabad",
            "Bareilly", "Belgaum", "Bhavnagar", "Bhiwandi", "Bhopal",
            "Bhubaneswar", "Bikaner", "Bokaro Steel City", "Chandigarh",
            "Coimbatore", "Cuttack", "Dehradun", "Dhanbad",
            "Durg-Bhilai Nagar", "Durgapur", "Erode", "Faridabad", "Firozabad",
            "Ghaziabad", "Gorakhpur", "Gulbarga", "Guntur", "Gurgaon",
            "Guwahati", "Gwalior", "Hubli-Dharwad", "Indore", "Jabalpur",
            "Jaipur", "Jalandhar", "Jammu", "Jamnagar", "Jamshedpur", "Jhansi",
            "Jodhpur", "Kannur", "Kanpur", "Kakinada", "Kochi", "Kottayam",
            "Kolhapur", "Kollam", "Kota", "Kozhikode", "Kurnool", "Lucknow",
            "Ludhiana", "Madurai", "Malappuram", "Mathura", "Goa", "Mangalore",
            "Meerut", "Moradabad", "Mysore", "Nagpur", "Nanded", "Nashik",
            "Nellore", "Noida", "Palakkad", "Patna", "Pondicherry", "Raipur",
            "Rajkot", "Rajahmundry", "Ranchi", "Rourkela", "Salem", "Sangli",
            "Siliguri", "Solapur", "Srinagar", "Sultanpur", "Surat",
            "Thiruvananthapuram", "Thrissur", "Tiruchirappalli", "Tirunelveli",
            "Tiruppur", "Ujjain", "Vijayapura", "Vadodara", "Varanasi",
            "Vasai-Virar City", "Vijayawada", "Visakhapatnam", "Warangal"
        ]

        cities_list_lower = [x.lower() for x in locations]
        loc = tracker.get_slot('location')

        if loc not in cities_list_lower:
            dispatcher.utter_message(
                "Sorry, we don’t operate in this city. Can you please specify some other location?"
            )
            return [
                SlotSet('location_match', "zero"),
                SlotSet('location', "null")
            ]
        else:
            return [SlotSet('location_match', "one"), SlotSet('location', loc)]
    def run(self, dispatcher, tracker, domain):
        loc = tracker.get_slot('location')
        cuisine = tracker.get_slot('cuisine')
        budget = tracker.get_slot('budget')

        zomato = zomatopy.initialize_app(zomato_config)
        location_detail = zomato.get_location(loc, 1)

        d1 = json.loads(location_detail)
        lat = d1["location_suggestions"][0]["latitude"]
        lon = d1["location_suggestions"][0]["longitude"]

        cuisines_dict = {
            'american': 1,
            'mexican': 73,
            'italian': 55,
            'chinese': 25,
            'north indian': 50,
            'south indian': 85
        }

        results = zomato.restaurant_search("", lat, lon,
                                           str(cuisines_dict.get(cuisine)), 50)

        d = json.loads(results)
        response = ""

        if (d.get('results_found', 0) == 0):
            response = "Sorry, we didn't find any results for this query."
            [SlotSet('search_result', 'zero')]
        else:
            response = self.filterRestaurantBasedOnBudget(
                budget, d['restaurants'])
            [SlotSet('search_result', 'found')]

        dispatcher.utter_message(str(response))
        return [SlotSet('location', loc)]
示例#20
0
 def run(self, dispatcher, tracker, domain):
     return [
         SlotSet('location', None),
         SlotSet('cuisine', None),
         SlotSet('minbudget', None),
         SlotSet('maxbudget', None),
         SlotSet('emailid', None),
         SlotSet('freetext', None)
     ]
示例#21
0
def transform_slots_to_standard(tracker):
    events = []
    latest_entities = tracker.latest_message.entities
    entity_values = []
    # if spacy detected datetime entities use those otherwise use the
    # the entities extracted by ner_crf
    try:
        for entity in latest_entities:
            if entity['extractor'] == "ner_spacy" and (
                    entity['entity'] == 'DATE' or entity['entity'] == 'TIME'):
                entity_values.append(entity['value'])

        if len(entity_values) > 0:
            entity_value = " ".join(entity_values)
            tracker._set_slot("date-period", DATETIME_to_iso(entity_value))
            events.append(SlotSet("date-period",
                                  DATETIME_to_iso(entity_value)))

            return events
    except:
        # spacy didn't find any entities related to datetime
        # so try to see if ner_crf extracted any entities related to
        # Datetime

        for entity in entities:
            if types_entities[entity] == "DATETIME":
                entity_values = []
                for tmp in tracker.get_latest_entity_values(entity):
                    entity_values.append(tmp)

                if len(entity_values) > 0:
                    entity_value = " ".join(entity_values)
                    tracker._set_slot(entity, DATETIME_to_iso(entity_value))
                    events.append(
                        SlotSet(entity, DATETIME_to_iso(entity_value)))

    return events
示例#22
0
    def run(self, dispatcher, tracker, domain):

        request = {
            'table': 'table_name',
            'position': 'quantity',
            'customer': 'customer_name',
            'quantity': 1
        }

        table = tracker.get_slot('Table')
        position = tracker.get_slot('position')
        quantity = tracker.get_slot('quantity')
        customer = tracker.get_slot('customer')

        PARAMS = {
            'table': table,
            'position': position,
            'customer': quantity,
            'quantity': customer
        }
        URL = 'http://192.168.1.1:3000/contracts'
        # requests.get()

        # query_response = requests.
        r = requests.get(url=URL, params=PARAMS)
        data = r.json()

        response = """Ok, got it! Here are the customers {} """.format(
            data['customers'])

        dispatcher.utter_message(response)
        return [
            SlotSet('Table', table),
            SlotSet('position', position),
            SlotSet('quantity', quantity),
            SlotSet('customer_name', customer_name)
        ]
示例#23
0
    def run(self, dispatcher, tracker, domain):
        config = {"user_key": "f75a7c69770eb245bc3634a238239520"}
        zomato = zomatopy.initialize_app(config)
        cuisine = tracker.get_slot('cuisine')
        price = tracker.get_slot('price')
        loc = tracker.get_slot('location')
        location_detail = zomato.get_location(loc, 1)
        d1 = json.loads(location_detail)
        lat = d1["location_suggestions"][0]["latitude"]
        lon = d1["location_suggestions"][0]["longitude"]
        cuisines_dict = {
            'american': 1,
            'chinese': 25,
            'italian': 55,
            'mexican': 73,
            'north indian': 50,
            'south indian': 85
        }
        results = zomato.restaurant_search("&sort=rating&order=desc", lat, lon,
                                           str(cuisines_dict.get(cuisine)))
        d = json.loads(results)
        price_dict = {
            'low': range(0, 300),
            'mid': range(301, 700),
            'high': range(701, 10000)
        }
        price_range = price_dict[price]

        response = ""
        if d['results_found'] == 0:
            response = "no results"
        else:
            response = response + "Showing you top rated restaurants: \n"
            response = response + "-----------------------------------------------------------------------------------------------------------------------\n"
            for restaurant in d['restaurants']:
                try:
                    if restaurant['restaurant'][
                            'average_cost_for_two'] in price_range:
                        response = response + restaurant['restaurant'][
                            'name'] + " in " + restaurant['restaurant'][
                                'location'][
                                    'address'] + " has been rated " + str(
                                        restaurant['restaurant']['user_rating']
                                        ['aggregate_rating']) + "\n"
                except Exception as e:
                    response = response + str(e)

        dispatcher.utter_message(response)
        return [SlotSet('can_ask_send_mail', True)]
示例#24
0
    def say(self, request, cid):
        message, = request.args.get(b"message", [])
        _payload = request.args.get(b"payload", [])
        _display_name = request.args.get(b"display_name", [])
        _uuid = request.args.get(b"uuid", [])
        logger.info(message)

        if len(_display_name) > 0:
            display_name, = _display_name
            tracker = self.agent.tracker_store.get_or_create_tracker(cid)
            if ("display_name" in tracker.current_slot_values()
                    and tracker.get_slot("display_name") != display_name):
                tracker.update(
                    SlotSet("display_name", display_name.decode("utf-8")))
                self.agent.tracker_store.save(tracker)

        if message == "_restart":
            self.message_store.clear(cid)
        else:
            if len(_uuid) > 0:
                self.message_store.log(
                    cid,
                    cid,
                    {
                        "type": "text",
                        "text": message.decode("utf-8")
                    },
                    _uuid[0].decode("utf-8"),
                )
            else:
                self.message_store.log(cid, cid, {
                    "type": "text",
                    "text": message.decode("utf-8")
                })

        if len(_payload) > 0:
            self.on_message(
                UserMessage(
                    _payload[0].decode("utf-8"),
                    output_channel=BotServerOutputChannel(self.message_store),
                    sender_id=cid,
                ))
        else:
            self.on_message(
                UserMessage(
                    message.decode("utf-8"),
                    output_channel=BotServerOutputChannel(self.message_store),
                    sender_id=cid,
                ))
示例#25
0
    def run(self, dispatcher, tracker, domain):
        loc = tracker.get_slot('location')

        with open('./data/lookup/locations.txt', 'r') as lookup:
            city_lookuplist = lookup.read().splitlines()
            city_lookuplist = [x.lower() for x in city_lookuplist]

        if loc not in city_lookuplist:
            dispatcher.utter_template('utter_ask_reenter_location', tracker)
            loc = None

        return [SlotSet('location', loc)]


# ActionSearchRestaurants().run("","","")
示例#26
0
    def run(self, dispatcher, tracker, domain):

        company_x = tracker.get_slot('company')

        symbols = get_available_symbols()
        for i in range(len(symbols)):
            if company_x.lower() in symbols[i]["name"].lower():
                company = symbols[i]["symbol"]

        companyobj = Stock(company)
        price = companyobj.get_price()

        response = """{} shares is {} currently.""".format(company, price)
        dispatcher.utter_message(response)
        return [SlotSet('company', company)]
示例#27
0
    def run(self, dispatcher, tracker, domain):
        values = "Loc:{0}; Cuisine:{1}; Budget:{2}".format(
            tracker.get_slot(SLOT_LOCATION), tracker.get_slot(SLOT_CUISINE),
            tracker.get_slot(SLOT_BUDGET))
        dispatcher.utter_message("ProcessMultipleInput.run {0}".format(values))

        slots = []

        if tracker.get_slot(SLOT_LOCATION) != None:
            ValidateLocation().run(dispatcher, tracker, domain)
            slots.append(
                SlotSet(SLOT_LOCATION, tracker.get_slot(SLOT_LOCATION)))

        if tracker.get_slot(SLOT_CUISINE) != None:
            ProcessCuisine().run(dispatcher, tracker, domain)
            slots.append(SlotSet(SLOT_CUISINE, tracker.get_slot(SLOT_CUISINE)))

        if tracker.get_slot(SLOT_BUDGET) != None:
            ProcessBudget().run(dispatcher, tracker, domain)
            #slot_value = ProcessBudget().run(dispatcher, tracker, domain)
            #SlotSet(SLOT_BUDGET, slot_value)
            slots.append(SlotSet(SLOT_BUDGET, tracker.get_slot(SLOT_BUDGET)))

        return (slots)
示例#28
0
 def run(self, dispatcher, tracker, domain):
     result = []
     movie = tracker.get_slot("movie.name")
     if movie is None:
         dispatcher.utter_message(error_messages())
         dispatcher.utter_template("utter_repeat")
     else:
         movie_db = DBManager()
         result = movie_db.get_year(movie)
         if result[1] is None:
             dispatcher.utter_message(error_messages())
         else:
             dispatcher.utter_message("Release year for " + result[0] +
                                      " is: " + str(result[1]))
             return [SlotSet("movie.release_date", result[1])]
def test_common_action_prefix():
    this = [
        ActionExecuted("action_listen"),
        ActionExecuted("greet"),
        UserUttered("hey"),
        ActionExecuted("amazing"),
        # until this point they are the same
        SlotSet("my_slot", "a"),
        ActionExecuted("a"),
        ActionExecuted("after_a"),
    ]
    other = [
        ActionExecuted("action_listen"),
        ActionExecuted("greet"),
        UserUttered("hey"),
        ActionExecuted("amazing"),
        # until this point they are the same
        SlotSet("my_slot", "b"),
        ActionExecuted("b"),
        ActionExecuted("after_b"),
    ]
    num_common = visualization._length_of_common_action_prefix(this, other)

    assert num_common == 3
示例#30
0
 def run(self, dispatcher, tracker, domain):
     result = []
     movie = tracker.get_slot("movie.name")
     if movie is None:
         dispatcher.utter_message(error_messages())
         dispatcher.utter_template("utter_repeat")
     else:
         movie_db = DBManager()
         result = movie_db.get_country(movie)
         if result[1] is None:
             dispatcher.utter_message(error_messages())
         else:
             dispatcher.utter_message("Release region for " + result[0] +
                                      " is: " + result[1])
             return [SlotSet("movie.location", result[1])]