def get_answer_from_kb(self, kb_details, question_from_user):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.kb_route = self.configuration[kb_details]

        question_to_kb = {}
        question_to_kb.update({'question': question_from_user})


        headers = {
            'Authorization': 'EndpointKey ' + self.kb_endpoint,
            'Content-Type': 'application/json'
        }

        try:
            self.log.write_log(sessionID='session1', log_message="question " + str(question_to_kb))
            self.conn = http.client.HTTPSConnection(self.kb_host, port=443)
            self.conn.request("POST", self.kb_route, str(question_to_kb), headers)
            self.response = self.conn.getresponse()
            self.answer = self.response.read()

            #this code is written to fetch the actual answer provided by the knowlegemaker

            answer_in_str = str(json.loads(self.answer))
            answer_in_dict = ast.literal_eval(answer_in_str)
            answer_return = answer_in_dict['answers'][0]['answer']

            self.log.write_log(sessionID='session1', log_message="question " + str(answer_return))
            return answer_return

        except:
            print("Unexpected error:", sys.exc_info()[0])
            print("Unexpected error:", sys.exc_info()[1])
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.kb_host = self.configuration['KB_HOST']
        self.kb_endpoint = self.configuration['KB_ENDPOINT']
        self.kb_route = ''

        self.log = Log()
Example #3
0
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()
     self.luis_app_id=self.configuration['LUIS_APP_ID']
     self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
     self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
     self.luis_app = LuisApplication(self.luis_app_id,self.luis_endpoint_key,self.luis_endpoint)
     self.luis_options = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
     self.luis_recognizer = LuisRecognizer(application=self.luis_app,prediction_options=self.luis_options,include_api_results=True)
     self.log=Log()
Example #4
0
	def getConfig( self, file, must_have ) :

		error = None
		config = ConfigReader( file )
		
		does_not_have_sections = []
		for section in must_have:
			if not config.hasSection( section ):
				does_not_have_sections.append( section )
				
		if does_not_have_sections:
			error = 	"Error: Config file does not contain sections:- " + ", ".join( does_not_have_sections )
				
		return config, error
 def getConfig( self, config_file, must_have ) :
     # Add self.config so new config config can be added to old.
     config = ConfigReader(config_file,
                           self.config,
                           overwrite_sections=True)
     does_not_have_sections = []
     for section in must_have:
         if len(section) > 0 and not config.hasSection( section ):
             print("section {0} not found".format(section))
             does_not_have_sections.append( section )
     if does_not_have_sections:
         error = "Error: Config file does not contain sections:- " + ", ".join( does_not_have_sections )
         raise ValueError(error)
     self.config = config
Example #6
0
class WeatherInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        #self.owmapikey = self.configuration['WEATHER_API_KEY']
        #self.owm = pyowm.OWM(self.owmapikey)

    def get_weather_info(self, city):

        self.bot_says = "Today the weather in"
        return self.bot_says

    def getIntentAndEntity(self, result):
        intent_str = json.loads(
            (str(result.top_scoring_intent)).replace("'", "\""))
        if ("intent" in intent_str):
            intent = intent_str.get('intent')
        else:
            intent = ""
        if (len(result.entities)) > 0:
            entity = result.entities[0].entity
            entity_type = result.entities[0].type
        else:
            entity = ""
            entity_type = ""
        return intent, entity, entity_type
Example #7
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.luis_util = LuisUtil()
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        #weather_info=WeatherInformation()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        out = self.luis_util.luis_result_as_dict(result)
        print(out)
        weather = out['topScoringIntent']['intent']
        weather = d[weather]
        #json_str = json.loads((str("hello")).replace("'", "\""))
        #weather=weather_info.get_weather_info(json_str.get('entity'))
        #weather = "i dont have anaswer"
        self.log.write_log(sessionID='session1',
                           log_message="Bot Says: " + str(weather))
        await turn_context.send_activity(f"{weather}")
Example #8
0
class WeatherInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.owmapikey = self.configuration['WEATHER_API_KEY']
        self.owm = pyowm.OWM(self.owmapikey)

    def get_weather_info(self, city):
        self.city = city

        mgr = self.owm.weather_manager()
        observation = mgr.weather_at_place(city)
        #get weather for the passed city
        weather = observation.weather
        #min max temperatures
        temp_dict_celsius = (weather.temperature('celsius'))
        min_temp = str(temp_dict_celsius['temp_min'])
        max_temp = str(temp_dict_celsius['temp_min'])
        #wind = str(weather.wind)
        humid = str(weather.humidity)

        self.bot_replies = "Today the weather in " + city + ".\n Maximum Temperature :" + max_temp + " degree celsius" + ".\n Minimum Temperature :" + min_temp + " degree celsius. " + ". \n Humidity: " + humid
        return self.bot_replies

    def get_weather_data(self, city):
        self.city = city

        MainQuery = "select  Date, City,Temp, max_temp,min_temp,Humid, Wind from w_data where " + "City=" + "'" + string.capwords(
            city) + "'"
        res = pysqldf(MainQuery)
        #res = tabulate(res)
        res = res.to_html(index=False, border=0)

        self.bot_replies = res
        return self.bot_replies
Example #9
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        info = get_data()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        json_str = json.loads((str(result.entities[0])).replace("'", "\""))
        weather = weather_info.get_weather_info(json_str.get('entity'))
        self.log.write_log(sessionID='session1',
                           log_message="Bot Says: " + str(weather))
        await turn_context.send_activity(f"{weather}")
class WeatherInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.owmapikey = self.configuration['WEATHER_API_KEY']
        self.owm = pyowm.OWM(self.owmapikey)

    def get_weather_info(self, city):
        self.city = city

        # Here we are calling pre-defined method weather_at... from open weather map(owm)
        # which we subscribed to and we are using the key to connect to it and then proving city name.
        # Then the following codes we'll get different types of information.
        # And at last combine'em all.
        observation = self.owm.weather_at_place(city)
        w = observation.get_weather()
        latlon_res = observation.get_location()
        lat = str(latlon_res.get_lat())
        lon = str(latlon_res.get_lon())

        wind_res = w.get_wind()
        wind_speed = str(wind_res.get('speed'))

        humidity = str(w.get_humidity())

        celsius_result = w.get_temperature('celsius')
        temp_min_celsius = str(celsius_result.get('temp_min'))
        temp_max_celsius = str(celsius_result.get('temp_max'))

        fahrenheit_result = w.get_temperature('fahrenheit')
        temp_min_fahrenheit = str(fahrenheit_result.get('temp_min'))
        temp_max_fahrenheit = str(fahrenheit_result.get('temp_max'))
        self.bot_says = "Today the weather in " + city + " is :\n Maximum Temperature :" + temp_max_celsius + " Degree Celsius" + ".\n Minimum Temperature :" + temp_min_celsius + " Degree Celsius" + ": \n" + "Humidity :" + humidity + "%"
        return self.bot_says
Example #11
0
def main(config_file, ignore_undefined=False, load_models_first=False):
    """The main function

    Arguments:
        config_file {str} -- Path for the run's configuration file
    """
    # # time the entire run
    with tictoc("Total run"):
        # initialize configuration
        global_config, pipeline, triggers = ConfigReader.read_configuration(
            config_file, ignore_undefined)

        pipeline.configure_names()

        #
        should_load_models = load_models_first or any(
            trig.requires_model_loading() for trig in triggers)
        if should_load_models:
            error(
                "Should load models but model deserialization is not enabled!",
                not global_config.misc.allow_model_deserialization)
            pipeline.load_models()

        for trig in sorted(triggers, key=lambda x: x.is_blocking):
            trig.link_pipeline(pipeline)
            trig.setup()

        for trig in triggers:
            trig.arm()

        if num_warnings > 0:
            warning("{} warnings occured.".format(num_warnings - 1))
        info("Logfile is at: {}".format(global_config.logfile))
    tictoc.log(global_config.logfile + ".timings")
Example #12
0
class WeatherInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.owmapikey = self.configuration['WEATHER_API_KEY']
        self.owm = pyowm.OWM(self.owmapikey)

    def get_weather_info(self, city):
        self.city = city

        observation = self.owm.weather_at_place(city)
        w = observation.get_weather()
        latlon_res = observation.get_location()
        lat = str(latlon_res.get_lat())
        lon = str(latlon_res.get_lon())

        wind_res = w.get_wind()
        wind_speed = str(wind_res.get('speed'))

        humidity = str(w.get_humidity())

        celsius_result = w.get_temperature('celsius')
        temp_min_celsius = str(celsius_result.get('temp_min'))
        temp_max_celsius = str(celsius_result.get('temp_max'))

        fahrenheit_result = w.get_temperature('fahrenheit')
        temp_min_fahrenheit = str(fahrenheit_result.get('temp_min'))
        temp_max_fahrenheit = str(fahrenheit_result.get('temp_max'))
        self.bot_says = "Today the weather in " + city + ".\n Maximum Temperature :" + temp_max_celsius + " Degree Celsius" + ".\n Minimum Temperature :" + temp_min_celsius + " Degree Celsius" + ": \n" + "Humidity :" + humidity + "%"
        return self.bot_says
Example #13
0
    def __init__(self, conversation_state: ConversationState,
                 user_state: UserState):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.qna_knowledge_base_id = self.configuration["QNA_KNOWLEDGEBASE_ID"]
        self.qna_endpoint_key = self.configuration["QNA_ENDPOINT_KEY"]
        self.qna_host = self.configuration["QNA_ENDPOINT_HOST"]
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(knowledge_base_id=self.qna_knowledge_base_id,
                             endpoint_key=self.qna_endpoint_key,
                             host=self.qna_host))
        self.log = Log()
        self.IntentIdentified = False
        self.intent = 'none'
        self.stat = 'init'
        self.city = ""
        self.score = ""

        if conversation_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. conversation_state is required but None was given"
            )
        if user_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. user_state is required but None was given"
            )

        self.conversation_state = conversation_state
        self.user_state = user_state

        self.conversation_data_accessor = self.conversation_state.create_property(
            "ConversationData")
        self.user_profile_accessor = self.user_state.create_property(
            "UserProfile")
Example #14
0
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        """self.owmapikey = self.configuration['A*_SEARCH_API_KEY'] 
        self.owm = pyowm.OWM(self.owmapikey)

    def get_direction_info(self,city):

        self.city=city










        self.bot_says = ###STRINGS OF DIRECTIONS ADDED TOGETHER (defined in function above)###"""
        return self.bot_says
Example #15
0
class CoronaInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        

    def get_corona_info(self,city):
        self.city=city
        covid = Covid()
        cases = covid.get_status_by_country_name(city)
        d = str(cases['deaths'])
        self.bot_says = "Total Death " + d 
        return self.bot_says
class directionInformation():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        """self.owmapikey = self.configuration['A*_SEARCH_API_KEY'] 
        self.owm = pyowm.OWM(self.owmapikey)"""

    def get_direction_info(self,input_string):

        self.input_string = input_string
        campus = A_Star("nodes_glossary.json", self.input_string)
        campus.solve()
        campus.format_output()
        output = " ".join(formatted_output)

        self.bot_says = output
        return self.bot_says
Example #17
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id, self.luis_endpoint_key, self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True, include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(application=self.luis_app, prediction_options=self.luis_options,
                                              include_api_results=True)
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        knowledgebase = KnowledgeBase()

        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        top_intent = self.top_intent(luis_result)

        user_query = turn_context.activity.text

        kb_answer = knowledgebase.get_answer_from_kb(top_intent, user_query)
        self.log.write_log(sessionID='session1', log_message="Answer from KB is : " + str(kb_answer))
        await turn_context.send_activity(f"{kb_answer}")

    @staticmethod
    def top_intent(results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0) -> str:
        if results is None:
            raise TypeError("LuisRecognizer.top_intent(): results cannot be None.")

        top_intent: str = None
        top_score: float = -1.0
        if results.intents:
            for intent_name, intent_score in results.intents.items():
                score = intent_score.score
                if score > top_score and score >= min_score:
                    top_intent = intent_name
                    top_score = score

        return top_intent or default_intent
Example #18
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id=self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,self.luis_endpoint_key,self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(application=self.luis_app,prediction_options=self.luis_options,include_api_results=True)
        self.log=Log()
 

    async def on_message_activity(self,turn_context:TurnContext):
        weather_info=WeatherInformation()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        #json_str = json.loads((str(result.entities[0])).replace("'", "\""))
        #weather=weather_info.get_weather_info(json_str.get('entity'))
        #self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
        #await turn_context.send_activity(f"{weather}")

        check = json.loads((str(result.intents[0])).replace("'", "\""))
        if check.get('intent') == 'Welcome':
            await turn_context.send_activity(f"Hello, I can help you know the weather of any city")

            #print("Welcome")
        elif check.get('intent') == 'weather': 
            json_str = json.loads((str(result.entities[0])).replace("'", "\""))
            weather=weather_info.get_weather_info(json_str.get('entity'))
            self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
            await turn_context.send_activity(f"{weather}")
        else:
            json_str = json.loads((str(result.entities[0])).replace("'", "\""))
            weather=weather_info.get_weather_data(json_str.get('entity'))
            self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
            await turn_context.send_activity(f"{weather}")
Example #19
0
class LuisConnect(ActivityHandler):
    def __init__(self, conversation_state: ConversationState,
                 user_state: UserState):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.qna_knowledge_base_id = self.configuration["QNA_KNOWLEDGEBASE_ID"]
        self.qna_endpoint_key = self.configuration["QNA_ENDPOINT_KEY"]
        self.qna_host = self.configuration["QNA_ENDPOINT_HOST"]
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(knowledge_base_id=self.qna_knowledge_base_id,
                             endpoint_key=self.qna_endpoint_key,
                             host=self.qna_host))
        self.log = Log()
        self.IntentIdentified = False
        self.intent = 'none'
        self.stat = 'init'
        self.city = ""
        self.score = ""

        if conversation_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. conversation_state is required but None was given"
            )
        if user_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. user_state is required but None was given"
            )

        self.conversation_state = conversation_state
        self.user_state = user_state

        self.conversation_data_accessor = self.conversation_state.create_property(
            "ConversationData")
        self.user_profile_accessor = self.user_state.create_property(
            "UserProfile")
        # session['IntentIdentified']=False
        # session['state']="init"
        # session['intent']='none'

    async def on_turn(self, turn_context: TurnContext):
        await super().on_turn(turn_context)

        await self.conversation_state.save_changes(turn_context)
        await self.user_state.save_changes(turn_context)

    def welcome(self):
        return "Hi How can I help you?"

    async def __send_intro_card(self, turn_context: TurnContext):
        card = HeroCard(
            title="Welcome to Bot Framework!",
            text="Welcome to Welcome Users bot sample! This Introduction card "
            "is a great way to introduce your Bot to the user and suggest "
            "some things to get them started. We use this opportunity to "
            "recommend a few next steps for learning more creating and deploying bots.",
            images=[CardImage(url="https://aka.ms/bf-welcome-card-image")],
            buttons=[
                CardAction(
                    type=ActionTypes.open_url,
                    title="Get an overview",
                    text="Get an overview",
                    display_text="Get an overview",
                    value=
                    "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0",
                ),
                CardAction(
                    type=ActionTypes.open_url,
                    title="Ask a question",
                    text="Ask a question",
                    display_text="Ask a question",
                    value=
                    "https://stackoverflow.com/questions/tagged/botframework",
                ),
                CardAction(
                    type=ActionTypes.open_url,
                    title="Learn how to deploy",
                    text="Learn how to deploy",
                    display_text="Learn how to deploy",
                    value=
                    "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0",
                ),
            ],
        )

        return await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(card)))

    def _process_input(self, text: str):
        color_text = "is the best color, I agree."

        if text == "red":
            return f"Red {color_text}"

        if text == "yellow":
            return f"Yellow {color_text}"

        if text == "blue":
            return f"Blue {color_text}"

        return "Please select a color from the suggested action choices"

    async def _send_suggested_actions(self, turn_context: TurnContext):
        """
            Creates and sends an activity with suggested actions to the user. When the user
            clicks one of the buttons the text value from the "CardAction" will be displayed
            in the channel just as if the user entered the text. There are multiple
            "ActionTypes" that may be used for different situations.
            """

        reply = MessageFactory.text("Confirm the option")

        reply.suggested_actions = SuggestedActions(actions=[
            CardAction(title="YES", type=ActionTypes.im_back, value="YES"),
            CardAction(title="NO", type=ActionTypes.im_back, value="NO"),
        ])

        return await turn_context.send_activity(reply)

    async def on_message_activity(self, turn_context: TurnContext):
        # weather_info=WeatherInformation()
        # print("new session :",session)
        # Get the state properties from the turn context.
        user_profile = await self.user_profile_accessor.get(
            turn_context, UserProfile)
        conversation_data = await self.conversation_data_accessor.get(
            turn_context, ConversationData)
        conversation_data.channel_id = turn_context.activity.channel_id
        print(conversation_data.channel_id)
        if user_profile.name is None:
            # First time around this is undefined, so we will prompt user for name.
            if conversation_data.prompted_for_user_name:
                # Set the name to what the user provided.
                user_profile.name = turn_context.activity.text

                # Acknowledge that we got their name.
                await turn_context.send_activity(
                    f"Thanks { user_profile.name }. To see conversation data, type anything in the {conversation_data.channel_id}"
                )

                # Reset the flag to allow the bot to go though the cycle again.
                conversation_data.prompted_for_user_name = False
            else:
                # Prompt the user for their name.
                await turn_context.send_activity("What is your name?")

                # Set the flag to true, so we don't prompt in the next turn.
                conversation_data.prompted_for_user_name = True
        else:
            print("1", self.IntentIdentified)
            print("turn_context", turn_context.activity.text)
            if self.IntentIdentified == False:
                luis_result = await self.luis_recognizer.recognize(turn_context
                                                                   )
                result = luis_result.properties["luisResult"]
                print(str(result.intents[0]))
                intentDetails = json.loads(
                    (str(result.intents[0])).replace("'", "\""))
                intent = intentDetails.get('intent')
                score = intentDetails.get('score')
                print(intent)
                print(score)
                self.IntentIdentified = True
                self.intent = intent
                self.score = score
            if self.intent == "Welcome" and self.score > 0.5:
                #bot_reply = "Hi How can I help you?"
                #bot_reply = self.welcome()
                await self.__send_intro_card(turn_context)
                bot_reply = f"{ user_profile.name }. To where should i book a flight for you?."
                self.IntentIdentified = False
            elif self.intent == "BookFlight" and self.score > 0.5:
                if self.stat == 'init':
                    print(str(result.entities[0]))
                    json_str = json.loads(
                        (str(result.entities[0])).replace("'", "\""))
                    #weather=weather_info.get_weather_info(json_str.get('entity'))
                    self.city = json_str.get('entity')
                    bot_reply = "should I book a flight to " + self.city + "."
                    await turn_context.send_activity(f"{bot_reply}")
                    print("1")
                    #await self._send_suggested_actions(turn_context)
                    print("2")
                    text = turn_context.activity.text.lower()
                    print("text", text)
                    #response_text = self._process_input(text)
                    #await turn_context.send_activity(MessageFactory.text(response_text))
                    self.stat = 'bookFlight'
                    bot_reply = ""
                    return await self._send_suggested_actions(turn_context)
                elif self.stat == 'bookFlight':
                    if turn_context.activity.text == "YES":
                        bot_reply = "Booked a flight to " + self.city + "."
                        self.stat = 'init'
                    else:
                        bot_reply = "cancelled booking procedure."
                        self.stat = 'init'
                self.log.write_log(sessionID='session1',
                                   log_message="Bot Says: " + str(bot_reply))
                self.IntentIdentified = False
            elif self.score < 0.5:
                # The actual call to the QnA Maker service.
                bot_reply = ""
                self.IntentIdentified = False
                response = await self.qna_maker.get_answers(turn_context)
                if response and len(response) > 0:
                    await turn_context.send_activity(
                        MessageFactory.text(response[0].answer))
                else:
                    await turn_context.send_activity(
                        "No QnA Maker answers were found.")
            await turn_context.send_activity(f"{bot_reply}")

    async def on_members_added_activity(self, members_added: ChannelAccount,
                                        turn_context: TurnContext):
        for member_added in members_added:
            if member_added.id != turn_context.activity.recipient.id:
                await turn_context.send_activity("Hello How can I help you!")
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()
     """self.owmapikey = self.configuration['A*_SEARCH_API_KEY'] 
Example #21
0
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()
     self.owmapikey = self.configuration['WEATHER_API_KEY']
     self.owm = pyowm.OWM(self.owmapikey)
Example #22
0
from flask import Flask
from config.config_reader import ConfigReader
from api.user_api import *

app = Flask(__name__)
app.register_blueprint(users_api)


@app.route('/')
def main_page():
    return 'It is working!'


if __name__ == '__main__':
    config_reader = ConfigReader()
    debug = config_reader.get_app_config("debug")
    port = config_reader.get_app_config("port")
    app.run(debug=debug, port=port)
Example #23
0
import sys

sys.path.insert(1, '/home/nitin/code/Ashrut/compass/ui_app/app/helper/kafka')
from consumer import CustomKafkaConsumer as kafka_consumer
from config.config_reader import ConfigReader

config = ConfigReader()
data = config.get_kafka_consumer_data()


ip = data['ip']
port = data['port']
topic = data['topic']

from_begin = True
if data['from_begin'] == 0:
	from_begin = False

consumer = kafka_consumer(ip=ip, port=port, topic=topic, 
						  from_begin=from_begin)
print('Starting Kafka Consumer!')
consumer.get()
Example #24
0
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()