Пример #1
0
    def __init__(self, parent=None):

        QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()

        self.file = None
        self.goal = None
        self.log = None

        self.setWindowTitle('Экспертная система')

        self.ui.actionNew.triggered.connect(self.showDialogNew)
        self.ui.actionOpen.triggered.connect(self.showDialogOpen)
        self.ui.actionSaveAs.triggered.connect(self.showDialogSaveAs)
        self.ui.actionSave.triggered.connect(self.saveKnowledge)
        
        self.ui.actionDomains.triggered.connect(self.showDialogDomains)
        self.ui.actionVariables.triggered.connect(self.showDialogVariables)
        self.ui.actionViewOntology.triggered.connect(self.showDialogOntologyView)
        self.ui.actionFacts.triggered.connect(self.showDialogFacts)

        self.ui.actionStart.triggered.connect(self.showDialogRecommendation)
        self.ui.action.triggered.connect(self.showDialogGoal)

        self.ui.actionSolution.triggered.connect(self.showDialogSolution)

        self.ui.buttonAdd.clicked.connect(self.showDialogAddRule)
        self.ui.buttonEdit.clicked.connect(self.showDialogEditRule)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)

        self.ui.Rules.setDragDropMode(QAbstractItemView.InternalMove)
        self.ui.Rules.itemSelectionChanged.connect(self.RefreshBoxes)
Пример #2
0
    def __init__(self, verbose):
        self._verbose = verbose

        self.knowledge = Knowledge()
        self.knowledge.add_to_memory(CS4635Context())

        self.invalid_list = list()
Пример #3
0
 def home_page(self):
     self.GUI()
     knowledge = Knowledge()
     '''Location and time for home'''
     time_json, str_time, str_day = knowledge.time_knowledge()
     clock = tk.Label(self.window,
                      text=str_day,
                      font=('Arial', 17),
                      fg='white',
                      bg='black')
     clock.place(relx=0.1, rely=0.1, anchor="center")
     clock = tk.Label(self.window,
                      text=str_time,
                      font=('Arial', 30),
                      fg='white',
                      bg='black')
     clock.place(relx=0.1, rely=0.05, anchor="center")
     '''weather for home'''
     weather_json = knowledge.weather_knowledge()
     temp = weather_json['main']['temp']
     print(temp)
     #temp = float(5/9)*(float(temp)-32 )
     temp = int(temp) - 273
     print(temp)
     self.display()
Пример #4
0
 def showDialogNew(self):
     qm = QMessageBox()
     qm.setWindowTitle('Создать новую базу знаний')
     ret = qm.question(self,'', "Вы уверены?", qm.Yes | qm.No)
     if ret == qm.Yes:
         self.knowledge = Knowledge()
         self.setWindowTitle('Экспертная система - БезНазвания' )
     else:
         pass
Пример #5
0
 def __init__(self, name=None, speech_input=False, facebook_input=False):
     self.phrases = Phrases()
     self.speech = Speech()
     self.knowledge = Knowledge(weather_api_token=weather_api_token)
     self.name = name
     self.facebook_input = facebook_input
     if self.facebook_input:
         self.facebook_response = list()
     self.speech_input = speech_input
     self.witai = Wit("S73IKQDWJ22OJMOSD6AOT4CSJOWXIPX6")
     self.fs = Fatsecret("90fe184a283449ed8a83e35790c04d65", "054e80b2be154337af191be2c9e11c28")
     self.translator = Translator()
Пример #6
0
def update_temp():
    global temp1
    global temp_
    knowledge = Knowledge()
    weather_json = knowledge.weather_knowledge()
    location_json = knowledge.location_knowledge()
    temp_ = weather_json['main']['temp']
    location_temp = location_json['state_prov']
    if temp1 != temp_:
        temp1 = temp_
        text = int(temp1 - 273)
        temp.config(text=location_temp + "City\n%d oC" % text)
    temp.after(50000, update_greeting)
Пример #7
0
    def test_nested(self):
        alice = Knowledge('alice ')
        bob = Knowledge()

        @bob.simple("about time")
        async def touch(message: str):
            assert message == 'about time'
            return 'time is nothing'

        alice.prefix('ask bob ', bob)  # make nested knowledge

        reply = asyncio.get_event_loop().run_until_complete(alice('alice ask bob about time'))
        print("reply", reply)
        assert reply == 'time is nothing', 'nested knowledge'
Пример #8
0
    def test_rule_4(self):
        g = make_graph(4, [(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (3, 0),
                           (1, 2), (2, 3)])
        k = Knowledge()
        k.set_forbidden(1, 3)

        meek = MeekRules(undirect_unforced_edges=False, knowledge=k)
        meek.orient_implied_subset(g, [0])

        assert len(g.edges()) == 7
        assert has_dir_edge(g, 1, 2)
        assert has_dir_edge(g, 2, 3)
        assert has_dir_edge(g, 0, 3)
        assert has_undir_edge(g, 0, 1)
        assert has_undir_edge(g, 0, 2)
Пример #9
0
    def learn_from_file(self):
        ''' It search for knowledge in directory, if exists it is loaded - Procura conhecimentos no diretório, se existir são carregados'''
        log("charging knowledge from files")
        import glob
        files = glob.glob("./know/*")
        for file in files:
            data = open(file, "r")
            data = data.readlines()

            nome = data[1].replace("#", "").replace("\n", "")
            print nome
            topicos = data[2].replace("#", "").replace("\n", "")
            descricao = data[3].replace("#", "").replace("\n", "")
            modelo = data[4].replace("#", "").replace("\n", "")
            endereco = file
            atributos = data[6].replace("#", "").replace("\n", "").split()
            dependencias = data[7].replace("#",
                                           "").replace("\n",
                                                       "").replace(",",
                                                                   "").split()
            for dep in dependencias:
                dep = dep.replace(",", "").replace(" ", "")
            tipoDeTarefa = data[8].replace("#", "").replace("\n", "").split()
            if len(tipoDeTarefa) > 0:
                tipoDeTarefa = tipoDeTarefa.pop()
            else:
                tipoDeTarefa = "passive"
            #print (type (tipoDeTarefa))
            know = Knowledge(nome, topicos, descricao, modelo, endereco,
                             atributos, dependencias, tipoDeTarefa)
            self.knowledge.append(know)
Пример #10
0
    def receive_knowledge(self, knowledge):
        ''' Callback: It receives knowledges from topic and save it in files - Recebe conhecimento e o salva em arquivos'''
        data = str(knowledge.data).split("\n")
        if self.has(data[1].replace("#", "").replace("\n", "")):
            #log ("I already have this knowledge: " + str(data[1]))
            return
        nome = data[1].replace("#", "").replace("\n", "")
        topicos = data[2].replace("#", "").replace("\n", "")
        descricao = data[3].replace("#", "").replace("\n", "")
        modelo = data[4].replace("#", "").replace("\n", "")
        endereco = data[5].replace("#", "").replace("\n", "")
        atributos = data[6].replace("#", "").replace("\n", "").split()
        dependencias = data[7].replace("#",
                                       "").replace("\n",
                                                   "").replace(",",
                                                               "").split()
        for dep in dependencias:
            dep = dep.replace(",", "").replace(" ", "")
        tipoDeTarefa = data[8].replace("#", "").replace("\n", "").split()
        if len(tipoDeTarefa) > 0:
            tipoDeTarefa = tipoDeTarefa.pop()
        else:
            tipoDeTarefa = "passive"

        know = Knowledge(nome, topicos, descricao, modelo, endereco, atributos,
                         dependencias, tipoDeTarefa)

        file = open(data[5].replace("#", "").replace("\n", ""), "wb")
        for i in data:
            file.write(i + "\n")
        self.knowledge.append(know)
        file.close()
        print('\033[94m' + "I learn!" + str(data[1]))
        self.addInLog("Learn " + str(data[1]))
Пример #11
0
def create_rdf():
    """
    Create SoftEng RDF file
    """

    graph = Graph()
    Knowledge(graph)
    AcademicDomain(graph)
    graph.serialize("ontology/RDF/softeng.rdf")
Пример #12
0
class StudentAgent:
    def __init__(self, verbose):
        self._verbose = verbose

        self.knowledge = Knowledge()
        self.knowledge.add_to_memory(CS4635Context())

    # Takes in list of words, returns question_object and data_requested
    def input_output(self, word_list):
        context = self.knowledge.infer_context(word_list)

        context.infer_topic(word_list)
        _data_requested = context.topic

        qframe = QuestionFrame(word_list, context)
        _question_object = qframe.object

        return _question_object, _data_requested
Пример #13
0
    def __init__(self):
        self.nlg = NLG(user_name=my_name)
        self.nlg_vn = NLG(user_name=my_name_vn, language='vi')
        self.speech = Speech(launch_phrase=launch_phrase,
                             debugger_enabled=debugger_enabled)
        self.wit_client_vn = Wit(wit_ai_token_vn)
        self.wit_client_en = Wit(wit_ai_token)
        self.knowledge = Knowledge(weather_api_token,
                                   google_cloud_api_key=google_cloud_api_key)
        #self.vision = Vision(camera=camera)
        self.bot_vn = 'ty'

        subprocess.Popen([
            "aplay", "/home/pi/AI-Smart-Mirror/sample-audio-files/Startup.wav"
        ],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
        time.sleep(4)
Пример #14
0
    def initialize(self, id, num_players, k, board, deck_type, my_hand, hands,
                   discard_pile, deck_size):
        """
        To be called once before the beginning.
        """
        self.id = id
        self.num_players = num_players
        self.k = k  # number of cards per hand
        self.board = board
        self.deck_type = deck_type

        # store a copy of the full deck
        self.full_deck = get_appearance(DECKS[deck_type]())
        self.full_deck_composition = Counter(self.full_deck)

        # hands
        self.my_hand = my_hand  # says in which positions there is actually a card
        self.hands = hands

        # discard pile
        self.discard_pile = discard_pile
        self.discard_pile_composition = Counter(discard_pile)

        # deck size
        self.deck_size = deck_size

        # personal knowledge
        self.personal_knowledge = Knowledge(self, Knowledge.PERSONAL, id)

        # public knowledge
        self.public_knowledge = [
            Knowledge(self, Knowledge.PUBLIC, i) for i in range(num_players)
        ]

        # all knowledge
        self.all_knowledge = self.public_knowledge + [self.personal_knowledge]

        # remove cards of other players from possibilities
        self.update_knowledge()

        # create hints manager
        self.hints_manager = HintsManager(self)
Пример #15
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()

        self.ui.Domains.currentTextChanged.connect(self.refreshDomainValues)
        self.ui.VarCategory.currentTextChanged.connect(self.refreshBlock)
        self.ui.textQuestion.setReadOnly(True)

        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)
Пример #16
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_dialog()
        self.ui.setupUi(self)

        self.ui.domainName.setPlaceholderText('Имя домена')

        self.knowledge = Knowledge()

        self.ui.buttonAdd.clicked.connect(self.click_buttonAdd)
        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)
        self.ui.domainName.setFocus()
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()
        self.edit = None

        self.ui.buttonAdd.clicked.connect(self.click_buttonAdd)
        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)

        self.ui.Facts.view().setFixedWidth(300)
Пример #18
0
    def __init__(self, game, x, y):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.images = {'normal': pg.image.load(path.join(game.img_folder, "apple_64px.png")).convert_alpha(), \
                       'blink': pg.image.load(path.join(game.img_folder, "apple_64px_blink.png")).convert_alpha(), \
                       'wink': pg.image.load(path.join(game.img_folder, "apple_64px_wink.png")).convert_alpha()}
        self.blinks = False
        self.blink_time = .25
        self.staring_time = 3
        self.start_time = time.time()
        self.image = self.images['normal']
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.hit_rect = self.rect
        self.hit_rect.center = self.rect.center
        self.vel = vec(0, 0)
        self.position = vec(x, y)
        self.dest = vec_dest(x, y)
        self.previous_pos = vec_prev(x, y)
        self.instruction = ""
        self.orientation = "front" # left, right, front, back
        self.name = "Young Apple"
        self.silence_responses = ["can you please say that again?", "oops, I missed that. say again?", "I heard *silence*", "repeat again, please?", "could you say again?", "I didn't hear that, try again?", "I heard *silence*"]
        self.knowledge = Knowledge(self)
        self.transcript = Transcript()

        # Working memory properties
        self.recognized = []
        self.actions = [] # current, complete list of action sequences e.g. [[1],[[0],[2]]]
        self.input_to_actions = []
        self.action_queue = [] # remaining actions to be completed
        self.current_action = []
        self.key_used = ""
        #self.responses = []
        self.response = ""
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()

        self.ui.buttonAdd.clicked.connect(self.click_buttonAdd)
        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)

        self.ui.tableWidget.setColumnWidth(0, 120)
        self.ui.tableWidget.setColumnWidth(1, 280)
        self.ui.tableWidget.setSelectionBehavior(
            self.ui.tableWidget.SelectRows)
        self.ui.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)
Пример #20
0
    def test_annotations(self):
        brain = Knowledge('alice ', 'bob ')

        @brain.simple('what time is it now?')
        async def current_time(message: str):
            return 'no time - no problem'

        @brain.regexp(r'I am (?P<name>\w+)')
        async def greet(message: str, name: str):
            return f"Hello, {name}!"

        @brain.simple("raise an error")
        async def broken(message: str):
            raise RuntimeError("test error")

        @brain.simple("skip none")
        async def skip_none(message: str):
            return None

        @brain.simple('multi')
        @brain.simple('another')
        @brain.regexp('.*?nano.*')
        async def multi(message: str):
            return 'ok'

        @brain.default()
        async def unknown(message: str):
            return "WTF?"

        @brain.simple('pass element')
        async def params(message: str, custom_value=None):
            assert custom_value is not None
            return message

        async def main():
            assert await brain('bob what time is it now?') == 'no time - no problem', 'simple match'
            assert await brain('alice I am Brayan!') == 'Hello, Brayan!', 'regexp named match'
            assert await brain('nick I am Alice') is None, 'no trigger'
            assert await brain('alice raise an error') == 'WTF?', 'suppress exception'
            assert await brain('alice skip none') == 'WTF?', 'skip none result'
            assert await brain('bob who are you?') == 'WTF?', 'default trigger'
            assert await brain('alice multi') == 'ok', 'multi triggers over first simple'
            assert await brain('alice another') == 'ok', 'multi triggers over second simple'
            assert await brain('alice super nano multi') == 'ok', 'multi triggers over regexp'
            assert await brain('alice pass element', custom_value=123) == 'pass element', 'pass element'

        asyncio.get_event_loop().run_until_complete(main())
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()

        self.ui.tableWidget.setColumnWidth(0, 135)
        self.ui.tableWidget.setColumnWidth(1, 60)
        self.ui.tableWidget.setColumnWidth(2, 135)
        self.ui.tableWidget.setSelectionBehavior(
            self.ui.tableWidget.SelectRows)
        self.ui.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)

        self.ui.variables.currentTextChanged.connect(self.RefreshValues)
        self.ui.buttonAdd.clicked.connect(self.click_buttonAdd)
        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)
Пример #22
0
def initialize_objs_vars():
    '''
    Initializing all game objects (and some important vars) at the start of the run, namely:
    Objects: Player, entities, god, game_map,
    Important VARS: game_state, fov_map, key, mouse
    '''
    # OBJECTS
    actor_comp = Actor(mental=pstats['mental'],
                       physical=pstats['physical'],
                       spiritual=pstats['spiritual'])
    inventory_comp = Inventory(5)
    knowledge_comp = Knowledge()
    player = Entity(0,
                    0,
                    '@',
                    colors['player'],
                    'Hero',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    actor=actor_comp,
                    inventory=inventory_comp,
                    knowledge=knowledge_comp)
    entities = [player]
    god = God()
    game_map = GameMap(const.get('map_width'), const.get('map_height'))
    game_map.make_map(player, entities)

    #Important vars
    game_state = GameStates.PLAYERS_TURN
    prev_game_state = game_state
    fov_map = initialize_fov(game_map)
    key = tcod.Key()
    mouse = tcod.Mouse()

    targeting_item = None

    targeting_skill = None

    #Message related stuff, in a near future, separate into combat, qests, chat, etc
    msg_log = MessageLog(const['message_x'], const['message_width'],
                         const['message_height'])

    return player, entities, god, game_map, game_state, prev_game_state, fov_map, msg_log, key, mouse, targeting_item, targeting_skill
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.knowledge = Knowledge()

        self.ui.tableWidget.setColumnWidth(0, 120)
        self.ui.tableWidget.setColumnWidth(1, 120)
        self.ui.tableWidget.setColumnWidth(2, 190)
        self.ui.tableWidget.setSelectionBehavior(
            self.ui.tableWidget.SelectRows)
        self.ui.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)

        self.ui.buttonAdd.clicked.connect(self.showDialogVariableAdd)
        self.ui.buttonDelete.clicked.connect(self.click_buttonDelete)
        self.ui.buttonEdit.clicked.connect(self.click_buttonEdit)

        self.ui.tableWidget.itemSelectionChanged.connect(
            self.RefreshQuestionDomainBoxes)
Пример #24
0
    def __init__(self, db_conn, db_name):
        from pymongo import Connection

        print "Opening MongoDB connection"
        self.conn = Connection(host=db_conn)
        self.db = self.conn[db_name]

        # Open subcollections
        self.knowledge = Knowledge(self)
        self.frames = Frames(self)
        #self.map = Map(self)
        self.geo = Geo(self)

        # Logging
        from wifistalker import Log
        header = 'DB'
        self.log = Log(self, use_stdout=True, header=header)

        # Log collection
        self._log = self['log']
        self._log.ensure_index('stamp_utc', expireAfterSeconds=60*60)
Пример #25
0
 def transform(self):
     """
     Convert original crash dump information into the target data format.
     Returns:
         Documents to be stored.
     """
     documents = []
     hash_value = set()
     result = self.extract_qdb()
     count, total = 0, len(result)
     for row in result:
         count += 1
         test_id, time_stamp, url, bug_id = row
         print(f"{test_id}, {count}/{total}")
         try:
             if requests.get(url, verify=False).status_code == 200:
                 dump = requests.get(url, verify=False).content.decode("utf-8")
                 processed = Process(dump).pre_process()
             else:
                 dump = self.extract_cdb(test_id)
                 processed = Process(dump).internal_process()
         except (IndexError, UnicodeDecodeError):
             continue
         cpnt_order, func_block = Knowledge(processed).add_knowledge()
         if not cpnt_order or not func_block:
             continue
         data = dict()
         data["test_id"] = test_id
         data["time_stamp"] = int(datetime.timestamp(time_stamp))
         data["cpnt_order"] = cpnt_order
         data["func_block"] = func_block
         data["bug_id"] = bug_id
         data["md5sum"] = hashlib.md5("".join("".join(i) for i in func_block).encode("utf-8")).hexdigest()
         # deduplication via set
         if data["md5sum"] in hash_value:
             continue
         hash_value.add(data["md5sum"])
         documents.append(data)
     return documents
Пример #26
0
 def detect_sim(self):
     """
     Detect crash dump similarity and output the comparison result.
     """
     message = []
     order_pair, block_pair = [], []
     for param in self.params:
         # parameter is test_id
         if re.match(r"^\d{9,}$", param):
             dump = ETL().extract_cdb(param)
             processed = Process(dump).internal_process()
         # parameter is dump_path
         else:
             with open(param, "r", encoding="utf-8") as fp:
                 dump = fp.read()
             processed = Process(dump).pre_process()
         cpnt_order, func_block = Knowledge(processed).add_knowledge()
         message.extend([cpnt_order, func_block])
         order_pair.append(cpnt_order)
         block_pair.append(func_block)
     # output dump comparison
     Log().dump_print(message)
     Calculate(order_pair, block_pair).calculate_sim(debug=True)
Пример #27
0
 def initialize(self):
     self.verbose = True
     self.statistics = Statistics()
     self.statistics.initialize(self)
     self.knowledge = Knowledge()
     self.knowledge.initialize(self)
     
     #todo: make this more generic,
     # i.e. allow for an arbitrary number of roles
     # load all rule bases
     self.loadMetaRules()
     self.loadAttackerRules()
     self.loadDefenderRules()
     self.loadCatcherRules()
     
     # distribute the roles to the bots 
     roleList = self.metaScript.runDynamicScript([len(self.game.team.members),self.statistics])
     if(roleList != None):
         self.distributeRoles(roleList)
     else: #If none of the rules apply, use a mixed team.
         self.distributeRoles(metaRules.mixedAttackers(len(self.game.team.members)))
     # and generate the corresponding scripts
     self.initializeRoles()
     self.initializeBotStats()
Пример #28
0
class StudentAgent:
    def __init__(self, verbose):
        self._verbose = verbose

        self.knowledge = Knowledge()
        self.knowledge.add_to_memory(CS4635Context())

        self.invalid_list = list()

    def input_output(self, word_list):
        # Understand
        context = self.knowledge.infer_context(word_list)
        working_memory = self.knowledge.understand(word_list, context)

        if working_memory is None:
            self.invalid_list.append(word_list)

        # Classify
        case = self.knowledge.classify(working_memory, context)

        _intent = case.label
        return _intent
Пример #29
0
class Bot(object):
    def __init__(self):
        self.nlg = NLG(user_name=my_name)
        self.speech = Speech(launch_phrase=launch_phrase, debugger_enabled=debugger_enabled)
        self.knowledge = Knowledge(weather_api_token)
        self.vision = Vision(camera=camera)

    def start(self):
        """
        Main loop. Waits for the launch phrase, then decides an action.
        :return:
        """
        while True:
            requests.get("http://localhost:8080/clear")
            if self.vision.recognize_face():
                print "Found face"
                if use_launch_phrase:
                    recognizer, audio = self.speech.listen_for_audio()
                    if self.speech.is_call_to_action(recognizer, audio):
                        self.__acknowledge_action()
                        self.decide_action()

                            
                else:

                    self.decide_action()

                        

    def decide_action(self):
        """
        Recursively decides an action based on the intent.
        :return:
        """
        recognizer, audio = self.speech.listen_for_audio()

        # received audio data, now we'll recognize it using Google Speech Recognition
        speech = self.speech.google_speech_recognition(recognizer, audio)
        #speech = "can you show me a map of Pune"
        #print speech

        if speech is not None:
            try:
                r = requests.get('https://api.wit.ai/message?v=20160918&q=%s' % speech,
                                 headers={"Authorization": wit_ai_token})
                print r.text
                json_resp = json.loads(r.text)
                entities = None
                intent = None
                Status_Type = None
                if 'entities' in json_resp and 'Intent' in json_resp['entities']:
                    entities = json_resp['entities']
                    intent = json_resp['entities']['Intent'][0]["value"]

                print intent
                if 'Status_Type' in json_resp['entities'] :
                    entities = json_resp['entities']
                    Status_Type = json_resp['entities']['Status_Type'][0]["value"]
                    

                #print Status_Type
                if Status_Type is not None:
                   self.__module_action(entities)
                   return 

               

                if intent == 'greeting':
                    self.__text_action(self.nlg.greet())
                elif intent == 'snow white':
                    self.__text_action(self.nlg.snow_white())
                elif intent == 'weather':
                    self.__weather_action(entities)
                elif intent == 'news':
                    self.__news_action()
                elif intent == 'maps':
                    self.__maps_action(entities)
                elif intent == 'youtube':
                    self.__youtube_action(entities)
                    #if self.vision.recognize_face():
                       # print "Found face"
                elif intent == 'zomato':
                    self.__zomato_action(entities)
                elif intent == 'uber':
                    self.__uber_action(entities)        
                elif intent == 'holidays':
                    self.__holidays_action()
                elif intent == 'appearance':
                    self.__appearance_action()
                elif intent == 'user status':
                    self.__user_status_action(entities)
                elif intent == 'user name':
                    self.__user_name_action()
                elif intent == 'personal status':
                    self.__personal_status_action()
                elif intent == 'joke':
                    self.__joke_action()
                elif intent == 'insult':
                    self.__insult_action()
                    return
                elif intent == 'appreciation':
                    self.__appreciation_action()
                    return
                  
                
                elif intent is None:
                    self.__hound_action(speech)
                    return
 

                else:
                     self.__text_action("I'm sorry, I don't know about that yet.")
                     return

                #time.sleep(20)
                

            except Exception as e:
                print "Failed wit!"
                print(e)
                traceback.print_exc()
                self.__text_action("I'm sorry, I couldn't understand what you meant by that")
                return

            self.decide_action()

    def __joke_action(self):
        joke = self.nlg.joke()

        if joke is not None:
            self.__text_action(joke)
        else:
            self.__text_action("I couldn't find any jokes")

    def __user_status_action(self, nlu_entities=None):
        attribute = None

        if (nlu_entities is not None) and ("Status_Type" in nlu_entities):
            attribute = nlu_entities['Status_Type'][0]['value']

        self.__text_action(self.nlg.user_status(attribute=attribute))

    def __user_name_action(self):
        if self.nlg.user_name is None:
            self.__text_action("I don't know your name. You can configure it in bot.py")

        self.__text_action(self.nlg.user_name)

    def __appearance_action(self):
        requests.get("http://localhost:8080/face")

    def __appreciation_action(self):
        self.__text_action(self.nlg.appreciation())

    def __acknowledge_action(self):
        self.__text_action(self.nlg.acknowledge())

    def __insult_action(self):
        self.__text_action(self.nlg.insult())

    def __personal_status_action(self):
        self.__text_action(self.nlg.personal_status())

    def __text_action(self, text=None):
        if text is not None:
            requests.get("http://localhost:8080/statement?text=%s" % text)
            self.speech.synthesize_text(text)

    def __news_action(self):
        headlines = self.knowledge.get_news()

        if headlines:
            requests.post("http://localhost:8080/news", data=json.dumps({"articles":headlines}))
            self.speech.synthesize_text(self.nlg.news("past"))
            interest = self.nlg.article_interest(headlines)
            if interest is not None:
                self.speech.synthesize_text(interest)
        else:
            self.__text_action("I had some trouble finding news for you")

    def __weather_action(self, nlu_entities=None):

        current_dtime = datetime.datetime.now()
        skip_weather = False # used if we decide that current weather is not important

        weather_obj = self.knowledge.find_weather()
        temperature = weather_obj['temperature']
        icon = weather_obj['icon']
        wind_speed = weather_obj['windSpeed']

        weather_speech = self.nlg.weather(temperature, current_dtime, "present")
        forecast_speech = None

        if nlu_entities is not None:
            if 'datetime' in nlu_entities:
                if 'grain' in nlu_entities['datetime'][0] and nlu_entities['datetime'][0]['grain'] == 'day':
                    dtime_str = nlu_entities['datetime'][0]['value'] # 2016-09-26T00:00:00.000-07:00
                    dtime = dateutil.parser.parse(dtime_str)
                    if current_dtime.date() == dtime.date(): # hourly weather
                        forecast_obj = {'forecast_type': 'hourly', 'forecast': weather_obj['daily_forecast']}
                        forecast_speech = self.nlg.forecast(forecast_obj)
                    elif current_dtime.date() < dtime.date(): # sometime in the future ... get the weekly forecast/ handle specific days
                        forecast_obj = {'forecast_type': 'daily', 'forecast': weather_obj['weekly_forecast']}
                        forecast_speech = self.nlg.forecast(forecast_obj)
                        skip_weather = True
            if 'Weather_Type' in nlu_entities:
                weather_type = nlu_entities['Weather_Type'][0]['value']
                print weather_type
                if weather_type == "current":
                    forecast_obj = {'forecast_type': 'current', 'forecast': weather_obj['current_forecast']}
                    forecast_speech = self.nlg.forecast(forecast_obj)
                elif weather_type == 'today':
                    forecast_obj = {'forecast_type': 'hourly', 'forecast': weather_obj['daily_forecast']}
                    forecast_speech = self.nlg.forecast(forecast_obj)
                elif weather_type == 'tomorrow' or weather_type == '3 day' or weather_type == '7 day':
                    forecast_obj = {'forecast_type': 'daily', 'forecast': weather_obj['weekly_forecast']}
                    forecast_speech = self.nlg.forecast(forecast_obj)
                    skip_weather = True


        weather_data = {"temperature": temperature, "icon": icon, 'windSpeed': wind_speed, "hour": datetime.datetime.now().hour}
        requests.post("http://localhost:8080/weather", data=json.dumps(weather_data))

        if not skip_weather:
            self.speech.synthesize_text(weather_speech)

        if forecast_speech is not None:
            self.speech.synthesize_text(forecast_speech)

    def __maps_action(self, nlu_entities=None):

        location = None
        map_type = None
        if nlu_entities is not None:
            if 'location' in nlu_entities:
                location = nlu_entities['location'][0]["value"]
                #location = nlu_entities['search_query'][0]["value"]
            else:
                location = nlu_entities['search_query'][0]["value"]
            if "Map_Type" in nlu_entities:
                map_type = nlu_entities['Map_Type'][0]["value"]

        if location is not None:
            maps_url = self.knowledge.get_map_url(location, map_type)
            maps_action = "Sure. Here's a map of %s." % location
            body = {'url': maps_url}
            requests.post("http://localhost:8080/image", data=json.dumps(body))
            self.speech.synthesize_text(maps_action)
        else:
            self.__text_action("I'm sorry, I couldn't understand what location you wanted.")

    def __youtube_action(self, nlu_entities=None):
        video = None
        DEVELOPER_KEY = ""  #add developer key 
        YOUTUBE_API_SERVICE_NAME = "youtube"
        YOUTUBE_API_VERSION = "v3"
        

        
        if nlu_entities is not None:
            if 'search_query' in nlu_entities:
                video = nlu_entities['search_query'][0]["value"]

        if video is not None:
            youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
            developerKey=DEVELOPER_KEY)
            search_response = youtube.search().list(
            q=video,
            part="id,snippet",
            ).execute()

            
            for search_result in search_response.get("items"):


                if search_result["id"]["kind"] == "youtube#video":
                    id= search_result["id"]["videoId"]
                    ch_title =  search_result["snippet"]["channelTitle"]
                   
                    title =  search_result["snippet"]["title"]
                    break;
                thumb = search_result["snippet"]["thumbnails"]["medium"]    

                


            for search_result in search_response.get("items"):


                thumb = search_result["snippet"]["thumbnails"]["medium"] 
                   
                break;
                   
           
            print id
            #print thumb
            videou = "https://www.youtube.com/embed/" + id + "?autoplay=1&controls=1"
            #print videou
           
            youtube_action = "Sure. Here's a video of %s." % video
            body = {'url': videou, 'channel': ch_title, 'thumb':thumb, 'titles':title}
            requests.post("http://localhost:8080/video", data=json.dumps(body))
            self.speech.synthesize_text(youtube_action)
            time.sleep(8)
            
           
           
        else:
            self.__text_action("I'm sorry, I couldn't understand what video you wanted.")  

    def __zomato_action(self, nlu_entities=None):
        if nlu_entities is not None:
            if 'location' in nlu_entities:
                entities=nlu_entities['location'][0]["value"]
                print entities
                response= requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities) #inset google maps key here
                resp_json_payload = response.json()
                lat=(resp_json_payload['results'][0]['geometry']['location']['lat'])
                lng=(resp_json_payload['results'][0]['geometry']['location']['lng'])

                print lat
                print lng
                locationUrlFromLatLong = "https://developers.zomato.com/api/v2.1/geocode?lat=%s&lon=%s" %(lat,lng)
                header = {"Accept": "application/json", "user_key": ""}  #add user key

                response = requests.get(locationUrlFromLatLong, headers=header)

                restaurants=(response.json().get("nearby_restaurants"))
                name = []
                rating = []
                avgcost = []
                for restaurant in restaurants:
                    name.append(restaurant['restaurant']['name'])
                    avgcost.append(restaurant['restaurant']['average_cost_for_two'])
                    rating.append(restaurant['restaurant']['user_rating']['aggregate_rating'])
                    
                    

                    #print name    

                

                zomato_data = {"cabtype": name, 'maxfare': avgcost, "minfare": rating}
                uber_action = "Sure. Here are some results"
                
                

                requests.post("http://localhost:8080/zomato", data=json.dumps(zomato_data))
                #self.speech.synthesize_text(uber_action)


               

                self.speech.synthesize_text(uber_action)
            
           
           
        else:
            self.__text_action("I'm sorry, I couldn't understand what restaurant you wanted.")  

    
    def __uber_action(self, nlu_entities=None):
        uber = None
        
                
        if nlu_entities is not None:
            if 'location' in nlu_entities:
                 entities3=nlu_entities['search_query'][0]["value"]
                 entities1=nlu_entities['location'][0]["value"]
                 entities2=nlu_entities['location'][1]["value"]
                 print entities3
                 print entities1
                 print entities2

        if entities1 and entities2  is not None:
            response= requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities1) #add key
            resp_json_payload = response.json()

            lat1=(resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng1=(resp_json_payload['results'][0]['geometry']['location']['lng'])

            response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities2)  #add key

            resp_json_payload = response.json()
            
            lat2=(resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng2=(resp_json_payload['results'][0]['geometry']['location']['lng'])

            oauth2credential = OAuth2Credential(
            client_id='', #add client id
            access_token='', #get access token
            expires_in_seconds= '2592000',
            scopes='all_trips delivery history history_lite places profile request request_receipt ride_widgets',
            grant_type='authorization_code',
            redirect_url='', #add redirect_url
            client_secret='', #add client secret
            refresh_token='', # add refresh token
        )

            session = Session(oauth2credential=oauth2credential)
            client = UberRidesClient(session, sandbox_mode=True)

            print (client)

            response = client.get_products(lat1, lng1)
            credentials = session.oauth2credential
            #print (response)
            response = client.get_user_profile()
            profile = response.json
            
            # response_uber = client.get_price_estimates(
            #     start_latitude=lat1,
            #     start_longitude=lng1,
            #     end_latitude=lat2,
            #     end_longitude=lng2,
            #     seat_count=1
            # )

            # estimate = response_uber.json.get('prices')

            # print estimate[0]['high_estimate']
            # print estimate[0]['low_estimate']
            # print estimate[0]['localized_display_name']
            # print estimate[0]['currency_code']
            # currency = estimate[0]['currency_code']
            # hi_est =  str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code'])
            # low_est =  str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code'])
            # type_cab =  estimate[0]['localized_display_name']
             

            # print estimate[0]

            response = client.get_products(lat1, lng1)
            products = response.json.get('products')
            #print(products)
            if entities3 == 'Uber go':
                for i in range(1,5):
                    if products[i]['display_name']=='uberGO':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            elif entities3 == 'Uber pool':
                for i in range(1,5):
                    if products[i]['display_name']=='POOL':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            else:
                product_id = products[0].get('product_id')
                type_cab = products[0].get('display_name')

            

            estimate = client.estimate_ride(
                product_id=product_id,
                start_latitude=lat1,
                start_longitude=lng1,
                end_latitude=lat2,
                end_longitude=lng2,
                seat_count=1
            )
            fare = estimate.json.get('fare') 
            bas = fare['display'] 
            client.cancel_current_ride()
            response = client.request_ride(
             product_id=product_id,
             start_latitude=lat1,
             start_longitude=lng1,
             end_latitude=lat2,
             end_longitude=lng2,
             seat_count=1,
             fare_id=fare['fare_id']
            )  

            request = response.json
            print request
            request_id = request.get('request_id')
            url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request_id
            ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request_id + '/map'

            token = "" #insert token

            data = {
                "status": "accepted"

                }

            headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"}

#Call REST API
            respons = requests.put(url, data=json.dumps(data), headers=headers)
            respon = requests.get(ur, headers=headers)
            response = client.get_ride_details(request_id)
            ride = response.json
            print ride

            status = ride.get('status')
            dri_name = ride.get('driver').get('name')
            dri_pic = ride.get('driver').get('picture_url')

            eta = ride.get('destination').get('eta')   
            car_pix = ride.get('vehicle').get('picture_url')

            
            # product_name1 = products[3]['display_name'] #GO
            # product_nam2 = products[2]['display_name'] #POOL

            uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % (entities1, entities2, type_cab, eta, bas)
            cab_data = {"cabtype": type_cab, 'maxfare': bas, "minfare": eta, 'to': entities2, 'from': entities1, 'status':status, 'driver': dri_name, 'pic': dri_pic, 'car': car_pix, 'map':ur}
            #print cab_data

            requests.post("http://localhost:8080/cab", data=json.dumps(cab_data))
            self.speech.synthesize_text(uber_action)
            
           
        else:
            self.__text_action("I'm sorry, I don't think that their is any cab available between these two locations.")                

    def __holidays_action(self):
        holidays = self.knowledge.get_holidays()
        next_holiday = self.__find_next_holiday(holidays)
        requests.post("http://localhost:8080/holidays", json.dumps({"holiday": next_holiday}))
        self.speech.synthesize_text(self.nlg.holiday(next_holiday['localName']))

    def __find_next_holiday(self, holidays):
        today = datetime.datetime.now()
        for holiday in holidays:
            date = holiday['date']
            if (date['day'] > today.day) and (date['month'] > today.month):
                return holiday

        # next year
        return holidays[0]


    

    def __module_action(self, nlu_entities=None):
        
        if nlu_entities is not None:
 
            Status_Type = nlu_entities['Status_Type'][0]["value"]
            if 'search_query' in nlu_entities:
                
                video = nlu_entities['search_query'][0]["value"]
                print video
                body = {'url': video, 'sta': Status_Type}
                print body

                requests.post("http://localhost:8080/module", data=json.dumps(body)) 
                print 'Raghav'
                self.speech.synthesize_text("sure")


        
  
    def __hound_action(self, speech=None):
         if speech is not None:
            clientId = "" #get client id from houndify
            clientKey = "" #insert client key
            userId = "test_user"
            requestInfo = {
              "Latitude": 18.5679, 
              "Longitude": 73.9143
            }

            client = houndify.TextHoundClient(clientId, clientKey, userId, requestInfo)
            response = client.query(speech)
            #conversationState = response["AllResults"][0]["ConversationState"]
            #client.setConversationState(conversationState)
            command = response["AllResults"][0]["WrittenResponseLong"]
            
           
            spoken = response["AllResults"][0]["SpokenResponseLong"]
             
            name = []
            rating = []
            avgcost = []    
            url = []  
            print 
            if "Template" in response["AllResults"][0]["ViewType"]:
                if len(response["AllResults"][0]["TemplateData"]["Items"]) > 8:
                    for item in range(0,10):
                        if 'Title' in response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]:
                            name.append(response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]["Title"])
                        if 'Subtitle' in response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]:
                            rating.append(response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]["Subtitle"])
                        if 'BodyText' in response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]:    
                            avgcost.append(response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]["BodyText"])
                        if 'URL' in response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]["Image"]:    
                            url.append(response["AllResults"][0]["TemplateData"]["Items"][item]["TemplateData"]["Image"][ "URL"])


                    hound_data = {"title": name, 'subtitle': rating, "details": avgcost, "url": url, "command": command}
                    requests.post("http://localhost:8080/other", data=json.dumps(hound_data))
                else:   
                    requests.post("http://localhost:8080/other", data=json.dumps(command))
                    

            #requests.get("http://localhost:8080/statement?text=%s" % text)
            #self.speech.synthesize_text(text)
            
            else:
                requests.post("http://localhost:8080/other", data=json.dumps(command))

            self.speech.synthesize_text(spoken)
            self.decide_action()
Пример #30
0
    #parse_tree_string = """((S (NP-SBJ-A (-NONE- *)) (VP(VB Tell) (NP-A (PRP me)) (SBAR-A(WHNP-0 (WDT what)) (S-A(NP-SBJ-0 (-NONE- *T*)) (VP (VBZ 's) (PP-LOC-PRD (IN in) (NP-A (NN room) (CD 3)))))))                                                 (. ?)))"""

    ##parse_tree_string = """((S (NP-SBJ-A (PRP I)) (VP (VBP am) (PP-LOC-PRD (IN in) (NP-A (NN room) (CD 2)))) (. .)))"""
    ##parse_tree_string = """((S (NP-SBJ-A (EX There)) (VP (VBP are) (NP-PRD-A (NP (QP (IN at) (JJS least) (CD 4)) (NNS hostages)) (PP-LOC (IN in) (NP-A (NN room) (CD 1))))) (. .)))  """
  
    
    ##parse_tree_string = """((SBARQ (WHNP-0 (WP What)) (SQ (VBP are) (NP-SBJ (PRP you)) (VP (VBG doing) (NP-0 (-NONE- *T*)))) (. ?)))"""
    #parse_tree_string = """((SQ (VBP Are) (NP-SBJ-0 (PRP you)) (VP (VBN flipped) (NP-A-0 (-NONE- *))) (. ?)))"""
    ##parse_tree_string = """((SINV (VP (VBP Are) (ADVP-LOC-PRD (RB there))) (NP-SBJ (DT any) (NNS hostages)) (. ?))) """

    ##parse_tree_string = """((S (NP-SBJ-A (NNP Junior)) (, ,) (VP (VP-A (VB go) (PP-CLR (TO to) (NP-A (NN room) (CD 3)))) (. .))))"""
    ##parse_tree_string = """((S (VP (VP-A (VB Go) (PP-CLR (TO to) (NP-A (NN room) (CD 3)))) (. .))))"""
    ##parse_tree_string = """((S (NP-SBJ-A (-NONE- *)) (VP (VB Look) (PP-CLR (IN for) (NP-A (NNP User) (CD 1))) (PP (IN in) (NP-A (NP (DT the) (NN library)) (CC and) (NP (DT the) (NN classroom))))) (. .)))"""
    ##parse_tree_string = """((S (VP (VB Look) (PP-CLR (IN for) (NP-A (NNP User) (CD 1))) (PP (IN in) (NP-A (NP (DT the) (NN library)) (CC and) (NP (DT the) (NN classroom))))) (. .)))"""
                                        
    knowledge = Knowledge()
    
    print knowledge.process_parse_tree(demo_sentences['GoToLibrary'], '')
    #print knowledge.process_parse_tree(demo_sentences['WhereAreTheHostages'], '')
    
    print knowledge.watch_list
    print knowledge.commander_known_entities
    print knowledge.command_queue
    

    #print 'Watch list \n' + str(knowledge.watch_list)
    print '-------------'

    
    
    ##parse_tree_string = """((SBARQ (WHADVP-0 (WRB Where)) (SQ (VP (VBP are) (NP-PRD-A (DT the) (NNS hostages)) (ADVP-0 (-NONE- *T*)))) (. ?)))  """
Пример #31
0
	Proportionality: exact
	Number: None

		Predicates: [[Topic:Commander], [Agent:*]]
	Action: tell]"""))

test_cases.append(('FollowMe', 0, """[('follow', {'Theme': 'Commander'})]"""))
test_cases.append(('LookForUser1', 0, """[('search', {'Theme': 'user_1', 'Location': 'library'}), ('search', {'Theme': 'user_1', 'Location': 'classroom'})]"""))
test_cases.append(('GetBombDefuser', 0, """[('retrieve', {'Source': 'user_1', 'Theme': 'bomb_defuser'}), ('go', {'Theme': '*', 'Location': 'unknown_current_location'})]"""))
test_cases.append(('EatSandwich', 0, """[('eat', {'Patient': 'sandwich'})]"""))
test_cases.append(('WhereAreYou', 3, """I don't know."""))
test_cases.append(('GoOfficeDefuse', 0, """[('go', {'Location': 'office'}), ('defuse', {'Theme': 'bomb'}), ('see', {'Theme': 'bomb'})]"""))
test_cases.append(('WhereIsUser1',3,""" """));
test_cases.append(('WhereIsHe',3, """ """));
if __name__ == '__main__':
    knowledge = Knowledge()
    library_entity = Entity({'EntityType':[Predicate('EntityType','room')]},
                             'library')
    user1_entity = Entity({'Theme' : [Predicate('Theme', 'user1')],
                            'Location' :
                               [Predicate('Location', library_entity)]})
    
    knowledge.junior_known_entities[user1_entity.id] = user1_entity
    knowledge.commander_known_entities[user1_entity.id] = user1_entity

    for test in test_cases:
        answer = knowledge.process_parse_tree(phrase_dict[test[0]],'')
        if answer[2] is not None:
            result = str(answer[2][test[1]])
        else:
            print 'Test ' + test[0] + ' failed. No output.'
Пример #32
0
 def __init__(self):
     self.nlg = NLG(user_name=my_name)
     self.speech = Speech(launch_phrase=launch_phrase, debugger_enabled=debugger_enabled)
     self.knowledge = Knowledge(weather_api_token)
     self.vision = Vision(camera=camera)
Пример #33
0
 def weather_action(self):
     weather_json = Knowledge.weather_knowledge()
Пример #34
0
class DynamicCommander(Commander):
    """
    Initializes everything that the commander needs. This includes loading the different rulesets, distributing the roles and generating scripts for the bots.
    """
    def initialize(self):
        self.verbose = True
        self.statistics = Statistics()
        self.statistics.initialize(self)
        self.knowledge = Knowledge()
        self.knowledge.initialize(self)
        
        #todo: make this more generic,
        # i.e. allow for an arbitrary number of roles
        # load all rule bases
        self.loadMetaRules()
        self.loadAttackerRules()
        self.loadDefenderRules()
        self.loadCatcherRules()
        
        # distribute the roles to the bots 
        roleList = self.metaScript.runDynamicScript([len(self.game.team.members),self.statistics])
        if(roleList != None):
            self.distributeRoles(roleList)
        else: #If none of the rules apply, use a mixed team.
            self.distributeRoles(metaRules.mixedAttackers(len(self.game.team.members)))
        # and generate the corresponding scripts
        self.initializeRoles()
        self.initializeBotStats()

    """
    Loads the meta rules with their weights.
    """
    def loadMetaRules(self):
        self.log.info("Loading the meta rules")
        conn = open(sys.path[0]+"/dynamicscripting/meta.txt",'r')
        self.metaRuleBase = jsonpickle.decode(conn.read())
        conn.close()
        
        # Generate an initial meta script
        self.metaScript = DynamicScriptingInstance(DynamicScriptingClass(self.metaRuleBase,"metaRules"))
        self.metaScript.generateScript(3)
        self.metaScript.printScript()
    
    """
    Loads the attacker rules with their weights.
    """
    def loadAttackerRules(self):
        self.log.info("Loading the attacker rules")
        conn = open(sys.path[0]+"/dynamicscripting/attacker.txt",'r')
        self.attackerRulebase = jsonpickle.decode(conn.read())
        conn.close()    
        
    """
    Loads the defender rules with their weights.
    """
    def loadDefenderRules(self):
        self.log.info("Loading the defender rules")
        conn = open(sys.path[0]+"/dynamicscripting/defender.txt",'r')
        self.defenderRulebase = jsonpickle.decode(conn.read())
        conn.close()        

    """
    Loads the catcher rules with their weights.
    """
    def loadCatcherRules(self):
        self.log.info("Loading the catcher rules")
        conn = open(sys.path[0]+"/dynamicscripting/catcher.txt",'r')
        self.catcherRulebase = jsonpickle.decode(conn.read())
        conn.close()
    
    """
    Distributes the roles to the bots according to a given distribution.
    """
    def distributeRoles(self,roleList):
        self.log.info("Distributing the roles")       
        self.log.info("Rolelist: "+ str(roleList))
        #assign each bot a role
        for botIndex in range(len(roleList)):
            self.game.team.members[botIndex].role = roleList[botIndex]
            
    def initializeRoles(self):
        self.log.info("Initializing roles")
		# load the rulebases
        self.dsclassAttacker = DynamicScriptingClass(self.attackerRulebase,"attackerRules")
        self.dsclassDefender = DynamicScriptingClass(self.defenderRulebase,"defenderRules")
        self.dsclassCatcher = DynamicScriptingClass(self.catcherRulebase,"catcherRules")
        i = 1
		#assign each bot a role, depending on its role
        for bot in self.game.team.members:
            bot.id = i
            self.log.info("Bot #" + str(i) + ": Generating " + bot.role + " script")
            if(bot.role == "attacker"):
                bot.script = DynamicScriptingInstance(self.dsclassAttacker,botRole = bot.role,botNumber = i)
                bot.script.generateScript(4)
                # add default rule
                bot.script.insertInScript(Rule(attackerRules.default_attacker_rule))
            elif(bot.role == "defender"):
                bot.script = DynamicScriptingInstance(self.dsclassDefender,botRole = bot.role,botNumber = i)
                bot.script.generateScript(4)
                bot.script.insertInScript(Rule(defenderRules.default_defender_rule))
            else: #if(bot.role == "catcher"): #backup
                bot.script = DynamicScriptingInstance(self.dsclassCatcher,botRole = bot.role,botNumber = i)
                bot.script.generateScript(4)
                #for i in bot.script.rules: #to check if there are different type of rules at base
                #    print(i.rule_type)
                bot.script.insertInScript(Rule(catcherRules.default_catcher_rule))
            bot.script.printScript()
            self.log.info("")
            i += 1

    """
    Initialises the statistics for the bots.
    """
    def initializeBotStats(self):
    
        self.timeSinceLastCommand = {} # used to detect bots that are stuck
    
        for bot in self.game.team.members:
            resetBotStats(bot)
            self.timeSinceLastCommand[bot.id] = 0

    """
    Updates the weights for all bots and the meta script in accordance
    with the procedure given in Spronck's paper.
    """
    def updateWeights(self):
        self.log.info("Updating weights!")
        self.metaScript.adjustWeights(self.metaScript.calculateTeamFitness(self.knowledge),self)
        for bot in self.game.team.members:
            fitness = bot.script.calculateAgentFitness(bot, self.knowledge)
            self.log.info("Bot #" + str(bot.id) + "[" + bot.role + "] fitness:" + str(fitness))
           
            bot.script.adjustWeights(fitness,self)

    """
    Save all the weights back to the files.
    """
    def saveWeights(self):
        self.saveWeightsRulebase(self.attackerRulebase,"attacker")
        self.saveWeightsRulebase(self.defenderRulebase,"defender")
        self.saveWeightsRulebase(self.catcherRulebase,"catcher")
        self.saveWeightsRulebase(self.metaRuleBase,"meta")
    
	"""
	save a certain rulebase
	"""
    def saveWeightsRulebase(self,rulebase,name):
        conn = open(sys.path[0] + "/dynamicscripting/" + name + ".txt",'w')
        funcBackup = []
        # Replace function by function names
        for rule in rulebase:
            funcBackup.append(rule.func)
            rule.func = rule.func.__name__
        rulebaseEncoded = jsonpickle.encode(rulebase)
        conn.write(rulebaseEncoded)
        conn.close()
        
        # Put them back.
        for i in range(len(rulebase)):
            rulebase[i].func = funcBackup[i]

    """
    Update the statistics for the bots. 
	Statistics are used to calculate bot fitness
    """
    def updateBotStats(self):
        for event in self.game.match.combatEvents:
            if event.type == event.TYPE_FLAG_RESTORED:
                if event.subject.team == self.game.team:
                    for bot in self.game.team.members:
                        bot.flag_restored += 1
                continue
            elif event.type == event.TYPE_FLAG_CAPTURED:
                if event.subject.team == self.game.team:
                    for bot in self.game.team.members:
                        bot.flag_stolen += 1
                continue

            if event.instigator == None:
                continue
            if event.instigator.team == self.game.team:
                if event.type == event.TYPE_KILLED:
                    event.instigator.kills += 1
                elif event.type == event.TYPE_FLAG_PICKEDUP:
                    event.instigator.flag_pickedup += 1
                elif event.type == event.TYPE_FLAG_DROPPED:
                    event.instigator.flag_dropped += 1
                elif event.type == event.TYPE_FLAG_CAPTURED:
                    event.instigator.flag_captured += 1
            else:
                if event.type == event.TYPE_KILLED:
                    event.subject.deaths += 1

    """
    This method is executed every game tick. It updates the statistics, it
    can switch the team composition and it gives new orders to the bots
    (based on their own scripts).
    """
    def tick(self):
       # self.log.info("Tick at time " + str(self.game.match.timePassed) + "!")
        
        self.statistics.tick() # Update statistics
        self.knowledge.tick() # Update knowledge base

        # update bot stats
        self.updateBotStats()
        
        # should the commander issue a new strategy?
        # TODO:
        # 1. make distributeRoles take the current distribution into account
        # 2. Let initializeRoles take currently good performing scripts for roles into account
        
        roleList = self.metaScript.runDynamicScript([len(self.game.team.members),self.statistics])
        if roleList != None:
            self.log.info("Switching tactics and adjusting weights")
            self.updateWeights()
            self.distributeRoles(roleList)
            self.initializeRoles()
            # Generate a new script based on latest weights for the next time.
            self.metaScript = DynamicScriptingInstance(DynamicScriptingClass(self.metaRuleBase,"metaRules"))
            self.metaScript.generateScript(3)
        
		# a bot that has the flag needs to be a catcher
        for bot in self.game.team.members:
            if bot.flag is not None and bot.role != "catcher":
                bot.role = "catcher"
                bot.script = DynamicScriptingInstance(self.dsclassCatcher,botRole = bot.role,botNumber = bot.id)
                bot.script.generateScript(4)
                bot.script.insertInScript(Rule(catcherRules.default_catcher_rule))
    
        # give the bots new commands
        for bot in self.game.bots_available:
            bot.script.runDynamicScript([bot,self,self.knowledge])
            self.timeSinceLastCommand[bot.id] = self.game.match.timePassed     

        # detect bots that are stuck    
        for bot in self.game.team.members:
            # more than 30 seconds (90 ticks) since bot has been available
            # it is probably stuck doing something silly, so reactivate it.
            if self.game.match.timePassed - self.timeSinceLastCommand[bot.id] > 30:
                print "REACTIVATING BOT", bot.id
                bot.script.runDynamicScript([bot,self,self.knowledge])
                self.timeSinceLastCommand[bot.id] = self.game.match.timePassed     
    
    """
    This method is executed at the end of the game.
    """
    def shutdown(self):
        self.updateWeights()
        self.saveWeights()
        print "statistics:",self.statistics.ourScore,"-",self.statistics.theirScore