def run(self, dispatcher, tracker, domain): return [SlotSet('location',None),SlotSet('api_response',None),SlotSet('cuisine',None),SlotSet('budget',None)]
def run(self, dispatcher, tracker, domain): config={ "user_key":config_loader.get_zomato_config()} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') budget=tracker.get_slot('budget') cuisine = tracker.get_slot('cuisine') if loc!=None: if Validation_Utilities().ValidateLocation(dispatcher,tracker)==False: dispatcher.utter_template('utter_noService',tracker) return [SlotSet('location',None)] elif cuisine==None: dispatcher.utter_template('utter_ask_cuisine',tracker) return [SlotSet('location',tracker.get_slot('location'))] else: dispatcher.utter_template('utter_ask_location',tracker) return [SlotSet('location',loc),SlotSet('cuisine',cuisine),SlotSet('budget',budget)] if cuisine!=None: if Validation_Utilities().ValidateCuisine(dispatcher,tracker)==False: dispatcher.utter_template('utter_ask_cuisine',tracker) return [SlotSet('cuisine',None)] elif budget==None: dispatcher.utter_template('utter_ask_budget',tracker) return [SlotSet('cuisine',tracker.get_slot('cuisine'))] else: dispatcher.utter_template('utter_ask_cuisine',tracker) return [SlotSet('location',loc),SlotSet('cuisine',cuisine),SlotSet('budget',budget)] if budget==None: dispatcher.utter_template('utter_ask_budget',tracker) return [SlotSet('location',loc),SlotSet('cuisine',cuisine),SlotSet('budget',budget)] if cuisine!=None and loc!=None and budget!=None: location_detail=zomato.get_location(loc, 1) d1 = json.loads(location_detail) lat=d1["location_suggestions"][0]["latitude"] lon=d1["location_suggestions"][0]["longitude"] city_id=d1["location_suggestions"][0]["city_id"] tracker.update(SlotSet("lat",lat)) tracker.update(SlotSet("lon",lon)) tracker.update(SlotSet("city_id",city_id)) cuisine_details=zomato.get_cuisines(city_id) cuisine_key="" try: c_k=list(cuisine_details.keys()) c_v=list(cuisine_details.values()) c_v=[x.lower() for x in c_v] c_index=c_v.index(cuisine.lower()) cuisine_key=str(c_k[c_index]) tracker.update(SlotSet('cuisine_key',cuisine_key)) except ValueError as e: dispatcher.utter_message("Sorry! not able to find cuisine {} restaurant. Please choose another cuisine".format(cuisine)) dispatcher.utter_template('utter_ask_cuisine',tracker) return [SlotSet('cuisine',None)] if cuisine_key!='': results=zomato.restaurant_search("", lat, lon, cuisine_key, 10) d = json.loads(results) api_response="{" response="" if d['results_found'] == 0: response= "no results" else: counter=1 for restaurant in d['restaurants']: api_response+='"{}":["{}","{}","{}","{}"]'.format(counter,restaurant['restaurant']['name'],restaurant['restaurant']['location']['address'],restaurant['restaurant']['average_cost_for_two'],restaurant['restaurant']['user_rating']['aggregate_rating']) if counter<6: response=response+ str(counter)+" : "+ restaurant['restaurant']['name']+ " in "+ restaurant['restaurant']['location']['address']+" has been rated "+restaurant['restaurant']['user_rating']['aggregate_rating'] +"\n" if counter<10: api_response+="," counter+=1 api_response+="}" tracker.update(SlotSet('api_response',api_response)) dispatcher.utter_message("-----\n"+response) return [SlotSet('location',loc),SlotSet('api_response',api_response),SlotSet('budget',budget),SlotSet('cuisine',cuisine)] else: dispatcher.utter_template('utter_ask_cuisine',tracker) return [SlotSet('location',loc),SlotSet('cuisine',None),SlotSet('budget',budget)]
def run(self, dispatcher, tracker, domain): return [SlotSet('is_authenticated', True)]
def run(self, dispatcher, tracker, domain): config = { "user_key": "10b24e1555ad73805c25a6a35e15f508" } #zomato API key zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') cuisine = cuisine.lower() budget = tracker.get_slot('budget') if budget == 'low': cost_to_filer_min = 0 cost_to_filer_max = 300 elif budget == 'mid': cost_to_filer_min = 301 cost_to_filer_max = 700 elif budget == 'high': cost_to_filer_min = 701 cost_to_filer_max = 9999 cols = [ 'restaurant name', 'restaurant address', 'avg. budget for two', 'zomato rating' ] resrnt_df = pd.DataFrame(columns=cols) 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, 'mexican': 73, 'italian': 55, 'north indian': 50, 'south indian': 85 } results = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), "rating", "desc", 20) response = "" for i in range(0, 5, 1): d = json.loads(results[i]) if d['results_found'] != 0: for restaurant in d['restaurants']: curr_res = { 'zomato rating': restaurant['restaurant']["user_rating"] ["aggregate_rating"], 'restaurant name': restaurant['restaurant']['name'], 'restaurant address': restaurant['restaurant']['location']['address'], 'avg. budget for two': restaurant['restaurant']['average_cost_for_two'] } if (curr_res['avg. budget for two'] >= cost_to_filer_min ) and (curr_res['avg. budget for two'] <= cost_to_filer_max): resrnt_df.loc[len(resrnt_df)] = curr_res # Restarants on aggregate rating resrnt_df = resrnt_df.sort_values( ['zomato rating', 'avg. budget for two'], ascending=[False, True]) email = tracker.get_slot('email') gmail_user = '******' #email id here gmail_password = '******' #type password here sent_from = gmail_user to = str(email) msg = MIMEMultipart('alternative') msg['Subject'] = "Top rated Restaurant search details" msg['From'] = gmail_user msg['To'] = to if len(resrnt_df) == 0: html = """ <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <p>Hi!</p> <p>Thanks for using Foodie, the restaurant chatbot.</p> <p>Sorry, we could not find restaurant that meet your criteria.</p> """ else: resrnt_df10 = resrnt_df.head(10) resrnt_df10 = resrnt_df10.reset_index(drop=True) resrnt_df10.index = resrnt_df10.index.map(str) html = """ <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <p>Hi!</p> <p>Thank you. Requested list of restaurants below.</p> <p>Enjoy !</p> """ html = html + resrnt_df10.to_html() html = html + "<p> based on your query...</p>" + cuisine + " restaurants " + budget + " budget at " + loc + "</body></html>" part2 = MIMEText(html, 'html') msg.attach(part2) server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, msg.as_string()) server.close() dispatcher.utter_message("Email Sent") return [SlotSet('email', email)]
def run(self, dispatcher, tracker, domain): config = {"user_key": "2f6fd90e303dfefa2caa9dc48ad2d73e"} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisines = [ 'chinese', 'mexican', 'italian', 'american', 'south indian', 'north indian' ] cuisine = tracker.get_slot('cuisine') soundex_dct = {get_soundex(value): value for value in cuisines} if get_soundex(cuisine) in soundex_dct.keys(): cuisine = soundex_dct[get_soundex(cuisine)] price = tracker.get_slot('price') temp_dict = {'1': [0, 300], '2': [300, 700], '3': [700]} location_detail = zomato.get_location(loc, 1) d1 = json.loads(location_detail) try: lat = d1["location_suggestions"][0]["latitude"] lon = d1["location_suggestions"][0]["longitude"] cuisines_dict = { 'american': 1, 'chinese': 25, 'mexican': 73, 'italian': 55, 'north indian': 50, 'south indian': 85 } lst = [] for val in range(0, 100, 20): results = zomato.restaurant_search( "", lat, lon, str(cuisines_dict.get(cuisine)), start=val) d = json.loads(results) for restaurant in d['restaurants']: lst.append( (restaurant['restaurant']['name'], restaurant['restaurant']['location']['address'], float( restaurant['restaurant']['average_cost_for_two']), float(restaurant['restaurant']['user_rating'] ['aggregate_rating']))) temp = ['max', 'maximum', 'less', 'lesser', 'not more'] if len(price) == 1: price.append(0) for idx in range(len(price)): if isinstance(price[idx], str): if price[idx].lower() in temp: price[idx] = 0 temp = ['min', 'minimum', 'more', 'higher', 'greater'] for value in price: if isinstance(value, str): if value.lower() in temp: price.remove(value) price = list(map(float, price)) price = sorted(price) #lst=[] #for restaurant in d['restaurants']: # lst.append((restaurant['restaurant']['name'],restaurant['restaurant']['location']['address'],float(restaurant['restaurant']['average_cost_for_two']),float(restaurant['restaurant']['user_rating']['aggregate_rating']))) lst1 = sorted(lst, key=lambda x: x[3], reverse=True) if len(price) == 1: final_lst = list(filter(lambda x: x[2] >= price[0], lst1))[:10] else: final_lst = list( filter(lambda x: x[2] >= price[0] and x[2] <= price[1], lst1))[:10] response = "" if len(final_lst) == 0: response = "no results" else: for restaurant in final_lst[:5]: response = response + restaurant[0] + " in " + restaurant[ 1] + " has been rated " + str(restaurant[3]) + "\n" restaurant_final_list = final_lst[:10] file = open("body.txt", "w") counter = 1 for restaurant in restaurant_final_list: file.write( "{}. Restaurant Name: {}\n Restaurant locality address: {}\n Average budget for two people: {}\n Zomato user rating: {}\n\n" .format(counter, restaurant[0], restaurant[1], restaurant[2], restaurant[3])) counter += 1 file.close() except: response = "no results" dispatcher.utter_message(response) #restaurant_final_list=final_lst[:10] #file=open("body.txt","w") #counter=1 #for restaurant in restaurant_final_list: # file.write("{}. Restaurant Name: {}\n Restaurant locality address: {}\n Average budget for two people: {}\n Zomato user rating: {}\n\n".format(counter,restaurant[0],restaurant[1],restaurant[2],restaurant[3])) # counter+=1 #file.close() return [ SlotSet('cuisine', cuisine), SlotSet('noresults', response == "no results") ]
def submit(self, dispatcher, tracker, domain): email = tracker.get_slot("new_email") confirmed = tracker.get_slot("new_email_confirmed") tracker.update(SlotSet("new_email")) tracker.update(SlotSet("new_email_confirmed"))
ActionExecuted, AllSlotsReset, \ ReminderScheduled, ConversationResumed, ConversationPaused, StoryExported, \ ActionReverted, BotUttered @pytest.mark.parametrize("one_event,another_event", [ (UserUttered("/greet", { "intent": "greet", "confidence": 1.0 }, []), UserUttered("/goodbye", { "intent": "goodbye", "confidence": 1.0 }, [])), (TopicSet("my_topic"), TopicSet("my_other_topic")), (SlotSet("my_slot", "value"), SlotSet("my__other_slot", "value")), (Restarted(), None), (AllSlotsReset(), None), (ConversationPaused(), None), (ConversationResumed(), None), (StoryExported(), None), (ActionReverted(), None), (ActionExecuted("my_action"), ActionExecuted("my_other_action")), (BotUttered("my_text", "my_data"), BotUttered("my_other_test", "my_other_data")), (ReminderScheduled("my_action", "now"), ReminderScheduled("my_other_action", "now")), ]) def test_event_has_proper_implementation(one_event, another_event): # equals tests assert one_event != another_event, \
def run(self, dispatcher, tracker, domain): name = tracker.get_slot('student_name') return [SlotSet("student_name", name)]
def run(self, dispatcher, tracker, domain): word = str(tracker.get_slot('word')) response = APICall(word) dispatcher.utter_message(response) return [SlotSet('word', word)]
def run(self, dispatcher, tracker, domain): loc = tracker.get_slot('location') response = "It is currently sunny in {} at the moment".format(loc) dispatcher.utter_message(response) return [SlotSet('location', loc)]
def run(self, dispatcher, tracker, domain): store_id = tracker.get_slot('store_id') date = tracker.get_slot('time') #d1 = date[:10] time_entity = next((e for e in tracker.latest_message.entities if e['entity'] == 'time'), None) ####### Extracting date extracted from the duckling for SQL query #Check for **duckling_time_dictionary['additional_info']['type']** #It would be either #interval #value if time_entity['additional_info']['type'] == 'value': # Checking grain value for day, week, month, quarter, year # Day if time_entity['additional_info']['grain'] == 'day': format = '%Y-%m-%dT%H:%M:%S%z' datestring = time_entity['additional_info']['value'] d = dateutil.parser.parse(datestring) d1 = d.date() d2 = d.date() + relativedelta(days = +1) # need to change the days=+1 # Week elif time_entity['additional_info']['grain'] == 'week': format = '%Y-%m-%dT%H:%M:%S%z' datestring = time_entity['additional_info']['value'] d = dateutil.parser.parse(datestring) d1 = d.date() d2 = d.date() + relativedelta(weeks = +1) # Month elif time_entity['additional_info']['grain'] == 'month': format = '%Y-%m-%dT%H:%M:%S%z' datestring = time_entity['additional_info']['value'] d = dateutil.parser.parse(datestring) d1 = d.date() d2 = d.date() + relativedelta(months = +1) # Quarter elif time_entity['additional_info']['grain'] == 'quarter': format = '%Y-%m-%dT%H:%M:%S%z' datestring = time_entity['additional_info']['value'] d = dateutil.parser.parse(datestring) d1 = d.date() d2 = d.date() + relativedelta(months = +3) # Year elif time_entity['additional_info']['grain'] == 'year': format = '%Y-%m-%dT%H:%M:%S%z' datestring = time_entity['additional_info']['value'] d = dateutil.parser.parse(datestring) d1 = d.date() d2 = d.date() + relativedelta(years = +1) else: d1 = None d2 = None elif time_entity['additional_info']['type'] == 'interval': format = '%Y-%m-%dT%H:%M:%S%z' datestring_from = time_entity['value']['from'] d_from = dateutil.parser.parse(datestring_from) d1 = d_from.date() datestring_to = time_entity['value']['to'] d_to = dateutil.parser.parse(datestring_to) d2 = d_to.date() else: d1 = None d2 = None ### Creating coonection to database on the basis of date if d1 is not None: # Credentilas for connecting to the database cnxn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};" "Server=pdssoldb.database.windows.net;" "Database=PDS_Sol_1;" "uid=Sandeep;pwd=Abcd@1111") d1 = d1.strftime('%Y-%m-%d') d2 = d2.strftime('%Y-%m-%d') query = "select sum(sales) from DH_ALL_STORES_ALL_DAYS_SALES_PRED_A where store_id = 369 and date >= {} and date < {} ".format("'"+ d1 +"'","'"+ d2 +"'") #query = "select sum(sales) from DH_ALL_STORES_ALL_DAYS_SALES_PRED_A where store_id = 369 and date >= {} ".format("'"+ d1 +"'") df = pd.read_sql_query(query,cnxn) sale_extracted = str(df[''].values[0]) #query = "select sum(sales) from DH_ALL_STORES_ALL_DAYS_SALES_PRED_A where store_id = 369 and date = {}".format("'"+ d1 +"'") response = "The total sale is : {}".format(sale_extracted) else: response = "Kindly provide a valid date for the query" dispatcher.utter_message(response) return [SlotSet('store_id',store_id)]
def run(self, dispatcher, tracker, domain): """Run method to execute action.""" return [SlotSet("user_name", '')]
def run(self, dispatcher, tracker, domain): config = {"user_key": "6ce88a5ec1419e335afa1c7f92f4b739"} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') budget = tracker.get_slot('budget') resturant_result = pd.DataFrame( columns=['id', 'name', 'address', 'rating', 'avg_price']) print("{} {} {}".format(loc, cuisine, budget)) 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 = { 'bakery': 5, 'chinese': 25, 'cafe': 30, 'italian': 55, 'biryani': 7, 'north indian': 50, 'south indian': 85 } if (budget == "business"): sort_order = "desc" elif (budget == "luxury"): sort_order = "desc" else: sort_order = "asc" results = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 50, sort_order) d = json.loads(results) response = "" if d['results_found'] == 0: response = "no results" else: for restaurant in d['restaurants']: #response=response+ "Found "+ restaurant['restaurant']['name']+ " in "+ restaurant['restaurant']['location']['address']+"\n" resturant_result.loc[len(resturant_result)] = [ restaurant['restaurant']['id'], restaurant['restaurant']['name'], restaurant['restaurant']['location']['address'], restaurant['restaurant']['user_rating'] ['aggregate_rating'], restaurant['restaurant']['average_cost_for_two'] ] sort_by_rating = resturant_result.sort_values('rating', ascending=False) if (budget == "business"): sort_by_rating = sort_by_rating[sort_by_rating["avg_price"] > 700] elif (budget == "luxury"): sort_by_rating = sort_by_rating[ (sort_by_rating["avg_price"] > 300) & (sort_by_rating["avg_price"] < 700)] elif (budget == "economy"): sort_by_rating = sort_by_rating[sort_by_rating["avg_price"] < 300] sort_by_rating = sort_by_rating.head() for index, row in sort_by_rating.iterrows(): print("{} in {} has been rated {}".format(row['name'], row['address'], row['rating'])) email_response = "List of top rated restaurants: \n" chat_response = "Showing you top rated restaurants: \n" for i in sort_by_rating.index: email_response = email_response + "Restaurant " + sort_by_rating.loc[ i, 'name'] + " in " + sort_by_rating.loc[ i, 'address'] + "And the average price for two people here is: " + str( sort_by_rating.loc[i, 'avg_price'] ) + " Rs. And has been rating is: " + sort_by_rating.loc[ i, 'rating'] + "\n" if i < 5: chat_response = chat_response + "Restaurant " + sort_by_rating.loc[ i, 'name'] + " in " + sort_by_rating.loc[ i, 'address'] + "And the average price for two people here is: " + str( sort_by_rating.loc[i, 'avg_price'] ) + " Rs. And has been rating is: " + sort_by_rating.loc[ i, 'rating'] + "\n" dispatcher.utter_message("-----" + response) return [ SlotSet('location', loc), SlotSet('email_content', email_response) ]
def run(self, dispatcher, tracker, domain): from rasa_core.events import Form, SlotSet return [Form(None), SlotSet(REQUESTED_SLOT, None)]
def say(cid): message = bytes(request.args.get("message"), "utf8") _payload = bytes(request.args.get("payload", ""), "utf8") _display_name = bytes(request.args.get("display_name", ""), "utf8") _uuid = bytes(request.args.get("uuid", ""), "utf8") _player_token = request.args.get("playerToken") _userId = request.args.get("userId", cid) _domain_name = request.args.get("domainName") # explicitly make playerToken, userId None if empty sting if not _player_token: _player_token = None if not _userId: _userId = None 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) tracker = self.agent.tracker_store.get_or_create_tracker(cid) tracker.update(SlotSet("userId", _userId)) tracker.update(SlotSet("playerToken", _player_token)) tracker.update(SlotSet("domainName", _domain_name)) 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.decode("utf-8"), ) if len(_payload) > 0: on_new_message( UserMessage( _payload[0].decode("utf-8"), output_channel=BotServerOutputChannel( self.message_store), sender_id=_userId, ), preprocessor=self.preprocessor, ) else: on_new_message( UserMessage( message.decode("utf-8"), output_channel=BotServerOutputChannel( self.message_store), sender_id=_userId, ), preprocessor=self.preprocessor, ) return "OK"
def run(self, dispatcher, tracker, domain): loc = tracker.get_slot('department') #response = tracker.current_slot_values() # response = '#' + json.dumps(aaa) + '#' if loc == 'algology': #response = "Prof. Dr. Öznur Öken" buttons = [Button(title="Prof. Dr. Öznur Öken", payload="/Dr1")] elif loc == 'brain and neurosurgery': #response = "1- Doç. Dr. Gülşah Bademci\n2- Doç. Dr. Suat CANBAY" buttons = [ Button(title="Doç. Dr. Gülşah Bademci", payload="/btn1"), Button(title="Doç. Dr. Suat CANBAY", payload="/btn2") ] elif loc == 'child hematology': #response = "Prof. Dr. Hatice Emel Özyürek" buttons = [ Button(title="Prof. Dr. Hatice Emel Özyürek", payload="/btn1") ] elif loc == 'child nephrology': #response = "Prof. Dr. Süleyman Kalman" buttons = [ Button(title="Prof. Dr. Süleyman Kalman", payload="/btn1") ] elif loc == 'child health and illness': #response = "1- Prof. Dr. Musa Kazım Çağlar\n2- Prof. Dr. Süleyman Kalman\n3- Prof. Dr. Hatice Emel Özyürek\n4- Yar. Doç. Dr. Pakize Elif Alkış\n5- Uzm. Dr. Mustafa Yücel Kızıltan\n6- Uzm. Dr. Gökalp Başbozkurt\n7- Uzm. Dr. Hafsa Uçur\n8- Uzm. Dr. Hüsniye Altan\n 9- Uzm. Dr. Sarkhan Elbayıyev\n 10- Uzm. Dr. Shahın Guliyev" buttons = [ Button(title="Prof. Dr. Musa Kazım Çağlar", payload="/btn1"), Button(title="Prof. Dr. Süleyman Kalman", payload="/btn2"), Button(title="Prof. Dr. Hatice Emel Özyürek", payload="/btn3"), Button(title="Yar. Doç. Dr. Pakize Elif Alkışn", payload="/btn4"), Button(title="Uzm. Dr. Mustafa Yücel Kızıltan", payload="/btn5"), Button(title="Uzm. Dr. Gökalp Başbozkurt", payload="/btn6"), Button(title="Uzm. Dr. Hafsa Uçur", payload="/btn7"), Button(title="Uzm. Dr. Hüsniye Altan", payload="/btn8"), Button(title="Uzm. Dr. Sarkhan Elbayıyev", payload="/btn9"), Button(title="Uzm. Dr. Shahın Guliyev", payload="/btn10") ] elif loc == 'dermatology': #response = "1- Uzm. Dr. Aylin Gözübüyükoğulları\n2- Uzm. Dr. Yeşim Akpınar Kara" buttons = [ Button(title="Uzm. Dr. Aylin Gözübüyükoğulları", payload="/Dr1"), Button(title="Uzm. Dr. Yeşim Akpınar Kara", payload="/Dr2") ] elif loc == 'diet policlinic': #response = "1- Uzm. Dyt. Gaye Başkurt\n2- Dyt. Deniz Özdemir\n3- Dyt. Halime Besler" buttons = [ Button(title="Uzm. Dyt. Gaye Başkurt", payload="/Dr1"), Button(title="Dyt. Deniz Özdemir", payload="/Dr2"), Button(title="Dyt. Halime Besler", payload="/Dr3") ] elif loc == 'endocrinology': #response = "Prof. Dr. Serdar Güler" buttons = [Button(title="Prof. Dr. Serdar Güler", payload="/Dr1")] elif loc == 'infectious diseases': #response = "Uzm. Dr. Mine Işık Arıgün" buttons = [ Button(title="Uzm. Dr. Mine Işık Arıgün", payload="/Dr1") ] elif loc == 'physical therapy and rehabilitation': #response = "1- Prof. Dr. Öznur Öken\n2- Uzm. Dr. Beril Özturan" buttons = [ Button(title="Prof. Dr. Öznur Öken", payload="/Dr1"), Button(title="Uzm. Dr. Beril Özturan", payload="/Dr2") ] elif loc == 'gastroenterology': #response = "1- Doç. Dr. Reskan Altun\n2- Doç. Dr. Yasemin Özderin Özin" buttons = [ Button(title="Doç. Dr. Reskan Altun", payload="/Dr1"), Button(title="Doç. Dr. Yasemin Özderin Özin", payload="/Dr2") ] elif loc == 'general surgery': #response = "1- Prof. Dr. Mehmet Mahir Özmen\n2- Yar. Doç. Dr. Cem Emir Güldoğan\n3- Yar. Doç. Dr. Emre Gündoğdu" buttons = [ Button(title="Prof. Dr. Mehmet Mahir Özmen", payload="/Dr1"), Button(title="Yar. Doç. Dr. Cem Emir Güldoğan", payload="/Dr2"), Button(title="Yar. Doç. Dr. Emre Gündoğdu", payload="/Dr3") ] elif loc == 'chest diseases': #response = "Prof. Dr. Uğur Gönüllü" buttons = [Button(title="Prof. Dr. Uğur Gönüllü", payload="/Dr1")] elif loc == 'eye diseases': #response = "Op. Dr. Samim Özdeş" buttons = [Button(title="Op. Dr. Samim Özdeş", payload="/Dr1")] elif loc == 'hematology policlinic': #response = "Prof. Dr. Oral Nevruz" buttons = [Button(title="Prof. Dr. Oral Nevruz", payload="/Dr1")] elif loc == 'internal diseases': #response = "1- Doç. Dr. Beril Akman\n2- Uzm. Dr. Sercan Cansaran\n3- Uzm. Dr. Sevgi Karabuğa\n4- Yar. Doç. Dr. Gökhan Celbek" buttons = [ Button(title="Doç. Dr. Beril Akman", payload="/Dr1"), Button(title="Uzm. Dr. Sercan Cansaran", payload="/Dr2"), Button(title="Uzm. Dr. Sevgi Karabuğa", payload="/Dr3"), Button(title="Yar. Doç. Dr. Gökhan Celbek", payload="/Dr4") ] elif loc == 'gynecology and Obstetrics': #response = "1- Yar. Doç. Dr. Müberra Namlı Kalem\n2- Yar. Doç. Dr. Coşkun Şimşir\n3- Prof. Dr. Ali Ergün\n4- Doç. Dr. Korhan Kahraman\n5- Doç. Dr. Turgut Var\n6- Doç. Dr. Türkan Örnek Gülpınar\n7- Op. Dr. Aslı Yücetürk\n8- Op. Dr. Ebru Yüce\n9- Prof. Dr. Timur Gürgan" buttons = [ Button(title="Yar. Doç. Dr. Müberra Namlı Kalem", payload="/Dr1"), Button(title="Yar. Doç. Dr. Coşkun Şimşir", payload="/Dr2"), Button(title="Prof. Dr. Ali Ergün", payload="/Dr3"), Button(title="Doç. Dr. Korhan Kahraman", payload="/Dr4"), Button(title="Doç. Dr. Turgut Var", payload="/Dr5"), Button(title="Doç. Dr. Türkan Örnek Gülpınar", payload="/Dr6"), Button(title="Op. Dr. Aslı Yücetürk", payload="/Dr7"), Button(title="Op. Dr. Ebru Yüce", payload="/Dr8"), Button(title="Prof. Dr. Timur Gürgan", payload="/Dr9") ] elif loc == 'cardiac surgery': #response = "1- Prof. Dr. Erol Şener\n2- Yar. Doç. Dr. Emre Boysan\n2- Yar. Doç. Renda Cırcı" buttons = [ Button(title="Prof. Dr. Erol Şener", payload="/Dr1"), Button(title="Yar. Doç. Dr. Emre Boysan", payload="/Dr2"), Button(title="Yar. Doç. Renda Cırcı", payload="/Dr3") ] elif loc == 'cardiology': #response = "1- Prof. Dr. Erdoğan İlkay\n2- Doç. Dr. Alper Canbay\n3- Uzm. Dr. Çiğdem Koca Tarı\n4- Uzm. Dr. Erol Kalender" buttons = [ Button(title="Prof. Dr. Erdoğan İlkay", payload="/Dr1"), Button(title="Doç. Dr. Alper Canbay", payload="/Dr2"), Button(title="Uzm. Dr. Çiğdem Koca Tarı", payload="/Dr3"), Button(title="Uzm. Dr. Erol Kalender", payload="/Dr4") ] elif loc == 'ENT diseases': #response = "1- Prof. Dr. Ali Altuntaş\n2- Prof. Dr. Serdar Karahatay\n3- Yar. Doç Dr. Canset Aydın" buttons = [ Button(title="Prof. Dr. Ali Altuntaş", payload="/Dr1"), Button(title="Prof. Dr. Serdar Karahatay", payload="/Dr2"), Button(title="Yar. Doç Dr. Canset Aydın", payload="/Dr3") ] elif loc == 'nephrology': #response = "Doç. Dr. Beril Akman" buttons = [Button(title="Doç. Dr. Beril Akman", payload="/Dr1")] elif loc == 'neurology': #response = "1- Prof. Dr. Mehmet Zülküf Önal\n2- Yar. Doç. Dr. Akçay Övünç Ozon" buttons = [ Button(title="Prof. Dr. Mehmet Zülküf Önal", payload="/Dr1"), Button(title="Yar. Doç. Dr. Akçay Övünç Ozon", payload="/Dr2") ] elif loc == 'orthopedics and traumatology': #response = "1- Yar. Doç. Dr. Uğur Gönç\n2- Op. Dr. Mesut Atabek\n3- Prof. Dr. levent Çelebi" buttons = [ Button(title="Yar. Doç. Dr. Uğur Gönç", payload="/Dr1"), Button(title="Op. Dr. Mesut Atabek", payload="/Dr2"), Button(title="Prof. Dr. levent Çelebi", payload="/Dr3") ] elif loc == 'plastic surgery': #response = "1- Op. Dr. Ergin Işık\n2- Op. Dr. Serdar Düzgün" buttons = [ Button(title="Op. Dr. Ergin Işık", payload="/Dr1"), Button(title="Op. Dr. Serdar Düzgün", payload="/Dr2") ] elif loc == 'psychiatry': #response = "Prof. Dr. Ali Bozkurt" buttons = [Button(title="Prof. Dr. Ali Bozkurt", payload="/Dr1")] elif loc == 'psychologist': #response = "Psk. Ezgi Kılınç" buttons = [Button(title="Psk. Ezgi Kılınç", payload="/Dr1")] elif loc == 'rheumatology': #response = "Doç. Dr. Orhan Küçükşahin" buttons = [ Button(title="Doç. Dr. Orhan Küçükşahin", payload="/Dr1") ] elif loc == 'medical oncology': #response = ["Prof. Dr. Fikret Arpacı", "Doç. Dr. Gökhan Erdem"] buttons = [ Button(title="Prof. Dr. Fikret Arpacı", payload="/Dr1"), Button(title="Doç. Dr. Gökhan Erdem", payload="/Dr2") ] elif loc == 'urology': response = "Müsait doktor bulunmamaktadır..." #response = "abc\n\nasd" response = "" # buttons = [ # Button(title="Btn1", payload="/btn1"), # Button(title="Btn2", payload="/btn2") # ] dispatcher.utter_button_message("my message", buttons) return [SlotSet('doctor', response)]
def run(self, dispatcher, tracker, domain): dispatcher.utter_message("looking for restaurants") restaurant_api = RestaurantAPI() restaurants = restaurant_api.search(tracker.get_slot("cuisine")) return [SlotSet("matches", restaurants)]
def run(self, dispatcher, tracker, domain): degree = tracker.get_slot('degree') return [SlotSet("degree", degree)]
def _merge_slots(self, entities=None): 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
def run(self, dispatcher, tracker, domain): val = tracker.get_slot('num') temp_dict = {'1': [0, 300], '2': [300, 700], '3': [700]} return [SlotSet('price', temp_dict[str(val)])]
def run(self, dispatcher, tracker, domain): config = { "user_key": "10b24e1555ad73805c25a6a35e15f508" } #zomato API key zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') cuisine = cuisine.lower() budget = tracker.get_slot('budget') if budget == 'low': cost_to_filer_min = 0 cost_to_filer_max = 300 elif budget == 'mid': cost_to_filer_min = 301 cost_to_filer_max = 700 elif budget == 'high': cost_to_filer_min = 701 cost_to_filer_max = 9999 cols = [ 'restaurant name', 'restaurant address', 'avg. budget for two', 'zomato rating' ] resrnt_df = pd.DataFrame(columns=cols) 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, 'mexican': 73, 'italian': 55, 'north indian': 50, 'south indian': 85 } results = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), "rating", "desc", 25) # filter budget later response = "" for i in range(0, 5, 1): d = json.loads(results[i]) if d['results_found'] != 0: for restaurant in d['restaurants']: curr_res = { 'zomato rating': restaurant['restaurant']["user_rating"] ["aggregate_rating"], 'restaurant name': restaurant['restaurant']['name'], 'restaurant address': restaurant['restaurant']['location']['address'], 'avg. budget for two': restaurant['restaurant']['average_cost_for_two'] } if (curr_res['avg. budget for two'] >= cost_to_filer_min ) and (curr_res['avg. budget for two'] <= cost_to_filer_max): resrnt_df.loc[len(resrnt_df)] = curr_res # sorting on aggregate rating resrnt_df = resrnt_df.sort_values( ['zomato rating', 'avg. budget for two'], ascending=[False, True]) resrnt_df10 = resrnt_df.head(10) resrnt_df = resrnt_df.head(5) resrnt_df = resrnt_df.reset_index(drop=True) resrnt_df.index = resrnt_df.index.map(str) # printing response if len(resrnt_df) != 0: for index, row in resrnt_df.iterrows(): response = response + index + ". Found \"" + row[ 'restaurant name'] + "\" in " + row[ 'restaurant address'] + " has been rated " + row[ 'zomato rating'] + "\n" else: response = 'couldnt find any restaurants in given price range' dispatcher.utter_message(response) return [SlotSet('budget', budget)]
# a couple of event instances that we can use for testing test_events = [ Event.from_parameters({ "event": UserUttered.type_name, "text": "/goodbye", "parse_data": { "intent": { "confidence": 1.0, "name": "greet" }, "entities": [] } }), BotUttered("Welcome!", {"test": True}), SlotSet("cuisine", 34), SlotSet("cuisine", "34"), SlotSet("location", None), SlotSet("location", [34, "34", None]), ] @pytest.fixture(scope="module") def app(core_server): return core_server.test_client() @pytest.fixture(scope="module") def secured_app(core_server_secured): return core_server_secured.test_client()
def run(self, dispatcher, tracker, domain): config = {"user_key": "40d3c87042beb41426334eba18090f72"} zomato = zomatopy.initialize_app(config) loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') price_lt = tracker.get_slot('price_lt') price_ut = tracker.get_slot('price_ut') 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, 'north indian': 50, 'south indian': 85, 'mexican': 73 } results = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 5, 0) d = json.loads(results) response = "" mail_response = "" if d['results_found'] == 0: response = "no results" elif ((price_lt == None) & (price_ut == None)): response = "Sorry could not extract the price range" else: index = 0 if price_lt != None: if price_ut != None: if price_ut < price_lt: price = price_lt price_lt = price_ut price_ut = price restaurants = d['restaurants'] for loop in [20, 40, 60, 80]: r = zomato.restaurant_search("", lat, lon, str(cuisines_dict.get(cuisine)), 10, loop) temp = json.loads(results) if temp['results_found'] > 0: restaurants.extend(temp['restaurants']) print(len(restaurants)) for restaurant in restaurants: price = restaurant['restaurant']['average_cost_for_two'] if (price_lt != None): if (price < int(price_lt)): continue if (price_ut != None): if (price > int(price_ut)): continue if (index <= 5): response = response + "Found " + restaurant['restaurant'][ 'name'] + " in " + restaurant['restaurant']['location'][ 'address'] + " has been rated" + restaurant[ 'restaurant']['user_rating'][ 'aggregate_rating'] + "\n" if (index <= 10): mail_response = mail_response + "Found " + restaurant[ 'restaurant']['name'] + " in " + restaurant[ 'restaurant']['location'][ 'address'] + "with an average budget for two as" + str( restaurant['restaurant'] ['average_cost_for_two'] ) + "has been rated" + restaurant['restaurant'][ 'user_rating']['aggregate_rating'] + "\n" index = index + 1 if (index == 10): break if (index == 0): response += "Could not find restaurants in the price range." mail_response += "Could not find restaurants in the price range." #response+="should I email you the details?" dispatcher.utter_message("-----" + response) return [SlotSet('mail_response', mail_response)]